diff --git a/.gitea/workflows/release.yml b/.gitea/workflows/release.yml index 113cd2b7..025301f5 100644 --- a/.gitea/workflows/release.yml +++ b/.gitea/workflows/release.yml @@ -335,7 +335,7 @@ jobs: # docker that can pull our container.image. runs-on: flutter-ci container: - image: git.fabledsword.com/bvandeusen/ci-android:36 + image: git.fabledsword.com/bvandeusen/ci-android:37 defaults: run: @@ -446,7 +446,7 @@ jobs: || github.ref == 'refs/heads/main' runs-on: flutter-ci container: - image: git.fabledsword.com/bvandeusen/ci-android:36 + image: git.fabledsword.com/bvandeusen/ci-android:37 defaults: run: diff --git a/android/.editorconfig b/android/.editorconfig new file mode 100644 index 00000000..001e301e --- /dev/null +++ b/android/.editorconfig @@ -0,0 +1,7 @@ +# ktlint reads this. The code style is ktlint's default (ktlint_official); +# the one exception is Compose's convention of naming @Composable functions +# like types (PlayerScreen, not playerScreen). +root = true + +[*.{kt,kts}] +ktlint_function_naming_ignore_when_annotated_with = Composable diff --git a/android/app/build.gradle.kts b/android/app/build.gradle.kts index 3c54f6ad..e2259ba6 100644 --- a/android/app/build.gradle.kts +++ b/android/app/build.gradle.kts @@ -15,7 +15,7 @@ plugins { android { namespace = "com.fabledsword.minstrel" - compileSdk = 36 + compileSdk = 37 defaultConfig { applicationId = "com.fabledsword.minstrel" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/MainActivity.kt b/android/app/src/main/java/com/fabledsword/minstrel/MainActivity.kt index 65c7edf0..224fa574 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/MainActivity.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/MainActivity.kt @@ -30,8 +30,8 @@ import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.auth.ui.AuthGateViewModel import com.fabledsword.minstrel.cache.CachedTrackIds import com.fabledsword.minstrel.connectivity.LocalServerHealth -import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.connectivity.NetworkStatusController +import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.nav.DetailSeedCache import com.fabledsword.minstrel.nav.LocalDetailSeedCache import com.fabledsword.minstrel.nav.Login @@ -56,8 +56,11 @@ import javax.inject.Inject @AndroidEntryPoint class MainActivity : ComponentActivity() { @Inject lateinit var seedCache: DetailSeedCache + @Inject lateinit var cachedTrackIds: CachedTrackIds + @Inject lateinit var serverHealth: NetworkStatusController + @Inject lateinit var authStore: AuthStore // Set when the user taps a notification: the media one asks for the full @@ -120,8 +123,9 @@ class MainActivity : ComponentActivity() { val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() } combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted).first { it } val permission = Manifest.permission.POST_NOTIFICATIONS - val granted = ContextCompat.checkSelfPermission(this@MainActivity, permission) == - PackageManager.PERMISSION_GRANTED + val granted = + ContextCompat.checkSelfPermission(this@MainActivity, permission) == + PackageManager.PERMISSION_GRANTED if (!granted) askToNotify.launch(permission) } } @@ -196,7 +200,10 @@ private fun App( * request fails. */ @Composable -private fun SignInWhenSessionRejected(gate: AuthGateViewModel, navController: NavHostController) { +private fun SignInWhenSessionRejected( + gate: AuthGateViewModel, + navController: NavHostController, +) { val sessionRejected by gate.sessionRejected.collectAsStateWithLifecycle() LaunchedEffect(sessionRejected, navController) { if (!sessionRejected) return@LaunchedEffect diff --git a/android/app/src/main/java/com/fabledsword/minstrel/MinstrelApplication.kt b/android/app/src/main/java/com/fabledsword/minstrel/MinstrelApplication.kt index 8d596289..8bae8f7f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/MinstrelApplication.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/MinstrelApplication.kt @@ -11,6 +11,7 @@ import com.fabledsword.minstrel.cache.CacheIndexer import com.fabledsword.minstrel.cache.audiocache.CacheBudgetSync import com.fabledsword.minstrel.cache.mutations.MutationReplayer import com.fabledsword.minstrel.cache.sync.SyncController +import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.diagnostics.DiagnosticsReporter import com.fabledsword.minstrel.diagnostics.DiagnosticsUploader @@ -24,7 +25,6 @@ import com.fabledsword.minstrel.player.LikedAudioPinner import com.fabledsword.minstrel.player.PlayEventsReporter import com.fabledsword.minstrel.player.PlaybackErrorReporter import com.fabledsword.minstrel.player.ResumeController -import com.fabledsword.minstrel.connectivity.NetworkStatusController import dagger.hilt.android.HiltAndroidApp import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch @@ -41,7 +41,6 @@ class MinstrelApplication : Application(), Configuration.Provider, SingletonImageLoader.Factory { - @Inject lateinit var workerFactory: HiltWorkerFactory /** @@ -66,7 +65,9 @@ class MinstrelApplication : * cold start with persisted cookie). Without this @Inject the * singleton would never instantiate. */ - @Suppress("unused") @Inject lateinit var syncController: SyncController + @Suppress("unused") + @Inject + lateinit var syncController: SyncController /** * Same construct-the-singleton trick — MutationReplayer's init @@ -75,7 +76,9 @@ class MinstrelApplication : * cold start with persisted cookie). Without this @Inject the * queue would only enqueue, never replay. */ - @Suppress("unused") @Inject lateinit var mutationReplayer: MutationReplayer + @Suppress("unused") + @Inject + lateinit var mutationReplayer: MutationReplayer /** * Same construct-the-singleton trick — DeliveryLauncher starts and stops @@ -83,7 +86,9 @@ class MinstrelApplication : * every nudge and reconnect. Without this @Inject no phone * notification would ever be posted. */ - @Suppress("unused") @Inject lateinit var deliveryLauncher: DeliveryLauncher + @Suppress("unused") + @Inject + lateinit var deliveryLauncher: DeliveryLauncher /** * Same construct-the-singleton trick — PlayEventsReporter's init @@ -92,7 +97,9 @@ class MinstrelApplication : * server. Without this @Inject the singleton would never * instantiate and Android plays would never reach the server. */ - @Suppress("unused") @Inject lateinit var playEventsReporter: PlayEventsReporter + @Suppress("unused") + @Inject + lateinit var playEventsReporter: PlayEventsReporter /** * Same construct-the-singleton trick — PlaybackErrorReporter @@ -102,7 +109,9 @@ class MinstrelApplication : * snackbar. Without this construct ExoPlayer skip-on-error is * invisible to the user. */ - @Suppress("unused") @Inject lateinit var playbackErrorReporter: PlaybackErrorReporter + @Suppress("unused") + @Inject + lateinit var playbackErrorReporter: PlaybackErrorReporter /** * Same construct-the-singleton trick — CoverPrefetcher's init @@ -110,7 +119,9 @@ class MinstrelApplication : * cache with the next track's cover so track changes don't flash * a loading state. */ - @Suppress("unused") @Inject lateinit var coverPrefetcher: CoverPrefetcher + @Suppress("unused") + @Inject + lateinit var coverPrefetcher: CoverPrefetcher /** * Same construct-the-singleton trick — CacheIndexer's init block @@ -119,7 +130,9 @@ class MinstrelApplication : * and the cached indicator their data source. Without this @Inject * the index would stay empty and the offline pools would be inert. */ - @Suppress("unused") @Inject lateinit var cacheIndexer: CacheIndexer + @Suppress("unused") + @Inject + lateinit var cacheIndexer: CacheIndexer /** * Same construct-the-singleton trick — CacheBudgetSync's init block @@ -127,14 +140,18 @@ class MinstrelApplication : * Without this @Inject the evictor would never arm, and the cache * would grow without a limit. */ - @Suppress("unused") @Inject lateinit var cacheBudgetSync: CacheBudgetSync + @Suppress("unused") + @Inject + lateinit var cacheBudgetSync: CacheBudgetSync /** * Same construct-the-singleton trick — LikedAudioPinner's init block * downloads liked tracks into the Liked songs budget. Without this * @Inject, liking a track would not keep it offline. */ - @Suppress("unused") @Inject lateinit var likedAudioPinner: LikedAudioPinner + @Suppress("unused") + @Inject + lateinit var likedAudioPinner: LikedAudioPinner /** * Same construct-the-singleton trick — AudioPrefetcher's init @@ -143,7 +160,9 @@ class MinstrelApplication : * SimpleCache via CacheWriter. Without this @Inject the * prefetchWindow setting would be inert and skips would re-fetch. */ - @Suppress("unused") @Inject lateinit var audioPrefetcher: AudioPrefetcher + @Suppress("unused") + @Inject + lateinit var audioPrefetcher: AudioPrefetcher /** * Same construct-the-singleton trick — NetworkStatusController owns the @@ -152,7 +171,9 @@ class MinstrelApplication : * signal (plus the VersionTooOld byproduct). It must exist from launch so * the poll loop runs and the StateFlow stays warm for every consumer. */ - @Suppress("unused") @Inject lateinit var networkStatusController: NetworkStatusController + @Suppress("unused") + @Inject + lateinit var networkStatusController: NetworkStatusController /** * Same construct-the-singleton trick — FreshnessSweeper's init @@ -161,7 +182,9 @@ class MinstrelApplication : * via MetadataProvider, so the cache stays warm without * user-driven pull-to-refresh. */ - @Suppress("unused") @Inject lateinit var freshnessSweeper: FreshnessSweeper + @Suppress("unused") + @Inject + lateinit var freshnessSweeper: FreshnessSweeper /** * Same construct-the-singleton trick — EventsStream's init block @@ -170,21 +193,31 @@ class MinstrelApplication : * Without this @Inject the events SharedFlow would have no * upstream and consumers would never see anything. */ - @Suppress("unused") @Inject lateinit var eventsStream: EventsStream + @Suppress("unused") + @Inject + lateinit var eventsStream: EventsStream /** * Same construct-the-singleton trick — LiveEventsDispatcher's * init block subscribes to EventsStream.events + the process * lifecycle and routes cross-screen state refreshes. */ - @Suppress("unused") @Inject lateinit var liveEventsDispatcher: LiveEventsDispatcher + @Suppress("unused") + @Inject + lateinit var liveEventsDispatcher: LiveEventsDispatcher // Device diagnostics. The reporter gates itself on the account's // debug flag; the uploader drains its buffer on a tick / recovery. - @Suppress("unused") @Inject lateinit var diagnosticsReporter: DiagnosticsReporter - @Suppress("unused") @Inject lateinit var diagnosticsUploader: DiagnosticsUploader + @Suppress("unused") + @Inject + lateinit var diagnosticsReporter: DiagnosticsReporter - @Inject @ApplicationScope lateinit var appScope: CoroutineScope + @Suppress("unused") + @Inject + lateinit var diagnosticsUploader: DiagnosticsUploader + + @Inject @ApplicationScope + lateinit var appScope: CoroutineScope override fun onCreate() { super.onCreate() @@ -208,10 +241,17 @@ class MinstrelApplication : * to the package-stack-trace tag DebugTree produces. */ private class ReleaseTree : Timber.Tree() { - override fun isLoggable(tag: String?, priority: Int): Boolean = - priority >= android.util.Log.WARN + override fun isLoggable( + tag: String?, + priority: Int, + ): Boolean = priority >= android.util.Log.WARN - override fun log(priority: Int, tag: String?, message: String, t: Throwable?) { + override fun log( + priority: Int, + tag: String?, + message: String, + t: Throwable?, + ) { val resolvedTag = tag ?: "Minstrel" if (t == null) { android.util.Log.println(priority, resolvedTag, message) @@ -226,9 +266,11 @@ class MinstrelApplication : } override val workManagerConfiguration: Configuration - get() = Configuration.Builder() - .setWorkerFactory(workerFactory) - .build() + get() = + Configuration + .Builder() + .setWorkerFactory(workerFactory) + .build() /** * Builds the process-singleton Coil ImageLoader with our shared @@ -242,10 +284,10 @@ class MinstrelApplication : * two read as one cross-dissolve. */ override fun newImageLoader(context: android.content.Context): ImageLoader = - ImageLoader.Builder(context) + ImageLoader + .Builder(context) .components { add(OkHttpNetworkFetcherFactory(callFactory = { okHttpClient })) - } - .crossfade(ART_CROSSFADE_MS) + }.crossfade(ART_CROSSFADE_MS) .build() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminInvitesRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminInvitesRepository.kt index 761bcf83..ab9fc97a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminInvitesRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminInvitesRepository.kt @@ -14,25 +14,29 @@ import javax.inject.Singleton * admin repos — direct REST, no caching. */ @Singleton -class AdminInvitesRepository @Inject constructor(retrofit: Retrofit) { - private val api: AdminInvitesApi = retrofit.create() +class AdminInvitesRepository + @Inject + constructor( + retrofit: Retrofit, + ) { + private val api: AdminInvitesApi = retrofit.create() - suspend fun list(): List = api.list().invites.map { it.toDomain() } + suspend fun list(): List = api.list().invites.map { it.toDomain() } - suspend fun create(note: String?): Invite = - api.create(CreateInviteBody(note = note?.takeIf { it.isNotEmpty() })).toDomain() + suspend fun create(note: String?): Invite = api.create(CreateInviteBody(note = note?.takeIf { it.isNotEmpty() })).toDomain() - suspend fun revoke(token: String) { - api.revoke(token) + suspend fun revoke(token: String) { + api.revoke(token) + } } -} -private fun InviteWire.toDomain(): Invite = Invite( - token = token, - invitedBy = invitedBy, - note = note, - createdAt = createdAt, - expiresAt = expiresAt, - redeemedAt = redeemedAt, - redeemedBy = redeemedBy, -) +private fun InviteWire.toDomain(): Invite = + Invite( + token = token, + invitedBy = invitedBy, + note = note, + createdAt = createdAt, + expiresAt = expiresAt, + redeemedAt = redeemedAt, + redeemedBy = redeemedBy, + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminQuarantineRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminQuarantineRepository.kt index 988f8355..3e03ce26 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminQuarantineRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminQuarantineRepository.kt @@ -17,19 +17,21 @@ import javax.inject.Singleton * Each action takes the row off the queue once the server accepts it. */ @Singleton -class AdminQuarantineRepository @Inject constructor( - retrofit: Retrofit, -) { - private val api: AdminQuarantineApi = retrofit.create() +class AdminQuarantineRepository + @Inject + constructor( + retrofit: Retrofit, + ) { + private val api: AdminQuarantineApi = retrofit.create() - suspend fun list(): List = api.list().map { it.toDomain() } + suspend fun list(): List = api.list().map { it.toDomain() } - suspend fun resolve(trackId: String) = api.resolve(trackId) + suspend fun resolve(trackId: String) = api.resolve(trackId) - suspend fun removeFile(trackId: String) = api.removeFile(trackId) + suspend fun removeFile(trackId: String) = api.removeFile(trackId) - suspend fun deleteFile(trackId: String) = api.deleteFile(trackId) -} + suspend fun deleteFile(trackId: String) = api.deleteFile(trackId) + } // ── Mappers ── diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminTagSourcesRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminTagSourcesRepository.kt index ddd115a1..974bca08 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminTagSourcesRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminTagSourcesRepository.kt @@ -18,31 +18,37 @@ import javax.inject.Singleton * Exceptions propagate to the ViewModel (which maps them via ErrorCopy). */ @Singleton -class AdminTagSourcesRepository @Inject constructor( - retrofit: Retrofit, -) { - private val api: AdminTagSourcesApi = retrofit.create() +class AdminTagSourcesRepository + @Inject + constructor( + retrofit: Retrofit, + ) { + private val api: AdminTagSourcesApi = retrofit.create() - suspend fun list(): List = api.list().providers.map { it.toDomain() } + suspend fun list(): List = api.list().providers.map { it.toDomain() } - suspend fun setEnabled(id: String, enabled: Boolean): AdminTagSourceRef = - api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain() + suspend fun setEnabled( + id: String, + enabled: Boolean, + ): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(enabled = enabled)).toDomain() - suspend fun setApiKey(id: String, apiKey: String): AdminTagSourceRef = - api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain() + suspend fun setApiKey( + id: String, + apiKey: String, + ): AdminTagSourceRef = api.update(id, UpdateTagSourceBody(apiKey = apiKey)).toDomain() - suspend fun test(id: String): TagSourceTestResult = api.test(id).toResult() -} + suspend fun test(id: String): TagSourceTestResult = api.test(id).toResult() + } -private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef = AdminTagSourceRef( - id = id, - displayName = displayName, - requiresApiKey = requiresApiKey, - supports = supports, - enabled = enabled, - apiKeySet = apiKeySet, - testable = testable, -) +private fun AdminTagSourceWire.toDomain(): AdminTagSourceRef = + AdminTagSourceRef( + id = id, + displayName = displayName, + requiresApiKey = requiresApiKey, + supports = supports, + enabled = enabled, + apiKeySet = apiKeySet, + testable = testable, + ) -private fun TestTagSourceWire.toResult(): TagSourceTestResult = - TagSourceTestResult(ok = ok, durationMs = durationMs, error = error) +private fun TestTagSourceWire.toResult(): TagSourceTestResult = TagSourceTestResult(ok = ok, durationMs = durationMs, error = error) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminUsersRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminUsersRepository.kt index 505c54a7..051e94f3 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminUsersRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminUsersRepository.kt @@ -16,26 +16,33 @@ import javax.inject.Singleton * admin repositories. */ @Singleton -class AdminUsersRepository @Inject constructor( - retrofit: Retrofit, -) { - private val api: AdminUsersApi = retrofit.create() +class AdminUsersRepository + @Inject + constructor( + retrofit: Retrofit, + ) { + private val api: AdminUsersApi = retrofit.create() - suspend fun list(): List = api.list().users.map { it.toDomain() } + suspend fun list(): List = api.list().users.map { it.toDomain() } - suspend fun setAdmin(id: String, isAdmin: Boolean) = - api.setAdmin(id, SetAdminBody(isAdmin)) + suspend fun setAdmin( + id: String, + isAdmin: Boolean, + ) = api.setAdmin(id, SetAdminBody(isAdmin)) - suspend fun resetPassword(id: String, newPassword: String) = - api.resetPassword(id, ResetPasswordBody(newPassword)) + suspend fun resetPassword( + id: String, + newPassword: String, + ) = api.resetPassword(id, ResetPasswordBody(newPassword)) - suspend fun delete(id: String) = api.delete(id) -} + suspend fun delete(id: String) = api.delete(id) + } -private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef( - id = id, - username = username, - displayName = displayName, - isAdmin = isAdmin, - createdAt = createdAt, -) +private fun AdminUserWire.toDomain(): AdminUserRef = + AdminUserRef( + id = id, + username = username, + displayName = displayName, + isAdmin = isAdmin, + createdAt = createdAt, + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminInvitesViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminInvitesViewModel.kt index ab7ddaec..9f708bb1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminInvitesViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminInvitesViewModel.kt @@ -25,72 +25,73 @@ data class AdminInvitesUiState( ) @HiltViewModel -class AdminInvitesViewModel @Inject constructor( - private val repository: AdminInvitesRepository, - networkStatus: NetworkStatusController, -) : ViewModel() { +class AdminInvitesViewModel + @Inject + constructor( + private val repository: AdminInvitesRepository, + networkStatus: NetworkStatusController, + ) : ViewModel() { + private val internal = MutableStateFlow(AdminInvitesUiState()) + val state: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(AdminInvitesUiState()) - val state: StateFlow = internal.asStateFlow() + /** One-shot signal for screens to show the generated token + copy UI. */ + private val createdChannel = Channel(Channel.BUFFERED) + val created: Flow = createdChannel.receiveAsFlow() - /** One-shot signal for screens to show the generated token + copy UI. */ - private val createdChannel = Channel(Channel.BUFFERED) - val created: Flow = createdChannel.receiveAsFlow() - - init { - refresh() - // Screen-level auto-recovery: reload a failed list - // when server health returns instead of waiting for a manual pull. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value.message != null) refresh() - } - } - } - - fun refresh() { - viewModelScope.launch { - internal.update { it.copy(isLoading = true, message = null) } - try { - val rows = repository.list() - internal.update { it.copy(isLoading = false, invites = rows) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - isLoading = false, - message = ErrorCopy.fromThrowable(e), - ) + init { + refresh() + // Screen-level auto-recovery: reload a failed list + // when server health returns instead of waiting for a manual pull. + viewModelScope.launch { + networkStatus.recoveries().collect { + if (internal.value.message != null) refresh() } } } - } - fun generate(note: String?) { - viewModelScope.launch { - try { - val invite = repository.create(note) - createdChannel.trySend(invite) - // Optimistically prepend; next refresh reconciles. - internal.update { it.copy(invites = listOf(invite) + it.invites) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy(message = ErrorCopy.fromThrowable(e)) + fun refresh() { + viewModelScope.launch { + internal.update { it.copy(isLoading = true, message = null) } + try { + val rows = repository.list() + internal.update { it.copy(isLoading = false, invites = rows) } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy( + isLoading = false, + message = ErrorCopy.fromThrowable(e), + ) + } } } } - } - fun revoke(token: String) { - val before = internal.value.invites - // Optimistic removal. - internal.update { it.copy(invites = before.filterNot { i -> i.token == token }) } - viewModelScope.launch { - runCatching { repository.revoke(token) } - .onFailure { refresh() } + fun generate(note: String?) { + viewModelScope.launch { + try { + val invite = repository.create(note) + createdChannel.trySend(invite) + // Optimistically prepend; next refresh reconciles. + internal.update { it.copy(invites = listOf(invite) + it.invites) } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy(message = ErrorCopy.fromThrowable(e)) + } + } + } + } + + fun revoke(token: String) { + val before = internal.value.invites + // Optimistic removal. + internal.update { it.copy(invites = before.filterNot { i -> i.token == token }) } + viewModelScope.launch { + runCatching { repository.revoke(token) } + .onFailure { refresh() } + } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminLandingScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminLandingScreen.kt index ba558f7d..b9a619b7 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminLandingScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminLandingScreen.kt @@ -39,11 +39,11 @@ import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.nav.AdminUsers import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.loadUiState -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.async @@ -56,7 +56,11 @@ import javax.inject.Inject // ─── State ─────────────────────────────────────────────────────────── -data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int) +data class AdminCounts( + val quarantine: Int, + val users: Int, + val tagSources: Int, +) /** The admin landing's counts, as the shared [UiState] (never Empty: it always has counts). */ typealias AdminLandingUiState = UiState @@ -64,31 +68,34 @@ typealias AdminLandingUiState = UiState // ─── ViewModel ─────────────────────────────────────────────────────── @HiltViewModel -class AdminLandingViewModel @Inject constructor( - private val quarantineRepo: AdminQuarantineRepository, - private val usersRepo: AdminUsersRepository, - private val tagSourcesRepo: AdminTagSourcesRepository, -) : ViewModel() { +class AdminLandingViewModel + @Inject + constructor( + private val quarantineRepo: AdminQuarantineRepository, + private val usersRepo: AdminUsersRepository, + private val tagSourcesRepo: AdminTagSourcesRepository, + ) : ViewModel() { + private val internal = MutableStateFlow(UiState.Loading) + val uiState: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(UiState.Loading) - val uiState: StateFlow = internal.asStateFlow() - - init { - refresh() - } - - fun refresh(): Job = viewModelScope.launch { - internal.value = UiState.Loading - internal.value = loadUiState { - coroutineScope { - val qua = async { quarantineRepo.list().size } - val usr = async { usersRepo.list().size } - val tag = async { tagSourcesRepo.list().count { it.enabled } } - UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await())) - } + init { + refresh() } + + fun refresh(): Job = + viewModelScope.launch { + internal.value = UiState.Loading + internal.value = + loadUiState { + coroutineScope { + val qua = async { quarantineRepo.list().size } + val usr = async { usersRepo.list().size } + val tag = async { tagSourcesRepo.list().count { it.enabled } } + UiState.Success(AdminCounts(qua.await(), usr.await(), tag.await())) + } + } + } } -} // ─── Screen ────────────────────────────────────────────────────────── @@ -116,21 +123,26 @@ fun AdminLandingScreen( ) { when (val s = state) { UiState.Loading, UiState.Empty -> LoadingCentered() - is UiState.Error -> EmptyState( - title = "Couldn't load admin counts", - body = s.message, - ) - is UiState.Success -> SectionList( - counts = s.data, - navController = navController, - ) + is UiState.Error -> + EmptyState( + title = "Couldn't load admin counts", + body = s.message, + ) + is UiState.Success -> + SectionList( + counts = s.data, + navController = navController, + ) } } } } @Composable -private fun SectionList(counts: AdminCounts, navController: NavHostController) { +private fun SectionList( + counts: AdminCounts, + navController: NavHostController, +) { LazyColumn( modifier = Modifier.fillMaxSize(), contentPadding = PaddingValues(16.dp), @@ -175,9 +187,10 @@ private fun SectionCard( onClick: () -> Unit, ) { ElevatedCard( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick), + modifier = + Modifier + .fillMaxWidth() + .clickable(onClick = onClick), ) { Row( modifier = Modifier.padding(16.dp), diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineScreen.kt index 2eb1200a..8fef2754 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineScreen.kt @@ -35,12 +35,12 @@ import com.fabledsword.minstrel.models.AdminQuarantineItemRef import com.fabledsword.minstrel.nav.AdminQuarantine import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -74,22 +74,26 @@ fun AdminQuarantineScreen( ) { when (val s = state) { UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "No reports", - body = "When listeners flag a track as a bad rip, wrong tags or " + - "a duplicate, their reports gather here.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load queue", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> QueueList( - rows = s.data, - onResolve = viewModel::resolve, - onRemoveFile = viewModel::removeFile, - onDeleteFile = viewModel::deleteFile, - ) + UiState.Empty -> + EmptyState( + title = "No reports", + body = + "When listeners flag a track as a bad rip, wrong tags or " + + "a duplicate, their reports gather here.", + ) + is UiState.Error -> + ErrorRetry( + title = "Couldn't load queue", + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> + QueueList( + rows = s.data, + onResolve = viewModel::resolve, + onRemoveFile = viewModel::removeFile, + onDeleteFile = viewModel::deleteFile, + ) } } } @@ -98,7 +102,10 @@ fun AdminQuarantineScreen( /** A confirm asked of the admin before a removal: which one, and of which track. */ private enum class Removal { File, Library } -private data class PendingRemoval(val row: AdminQuarantineItemRef, val kind: Removal) +private data class PendingRemoval( + val row: AdminQuarantineItemRef, + val kind: Removal, +) @Composable private fun QueueList( @@ -146,20 +153,23 @@ private fun RemovalConfirm( onDismiss: () -> Unit, ) { val title = pending.row.trackTitle - val (heading, body, action) = when (pending.kind) { - Removal.File -> Triple( - "Remove the file?", - "Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " + - "and plays, and takes over a good copy when one is in the library. Its reports are cleared.", - "Remove the file", - ) - Removal.Library -> Triple( - "Remove from library?", - "Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " + - "places. To keep the track for a good copy, remove the file instead.", - "Remove from library", - ) - } + val (heading, body, action) = + when (pending.kind) { + Removal.File -> + Triple( + "Remove the file?", + "Delete the file of \u201c$title\u201d and keep the track. It waits, with its likes " + + "and plays, and takes over a good copy when one is in the library. Its reports are cleared.", + "Remove the file", + ) + Removal.Library -> + Triple( + "Remove from library?", + "Remove \u201c$title\u201d and its file for good, with its likes, plays and playlist " + + "places. To keep the track for a good copy, remove the file instead.", + "Remove from library", + ) + } ConfirmDestructiveDialog( title = heading, text = body, @@ -177,9 +187,10 @@ private fun QuarantineRow( onDeleteFile: () -> Unit, ) { Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModel.kt index 7f668884..099dc27c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModel.kt @@ -27,62 +27,69 @@ import javax.inject.Inject typealias AdminQuarantineUiState = UiState> @HiltViewModel -class AdminQuarantineViewModel @Inject constructor( - private val repository: AdminQuarantineRepository, - private val eventsStream: EventsStream, - networkStatus: NetworkStatusController, -) : ViewModel() { +class AdminQuarantineViewModel + @Inject + constructor( + private val repository: AdminQuarantineRepository, + private val eventsStream: EventsStream, + networkStatus: NetworkStatusController, + ) : ViewModel() { + private val internal = MutableStateFlow(UiState.Loading) + val uiState: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(UiState.Loading) - val uiState: StateFlow = internal.asStateFlow() + /** + * One-shot messages for the screen's snackbar. A failed action has to say + * why: the row quietly reappearing reads as a glitch, and for a removal + * refused by a read-only library it hides the one thing an admin can fix. + */ + private val transientMessagesChannel = Channel(Channel.BUFFERED) + val transientMessages: Flow = transientMessagesChannel.receiveAsFlow() - /** - * One-shot messages for the screen's snackbar. A failed action has to say - * why: the row quietly reappearing reads as a glitch, and for a removal - * refused by a read-only library it hides the one thing an admin can fix. - */ - private val transientMessagesChannel = Channel(Channel.BUFFERED) - val transientMessages: Flow = transientMessagesChannel.receiveAsFlow() - - init { - refresh() - viewModelScope.launch { - eventsStream.events - .filter { it.kind.startsWith("quarantine.") } - .collect { refresh() } + init { + refresh() + viewModelScope.launch { + eventsStream.events + .filter { it.kind.startsWith("quarantine.") } + .collect { refresh() } + } + // Screen-level auto-recovery: reload a failed list + // when server health returns instead of waiting for a manual pull. + viewModelScope.launch { + networkStatus.recoveries().collect { + if (internal.value is UiState.Error) refresh() + } + } } - // Screen-level auto-recovery: reload a failed list - // when server health returns instead of waiting for a manual pull. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value is UiState.Error) refresh() + + fun refresh(): Job = + viewModelScope.launch { + internal.value = UiState.Loading + internal.value = loadUiState { repository.list().toListState() } + } + + fun resolve(trackId: String) = act(trackId) { repository.resolve(it) } + + fun removeFile(trackId: String) = act(trackId) { repository.removeFile(it) } + + fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) } + + private fun act( + trackId: String, + action: suspend (String) -> Unit, + ) { + val before = internal.value + if (before is UiState.Success) { + internal.value = before.data.filterNot { it.trackId == trackId }.toListState() + } + viewModelScope.launch { + try { + action(trackId) + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + transientMessagesChannel.trySend(ErrorCopy.fromThrowable(e)) + refresh() + } } } } - - fun refresh(): Job = viewModelScope.launch { - internal.value = UiState.Loading - internal.value = loadUiState { repository.list().toListState() } - } - - fun resolve(trackId: String) = act(trackId) { repository.resolve(it) } - fun removeFile(trackId: String) = act(trackId) { repository.removeFile(it) } - fun deleteFile(trackId: String) = act(trackId) { repository.deleteFile(it) } - - private fun act(trackId: String, action: suspend (String) -> Unit) { - val before = internal.value - if (before is UiState.Success) { - internal.value = before.data.filterNot { it.trackId == trackId }.toListState() - } - viewModelScope.launch { - try { - action(trackId) - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - transientMessagesChannel.trySend(ErrorCopy.fromThrowable(e)) - refresh() - } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesScreen.kt index 10c77d47..650be68c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesScreen.kt @@ -36,12 +36,12 @@ import com.fabledsword.minstrel.models.AdminTagSourceRef import com.fabledsword.minstrel.models.TagSourceTestResult import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.shared.UiState -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -68,22 +68,25 @@ fun AdminTagSourcesScreen( ) { when (val s = state) { UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "No tag sources", - body = "Tag-enrichment providers register on the server; none are available.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load tag sources", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> TagSourceList( - providers = s.data.providers, - testResults = s.data.testResults, - onToggle = viewModel::setEnabled, - onSaveKey = viewModel::saveApiKey, - onTest = viewModel::test, - ) + UiState.Empty -> + EmptyState( + title = "No tag sources", + body = "Tag-enrichment providers register on the server; none are available.", + ) + is UiState.Error -> + ErrorRetry( + title = "Couldn't load tag sources", + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> + TagSourceList( + providers = s.data.providers, + testResults = s.data.testResults, + onToggle = viewModel::setEnabled, + onSaveKey = viewModel::saveApiKey, + onTest = viewModel::test, + ) } } } @@ -156,7 +159,10 @@ private fun TagSourceCard( } @Composable -private fun ApiKeyRow(provider: AdminTagSourceRef, onSaveKey: (String, String) -> Unit) { +private fun ApiKeyRow( + provider: AdminTagSourceRef, + onSaveKey: (String, String) -> Unit, +) { var key by remember(provider.id) { mutableStateOf("") } OutlinedTextField( value = key, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesViewModel.kt index 02f9af2e..951fe6b2 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminTagSourcesViewModel.kt @@ -28,86 +28,99 @@ data class AdminTagSources( typealias AdminTagSourcesUiState = UiState @HiltViewModel -class AdminTagSourcesViewModel @Inject constructor( - private val repository: AdminTagSourcesRepository, - networkStatus: NetworkStatusController, -) : ViewModel() { +class AdminTagSourcesViewModel + @Inject + constructor( + private val repository: AdminTagSourcesRepository, + networkStatus: NetworkStatusController, + ) : ViewModel() { + private val internal = MutableStateFlow(UiState.Loading) + val uiState: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(UiState.Loading) - val uiState: StateFlow = internal.asStateFlow() - - init { - refresh() - // Screen-level auto-recovery: reload a failed list when server - // health returns instead of waiting for a manual pull. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value is UiState.Error) refresh() + init { + refresh() + // Screen-level auto-recovery: reload a failed list when server + // health returns instead of waiting for a manual pull. + viewModelScope.launch { + networkStatus.recoveries().collect { + if (internal.value is UiState.Error) refresh() + } } } - } - fun refresh(): Job = viewModelScope.launch { - internal.value = UiState.Loading - internal.value = loadUiState { - val providers = repository.list() - if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers)) - } - } + fun refresh(): Job = + viewModelScope.launch { + internal.value = UiState.Loading + internal.value = + loadUiState { + val providers = repository.list() + if (providers.isEmpty()) UiState.Empty else UiState.Success(AdminTagSources(providers)) + } + } - fun setEnabled(id: String, enabled: Boolean) { - val before = (internal.value as? UiState.Success)?.data ?: return - // Optimistic toggle; reconcile via refresh() if the server rejects. - internal.value = UiState.Success( - before.copy( - providers = before.providers.map { - if (it.id == id) it.copy(enabled = enabled) else it - }, - ), - ) - viewModelScope.launch { - try { - repository.setEnabled(id, enabled) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - refresh() + fun setEnabled( + id: String, + enabled: Boolean, + ) { + val before = (internal.value as? UiState.Success)?.data ?: return + // Optimistic toggle; reconcile via refresh() if the server rejects. + internal.value = + UiState.Success( + before.copy( + providers = + before.providers.map { + if (it.id == id) it.copy(enabled = enabled) else it + }, + ), + ) + viewModelScope.launch { + try { + repository.setEnabled(id, enabled) + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + refresh() + } } } - } - fun saveApiKey(id: String, apiKey: String) { - viewModelScope.launch { - try { - replaceProvider(repository.setApiKey(id, apiKey)) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - refresh() + fun saveApiKey( + id: String, + apiKey: String, + ) { + viewModelScope.launch { + try { + replaceProvider(repository.setApiKey(id, apiKey)) + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + refresh() + } } } - } - fun test(id: String) { - viewModelScope.launch { - val result = try { - repository.test(id) - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e)) + fun test(id: String) { + viewModelScope.launch { + val result = + try { + repository.test(id) + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + TagSourceTestResult(ok = false, error = ErrorCopy.fromThrowable(e)) + } + val current = (internal.value as? UiState.Success)?.data ?: return@launch + internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result))) } - val current = (internal.value as? UiState.Success)?.data ?: return@launch - internal.value = UiState.Success(current.copy(testResults = current.testResults + (id to result))) + } + + private fun replaceProvider(updated: AdminTagSourceRef) { + val current = (internal.value as? UiState.Success)?.data ?: return + internal.value = + UiState.Success( + current.copy( + providers = current.providers.map { if (it.id == updated.id) updated else it }, + ), + ) } } - - private fun replaceProvider(updated: AdminTagSourceRef) { - val current = (internal.value as? UiState.Success)?.data ?: return - internal.value = UiState.Success( - current.copy( - providers = current.providers.map { if (it.id == updated.id) updated else it }, - ), - ) - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersScreen.kt index 6bbb9741..6a1b11a3 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersScreen.kt @@ -2,37 +2,27 @@ package com.fabledsword.minstrel.admin.ui +import android.content.ClipData 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.size import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.layout.size import androidx.compose.material3.AlertDialog import androidx.compose.material3.Button -import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.Copy -import com.composables.icons.lucide.KeyRound -import com.composables.icons.lucide.Plus -import com.composables.icons.lucide.Trash2 import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton import androidx.compose.material3.OutlinedTextField import androidx.compose.material3.Scaffold import androidx.compose.material3.Switch import androidx.compose.material3.Text import androidx.compose.material3.TextButton -import android.content.ClipData -import androidx.compose.ui.platform.ClipEntry -import androidx.compose.ui.platform.LocalClipboard -import com.fabledsword.minstrel.auth.PasswordRules -import com.fabledsword.minstrel.models.Invite import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -42,19 +32,28 @@ import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.ClipEntry +import androidx.compose.ui.platform.LocalClipboard import androidx.compose.ui.text.input.PasswordVisualTransformation import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController +import com.composables.icons.lucide.Copy +import com.composables.icons.lucide.KeyRound +import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Plus +import com.composables.icons.lucide.Trash2 +import com.fabledsword.minstrel.auth.PasswordRules import com.fabledsword.minstrel.models.AdminUserRef +import com.fabledsword.minstrel.models.Invite import com.fabledsword.minstrel.nav.AdminUsers import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import kotlinx.coroutines.launch @Composable @@ -175,11 +174,15 @@ private fun AdminUsersScaffold( } @Composable -private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = null) { +private fun SectionHeader( + label: String, + trailing: (@Composable () -> Unit)? = null, +) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( @@ -202,15 +205,16 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection( UiState.Loading -> item { CenteredHint("Loading users…") } UiState.Empty -> item { CenteredHint("No registered users.") } is UiState.Error -> item { CenteredHint(state.message) } - is UiState.Success -> items(items = state.data, key = { it.id }) { user -> - UserRow( - user = user, - onSetAdmin = { onSetAdmin(user.id, it) }, - onResetPassword = { onAskResetPassword(user) }, - onDelete = { onAskDelete(user) }, - ) - HorizontalDivider() - } + is UiState.Success -> + items(items = state.data, key = { it.id }) { user -> + UserRow( + user = user, + onSetAdmin = { onSetAdmin(user.id, it) }, + onResetPassword = { onAskResetPassword(user) }, + onDelete = { onAskDelete(user) }, + ) + HorizontalDivider() + } } } @@ -220,13 +224,15 @@ private fun androidx.compose.foundation.lazy.LazyListScope.invitesSection( ) { when { state.isLoading -> item { CenteredHint("Loading invites…") } - state.invites.isEmpty() -> item { - CenteredHint("No active invites. Use Generate to create one.") - } - else -> items(items = state.invites, key = { it.token }) { invite -> - InviteRow(invite = invite, onRevoke = { onRevoke(invite.token) }) - HorizontalDivider() - } + state.invites.isEmpty() -> + item { + CenteredHint("No active invites. Use Generate to create one.") + } + else -> + items(items = state.invites, key = { it.token }) { invite -> + InviteRow(invite = invite, onRevoke = { onRevoke(invite.token) }) + HorizontalDivider() + } } } @@ -241,11 +247,15 @@ private fun CenteredHint(text: String) { } @Composable -private fun InviteRow(invite: Invite, onRevoke: () -> Unit) { +private fun InviteRow( + invite: Invite, + onRevoke: () -> Unit, +) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, ) { Column(modifier = Modifier.weight(1f)) { @@ -256,13 +266,14 @@ private fun InviteRow(invite: Invite, onRevoke: () -> Unit) { maxLines = 1, overflow = TextOverflow.Ellipsis, ) - val subtitle = buildString { - if (!invite.note.isNullOrEmpty()) { - append(invite.note) - append(" · ") + val subtitle = + buildString { + if (!invite.note.isNullOrEmpty()) { + append(invite.note) + append(" · ") + } + append(if (invite.isRedeemed) "redeemed" else "expires ${invite.expiresAt}") } - append(if (invite.isRedeemed) "redeemed" else "expires ${invite.expiresAt}") - } Text( text = subtitle, style = MaterialTheme.typography.bodySmall, @@ -284,7 +295,10 @@ private fun InviteRow(invite: Invite, onRevoke: () -> Unit) { } @Composable -private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) -> Unit) { +private fun GenerateInviteDialog( + onDismiss: () -> Unit, + onConfirm: (String?) -> Unit, +) { var note by remember { mutableStateOf("") } AlertDialog( onDismissRequest = onDismiss, @@ -317,7 +331,10 @@ private fun GenerateInviteDialog(onDismiss: () -> Unit, onConfirm: (String?) -> } @Composable -private fun GeneratedInviteDialog(invite: Invite, onDismiss: () -> Unit) { +private fun GeneratedInviteDialog( + invite: Invite, + onDismiss: () -> Unit, +) { val clipboard = LocalClipboard.current val scope = rememberCoroutineScope() AlertDialog( @@ -399,9 +416,10 @@ private fun UserRow( onDelete: () -> Unit, ) { Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(8.dp), ) { Text( @@ -444,7 +462,11 @@ private fun UserRow( } @Composable -private fun ToggleRow(label: String, checked: Boolean, onChange: (Boolean) -> Unit) { +private fun ToggleRow( + label: String, + checked: Boolean, + onChange: (Boolean) -> Unit, +) { Row( modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically, @@ -496,8 +518,9 @@ private fun DeleteConfirmDialog( ) { ConfirmDestructiveDialog( title = "Delete user?", - text = "Delete @${user.username}? This removes the account and all " + - "their data. Type $DELETE_CONFIRM_WORD to confirm.", + text = + "Delete @${user.username}? This removes the account and all " + + "their data. Type $DELETE_CONFIRM_WORD to confirm.", confirmLabel = "Delete", onConfirm = onConfirm, onDismiss = onDismiss, @@ -506,4 +529,3 @@ private fun DeleteConfirmDialog( } private const val DELETE_CONFIRM_WORD = "DELETE" - diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersViewModel.kt index ac1d8388..ff9f5f0d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminUsersViewModel.kt @@ -21,77 +21,86 @@ import javax.inject.Inject typealias AdminUsersUiState = UiState> @HiltViewModel -class AdminUsersViewModel @Inject constructor( - private val repository: AdminUsersRepository, - networkStatus: NetworkStatusController, -) : ViewModel() { +class AdminUsersViewModel + @Inject + constructor( + private val repository: AdminUsersRepository, + networkStatus: NetworkStatusController, + ) : ViewModel() { + private val internal = MutableStateFlow(UiState.Loading) + val uiState: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(UiState.Loading) - val uiState: StateFlow = internal.asStateFlow() + init { + refresh() + // Screen-level auto-recovery: reload a failed list + // when server health returns instead of waiting for a manual pull. + viewModelScope.launch { + networkStatus.recoveries().collect { + if (internal.value is UiState.Error) refresh() + } + } + } - init { - refresh() - // Screen-level auto-recovery: reload a failed list - // when server health returns instead of waiting for a manual pull. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value is UiState.Error) refresh() + fun refresh(): Job = + viewModelScope.launch { + internal.value = UiState.Loading + internal.value = loadUiState { repository.list().toListState() } + } + + fun setAdmin( + id: String, + isAdmin: Boolean, + ) = patch(id, { it.copy(isAdmin = isAdmin) }) { + repository.setAdmin(it, isAdmin) + } + + fun resetPassword( + id: String, + newPassword: String, + ) { + viewModelScope.launch { + runCatching { repository.resetPassword(id, newPassword) } + } + } + + fun delete(id: String) { + val before = internal.value + if (before is UiState.Success) { + internal.value = before.data.filterNot { it.id == id }.toListState() + } + viewModelScope.launch { + try { + repository.delete(id) + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + refresh() + } + } + } + + private fun patch( + id: String, + mutate: (AdminUserRef) -> AdminUserRef, + action: suspend (String) -> Unit, + ) { + val before = internal.value + if (before is UiState.Success) { + internal.value = + UiState.Success( + before.data.map { if (it.id == id) mutate(it) else it }, + ) + } + viewModelScope.launch { + try { + action(id) + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + // Server-side guard might have rejected the toggle (e.g. + // last-admin protection); refetch reconciles state. + refresh() + } } } } - - fun refresh(): Job = viewModelScope.launch { - internal.value = UiState.Loading - internal.value = loadUiState { repository.list().toListState() } - } - - fun setAdmin(id: String, isAdmin: Boolean) = patch(id, { it.copy(isAdmin = isAdmin) }) { - repository.setAdmin(it, isAdmin) - } - - fun resetPassword(id: String, newPassword: String) { - viewModelScope.launch { - runCatching { repository.resetPassword(id, newPassword) } - } - } - - fun delete(id: String) { - val before = internal.value - if (before is UiState.Success) { - internal.value = before.data.filterNot { it.id == id }.toListState() - } - viewModelScope.launch { - try { - repository.delete(id) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - refresh() - } - } - } - - private fun patch( - id: String, - mutate: (AdminUserRef) -> AdminUserRef, - action: suspend (String) -> Unit, - ) { - val before = internal.value - if (before is UiState.Success) { - internal.value = UiState.Success( - before.data.map { if (it.id == id) mutate(it) else it }, - ) - } - viewModelScope.launch { - try { - action(id) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Server-side guard might have rejected the toggle (e.g. - // last-admin protection); refetch reconciles state. - refresh() - } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/AuthCookieInterceptor.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/AuthCookieInterceptor.kt index 4c721863..6b92113d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/AuthCookieInterceptor.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/AuthCookieInterceptor.kt @@ -20,43 +20,47 @@ import javax.inject.Singleton * from any of those hosts would sign the user out of Minstrel. */ @Singleton -class AuthCookieInterceptor @Inject constructor( - private val authStore: AuthStore, -) : Interceptor { - - override fun intercept(chain: Interceptor.Chain): Response { - val original = chain.request() - if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) { - // External request — no Minstrel session cookie attached, - // and a 401 from this host does NOT clear the user's - // session. Pass through untouched. - return chain.proceed(original) - } - val cookie = authStore.sessionCookieForRequest() - val request = original.newBuilder().apply { - if (!cookie.isNullOrEmpty()) header("Cookie", cookie) - }.build() - - val response = chain.proceed(request) - - if (response.code == HTTP_UNAUTHORIZED) { - // Only a refusal of the cookie this request carried ends the - // session. A request sent without one says nothing about the - // stored login, and a refusal of an older cookie must not - // discard one a sign-in has stored since. - if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie) - } else if (response.isSuccessful) { - // Capture the first Set-Cookie pair on login; subsequent - // responses that include Set-Cookie keep the store fresh. - response.headers("Set-Cookie").firstOrNull()?.let { sc -> - val firstPair = sc.substringBefore(';') - if (firstPair.isNotBlank()) authStore.setSessionCookie(firstPair) +class AuthCookieInterceptor + @Inject + constructor( + private val authStore: AuthStore, + ) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val original = chain.request() + if (original.url.host != BaseUrlInterceptor.PLACEHOLDER_HOST) { + // External request — no Minstrel session cookie attached, + // and a 401 from this host does NOT clear the user's + // session. Pass through untouched. + return chain.proceed(original) } - } - return response - } + val cookie = authStore.sessionCookieForRequest() + val request = + original + .newBuilder() + .apply { + if (!cookie.isNullOrEmpty()) header("Cookie", cookie) + }.build() - private companion object { - const val HTTP_UNAUTHORIZED = 401 + val response = chain.proceed(request) + + if (response.code == HTTP_UNAUTHORIZED) { + // Only a refusal of the cookie this request carried ends the + // session. A request sent without one says nothing about the + // stored login, and a refusal of an older cookie must not + // discard one a sign-in has stored since. + if (!cookie.isNullOrEmpty()) authStore.dropRejectedSessionCookie(cookie) + } else if (response.isSuccessful) { + // Capture the first Set-Cookie pair on login; subsequent + // responses that include Set-Cookie keep the store fresh. + response.headers("Set-Cookie").firstOrNull()?.let { sc -> + val firstPair = sc.substringBefore(';') + if (firstPair.isNotBlank()) authStore.setSessionCookie(firstPair) + } + } + return response + } + + private companion object { + const val HTTP_UNAUTHORIZED = 401 + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/BaseUrlInterceptor.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/BaseUrlInterceptor.kt index 2a732f7a..90a2b0d3 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/BaseUrlInterceptor.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/BaseUrlInterceptor.kt @@ -31,39 +31,43 @@ import javax.inject.Singleton * error in the caller's normal error path. */ @Singleton -class BaseUrlInterceptor @Inject constructor( - private val authStore: AuthStore, -) : Interceptor { +class BaseUrlInterceptor + @Inject + constructor( + private val authStore: AuthStore, + ) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val original = chain.request() + // Early-bail keeps the no-op path for external URLs cheap + // (no AuthStore read, no URL parse). + if (original.url.host != PLACEHOLDER_HOST) return chain.proceed(original) + // Unparseable baseUrl folds into the same proceed path — keeps + // detekt's ReturnCount happy by avoiding a second early return. + val rewritten: HttpUrl = + authStore.baseUrl.value.toHttpUrlOrNull()?.let { baseUrl -> + original.url + .newBuilder() + .scheme(baseUrl.scheme) + .host(baseUrl.host) + .port(baseUrl.port) + .build() + } ?: original.url + return chain.proceed( + original + .newBuilder() + .url(rewritten) + // Lets CleartextGuardInterceptor tell server requests from + // external fetches once the placeholder host is gone. + .tag(MinstrelServerRequest::class.java, MinstrelServerRequest) + .build(), + ) + } - override fun intercept(chain: Interceptor.Chain): Response { - val original = chain.request() - // Early-bail keeps the no-op path for external URLs cheap - // (no AuthStore read, no URL parse). - if (original.url.host != PLACEHOLDER_HOST) return chain.proceed(original) - // Unparseable baseUrl folds into the same proceed path — keeps - // detekt's ReturnCount happy by avoiding a second early return. - val rewritten: HttpUrl = authStore.baseUrl.value.toHttpUrlOrNull()?.let { baseUrl -> - original.url.newBuilder() - .scheme(baseUrl.scheme) - .host(baseUrl.host) - .port(baseUrl.port) - .build() - } ?: original.url - return chain.proceed( - original.newBuilder() - .url(rewritten) - // Lets CleartextGuardInterceptor tell server requests from - // external fetches once the placeholder host is gone. - .tag(MinstrelServerRequest::class.java, MinstrelServerRequest) - .build(), - ) + companion object { + /** Sentinel host used by Retrofit + every code path that builds + * a Minstrel-server URL via the `http://placeholder.invalid/...` + * form (see [com.fabledsword.minstrel.shared.resolveServerUrl], + * CoverUrls.kt, AlbumRef/TrackRef cover getters). */ + const val PLACEHOLDER_HOST = "placeholder.invalid" + } } - - companion object { - /** Sentinel host used by Retrofit + every code path that builds - * a Minstrel-server URL via the `http://placeholder.invalid/...` - * form (see [com.fabledsword.minstrel.shared.resolveServerUrl], - * CoverUrls.kt, AlbumRef/TrackRef cover getters). */ - const val PLACEHOLDER_HOST = "placeholder.invalid" - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/CleartextGuard.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/CleartextGuard.kt index 83dd29ce..5324ea59 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/CleartextGuard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/CleartextGuard.kt @@ -39,7 +39,12 @@ class CleartextGuardInterceptor( if (request.isHttps || request.tag(MinstrelServerRequest::class.java) == null) { return chain.proceed(request) } - val address = chain.connection()?.route()?.socketAddress?.address + val address = + chain + .connection() + ?.route() + ?.socketAddress + ?.address if (address != null && !allows(address)) { throw CleartextToPublicHostException(request.url.host) } @@ -48,8 +53,9 @@ class CleartextGuardInterceptor( } /** The server was reached over plain HTTP at a public address, and refused. */ -class CleartextToPublicHostException(host: String) : - IOException("refusing plain http:// to $host: it is a public address") +class CleartextToPublicHostException( + host: String, +) : IOException("refusing plain http:// to $host: it is a public address") /** Which addresses plain HTTP may reach: the home network, never the internet. */ object CleartextPolicy { @@ -62,8 +68,10 @@ object CleartextPolicy { fun allows(address: InetAddress): Boolean = address.isLoopbackAddress || - address.isSiteLocalAddress || // 10/8, 172.16/12, 192.168/16 - address.isLinkLocalAddress || // 169.254/16, fe80::/10 + address.isSiteLocalAddress || + // 10/8, 172.16/12, 192.168/16 + address.isLinkLocalAddress || + // 169.254/16, fe80::/10 address.isAnyLocalAddress || isCarrierGradeNat(address) || isUniqueLocal(address) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/ErrorCopy.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/ErrorCopy.kt index 3cf1d50b..51c532b5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/ErrorCopy.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/ErrorCopy.kt @@ -1,6 +1,5 @@ package com.fabledsword.minstrel.api -import kotlinx.serialization.SerialName import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import retrofit2.HttpException @@ -23,10 +22,15 @@ object ErrorCopy { private val json = Json { ignoreUnknownKeys = true } @Serializable - private data class Envelope(val error: Body? = null) + private data class Envelope( + val error: Body? = null, + ) @Serializable - private data class Body(val code: String = "", val message: String = "") + private data class Body( + val code: String = "", + val message: String = "", + ) /** Friendly copy for a known error [code], or the `unknown` fallback. */ fun messageFor(code: String): String = TABLE[code] ?: TABLE.getValue("unknown") @@ -36,12 +40,13 @@ object ErrorCopy { * HttpException bodies for the server code; treats IOExceptions * as connection failures. */ - fun fromThrowable(t: Throwable): String = when (t) { - is HttpException -> fromHttp(t) - is CleartextToPublicHostException -> messageFor("cleartext_public") - is IOException -> messageFor("connection_refused") - else -> TABLE.getValue("unknown") - } + fun fromThrowable(t: Throwable): String = + when (t) { + is HttpException -> fromHttp(t) + is CleartextToPublicHostException -> messageFor("cleartext_public") + is IOException -> messageFor("connection_refused") + else -> TABLE.getValue("unknown") + } /** * Codes whose server message carries specifics an admin needs in order @@ -65,8 +70,9 @@ object ErrorCopy { } private fun bodyFromHttp(e: HttpException): Body { - val raw = runCatching { e.response()?.errorBody()?.string() }.getOrNull() - ?: return Body() + val raw = + runCatching { e.response()?.errorBody()?.string() }.getOrNull() + ?: return Body() return runCatching { json.decodeFromString(raw).error } .getOrNull() ?: Body() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/NetworkModule.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/NetworkModule.kt index aa8eef2d..f8ce1d54 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/NetworkModule.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/NetworkModule.kt @@ -28,7 +28,6 @@ import javax.inject.Singleton @Module @InstallIn(SingletonComponent::class) object NetworkModule { - @Provides @Singleton fun provideHttpLogging(): HttpLoggingInterceptor = @@ -49,7 +48,8 @@ object NetworkModule { reachability: ReachabilityReportingInterceptor, logging: HttpLoggingInterceptor, ): OkHttpClient = - OkHttpClient.Builder() + OkHttpClient + .Builder() // ReachabilityReportingInterceptor MUST run first: it identifies // Minstrel-bound requests by the still-unrewritten PLACEHOLDER_HOST // (so external artwork fetches don't read as server reachability) @@ -82,7 +82,8 @@ object NetworkModule { okHttp: OkHttpClient, json: Json, ): Retrofit = - Retrofit.Builder() + Retrofit + .Builder() // Placeholder base URL — BaseUrlInterceptor rewrites every // outgoing request to the live AuthStore value, so this // string only has to satisfy Retrofit's parser and is diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/ServerBaseUrl.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/ServerBaseUrl.kt index 889146be..70d56fcc 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/ServerBaseUrl.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/ServerBaseUrl.kt @@ -6,4 +6,6 @@ package com.fabledsword.minstrel.api * the graph. */ @JvmInline -value class ServerBaseUrl(val value: String) +value class ServerBaseUrl( + val value: String, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminInvitesApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminInvitesApi.kt index dd64bc8c..58891d5a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminInvitesApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminInvitesApi.kt @@ -20,10 +20,14 @@ interface AdminInvitesApi { suspend fun list(): AdminInvitesListWire @POST("api/admin/invites") - suspend fun create(@Body body: CreateInviteBody): InviteWire + suspend fun create( + @Body body: CreateInviteBody, + ): InviteWire @DELETE("api/admin/invites/{token}") - suspend fun revoke(@Path("token") token: String) + suspend fun revoke( + @Path("token") token: String, + ) } /** @@ -31,4 +35,6 @@ interface AdminInvitesApi { * which the server treats the same as an absent field. */ @Serializable -data class CreateInviteBody(val note: String? = null) +data class CreateInviteBody( + val note: String? = null, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminQuarantineApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminQuarantineApi.kt index ec1116c5..854d557e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminQuarantineApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminQuarantineApi.kt @@ -19,11 +19,17 @@ interface AdminQuarantineApi { suspend fun list(): List @POST("api/admin/quarantine/{trackId}/resolve") - suspend fun resolve(@Path("trackId") trackId: String) + suspend fun resolve( + @Path("trackId") trackId: String, + ) @POST("api/admin/quarantine/{trackId}/remove-file") - suspend fun removeFile(@Path("trackId") trackId: String) + suspend fun removeFile( + @Path("trackId") trackId: String, + ) @POST("api/admin/quarantine/{trackId}/delete-file") - suspend fun deleteFile(@Path("trackId") trackId: String) + suspend fun deleteFile( + @Path("trackId") trackId: String, + ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminTagSourcesApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminTagSourcesApi.kt index b7f0a96a..fcd9a8cc 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminTagSourcesApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminTagSourcesApi.kt @@ -23,10 +23,15 @@ interface AdminTagSourcesApi { suspend fun list(): AdminTagSourcesListWire @PATCH("api/admin/tag-sources/{id}") - suspend fun update(@Path("id") id: String, @Body body: UpdateTagSourceBody): AdminTagSourceWire + suspend fun update( + @Path("id") id: String, + @Body body: UpdateTagSourceBody, + ): AdminTagSourceWire @POST("api/admin/tag-sources/{id}/test") - suspend fun test(@Path("id") id: String): TestTagSourceWire + suspend fun test( + @Path("id") id: String, + ): TestTagSourceWire } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminUsersApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminUsersApi.kt index 0064f792..e0a85c02 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminUsersApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminUsersApi.kt @@ -15,13 +15,21 @@ interface AdminUsersApi { suspend fun list(): AdminUsersListWire @PUT("api/admin/users/{id}/admin") - suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody) + suspend fun setAdmin( + @Path("id") id: String, + @Body body: SetAdminBody, + ) @POST("api/admin/users/{id}/reset-password") - suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody) + suspend fun resetPassword( + @Path("id") id: String, + @Body body: ResetPasswordBody, + ) @DELETE("api/admin/users/{id}") - suspend fun delete(@Path("id") id: String) + suspend fun delete( + @Path("id") id: String, + ) } @Serializable @@ -30,4 +38,6 @@ data class SetAdminBody( ) @Serializable -data class ResetPasswordBody(val password: String) +data class ResetPasswordBody( + val password: String, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AuthApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AuthApi.kt index b7dc6e3a..e023ae21 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AuthApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AuthApi.kt @@ -14,7 +14,9 @@ import retrofit2.http.POST */ interface AuthApi { @POST("api/auth/login") - suspend fun login(@Body body: LoginRequestBody): LoginResponseWire + suspend fun login( + @Body body: LoginRequestBody, + ): LoginResponseWire @POST("api/auth/logout") suspend fun logout() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/CastApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/CastApi.kt index 736cfbb8..80a07bd1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/CastApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/CastApi.kt @@ -22,7 +22,9 @@ import retrofit2.http.POST */ interface CastApi { @POST("api/cast/stream-token") - suspend fun streamToken(@Body req: StreamTokenRequest): StreamTokenResponse + suspend fun streamToken( + @Body req: StreamTokenRequest, + ): StreamTokenResponse } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiagnosticsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiagnosticsApi.kt index 38e91dd7..a439a0a8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiagnosticsApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiagnosticsApi.kt @@ -14,7 +14,9 @@ import retrofit2.http.POST */ interface DiagnosticsApi { @POST("api/diagnostics") - suspend fun report(@Body body: DiagnosticsReportRequest) + suspend fun report( + @Body body: DiagnosticsReportRequest, + ) } @Serializable diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/EventsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/EventsApi.kt index 0c56f259..f2076eb9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/EventsApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/EventsApi.kt @@ -17,14 +17,22 @@ import retrofit2.http.POST */ interface EventsApi { @POST("api/events") - suspend fun playStarted(@Body body: PlayStartedRequest): PlayStartedResponse + suspend fun playStarted( + @Body body: PlayStartedRequest, + ): PlayStartedResponse @POST("api/events") - suspend fun playEnded(@Body body: PlayEndedRequest) + suspend fun playEnded( + @Body body: PlayEndedRequest, + ) @POST("api/events") - suspend fun playSkipped(@Body body: PlaySkippedRequest) + suspend fun playSkipped( + @Body body: PlaySkippedRequest, + ) @POST("api/events") - suspend fun playOffline(@Body body: PlayOfflineRequest) + suspend fun playOffline( + @Body body: PlayOfflineRequest, + ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/LibraryApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/LibraryApi.kt index 4bccddfc..5a96eb77 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/LibraryApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/LibraryApi.kt @@ -30,13 +30,19 @@ import retrofit2.http.Query */ interface LibraryApi { @GET("api/tracks/{id}") - suspend fun getTrack(@Path("id") id: String): TrackWire + suspend fun getTrack( + @Path("id") id: String, + ): TrackWire @GET("api/artists/{id}") - suspend fun getArtistDetail(@Path("id") id: String): ArtistDetailWire + suspend fun getArtistDetail( + @Path("id") id: String, + ): ArtistDetailWire @GET("api/artists/{id}/tracks") - suspend fun getArtistTracks(@Path("id") id: String): List + suspend fun getArtistTracks( + @Path("id") id: String, + ): List @GET("api/artists/{id}/similar") suspend fun getSimilarArtists( @@ -51,10 +57,14 @@ interface LibraryApi { ): List @GET("api/albums/{id}") - suspend fun getAlbumDetail(@Path("id") id: String): AlbumDetailWire + suspend fun getAlbumDetail( + @Path("id") id: String, + ): AlbumDetailWire @GET("api/library/shuffle") - suspend fun shuffleLibrary(@Query("limit") limit: Int = 100): List + suspend fun shuffleLibrary( + @Query("limit") limit: Int = 100, + ): List // Browse axes. Both indexes are unpaged by design: the client needs // the whole set to render a browsable picker, and even a messy library diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/LikesApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/LikesApi.kt index 0be5ba45..4b0ac987 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/LikesApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/LikesApi.kt @@ -20,10 +20,16 @@ import retrofit2.http.Path */ interface LikesApi { @POST("api/likes/{kind}/{id}") - suspend fun like(@Path("kind") kind: String, @Path("id") id: String) + suspend fun like( + @Path("kind") kind: String, + @Path("id") id: String, + ) @DELETE("api/likes/{kind}/{id}") - suspend fun unlike(@Path("kind") kind: String, @Path("id") id: String) + suspend fun unlike( + @Path("kind") kind: String, + @Path("id") id: String, + ) @GET("api/likes/ids") suspend fun ids(): LikedIdsWire diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt index bf089a4a..77918e73 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/MeApi.kt @@ -27,14 +27,18 @@ interface MeApi { * state without an extra GET. */ @PUT("api/me/profile") - suspend fun updateProfile(@Body body: UpdateProfileRequest): MyProfileWire + suspend fun updateProfile( + @Body body: UpdateProfileRequest, + ): MyProfileWire /** * Change the caller's password. Server validates `current_password` * before accepting `new_password`. No body on success (204). */ @PUT("api/me/password") - suspend fun changePassword(@Body body: ChangePasswordRequest) + suspend fun changePassword( + @Body body: ChangePasswordRequest, + ) /** * Caller's ListenBrainz state — never returns the token itself, @@ -59,7 +63,9 @@ interface MeApi { * post-write status so callers refresh without a separate GET. */ @PUT("api/me/listenbrainz") - suspend fun setListenBrainz(@Body body: ListenBrainzPutBody): ListenBrainzStatusWire + suspend fun setListenBrainz( + @Body body: ListenBrainzPutBody, + ): ListenBrainzStatusWire /** The caller's loudness-normalization preference, or the defaults if never set. */ @GET("api/me/normalization") @@ -67,7 +73,9 @@ interface MeApi { /** Replaces the whole preference; returns what the server stored. */ @PUT("api/me/normalization") - suspend fun putNormalization(@Body body: NormalizationPrefs): NormalizationPrefs + suspend fun putNormalization( + @Body body: NormalizationPrefs, + ): NormalizationPrefs } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/NotificationsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/NotificationsApi.kt index 942817fe..e7cdb0e6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/NotificationsApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/NotificationsApi.kt @@ -15,20 +15,28 @@ import retrofit2.http.Query */ interface NotificationsApi { @GET("api/me/notifications") - suspend fun list(@Query("limit") limit: Int): NotificationsPageWire + suspend fun list( + @Query("limit") limit: Int, + ): NotificationsPageWire /** 204; 404 when the notice is gone, which a replay treats as done. */ @POST("api/me/notifications/{id}/read") - suspend fun markRead(@Path("id") id: String) + suspend fun markRead( + @Path("id") id: String, + ) @POST("api/me/notifications/read-all") - suspend fun readAll(@Body body: ReadAllBody) + suspend fun readAll( + @Body body: ReadAllBody, + ) @GET("api/me/notification-settings") suspend fun getSettings(): NotificationSettingsWire @PUT("api/me/notification-settings") - suspend fun putSettings(@Body body: PutNotificationSettingsBody): NotificationSettingsWire + suspend fun putSettings( + @Body body: PutNotificationSettingsBody, + ): NotificationSettingsWire } @Serializable @@ -55,7 +63,9 @@ data class NotificationsPageWire( * the app's Json drops default-valued fields. */ @Serializable -data class ReadAllBody(@SerialName("up_to") val upTo: String?) +data class ReadAllBody( + @SerialName("up_to") val upTo: String?, +) @Serializable data class NotificationKindSettingWire( @@ -87,4 +97,6 @@ data class NotificationSettingChangeWire( ) @Serializable -data class PutNotificationSettingsBody(val kinds: List) +data class PutNotificationSettingsBody( + val kinds: List, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaybackErrorsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaybackErrorsApi.kt index df792717..2b249e85 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaybackErrorsApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaybackErrorsApi.kt @@ -13,7 +13,9 @@ import retrofit2.http.POST */ interface PlaybackErrorsApi { @POST("api/playback-errors") - suspend fun report(@Body body: PlaybackErrorReportRequest) + suspend fun report( + @Body body: PlaybackErrorReportRequest, + ) } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt index 520ab623..ade2b0e5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/PlaylistsApi.kt @@ -24,24 +24,35 @@ interface PlaylistsApi { * playlists (not kind-filtered). */ @GET("api/playlists") - suspend fun list(@Query("kind") kind: String = "all"): PlaylistsListWire + suspend fun list( + @Query("kind") kind: String = "all", + ): PlaylistsListWire @GET("api/playlists/{id}") - suspend fun get(@Path("id") id: String): PlaylistDetailWire + suspend fun get( + @Path("id") id: String, + ): PlaylistDetailWire /** * POST /api/playlists — make a playlist under the id the app chose, * so a create queued offline and sent again finds the same list. */ @POST("api/playlists") - suspend fun create(@Body body: CreatePlaylistRequest) + suspend fun create( + @Body body: CreatePlaylistRequest, + ) /** PATCH /api/playlists/{id} — rename, or make public or private. Null fields stay as they are. */ @PATCH("api/playlists/{id}") - suspend fun update(@Path("id") id: String, @Body body: UpdatePlaylistRequest) + suspend fun update( + @Path("id") id: String, + @Body body: UpdatePlaylistRequest, + ) @DELETE("api/playlists/{id}") - suspend fun delete(@Path("id") id: String) + suspend fun delete( + @Path("id") id: String, + ) /** * DELETE /api/playlists/{id}/tracks/{position}. [trackId] is the song @@ -62,7 +73,10 @@ interface PlaylistsApi { * changes nothing the second time. */ @PUT("api/playlists/{id}/tracks") - suspend fun reorder(@Path("id") id: String, @Body body: ReorderTracksRequest) + suspend fun reorder( + @Path("id") id: String, + @Body body: ReorderTracksRequest, + ) /** POST /api/playlists/{id}/tracks — append the given track IDs to the owner's playlist. */ @POST("api/playlists/{id}/tracks") @@ -79,7 +93,9 @@ interface PlaylistsApi { * pick seed tracks. The kind is the raw system_variant. */ @POST("api/playlists/system/{kind}/refresh") - suspend fun refreshSystem(@Path("kind") variant: String): RefreshSystemResponse + suspend fun refreshSystem( + @Path("kind") variant: String, + ): RefreshSystemResponse /** * GET /api/playlists/system/{kind}/shuffle. Returns @@ -89,7 +105,9 @@ interface PlaylistsApi { * the stored order. */ @GET("api/playlists/system/{kind}/shuffle") - suspend fun systemShuffle(@Path("kind") variant: String): PlaylistDetailWire + suspend fun systemShuffle( + @Path("kind") variant: String, + ): PlaylistDetailWire } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/QuarantineApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/QuarantineApi.kt index fbc6314d..e390ac8b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/QuarantineApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/QuarantineApi.kt @@ -20,10 +20,14 @@ interface QuarantineApi { suspend fun listMine(): List @POST("api/quarantine") - suspend fun flag(@Body body: FlagRequest) + suspend fun flag( + @Body body: FlagRequest, + ) @DELETE("api/quarantine/{trackId}") - suspend fun unflag(@Path("trackId") trackId: String) + suspend fun unflag( + @Path("trackId") trackId: String, + ) } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/ReplayGainApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/ReplayGainApi.kt index 4e83ea27..9dd03d8a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/ReplayGainApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/ReplayGainApi.kt @@ -11,5 +11,7 @@ interface ReplayGainApi { * missing from `items` has not been measured yet. */ @GET("api/tracks/replay-gain") - suspend fun getReplayGain(@Query("ids") ids: String): ReplayGainResponseWire + suspend fun getReplayGain( + @Query("ids") ids: String, + ): ReplayGainResponseWire } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/SyncApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/SyncApi.kt index 4020a649..22df31e4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/SyncApi.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/SyncApi.kt @@ -19,5 +19,7 @@ import retrofit2.http.Query */ interface SyncApi { @GET("api/library/sync") - suspend fun sync(@Query("since") since: Long): Response + suspend fun sync( + @Query("since") since: Long, + ): Response } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthController.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthController.kt index ad7046b5..eb4c71df 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthController.kt @@ -29,114 +29,121 @@ import javax.inject.Singleton * username after a fresh app launch without re-prompting. */ @Singleton -class AuthController @Inject constructor( - private val authStore: AuthStore, - private val json: Json, - @ApplicationScope private val scope: CoroutineScope, - retrofit: Retrofit, -) { - private val api: AuthApi = retrofit.create() - private val meApi: MeApi = retrofit.create() +class AuthController + @Inject + constructor( + private val authStore: AuthStore, + private val json: Json, + @ApplicationScope private val scope: CoroutineScope, + retrofit: Retrofit, + ) { + private val api: AuthApi = retrofit.create() + private val meApi: MeApi = retrofit.create() - private val currentUserState = MutableStateFlow(null) - val currentUser: StateFlow = currentUserState.asStateFlow() + private val currentUserState = MutableStateFlow(null) + val currentUser: StateFlow = currentUserState.asStateFlow() - val sessionCookie: StateFlow get() = authStore.sessionCookie + val sessionCookie: StateFlow get() = authStore.sessionCookie - val isSignedIn: Boolean - get() = !authStore.sessionCookie.value.isNullOrEmpty() + val isSignedIn: Boolean + get() = !authStore.sessionCookie.value.isNullOrEmpty() - init { - // Rehydrate currentUser whenever the persisted userJson emits - // (cold start with a saved cookie OR explicit sign-in/out - // writing through AuthStore). Decode failures collapse to null - // so a malformed row can't crash the app — worst case is a - // blank username until the next sign-in writes a valid value. - scope.launch { - authStore.userJson.collect { raw -> - currentUserState.value = raw?.let { decodeUser(it) } + init { + // Rehydrate currentUser whenever the persisted userJson emits + // (cold start with a saved cookie OR explicit sign-in/out + // writing through AuthStore). Decode failures collapse to null + // so a malformed row can't crash the app — worst case is a + // blank username until the next sign-in writes a valid value. + scope.launch { + authStore.userJson.collect { raw -> + currentUserState.value = raw?.let { decodeUser(it) } + } } + // Refresh from /api/me on startup so a remotely-changed account + // flag (e.g. an admin enabling debug mode) reaches the device + // without a re-login. Best-effort; failures keep the cached value. + scope.launch { refreshProfile() } } - // Refresh from /api/me on startup so a remotely-changed account - // flag (e.g. an admin enabling debug mode) reaches the device - // without a re-login. Best-effort; failures keep the cached value. - scope.launch { refreshProfile() } - } - /** - * Submit credentials. On success the AuthCookieInterceptor will - * have captured the Set-Cookie before this method returns; the - * caller can safely navigate to the in-shell graph. Throws on - * any non-2xx response (caller surfaces in UI). - */ - suspend fun signIn(username: String, password: String): UserRef { - val response = api.login(LoginRequestBody(username = username, password = password)) - val user = UserRef( - id = response.user.id, - username = response.user.username, - isAdmin = response.user.isAdmin, - ) - currentUserState.value = user - authStore.setUserJson(json.encodeToString(UserRef.serializer(), user)) - // Pull the fuller /me shape (carries debug_mode_enabled) right - // after login so the diagnostics gate is correct without waiting - // for the next startup refresh. - scope.launch { refreshProfile() } - return user - } + /** + * Submit credentials. On success the AuthCookieInterceptor will + * have captured the Set-Cookie before this method returns; the + * caller can safely navigate to the in-shell graph. Throws on + * any non-2xx response (caller surfaces in UI). + */ + suspend fun signIn( + username: String, + password: String, + ): UserRef { + val response = api.login(LoginRequestBody(username = username, password = password)) + val user = + UserRef( + id = response.user.id, + username = response.user.username, + isAdmin = response.user.isAdmin, + ) + currentUserState.value = user + authStore.setUserJson(json.encodeToString(UserRef.serializer(), user)) + // Pull the fuller /me shape (carries debug_mode_enabled) right + // after login so the diagnostics gate is correct without waiting + // for the next startup refresh. + scope.launch { refreshProfile() } + return user + } - /** - * Re-fetch the caller's profile from /api/me and update currentUser - * + persisted userJson. Carries account-level flags (debug mode) - * that aren't in the login response. Best-effort: a network failure - * leaves the cached identity untouched. No-op when signed out. - * Waits for the stored login to load first: at launch this runs before - * it has, and would otherwise read the user as signed out and skip. - */ - suspend fun refreshProfile() { - authStore.awaitSessionHydrated() - if (!isSignedIn) return - val p = runCatching { meApi.getProfile() }.getOrNull() ?: return - val user = UserRef( - id = p.id, - username = p.username, - isAdmin = p.isAdmin, - debugModeEnabled = p.debugModeEnabled, - ) - currentUserState.value = user - authStore.setUserJson(json.encodeToString(UserRef.serializer(), user)) - } + /** + * Re-fetch the caller's profile from /api/me and update currentUser + * + persisted userJson. Carries account-level flags (debug mode) + * that aren't in the login response. Best-effort: a network failure + * leaves the cached identity untouched. No-op when signed out. + * Waits for the stored login to load first: at launch this runs before + * it has, and would otherwise read the user as signed out and skip. + */ + suspend fun refreshProfile() { + authStore.awaitSessionHydrated() + if (!isSignedIn) return + val p = runCatching { meApi.getProfile() }.getOrNull() ?: return + val user = + UserRef( + id = p.id, + username = p.username, + isAdmin = p.isAdmin, + debugModeEnabled = p.debugModeEnabled, + ) + currentUserState.value = user + authStore.setUserJson(json.encodeToString(UserRef.serializer(), user)) + } - /** - * Signs out here at once and ends the session on the server too. - * - * The app shows signed-out straight away, then calls - * `/api/auth/logout` while the session cookie is still set: the cookie - * is what tells the server which session to drop, so the call has to go - * before the cookie is cleared. The call waits at most - * [LOGOUT_TIMEOUT_MS]; offline, or on an error, the cookie is cleared - * anyway and the server session expires on its own. It runs in the - * application scope, so the screen that asked closing as the app shows - * signed-out can't cancel it halfway. - */ - suspend fun signOut() { - currentUserState.value = null - authStore.setUserJson(null) - scope.launch { - try { - withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } } - } finally { - authStore.setSessionCookie(null) - } - }.join() - } + /** + * Signs out here at once and ends the session on the server too. + * + * The app shows signed-out straight away, then calls + * `/api/auth/logout` while the session cookie is still set: the cookie + * is what tells the server which session to drop, so the call has to go + * before the cookie is cleared. The call waits at most + * [LOGOUT_TIMEOUT_MS]; offline, or on an error, the cookie is cleared + * anyway and the server session expires on its own. It runs in the + * application scope, so the screen that asked closing as the app shows + * signed-out can't cancel it halfway. + */ + suspend fun signOut() { + currentUserState.value = null + authStore.setUserJson(null) + scope + .launch { + try { + withTimeoutOrNull(LOGOUT_TIMEOUT_MS) { runCatching { api.logout() } } + } finally { + authStore.setSessionCookie(null) + } + }.join() + } - private fun decodeUser(raw: String): UserRef? = - runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull() + private fun decodeUser(raw: String): UserRef? = runCatching { json.decodeFromString(UserRef.serializer(), raw) }.getOrNull() - private companion object { - // Long enough for a logout on a slow connection, short enough that - // signing out offline doesn't seem to hang. - const val LOGOUT_TIMEOUT_MS = 5_000L + private companion object { + // Long enough for a logout on a slow connection, short enough that + // signing out offline doesn't seem to hang. + const val LOGOUT_TIMEOUT_MS = 5_000L + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt index f4f5e1ce..a6fa1333 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/AuthStore.kt @@ -21,6 +21,14 @@ import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton +// AuthStore is the single-row facade over auth_session (de-facto +// app_preferences — see entity comment). It legitimately owns one +// getter + one setter + one persist helper per pref column; the +// function count scales with the pref count, not with feature +// complexity. Splitting into per-pref stores would scatter the +// shared dao + scope + json plumbing for no real gain. Suppress +// the cap rather than fragment. + /** * Holds the user's session cookie and configured server base URL. * @@ -44,353 +52,352 @@ import javax.inject.Singleton * [awaitSessionHydrated] lets a caller that needs a definitive answer * (the auth gate) wait for this. */ -// AuthStore is the single-row facade over auth_session (de-facto -// app_preferences — see entity comment). It legitimately owns one -// getter + one setter + one persist helper per pref column; the -// function count scales with the pref count, not with feature -// complexity. Splitting into per-pref stores would scatter the -// shared dao + scope + json plumbing for no real gain. Suppress -// the cap rather than fragment. @Suppress("TooManyFunctions") @Singleton -class AuthStore @Inject constructor( - private val dao: AuthSessionDao, - private val vault: SessionVault, - @ApplicationScope private val scope: CoroutineScope, -) { - private val sessionCookieState = MutableStateFlow(null) - val sessionCookie: StateFlow = sessionCookieState.asStateFlow() +class AuthStore + @Inject + constructor( + private val dao: AuthSessionDao, + private val vault: SessionVault, + @ApplicationScope private val scope: CoroutineScope, + ) { + private val sessionCookieState = MutableStateFlow(null) + val sessionCookie: StateFlow = sessionCookieState.asStateFlow() - private val baseUrlState = MutableStateFlow(DEFAULT_BASE_URL) - val baseUrl: StateFlow = baseUrlState.asStateFlow() + private val baseUrlState = MutableStateFlow(DEFAULT_BASE_URL) + val baseUrl: StateFlow = baseUrlState.asStateFlow() - private val userJsonState = MutableStateFlow(null) - val userJson: StateFlow = userJsonState.asStateFlow() + private val userJsonState = MutableStateFlow(null) + val userJson: StateFlow = userJsonState.asStateFlow() - private val themeModeState = MutableStateFlow(null) - val themeMode: StateFlow = themeModeState.asStateFlow() + private val themeModeState = MutableStateFlow(null) + val themeMode: StateFlow = themeModeState.asStateFlow() - private val clientIdState = MutableStateFlow(null) - val clientId: StateFlow = clientIdState.asStateFlow() + private val clientIdState = MutableStateFlow(null) + val clientId: StateFlow = clientIdState.asStateFlow() - private val cacheSettingsState = MutableStateFlow(CacheSettings.DEFAULT) - val cacheSettings: StateFlow = cacheSettingsState.asStateFlow() + private val cacheSettingsState = MutableStateFlow(CacheSettings.DEFAULT) + val cacheSettings: StateFlow = cacheSettingsState.asStateFlow() - private val diagnosticsOptOutState = MutableStateFlow(false) - val diagnosticsOptOut: StateFlow = diagnosticsOptOutState.asStateFlow() + private val diagnosticsOptOutState = MutableStateFlow(false) + val diagnosticsOptOut: StateFlow = diagnosticsOptOutState.asStateFlow() - private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT) - val normalization: StateFlow = normalizationState.asStateFlow() + private val normalizationState = MutableStateFlow(NormalizationPrefs.DEFAULT) + val normalization: StateFlow = normalizationState.asStateFlow() - // Background delivery: the device's choice, on by default. - // The shade's high-water mark lives in the same row but is read and - // written through the DAO by NotificationSync, awaited, never cached here. - private val backgroundDeliveryState = MutableStateFlow(true) - val backgroundDelivery: StateFlow = backgroundDeliveryState.asStateFlow() + // Background delivery: the device's choice, on by default. + // The shade's high-water mark lives in the same row but is read and + // written through the DAO by NotificationSync, awaited, never cached here. + private val backgroundDeliveryState = MutableStateFlow(true) + val backgroundDelivery: StateFlow = 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(null) - val cacheOwnerUserId: StateFlow = cacheOwnerState.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(null) + val cacheOwnerUserId: StateFlow = cacheOwnerState.asStateFlow() - private val settingsLoadedState = MutableStateFlow(false) + private val settingsLoadedState = MutableStateFlow(false) - /** True once the stored settings row has been read at least once. */ - val settingsLoaded: StateFlow = settingsLoadedState.asStateFlow() + /** True once the stored settings row has been read at least once. */ + val settingsLoaded: StateFlow = 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 - // sign-in or a 401 that lands while hydration runs is never overwritten - // by the stale value hydration read. - private val cookieLock = Mutex() + // Serialises every cookie persist with the one-time hydration, so a + // sign-in or a 401 that lands while hydration runs is never overwritten + // by the stale value hydration read. + private val cookieLock = Mutex() - // Set by setSessionCookie. Once something has written the cookie this - // process, that value wins over whatever hydration finds on disk. - @Volatile private var cookieTouched = false + // Set by setSessionCookie. Once something has written the cookie this + // process, that value wins over whatever hydration finds on disk. + @Volatile private var cookieTouched = false - private val cookieHydration: Deferred = scope.async { hydrateSessionCookie() } + private val cookieHydration: Deferred = scope.async { hydrateSessionCookie() } - init { - scope.launch { - dao.observe().collect { row -> - baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL - userJsonState.value = row?.userJson - themeModeState.value = row?.themeMode - clientIdState.value = row?.clientId - cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson) - diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false - normalizationState.value = decodeNormalization(row?.normalizationJson) - backgroundDeliveryState.value = row?.backgroundDelivery ?: true - cacheOwnerState.value = row?.cacheOwnerUserId - settingsLoadedState.value = true + init { + scope.launch { + dao.observe().collect { row -> + baseUrlState.value = row?.baseUrl ?: DEFAULT_BASE_URL + userJsonState.value = row?.userJson + themeModeState.value = row?.themeMode + clientIdState.value = row?.clientId + cacheSettingsState.value = decodeCacheSettings(row?.cacheSettingsJson) + diagnosticsOptOutState.value = row?.diagnosticsOptOut ?: false + normalizationState.value = decodeNormalization(row?.normalizationJson) + backgroundDeliveryState.value = row?.backgroundDelivery ?: true + cacheOwnerState.value = row?.cacheOwnerUserId + settingsLoadedState.value = true + } } } - } - private fun decodeCacheSettings(raw: String?): CacheSettings { - if (raw.isNullOrEmpty()) return CacheSettings.DEFAULT - return runCatching { - json.decodeFromString(CacheSettings.serializer(), raw) - }.getOrDefault(CacheSettings.DEFAULT) - } - - private fun decodeNormalization(raw: String?): NormalizationPrefs { - if (raw.isNullOrEmpty()) return NormalizationPrefs.DEFAULT - return runCatching { - json.decodeFromString(NormalizationPrefs.serializer(), raw) - }.getOrDefault(NormalizationPrefs.DEFAULT) - } - - /** - * Suspends until the stored session cookie has been loaded into - * [sessionCookie], or [HYDRATION_DEADLINE_MS] passes, so a wedged - * Keystore cannot leave the start screen spinning. Returns false on - * the deadline; the caller then decides from whatever has loaded, and a - * late hydration still lands in [sessionCookie]. - */ - suspend fun awaitSessionHydrated(): Boolean { - val done = withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } != null - if (!done) Timber.w("auth store: session hydration passed its deadline; deciding without it") - return done - } - - fun setSessionCookie(value: String?) { - cookieTouched = true - sessionCookieState.value = value - scope.launch { cookieLock.withLock { storeCookie(value) } } - } - - /** - * The cookie to attach to an outgoing request. Blocks the calling - * (OkHttp) thread until the stored cookie has loaded, up to - * [HYDRATION_DEADLINE_MS], so a request made in the first moment after - * launch carries the login instead of going out without it. Once - * hydration has finished this is a plain read. - */ - fun sessionCookieForRequest(): String? { - if (!cookieHydration.isCompleted) { - runBlocking { withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } } + private fun decodeCacheSettings(raw: String?): CacheSettings { + if (raw.isNullOrEmpty()) return CacheSettings.DEFAULT + return runCatching { + json.decodeFromString(CacheSettings.serializer(), raw) + }.getOrDefault(CacheSettings.DEFAULT) } - return sessionCookieState.value - } - /** - * True once the server has refused the current session (see - * [dropRejectedSessionCookie]) and the UI has not yet sent the user to - * sign in. Held rather than fired, so a refusal that lands while the app - * is in the background is still acted on when it comes back. A sign-out - * the user asked for does not set it. - */ - private val sessionRejectedState = MutableStateFlow(false) - val sessionRejected: StateFlow = sessionRejectedState.asStateFlow() - - /** The UI has opened the sign-in screen for a refused session. */ - fun consumeSessionRejected() { - sessionRejectedState.value = false - } - - /** - * Signs out because the server answered 401 to a request that carried - * [rejected]. Does nothing when the store has since moved on to another - * cookie (a sign-in landed meanwhile), so a refusal of an old session - * never discards a new one. What is persisted is read inside the lock, - * so a sign-in racing this call is the value that ends up stored. - */ - fun dropRejectedSessionCookie(rejected: String) { - if (!sessionCookieState.compareAndSet(rejected, null)) return - cookieTouched = true - scope.launch { cookieLock.withLock { storeCookie(sessionCookieState.value) } } - sessionRejectedState.value = true - } - - private suspend fun hydrateSessionCookie() = cookieLock.withLock { - val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull() - if (cookieTouched) return@withLock - // A cookie in the row is the newer one when both exist: the row is - // only written when the vault failed, and an install upgrading from - // before the vault has nothing in the vault yet. - val cookie = legacy ?: vault.read() - // Best-effort: if moving it fails, the session still loads this time - // and the move is retried on the next launch. Hydration must never - // throw, or awaitSessionHydrated would leave the auth gate stuck. - if (legacy != null) { - runCatching { storeCookie(legacy) } - .onFailure { Timber.w(it, "auth store: could not move the session cookie into the vault") } + private fun decodeNormalization(raw: String?): NormalizationPrefs { + if (raw.isNullOrEmpty()) return NormalizationPrefs.DEFAULT + return runCatching { + json.decodeFromString(NormalizationPrefs.serializer(), raw) + }.getOrDefault(NormalizationPrefs.DEFAULT) } - sessionCookieState.value = cookie - } - // Vault first; the Room row only when the Keystore is unusable, so a - // broken Keystore degrades to the old storage rather than a sign-out. - private suspend fun storeCookie(value: String?) { - if (vault.write(value)) { - if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null) - } else { - persistLegacyCookie(value) + /** + * Suspends until the stored session cookie has been loaded into + * [sessionCookie], or [HYDRATION_DEADLINE_MS] passes, so a wedged + * Keystore cannot leave the start screen spinning. Returns false on + * the deadline; the caller then decides from whatever has loaded, and a + * late hydration still lands in [sessionCookie]. + */ + suspend fun awaitSessionHydrated(): Boolean { + val done = withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } != null + if (!done) Timber.w("auth store: session hydration passed its deadline; deciding without it") + return done } - } - fun setBaseUrl(value: String) { - baseUrlState.value = value - scope.launch { persistBaseUrl(value) } - } + fun setSessionCookie(value: String?) { + cookieTouched = true + sessionCookieState.value = value + scope.launch { cookieLock.withLock { storeCookie(value) } } + } - fun setUserJson(value: String?) { - userJsonState.value = value - scope.launch { persistUserJson(value) } - } + /** + * The cookie to attach to an outgoing request. Blocks the calling + * (OkHttp) thread until the stored cookie has loaded, up to + * [HYDRATION_DEADLINE_MS], so a request made in the first moment after + * launch carries the login instead of going out without it. Once + * hydration has finished this is a plain read. + */ + fun sessionCookieForRequest(): String? { + if (!cookieHydration.isCompleted) { + runBlocking { withTimeoutOrNull(HYDRATION_DEADLINE_MS) { cookieHydration.await() } } + } + return sessionCookieState.value + } - fun setThemeMode(value: String?) { - themeModeState.value = value - scope.launch { persistThemeMode(value) } - } + /** + * True once the server has refused the current session (see + * [dropRejectedSessionCookie]) and the UI has not yet sent the user to + * sign in. Held rather than fired, so a refusal that lands while the app + * is in the background is still acted on when it comes back. A sign-out + * the user asked for does not set it. + */ + private val sessionRejectedState = MutableStateFlow(false) + val sessionRejected: StateFlow = sessionRejectedState.asStateFlow() - fun setClientId(value: String?) { - clientIdState.value = value - scope.launch { persistClientId(value) } - } + /** The UI has opened the sign-in screen for a refused session. */ + fun consumeSessionRejected() { + sessionRejectedState.value = false + } - fun setCacheSettings(value: CacheSettings) { - cacheSettingsState.value = value - val encoded = json.encodeToString(CacheSettings.serializer(), value) - scope.launch { persistCacheSettings(encoded) } - } + /** + * Signs out because the server answered 401 to a request that carried + * [rejected]. Does nothing when the store has since moved on to another + * cookie (a sign-in landed meanwhile), so a refusal of an old session + * never discards a new one. What is persisted is read inside the lock, + * so a sign-in racing this call is the value that ends up stored. + */ + fun dropRejectedSessionCookie(rejected: String) { + if (!sessionCookieState.compareAndSet(rejected, null)) return + cookieTouched = true + scope.launch { cookieLock.withLock { storeCookie(sessionCookieState.value) } } + sessionRejectedState.value = true + } - fun setDiagnosticsOptOut(value: Boolean) { - diagnosticsOptOutState.value = value - scope.launch { persistDiagnosticsOptOut(value) } - } + private suspend fun hydrateSessionCookie() = + cookieLock.withLock { + val legacy = runCatching { dao.get()?.sessionCookie }.getOrNull() + if (cookieTouched) return@withLock + // A cookie in the row is the newer one when both exist: the row is + // only written when the vault failed, and an install upgrading from + // before the vault has nothing in the vault yet. + val cookie = legacy ?: vault.read() + // Best-effort: if moving it fails, the session still loads this time + // and the move is retried on the next launch. Hydration must never + // throw, or awaitSessionHydrated would leave the auth gate stuck. + if (legacy != null) { + runCatching { storeCookie(legacy) } + .onFailure { Timber.w(it, "auth store: could not move the session cookie into the vault") } + } + sessionCookieState.value = cookie + } - fun setNormalization(value: NormalizationPrefs) { - normalizationState.value = value - val encoded = json.encodeToString(NormalizationPrefs.serializer(), value) - scope.launch { persistNormalization(encoded) } - } - - fun setBackgroundDelivery(value: Boolean) { - backgroundDeliveryState.value = value - scope.launch { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(backgroundDelivery = value)) + // Vault first; the Room row only when the Keystore is unusable, so a + // broken Keystore degrades to the old storage rather than a sign-out. + private suspend fun storeCookie(value: String?) { + if (vault.write(value)) { + if (dao.get()?.sessionCookie != null) dao.setSessionCookie(null) } else { - dao.setBackgroundDelivery(value) + persistLegacyCookie(value) } } - } - /** - * 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) + fun setBaseUrl(value: String) { + baseUrlState.value = value + scope.launch { persistBaseUrl(value) } + } + + fun setUserJson(value: String?) { + userJsonState.value = value + scope.launch { persistUserJson(value) } + } + + fun setThemeMode(value: String?) { + themeModeState.value = value + scope.launch { persistThemeMode(value) } + } + + fun setClientId(value: String?) { + clientIdState.value = value + scope.launch { persistClientId(value) } + } + + fun setCacheSettings(value: CacheSettings) { + cacheSettingsState.value = value + val encoded = json.encodeToString(CacheSettings.serializer(), value) + scope.launch { persistCacheSettings(encoded) } + } + + fun setDiagnosticsOptOut(value: Boolean) { + diagnosticsOptOutState.value = value + scope.launch { persistDiagnosticsOptOut(value) } + } + + fun setNormalization(value: NormalizationPrefs) { + normalizationState.value = value + val encoded = json.encodeToString(NormalizationPrefs.serializer(), value) + scope.launch { persistNormalization(encoded) } + } + + fun setBackgroundDelivery(value: Boolean) { + backgroundDeliveryState.value = value + scope.launch { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(backgroundDelivery = value)) + } else { + dao.setBackgroundDelivery(value) + } + } + } + + /** + * 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?) { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(sessionCookie = value)) + } else { + dao.setSessionCookie(value) + } + } + + private suspend fun persistBaseUrl(value: String) { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(baseUrl = value)) + } else { + dao.setBaseUrl(value) + } + } + + private suspend fun persistUserJson(value: String?) { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(userJson = value)) + } else { + dao.setUserJson(value) + } + } + + private suspend fun persistThemeMode(value: String?) { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(themeMode = value)) + } else { + dao.setThemeMode(value) + } + } + + private suspend fun persistClientId(value: String?) { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(clientId = value)) + } else { + dao.setClientId(value) + } + } + + private suspend fun persistCacheSettings(json: String) { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(cacheSettingsJson = json)) + } else { + dao.setCacheSettingsJson(json) + } + } + + private suspend fun persistDiagnosticsOptOut(value: Boolean) { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(diagnosticsOptOut = value)) + } else { + dao.setDiagnosticsOptOut(value) + } + } + + private suspend fun persistNormalization(json: String) { + if (dao.get() == null) { + dao.upsert(currentEntity().copy(normalizationJson = json)) + } else { + dao.setNormalizationJson(json) + } + } + + private fun currentEntity(): AuthSessionEntity = + AuthSessionEntity( + id = ROW_ID, + // Never copied into the row: the cookie lives in the vault, and + // persistLegacyCookie sets it explicitly on the fallback path. + sessionCookie = null, + baseUrl = baseUrlState.value, + userJson = userJsonState.value, + themeMode = themeModeState.value, + clientId = clientIdState.value, + cacheSettingsJson = + json.encodeToString( + CacheSettings.serializer(), + cacheSettingsState.value, + ), + diagnosticsOptOut = diagnosticsOptOutState.value, + normalizationJson = + json.encodeToString( + NormalizationPrefs.serializer(), + normalizationState.value, + ), + backgroundDelivery = backgroundDeliveryState.value, + cacheOwnerUserId = cacheOwnerState.value, + ) + + companion object { + const val DEFAULT_BASE_URL: String = "http://localhost:8080" + + // Generous on purpose: hydration is one local row read and one + // Keystore decrypt, normally milliseconds. This only bounds "never". + const val HYDRATION_DEADLINE_MS: Long = 10_000 + private const val ROW_ID = 0 } } - - /** 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?) { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(sessionCookie = value)) - } else { - dao.setSessionCookie(value) - } - } - - private suspend fun persistBaseUrl(value: String) { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(baseUrl = value)) - } else { - dao.setBaseUrl(value) - } - } - - private suspend fun persistUserJson(value: String?) { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(userJson = value)) - } else { - dao.setUserJson(value) - } - } - - private suspend fun persistThemeMode(value: String?) { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(themeMode = value)) - } else { - dao.setThemeMode(value) - } - } - - private suspend fun persistClientId(value: String?) { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(clientId = value)) - } else { - dao.setClientId(value) - } - } - - private suspend fun persistCacheSettings(json: String) { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(cacheSettingsJson = json)) - } else { - dao.setCacheSettingsJson(json) - } - } - - private suspend fun persistDiagnosticsOptOut(value: Boolean) { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(diagnosticsOptOut = value)) - } else { - dao.setDiagnosticsOptOut(value) - } - } - - private suspend fun persistNormalization(json: String) { - if (dao.get() == null) { - dao.upsert(currentEntity().copy(normalizationJson = json)) - } else { - dao.setNormalizationJson(json) - } - } - - private fun currentEntity(): AuthSessionEntity = AuthSessionEntity( - id = ROW_ID, - // Never copied into the row: the cookie lives in the vault, and - // persistLegacyCookie sets it explicitly on the fallback path. - sessionCookie = null, - baseUrl = baseUrlState.value, - userJson = userJsonState.value, - themeMode = themeModeState.value, - clientId = clientIdState.value, - cacheSettingsJson = json.encodeToString( - CacheSettings.serializer(), - cacheSettingsState.value, - ), - diagnosticsOptOut = diagnosticsOptOutState.value, - normalizationJson = json.encodeToString( - NormalizationPrefs.serializer(), - normalizationState.value, - ), - backgroundDelivery = backgroundDeliveryState.value, - cacheOwnerUserId = cacheOwnerState.value, - ) - - companion object { - const val DEFAULT_BASE_URL: String = "http://localhost:8080" - - // Generous on purpose: hydration is one local row read and one - // Keystore decrypt, normally milliseconds. This only bounds "never". - const val HYDRATION_DEADLINE_MS: Long = 10_000 - private const val ROW_ID = 0 - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt index 57d4d881..dec1e63d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ServerProbe.kt @@ -35,21 +35,30 @@ import kotlin.coroutines.resumeWithException * Plain http still passes through [com.fabledsword.minstrel.api.CleartextGuardInterceptor] * on [client], so the fallback can only succeed on a home-network address. */ -class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Long) { - +class ServerProbe internal constructor( + client: OkHttpClient, + callTimeoutMillis: Long, +) { // Each attempt is short: a probe that stalls holds the sign-in screen. - @Inject constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS) + @Inject + constructor(client: OkHttpClient) : this(client, CALL_TIMEOUT_MILLIS) - private val client: OkHttpClient = client.newBuilder() - .connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) - .callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) - .build() + private val client: OkHttpClient = + client + .newBuilder() + .connectTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) + .callTimeout(callTimeoutMillis, TimeUnit.MILLISECONDS) + .build() sealed interface Result { /** Minstrel answered at [baseUrl], which includes its scheme. */ - data class Found(val baseUrl: String) : Result + data class Found( + val baseUrl: String, + ) : Result - data class Failed(val message: String) : Result + data class Failed( + val message: String, + ) : Result } suspend fun find(input: String): Result { @@ -100,21 +109,28 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: data object Minstrel : Outcome /** Nothing answered: the next scheme may be tried. */ - data class Unreachable(val publicCleartext: Boolean = false) : Outcome + data class Unreachable( + val publicCleartext: Boolean = false, + ) : Outcome /** Something answered, or TLS failed to verify: stop here. */ - data class Stop(val message: String) : Outcome + data class Stop( + val message: String, + ) : Outcome } private suspend fun attempt(baseUrl: String): Outcome { - val url = "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull() - ?: return Outcome.Stop("That doesn't look like a server address.") - val request = Request.Builder() - .url(url) - // Lets CleartextGuardInterceptor treat the probe as a Minstrel - // server request, as it treats sign-in. - .tag(MinstrelServerRequest::class.java, MinstrelServerRequest) - .build() + val url = + "$baseUrl$SETUP_STATUS_PATH".toHttpUrlOrNull() + ?: return Outcome.Stop("That doesn't look like a server address.") + val request = + Request + .Builder() + .url(url) + // Lets CleartextGuardInterceptor treat the probe as a Minstrel + // server request, as it treats sign-in. + .tag(MinstrelServerRequest::class.java, MinstrelServerRequest) + .build() return try { client.newCall(request).await().use { response -> if (isMinstrel(response)) { @@ -123,9 +139,13 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: Outcome.Stop("A server answered at $baseUrl, but it isn't Minstrel.") } } - } catch (@Suppress("SwallowedException") e: CleartextToPublicHostException) { + } catch ( + @Suppress("SwallowedException") e: CleartextToPublicHostException, + ) { Outcome.Unreachable(publicCleartext = true) - } catch (@Suppress("SwallowedException") e: UnknownHostException) { + } catch ( + @Suppress("SwallowedException") e: UnknownHostException, + ) { Outcome.Stop("Couldn't find a server named ${url.host}.") } catch (e: IOException) { if (isCertificateFailure(e)) { @@ -161,11 +181,17 @@ class ServerProbe internal constructor(client: OkHttpClient, callTimeoutMillis: continuation.invokeOnCancellation { cancel() } enqueue( object : Callback { - override fun onResponse(call: Call, response: Response) { + override fun onResponse( + call: Call, + response: Response, + ) { if (continuation.isActive) continuation.resume(response) else response.close() } - override fun onFailure(call: Call, e: IOException) { + override fun onFailure( + call: Call, + e: IOException, + ) { if (continuation.isActive) continuation.resumeWithException(e) } }, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/SessionVault.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/SessionVault.kt index 25ab5c44..b5a2d610 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/SessionVault.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/SessionVault.kt @@ -54,7 +54,10 @@ internal object SealedBox { // under the same key will not open as a session cookie. private val AAD = "minstrel-session-cookie-v1".toByteArray(Charsets.UTF_8) - fun seal(key: SecretKey, plaintext: String): String { + fun seal( + key: SecretKey, + plaintext: String, + ): String { val cipher = Cipher.getInstance(TRANSFORMATION) // No IV passed: the provider generates a fresh random one. Keystore // keys refuse a caller-chosen IV for encryption by default. @@ -64,7 +67,10 @@ internal object SealedBox { return Base64.getEncoder().encodeToString(sealed) } - fun open(key: SecretKey, sealed: String): String { + fun open( + key: SecretKey, + sealed: String, + ): String { val bytes = Base64.getDecoder().decode(sealed) require(bytes.size > IV_BYTES) { "sealed value too short" } val cipher = Cipher.getInstance(TRANSFORMATION) @@ -85,58 +91,60 @@ internal object SealedBox { * credential that no longer verifies. */ @Singleton -class KeystoreSessionVault @Inject constructor( - @ApplicationContext context: Context, -) : SessionVault { - private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) +class KeystoreSessionVault + @Inject + constructor( + @ApplicationContext context: Context, + ) : SessionVault { + private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) - override fun read(): String? { - val sealed = prefs.getString(KEY_COOKIE, null) ?: return null - return runCatching { SealedBox.open(key(), sealed) } - .onFailure { - Timber.w(it, "session vault: stored cookie would not decrypt; discarding it") - prefs.edit().remove(KEY_COOKIE).commit() - } - .getOrNull() - } - - override fun write(value: String?): Boolean = runCatching { - val editor = prefs.edit() - if (value == null) { - editor.remove(KEY_COOKIE) - } else { - editor.putString(KEY_COOKIE, SealedBox.seal(key(), value)) + override fun read(): String? { + val sealed = prefs.getString(KEY_COOKIE, null) ?: return null + return runCatching { SealedBox.open(key(), sealed) } + .onFailure { + Timber.w(it, "session vault: stored cookie would not decrypt; discarding it") + prefs.edit().remove(KEY_COOKIE).commit() + }.getOrNull() } - editor.commit() - }.onFailure { - Timber.w(it, "session vault: Keystore unavailable; cookie not stored in the vault") - }.getOrDefault(false) - private fun key(): SecretKey { - val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } - (keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it } - val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE) - generator.init( - KeyGenParameterSpec.Builder( - KEY_ALIAS, - KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, + override fun write(value: String?): Boolean = + runCatching { + val editor = prefs.edit() + if (value == null) { + editor.remove(KEY_COOKIE) + } else { + editor.putString(KEY_COOKIE, SealedBox.seal(key(), value)) + } + editor.commit() + }.onFailure { + Timber.w(it, "session vault: Keystore unavailable; cookie not stored in the vault") + }.getOrDefault(false) + + private fun key(): SecretKey { + val keyStore = KeyStore.getInstance(ANDROID_KEYSTORE).apply { load(null) } + (keyStore.getKey(KEY_ALIAS, null) as? SecretKey)?.let { return it } + val generator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, ANDROID_KEYSTORE) + generator.init( + KeyGenParameterSpec + .Builder( + KEY_ALIAS, + KeyProperties.PURPOSE_ENCRYPT or KeyProperties.PURPOSE_DECRYPT, + ).setBlockModes(KeyProperties.BLOCK_MODE_GCM) + .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) + .setKeySize(KEY_BITS) + .build(), ) - .setBlockModes(KeyProperties.BLOCK_MODE_GCM) - .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_NONE) - .setKeySize(KEY_BITS) - .build(), - ) - return generator.generateKey() - } + return generator.generateKey() + } - private companion object { - const val ANDROID_KEYSTORE = "AndroidKeyStore" - const val KEY_ALIAS = "minstrel_session_cookie" - const val KEY_BITS = 256 - const val PREFS_NAME = "session_vault" - const val KEY_COOKIE = "sealed_cookie" + private companion object { + const val ANDROID_KEYSTORE = "AndroidKeyStore" + const val KEY_ALIAS = "minstrel_session_cookie" + const val KEY_BITS = 256 + const val PREFS_NAME = "session_vault" + const val KEY_COOKIE = "sealed_cookie" + } } -} @Module @InstallIn(SingletonComponent::class) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/AuthGateViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/AuthGateViewModel.kt index b8b86a1f..81d3c9d2 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/AuthGateViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/AuthGateViewModel.kt @@ -30,34 +30,36 @@ import javax.inject.Inject * and then exactly one resolved value. */ @HiltViewModel -class AuthGateViewModel @Inject constructor( - private val dao: AuthSessionDao, - private val authStore: AuthStore, -) : ViewModel() { +class AuthGateViewModel + @Inject + constructor( + private val dao: AuthSessionDao, + private val authStore: AuthStore, + ) : ViewModel() { + private val internal = MutableStateFlow(null) + val startDestination: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(null) - val startDestination: StateFlow = internal.asStateFlow() + /** + * True when the server has ended the session while the app was in use; + * the root NavHost answers by opening the sign-in screen, then calls + * [consumeSessionRejected]. + */ + val sessionRejected: StateFlow = authStore.sessionRejected - /** - * True when the server has ended the session while the app was in use; - * the root NavHost answers by opening the sign-in screen, then calls - * [consumeSessionRejected]. - */ - val sessionRejected: StateFlow = authStore.sessionRejected + fun consumeSessionRejected() = authStore.consumeSessionRejected() - fun consumeSessionRejected() = authStore.consumeSessionRejected() - - init { - viewModelScope.launch { - authStore.awaitSessionHydrated() - val signedIn = !authStore.sessionCookie.value.isNullOrEmpty() - val row = dao.get() - internal.value = when { - row == null -> ServerUrl - row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl - !signedIn -> Login - else -> Home + init { + viewModelScope.launch { + authStore.awaitSessionHydrated() + val signedIn = !authStore.sessionCookie.value.isNullOrEmpty() + val row = dao.get() + internal.value = + when { + row == null -> ServerUrl + row.baseUrl == AuthStore.DEFAULT_BASE_URL && !signedIn -> ServerUrl + !signedIn -> Login + else -> Home + } } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/LoginScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/LoginScreen.kt index 3f3770a2..bf6ec6db 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/LoginScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/LoginScreen.kt @@ -71,9 +71,10 @@ private fun LoginForm( onChangeServerUrl: () -> Unit, ) { Column( - modifier = Modifier - .fillMaxSize() - .padding(24.dp), + modifier = + Modifier + .fillMaxSize() + .padding(24.dp), verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically), horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -89,10 +90,11 @@ private fun LoginForm( label = { Text("Username") }, singleLine = true, enabled = !state.isSubmitting, - keyboardOptions = KeyboardOptions( - keyboardType = KeyboardType.Email, - imeAction = ImeAction.Next, - ), + keyboardOptions = + KeyboardOptions( + keyboardType = KeyboardType.Email, + imeAction = ImeAction.Next, + ), ) OutlinedTextField( value = state.password, @@ -102,10 +104,11 @@ private fun LoginForm( singleLine = true, enabled = !state.isSubmitting, visualTransformation = PasswordVisualTransformation(), - keyboardOptions = KeyboardOptions( - keyboardType = KeyboardType.Password, - imeAction = ImeAction.Done, - ), + keyboardOptions = + KeyboardOptions( + keyboardType = KeyboardType.Password, + imeAction = ImeAction.Done, + ), keyboardActions = KeyboardActions(onDone = { onSubmit() }), ) if (state.errorMessage != null) { @@ -126,12 +129,16 @@ private fun LoginForm( } @Composable -private fun SubmitButton(state: LoginFormState, onSubmit: () -> Unit) { +private fun SubmitButton( + state: LoginFormState, + onSubmit: () -> Unit, +) { Button( onClick = onSubmit, - enabled = !state.isSubmitting && - state.username.isNotBlank() && - state.password.isNotBlank(), + enabled = + !state.isSubmitting && + state.username.isNotBlank() && + state.password.isNotBlank(), modifier = Modifier.fillMaxWidth(), ) { if (state.isSubmitting) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/LoginViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/LoginViewModel.kt index d7a01786..ee055d55 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/LoginViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/LoginViewModel.kt @@ -21,44 +21,45 @@ data class LoginFormState( ) @HiltViewModel -class LoginViewModel @Inject constructor( - private val auth: AuthController, -) : ViewModel() { +class LoginViewModel + @Inject + constructor( + private val auth: AuthController, + ) : ViewModel() { + private val internal = MutableStateFlow(LoginFormState()) + val state: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(LoginFormState()) - val state: StateFlow = internal.asStateFlow() + fun setUsername(value: String) { + internal.update { it.copy(username = value, errorMessage = null) } + } - fun setUsername(value: String) { - internal.update { it.copy(username = value, errorMessage = null) } - } + fun setPassword(value: String) { + internal.update { it.copy(password = value, errorMessage = null) } + } - fun setPassword(value: String) { - internal.update { it.copy(password = value, errorMessage = null) } - } - - fun submit() { - val s = internal.value - if (s.username.isBlank() || s.password.isBlank() || s.isSubmitting) return - viewModelScope.launch { - internal.update { it.copy(isSubmitting = true, errorMessage = null) } - try { - auth.signIn(s.username, s.password) - internal.update { it.copy(isSubmitting = false, signedIn = true) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - isSubmitting = false, - errorMessage = ErrorCopy.fromThrowable(e), - ) + fun submit() { + val s = internal.value + if (s.username.isBlank() || s.password.isBlank() || s.isSubmitting) return + viewModelScope.launch { + internal.update { it.copy(isSubmitting = true, errorMessage = null) } + try { + auth.signIn(s.username, s.password) + internal.update { it.copy(isSubmitting = false, signedIn = true) } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy( + isSubmitting = false, + errorMessage = ErrorCopy.fromThrowable(e), + ) + } } } } - } - /** Called after the navigation away from /login completes. */ - fun consumeSignedIn() { - internal.update { it.copy(signedIn = false) } + /** Called after the navigation away from /login completes. */ + fun consumeSignedIn() { + internal.update { it.copy(signedIn = false) } + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt index 8b78a134..df078459 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/auth/ui/ServerUrlScreen.kt @@ -51,64 +51,68 @@ data class ServerUrlFormState( ) @HiltViewModel -class ServerUrlViewModel @Inject constructor( - private val authStore: AuthStore, - private val probe: ServerProbe, -) : ViewModel() { +class ServerUrlViewModel + @Inject + constructor( + private val authStore: AuthStore, + private val probe: ServerProbe, + ) : ViewModel() { + private val internal = + MutableStateFlow( + // Pre-fill ONLY if the user has previously saved a real URL — + // the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is + // an internal HTTP-client fallback, not something a user + // typed. Leaving the field empty lets the OutlinedTextField's + // placeholder ("minstrel.example.com") show through so the user + // can just type without first having to clear. + ServerUrlFormState( + url = + authStore.baseUrl.value + .takeIf { it != AuthStore.DEFAULT_BASE_URL } + .orEmpty(), + ), + ) + val state: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow( - // Pre-fill ONLY if the user has previously saved a real URL — - // the DEFAULT_BASE_URL placeholder (`http://localhost:8080`) is - // an internal HTTP-client fallback, not something a user - // typed. Leaving the field empty lets the OutlinedTextField's - // placeholder ("minstrel.example.com") show through so the user - // can just type without first having to clear. - ServerUrlFormState( - url = authStore.baseUrl.value - .takeIf { it != AuthStore.DEFAULT_BASE_URL } - .orEmpty(), - ), - ) - val state: StateFlow = internal.asStateFlow() + private var probeJob: Job? = null - private var probeJob: Job? = null + fun setUrl(value: String) { + internal.update { it.copy(url = value, errorMessage = null) } + } - fun setUrl(value: String) { - internal.update { it.copy(url = value, errorMessage = null) } - } - - /** - * Looks for Minstrel at the typed address ([ServerProbe]) and saves the - * full URL that answered, scheme included, so every caller of - * [AuthStore.baseUrl] still receives a complete URL. - */ - fun submit() { - if (internal.value.probing) return - val typed = internal.value.url - probeJob = viewModelScope.launch { - internal.update { it.copy(probing = true, errorMessage = null) } - when (val result = probe.find(typed)) { - is ServerProbe.Result.Found -> { - authStore.setBaseUrl(result.baseUrl) - internal.update { it.copy(probing = false, saved = true) } + /** + * Looks for Minstrel at the typed address ([ServerProbe]) and saves the + * full URL that answered, scheme included, so every caller of + * [AuthStore.baseUrl] still receives a complete URL. + */ + fun submit() { + if (internal.value.probing) return + val typed = internal.value.url + probeJob = + viewModelScope.launch { + internal.update { it.copy(probing = true, errorMessage = null) } + when (val result = probe.find(typed)) { + is ServerProbe.Result.Found -> { + authStore.setBaseUrl(result.baseUrl) + internal.update { it.copy(probing = false, saved = true) } + } + is ServerProbe.Result.Failed -> + internal.update { it.copy(probing = false, errorMessage = result.message) } + } } - is ServerProbe.Result.Failed -> - internal.update { it.copy(probing = false, errorMessage = result.message) } - } + } + + fun cancelProbe() { + probeJob?.cancel() + probeJob = null + internal.update { it.copy(probing = false) } + } + + fun consumeSaved() { + internal.update { it.copy(saved = false) } } } - fun cancelProbe() { - probeJob?.cancel() - probeJob = null - internal.update { it.copy(probing = false) } - } - - fun consumeSaved() { - internal.update { it.copy(saved = false) } - } -} - // ─── Screen ─────────────────────────────────────────────────────────── @Composable @@ -149,9 +153,10 @@ private fun ServerUrlForm( onCancel: () -> Unit, ) { Column( - modifier = Modifier - .fillMaxSize() - .padding(24.dp), + modifier = + Modifier + .fillMaxSize() + .padding(24.dp), verticalArrangement = Arrangement.spacedBy(16.dp, Alignment.CenterVertically), horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -176,10 +181,11 @@ private fun ServerUrlForm( }, singleLine = true, enabled = !state.probing, - keyboardOptions = KeyboardOptions( - keyboardType = KeyboardType.Uri, - imeAction = ImeAction.Done, - ), + keyboardOptions = + KeyboardOptions( + keyboardType = KeyboardType.Uri, + imeAction = ImeAction.Done, + ), keyboardActions = KeyboardActions(onDone = { onSubmit() }), ) if (state.errorMessage != null) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/CacheIndexer.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/CacheIndexer.kt index e7ace5ed..ee7fe070 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/CacheIndexer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/CacheIndexer.kt @@ -31,34 +31,36 @@ import javax.inject.Singleton * the construct-the-singleton trick in `MinstrelApplication`. */ @Singleton -class CacheIndexer @Inject constructor( - playerController: PlayerController, - private val dao: AudioCacheIndexDao, - @ApplicationScope private val scope: CoroutineScope, -) { - init { - scope.launch { - playerController.uiState - .map { it.currentTrack } - .distinctUntilChanged { a, b -> a?.id == b?.id } - .collect { track -> if (track != null) record(track) } +class CacheIndexer + @Inject + constructor( + playerController: PlayerController, + private val dao: AudioCacheIndexDao, + @ApplicationScope private val scope: CoroutineScope, + ) { + init { + scope.launch { + playerController.uiState + .map { it.currentTrack } + .distinctUntilChanged { a, b -> a?.id == b?.id } + .collect { track -> if (track != null) record(track) } + } } - } - private suspend fun record(track: TrackRef) { - val now = Clock.System.now() - if (dao.get(track.id) != null) { - dao.touchLastPlayed(track.id, now) - } else { - dao.upsert( - AudioCacheIndexEntity( - trackId = track.id, - path = track.streamUrl, - sizeBytes = 0, - lastPlayedAt = now, - source = CacheSource.INCIDENTAL, - ), - ) + private suspend fun record(track: TrackRef) { + val now = Clock.System.now() + if (dao.get(track.id) != null) { + dao.touchLastPlayed(track.id, now) + } else { + dao.upsert( + AudioCacheIndexEntity( + trackId = track.id, + path = track.streamUrl, + sizeBytes = 0, + lastPlayedAt = now, + source = CacheSource.INCIDENTAL, + ), + ) + } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/CachedTrackIds.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/CachedTrackIds.kt index d5940efc..d8a8dccf 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/CachedTrackIds.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/CachedTrackIds.kt @@ -33,28 +33,29 @@ import javax.inject.Singleton * library is opened offline with no active playback. */ @Singleton -class CachedTrackIds @Inject constructor( - playerController: PlayerController, - private val playerFactory: PlayerFactory, - @ApplicationScope scope: CoroutineScope, -) { - private val refresh = MutableStateFlow(0L) +class CachedTrackIds + @Inject + constructor( + playerController: PlayerController, + private val playerFactory: PlayerFactory, + @ApplicationScope scope: CoroutineScope, + ) { + private val refresh = MutableStateFlow(0L) - val ids: StateFlow> = - refresh - .map { readKeys() } - .flowOn(Dispatchers.IO) - .stateIn(scope, SharingStarted.Eagerly, emptySet()) + val ids: StateFlow> = + refresh + .map { readKeys() } + .flowOn(Dispatchers.IO) + .stateIn(scope, SharingStarted.Eagerly, emptySet()) - init { - scope.launch { - playerController.uiState - .map { it.currentTrack?.id } - .distinctUntilChanged() - .collect { refresh.value += 1 } + init { + scope.launch { + playerController.uiState + .map { it.currentTrack?.id } + .distinctUntilChanged() + .collect { refresh.value += 1 } + } } - } - private fun readKeys(): Set = - runCatching { playerFactory.simpleCache.keys.toSet() }.getOrDefault(emptySet()) -} + private fun readKeys(): Set = runCatching { playerFactory.simpleCache.keys.toSet() }.getOrDefault(emptySet()) + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/ShuffleSource.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/ShuffleSource.kt index 1f742912..b2eeb878 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/ShuffleSource.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/ShuffleSource.kt @@ -28,42 +28,44 @@ private const val POOL_LIMIT = 100 * plays the pool from the cache. */ @Singleton -class ShuffleSource @Inject constructor( - private val cacheIndexDao: AudioCacheIndexDao, - private val trackDao: CachedTrackDao, - private val likes: LikesRepository, - private val playerFactory: PlayerFactory, -) { - /** Cached tracks, most-recently-played first (liked included). */ - suspend fun recentlyPlayed(limit: Int = POOL_LIMIT): List = - materialize(residentIdsByRecency()).take(limit) +class ShuffleSource + @Inject + constructor( + private val cacheIndexDao: AudioCacheIndexDao, + private val trackDao: CachedTrackDao, + private val likes: LikesRepository, + private val playerFactory: PlayerFactory, + ) { + /** Cached tracks, most-recently-played first (liked included). */ + suspend fun recentlyPlayed(limit: Int = POOL_LIMIT): List = materialize(residentIdsByRecency()).take(limit) - /** Cached tracks that are in the user's liked set, recency-ordered. */ - suspend fun liked(limit: Int = POOL_LIMIT): List { - val likedSet = likes.likedTrackIds() - val ids = residentIdsByRecency().filter { it in likedSet } - return materialize(ids).take(limit) - } + /** Cached tracks that are in the user's liked set, recency-ordered. */ + suspend fun liked(limit: Int = POOL_LIMIT): List { + val likedSet = likes.likedTrackIds() + val ids = residentIdsByRecency().filter { it in likedSet } + return materialize(ids).take(limit) + } - /** Recency-ordered ids whose audio is actually resident in the cache. */ - private suspend fun residentIdsByRecency(): List { - val resident = runCatching { playerFactory.simpleCache.keys.toSet() } - .getOrDefault(emptySet()) - return cacheIndexDao.trackIdsByRecency().filter { it in resident } - } + /** Recency-ordered ids whose audio is actually resident in the cache. */ + private suspend fun residentIdsByRecency(): List { + val resident = + runCatching { playerFactory.simpleCache.keys.toSet() } + .getOrDefault(emptySet()) + return cacheIndexDao.trackIdsByRecency().filter { it in resident } + } - /** Materialize ordered ids into TrackRefs from cached metadata, preserving order. */ - private suspend fun materialize(orderedIds: List): List { - if (orderedIds.isEmpty()) return emptyList() - val byId = trackDao.getByIds(orderedIds).associateBy { it.id } - return orderedIds.mapNotNull { id -> - // Clear the server's missing mark. Every id reaching here - // came through residentIdsByRecency, which already proved the - // AUDIO is in the local cache — so these play regardless of what - // the server has lost, and the queue filter in PlayerController - // would otherwise throw away tracks that work perfectly. Missing - // means "cannot stream", not "cannot play". - byId[id]?.toDomain()?.copy(unavailable = false) + /** Materialize ordered ids into TrackRefs from cached metadata, preserving order. */ + private suspend fun materialize(orderedIds: List): List { + if (orderedIds.isEmpty()) return emptyList() + val byId = trackDao.getByIds(orderedIds).associateBy { it.id } + return orderedIds.mapNotNull { id -> + // Clear the server's missing mark. Every id reaching here + // came through residentIdsByRecency, which already proved the + // AUDIO is in the local cache — so these play regardless of what + // the server has lost, and the queue filter in PlayerController + // would otherwise throw away tracks that work perfectly. Missing + // means "cannot stream", not "cannot play". + byId[id]?.toDomain()?.copy(unavailable = false) + } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt index b7bd0bdd..9be4f731 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountCache.kt @@ -34,12 +34,17 @@ internal enum class OwnerStep { 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 -} +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 @@ -62,48 +67,53 @@ internal fun ownerStep(loaded: Boolean, signedInUserId: String?, ownerUserId: St * 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, - @ApplicationScope scope: CoroutineScope, -) { - private val ownedState = MutableStateFlow(false) +class AccountCache + @Inject + constructor( + private val authStore: AuthStore, + authController: AuthController, + private val tables: AccountTables, + private val player: Lazy, + @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 = ownedState.asStateFlow() + /** True while the signed-in account is the one the cached data belongs to. */ + val ownedBySignedInUser: StateFlow = 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) + 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) } } - OwnerStep.OWNED -> ownedState.value = true + } + + 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() } } - - 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() - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt index 164ee0c8..197e2582 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/account/AccountTables.kt @@ -12,17 +12,21 @@ import javax.inject.Singleton * (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() +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() + } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/BucketLedger.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/BucketLedger.kt index ce8647c5..98de7bbc 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/BucketLedger.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/BucketLedger.kt @@ -27,10 +27,11 @@ class BucketLedger( private val lengthOf: (S) -> Long, lruOrder: Comparator, ) { - private val spans = mapOf( - CacheBucket.LIKED to TreeSet(lruOrder), - CacheBucket.RECENT to TreeSet(lruOrder), - ) + private val spans = + mapOf( + CacheBucket.LIKED to TreeSet(lruOrder), + CacheBucket.RECENT to TreeSet(lruOrder), + ) private val bytes = mutableMapOf(CacheBucket.LIKED to 0L, CacheBucket.RECENT to 0L) private val spansByKey = HashMap>() private val bucketByKey = HashMap() @@ -43,16 +44,16 @@ class BucketLedger( /** Cap on Recently played bytes; 0 means unlimited. */ var recentCapBytes: Long = 0L - fun bucketOf(key: String): CacheBucket = - if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT + fun bucketOf(key: String): CacheBucket = if (key in liked) CacheBucket.LIKED else CacheBucket.RECENT fun bytesIn(bucket: CacheBucket): Long = bytes.getValue(bucket) /** Bytes the Liked budget can still take; [Long.MAX_VALUE] when unlimited. */ - fun likedRoomBytes(): Long = when { - likedCapBytes <= 0L -> Long.MAX_VALUE - else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L) - } + fun likedRoomBytes(): Long = + when { + likedCapBytes <= 0L -> Long.MAX_VALUE + else -> (likedCapBytes - bytesIn(CacheBucket.LIKED)).coerceAtLeast(0L) + } fun add(span: S) { val key = keyOf(span) @@ -105,7 +106,10 @@ class BucketLedger( * [pendingBytes] describe a write about to start, so room is made for it * in its own bucket first. Recently played is trimmed before Liked. */ - fun nextEviction(pendingKey: String? = null, pendingBytes: Long = 0L): S? { + fun nextEviction( + pendingKey: String? = null, + pendingBytes: Long = 0L, + ): S? { if (!armed) return null val pendingBucket = pendingKey?.let(::bucketOf) return listOf(CacheBucket.RECENT, CacheBucket.LIKED).firstNotNullOfOrNull { bucket -> @@ -114,7 +118,10 @@ class BucketLedger( } } - private fun oldestIfOver(bucket: CacheBucket, incoming: Long): S? { + private fun oldestIfOver( + bucket: CacheBucket, + incoming: Long, + ): S? { val cap = if (bucket == CacheBucket.LIKED) likedCapBytes else recentCapBytes val over = cap > 0L && bytesIn(bucket) + incoming > cap return if (over) spans.getValue(bucket).firstOrNull() else null diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/CacheBudgetSync.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/CacheBudgetSync.kt index 132d0969..e4bf0877 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/CacheBudgetSync.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/CacheBudgetSync.kt @@ -23,18 +23,20 @@ import javax.inject.Singleton * `MinstrelApplication`. */ @Singleton -class CacheBudgetSync @Inject constructor( - likes: LikesRepository, - authStore: AuthStore, - evictor: TwoBucketCacheEvictor, - @ApplicationScope scope: CoroutineScope, -) { - init { - scope.launch(Dispatchers.IO) { - combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair) - .collect { (ids, settings) -> - evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes) - } +class CacheBudgetSync + @Inject + constructor( + likes: LikesRepository, + authStore: AuthStore, + evictor: TwoBucketCacheEvictor, + @ApplicationScope scope: CoroutineScope, + ) { + init { + scope.launch(Dispatchers.IO) { + combine(likes.observeSignedInLikedTrackIds(), authStore.cacheSettings, ::Pair) + .collect { (ids, settings) -> + evictor.update(ids, settings.likedCapBytes, settings.rollingCapBytes) + } + } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/TwoBucketCacheEvictor.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/TwoBucketCacheEvictor.kt index 02036c29..d4a312c2 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/TwoBucketCacheEvictor.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/audiocache/TwoBucketCacheEvictor.kt @@ -11,7 +11,11 @@ import javax.inject.Singleton * Bytes held against each audio-cache budget, and how much more the Liked * budget can take ([Long.MAX_VALUE] when it is unlimited). */ -data class CacheUsage(val likedBytes: Long, val recentBytes: Long, val likedRoomBytes: Long) +data class CacheUsage( + val likedBytes: Long, + val recentBytes: Long, + val likedRoomBytes: Long, +) /** * The audio cache's eviction policy: two budgets, Liked songs and Recently @@ -29,84 +33,111 @@ data class CacheUsage(val likedBytes: Long, val recentBytes: Long, val likedRoom * deadlock. */ @Singleton -class TwoBucketCacheEvictor @Inject constructor() : CacheEvictor { - private val ledger = BucketLedger( - keyOf = { it.key }, - lengthOf = { it.length }, - lruOrder = compareBy { it.lastTouchTimestamp }.then(naturalOrder()), - ) +class TwoBucketCacheEvictor + @Inject + constructor() : CacheEvictor { + private val ledger = + BucketLedger( + keyOf = { it.key }, + lengthOf = { it.length }, + lruOrder = compareBy { it.lastTouchTimestamp }.then(naturalOrder()), + ) - @Volatile private var cache: Cache? = null + @Volatile private var cache: Cache? = null - /** Called once the SimpleCache exists, so updates can trim it. */ - fun attach(cache: Cache) { - this.cache = cache - } - - /** Apply a new liked set and caps, then trim whatever no longer fits. */ - fun update(likedIds: Set, likedCapBytes: Long, recentCapBytes: Long) { - val c = cache - val apply = { - ledger.likedCapBytes = likedCapBytes - ledger.recentCapBytes = recentCapBytes - ledger.setLiked(likedIds) + /** Called once the SimpleCache exists, so updates can trim it. */ + fun attach(cache: Cache) { + this.cache = cache } - if (c == null) { - synchronized(ledger) { apply() } - } else { - synchronized(c) { - synchronized(ledger) { - apply() - evict(c, pendingKey = null, pendingBytes = 0L) + + /** Apply a new liked set and caps, then trim whatever no longer fits. */ + fun update( + likedIds: Set, + likedCapBytes: Long, + recentCapBytes: Long, + ) { + val c = cache + val apply = { + ledger.likedCapBytes = likedCapBytes + ledger.recentCapBytes = recentCapBytes + ledger.setLiked(likedIds) + } + if (c == null) { + synchronized(ledger) { apply() } + } else { + synchronized(c) { + synchronized(ledger) { + apply() + evict(c, pendingKey = null, pendingBytes = 0L) + } } } } - } - fun usage(): CacheUsage = synchronized(ledger) { - CacheUsage( - likedBytes = ledger.bytesIn(CacheBucket.LIKED), - recentBytes = ledger.bytesIn(CacheBucket.RECENT), - likedRoomBytes = ledger.likedRoomBytes(), - ) - } + fun usage(): CacheUsage = + synchronized(ledger) { + CacheUsage( + likedBytes = ledger.bytesIn(CacheBucket.LIKED), + recentBytes = ledger.bytesIn(CacheBucket.RECENT), + likedRoomBytes = ledger.likedRoomBytes(), + ) + } - override fun requiresCacheSpanTouches(): Boolean = true + override fun requiresCacheSpanTouches(): Boolean = true - override fun onCacheInitialized() = Unit + override fun onCacheInitialized() = Unit - override fun onStartFile(cache: Cache, key: String, position: Long, length: Long) { - synchronized(ledger) { - evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length) + override fun onStartFile( + cache: Cache, + key: String, + position: Long, + length: Long, + ) { + synchronized(ledger) { + evict(cache, key, if (length == C.LENGTH_UNSET.toLong()) 0L else length) + } + } + + override fun onSpanAdded( + cache: Cache, + span: CacheSpan, + ) { + synchronized(ledger) { + ledger.add(span) + evict(cache, pendingKey = null, pendingBytes = 0L) + } + } + + override fun onSpanRemoved( + cache: Cache, + span: CacheSpan, + ) { + synchronized(ledger) { ledger.remove(span) } + } + + override fun onSpanTouched( + cache: Cache, + oldSpan: CacheSpan, + newSpan: CacheSpan, + ) { + synchronized(ledger) { + ledger.remove(oldSpan) + ledger.add(newSpan) + evict(cache, pendingKey = null, pendingBytes = 0L) + } + } + + private fun evict( + cache: Cache, + pendingKey: String?, + pendingBytes: Long, + ) { + while (true) { + val span = ledger.nextEviction(pendingKey, pendingBytes) ?: return + cache.removeSpan(span) + // removeSpan reports back through onSpanRemoved; removing here as + // well guarantees the loop advances even if it did not. + ledger.remove(span) + } } } - - override fun onSpanAdded(cache: Cache, span: CacheSpan) { - synchronized(ledger) { - ledger.add(span) - evict(cache, pendingKey = null, pendingBytes = 0L) - } - } - - override fun onSpanRemoved(cache: Cache, span: CacheSpan) { - synchronized(ledger) { ledger.remove(span) } - } - - override fun onSpanTouched(cache: Cache, oldSpan: CacheSpan, newSpan: CacheSpan) { - synchronized(ledger) { - ledger.remove(oldSpan) - ledger.add(newSpan) - evict(cache, pendingKey = null, pendingBytes = 0L) - } - } - - private fun evict(cache: Cache, pendingKey: String?, pendingBytes: Long) { - while (true) { - val span = ledger.nextEviction(pendingKey, pendingBytes) ?: return - cache.removeSpan(span) - // removeSpan reports back through onSpanRemoved; removing here as - // well guarantees the loop advances even if it did not. - ledger.remove(span) - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt index c11d1c14..d6252ea3 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/AppDatabase.kt @@ -15,9 +15,9 @@ import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao -import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao +import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao @@ -32,9 +32,9 @@ import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity import com.fabledsword.minstrel.cache.db.entities.CachedNotificationSettingsEntity import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistEntity -import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity import com.fabledsword.minstrel.cache.db.entities.CachedPlaylistTrackEntity import com.fabledsword.minstrel.cache.db.entities.CachedQuarantineEntity +import com.fabledsword.minstrel.cache.db.entities.CachedResumeStateEntity import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity import com.fabledsword.minstrel.cache.db.entities.DiagnosticEventEntity import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity @@ -101,104 +101,126 @@ import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity @TypeConverters(MinstrelTypeConverters::class) abstract class AppDatabase : RoomDatabase() { abstract fun syncMetadataDao(): SyncMetadataDao + abstract fun cachedArtistDao(): CachedArtistDao + abstract fun cachedAlbumDao(): CachedAlbumDao + abstract fun cachedTrackDao(): CachedTrackDao + abstract fun cachedLikeDao(): CachedLikeDao + abstract fun cachedPlaylistDao(): CachedPlaylistDao + abstract fun cachedPlaylistTrackDao(): CachedPlaylistTrackDao + abstract fun cachedQuarantineDao(): CachedQuarantineDao + abstract fun audioCacheIndexDao(): AudioCacheIndexDao + abstract fun cachedMutationDao(): CachedMutationDao + abstract fun cachedResumeStateDao(): CachedResumeStateDao + abstract fun cachedHomeIndexDao(): CachedHomeIndexDao + abstract fun cachedHistorySnapshotDao(): CachedHistorySnapshotDao + abstract fun authSessionDao(): AuthSessionDao + abstract fun diagnosticEventDao(): DiagnosticEventDao + abstract fun cachedNotificationDao(): CachedNotificationDao } /** v8 → v9: add the nullable normalization preference column. */ -val MIGRATION_8_9: Migration = object : Migration(8, 9) { - override fun migrate(db: SupportSQLiteDatabase) { - db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT") +val MIGRATION_8_9: Migration = + object : Migration(8, 9) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE auth_session ADD COLUMN normalizationJson TEXT") + } } -} /** * v9 → v10: the gain columns. Rows synced before this carry no gains, * and the sync is incremental, so it would never re-send them: the cursor goes * back to 0 and the next sync is a full one, upserting every row in place. */ -val MIGRATION_9_10: Migration = object : Migration(9, 10) { - override fun migrate(db: SupportSQLiteDatabase) { - db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL") - db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL") - db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL") - db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumPeak REAL") - db.execSQL("UPDATE sync_metadata SET cursor = 0") +val MIGRATION_9_10: Migration = + object : Migration(9, 10) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackGain REAL") + db.execSQL("ALTER TABLE cached_tracks ADD COLUMN trackPeak REAL") + db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumGain REAL") + db.execSQL("ALTER TABLE cached_albums ADD COLUMN albumPeak REAL") + db.execSQL("UPDATE sync_metadata SET cursor = 0") + } } -} /** * v10 → v11: the notifications inbox cache and its settings. The SQL * matches what Room generates for the two entities; Room checks it on open. */ -val MIGRATION_10_11: Migration = object : Migration(10, 11) { - override fun migrate(db: SupportSQLiteDatabase) { - db.execSQL( - "CREATE TABLE IF NOT EXISTS `cached_notifications` (" + - "`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " + - "`body` TEXT NOT NULL, `link` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " + - "`readAt` INTEGER, PRIMARY KEY(`id`))", - ) - db.execSQL( - "CREATE TABLE IF NOT EXISTS `cached_notification_settings` (" + - "`id` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))", - ) +val MIGRATION_10_11: Migration = + object : Migration(10, 11) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL( + "CREATE TABLE IF NOT EXISTS `cached_notifications` (" + + "`id` TEXT NOT NULL, `kind` TEXT NOT NULL, `title` TEXT NOT NULL, " + + "`body` TEXT NOT NULL, `link` TEXT NOT NULL, `createdAt` INTEGER NOT NULL, " + + "`readAt` INTEGER, PRIMARY KEY(`id`))", + ) + db.execSQL( + "CREATE TABLE IF NOT EXISTS `cached_notification_settings` (" + + "`id` INTEGER NOT NULL, `json` TEXT NOT NULL, PRIMARY KEY(`id`))", + ) + } } -} /** * v11 → v12: background delivery. The device choice defaults on, * as the entity's column default says; the high-water mark starts empty, so * the first catch-up sets it without announcing anything. */ -val MIGRATION_11_12: Migration = object : Migration(11, 12) { - override fun migrate(db: SupportSQLiteDatabase) { - db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1") - db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER") +val MIGRATION_11_12: Migration = + object : Migration(11, 12) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE auth_session ADD COLUMN backgroundDelivery INTEGER NOT NULL DEFAULT 1") + db.execSQL("ALTER TABLE auth_session ADD COLUMN notifiedUpTo INTEGER") + } } -} /** * v12 → v13: a playlist's cover albums and creation time. Both start empty; * Home refreshes the playlist list on open, which fills them. */ -val MIGRATION_12_13: Migration = object : Migration(12, 13) { - override fun migrate(db: SupportSQLiteDatabase) { - db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''") - db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''") +val MIGRATION_12_13: Migration = + object : Migration(12, 13) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE cached_playlists ADD COLUMN coverAlbumIds TEXT NOT NULL DEFAULT ''") + db.execSQL("ALTER TABLE cached_playlists ADD COLUMN createdAt TEXT NOT NULL DEFAULT ''") + } } -} /** * v13 → v14: a playlist's place on its Home shelf. Starts at 0 (unranked); * Home refreshes the playlist list on open, which fills it. */ -val MIGRATION_13_14: Migration = object : Migration(13, 14) { - override fun migrate(db: SupportSQLiteDatabase) { - db.execSQL("ALTER TABLE cached_playlists ADD COLUMN shelfRank INTEGER NOT NULL DEFAULT 0") +val MIGRATION_13_14: Migration = + object : Migration(13, 14) { + override fun migrate(db: SupportSQLiteDatabase) { + 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") +val MIGRATION_14_15: Migration = + object : Migration(14, 15) { + override fun migrate(db: SupportSQLiteDatabase) { + db.execSQL("ALTER TABLE auth_session ADD COLUMN cacheOwnerUserId TEXT") + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt index 506161f9..16216452 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/DatabaseModule.kt @@ -11,12 +11,12 @@ import com.fabledsword.minstrel.cache.db.dao.CachedHomeIndexDao import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.db.dao.CachedNotificationDao -import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao import com.fabledsword.minstrel.cache.db.dao.CachedQuarantineDao import com.fabledsword.minstrel.cache.db.dao.CachedResumeStateDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao +import com.fabledsword.minstrel.cache.db.dao.DiagnosticEventDao import com.fabledsword.minstrel.cache.db.dao.SyncMetadataDao import dagger.Module import dagger.Provides @@ -31,8 +31,11 @@ import javax.inject.Singleton object DatabaseModule { @Provides @Singleton - fun provideDatabase(@ApplicationContext context: Context): AppDatabase = - Room.databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME) + fun provideDatabase( + @ApplicationContext context: Context, + ): AppDatabase = + Room + .databaseBuilder(context, AppDatabase::class.java, DATABASE_NAME) // Explicit migrations from v8 onward; an older schema has no path // and rebuilds. The sync controller refills the cache from the // server on first launch, so a rebuild loses only the unsynced @@ -45,8 +48,7 @@ object DatabaseModule { MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, - ) - .fallbackToDestructiveMigration(dropAllTables = true) + ).fallbackToDestructiveMigration(dropAllTables = true) .build() // DAO @Provides — Hilt can't inject AppDatabase abstract accessors @@ -69,33 +71,27 @@ object DatabaseModule { @Provides @Singleton - fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao = - db.cachedResumeStateDao() + fun provideCachedResumeStateDao(db: AppDatabase): CachedResumeStateDao = db.cachedResumeStateDao() @Provides @Singleton - fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao = - db.cachedHomeIndexDao() + fun provideCachedHomeIndexDao(db: AppDatabase): CachedHomeIndexDao = db.cachedHomeIndexDao() @Provides @Singleton - fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao = - db.cachedHistorySnapshotDao() + fun provideCachedHistorySnapshotDao(db: AppDatabase): CachedHistorySnapshotDao = db.cachedHistorySnapshotDao() @Provides @Singleton - fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao = - db.cachedQuarantineDao() + fun provideCachedQuarantineDao(db: AppDatabase): CachedQuarantineDao = db.cachedQuarantineDao() @Provides @Singleton - fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao = - db.cachedPlaylistDao() + fun provideCachedPlaylistDao(db: AppDatabase): CachedPlaylistDao = db.cachedPlaylistDao() @Provides @Singleton - fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao = - db.cachedPlaylistTrackDao() + fun provideCachedPlaylistTrackDao(db: AppDatabase): CachedPlaylistTrackDao = db.cachedPlaylistTrackDao() @Provides @Singleton @@ -103,8 +99,7 @@ object DatabaseModule { @Provides @Singleton - fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao = - db.cachedMutationDao() + fun provideCachedMutationDao(db: AppDatabase): CachedMutationDao = db.cachedMutationDao() @Provides @Singleton @@ -112,18 +107,15 @@ object DatabaseModule { @Provides @Singleton - fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao = - db.audioCacheIndexDao() + fun provideAudioCacheIndexDao(db: AppDatabase): AudioCacheIndexDao = db.audioCacheIndexDao() @Provides @Singleton - fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao = - db.diagnosticEventDao() + fun provideDiagnosticEventDao(db: AppDatabase): DiagnosticEventDao = db.diagnosticEventDao() @Provides @Singleton - fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao = - db.cachedNotificationDao() + fun provideCachedNotificationDao(db: AppDatabase): CachedNotificationDao = db.cachedNotificationDao() private const val DATABASE_NAME = "minstrel.db" } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/TypeConverters.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/TypeConverters.kt index bff8e5a5..27bfc1de 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/TypeConverters.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/TypeConverters.kt @@ -21,11 +21,9 @@ enum class CacheSource { MANUAL, AUTO_LIKED, AUTO_PLAYLIST, AUTO_PREFETCH, INCID class MinstrelTypeConverters { @TypeConverter fun instantToLong(i: Instant?): Long? = i?.toEpochMilliseconds() - @TypeConverter fun longToInstant(l: Long?): Instant? = - l?.let { Instant.fromEpochMilliseconds(it) } + @TypeConverter fun longToInstant(l: Long?): Instant? = l?.let { Instant.fromEpochMilliseconds(it) } @TypeConverter fun sourceToName(s: CacheSource?): String? = s?.name - @TypeConverter fun nameToSource(n: String?): CacheSource? = - n?.let { CacheSource.valueOf(it) } + @TypeConverter fun nameToSource(n: String?): CacheSource? = n?.let { CacheSource.valueOf(it) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AudioCacheIndexDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AudioCacheIndexDao.kt index 543b5b6b..18ce3621 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AudioCacheIndexDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/AudioCacheIndexDao.kt @@ -37,7 +37,10 @@ interface AudioCacheIndexDao { @Query( "UPDATE audio_cache_index SET lastPlayedAt = :at WHERE trackId = :trackId", ) - suspend fun touchLastPlayed(trackId: String, at: kotlinx.datetime.Instant) + suspend fun touchLastPlayed( + trackId: String, + at: kotlinx.datetime.Instant, + ) @Query("DELETE FROM audio_cache_index WHERE trackId = :trackId") suspend fun deleteByTrackId(trackId: String) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedAlbumDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedAlbumDao.kt index da68891b..064429ed 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedAlbumDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedAlbumDao.kt @@ -30,10 +30,16 @@ interface CachedAlbumDao { "ORDER BY sortTitle COLLATE NOCASE ASC " + "LIMIT :limit", ) - suspend fun searchByTitle(q: String, limit: Int): List + suspend fun searchByTitle( + q: String, + limit: Int, + ): List @Query("SELECT id FROM cached_albums WHERE fetchedAt < :before LIMIT :limit") - suspend fun idsStaleBefore(before: Long, limit: Int): List + suspend fun idsStaleBefore( + before: Long, + limit: Int, + ): List @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertAll(rows: List) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedArtistDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedArtistDao.kt index d5127a8b..a8bd9015 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedArtistDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedArtistDao.kt @@ -24,10 +24,16 @@ interface CachedArtistDao { "ORDER BY sortName COLLATE NOCASE ASC " + "LIMIT :limit", ) - suspend fun searchByName(q: String, limit: Int): List + suspend fun searchByName( + q: String, + limit: Int, + ): List @Query("SELECT id FROM cached_artists WHERE fetchedAt < :before LIMIT :limit") - suspend fun idsStaleBefore(before: Long, limit: Int): List + suspend fun idsStaleBefore( + before: Long, + limit: Int, + ): List @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertAll(rows: List) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHomeIndexDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHomeIndexDao.kt index 35608279..7f2dd6ec 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHomeIndexDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedHomeIndexDao.kt @@ -44,7 +44,10 @@ interface CachedHomeIndexDao { * sequence rather than as a single content swap. */ @Transaction - suspend fun replaceSections(sections: List, rows: List) { + suspend fun replaceSections( + sections: List, + rows: List, + ) { deleteSections(sections) if (rows.isNotEmpty()) upsertAll(rows) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedLikeDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedLikeDao.kt index 5b3e2ed8..ca3087b9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedLikeDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedLikeDao.kt @@ -25,13 +25,20 @@ interface CachedLikeDao { "SELECT entityId FROM cached_likes " + "WHERE userId = :userId AND entityType = :entityType", ) - fun observeLikedIdsOfType(userId: String, entityType: String): Flow> + fun observeLikedIdsOfType( + userId: String, + entityType: String, + ): Flow> @Query( "SELECT EXISTS(SELECT 1 FROM cached_likes " + "WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId)", ) - fun observeIsLiked(userId: String, entityType: String, entityId: String): Flow + fun observeIsLiked( + userId: String, + entityType: String, + entityId: String, + ): Flow @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertAll(rows: List) @@ -40,7 +47,11 @@ interface CachedLikeDao { "DELETE FROM cached_likes " + "WHERE userId = :userId AND entityType = :entityType AND entityId = :entityId", ) - suspend fun delete(userId: String, entityType: String, entityId: String) + suspend fun delete( + userId: String, + entityType: String, + entityId: String, + ) @Query("DELETE FROM cached_likes WHERE userId = :userId") suspend fun clearForUser(userId: String) @@ -53,7 +64,10 @@ interface CachedLikeDao { * stale Liked tab entry forever. */ @Transaction - suspend fun replaceAllForUser(userId: String, rows: List) { + suspend fun replaceAllForUser( + userId: String, + rows: List, + ) { clearForUser(userId) upsertAll(rows) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedMutationDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedMutationDao.kt index a13329a6..065857ff 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedMutationDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedMutationDao.kt @@ -24,7 +24,10 @@ interface CachedMutationDao { "UPDATE cached_mutations SET attempts = attempts + 1, lastAttemptAt = :at " + "WHERE id = :id", ) - suspend fun recordAttempt(id: Long, at: Instant) + suspend fun recordAttempt( + id: Long, + at: Instant, + ) @Query("DELETE FROM cached_mutations WHERE id = :id") suspend fun delete(id: Long) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt index e13cc24d..ffe8e119 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedNotificationDao.kt @@ -35,7 +35,10 @@ interface CachedNotificationDao { } @Query("UPDATE cached_notifications SET readAt = :at WHERE id = :id AND readAt IS NULL") - suspend fun markRead(id: String, at: Instant) + suspend fun markRead( + id: String, + at: Instant, + ) @Query("UPDATE cached_notifications SET readAt = :at WHERE readAt IS NULL") suspend fun markAllRead(at: Instant) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt index 9ab89204..215edf9d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistDao.kt @@ -55,7 +55,10 @@ interface CachedPlaylistDao { suspend fun deleteAllOwned(userId: String) @Query("DELETE FROM cached_playlists WHERE userId = :userId AND id NOT IN (:keepIds)") - suspend fun deleteOwnedNotIn(userId: String, keepIds: List) + suspend fun deleteOwnedNotIn( + userId: String, + keepIds: List, + ) /** * Atomically reconciles the cache against the fresh list response. diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistTrackDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistTrackDao.kt index 23e4341b..11be7d19 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistTrackDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedPlaylistTrackDao.kt @@ -67,5 +67,8 @@ interface CachedPlaylistTrackDao { "DELETE FROM cached_playlist_tracks " + "WHERE playlistId = :playlistId AND trackId IN (:trackIds)", ) - suspend fun deleteTracksFromPlaylist(playlistId: String, trackIds: List) + suspend fun deleteTracksFromPlaylist( + playlistId: String, + trackIds: List, + ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedTrackDao.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedTrackDao.kt index acd69f89..4acfaaae 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedTrackDao.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/db/dao/CachedTrackDao.kt @@ -30,10 +30,16 @@ interface CachedTrackDao { "ORDER BY title COLLATE NOCASE ASC " + "LIMIT :limit", ) - suspend fun searchByTitle(q: String, limit: Int): List + suspend fun searchByTitle( + q: String, + limit: Int, + ): List @Query("SELECT id FROM cached_tracks WHERE fetchedAt < :before LIMIT :limit") - suspend fun idsStaleBefore(before: Long, limit: Int): List + suspend fun idsStaleBefore( + before: Long, + limit: Int, + ): List @Insert(onConflict = OnConflictStrategy.REPLACE) suspend fun upsertAll(rows: List) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt index c2ea1ac1..f48e5224 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt @@ -87,206 +87,238 @@ data class LikeTogglePayload( */ @Suppress("TooManyFunctions") // one enqueue per mutation kind, like the replayer's dispatchers @Singleton -class MutationQueue @Inject constructor( - private val dao: CachedMutationDao, - private val json: Json, -) { - // capacity=1 DROP_OLDEST so a burst of user enqueues (e.g. liking N - // tracks while offline) surfaces as one snackbar rather than queueing - // N. replay=0 because a hint observed at enqueue time isn't useful - // to a screen that mounts later. - private val _userEnqueueHints = MutableSharedFlow( - replay = 0, - extraBufferCapacity = 1, - onBufferOverflow = BufferOverflow.DROP_OLDEST, - ) +class MutationQueue + @Inject + constructor( + private val dao: CachedMutationDao, + private val json: Json, + ) { + // capacity=1 DROP_OLDEST so a burst of user enqueues (e.g. liking N + // tracks while offline) surfaces as one snackbar rather than queueing + // N. replay=0 because a hint observed at enqueue time isn't useful + // to a screen that mounts later. + private val _userEnqueueHints = + MutableSharedFlow( + replay = 0, + extraBufferCapacity = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) - /** - * Hint stream consumed by [com.fabledsword.minstrel.shared.widgets.ShellScaffold] - * to surface "Saved — will sync when online" as a snackbar whenever a - * user-driven write hits the offline-fallback path. Background-only - * enqueues (play-events, playback-error reports) do not emit — those - * fire from non-foreground paths where a snackbar would be either - * dropped (no shell mounted) or jarring (lock-screen toggle). - */ - val userEnqueueHints: SharedFlow = _userEnqueueHints.asSharedFlow() + /** + * Hint stream consumed by [com.fabledsword.minstrel.shared.widgets.ShellScaffold] + * to surface "Saved — will sync when online" as a snackbar whenever a + * user-driven write hits the offline-fallback path. Background-only + * enqueues (play-events, playback-error reports) do not emit — those + * fire from non-foreground paths where a snackbar would be either + * dropped (no shell mounted) or jarring (lock-screen toggle). + */ + val userEnqueueHints: SharedFlow = _userEnqueueHints.asSharedFlow() - suspend fun enqueueLikeToggle( - entityType: String, - entityId: String, - desiredState: Boolean, - ): Long = insertUserDriven( - MutationKind.LIKE_TOGGLE, - json.encodeToString( - LikeTogglePayload.serializer(), - LikeTogglePayload(entityType, entityId, desiredState), - ), - ) + suspend fun enqueueLikeToggle( + entityType: String, + entityId: String, + desiredState: Boolean, + ): Long = + insertUserDriven( + MutationKind.LIKE_TOGGLE, + json.encodeToString( + LikeTogglePayload.serializer(), + LikeTogglePayload(entityType, entityId, desiredState), + ), + ) - suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven( - MutationKind.QUARANTINE_UNFLAG, - json.encodeToString( - QuarantineUnflagPayload.serializer(), - QuarantineUnflagPayload(trackId), - ), - ) + suspend fun enqueueQuarantineUnflag(trackId: String): Long = + insertUserDriven( + MutationKind.QUARANTINE_UNFLAG, + json.encodeToString( + QuarantineUnflagPayload.serializer(), + QuarantineUnflagPayload(trackId), + ), + ) - suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = insertUserDriven( - MutationKind.PLAYLIST_APPEND, - json.encodeToString(PlaylistAppendPayload.serializer(), payload), - ) + suspend fun enqueuePlaylistAppend(payload: PlaylistAppendPayload): Long = + insertUserDriven( + MutationKind.PLAYLIST_APPEND, + json.encodeToString(PlaylistAppendPayload.serializer(), payload), + ) - suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = insertUserDriven( - MutationKind.PLAYLIST_CREATE, - json.encodeToString(PlaylistCreatePayload.serializer(), payload), - ) + suspend fun enqueuePlaylistCreate(payload: PlaylistCreatePayload): Long = + insertUserDriven( + MutationKind.PLAYLIST_CREATE, + json.encodeToString(PlaylistCreatePayload.serializer(), payload), + ) - suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long = insertUserDriven( - MutationKind.PLAYLIST_UPDATE, - json.encodeToString(PlaylistUpdatePayload.serializer(), payload), - ) + suspend fun enqueuePlaylistUpdate(payload: PlaylistUpdatePayload): Long = + insertUserDriven( + MutationKind.PLAYLIST_UPDATE, + json.encodeToString(PlaylistUpdatePayload.serializer(), payload), + ) - suspend fun enqueuePlaylistDelete(playlistId: String): Long = insertUserDriven( - MutationKind.PLAYLIST_DELETE, - json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)), - ) + suspend fun enqueuePlaylistDelete(playlistId: String): Long = + insertUserDriven( + MutationKind.PLAYLIST_DELETE, + json.encodeToString(PlaylistDeletePayload.serializer(), PlaylistDeletePayload(playlistId)), + ) - suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long = insertUserDriven( - MutationKind.PLAYLIST_REMOVE_TRACK, - json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload), - ) + suspend fun enqueuePlaylistRemoveTrack(payload: PlaylistRemoveTrackPayload): Long = + insertUserDriven( + MutationKind.PLAYLIST_REMOVE_TRACK, + json.encodeToString(PlaylistRemoveTrackPayload.serializer(), payload), + ) - suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long = insertUserDriven( - MutationKind.PLAYLIST_REORDER, - json.encodeToString(PlaylistReorderPayload.serializer(), payload), - ) + suspend fun enqueuePlaylistReorder(payload: PlaylistReorderPayload): Long = + insertUserDriven( + MutationKind.PLAYLIST_REORDER, + json.encodeToString(PlaylistReorderPayload.serializer(), payload), + ) - /** - * Ids of playlists made on this device that the server hasn't been - * sent yet. A list refresh keeps them, so a playlist made offline - * doesn't vanish before its create goes out. - */ - suspend fun pendingPlaylistCreateIds(): Set = dao.getAll() - .asSequence() - .filter { it.kind == MutationKind.PLAYLIST_CREATE } - .mapNotNull { row -> - runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) } - .getOrNull()?.id - } - .toSet() + /** + * Ids of playlists made on this device that the server hasn't been + * sent yet. A list refresh keeps them, so a playlist made offline + * doesn't vanish before its create goes out. + */ + suspend fun pendingPlaylistCreateIds(): Set = + dao + .getAll() + .asSequence() + .filter { it.kind == MutationKind.PLAYLIST_CREATE } + .mapNotNull { row -> + runCatching { json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload) } + .getOrNull() + ?.id + }.toSet() - /** - * The like state each still-queued like toggle sets, by - * [likeToggleKey], the newest toggle winning. A toggle for an entity - * found here must queue behind it rather than go live, or the older - * one replays after it and undoes it; and a refresh keeps these states - * over the server's, which hasn't seen them yet. - */ - suspend fun pendingLikeStates(): Map = buildMap { - dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row -> - runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) } - .getOrNull() - ?.let { put(likeToggleKey(it.entityType, it.entityId), it.desiredState) } - } - } - - /** - * Whether each track with a quarantine flag or unflag still queued ends - * up flagged (true) or not, the newest winning. Read for the same two - * reasons as [pendingLikeStates]. - */ - suspend fun pendingQuarantineStates(): Map = buildMap { - dao.getAll().forEach { row -> - when (row.kind) { - MutationKind.QUARANTINE_FLAG -> runCatching { - json.decodeFromString(QuarantineFlagPayload.serializer(), row.payload) - }.getOrNull()?.let { put(it.trackId, true) } - MutationKind.QUARANTINE_UNFLAG -> runCatching { - json.decodeFromString(QuarantineUnflagPayload.serializer(), row.payload) - }.getOrNull()?.let { put(it.trackId, false) } + /** + * The like state each still-queued like toggle sets, by + * [likeToggleKey], the newest toggle winning. A toggle for an entity + * found here must queue behind it rather than go live, or the older + * one replays after it and undoes it; and a refresh keeps these states + * over the server's, which hasn't seen them yet. + */ + suspend fun pendingLikeStates(): Map = + buildMap { + dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row -> + runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) } + .getOrNull() + ?.let { put(likeToggleKey(it.entityType, it.entityId), it.desiredState) } + } } + + /** + * Whether each track with a quarantine flag or unflag still queued ends + * up flagged (true) or not, the newest winning. Read for the same two + * reasons as [pendingLikeStates]. + */ + suspend fun pendingQuarantineStates(): Map = + buildMap { + dao.getAll().forEach { row -> + when (row.kind) { + MutationKind.QUARANTINE_FLAG -> + runCatching { + json.decodeFromString(QuarantineFlagPayload.serializer(), row.payload) + }.getOrNull()?.let { put(it.trackId, true) } + MutationKind.QUARANTINE_UNFLAG -> + runCatching { + json.decodeFromString(QuarantineUnflagPayload.serializer(), row.payload) + }.getOrNull()?.let { put(it.trackId, false) } + } + } + } + + suspend fun enqueueQuarantineFlag( + trackId: String, + reason: String, + notes: String, + ): Long = + insertUserDriven( + MutationKind.QUARANTINE_FLAG, + json.encodeToString( + QuarantineFlagPayload.serializer(), + QuarantineFlagPayload(trackId, reason, notes), + ), + ) + + /** Queues the user's whole normalization preference for replay. */ + suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = + insertUserDriven( + MutationKind.NORMALIZATION_SET, + json.encodeToString(NormalizationPrefs.serializer(), prefs), + ) + + suspend fun enqueueNotificationRead(id: String): Long = + insertUserDriven( + MutationKind.NOTIFICATION_READ, + json.encodeToString(NotificationReadPayload.serializer(), NotificationReadPayload(id)), + ) + + suspend fun enqueueNotificationsReadAll(upToIso: String?): Long = + insertUserDriven( + MutationKind.NOTIFICATIONS_READ_ALL, + json.encodeToString( + NotificationsReadAllPayload.serializer(), + NotificationsReadAllPayload(upToIso), + ), + ) + + suspend fun enqueueNotificationSettingSet(payload: NotificationSettingPayload): Long = + insertUserDriven( + MutationKind.NOTIFICATION_SETTING_SET, + json.encodeToString(NotificationSettingPayload.serializer(), payload), + ) + + suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = + dao.insert( + CachedMutationEntity( + kind = MutationKind.PLAY_OFFLINE, + payload = json.encodeToString(PlayOfflinePayload.serializer(), payload), + ), + ) + + suspend fun enqueuePlaybackErrorReport(payload: PlaybackErrorReportPayload): Long = + dao.insert( + CachedMutationEntity( + kind = MutationKind.PLAYBACK_ERROR_REPORT, + payload = json.encodeToString(PlaybackErrorReportPayload.serializer(), payload), + ), + ) + + /** + * Durable close-by-id for an already-open server play row. Background + * path only (no user hint) — same as [enqueuePlayOffline]. + */ + suspend fun enqueuePlayEnded(payload: PlayEndedPayload): Long = + dao.insert( + CachedMutationEntity( + kind = MutationKind.PLAY_ENDED, + payload = json.encodeToString(PlayEndedPayload.serializer(), payload), + ), + ) + + private suspend fun insertUserDriven( + kind: String, + payload: String, + ): Long { + val id = dao.insert(CachedMutationEntity(kind = kind, payload = payload)) + _userEnqueueHints.tryEmit(QUEUED_MESSAGE) + return id } } - suspend fun enqueueQuarantineFlag( - trackId: String, - reason: String, - notes: String, - ): Long = insertUserDriven( - MutationKind.QUARANTINE_FLAG, - json.encodeToString( - QuarantineFlagPayload.serializer(), - QuarantineFlagPayload(trackId, reason, notes), - ), - ) - - /** Queues the user's whole normalization preference for replay. */ - suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven( - MutationKind.NORMALIZATION_SET, - json.encodeToString(NormalizationPrefs.serializer(), prefs), - ) - - suspend fun enqueueNotificationRead(id: String): Long = insertUserDriven( - MutationKind.NOTIFICATION_READ, - json.encodeToString(NotificationReadPayload.serializer(), NotificationReadPayload(id)), - ) - - suspend fun enqueueNotificationsReadAll(upToIso: String?): Long = insertUserDriven( - MutationKind.NOTIFICATIONS_READ_ALL, - json.encodeToString( - NotificationsReadAllPayload.serializer(), - NotificationsReadAllPayload(upToIso), - ), - ) - - suspend fun enqueueNotificationSettingSet(payload: NotificationSettingPayload): Long = - insertUserDriven( - MutationKind.NOTIFICATION_SETTING_SET, - json.encodeToString(NotificationSettingPayload.serializer(), payload), - ) - - suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert( - CachedMutationEntity( - kind = MutationKind.PLAY_OFFLINE, - payload = json.encodeToString(PlayOfflinePayload.serializer(), payload), - ), - ) - - suspend fun enqueuePlaybackErrorReport(payload: PlaybackErrorReportPayload): Long = dao.insert( - CachedMutationEntity( - kind = MutationKind.PLAYBACK_ERROR_REPORT, - payload = json.encodeToString(PlaybackErrorReportPayload.serializer(), payload), - ), - ) - - /** - * Durable close-by-id for an already-open server play row. Background - * path only (no user hint) — same as [enqueuePlayOffline]. - */ - suspend fun enqueuePlayEnded(payload: PlayEndedPayload): Long = dao.insert( - CachedMutationEntity( - kind = MutationKind.PLAY_ENDED, - payload = json.encodeToString(PlayEndedPayload.serializer(), payload), - ), - ) - - private suspend fun insertUserDriven(kind: String, payload: String): Long { - val id = dao.insert(CachedMutationEntity(kind = kind, payload = payload)) - _userEnqueueHints.tryEmit(QUEUED_MESSAGE) - return id - } -} - /** * Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the * `DELETE /api/quarantine/{trackId}` call lost during a connectivity * hiccup. The replayer just re-fires the DELETE; idempotent server-side. */ @Serializable -data class QuarantineUnflagPayload(val trackId: String) +data class QuarantineUnflagPayload( + val trackId: String, +) /** The key [MutationQueue.pendingLikeStates] files a like toggle under. */ -fun likeToggleKey(entityType: String, entityId: String): String = "$entityType:$entityId" +fun likeToggleKey( + entityType: String, + entityId: String, +): String = "$entityType:$entityId" /** * Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to @@ -320,7 +352,9 @@ data class PlaylistUpdatePayload( /** Persisted payload for `MutationKind.PLAYLIST_DELETE`. */ @Serializable -data class PlaylistDeletePayload(val playlistId: String) +data class PlaylistDeletePayload( + val playlistId: String, +) /** * Persisted payload for `MutationKind.PLAYLIST_REMOVE_TRACK`. [trackId] is @@ -405,7 +439,9 @@ data class PlaybackErrorReportPayload( /** Persisted payload for `MutationKind.NOTIFICATION_READ`. */ @Serializable -data class NotificationReadPayload(val id: String) +data class NotificationReadPayload( + val id: String, +) /** * Persisted payload for `MutationKind.NOTIFICATIONS_READ_ALL`. @@ -413,7 +449,9 @@ data class NotificationReadPayload(val id: String) * when the inbox was empty on the device, which marks everything. */ @Serializable -data class NotificationsReadAllPayload(val upToIso: String?) +data class NotificationsReadAllPayload( + val upToIso: String?, +) /** * Persisted payload for `MutationKind.NOTIFICATION_SETTING_SET`: one diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt index 96c1f400..3da828e3 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationReplayer.kt @@ -9,24 +9,24 @@ import com.fabledsword.minstrel.api.endpoints.FlagRequest import com.fabledsword.minstrel.api.endpoints.LikesApi import com.fabledsword.minstrel.api.endpoints.MeApi import com.fabledsword.minstrel.api.endpoints.NotificationsApi -import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody -import com.fabledsword.minstrel.api.endpoints.ReadAllBody import com.fabledsword.minstrel.api.endpoints.PlaybackErrorReportRequest import com.fabledsword.minstrel.api.endpoints.PlaybackErrorsApi import com.fabledsword.minstrel.api.endpoints.PlaylistsApi +import com.fabledsword.minstrel.api.endpoints.PutNotificationSettingsBody import com.fabledsword.minstrel.api.endpoints.QuarantineApi +import com.fabledsword.minstrel.api.endpoints.ReadAllBody import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest -import com.fabledsword.minstrel.connectivity.NetworkStatusController -import com.fabledsword.minstrel.connectivity.ServerHealth -import com.fabledsword.minstrel.models.wire.PlayEndedRequest -import com.fabledsword.minstrel.models.wire.PlayOfflineRequest 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.entities.CachedMutationEntity +import com.fabledsword.minstrel.connectivity.NetworkStatusController +import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.likes.data.LikesRepository +import com.fabledsword.minstrel.models.wire.PlayEndedRequest +import com.fabledsword.minstrel.models.wire.PlayOfflineRequest import com.fabledsword.minstrel.settings.data.NormalizationPrefs import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.distinctUntilChanged @@ -35,7 +35,6 @@ import kotlinx.coroutines.flow.filterNotNull import kotlinx.coroutines.flow.map import kotlinx.coroutines.launch import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock import kotlinx.datetime.Clock import kotlinx.serialization.SerializationException import kotlinx.serialization.json.Json @@ -75,296 +74,311 @@ import javax.inject.Singleton * forever. */ @Singleton -class MutationReplayer @Inject constructor( - private val dao: CachedMutationDao, - private val authStore: AuthStore, - private val accountCache: AccountCache, - private val json: Json, - @ApplicationScope private val scope: CoroutineScope, - networkStatus: NetworkStatusController, - retrofit: Retrofit, -) { - private val likesApi: LikesApi = retrofit.create() - private val quarantineApi: QuarantineApi = retrofit.create() - private val playlistsApi: PlaylistsApi = retrofit.create() - private val eventsApi: EventsApi = retrofit.create() - private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create() - private val meApi: MeApi = retrofit.create() - private val notificationsApi: NotificationsApi = retrofit.create() +class MutationReplayer + @Inject + constructor( + private val dao: CachedMutationDao, + private val authStore: AuthStore, + private val accountCache: AccountCache, + private val json: Json, + @ApplicationScope private val scope: CoroutineScope, + networkStatus: NetworkStatusController, + retrofit: Retrofit, + ) { + private val likesApi: LikesApi = retrofit.create() + private val quarantineApi: QuarantineApi = retrofit.create() + private val playlistsApi: PlaylistsApi = retrofit.create() + private val eventsApi: EventsApi = retrofit.create() + private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create() + private val meApi: MeApi = retrofit.create() + private val notificationsApi: NotificationsApi = retrofit.create() - private val mutex = Mutex() + private val mutex = Mutex() - private enum class Outcome { SENT, DROP, RETRY } + private enum class Outcome { SENT, DROP, RETRY } - init { - scope.launch { - authStore.sessionCookie - .filterNotNull() - .distinctUntilChanged() - .collect { drainSafe() } + init { + scope.launch { + authStore.sessionCookie + .filterNotNull() + .distinctUntilChanged() + .collect { drainSafe() } + } + scope.launch { + accountCache.ownedBySignedInUser + .filter { it } + .collect { drainSafe() } + } + // Server-reachable-again: replay queued writes the moment the + // health signal recovers, so an offline→online transition mid- + // session doesn't wait for the next cold start / re-auth. + scope.launch { + networkStatus.state + .map { it == ServerHealth.Healthy } + .distinctUntilChanged() + .filter { it } + .collect { drainSafe() } + } } - scope.launch { - accountCache.ownedBySignedInUser - .filter { it } - .collect { drainSafe() } - } - // Server-reachable-again: replay queued writes the moment the - // health signal recovers, so an offline→online transition mid- - // session doesn't wait for the next cold start / re-auth. - scope.launch { - networkStatus.state - .map { it == ServerHealth.Healthy } - .distinctUntilChanged() - .filter { it } - .collect { drainSafe() } - } - } - /** Public entry-point; coalesces concurrent triggers via a Mutex. */ - suspend fun drainSafe() { - if (!mutex.tryLock()) return - try { - drain() - } finally { - mutex.unlock() + /** Public entry-point; coalesces concurrent triggers via a Mutex. */ + suspend fun drainSafe() { + if (!mutex.tryLock()) return + try { + drain() + } finally { + mutex.unlock() + } } - } - private suspend fun drain() { - // Another account's writes must not go out under this session. - if (!accountCache.ownedBySignedInUser.value) return - val rows = dao.getAll() - // Collapse superseded toggles (likes, settings): only the latest - // desired state per entity is replayed; older toggles for the same - // entity are dropped unsent. Without this, partial-failure + - // differential retry could replay an older toggle last and invert the - // final state — an unlike the user already made would be undone. - val superseded = supersededToggleIds(rows, json) - // A playlist's changes go out in the order they were made: once one - // has to wait, the rest for that list wait behind it, so an add - // never reaches the server before the create of its list. - val waiting = HashSet() - for (row in rows) { - replayRow(row, superseded = row.id in superseded, waiting = waiting) + private suspend fun drain() { + // Another account's writes must not go out under this session. + if (!accountCache.ownedBySignedInUser.value) return + val rows = dao.getAll() + // Collapse superseded toggles (likes, settings): only the latest + // desired state per entity is replayed; older toggles for the same + // entity are dropped unsent. Without this, partial-failure + + // differential retry could replay an older toggle last and invert the + // final state — an unlike the user already made would be undone. + val superseded = supersededToggleIds(rows, json) + // A playlist's changes go out in the order they were made: once one + // has to wait, the rest for that list wait behind it, so an add + // never reaches the server before the create of its list. + val waiting = HashSet() + for (row in rows) { + replayRow(row, superseded = row.id in superseded, waiting = waiting) + } } - } - /** - * Sends one row, or drops it when a later row has superseded it, or - * leaves it queued when an earlier change to the same playlist is still - * waiting. A row that has to retry makes its playlist wait in [waiting]. - */ - private suspend fun replayRow(row: CachedMutationEntity, superseded: Boolean, waiting: MutableSet) { - val playlistId = playlistIdOf(row, json) - when { - superseded -> dao.delete(row.id) - playlistId != null && playlistId in waiting -> Unit - else -> when (outcomeFor(row)) { - Outcome.SENT, Outcome.DROP -> dao.delete(row.id) - Outcome.RETRY -> { - dao.recordAttempt(row.id, Clock.System.now()) - playlistId?.let(waiting::add) + /** + * Sends one row, or drops it when a later row has superseded it, or + * leaves it queued when an earlier change to the same playlist is still + * waiting. A row that has to retry makes its playlist wait in [waiting]. + */ + private suspend fun replayRow( + row: CachedMutationEntity, + superseded: Boolean, + waiting: MutableSet, + ) { + val playlistId = playlistIdOf(row, json) + when { + superseded -> dao.delete(row.id) + playlistId != null && playlistId in waiting -> Unit + else -> + when (outcomeFor(row)) { + Outcome.SENT, Outcome.DROP -> dao.delete(row.id) + Outcome.RETRY -> { + dao.recordAttempt(row.id, Clock.System.now()) + playlistId?.let(waiting::add) + } + } + } + } + + private suspend fun outcomeFor(row: CachedMutationEntity): Outcome = + try { + dispatch(row) + } catch (e: HttpException) { + if (isPermanent(e.code())) Outcome.DROP else Outcome.RETRY + } catch ( + @Suppress("SwallowedException") e: SerializationException, + ) { + // Corrupt / schema-incompatible payload — permanent, drop it. + Outcome.DROP + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + // Transport / unknown — leave queued for the next pass. + Outcome.RETRY + } + + /** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */ + private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code) + + /** + * Returns the outcome of replaying one row. SENT on a 2xx; DROP for an + * unknown kind/variant. Network / HTTP failures THROW and are classified + * by [outcomeFor] — dispatchers never swallow them. + */ + private suspend fun dispatch(row: CachedMutationEntity): Outcome = + when (row.kind) { + MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload) + MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload) + MutationKind.PLAYLIST_APPEND, + MutationKind.PLAYLIST_CREATE, + MutationKind.PLAYLIST_UPDATE, + MutationKind.PLAYLIST_DELETE, + MutationKind.PLAYLIST_REMOVE_TRACK, + MutationKind.PLAYLIST_REORDER, + -> dispatchPlaylist(row) + MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload) + MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload) + MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload) + MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload) + MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload) + MutationKind.NOTIFICATION_READ, + MutationKind.NOTIFICATIONS_READ_ALL, + MutationKind.NOTIFICATION_SETTING_SET, + -> dispatchNotification(row) + // Unknown kind — drop so a stale schema entry can't wedge the queue. + else -> Outcome.DROP + } + + /** The notifications inbox's kinds, split out to keep [dispatch] simple. */ + private suspend fun dispatchNotification(row: CachedMutationEntity): Outcome = + when (row.kind) { + MutationKind.NOTIFICATION_READ -> dispatchNotificationRead(row.payload) + MutationKind.NOTIFICATIONS_READ_ALL -> dispatchNotificationsReadAll(row.payload) + MutationKind.NOTIFICATION_SETTING_SET -> dispatchNotificationSettingSet(row.payload) + else -> Outcome.DROP + } + + private suspend fun dispatchLikeToggle(payload: String): Outcome { + val decoded = json.decodeFromString(LikeTogglePayload.serializer(), payload) + val kindPath = + when (decoded.entityType) { + LikesRepository.ENTITY_ARTIST -> "artists" + LikesRepository.ENTITY_ALBUM -> "albums" + LikesRepository.ENTITY_TRACK -> "tracks" + else -> return Outcome.DROP } + if (decoded.desiredState) { + likesApi.like(kindPath, decoded.entityId) + } else { + likesApi.unlike(kindPath, decoded.entityId) } + return Outcome.SENT + } + + private suspend fun dispatchQuarantineUnflag(payload: String): Outcome { + val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload) + quarantineApi.unflag(decoded.trackId) + return Outcome.SENT + } + + /** + * A listener's own playlists, split out to keep [dispatch] simple. A + * 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since, + * and nothing is left to do. + */ + private suspend fun dispatchPlaylist(row: CachedMutationEntity): Outcome { + val payload = row.payload + when (row.kind) { + MutationKind.PLAYLIST_APPEND -> { + val p = json.decodeFromString(PlaylistAppendPayload.serializer(), payload) + playlistsApi.appendTracks( + p.playlistId, + AppendTracksRequest(trackIds = p.trackIds, requestId = p.requestId), + ) + } + MutationKind.PLAYLIST_CREATE -> { + val p = json.decodeFromString(PlaylistCreatePayload.serializer(), payload) + playlistsApi.create(CreatePlaylistRequest(id = p.id, name = p.name, isPublic = p.isPublic)) + } + MutationKind.PLAYLIST_UPDATE -> { + val p = json.decodeFromString(PlaylistUpdatePayload.serializer(), payload) + playlistsApi.update(p.playlistId, UpdatePlaylistRequest(name = p.name, isPublic = p.isPublic)) + } + MutationKind.PLAYLIST_DELETE -> { + val p = json.decodeFromString(PlaylistDeletePayload.serializer(), payload) + playlistsApi.delete(p.playlistId) + } + MutationKind.PLAYLIST_REMOVE_TRACK -> { + val p = json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), payload) + playlistsApi.removeTrack(p.playlistId, p.position, p.trackId) + } + MutationKind.PLAYLIST_REORDER -> { + val p = json.decodeFromString(PlaylistReorderPayload.serializer(), payload) + playlistsApi.reorder(p.playlistId, ReorderTracksRequest(trackIds = p.trackIds)) + } + else -> return Outcome.DROP + } + return Outcome.SENT + } + + private suspend fun dispatchQuarantineFlag(payload: String): Outcome { + val decoded = json.decodeFromString(QuarantineFlagPayload.serializer(), payload) + quarantineApi.flag( + FlagRequest( + trackId = decoded.trackId, + reason = decoded.reason, + notes = decoded.notes, + ), + ) + return Outcome.SENT + } + + private suspend fun dispatchPlayOffline(payload: String): Outcome { + val decoded = json.decodeFromString(PlayOfflinePayload.serializer(), payload) + eventsApi.playOffline( + PlayOfflineRequest( + trackId = decoded.trackId, + clientId = decoded.clientId, + at = decoded.atIso, + durationPlayedMs = decoded.durationPlayedMs, + source = decoded.source, + deviceClass = decoded.deviceClass, + ), + ) + return Outcome.SENT + } + + private suspend fun dispatchPlayEnded(payload: String): Outcome { + val decoded = json.decodeFromString(PlayEndedPayload.serializer(), payload) + eventsApi.playEnded( + PlayEndedRequest( + playEventId = decoded.playEventId, + durationPlayedMs = decoded.durationPlayedMs, + ), + ) + return Outcome.SENT + } + + /** + * Sends the queued normalization preference. The device already shows + * it, so the server's echo is not written back: a change made since the + * row was queued would be a newer row, and the collapse keeps only that. + */ + private suspend fun dispatchNormalizationSet(payload: String): Outcome { + meApi.putNormalization(json.decodeFromString(NormalizationPrefs.serializer(), payload)) + return Outcome.SENT + } + + /** A 404 (the notice was trimmed or already gone) is a 4xx, so DROP: nothing left to do. */ + private suspend fun dispatchNotificationRead(payload: String): Outcome { + val decoded = json.decodeFromString(NotificationReadPayload.serializer(), payload) + notificationsApi.markRead(decoded.id) + return Outcome.SENT + } + + private suspend fun dispatchNotificationsReadAll(payload: String): Outcome { + val decoded = json.decodeFromString(NotificationsReadAllPayload.serializer(), payload) + notificationsApi.readAll(ReadAllBody(upTo = decoded.upToIso)) + return Outcome.SENT + } + + /** An unknown channel can only come from a corrupt row: DROP it. */ + private suspend fun dispatchNotificationSettingSet(payload: String): Outcome { + val decoded = json.decodeFromString(NotificationSettingPayload.serializer(), payload) + val change = notificationSettingChange(decoded) ?: return Outcome.DROP + notificationsApi.putSettings(PutNotificationSettingsBody(listOf(change))) + return Outcome.SENT + } + + private suspend fun dispatchPlaybackErrorReport(payload: String): Outcome { + val decoded = json.decodeFromString(PlaybackErrorReportPayload.serializer(), payload) + playbackErrorsApi.report( + PlaybackErrorReportRequest( + trackId = decoded.trackId, + kind = decoded.kind, + detail = decoded.detail, + clientId = decoded.clientId, + ), + ) + return Outcome.SENT } } - private suspend fun outcomeFor(row: CachedMutationEntity): Outcome = try { - dispatch(row) - } catch (e: HttpException) { - if (isPermanent(e.code())) Outcome.DROP else Outcome.RETRY - } catch (@Suppress("SwallowedException") e: SerializationException) { - // Corrupt / schema-incompatible payload — permanent, drop it. - Outcome.DROP - } catch (@Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable) { - // Transport / unknown — leave queued for the next pass. - Outcome.RETRY - } - - /** A refusal that a replay would only get again ([isRetryableStatus]'s complement). */ - private fun isPermanent(code: Int): Boolean = !isRetryableStatus(code) - - /** - * Returns the outcome of replaying one row. SENT on a 2xx; DROP for an - * unknown kind/variant. Network / HTTP failures THROW and are classified - * by [outcomeFor] — dispatchers never swallow them. - */ - private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) { - MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload) - MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload) - MutationKind.PLAYLIST_APPEND, - MutationKind.PLAYLIST_CREATE, - MutationKind.PLAYLIST_UPDATE, - MutationKind.PLAYLIST_DELETE, - MutationKind.PLAYLIST_REMOVE_TRACK, - MutationKind.PLAYLIST_REORDER, - -> dispatchPlaylist(row) - MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload) - MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload) - MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload) - MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload) - MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload) - MutationKind.NOTIFICATION_READ, - MutationKind.NOTIFICATIONS_READ_ALL, - MutationKind.NOTIFICATION_SETTING_SET, - -> dispatchNotification(row) - // Unknown kind — drop so a stale schema entry can't wedge the queue. - else -> Outcome.DROP - } - - /** The notifications inbox's kinds, split out to keep [dispatch] simple. */ - private suspend fun dispatchNotification(row: CachedMutationEntity): Outcome = when (row.kind) { - MutationKind.NOTIFICATION_READ -> dispatchNotificationRead(row.payload) - MutationKind.NOTIFICATIONS_READ_ALL -> dispatchNotificationsReadAll(row.payload) - MutationKind.NOTIFICATION_SETTING_SET -> dispatchNotificationSettingSet(row.payload) - else -> Outcome.DROP - } - - private suspend fun dispatchLikeToggle(payload: String): Outcome { - val decoded = json.decodeFromString(LikeTogglePayload.serializer(), payload) - val kindPath = when (decoded.entityType) { - LikesRepository.ENTITY_ARTIST -> "artists" - LikesRepository.ENTITY_ALBUM -> "albums" - LikesRepository.ENTITY_TRACK -> "tracks" - else -> return Outcome.DROP - } - if (decoded.desiredState) { - likesApi.like(kindPath, decoded.entityId) - } else { - likesApi.unlike(kindPath, decoded.entityId) - } - return Outcome.SENT - } - - private suspend fun dispatchQuarantineUnflag(payload: String): Outcome { - val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload) - quarantineApi.unflag(decoded.trackId) - return Outcome.SENT - } - - /** - * A listener's own playlists, split out to keep [dispatch] simple. A - * 404 or 409 is a 4xx, so DROP: the list is gone, or has changed since, - * and nothing is left to do. - */ - private suspend fun dispatchPlaylist(row: CachedMutationEntity): Outcome { - val payload = row.payload - when (row.kind) { - MutationKind.PLAYLIST_APPEND -> { - val p = json.decodeFromString(PlaylistAppendPayload.serializer(), payload) - playlistsApi.appendTracks( - p.playlistId, - AppendTracksRequest(trackIds = p.trackIds, requestId = p.requestId), - ) - } - MutationKind.PLAYLIST_CREATE -> { - val p = json.decodeFromString(PlaylistCreatePayload.serializer(), payload) - playlistsApi.create(CreatePlaylistRequest(id = p.id, name = p.name, isPublic = p.isPublic)) - } - MutationKind.PLAYLIST_UPDATE -> { - val p = json.decodeFromString(PlaylistUpdatePayload.serializer(), payload) - playlistsApi.update(p.playlistId, UpdatePlaylistRequest(name = p.name, isPublic = p.isPublic)) - } - MutationKind.PLAYLIST_DELETE -> { - val p = json.decodeFromString(PlaylistDeletePayload.serializer(), payload) - playlistsApi.delete(p.playlistId) - } - MutationKind.PLAYLIST_REMOVE_TRACK -> { - val p = json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), payload) - playlistsApi.removeTrack(p.playlistId, p.position, p.trackId) - } - MutationKind.PLAYLIST_REORDER -> { - val p = json.decodeFromString(PlaylistReorderPayload.serializer(), payload) - playlistsApi.reorder(p.playlistId, ReorderTracksRequest(trackIds = p.trackIds)) - } - else -> return Outcome.DROP - } - return Outcome.SENT - } - - private suspend fun dispatchQuarantineFlag(payload: String): Outcome { - val decoded = json.decodeFromString(QuarantineFlagPayload.serializer(), payload) - quarantineApi.flag( - FlagRequest( - trackId = decoded.trackId, - reason = decoded.reason, - notes = decoded.notes, - ), - ) - return Outcome.SENT - } - - private suspend fun dispatchPlayOffline(payload: String): Outcome { - val decoded = json.decodeFromString(PlayOfflinePayload.serializer(), payload) - eventsApi.playOffline( - PlayOfflineRequest( - trackId = decoded.trackId, - clientId = decoded.clientId, - at = decoded.atIso, - durationPlayedMs = decoded.durationPlayedMs, - source = decoded.source, - deviceClass = decoded.deviceClass, - ), - ) - return Outcome.SENT - } - - private suspend fun dispatchPlayEnded(payload: String): Outcome { - val decoded = json.decodeFromString(PlayEndedPayload.serializer(), payload) - eventsApi.playEnded( - PlayEndedRequest( - playEventId = decoded.playEventId, - durationPlayedMs = decoded.durationPlayedMs, - ), - ) - return Outcome.SENT - } - - /** - * Sends the queued normalization preference. The device already shows - * it, so the server's echo is not written back: a change made since the - * row was queued would be a newer row, and the collapse keeps only that. - */ - private suspend fun dispatchNormalizationSet(payload: String): Outcome { - meApi.putNormalization(json.decodeFromString(NormalizationPrefs.serializer(), payload)) - return Outcome.SENT - } - - /** A 404 (the notice was trimmed or already gone) is a 4xx, so DROP: nothing left to do. */ - private suspend fun dispatchNotificationRead(payload: String): Outcome { - val decoded = json.decodeFromString(NotificationReadPayload.serializer(), payload) - notificationsApi.markRead(decoded.id) - return Outcome.SENT - } - - private suspend fun dispatchNotificationsReadAll(payload: String): Outcome { - val decoded = json.decodeFromString(NotificationsReadAllPayload.serializer(), payload) - notificationsApi.readAll(ReadAllBody(upTo = decoded.upToIso)) - return Outcome.SENT - } - - /** An unknown channel can only come from a corrupt row: DROP it. */ - private suspend fun dispatchNotificationSettingSet(payload: String): Outcome { - val decoded = json.decodeFromString(NotificationSettingPayload.serializer(), payload) - val change = notificationSettingChange(decoded) ?: return Outcome.DROP - notificationsApi.putSettings(PutNotificationSettingsBody(listOf(change))) - return Outcome.SENT - } - - private suspend fun dispatchPlaybackErrorReport(payload: String): Outcome { - val decoded = json.decodeFromString(PlaybackErrorReportPayload.serializer(), payload) - playbackErrorsApi.report( - PlaybackErrorReportRequest( - trackId = decoded.trackId, - kind = decoded.kind, - detail = decoded.detail, - clientId = decoded.clientId, - ), - ) - return Outcome.SENT - } -} - /** * Row ids of desired-state toggles superseded by a later toggle for the same * entity. Applies to every kind whose payload encodes a TARGET state rather @@ -376,10 +390,14 @@ class MutationReplayer @Inject constructor( * instance. [rows] must be ascending by id (FIFO), which is what * `CachedMutationDao.getAll()` returns. */ -internal fun supersededToggleIds(rows: List, json: Json): Set { +internal fun supersededToggleIds( + rows: List, + json: Json, +): Set { val latestByEntity = HashMap() val superseded = HashSet() - rows.asSequence() + rows + .asSequence() .mapNotNull { row -> toggleKeyOf(row, json)?.let { key -> key to row.id } } .forEach { (key, id) -> // Ascending ids mean a prior entry for this key is always older. @@ -397,46 +415,58 @@ internal fun supersededToggleIds(rows: List, json: Json): * The kind is part of the key so two toggle kinds can never collide on the * same entity id. */ -private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when (row.kind) { - MutationKind.LIKE_TOGGLE -> runCatching { - json.decodeFromString(LikeTogglePayload.serializer(), row.payload) - }.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" } +private fun toggleKeyOf( + row: CachedMutationEntity, + json: Json, +): String? = + when (row.kind) { + MutationKind.LIKE_TOGGLE -> + runCatching { + json.decodeFromString(LikeTogglePayload.serializer(), row.payload) + }.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" } - MutationKind.NOTIFICATION_SETTING_SET -> runCatching { - json.decodeFromString(NotificationSettingPayload.serializer(), row.payload) - }.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" } + MutationKind.NOTIFICATION_SETTING_SET -> + runCatching { + json.decodeFromString(NotificationSettingPayload.serializer(), row.payload) + }.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" } - // A reorder is the list's whole new order, so only the last one counts. - MutationKind.PLAYLIST_REORDER -> runCatching { - json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload) - }.getOrNull()?.let { "${row.kind}:${it.playlistId}" } + // A reorder is the list's whole new order, so only the last one counts. + MutationKind.PLAYLIST_REORDER -> + runCatching { + json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload) + }.getOrNull()?.let { "${row.kind}:${it.playlistId}" } - // One preference per user, so every normalization row shares one key. - MutationKind.NORMALIZATION_SET -> runCatching { - json.decodeFromString(NormalizationPrefs.serializer(), row.payload) - }.getOrNull()?.let { row.kind } + // One preference per user, so every normalization row shares one key. + MutationKind.NORMALIZATION_SET -> + runCatching { + json.decodeFromString(NormalizationPrefs.serializer(), row.payload) + }.getOrNull()?.let { row.kind } - else -> null -} + else -> null + } /** * The playlist a queued row changes, or null for a row that isn't a * playlist change (or won't decode, which its dispatcher then DROPs). */ -internal fun playlistIdOf(row: CachedMutationEntity, json: Json): String? = runCatching { - when (row.kind) { - MutationKind.PLAYLIST_APPEND -> - json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId - MutationKind.PLAYLIST_CREATE -> - json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id - MutationKind.PLAYLIST_UPDATE -> - json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId - MutationKind.PLAYLIST_DELETE -> - json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId - MutationKind.PLAYLIST_REMOVE_TRACK -> - json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId - MutationKind.PLAYLIST_REORDER -> - json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId - else -> null - } -}.getOrNull() +internal fun playlistIdOf( + row: CachedMutationEntity, + json: Json, +): String? = + runCatching { + when (row.kind) { + MutationKind.PLAYLIST_APPEND -> + json.decodeFromString(PlaylistAppendPayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_CREATE -> + json.decodeFromString(PlaylistCreatePayload.serializer(), row.payload).id + MutationKind.PLAYLIST_UPDATE -> + json.decodeFromString(PlaylistUpdatePayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_DELETE -> + json.decodeFromString(PlaylistDeletePayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_REMOVE_TRACK -> + json.decodeFromString(PlaylistRemoveTrackPayload.serializer(), row.payload).playlistId + MutationKind.PLAYLIST_REORDER -> + json.decodeFromString(PlaylistReorderPayload.serializer(), row.payload).playlistId + else -> null + } + }.getOrNull() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/OfflineWriteHintViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/OfflineWriteHintViewModel.kt index b1632ef3..7f7fb830 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/OfflineWriteHintViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/OfflineWriteHintViewModel.kt @@ -13,8 +13,10 @@ import javax.inject.Inject * accessor. Mirrors PlaybackErrorViewModel. */ @HiltViewModel -class OfflineWriteHintViewModel @Inject constructor( - mutationQueue: MutationQueue, -) : ViewModel() { - val messages: Flow = mutationQueue.userEnqueueHints -} +class OfflineWriteHintViewModel + @Inject + constructor( + mutationQueue: MutationQueue, + ) : ViewModel() { + val messages: Flow = mutationQueue.userEnqueueHints + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/sync/SyncController.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/sync/SyncController.kt index 40ef2b40..860e0a7f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/sync/SyncController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/sync/SyncController.kt @@ -3,8 +3,6 @@ package com.fabledsword.minstrel.cache.sync import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.api.endpoints.SyncApi import com.fabledsword.minstrel.auth.AuthStore -import com.fabledsword.minstrel.connectivity.NetworkStatusController -import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao @@ -13,6 +11,8 @@ import com.fabledsword.minstrel.cache.db.entities.CachedAlbumEntity import com.fabledsword.minstrel.cache.db.entities.CachedArtistEntity import com.fabledsword.minstrel.cache.db.entities.CachedTrackEntity import com.fabledsword.minstrel.cache.db.entities.SyncMetadataEntity +import com.fabledsword.minstrel.connectivity.NetworkStatusController +import com.fabledsword.minstrel.connectivity.ServerHealth import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.models.wire.SyncAlbumWire import com.fabledsword.minstrel.models.wire.SyncArtistWire @@ -50,199 +50,204 @@ import javax.inject.Singleton * cursor to 0 and pulls the full entity set again (see [resetCursor]). */ @Singleton -class SyncController @Inject constructor( - private val syncMetadataDao: SyncMetadataDao, - private val artistDao: CachedArtistDao, - private val albumDao: CachedAlbumDao, - private val trackDao: CachedTrackDao, - private val authStore: AuthStore, - @ApplicationScope private val scope: CoroutineScope, - networkStatus: NetworkStatusController, - retrofit: Retrofit, -) { - private val api: SyncApi = retrofit.create() - - // Single in-flight guard: the cookie + health-recovery triggers (and a - // pull-to-refresh) can fire concurrently; coalesce them into one pass. - private val mutex = Mutex() - - private val lastSyncErrorInternal = MutableStateFlow(null) - - /** - * Human copy for the most recent sync failure; null after any clean - * pass. Lets the Library screen distinguish "empty because the first - * sync failed" (show error + retry) from "genuinely empty library" - * (show welcome copy) — a failed sync over a populated cache stays - * silent, since the cached content is still the better surface. - */ - val lastSyncError: StateFlow = lastSyncErrorInternal.asStateFlow() - - init { - scope.launch { - authStore.sessionCookie - .filterNotNull() - .distinctUntilChanged() - .collect { syncSafe() } - } - // Re-sync when the server becomes reachable again mid-session, so a - // delta missed while offline lands without waiting for a cold start. - scope.launch { - networkStatus.state - .map { it == ServerHealth.Healthy } - .distinctUntilChanged() - .filter { it } - .collect { syncSafe() } - } - } - - /** Public entry-point for "Sync now" affordances. Swallows errors into [lastSyncError]. */ - suspend fun syncSafe() { - if (!mutex.tryLock()) return - try { - runCatching { sync() } - .onSuccess { lastSyncErrorInternal.value = null } - .onFailure { lastSyncErrorInternal.value = ErrorCopy.fromThrowable(it) } - } finally { - mutex.unlock() - } - } - - /** - * Pulls pages until the server has nothing newer. The server returns - * at most 1000 changes a call, and a full library re-read adds tens - * of thousands, so one page per trigger would leave the cache behind: - * merge deletes would never arrive and the freshness sweep would keep - * asking for tracks that are gone. The cursor is stored after each - * page, so an interrupted pass resumes where it stopped. - */ - private suspend fun sync() { - repeat(MAX_PAGES_PER_PASS) { - if (!syncPage()) return - } - } - - /** One page of the change log. True when the server may hold more. */ - private suspend fun syncPage(): Boolean { - val meta = syncMetadataDao.get() - val cursor = meta?.cursor ?: 0L - val response = api.sync(cursor) - return when (response.code()) { - HTTP_NO_CONTENT -> { - touchLastSyncAt(cursor) - false - } - HTTP_GONE -> { - resetCursor() - true - } - HTTP_OK -> { - val body = response.body() ?: return false - applyDeltas(body.upserts.artist, body.upserts.album, body.upserts.track) - applyDeletes(body.deletes.artist, body.deletes.album, body.deletes.track) - syncMetadataDao.upsert( - SyncMetadataEntity( - id = 0, - cursor = body.cursor, - lastSyncAt = Clock.System.now(), - ), - ) - // A cursor that did not advance would ask for the same page - // again; stop rather than spin. - body.cursor > cursor - } - else -> { - // Unhandled status — treat as a no-op; the next - // app start retries from the same cursor. - false - } - } - } - - private suspend fun applyDeltas( - artists: List, - albums: List, - tracks: List, +class SyncController + @Inject + constructor( + private val syncMetadataDao: SyncMetadataDao, + private val artistDao: CachedArtistDao, + private val albumDao: CachedAlbumDao, + private val trackDao: CachedTrackDao, + private val authStore: AuthStore, + @ApplicationScope private val scope: CoroutineScope, + networkStatus: NetworkStatusController, + retrofit: Retrofit, ) { - if (artists.isNotEmpty()) artistDao.upsertAll(artists.map { it.toEntity() }) - if (albums.isNotEmpty()) albumDao.upsertAll(albums.map { it.toEntity() }) - if (tracks.isNotEmpty()) trackDao.upsertAll(tracks.map { it.toEntity() }) - } + private val api: SyncApi = retrofit.create() - private suspend fun applyDeletes( - artistIds: List, - albumIds: List, - trackIds: List, - ) { - if (artistIds.isNotEmpty()) artistDao.deleteByIds(artistIds) - if (albumIds.isNotEmpty()) albumDao.deleteByIds(albumIds) - if (trackIds.isNotEmpty()) trackDao.deleteByIds(trackIds) - } + // Single in-flight guard: the cookie + health-recovery triggers (and a + // pull-to-refresh) can fire concurrently; coalesce them into one pass. + private val mutex = Mutex() - private suspend fun touchLastSyncAt(cursor: Long) { - syncMetadataDao.upsert( - SyncMetadataEntity(id = 0, cursor = cursor, lastSyncAt = Clock.System.now()), - ) - } + private val lastSyncErrorInternal = MutableStateFlow(null) - private suspend fun resetCursor() { - // The Library DAOs only expose deleteByIds; for the rare 410 - // path the next page is requested with cursor=0 after - // resetting our cursor. The following pages carry the full - // entity set, which upsertAll overwrites the existing rows - // with — old rows for entities the server no longer knows - // about linger until MetadataProvider's refresh meets their - // 404 and drops them. - syncMetadataDao.upsert( - SyncMetadataEntity(id = 0, cursor = 0, lastSyncAt = null), - ) - } + /** + * Human copy for the most recent sync failure; null after any clean + * pass. Lets the Library screen distinguish "empty because the first + * sync failed" (show error + retry) from "genuinely empty library" + * (show welcome copy) — a failed sync over a populated cache stays + * silent, since the cached content is still the better surface. + */ + val lastSyncError: StateFlow = lastSyncErrorInternal.asStateFlow() - private companion object { - const val HTTP_OK = 200 - const val HTTP_NO_CONTENT = 204 - const val HTTP_GONE = 410 + init { + scope.launch { + authStore.sessionCookie + .filterNotNull() + .distinctUntilChanged() + .collect { syncSafe() } + } + // Re-sync when the server becomes reachable again mid-session, so a + // delta missed while offline lands without waiting for a cold start. + scope.launch { + networkStatus.state + .map { it == ServerHealth.Healthy } + .distinctUntilChanged() + .filter { it } + .collect { syncSafe() } + } + } - // A guard, not a budget: 1000 pages is a million changes, far past - // anything a library writes between two app starts. - const val MAX_PAGES_PER_PASS = 1000 + /** Public entry-point for "Sync now" affordances. Swallows errors into [lastSyncError]. */ + suspend fun syncSafe() { + if (!mutex.tryLock()) return + try { + runCatching { sync() } + .onSuccess { lastSyncErrorInternal.value = null } + .onFailure { lastSyncErrorInternal.value = ErrorCopy.fromThrowable(it) } + } finally { + mutex.unlock() + } + } + + /** + * Pulls pages until the server has nothing newer. The server returns + * at most 1000 changes a call, and a full library re-read adds tens + * of thousands, so one page per trigger would leave the cache behind: + * merge deletes would never arrive and the freshness sweep would keep + * asking for tracks that are gone. The cursor is stored after each + * page, so an interrupted pass resumes where it stopped. + */ + private suspend fun sync() { + repeat(MAX_PAGES_PER_PASS) { + if (!syncPage()) return + } + } + + /** One page of the change log. True when the server may hold more. */ + private suspend fun syncPage(): Boolean { + val meta = syncMetadataDao.get() + val cursor = meta?.cursor ?: 0L + val response = api.sync(cursor) + return when (response.code()) { + HTTP_NO_CONTENT -> { + touchLastSyncAt(cursor) + false + } + HTTP_GONE -> { + resetCursor() + true + } + HTTP_OK -> { + val body = response.body() ?: return false + applyDeltas(body.upserts.artist, body.upserts.album, body.upserts.track) + applyDeletes(body.deletes.artist, body.deletes.album, body.deletes.track) + syncMetadataDao.upsert( + SyncMetadataEntity( + id = 0, + cursor = body.cursor, + lastSyncAt = Clock.System.now(), + ), + ) + // A cursor that did not advance would ask for the same page + // again; stop rather than spin. + body.cursor > cursor + } + else -> { + // Unhandled status — treat as a no-op; the next + // app start retries from the same cursor. + false + } + } + } + + private suspend fun applyDeltas( + artists: List, + albums: List, + tracks: List, + ) { + if (artists.isNotEmpty()) artistDao.upsertAll(artists.map { it.toEntity() }) + if (albums.isNotEmpty()) albumDao.upsertAll(albums.map { it.toEntity() }) + if (tracks.isNotEmpty()) trackDao.upsertAll(tracks.map { it.toEntity() }) + } + + private suspend fun applyDeletes( + artistIds: List, + albumIds: List, + trackIds: List, + ) { + if (artistIds.isNotEmpty()) artistDao.deleteByIds(artistIds) + if (albumIds.isNotEmpty()) albumDao.deleteByIds(albumIds) + if (trackIds.isNotEmpty()) trackDao.deleteByIds(trackIds) + } + + private suspend fun touchLastSyncAt(cursor: Long) { + syncMetadataDao.upsert( + SyncMetadataEntity(id = 0, cursor = cursor, lastSyncAt = Clock.System.now()), + ) + } + + private suspend fun resetCursor() { + // The Library DAOs only expose deleteByIds; for the rare 410 + // path the next page is requested with cursor=0 after + // resetting our cursor. The following pages carry the full + // entity set, which upsertAll overwrites the existing rows + // with — old rows for entities the server no longer knows + // about linger until MetadataProvider's refresh meets their + // 404 and drops them. + syncMetadataDao.upsert( + SyncMetadataEntity(id = 0, cursor = 0, lastSyncAt = null), + ) + } + + private companion object { + const val HTTP_OK = 200 + const val HTTP_NO_CONTENT = 204 + const val HTTP_GONE = 410 + + // A guard, not a budget: 1000 pages is a million changes, far past + // anything a library writes between two app starts. + const val MAX_PAGES_PER_PASS = 1000 + } } -} // ── Mappers (file-internal — sync wire types stay out of UI) ── -private fun SyncArtistWire.toEntity(): CachedArtistEntity = CachedArtistEntity( - id = id, - name = name, - sortName = sortName, - mbid = mbid, - artistThumbPath = artistThumbPath, - artistFanartPath = artistFanartPath, -) +private fun SyncArtistWire.toEntity(): CachedArtistEntity = + CachedArtistEntity( + id = id, + name = name, + sortName = sortName, + mbid = mbid, + artistThumbPath = artistThumbPath, + artistFanartPath = artistFanartPath, + ) -private fun SyncAlbumWire.toEntity(): CachedAlbumEntity = CachedAlbumEntity( - id = id, - artistId = artistId, - title = title, - sortTitle = sortTitle, - releaseDate = releaseDate, - coverPath = coverArtPath, - mbid = mbid, - albumGain = albumGain, - albumPeak = albumPeak, -) +private fun SyncAlbumWire.toEntity(): CachedAlbumEntity = + CachedAlbumEntity( + id = id, + artistId = artistId, + title = title, + sortTitle = sortTitle, + releaseDate = releaseDate, + coverPath = coverArtPath, + mbid = mbid, + albumGain = albumGain, + albumPeak = albumPeak, + ) -private fun SyncTrackWire.toEntity(): CachedTrackEntity = CachedTrackEntity( - id = id, - albumId = albumId, - artistId = artistId, - title = title, - durationMs = durationMs, - trackNumber = trackNumber, - discNumber = discNumber, - filePath = filePath, - fileFormat = fileFormat, - genre = genre, - missing = missing, - trackGain = trackGain, - trackPeak = trackPeak, -) +private fun SyncTrackWire.toEntity(): CachedTrackEntity = + CachedTrackEntity( + id = id, + albumId = albumId, + artistId = artistId, + title = title, + durationMs = durationMs, + trackNumber = trackNumber, + discNumber = discNumber, + filePath = filePath, + fileFormat = fileFormat, + genre = genre, + missing = missing, + trackGain = trackGain, + trackPeak = trackPeak, + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ConnectivityObserver.kt b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ConnectivityObserver.kt index bf6ea705..1398f0f1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ConnectivityObserver.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ConnectivityObserver.kt @@ -36,76 +36,87 @@ import javax.inject.Singleton * repositories can also collect this to gate retry loops. */ @Singleton -class ConnectivityObserver @Inject constructor( - @ApplicationContext context: Context, -) { - private val cm = context.getSystemService(ConnectivityManager::class.java) +class ConnectivityObserver + @Inject + constructor( + @ApplicationContext context: Context, + ) { + private val cm = context.getSystemService(ConnectivityManager::class.java) - val online: Flow = callbackFlow { - val request = NetworkRequest.Builder() - .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - .build() - val callback = object : ConnectivityManager.NetworkCallback() { - override fun onAvailable(network: Network) { + val online: Flow = + callbackFlow { + val request = + NetworkRequest + .Builder() + .addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) + .build() + val callback = + object : ConnectivityManager.NetworkCallback() { + override fun onAvailable(network: Network) { + trySend(hasActiveNetwork()) + } + + override fun onLost(network: Network) { + trySend(hasActiveNetwork()) + } + + override fun onCapabilitiesChanged( + network: Network, + capabilities: NetworkCapabilities, + ) { + // INTERNET only -- NOT VALIDATED. A WAN/validation flicker + // must not read as "device offline" when the LAN (and the + // Minstrel server on it) is still reachable. /healthz is the + // authority on server reachability. + trySend( + capabilities.hasCapability( + NetworkCapabilities.NET_CAPABILITY_INTERNET, + ), + ) + } + } + cm.registerNetworkCallback(request, callback) + // Seed the initial value so the banner doesn't flash before the + // first capability callback fires. trySend(hasActiveNetwork()) - } - override fun onLost(network: Network) { - trySend(hasActiveNetwork()) - } - override fun onCapabilitiesChanged( - network: Network, - capabilities: NetworkCapabilities, - ) { - // INTERNET only -- NOT VALIDATED. A WAN/validation flicker - // must not read as "device offline" when the LAN (and the - // Minstrel server on it) is still reachable. /healthz is the - // authority on server reachability. - trySend( - capabilities.hasCapability( - NetworkCapabilities.NET_CAPABILITY_INTERNET, - ), - ) - } + awaitClose { cm.unregisterNetworkCallback(callback) } + }.distinctUntilChanged() + + /** + * Whether the network the device is using now is unmetered: Wi-Fi or + * Ethernet, but not mobile data or a hotspot Android marks metered. + * Downloads the user did not start (the liked-song downloads) wait for + * this. + */ + val unmetered: Flow = + callbackFlow { + val callback = + object : ConnectivityManager.NetworkCallback() { + override fun onCapabilitiesChanged( + network: Network, + capabilities: NetworkCapabilities, + ) { + trySend(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) + } + + override fun onLost(network: Network) { + trySend(false) + } + } + cm.registerDefaultNetworkCallback(callback) + trySend(isActiveNetworkUnmetered()) + awaitClose { cm.unregisterNetworkCallback(callback) } + }.distinctUntilChanged() + + private fun isActiveNetworkUnmetered(): Boolean { + val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) } + return caps != null && + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) } - cm.registerNetworkCallback(request, callback) - // Seed the initial value so the banner doesn't flash before the - // first capability callback fires. - trySend(hasActiveNetwork()) - awaitClose { cm.unregisterNetworkCallback(callback) } - }.distinctUntilChanged() - /** - * Whether the network the device is using now is unmetered: Wi-Fi or - * Ethernet, but not mobile data or a hotspot Android marks metered. - * Downloads the user did not start (the liked-song downloads) wait for - * this. - */ - val unmetered: Flow = callbackFlow { - val callback = object : ConnectivityManager.NetworkCallback() { - override fun onCapabilitiesChanged( - network: Network, - capabilities: NetworkCapabilities, - ) { - trySend(capabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) - } - override fun onLost(network: Network) { - trySend(false) - } + private fun hasActiveNetwork(): Boolean { + val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) } + return caps != null && + caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) } - cm.registerDefaultNetworkCallback(callback) - trySend(isActiveNetworkUnmetered()) - awaitClose { cm.unregisterNetworkCallback(callback) } - }.distinctUntilChanged() - - private fun isActiveNetworkUnmetered(): Boolean { - val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) } - return caps != null && - caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED) } - - private fun hasActiveNetwork(): Boolean { - val caps = cm.activeNetwork?.let { cm.getNetworkCapabilities(it) } - return caps != null && - caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET) - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/NetworkStatusController.kt b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/NetworkStatusController.kt index b01f8d3e..d1211755 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/NetworkStatusController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/NetworkStatusController.kt @@ -55,140 +55,155 @@ private const val ARBITRATE_MIN_GAP_MS = 2_000L * [com.fabledsword.minstrel.MinstrelApplication]. */ @Singleton -class NetworkStatusController @Inject constructor( - @ApplicationScope private val scope: CoroutineScope, - connectivity: ConnectivityObserver, - private val authStore: AuthStore, - retrofit: Retrofit, -) : DefaultLifecycleObserver { - private val api: HealthzApi = retrofit.create(HealthzApi::class.java) - private val machine = ReachabilityMachine() - private val lastProbeAtMs = AtomicLong(0) +class NetworkStatusController + @Inject + constructor( + @ApplicationScope private val scope: CoroutineScope, + connectivity: ConnectivityObserver, + private val authStore: AuthStore, + retrofit: Retrofit, + ) : DefaultLifecycleObserver { + private val api: HealthzApi = retrofit.create(HealthzApi::class.java) + private val machine = ReachabilityMachine() + private val lastProbeAtMs = AtomicLong(0) - private val stateInternal = MutableStateFlow(ServerHealth.Healthy) - val state: StateFlow = stateInternal.asStateFlow() + private val stateInternal = MutableStateFlow(ServerHealth.Healthy) + val state: StateFlow = stateInternal.asStateFlow() - private val versionInternal = MutableStateFlow(VersionResult.SKIPPED) - val versionResult: StateFlow = versionInternal.asStateFlow() + private val versionInternal = MutableStateFlow(VersionResult.SKIPPED) + val versionResult: StateFlow = versionInternal.asStateFlow() - private sealed interface Intent { - data class Link(val up: Boolean) : Intent - data class Probe(val resp: HealthzResponse?) : Intent - object OpSuccess : Intent - object OpFailure : Intent - } + private sealed interface Intent { + data class Link( + val up: Boolean, + ) : Intent - private val intents = Channel(Channel.UNLIMITED) + data class Probe( + val resp: HealthzResponse?, + ) : Intent - init { - ProcessLifecycleOwner.get().lifecycle.addObserver(this) - scope.launch { reduceLoop() } - scope.launch { - connectivity.online.collect { up -> - intents.trySend(Intent.Link(up)) - if (up) probeOnce() - } + object OpSuccess : Intent + + object OpFailure : Intent } - scope.launch { pollLoop() } - } - /** A real server op verifiably succeeded — self-proving recovery. Cheap; safe on hot paths. */ - fun reportSuccess() { - if (stateInternal.value != ServerHealth.Healthy) intents.trySend(Intent.OpSuccess) - } + private val intents = Channel(Channel.UNLIMITED) - /** A real network op failed — triggers /healthz arbitration. No-op when already Offline. */ - fun reportFailure() { - if (stateInternal.value == ServerHealth.Offline) return - intents.trySend(Intent.OpFailure) - } - - /** One-shot recheck for pull-to-refresh and the banner. */ - fun recheck() { - scope.launch { probeOnce(force = true) } - } - - /** - * App returned to the foreground — probe now rather than waiting for the - * poll loop. - * - * The link-return probe in `init` does NOT cover this: it fires on a - * connectivity *change*, and an app backgrounded on stable Wi-Fi sees none. - * force = true so this also bypasses the ARBITRATE_MIN_GAP_MS throttle — - * a user bringing the app up is exactly when a stale banner and a refused - * track are most visible, and it's a once-per-foreground cost. - */ - override fun onStart(owner: LifecycleOwner) { - recheck() - } - - private suspend fun reduceLoop() { - for (intent in intents) { - val now = System.currentTimeMillis() - when (intent) { - is Intent.Link -> machine.onLinkChange(intent.up) - is Intent.Probe -> applyProbe(intent.resp, now) - Intent.OpSuccess -> machine.onSuccess() - Intent.OpFailure -> { - machine.onOpFailure(now) - // Arbitrate off the reducer thread: awaiting a stalled - // /healthz here would block a concurrent self-proving - // success from snapping us straight back to Healthy. - scope.launch { probeOnce() } + init { + ProcessLifecycleOwner.get().lifecycle.addObserver(this) + scope.launch { reduceLoop() } + scope.launch { + connectivity.online.collect { up -> + intents.trySend(Intent.Link(up)) + if (up) probeOnce() } } - emit(machine.health()) + scope.launch { pollLoop() } } - } - private fun applyProbe(resp: HealthzResponse?, now: Long) { - if (resp == null) { - machine.onProbeFailure(now) - } else { - machine.onSuccess() - versionInternal.value = versionResultFor(resp) + /** A real server op verifiably succeeded — self-proving recovery. Cheap; safe on hot paths. */ + fun reportSuccess() { + if (stateInternal.value != ServerHealth.Healthy) intents.trySend(Intent.OpSuccess) } - } - private fun emit(next: ServerHealth) { - if (stateInternal.value != next) { - Timber.w("NetworkStatus -> %s", next) - stateInternal.value = next + /** A real network op failed — triggers /healthz arbitration. No-op when already Offline. */ + fun reportFailure() { + if (stateInternal.value == ServerHealth.Offline) return + intents.trySend(Intent.OpFailure) } - } - private suspend fun pollLoop() { - probeOnce() - while (true) { - val interval = - if (stateInternal.value == ServerHealth.Healthy) POLL_HEALTHY_MS - else POLL_DEGRADED_MS - delay(interval) + /** One-shot recheck for pull-to-refresh and the banner. */ + fun recheck() { + scope.launch { probeOnce(force = true) } + } + + /** + * App returned to the foreground — probe now rather than waiting for the + * poll loop. + * + * The link-return probe in `init` does NOT cover this: it fires on a + * connectivity *change*, and an app backgrounded on stable Wi-Fi sees none. + * force = true so this also bypasses the ARBITRATE_MIN_GAP_MS throttle — + * a user bringing the app up is exactly when a stale banner and a refused + * track are most visible, and it's a once-per-foreground cost. + */ + override fun onStart(owner: LifecycleOwner) { + recheck() + } + + private suspend fun reduceLoop() { + for (intent in intents) { + val now = System.currentTimeMillis() + when (intent) { + is Intent.Link -> machine.onLinkChange(intent.up) + is Intent.Probe -> applyProbe(intent.resp, now) + Intent.OpSuccess -> machine.onSuccess() + Intent.OpFailure -> { + machine.onOpFailure(now) + // Arbitrate off the reducer thread: awaiting a stalled + // /healthz here would block a concurrent self-proving + // success from snapping us straight back to Healthy. + scope.launch { probeOnce() } + } + } + emit(machine.health()) + } + } + + private fun applyProbe( + resp: HealthzResponse?, + now: Long, + ) { + if (resp == null) { + machine.onProbeFailure(now) + } else { + machine.onSuccess() + versionInternal.value = versionResultFor(resp) + } + } + + private fun emit(next: ServerHealth) { + if (stateInternal.value != next) { + Timber.w("NetworkStatus -> %s", next) + stateInternal.value = next + } + } + + private suspend fun pollLoop() { probeOnce() + while (true) { + val interval = + if (stateInternal.value == ServerHealth.Healthy) { + POLL_HEALTHY_MS + } else { + POLL_DEGRADED_MS + } + delay(interval) + probeOnce() + } + } + + private suspend fun probeOnce(force: Boolean = false) { + // Startup guard: don't poll the localhost placeholder before AuthStore + // hydrates the real base URL — that false failure would flash the banner. + if (authStore.baseUrl.value == AuthStore.DEFAULT_BASE_URL) return + val now = System.currentTimeMillis() + if (!force && now - lastProbeAtMs.get() < ARBITRATE_MIN_GAP_MS) return + lastProbeAtMs.set(now) + val resp = runCatching { api.check() }.getOrNull() + intents.trySend(Intent.Probe(resp)) + } + + private fun versionResultFor(resp: HealthzResponse): VersionResult { + val min = resp.minClientVersion + return when { + min.isEmpty() -> VersionResult.SKIPPED + isVersionNewer(min, BuildConfig.VERSION_NAME) -> VersionResult.TOO_OLD + else -> VersionResult.OK + } } } - private suspend fun probeOnce(force: Boolean = false) { - // Startup guard: don't poll the localhost placeholder before AuthStore - // hydrates the real base URL — that false failure would flash the banner. - if (authStore.baseUrl.value == AuthStore.DEFAULT_BASE_URL) return - val now = System.currentTimeMillis() - if (!force && now - lastProbeAtMs.get() < ARBITRATE_MIN_GAP_MS) return - lastProbeAtMs.set(now) - val resp = runCatching { api.check() }.getOrNull() - intents.trySend(Intent.Probe(resp)) - } - - private fun versionResultFor(resp: HealthzResponse): VersionResult { - val min = resp.minClientVersion - return when { - min.isEmpty() -> VersionResult.SKIPPED - isVersionNewer(min, BuildConfig.VERSION_NAME) -> VersionResult.TOO_OLD - else -> VersionResult.OK - } - } -} - /** * Reactive [ServerHealth] snapshot provided once at the app root. Lets leaf * composables (TrackRow gating, write-affordance disabling) branch on health diff --git a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ReachabilityMachine.kt b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ReachabilityMachine.kt index 3aff5458..44e49d7e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ReachabilityMachine.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ReachabilityMachine.kt @@ -41,7 +41,6 @@ internal const val CORROBORATION_MIN_SPACING_MS = 3_000L * sustained-time backstop. */ class ReachabilityMachine { - private enum class Reachability { Reachable, Unstable, Unreachable } private var linkUp = true @@ -89,12 +88,13 @@ class ReachabilityMachine { } } - fun health(): ServerHealth = when { - !linkUp -> ServerHealth.Offline - reachability == Reachability.Reachable -> ServerHealth.Healthy - reachability == Reachability.Unstable -> ServerHealth.Unstable - else -> ServerHealth.ServerDown - } + fun health(): ServerHealth = + when { + !linkUp -> ServerHealth.Offline + reachability == Reachability.Reachable -> ServerHealth.Healthy + reachability == Reachability.Unstable -> ServerHealth.Unstable + else -> ServerHealth.ServerDown + } private fun shouldEscalate(nowMs: Long): Boolean { val corroborated = recentOpFailures.size >= CORROBORATION_OP_THRESHOLD diff --git a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ReachabilityReportingInterceptor.kt b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ReachabilityReportingInterceptor.kt index c7d98c8b..ce7dff39 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ReachabilityReportingInterceptor.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ReachabilityReportingInterceptor.kt @@ -29,21 +29,23 @@ private const val HEALTHZ_PATH = "/healthz" * already constructed (construct-the-singleton trick in MinstrelApplication). */ @Singleton -class ReachabilityReportingInterceptor @Inject constructor( - private val networkStatus: Lazy, -) : Interceptor { - override fun intercept(chain: Interceptor.Chain): Response { - val request = chain.request() - val isMinstrel = request.url.host == PLACEHOLDER_HOST - val isHealthz = request.url.encodedPath.endsWith(HEALTHZ_PATH) - if (!isMinstrel || isHealthz) return chain.proceed(request) - return try { - val response = chain.proceed(request) - if (response.isSuccessful) networkStatus.get().reportSuccess() - response - } catch (e: IOException) { - networkStatus.get().reportFailure() - throw e +class ReachabilityReportingInterceptor + @Inject + constructor( + private val networkStatus: Lazy, + ) : Interceptor { + override fun intercept(chain: Interceptor.Chain): Response { + val request = chain.request() + val isMinstrel = request.url.host == PLACEHOLDER_HOST + val isHealthz = request.url.encodedPath.endsWith(HEALTHZ_PATH) + if (!isMinstrel || isHealthz) return chain.proceed(request) + return try { + val response = chain.proceed(request) + if (response.isSuccessful) networkStatus.get().reportSuccess() + response + } catch (e: IOException) { + networkStatus.get().reportFailure() + throw e + } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/Recovery.kt b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/Recovery.kt index b29681ff..2bcdc346 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/Recovery.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/Recovery.kt @@ -19,9 +19,10 @@ import kotlinx.coroutines.flow.map * heals itself the moment connectivity returns instead of sitting in the * failed state until a manual pull-to-refresh. */ -fun NetworkStatusController.recoveries(): Flow = state - .map { it == ServerHealth.Healthy } - .distinctUntilChanged() - .drop(1) - .filter { it } - .map { } +fun NetworkStatusController.recoveries(): Flow = + state + .map { it == ServerHealth.Healthy } + .distinctUntilChanged() + .drop(1) + .filter { it } + .map { } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ui/ConnectionErrorBanner.kt b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ui/ConnectionErrorBanner.kt index 2d1eef2f..dee8ff40 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ui/ConnectionErrorBanner.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/connectivity/ui/ConnectionErrorBanner.kt @@ -43,12 +43,14 @@ private const val BACK_ONLINE_FLASH_MS = 2_000L * re-wrapping StateFlow — the controller's is already app-scoped and warm. */ @HiltViewModel -class ConnectivityBannerViewModel @Inject constructor( - networkStatus: NetworkStatusController, - @Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle, -) : ViewModel() { - val health: StateFlow = networkStatus.state -} +class ConnectivityBannerViewModel + @Inject + constructor( + networkStatus: NetworkStatusController, + @Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle, + ) : ViewModel() { + val health: StateFlow = networkStatus.state + } /** * Shell banner. Tells the user *why* they're degraded — no link vs server-down @@ -57,9 +59,7 @@ class ConnectivityBannerViewModel @Inject constructor( * recovery is unmistakable. Sentence case, understated voice (design system). */ @Composable -fun ConnectionErrorBanner( - viewModel: ConnectivityBannerViewModel = hiltViewModel(), -) { +fun ConnectionErrorBanner(viewModel: ConnectivityBannerViewModel = hiltViewModel()) { val health by viewModel.health.collectAsStateWithLifecycle() var showBackOnline by remember { mutableStateOf(false) } var wasDown by remember { mutableStateOf(false) } @@ -89,7 +89,10 @@ fun ConnectionErrorBanner( } @Composable -private fun BannerContent(health: ServerHealth, backOnline: Boolean) { +private fun BannerContent( + health: ServerHealth, + backOnline: Boolean, +) { val scheme = MaterialTheme.colorScheme val background: Color val foreground: Color @@ -108,10 +111,11 @@ private fun BannerContent(health: ServerHealth, backOnline: Boolean) { } } Row( - modifier = Modifier - .fillMaxWidth() - .background(background) - .padding(horizontal = 16.dp, vertical = 10.dp), + modifier = + Modifier + .fillMaxWidth() + .background(background) + .padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { @@ -124,11 +128,15 @@ private fun BannerContent(health: ServerHealth, backOnline: Boolean) { } } -private fun bannerText(health: ServerHealth, backOnline: Boolean): String = when { - backOnline -> "Back online." - health == ServerHealth.Offline -> "No connection — check Wi-Fi or mobile data." - health == ServerHealth.ServerDown -> - "Server unreachable — your cached content is still available." - health == ServerHealth.Unstable -> "Reconnecting…" - else -> "" -} +private fun bannerText( + health: ServerHealth, + backOnline: Boolean, +): String = + when { + backOnline -> "Back online." + health == ServerHealth.Offline -> "No connection — check Wi-Fi or mobile data." + health == ServerHealth.ServerDown -> + "Server unreachable — your cached content is still available." + health == ServerHealth.Unstable -> "Reconnecting…" + else -> "" + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/di/AppModule.kt b/android/app/src/main/java/com/fabledsword/minstrel/di/AppModule.kt index 1add2f76..bb7de8ff 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/di/AppModule.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/di/AppModule.kt @@ -20,11 +20,12 @@ annotation class ApplicationScope object AppModule { @Provides @Singleton - fun provideJson(): Json = Json { - ignoreUnknownKeys = true - explicitNulls = false - coerceInputValues = true - } + fun provideJson(): Json = + Json { + ignoreUnknownKeys = true + explicitNulls = false + coerceInputValues = true + } @Provides @Singleton diff --git a/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsReporter.kt b/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsReporter.kt index 9bff541b..5707caa1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsReporter.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsReporter.kt @@ -5,9 +5,9 @@ import android.content.Context import android.content.Intent import android.content.IntentFilter import android.os.PowerManager +import androidx.core.content.ContextCompat import androidx.lifecycle.DefaultLifecycleObserver import androidx.lifecycle.LifecycleOwner -import androidx.core.content.ContextCompat import androidx.lifecycle.ProcessLifecycleOwner import com.fabledsword.minstrel.auth.AuthController import com.fabledsword.minstrel.auth.AuthStore @@ -52,338 +52,388 @@ import javax.inject.Singleton */ @Suppress("TooManyFunctions") // one collector + one (un)register pair per signal; cohesive @Singleton -class DiagnosticsReporter @Inject constructor( - @ApplicationContext private val context: Context, - @ApplicationScope private val scope: CoroutineScope, - private val dao: DiagnosticEventDao, - private val authController: AuthController, - private val authStore: AuthStore, - private val connectivity: ConnectivityObserver, - private val networkStatus: NetworkStatusController, - private val playerController: PlayerController, - private val outputPicker: OutputPickerController, - private val remoteState: RemotePlayerState, - private val json: Json, -) { - @Volatile private var enabled = false - private var collectorJob: Job? = null - private var powerReceiver: BroadcastReceiver? = null - private var lifecycleObserver: DefaultLifecycleObserver? = null +class DiagnosticsReporter + @Inject + constructor( + @ApplicationContext private val context: Context, + @ApplicationScope private val scope: CoroutineScope, + private val dao: DiagnosticEventDao, + private val authController: AuthController, + private val authStore: AuthStore, + private val connectivity: ConnectivityObserver, + private val networkStatus: NetworkStatusController, + private val playerController: PlayerController, + private val outputPicker: OutputPickerController, + private val remoteState: RemotePlayerState, + private val json: Json, + ) { + @Volatile private var enabled = false + private var collectorJob: Job? = null + private var powerReceiver: BroadcastReceiver? = null + private var lifecycleObserver: DefaultLifecycleObserver? = null - init { - // Gate = account flag (currentUser.debugModeEnabled) AND not the - // per-device local opt-out. - scope.launch { - combine(authController.currentUser, authStore.diagnosticsOptOut) { user, optOut -> - (user?.debugModeEnabled == true) && !optOut - }.distinctUntilChanged().collect { setEnabled(it) } - } - // Periodically re-pull /me so a remote admin flip propagates - // without a re-login or app restart. - scope.launch { - while (true) { - delay(GATE_REFRESH_MS) - authController.refreshProfile() + init { + // Gate = account flag (currentUser.debugModeEnabled) AND not the + // per-device local opt-out. + scope.launch { + combine(authController.currentUser, authStore.diagnosticsOptOut) { user, optOut -> + (user?.debugModeEnabled == true) && !optOut + }.distinctUntilChanged().collect { setEnabled(it) } + } + // Periodically re-pull /me so a remote admin flip propagates + // without a re-login or app restart. + scope.launch { + while (true) { + delay(GATE_REFRESH_MS) + authController.refreshProfile() + } } } - } - private fun setEnabled(value: Boolean) { - if (value == enabled) return - enabled = value - if (value) start() else stop() - } - - private fun start() { - registerPowerReceiver() - registerLifecycleObserver() - collectorJob = scope.launch { - record("lifecycle", buildJsonObject { put("event", "reporting_started") }) - launch { collectConnectivity() } - launch { collectServerHealth() } - launch { collectUpnpDrops() } - launch { collectPlayerState() } - launch { collectTrackChanges() } - launch { collectTransportFlap() } - launch { collectRoutes() } - launch { heartbeatLoop() } + private fun setEnabled(value: Boolean) { + if (value == enabled) return + enabled = value + if (value) start() else stop() } - } - private fun stop() { - collectorJob?.cancel() - collectorJob = null - unregisterPowerReceiver() - unregisterLifecycleObserver() - // Off means off: drop any unsent buffer (honors the user OFF - // intent and avoids leaking data captured before disable). - scope.launch { runCatching { dao.clear() } } - } - - private suspend fun collectConnectivity() { - connectivity.online.distinctUntilChanged().collect { online -> - record("connectivity", buildJsonObject { - put("event", "online_changed") - put("online", online) - }) + private fun start() { + registerPowerReceiver() + registerLifecycleObserver() + collectorJob = + scope.launch { + record("lifecycle", buildJsonObject { put("event", "reporting_started") }) + launch { collectConnectivity() } + launch { collectServerHealth() } + launch { collectUpnpDrops() } + launch { collectPlayerState() } + launch { collectTrackChanges() } + launch { collectTransportFlap() } + launch { collectRoutes() } + launch { heartbeatLoop() } + } } - } - private suspend fun collectServerHealth() { - // state is a StateFlow — already conflated/distinct, so no - // distinctUntilChanged (it's a deprecation warning = build error). - networkStatus.state.collect { s -> - record("connectivity", buildJsonObject { - put("event", "server_health") - put("state", s.name) - }) + private fun stop() { + collectorJob?.cancel() + collectorJob = null + unregisterPowerReceiver() + unregisterLifecycleObserver() + // Off means off: drop any unsent buffer (honors the user OFF + // intent and avoids leaking data captured before disable). + scope.launch { runCatching { dao.clear() } } } - } - private suspend fun collectUpnpDrops() { - playerController.dropEvents.collect { msg -> - record("upnp_sync", buildJsonObject { - put("event", "drop") - put("message", msg) - }) - } - } - - private suspend fun collectPlayerState() { - // 'playback', not 'upnp_sync' — player state applies to every output - // route (phone speaker, Bluetooth, UPnP), not just casting. - playerController.uiState - .map { Triple(it.currentSource, it.isUpnpLoading, it.playbackError) } - .distinctUntilChanged() - .collect { (source, upnpLoading, err) -> - record("playback", buildJsonObject { - put("event", "player_state") - put("source", source ?: "") - put("upnp_loading", upnpLoading) - if (err != null) put("error", err) - }) + private suspend fun collectConnectivity() { + connectivity.online.distinctUntilChanged().collect { online -> + record( + "connectivity", + buildJsonObject { + put("event", "online_changed") + put("online", online) + }, + ) } - } + } - // Emit a snapshot at each track/queue-index change — captures a - // skip-induced local↔Sonos desync at the INSTANT it happens, which the - // 45s heartbeat misses. Note: uiState is a conflated StateFlow, so a - // very rapid skip burst may coalesce intermediate indices (we still get - // the boundaries + the local-vs-Sonos snapshot). - private suspend fun collectTrackChanges() { - playerController.uiState - .map { it.queueIndex to it.currentTrack?.id } - .distinctUntilChanged() - .collect { (index, _) -> - val ui = playerController.uiState.value - val casting = outputPicker.routesState.value.current.protocol != + private suspend fun collectServerHealth() { + // state is a StateFlow — already conflated/distinct, so no + // distinctUntilChanged (it's a deprecation warning = build error). + networkStatus.state.collect { s -> + record( + "connectivity", + buildJsonObject { + put("event", "server_health") + put("state", s.name) + }, + ) + } + } + + private suspend fun collectUpnpDrops() { + playerController.dropEvents.collect { msg -> + record( + "upnp_sync", + buildJsonObject { + put("event", "drop") + put("message", msg) + }, + ) + } + } + + private suspend fun collectPlayerState() { + // 'playback', not 'upnp_sync' — player state applies to every output + // route (phone speaker, Bluetooth, UPnP), not just casting. + playerController.uiState + .map { Triple(it.currentSource, it.isUpnpLoading, it.playbackError) } + .distinctUntilChanged() + .collect { (source, upnpLoading, err) -> + record( + "playback", + buildJsonObject { + put("event", "player_state") + put("source", source ?: "") + put("upnp_loading", upnpLoading) + if (err != null) put("error", err) + }, + ) + } + } + + // Emit a snapshot at each track/queue-index change — captures a + // skip-induced local↔Sonos desync at the INSTANT it happens, which the + // 45s heartbeat misses. Note: uiState is a conflated StateFlow, so a + // very rapid skip burst may coalesce intermediate indices (we still get + // the boundaries + the local-vs-Sonos snapshot). + private suspend fun collectTrackChanges() { + playerController.uiState + .map { it.queueIndex to it.currentTrack?.id } + .distinctUntilChanged() + .collect { (index, _) -> + val ui = playerController.uiState.value + val casting = + outputPicker.routesState.value.current.protocol != + OutputRoute.Protocol.SYSTEM + record( + "playback", + buildJsonObject { + put("event", "track_change") + put("local_index", index) + // Track IDENTITY, not just index — indices wobble across + // re-casts, so the id + Sonos URI make a desync unambiguous. + put("local_track_id", ui.currentTrack?.id ?: "") + put("local_pos_ms", ui.positionMs) + putSonos(this, casting) + put("upnp_loading", ui.isUpnpLoading) + put("server_health", networkStatus.state.value.name) + put("route", outputPicker.routesState.value.current.name) + }, + ) + } + } + + /** + * Catch the renderer rapidly leaving and re-entering PLAYING. + * + * The symptom: a Sonos rapidly play-pause-play-pausing, about every half + * second, usually as a track starts, cleared by a manual pause or skip. + * No other collector sees it: `player_state` carries + * source/loading/error but not playing, `track_change` needs the index + * to move, and the heartbeat samples once per 45s. + * + * Records every raw transport change (cheap — steady playback produces + * a couple per track) and, when they come in a burst, one summary event + * carrying the whole sequence. The summary is the useful artefact: it + * pairs the renderer's states with local-vs-Sonos track and position, so + * an episode says whether the app and the renderer disagreed about which + * track was playing, or agreed while the renderer rebuffered. + * + * See [TransportObservation] on the 1 Hz sampling limit. + */ + private suspend fun collectTransportFlap() { + val detector = TransportFlapDetector() + playerController.transportEvents.collect { obs -> + record( + "upnp_sync", + buildJsonObject { + put("event", "transport") + put("state", obs.state) + put("status_ok", obs.statusOk) + put("sonos_track", obs.trackNumber) + put("sonos_pos_ms", obs.positionMs) + put("play_intent", obs.playIntent) + }, + ) + detector.onChange(obs)?.let { recordFlapSummary(it) } + } + } + + private suspend fun recordFlapSummary(recent: List) { + val ui = playerController.uiState.value + val casting = + outputPicker.routesState.value.current.protocol != OutputRoute.Protocol.SYSTEM - record("playback", buildJsonObject { - put("event", "track_change") - put("local_index", index) - // Track IDENTITY, not just index — indices wobble across - // re-casts, so the id + Sonos URI make a desync unambiguous. + val spanMs = recent.last().atElapsedMs - recent.first().atElapsedMs + record( + "upnp_sync", + buildJsonObject { + put("event", "transport_flap") + put("changes", recent.size) + put("window_ms", spanMs) + // The sequence itself, e.g. "PLAYING>TRANSITIONING>STOPPED>PLAYING". + // Whether STOPPED appears at all is the first question to ask of a + // captured episode. + put("sequence", recent.joinToString(">") { it.state }) + put("sonos_positions_ms", recent.joinToString(",") { it.positionMs.toString() }) + put("sonos_tracks", recent.joinToString(",") { it.trackNumber.toString() }) + put("local_index", ui.queueIndex) put("local_track_id", ui.currentTrack?.id ?: "") put("local_pos_ms", ui.positionMs) putSonos(this, casting) put("upnp_loading", ui.isUpnpLoading) put("server_health", networkStatus.state.value.name) put("route", outputPicker.routesState.value.current.name) - }) - } - } - - /** - * Catch the renderer rapidly leaving and re-entering PLAYING. - * - * The symptom: a Sonos rapidly play-pause-play-pausing, about every half - * second, usually as a track starts, cleared by a manual pause or skip. - * No other collector sees it: `player_state` carries - * source/loading/error but not playing, `track_change` needs the index - * to move, and the heartbeat samples once per 45s. - * - * Records every raw transport change (cheap — steady playback produces - * a couple per track) and, when they come in a burst, one summary event - * carrying the whole sequence. The summary is the useful artefact: it - * pairs the renderer's states with local-vs-Sonos track and position, so - * an episode says whether the app and the renderer disagreed about which - * track was playing, or agreed while the renderer rebuffered. - * - * See [TransportObservation] on the 1 Hz sampling limit. - */ - private suspend fun collectTransportFlap() { - val detector = TransportFlapDetector() - playerController.transportEvents.collect { obs -> - record("upnp_sync", buildJsonObject { - put("event", "transport") - put("state", obs.state) - put("status_ok", obs.statusOk) - put("sonos_track", obs.trackNumber) - put("sonos_pos_ms", obs.positionMs) - put("play_intent", obs.playIntent) - }) - detector.onChange(obs)?.let { recordFlapSummary(it) } - } - } - - private suspend fun recordFlapSummary(recent: List) { - val ui = playerController.uiState.value - val casting = outputPicker.routesState.value.current.protocol != - OutputRoute.Protocol.SYSTEM - val spanMs = recent.last().atElapsedMs - recent.first().atElapsedMs - record("upnp_sync", buildJsonObject { - put("event", "transport_flap") - put("changes", recent.size) - put("window_ms", spanMs) - // The sequence itself, e.g. "PLAYING>TRANSITIONING>STOPPED>PLAYING". - // Whether STOPPED appears at all is the first question to ask of a - // captured episode. - put("sequence", recent.joinToString(">") { it.state }) - put("sonos_positions_ms", recent.joinToString(",") { it.positionMs.toString() }) - put("sonos_tracks", recent.joinToString(",") { it.trackNumber.toString() }) - put("local_index", ui.queueIndex) - put("local_track_id", ui.currentTrack?.id ?: "") - put("local_pos_ms", ui.positionMs) - putSonos(this, casting) - put("upnp_loading", ui.isUpnpLoading) - put("server_health", networkStatus.state.value.name) - put("route", outputPicker.routesState.value.current.name) - addPowerFields(this) - }) - } - - private suspend fun collectRoutes() { - // 'playback' — route changes happen for all outputs. This only ever - // logs the ACTIVE route (routesState.current), so no "connected" flag. - outputPicker.routesState.map { it.current }.distinctUntilChanged().collect { r -> - record("playback", buildJsonObject { - put("event", "route") - put("id", r.id) - put("name", r.name) - put("kind", r.kind.name) - put("protocol", r.protocol.name) - }) - } - } - - private suspend fun heartbeatLoop() { - while (true) { - delay(HEARTBEAT_MS) - val ui = playerController.uiState.value - val route = outputPicker.routesState.value.current - val routeActive = route.protocol != OutputRoute.Protocol.SYSTEM - // Idle = nothing worth sampling. Skip to keep the buffer lean. - if (!ui.isPlaying && !routeActive) continue - record("heartbeat", buildJsonObject { - put("server_health", networkStatus.state.value.name) - put("is_playing", ui.isPlaying) - put("source", ui.currentSource ?: "") - put("local_index", ui.queueIndex) - put("local_track_id", ui.currentTrack?.id ?: "") - put("local_pos_ms", ui.positionMs) - put("route", route.name) - put("route_protocol", route.protocol.name) - putSonos(this, routeActive) - addPowerFields(this) - }) - } - } - - // --- power + lifecycle taps ------------------------------------------- - - private fun registerPowerReceiver() { - if (powerReceiver != null) return - val receiver = object : BroadcastReceiver() { - override fun onReceive(c: Context?, intent: Intent?) { - val action = intent?.action ?: return - if (!enabled) return - scope.launch { record("power", powerEvent(action)) } - } - } - val filter = IntentFilter().apply { - addAction(Intent.ACTION_SCREEN_ON) - addAction(Intent.ACTION_SCREEN_OFF) - addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED) - } - // System-protected broadcasts, but pass NOT_EXPORTED explicitly so - // the API 34+ registerReceiver flag requirement is satisfied. - ContextCompat.registerReceiver( - context, receiver, filter, ContextCompat.RECEIVER_NOT_EXPORTED, - ) - powerReceiver = receiver - } - - private fun unregisterPowerReceiver() { - powerReceiver?.let { runCatching { context.unregisterReceiver(it) } } - powerReceiver = null - } - - private fun registerLifecycleObserver() { - if (lifecycleObserver != null) return - val obs = object : DefaultLifecycleObserver { - override fun onStart(owner: LifecycleOwner) = logLifecycle("app_foreground") - override fun onStop(owner: LifecycleOwner) = logLifecycle("app_background") - } - lifecycleObserver = obs - scope.launch(Dispatchers.Main) { - ProcessLifecycleOwner.get().lifecycle.addObserver(obs) - } - } - - private fun unregisterLifecycleObserver() { - val obs = lifecycleObserver ?: return - lifecycleObserver = null - scope.launch(Dispatchers.Main) { - ProcessLifecycleOwner.get().lifecycle.removeObserver(obs) - } - } - - private fun logLifecycle(event: String) { - if (!enabled) return - scope.launch { record("lifecycle", buildJsonObject { put("event", event) }) } - } - - private fun powerEvent(action: String): JsonObject = buildJsonObject { - put("event", action.substringAfterLast('.')) - addPowerFields(this) - } - - // Sonos/UPnP remote-vs-local desync fields. Only meaningful while a - // remote route is active; zeroed otherwise so a stale RemotePlayerState - // from a just-ended cast can't masquerade as live Sonos data (the - // cast→phone handoff artifact). currentTrackUri is the desync ground - // truth — it carries the track the speaker is actually streaming. - private fun putSonos(builder: kotlinx.serialization.json.JsonObjectBuilder, casting: Boolean) { - builder.put("sonos_track", if (casting) remoteState.trackNumber else 0) - builder.put("sonos_pos_ms", if (casting) remoteState.positionMs else 0) - builder.put("sonos_playing", casting && remoteState.isPlaying) - if (casting) builder.put("sonos_uri", remoteState.currentTrackUri) - } - - private fun addPowerFields(builder: kotlinx.serialization.json.JsonObjectBuilder) { - val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager - builder.put("doze", pm.isDeviceIdleMode) - builder.put("screen_on", pm.isInteractive) - builder.put("battery_opt_ignored", pm.isIgnoringBatteryOptimizations(context.packageName)) - } - - private suspend fun record(kind: String, payload: JsonObject) { - runCatching { - val id = dao.insert( - DiagnosticEventEntity( - kind = kind, - occurredAtMillis = System.currentTimeMillis(), - payloadJson = json.encodeToString(JsonObject.serializer(), payload), - ), + addPowerFields(this) + }, ) - if (id % TRIM_INTERVAL == 0L) dao.trimToNewest(MAX_BUFFER) + } + + private suspend fun collectRoutes() { + // 'playback' — route changes happen for all outputs. This only ever + // logs the ACTIVE route (routesState.current), so no "connected" flag. + outputPicker.routesState.map { it.current }.distinctUntilChanged().collect { r -> + record( + "playback", + buildJsonObject { + put("event", "route") + put("id", r.id) + put("name", r.name) + put("kind", r.kind.name) + put("protocol", r.protocol.name) + }, + ) + } + } + + private suspend fun heartbeatLoop() { + while (true) { + delay(HEARTBEAT_MS) + val ui = playerController.uiState.value + val route = outputPicker.routesState.value.current + val routeActive = route.protocol != OutputRoute.Protocol.SYSTEM + // Idle = nothing worth sampling. Skip to keep the buffer lean. + if (!ui.isPlaying && !routeActive) continue + record( + "heartbeat", + buildJsonObject { + put("server_health", networkStatus.state.value.name) + put("is_playing", ui.isPlaying) + put("source", ui.currentSource ?: "") + put("local_index", ui.queueIndex) + put("local_track_id", ui.currentTrack?.id ?: "") + put("local_pos_ms", ui.positionMs) + put("route", route.name) + put("route_protocol", route.protocol.name) + putSonos(this, routeActive) + addPowerFields(this) + }, + ) + } + } + + // --- power + lifecycle taps ------------------------------------------- + + private fun registerPowerReceiver() { + if (powerReceiver != null) return + val receiver = + object : BroadcastReceiver() { + override fun onReceive( + c: Context?, + intent: Intent?, + ) { + val action = intent?.action ?: return + if (!enabled) return + scope.launch { record("power", powerEvent(action)) } + } + } + val filter = + IntentFilter().apply { + addAction(Intent.ACTION_SCREEN_ON) + addAction(Intent.ACTION_SCREEN_OFF) + addAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED) + } + // System-protected broadcasts, but pass NOT_EXPORTED explicitly so + // the API 34+ registerReceiver flag requirement is satisfied. + ContextCompat.registerReceiver( + context, + receiver, + filter, + ContextCompat.RECEIVER_NOT_EXPORTED, + ) + powerReceiver = receiver + } + + private fun unregisterPowerReceiver() { + powerReceiver?.let { runCatching { context.unregisterReceiver(it) } } + powerReceiver = null + } + + private fun registerLifecycleObserver() { + if (lifecycleObserver != null) return + val obs = + object : DefaultLifecycleObserver { + override fun onStart(owner: LifecycleOwner) = logLifecycle("app_foreground") + + override fun onStop(owner: LifecycleOwner) = logLifecycle("app_background") + } + lifecycleObserver = obs + scope.launch(Dispatchers.Main) { + ProcessLifecycleOwner.get().lifecycle.addObserver(obs) + } + } + + private fun unregisterLifecycleObserver() { + val obs = lifecycleObserver ?: return + lifecycleObserver = null + scope.launch(Dispatchers.Main) { + ProcessLifecycleOwner.get().lifecycle.removeObserver(obs) + } + } + + private fun logLifecycle(event: String) { + if (!enabled) return + scope.launch { record("lifecycle", buildJsonObject { put("event", event) }) } + } + + private fun powerEvent(action: String): JsonObject = + buildJsonObject { + put("event", action.substringAfterLast('.')) + addPowerFields(this) + } + + // Sonos/UPnP remote-vs-local desync fields. Only meaningful while a + // remote route is active; zeroed otherwise so a stale RemotePlayerState + // from a just-ended cast can't masquerade as live Sonos data (the + // cast→phone handoff artifact). currentTrackUri is the desync ground + // truth — it carries the track the speaker is actually streaming. + private fun putSonos( + builder: kotlinx.serialization.json.JsonObjectBuilder, + casting: Boolean, + ) { + builder.put("sonos_track", if (casting) remoteState.trackNumber else 0) + builder.put("sonos_pos_ms", if (casting) remoteState.positionMs else 0) + builder.put("sonos_playing", casting && remoteState.isPlaying) + if (casting) builder.put("sonos_uri", remoteState.currentTrackUri) + } + + private fun addPowerFields(builder: kotlinx.serialization.json.JsonObjectBuilder) { + val pm = context.getSystemService(Context.POWER_SERVICE) as PowerManager + builder.put("doze", pm.isDeviceIdleMode) + builder.put("screen_on", pm.isInteractive) + builder.put("battery_opt_ignored", pm.isIgnoringBatteryOptimizations(context.packageName)) + } + + private suspend fun record( + kind: String, + payload: JsonObject, + ) { + runCatching { + val id = + dao.insert( + DiagnosticEventEntity( + kind = kind, + occurredAtMillis = System.currentTimeMillis(), + payloadJson = json.encodeToString(JsonObject.serializer(), payload), + ), + ) + if (id % TRIM_INTERVAL == 0L) dao.trimToNewest(MAX_BUFFER) + } + } + + private companion object { + const val HEARTBEAT_MS = 45_000L + const val GATE_REFRESH_MS = 300_000L // re-pull /me every 5 min + const val MAX_BUFFER = 5_000 // ring-buffer ceiling, oldest dropped + const val TRIM_INTERVAL = 50L // trim every N inserts, not every one } } - - private companion object { - const val HEARTBEAT_MS = 45_000L - const val GATE_REFRESH_MS = 300_000L // re-pull /me every 5 min - const val MAX_BUFFER = 5_000 // ring-buffer ceiling, oldest dropped - const val TRIM_INTERVAL = 50L // trim every N inserts, not every one - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsUploader.kt b/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsUploader.kt index a19622c4..c2b01a1a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsUploader.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/diagnostics/DiagnosticsUploader.kt @@ -38,84 +38,93 @@ import javax.inject.Singleton * uploader treats as success so the buffer drains either way. */ @Singleton -class DiagnosticsUploader @Inject constructor( - private val dao: DiagnosticEventDao, - private val authStore: AuthStore, - private val json: Json, - @ApplicationScope private val scope: CoroutineScope, - networkStatus: NetworkStatusController, - retrofit: Retrofit, -) { - private val api: DiagnosticsApi = retrofit.create() - private val mutex = Mutex() +class DiagnosticsUploader + @Inject + constructor( + private val dao: DiagnosticEventDao, + private val authStore: AuthStore, + private val json: Json, + @ApplicationScope private val scope: CoroutineScope, + networkStatus: NetworkStatusController, + retrofit: Retrofit, + ) { + private val api: DiagnosticsApi = retrofit.create() + private val mutex = Mutex() - init { - scope.launch { - while (true) { - delay(UPLOAD_INTERVAL_MS) - drainSafe() + init { + scope.launch { + while (true) { + delay(UPLOAD_INTERVAL_MS) + drainSafe() + } + } + scope.launch { + authStore.sessionCookie + .filterNotNull() + .distinctUntilChanged() + .collect { drainSafe() } + } + scope.launch { + networkStatus.state + .map { it == ServerHealth.Healthy } + .distinctUntilChanged() + .filter { it } + .collect { drainSafe() } } } - scope.launch { - authStore.sessionCookie.filterNotNull().distinctUntilChanged().collect { drainSafe() } + + /** Coalesces concurrent triggers via tryLock — a drain in flight wins. */ + private suspend fun drainSafe() { + // A trigger at launch can fire before the stored login has loaded; + // wait for it, so a signed-in user is not read as signed out. + authStore.awaitSessionHydrated() + val clientId = authStore.clientId.value + // Signed out / no client id yet → nothing to do. Single guard keeps + // the return count within the detekt gate. + if (authStore.sessionCookie.value.isNullOrEmpty() || clientId == null) return + if (!mutex.tryLock()) return + try { + drain(clientId) + } finally { + mutex.unlock() + } } - scope.launch { - networkStatus.state - .map { it == ServerHealth.Healthy } - .distinctUntilChanged() - .filter { it } - .collect { drainSafe() } + + private suspend fun drain(clientId: String) { + var more = true + while (more) { + val batch = runCatching { dao.takeBatch(BATCH_SIZE) }.getOrNull().orEmpty() + val sent = batch.isNotEmpty() && runCatching { upload(clientId, batch) }.isSuccess + if (sent) runCatching { dao.deleteByIds(batch.map { it.id }) } + // Keep going only while a full batch sent cleanly; otherwise stop + // (empty buffer, or a failure to retry on the next trigger). + more = sent && batch.size >= BATCH_SIZE + } + } + + private suspend fun upload( + clientId: String, + batch: List, + ) { + api.report( + DiagnosticsReportRequest( + clientId = clientId, + appVersion = BuildConfig.VERSION_NAME, + osVersion = "Android ${Build.VERSION.RELEASE} (${Build.MODEL})", + events = + batch.map { row -> + DiagnosticEventWire( + kind = row.kind, + occurredAt = row.occurredAtMillis, + payload = json.parseToJsonElement(row.payloadJson), + ) + }, + ), + ) + } + + private companion object { + const val UPLOAD_INTERVAL_MS = 60_000L + const val BATCH_SIZE = 100 } } - - /** Coalesces concurrent triggers via tryLock — a drain in flight wins. */ - private suspend fun drainSafe() { - // A trigger at launch can fire before the stored login has loaded; - // wait for it, so a signed-in user is not read as signed out. - authStore.awaitSessionHydrated() - val clientId = authStore.clientId.value - // Signed out / no client id yet → nothing to do. Single guard keeps - // the return count within the detekt gate. - if (authStore.sessionCookie.value.isNullOrEmpty() || clientId == null) return - if (!mutex.tryLock()) return - try { - drain(clientId) - } finally { - mutex.unlock() - } - } - - private suspend fun drain(clientId: String) { - var more = true - while (more) { - val batch = runCatching { dao.takeBatch(BATCH_SIZE) }.getOrNull().orEmpty() - val sent = batch.isNotEmpty() && runCatching { upload(clientId, batch) }.isSuccess - if (sent) runCatching { dao.deleteByIds(batch.map { it.id }) } - // Keep going only while a full batch sent cleanly; otherwise stop - // (empty buffer, or a failure to retry on the next trigger). - more = sent && batch.size >= BATCH_SIZE - } - } - - private suspend fun upload(clientId: String, batch: List) { - api.report( - DiagnosticsReportRequest( - clientId = clientId, - appVersion = BuildConfig.VERSION_NAME, - osVersion = "Android ${Build.VERSION.RELEASE} (${Build.MODEL})", - events = batch.map { row -> - DiagnosticEventWire( - kind = row.kind, - occurredAt = row.occurredAtMillis, - payload = json.parseToJsonElement(row.payloadJson), - ) - }, - ), - ) - } - - private companion object { - const val UPLOAD_INTERVAL_MS = 60_000L - const val BATCH_SIZE = 100 - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/events/EventsStream.kt b/android/app/src/main/java/com/fabledsword/minstrel/events/EventsStream.kt index 16c96adc..2844492d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/events/EventsStream.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/events/EventsStream.kt @@ -63,157 +63,171 @@ private const val EVENTS_BUFFER_CAPACITY = 64 * needing a separate path through here. */ @Singleton -class EventsStream @Inject constructor( - private val authStore: AuthStore, - @ApplicationScope private val scope: CoroutineScope, - private val okHttpClient: OkHttpClient, - private val json: Json, - private val connectivity: ConnectivityObserver, -) { - private val factory = EventSources.createFactory(okHttpClient) +class EventsStream + @Inject + constructor( + private val authStore: AuthStore, + @ApplicationScope private val scope: CoroutineScope, + private val okHttpClient: OkHttpClient, + private val json: Json, + private val connectivity: ConnectivityObserver, + ) { + private val factory = EventSources.createFactory(okHttpClient) - private val emitter = MutableSharedFlow( - replay = 0, - extraBufferCapacity = EVENTS_BUFFER_CAPACITY, - onBufferOverflow = BufferOverflow.DROP_OLDEST, - ) - val events: SharedFlow = emitter.asSharedFlow() + private val emitter = + MutableSharedFlow( + replay = 0, + extraBufferCapacity = EVENTS_BUFFER_CAPACITY, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + val events: SharedFlow = emitter.asSharedFlow() - private val connectedState = MutableStateFlow(false) - val connected: StateFlow = connectedState.asStateFlow() + private val connectedState = MutableStateFlow(false) + val connected: StateFlow = connectedState.asStateFlow() - private var currentSource: EventSource? = null - @Volatile private var signedIn = false - private var reconnectJob: Job? = null - private var backoffMs = ReconnectBackoff.BASE_MS + private var currentSource: EventSource? = null - init { - scope.launch { - authStore.sessionCookie - .map { !it.isNullOrEmpty() } - .distinctUntilChanged() - .collect { isSignedIn -> - signedIn = isSignedIn - if (isSignedIn) { - backoffMs = ReconnectBackoff.BASE_MS - connect() - } else { - disconnect() + @Volatile private var signedIn = false + private var reconnectJob: Job? = null + private var backoffMs = ReconnectBackoff.BASE_MS + + init { + scope.launch { + authStore.sessionCookie + .map { !it.isNullOrEmpty() } + .distinctUntilChanged() + .collect { isSignedIn -> + signedIn = isSignedIn + if (isSignedIn) { + backoffMs = ReconnectBackoff.BASE_MS + connect() + } else { + disconnect() + } } + } + scope.launch { + connectivity.online.collect { up -> if (up) reconnectNow() } + } + } + + /** + * Cuts a pending backoff short: reconnects at once and starts the ladder + * over. For a network that has just come up, or the app coming to the + * foreground, where waiting out a five-minute backoff would leave the + * server unheard from for nothing. Does nothing while a stream is open or + * opening. + */ + @Synchronized + fun reconnectNow() { + if (!signedIn || reconnectJob?.isActive != true) return + backoffMs = ReconnectBackoff.BASE_MS + connect() + } + + @Synchronized + private fun connect() { + reconnectJob?.cancel() + currentSource?.cancel() + currentSource = openSubscription() + } + + @Synchronized + private fun disconnect() { + reconnectJob?.cancel() + currentSource?.cancel() + currentSource = null + connectedState.value = false + } + + /** + * Schedule a reconnect after the current backoff, jittered, then + * double it (capped). No-op when signed out — sign-out's [disconnect] + * cancels the pending job. A successful [Listener.onOpen] resets + * the backoff to the floor. + */ + @Synchronized + private fun scheduleReconnect() { + connectedState.value = false + if (!signedIn) return + reconnectJob?.cancel() + val waitMs = ReconnectBackoff.jittered(backoffMs) + backoffMs = ReconnectBackoff.next(backoffMs) + reconnectJob = + scope.launch { + delay(waitMs) + if (signedIn) connect() } } - scope.launch { - connectivity.online.collect { up -> if (up) reconnectNow() } - } - } - /** - * Cuts a pending backoff short: reconnects at once and starts the ladder - * over. For a network that has just come up, or the app coming to the - * foreground, where waiting out a five-minute backoff would leave the - * server unheard from for nothing. Does nothing while a stream is open or - * opening. - */ - @Synchronized - fun reconnectNow() { - if (!signedIn || reconnectJob?.isActive != true) return - backoffMs = ReconnectBackoff.BASE_MS - connect() - } - - @Synchronized - private fun connect() { - reconnectJob?.cancel() - currentSource?.cancel() - currentSource = openSubscription() - } - - @Synchronized - private fun disconnect() { - reconnectJob?.cancel() - currentSource?.cancel() - currentSource = null - connectedState.value = false - } - - /** - * Schedule a reconnect after the current backoff, jittered, then - * double it (capped). No-op when signed out — sign-out's [disconnect] - * cancels the pending job. A successful [Listener.onOpen] resets - * the backoff to the floor. - */ - @Synchronized - private fun scheduleReconnect() { - connectedState.value = false - if (!signedIn) return - reconnectJob?.cancel() - val waitMs = ReconnectBackoff.jittered(backoffMs) - backoffMs = ReconnectBackoff.next(backoffMs) - reconnectJob = scope.launch { - delay(waitMs) - if (signedIn) connect() - } - } - - private fun openSubscription(): EventSource { - val request = Request.Builder() - .url("http://placeholder.invalid$SSE_PATH") - .header("Accept", "text/event-stream") - .build() - return factory.newEventSource(request, Listener()) - } - - private inner class Listener : EventSourceListener() { - override fun onOpen(eventSource: EventSource, response: Response) { - backoffMs = ReconnectBackoff.BASE_MS - connectedState.value = true + private fun openSubscription(): EventSource { + val request = + Request + .Builder() + .url("http://placeholder.invalid$SSE_PATH") + .header("Accept", "text/event-stream") + .build() + return factory.newEventSource(request, Listener()) } - override fun onEvent( - eventSource: EventSource, - id: String?, - type: String?, + private inner class Listener : EventSourceListener() { + override fun onOpen( + eventSource: EventSource, + response: Response, + ) { + backoffMs = ReconnectBackoff.BASE_MS + connectedState.value = true + } + + override fun onEvent( + eventSource: EventSource, + id: String?, + type: String?, + data: String, + ) { + parseFrame(kind = type, data = data)?.let(emitter::tryEmit) + } + + override fun onClosed(eventSource: EventSource) { + scheduleReconnect() + } + + override fun onFailure( + eventSource: EventSource, + t: Throwable?, + response: Response?, + ) { + scheduleReconnect() + } + } + + /** + * Parses one SSE frame into a [LiveEvent]. The SSE `event:` field + * carries the kind; the `data:` field is a JSON object with + * `kind`/`user_id`/`data` (the kind in the payload is redundant + * with the SSE event field — we prefer the SSE field, falling + * back to the payload field). Heartbeat comment frames don't + * reach here (okhttp-sse filters them). + */ + private fun parseFrame( + kind: String?, data: String, - ) { - parseFrame(kind = type, data = data)?.let(emitter::tryEmit) - } - - override fun onClosed(eventSource: EventSource) { - scheduleReconnect() - } - - override fun onFailure( - eventSource: EventSource, - t: Throwable?, - response: Response?, - ) { - scheduleReconnect() - } + ): LiveEvent? = + try { + val payload = json.parseToJsonElement(data).jsonObject + val resolvedKind = kind ?: payload["kind"]?.jsonPrimitive?.contentOrNull + if (resolvedKind.isNullOrEmpty()) { + null + } else { + LiveEvent( + kind = resolvedKind, + userId = payload["user_id"]?.jsonPrimitive?.contentOrNull.orEmpty(), + data = (payload["data"] as? JsonObject) ?: JsonObject(emptyMap()), + ) + } + } catch ( + @Suppress("TooGenericExceptionCaught") _: Throwable, + ) { + null + } } - - /** - * Parses one SSE frame into a [LiveEvent]. The SSE `event:` field - * carries the kind; the `data:` field is a JSON object with - * `kind`/`user_id`/`data` (the kind in the payload is redundant - * with the SSE event field — we prefer the SSE field, falling - * back to the payload field). Heartbeat comment frames don't - * reach here (okhttp-sse filters them). - */ - private fun parseFrame(kind: String?, data: String): LiveEvent? = try { - val payload = json.parseToJsonElement(data).jsonObject - val resolvedKind = kind ?: payload["kind"]?.jsonPrimitive?.contentOrNull - if (resolvedKind.isNullOrEmpty()) { - null - } else { - LiveEvent( - kind = resolvedKind, - userId = payload["user_id"]?.jsonPrimitive?.contentOrNull.orEmpty(), - data = (payload["data"] as? JsonObject) ?: JsonObject(emptyMap()), - ) - } - } catch ( - @Suppress("TooGenericExceptionCaught") _: Throwable, - ) { - null - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/events/LiveEventsDispatcher.kt b/android/app/src/main/java/com/fabledsword/minstrel/events/LiveEventsDispatcher.kt index a656f0bc..3d1d306c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/events/LiveEventsDispatcher.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/events/LiveEventsDispatcher.kt @@ -28,57 +28,58 @@ import javax.inject.Singleton * stream reconnects and the re-refresh avoids stale data flashing. */ @Singleton -class LiveEventsDispatcher @Inject constructor( - private val eventsStream: EventsStream, - private val likes: LikesRepository, - private val notifications: NotificationsRepository, - @ApplicationScope private val scope: CoroutineScope, -) : DefaultLifecycleObserver { +class LiveEventsDispatcher + @Inject + constructor( + private val eventsStream: EventsStream, + private val likes: LikesRepository, + private val notifications: NotificationsRepository, + @ApplicationScope private val scope: CoroutineScope, + ) : DefaultLifecycleObserver { + init { + ProcessLifecycleOwner.get().lifecycle.addObserver(this) + scope.launch { + eventsStream.events.collect { e -> handle(e) } + } + } - init { - ProcessLifecycleOwner.get().lifecycle.addObserver(this) - scope.launch { - eventsStream.events.collect { e -> handle(e) } + private fun handle(event: LiveEvent) { + when (event.kind) { + "track.liked", + "track.unliked", + "album.liked", + "album.unliked", + "artist.liked", + "artist.unliked", + -> refreshLikes() + // a contentless nudge; the inbox refetches its newest page. + "notification.created" -> refreshNotifications() + } + // Other kinds (playlist.*, quarantine.*, request.status_changed, + // scan.*) reach screen-scoped subscribers via EventsStream + // directly. Add cross-screen cases here only when a new + // Repository-level refresh becomes available. + } + + override fun onStart(owner: LifecycleOwner) { + // App returned to the foreground. SSE will catch up but might + // not have reconnected yet (it may be deep in its backoff, so it + // is told to try now); flush the cross-screen refreshes + // defensively. + eventsStream.reconnectNow() + refreshLikes() + refreshNotifications() + } + + private fun refreshNotifications() { + scope.launch { + runCatching { notifications.refresh() } + } + } + + private fun refreshLikes() { + scope.launch { + runCatching { likes.refreshIds() } + } } } - - private fun handle(event: LiveEvent) { - when (event.kind) { - "track.liked", - "track.unliked", - "album.liked", - "album.unliked", - "artist.liked", - "artist.unliked", - -> refreshLikes() - // a contentless nudge; the inbox refetches its newest page. - "notification.created" -> refreshNotifications() - } - // Other kinds (playlist.*, quarantine.*, request.status_changed, - // scan.*) reach screen-scoped subscribers via EventsStream - // directly. Add cross-screen cases here only when a new - // Repository-level refresh becomes available. - } - - override fun onStart(owner: LifecycleOwner) { - // App returned to the foreground. SSE will catch up but might - // not have reconnected yet (it may be deep in its backoff, so it - // is told to try now); flush the cross-screen refreshes - // defensively. - eventsStream.reconnectNow() - refreshLikes() - refreshNotifications() - } - - private fun refreshNotifications() { - scope.launch { - runCatching { notifications.refresh() } - } - } - - private fun refreshLikes() { - scope.launch { - runCatching { likes.refreshIds() } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/events/ReconnectBackoff.kt b/android/app/src/main/java/com/fabledsword/minstrel/events/ReconnectBackoff.kt index 6a19c2b6..87e37226 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/events/ReconnectBackoff.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/events/ReconnectBackoff.kt @@ -24,7 +24,10 @@ internal object ReconnectBackoff { fun next(currentMs: Long): Long = (currentMs * 2).coerceAtMost(MAX_MS) /** [ms] moved by up to a quarter either way. */ - fun jittered(ms: Long, random: Random = Random.Default): Long { + fun jittered( + ms: Long, + random: Random = Random.Default, + ): Long { val spread = ms * JITTER return (ms + random.nextDouble(-spread, spread)).toLong() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/history/data/HistoryRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/history/data/HistoryRepository.kt index 9877b160..650485f7 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/history/data/HistoryRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/history/data/HistoryRepository.kt @@ -49,29 +49,33 @@ data class HistoryPage( * ordering/paging bookkeeping for no UX gain. */ @Singleton -class HistoryRepository @Inject constructor( - private val snapshotDao: CachedHistorySnapshotDao, - private val json: Json, - retrofit: Retrofit, -) { - private val api: HistoryApi = retrofit.create() +class HistoryRepository + @Inject + constructor( + private val snapshotDao: CachedHistorySnapshotDao, + private val json: Json, + retrofit: Retrofit, + ) { + private val api: HistoryApi = retrofit.create() - fun observeHistory(): Flow = - snapshotDao.observe().map { row -> - row?.let { json.decodeFromString(it.json).toDomain() } + fun observeHistory(): Flow = + snapshotDao.observe().map { row -> + row?.let { json.decodeFromString(it.json).toDomain() } + } + + /** Fetch the latest history and overwrite the cached snapshot. */ + suspend fun refresh() { + val wire = api.getHistory() + val blob = json.encodeToString(HistoryPageWire.serializer(), wire) + snapshotDao.upsert(CachedHistorySnapshotEntity(json = blob)) } - - /** Fetch the latest history and overwrite the cached snapshot. */ - suspend fun refresh() { - val wire = api.getHistory() - val blob = json.encodeToString(HistoryPageWire.serializer(), wire) - snapshotDao.upsert(CachedHistorySnapshotEntity(json = blob)) } -} -private fun HistoryPageWire.toDomain(): HistoryPage = HistoryPage( - entries = events.map { - HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain()) - }, - hasMore = hasMore, -) +private fun HistoryPageWire.toDomain(): HistoryPage = + HistoryPage( + entries = + events.map { + HistoryEntry(id = it.id, playedAt = it.playedAt, track = it.track.toDomain()) + }, + hasMore = hasMore, + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/history/ui/HistoryTab.kt b/android/app/src/main/java/com/fabledsword/minstrel/history/ui/HistoryTab.kt index 245e7a25..895054fc 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/history/ui/HistoryTab.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/history/ui/HistoryTab.kt @@ -1,10 +1,7 @@ package com.fabledsword.minstrel.history.ui 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.padding import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.material3.HorizontalDivider @@ -26,12 +23,12 @@ import com.fabledsword.minstrel.history.data.HistoryRepository import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.shared.UiState -import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb +import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job @@ -56,56 +53,58 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L // ─── ViewModel ─────────────────────────────────────────────────────── @HiltViewModel -class HistoryTabViewModel @Inject constructor( - private val repository: HistoryRepository, - private val player: PlayerController, - networkStatus: NetworkStatusController, -) : ViewModel() { +class HistoryTabViewModel + @Inject + constructor( + private val repository: HistoryRepository, + private val player: PlayerController, + networkStatus: NetworkStatusController, + ) : ViewModel() { + private val refreshError = MutableStateFlow(null) - private val refreshError = MutableStateFlow(null) + /** + * Cache-first: emits the cached snapshot instantly (paints from + * disk on cold open), then SWR-refreshes underneath. Shows Error + * only when there's nothing cached AND the refresh failed — a + * failed refresh over a populated cache stays silent. + */ + val uiState: StateFlow>> = + combine(repository.observeHistory(), refreshError) { page, err -> + when { + page != null && page.entries.isNotEmpty() -> UiState.Success(page.entries) + page != null -> UiState.Empty + err != null -> UiState.Error(err) + else -> UiState.Loading + } + }.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = UiState.Loading, + ) - /** - * Cache-first: emits the cached snapshot instantly (paints from - * disk on cold open), then SWR-refreshes underneath. Shows Error - * only when there's nothing cached AND the refresh failed — a - * failed refresh over a populated cache stays silent. - */ - val uiState: StateFlow>> = - combine(repository.observeHistory(), refreshError) { page, err -> - when { - page != null && page.entries.isNotEmpty() -> UiState.Success(page.entries) - page != null -> UiState.Empty - err != null -> UiState.Error(err) - else -> UiState.Loading + init { + refresh() + // Screen-level auto-recovery: re-pull when server + // health returns, so a load that failed offline heals unprompted. + viewModelScope.launch { + networkStatus.recoveries().collect { refresh() } } - }.stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = UiState.Loading, - ) + } - init { - refresh() - // Screen-level auto-recovery: re-pull when server - // health returns, so a load that failed offline heals unprompted. - viewModelScope.launch { - networkStatus.recoveries().collect { refresh() } + fun refresh(): Job = + viewModelScope.launch { + refreshError.value = null + runCatching { repository.refresh() } + .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } + } + + /** Plays the tapped track on its own. */ + fun playTrack(track: TrackRef) { + if (track.streamUrl.isEmpty()) return + player.setQueue(listOf(track), initialIndex = 0, source = "history") } } - fun refresh(): Job = viewModelScope.launch { - refreshError.value = null - runCatching { repository.refresh() } - .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } - } - - /** Plays the tapped track on its own. */ - fun playTrack(track: TrackRef) { - if (track.streamUrl.isEmpty()) return - player.setQueue(listOf(track), initialIndex = 0, source = "history") - } -} - // ─── Composable ────────────────────────────────────────────────────── @Composable @@ -121,22 +120,25 @@ fun HistoryTab( PullToRefreshScaffold(onRefresh = { viewModel.refresh().join() }) { when (val s = state) { UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "No listening history yet", - body = "Play something — your recent plays will show up here.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load history", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> HistoryList( - entries = s.data, - playingTrackId = playingTrackId, - onPlay = viewModel::playTrack, - onNavigateToAlbum = onNavigateToAlbum, - onNavigateToArtist = onNavigateToArtist, - ) + UiState.Empty -> + EmptyState( + title = "No listening history yet", + body = "Play something — your recent plays will show up here.", + ) + is UiState.Error -> + ErrorRetry( + title = "Couldn't load history", + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> + HistoryList( + entries = s.data, + playingTrackId = playingTrackId, + onPlay = viewModel::playTrack, + onNavigateToAlbum = onNavigateToAlbum, + onNavigateToArtist = onNavigateToArtist, + ) } } } @@ -215,8 +217,9 @@ private const val DAYS_PER_WEEK = 7L * up the row over malformed timestamps. */ private fun relativeTime(iso: String): String { - val parsed = runCatching { OffsetDateTime.parse(iso) }.getOrNull() - ?: return iso + val parsed = + runCatching { OffsetDateTime.parse(iso) }.getOrNull() + ?: return iso val local = parsed.atZoneSameInstant(ZoneId.systemDefault()) val now = OffsetDateTime.now(ZoneId.systemDefault()) val minutes = ChronoUnit.MINUTES.between(local, now) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/home/data/HomeRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/home/data/HomeRepository.kt index a2aa761c..4781d00c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/home/data/HomeRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/home/data/HomeRepository.kt @@ -44,163 +44,162 @@ import javax.inject.Singleton // Per-section observe accessors (one per Home row) inflate the function // count past detekt's 11 default — accessor density, not complexity. @Suppress("TooManyFunctions") -class HomeRepository @Inject constructor( - private val homeIndexDao: CachedHomeIndexDao, - private val metadataProvider: MetadataProvider, - private val prewarmer: HomeArtistPrewarmer, - retrofit: Retrofit, -) { - private val api: HomeApi = retrofit.create() - private val meApi: MeApi = retrofit.create() +class HomeRepository + @Inject + constructor( + private val homeIndexDao: CachedHomeIndexDao, + private val metadataProvider: MetadataProvider, + private val prewarmer: HomeArtistPrewarmer, + retrofit: Retrofit, + ) { + private val api: HomeApi = retrofit.create() + private val meApi: MeApi = retrofit.create() - /** - * Caller's system-playlist build state for the Home placeholder - * cards. One-shot GET; the caller refreshes alongside the index. - */ - suspend fun getSystemPlaylistsStatus(): SystemPlaylistsStatus = - meApi.getSystemPlaylistsStatus().let { - SystemPlaylistsStatus( - inFlight = it.inFlight, - lastRunAt = it.lastRunAt, - lastError = it.lastError, + /** + * Caller's system-playlist build state for the Home placeholder + * cards. One-shot GET; the caller refreshes alongside the index. + */ + suspend fun getSystemPlaylistsStatus(): SystemPlaylistsStatus = + meApi.getSystemPlaylistsStatus().let { + SystemPlaylistsStatus( + inFlight = it.inFlight, + lastRunAt = it.lastRunAt, + lastError = it.lastError, + ) + } + + fun observeRecentlyAddedAlbums(): Flow>> = observeAlbumSection(SECTION_RECENTLY_ADDED_ALBUMS) + + fun observeRediscoverAlbums(): Flow>> = observeAlbumSection(SECTION_REDISCOVER_ALBUMS) + + fun observeRediscoverArtists(): Flow>> = observeArtistSection(SECTION_REDISCOVER_ARTISTS) + + fun observeMostPlayedTracks(): Flow>> = observeTrackSection(SECTION_MOST_PLAYED_TRACKS) + + fun observeLastPlayedArtists(): Flow>> = observeArtistSection(SECTION_LAST_PLAYED_ARTISTS) + + fun observeYouMightLikeAlbums(): Flow>> = observeAlbumSection(SECTION_YOU_MIGHT_LIKE_ALBUMS) + + fun observeYouMightLikeArtists(): Flow>> = observeArtistSection(SECTION_YOU_MIGHT_LIKE_ARTISTS) + + /** True when the index cache already has content on screen to protect. */ + suspend fun hasCachedIndex(): Boolean = homeIndexDao.hasAny() + + /** + * Pulls /api/home/index and swaps every cached_home_index section in + * a single transaction, then pre-warms the top artists. Missing + * entity rows hydrate via the on-miss path. + * + * One transaction for all seven sections is deliberate: Room notifies + * observers once, on commit, so Home swaps from the old content to + * the new in a single emission. Per-section, un-transacted writes + * would make every row visibly collapse to empty and refill, one + * after another. + */ + suspend fun refreshIndex() { + val wire = api.getHomeIndex() + homeIndexDao.replaceSections( + sections = ALL_SECTIONS, + rows = + rowsFor(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums) + + rowsFor(SECTION_REDISCOVER_ALBUMS, "album", wire.rediscoverAlbums) + + rowsFor(SECTION_REDISCOVER_ARTISTS, "artist", wire.rediscoverArtists) + + rowsFor(SECTION_MOST_PLAYED_TRACKS, "track", wire.mostPlayedTracks) + + rowsFor(SECTION_LAST_PLAYED_ARTISTS, "artist", wire.lastPlayedArtists) + + rowsFor(SECTION_YOU_MIGHT_LIKE_ALBUMS, "album", wire.youMightLikeAlbums) + + rowsFor(SECTION_YOU_MIGHT_LIKE_ARTISTS, "artist", wire.youMightLikeArtists), + ) + prewarmer.warm( + wire.rediscoverArtists + wire.lastPlayedArtists + wire.youMightLikeArtists, ) } - fun observeRecentlyAddedAlbums(): Flow>> = - observeAlbumSection(SECTION_RECENTLY_ADDED_ALBUMS) + private fun rowsFor( + section: String, + entityType: String, + ids: List, + ): List = + ids.mapIndexed { index, id -> + CachedHomeIndexEntity( + section = section, + position = index, + entityType = entityType, + entityId = id, + ) + } - fun observeRediscoverAlbums(): Flow>> = - observeAlbumSection(SECTION_REDISCOVER_ALBUMS) + /** + * The section's ordered entity ids, deduplicated. + * + * Room re-runs the query on every write to `cached_home_index` — and + * `CachedHomeIndexEntity.fetchedAt` is stamped fresh each time — so + * comparing whole rows would call every rewrite a change. Comparing + * the id list instead means a section whose contents didn't actually + * move never restarts the `flatMapLatest` below, which would + * otherwise tear down and rebuild all of its tiles' hydration flows + * and flicker unchanged tiles. + */ + private fun observeSectionIds(section: String): Flow> = + homeIndexDao + .observeBySection(section) + .map { rows -> rows.map { it.entityId } } + .distinctUntilChanged() - fun observeRediscoverArtists(): Flow>> = - observeArtistSection(SECTION_REDISCOVER_ARTISTS) - - fun observeMostPlayedTracks(): Flow>> = - observeTrackSection(SECTION_MOST_PLAYED_TRACKS) - - fun observeLastPlayedArtists(): Flow>> = - observeArtistSection(SECTION_LAST_PLAYED_ARTISTS) - - fun observeYouMightLikeAlbums(): Flow>> = - observeAlbumSection(SECTION_YOU_MIGHT_LIKE_ALBUMS) - - fun observeYouMightLikeArtists(): Flow>> = - observeArtistSection(SECTION_YOU_MIGHT_LIKE_ARTISTS) - - /** True when the index cache already has content on screen to protect. */ - suspend fun hasCachedIndex(): Boolean = homeIndexDao.hasAny() - - /** - * Pulls /api/home/index and swaps every cached_home_index section in - * a single transaction, then pre-warms the top artists. Missing - * entity rows hydrate via the on-miss path. - * - * One transaction for all seven sections is deliberate: Room notifies - * observers once, on commit, so Home swaps from the old content to - * the new in a single emission. Per-section, un-transacted writes - * would make every row visibly collapse to empty and refill, one - * after another. - */ - suspend fun refreshIndex() { - val wire = api.getHomeIndex() - homeIndexDao.replaceSections( - sections = ALL_SECTIONS, - rows = rowsFor(SECTION_RECENTLY_ADDED_ALBUMS, "album", wire.recentlyAddedAlbums) + - rowsFor(SECTION_REDISCOVER_ALBUMS, "album", wire.rediscoverAlbums) + - rowsFor(SECTION_REDISCOVER_ARTISTS, "artist", wire.rediscoverArtists) + - rowsFor(SECTION_MOST_PLAYED_TRACKS, "track", wire.mostPlayedTracks) + - rowsFor(SECTION_LAST_PLAYED_ARTISTS, "artist", wire.lastPlayedArtists) + - rowsFor(SECTION_YOU_MIGHT_LIKE_ALBUMS, "album", wire.youMightLikeAlbums) + - rowsFor(SECTION_YOU_MIGHT_LIKE_ARTISTS, "artist", wire.youMightLikeArtists), - ) - prewarmer.warm( - wire.rediscoverArtists + wire.lastPlayedArtists + wire.youMightLikeArtists, - ) - } - - private fun rowsFor( - section: String, - entityType: String, - ids: List, - ): List = ids.mapIndexed { index, id -> - CachedHomeIndexEntity( - section = section, - position = index, - entityType = entityType, - entityId = id, - ) - } - - /** - * The section's ordered entity ids, deduplicated. - * - * Room re-runs the query on every write to `cached_home_index` — and - * `CachedHomeIndexEntity.fetchedAt` is stamped fresh each time — so - * comparing whole rows would call every rewrite a change. Comparing - * the id list instead means a section whose contents didn't actually - * move never restarts the `flatMapLatest` below, which would - * otherwise tear down and rebuild all of its tiles' hydration flows - * and flicker unchanged tiles. - */ - private fun observeSectionIds(section: String): Flow> = - homeIndexDao.observeBySection(section) - .map { rows -> rows.map { it.entityId } } - .distinctUntilChanged() - - @OptIn(ExperimentalCoroutinesApi::class) - private fun observeAlbumSection(section: String): Flow>> = - observeSectionIds(section).flatMapLatest { ids -> - if (ids.isEmpty()) { - flowOf(emptyList()) - } else { - combine(ids.map { metadataProvider.observeAlbum(it) }) { refs -> - ids.mapIndexed { i, id -> HomeTile(id, refs[i]) } + @OptIn(ExperimentalCoroutinesApi::class) + private fun observeAlbumSection(section: String): Flow>> = + observeSectionIds(section).flatMapLatest { ids -> + if (ids.isEmpty()) { + flowOf(emptyList()) + } else { + combine(ids.map { metadataProvider.observeAlbum(it) }) { refs -> + ids.mapIndexed { i, id -> HomeTile(id, refs[i]) } + } } } - } - @OptIn(ExperimentalCoroutinesApi::class) - private fun observeArtistSection(section: String): Flow>> = - observeSectionIds(section).flatMapLatest { ids -> - if (ids.isEmpty()) { - flowOf(emptyList()) - } else { - combine(ids.map { metadataProvider.observeArtist(it) }) { refs -> - ids.mapIndexed { i, id -> HomeTile(id, refs[i]) } + @OptIn(ExperimentalCoroutinesApi::class) + private fun observeArtistSection(section: String): Flow>> = + observeSectionIds(section).flatMapLatest { ids -> + if (ids.isEmpty()) { + flowOf(emptyList()) + } else { + combine(ids.map { metadataProvider.observeArtist(it) }) { refs -> + ids.mapIndexed { i, id -> HomeTile(id, refs[i]) } + } } } - } - @OptIn(ExperimentalCoroutinesApi::class) - private fun observeTrackSection(section: String): Flow>> = - observeSectionIds(section).flatMapLatest { ids -> - if (ids.isEmpty()) { - flowOf(emptyList()) - } else { - combine(ids.map { metadataProvider.observeTrack(it) }) { refs -> - ids.mapIndexed { i, id -> HomeTile(id, refs[i]) } + @OptIn(ExperimentalCoroutinesApi::class) + private fun observeTrackSection(section: String): Flow>> = + observeSectionIds(section).flatMapLatest { ids -> + if (ids.isEmpty()) { + flowOf(emptyList()) + } else { + combine(ids.map { metadataProvider.observeTrack(it) }) { refs -> + ids.mapIndexed { i, id -> HomeTile(id, refs[i]) } + } } } + + companion object { + const val SECTION_RECENTLY_ADDED_ALBUMS = "recently_added_albums" + const val SECTION_REDISCOVER_ALBUMS = "rediscover_albums" + const val SECTION_REDISCOVER_ARTISTS = "rediscover_artists" + const val SECTION_MOST_PLAYED_TRACKS = "most_played_tracks" + const val SECTION_LAST_PLAYED_ARTISTS = "last_played_artists" + const val SECTION_YOU_MIGHT_LIKE_ALBUMS = "you_might_like_albums" + const val SECTION_YOU_MIGHT_LIKE_ARTISTS = "you_might_like_artists" + + /** Every section [refreshIndex] owns — the unit of one atomic swap. */ + val ALL_SECTIONS = + listOf( + SECTION_RECENTLY_ADDED_ALBUMS, + SECTION_REDISCOVER_ALBUMS, + SECTION_REDISCOVER_ARTISTS, + SECTION_MOST_PLAYED_TRACKS, + SECTION_LAST_PLAYED_ARTISTS, + SECTION_YOU_MIGHT_LIKE_ALBUMS, + SECTION_YOU_MIGHT_LIKE_ARTISTS, + ) } - - companion object { - const val SECTION_RECENTLY_ADDED_ALBUMS = "recently_added_albums" - const val SECTION_REDISCOVER_ALBUMS = "rediscover_albums" - const val SECTION_REDISCOVER_ARTISTS = "rediscover_artists" - const val SECTION_MOST_PLAYED_TRACKS = "most_played_tracks" - const val SECTION_LAST_PLAYED_ARTISTS = "last_played_artists" - const val SECTION_YOU_MIGHT_LIKE_ALBUMS = "you_might_like_albums" - const val SECTION_YOU_MIGHT_LIKE_ARTISTS = "you_might_like_artists" - - /** Every section [refreshIndex] owns — the unit of one atomic swap. */ - val ALL_SECTIONS = listOf( - SECTION_RECENTLY_ADDED_ALBUMS, - SECTION_REDISCOVER_ALBUMS, - SECTION_REDISCOVER_ARTISTS, - SECTION_MOST_PLAYED_TRACKS, - SECTION_LAST_PLAYED_ARTISTS, - SECTION_YOU_MIGHT_LIKE_ALBUMS, - SECTION_YOU_MIGHT_LIKE_ARTISTS, - ) } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt index dfcd1997..dd55a42e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/home/ui/HomeScreen.kt @@ -31,7 +31,6 @@ import androidx.compose.foundation.lazy.LazyListScope import androidx.compose.foundation.lazy.LazyRow import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.LazyHorizontalGrid -import androidx.compose.foundation.lazy.grid.items as gridItems import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.itemsIndexed import androidx.compose.foundation.shape.RoundedCornerShape @@ -49,14 +48,14 @@ import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip -import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.platform.LocalConfiguration +import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.unit.Dp import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope import androidx.lifecycle.compose.collectAsStateWithLifecycle +import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController import com.composables.icons.lucide.Heart import com.composables.icons.lucide.History @@ -85,8 +84,8 @@ import com.fabledsword.minstrel.playlists.byShelfRank import com.fabledsword.minstrel.playlists.data.PlaylistsRepository import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled import com.fabledsword.minstrel.playlists.shelfMeta -import com.fabledsword.minstrel.playlists.widgets.OfflinePoolCard import com.fabledsword.minstrel.playlists.widgets.GenreBandCard +import com.fabledsword.minstrel.playlists.widgets.OfflinePoolCard import com.fabledsword.minstrel.playlists.widgets.PlaceholderShape import com.fabledsword.minstrel.playlists.widgets.PlaylistPlaceholderCard import com.fabledsword.minstrel.playlists.widgets.SongsLikeCard @@ -98,7 +97,6 @@ import com.fabledsword.minstrel.shared.VeilOutcome import com.fabledsword.minstrel.shared.VeilSessionResult import com.fabledsword.minstrel.shared.VeilSettleState import com.fabledsword.minstrel.shared.asCacheFirstStateFlow -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ArtSettleTracker import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry @@ -106,6 +104,7 @@ import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow import com.fabledsword.minstrel.shared.widgets.LocalArtSettleTracker import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile import com.fabledsword.minstrel.shared.widgets.SkeletonSectionHeader @@ -122,17 +121,19 @@ import kotlinx.coroutines.flow.SharingStarted import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.combine +import kotlinx.coroutines.flow.filter import kotlinx.coroutines.flow.first import kotlinx.coroutines.flow.map import kotlinx.coroutines.flow.receiveAsFlow import kotlinx.coroutines.flow.stateIn -import kotlinx.coroutines.flow.filter import kotlinx.coroutines.launch import kotlinx.coroutines.withTimeoutOrNull import javax.inject.Inject +import androidx.compose.foundation.lazy.grid.items as gridItems private const val SHARE_STOP_TIMEOUT_MS = 5_000L private const val BOTTOM_PADDING_FOR_MINIPLAYER_DP = 140 + // Recently Added is laid out in a multi-row LazyHorizontalGrid that // scrolls as one panel (same pattern as Most Played). Two rows trades // a tall block for fewer columns to scroll past — a 200dp tile × 2 = @@ -169,367 +170,384 @@ data class HomeSections( val youMightLikeArtists: List> = emptyList(), ) { val isAllEmpty: Boolean - get() = playlists.isEmpty() && - recentlyAddedAlbums.isEmpty() && - rediscoverAlbums.isEmpty() && - rediscoverArtists.isEmpty() && - mostPlayedTracks.isEmpty() && - lastPlayedArtists.isEmpty() && - youMightLikeAlbums.isEmpty() && - youMightLikeArtists.isEmpty() + get() = + playlists.isEmpty() && + recentlyAddedAlbums.isEmpty() && + rediscoverAlbums.isEmpty() && + rediscoverArtists.isEmpty() && + mostPlayedTracks.isEmpty() && + lastPlayedArtists.isEmpty() && + youMightLikeAlbums.isEmpty() && + youMightLikeArtists.isEmpty() } // ─── ViewModel ─────────────────────────────────────────────────────── @HiltViewModel -class HomeViewModel @Inject constructor( - private val homeRepository: HomeRepository, - private val playlistsRepository: PlaylistsRepository, - private val libraryRepository: LibraryRepository, - private val player: com.fabledsword.minstrel.player.PlayerController, - private val shuffleSource: com.fabledsword.minstrel.cache.ShuffleSource, - private val eventsStream: com.fabledsword.minstrel.events.EventsStream, - networkStatus: com.fabledsword.minstrel.connectivity.NetworkStatusController, -) : ViewModel() { +class HomeViewModel + @Inject + constructor( + private val homeRepository: HomeRepository, + private val playlistsRepository: PlaylistsRepository, + private val libraryRepository: LibraryRepository, + private val player: com.fabledsword.minstrel.player.PlayerController, + private val shuffleSource: com.fabledsword.minstrel.cache.ShuffleSource, + private val eventsStream: com.fabledsword.minstrel.events.EventsStream, + networkStatus: com.fabledsword.minstrel.connectivity.NetworkStatusController, + ) : ViewModel() { + private val systemStatusInternal = MutableStateFlow(SystemPlaylistsStatus()) - private val systemStatusInternal = MutableStateFlow(SystemPlaylistsStatus()) + /** System-playlist build status for the Home placeholder cards. */ + val systemStatus: StateFlow = systemStatusInternal.asStateFlow() - /** System-playlist build status for the Home placeholder cards. */ - val systemStatus: StateFlow = systemStatusInternal.asStateFlow() + /** + * Cache-only when there's no link OR the server is unreachable. Reads the + * unified [NetworkStatusController] (not the raw device link) so Home reacts + * to ServerDown too; the transient Unstable state stays calm (not offline). + */ + val offline: StateFlow = + networkStatus.state + .map { it == ServerHealth.Offline || it == ServerHealth.ServerDown } + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = false, + ) - /** - * Cache-only when there's no link OR the server is unreachable. Reads the - * unified [NetworkStatusController] (not the raw device link) so Home reacts - * to ServerDown too; the transient Unstable state stays calm (not offline). - */ - val offline: StateFlow = networkStatus.state - .map { it == ServerHealth.Offline || it == ServerHealth.ServerDown } - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = false, - ) + private val snackbarMessages = Channel(Channel.BUFFERED) - private val snackbarMessages = Channel(Channel.BUFFERED) + /** + * Transient snackbar messages: offline-pool taps, playback failures, and + * the outcome of a refresh the user explicitly asked for. + */ + val transientMessages: Flow = snackbarMessages.receiveAsFlow() - /** - * Transient snackbar messages: offline-pool taps, playback failures, and - * the outcome of a refresh the user explicitly asked for. - */ - val transientMessages: Flow = snackbarMessages.receiveAsFlow() + /** + * Copy for the most recent /home/index refresh failure; null once a + * refresh succeeds. Folded into [uiState] so an empty cache + failed + * refresh renders as Error (with retry) instead of masquerading as + * the "Welcome to Minstrel" empty state. + */ + private val refreshError = MutableStateFlow(null) - /** - * Copy for the most recent /home/index refresh failure; null once a - * refresh succeeds. Folded into [uiState] so an empty cache + failed - * refresh renders as Error (with retry) instead of masquerading as - * the "Welcome to Minstrel" empty state. - */ - private val refreshError = MutableStateFlow(null) + /** + * Cover-art loads in flight on Home, reported by every [ServerImage] + * under [LocalArtSettleTracker]. The veil waits on this so artwork + * arriving a beat after its tile lands behind the veil rather than + * popping in on screen. + */ + val artTracker = ArtSettleTracker() - /** - * Cover-art loads in flight on Home, reported by every [ServerImage] - * under [LocalArtSettleTracker]. The veil waits on this so artwork - * arriving a beat after its tile lands behind the veil rather than - * popping in on screen. - */ - val artTracker = ArtSettleTracker() - - /** - * Tap an offline pool: shuffle + play its cached tracks. Empty - * pool surfaces a snackbar rather than starting silent playback. - */ - fun playPool(kind: OfflinePoolKind) { - viewModelScope.launch { - val tracks = when (kind) { - OfflinePoolKind.RECENTLY_PLAYED -> shuffleSource.recentlyPlayed() - OfflinePoolKind.LIKED -> shuffleSource.liked() - }.shuffled() - if (tracks.isEmpty()) { - snackbarMessages.trySend("No cached ${kind.label} tracks yet") - } else { - player.setQueue(tracks, initialIndex = 0, source = "offline:${kind.name}") - } - } - } - - /** - * Tap on a Most-played tile: replace the queue with the section's - * tracks and start at the tapped index. Home's section is itself the - * playable unit, not a list of album-detail links. - */ - fun playMostPlayed(tracks: List, startIndex: Int) { - if (tracks.isEmpty()) return - player.setQueue( - tracks = tracks, - initialIndex = startIndex.coerceIn(0, tracks.lastIndex), - source = "home:most_played", - ) - } - - /** - * Tap the album play-button overlay: fetch the album detail and - * play its tracks from the first. Suspending so the button's spinner - * waits for the fetch + queue setup; the inner work is launched in - * viewModelScope so cancellation from leaving the screen mid-fetch - * doesn't kill playback. Errors surface via the snackbar channel, - * like the ArtistDetail play handler. - */ - suspend fun playAlbum(albumId: String) { - viewModelScope.launch { - playAlbumFromStart(albumId, libraryRepository, player) { snackbarMessages.trySend(it) } - }.join() - } - - /** - * Tap the artist play-button overlay: fetch every track across the - * artist's albums, shuffle, play from index 0 (shufflePlayArtist, as - * the Artist page's Play does). - */ - suspend fun playArtistShuffled(artistId: String) { - viewModelScope.launch { - shufflePlayArtist(artistId, libraryRepository, player) { snackbarMessages.trySend(it) } - }.join() - } - - /** - * Tap the playlist play-button overlay: fetch the playlist's tracks - * (rotation-aware shuffle for refreshable system playlists, stored - * order for everything else), 8s timeout, play from index 0. - * Empty-mix and timeout get their own copy strings; other errors - * fall through to [ErrorCopy.fromThrowable]. - */ - suspend fun playPlaylist(playlist: PlaylistRef) { - viewModelScope.launch { - playPlaylistShuffled(playlist, playlistsRepository, player) { - snackbarMessages.trySend(it) - } - }.join() - } - - /** - * Pulls /home/index, the playlists list and the system-playlist - * status. Returns true when the load-bearing /home/index pull - * succeeded — the veil controller retries on false and reports the - * outcome, so this must report failure rather than swallow it. - */ - private suspend fun runRefresh(): Boolean = coroutineScope { - // /home/index is the load-bearing pull: its failure drives the - // empty-cache Error state. A failure over a populated cache - // stays silent — cached sections beat a full-screen error. - // - // Cleared on success, NOT at the start of each attempt: with the - // veil's retries, clearing up front made a failing cold start - // flash the "Welcome to Minstrel" empty state (empty cache + no - // error reads as Empty) between one attempt and the next. - val home = async { - runCatching { homeRepository.refreshIndex() } - .onSuccess { refreshError.value = null } - .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } - .isSuccess - } - val lists = launch { runCatching { playlistsRepository.refreshList() } } - val status = launch { - runCatching { homeRepository.getSystemPlaylistsStatus() } - .onSuccess { systemStatusInternal.value = it } - } - lists.join() - status.join() - home.await() - } - - /** - * The Error state's explicit Retry button. User-initiated, so it gets - * the controller's retries and reports its outcome; over an empty cache - * there's no content to protect, so no veil goes up. - */ - fun retry() = veil.request(userInitiated = true) - - /** - * Manual pull-to-refresh. Goes behind the veil like every other - * refresh: a pull churns the screen exactly as the automatic paths - * do, and a small spinner does not hide it. - * - * Suspends until the veil has taken over OR the session has finished, - * so the pull indicator hands off to exactly one successor: the veil if - * content changed, the "Already up to date" snackbar if it didn't. The - * timeout is only a backstop against a session that outlives it. - */ - suspend fun refreshFromPull() { - val before = veil.finishedSessions.value - veil.request(userInitiated = true) - withTimeoutOrNull(PULL_HANDOFF_TIMEOUT_MS) { - combine(veil.visible, veil.finishedSessions) { veiled, finished -> - veiled || finished != before - }.first { it } - } - } - - val uiState: StateFlow> = - combineHomeFlows().asCacheFirstStateFlow(viewModelScope) - - /** - * The core five section flows merged into the sections struct. Split - * out so each combine call stays inside the coroutines built-in arity - * limit (5) and avoids the typed-vararg acrobatics a wider combine - * across heterogeneous types would need. [observeHomeSections] then - * folds in the two you-might-like flows, and [combineHomeFlows] the - * playlists flow. - */ - private fun observeCoreSections() = combine( - homeRepository.observeRecentlyAddedAlbums(), - homeRepository.observeRediscoverAlbums(), - homeRepository.observeRediscoverArtists(), - homeRepository.observeMostPlayedTracks(), - homeRepository.observeLastPlayedArtists(), - ) { recent, rediscoverAlbums, rediscoverArtists, mostPlayed, lastPlayed -> - HomeSections( - recentlyAddedAlbums = recent, - rediscoverAlbums = rediscoverAlbums, - rediscoverArtists = rediscoverArtists, - mostPlayedTracks = mostPlayed, - lastPlayedArtists = lastPlayed, - ) - } - - private fun observeHomeSections() = combine( - observeCoreSections(), - homeRepository.observeYouMightLikeAlbums(), - homeRepository.observeYouMightLikeArtists(), - ) { core, ymlAlbums, ymlArtists -> - core.copy(youMightLikeAlbums = ymlAlbums, youMightLikeArtists = ymlArtists) - } - - private fun combineHomeFlows() = - combine( - observeHomeSections(), - playlistsRepository.observeAll(), - refreshError, - ) { sections, playlists, err -> - val merged = sections.copy(playlists = playlists) - when { - !merged.isAllEmpty -> UiState.Success(merged) - err != null -> UiState.Error(err) - else -> UiState.Empty + /** + * Tap an offline pool: shuffle + play its cached tracks. Empty + * pool surfaces a snackbar rather than starting silent playback. + */ + fun playPool(kind: OfflinePoolKind) { + viewModelScope.launch { + val tracks = + when (kind) { + OfflinePoolKind.RECENTLY_PLAYED -> shuffleSource.recentlyPlayed() + OfflinePoolKind.LIKED -> shuffleSource.liked() + }.shuffled() + if (tracks.isEmpty()) { + snackbarMessages.trySend("No cached ${kind.label} tracks yet") + } else { + player.setQueue(tracks, initialIndex = 0, source = "offline:${kind.name}") + } } } - // ─── Updating veil ─────────────────────────────────────────────── - // Declared after uiState: these initialisers read it, and Kotlin runs - // property initialisers and init blocks in declaration order. - - /** - * What the veil watches to decide Home has stopped moving: the whole - * rendered state, plus how many covers are still loading. - * - * [UiState.Success] wraps a [HomeSections] data class, so any visible - * change — a section swapping ids, one tile hydrating from skeleton to - * album — changes this value and re-arms the veil's quiet window. - * - * Unhydrated tiles deliberately do NOT gate `quiescent`. A tile whose - * on-miss fetch soft-fails keeps a null value indefinitely - * ([MetadataProvider] swallows those errors), so treating "no - * skeletons left" as the settle condition would pin the veil to its - * hard ceiling on every refresh. They're covered by the content key - * instead: each tile that lands re-arms the window, and once they stop - * landing the screen is genuinely still. - */ - private val settleSignal: Flow = - combine(uiState, artTracker.inFlight) { state, artInFlight -> - VeilSettleState( - contentKey = state, - hasContent = state is UiState.Success, - quiescent = artInFlight == 0, + /** + * Tap on a Most-played tile: replace the queue with the section's + * tracks and start at the tapped index. Home's section is itself the + * playable unit, not a list of album-detail links. + */ + fun playMostPlayed( + tracks: List, + startIndex: Int, + ) { + if (tracks.isEmpty()) return + player.setQueue( + tracks = tracks, + initialIndex = startIndex.coerceIn(0, tracks.lastIndex), + source = "home:most_played", ) } - private val veil = UpdateVeilController( - scope = viewModelScope, - settleSignal = settleSignal, - shouldVeil = { - // Only worth hiding churn when there's already content to - // hide. A cold load over an empty cache keeps its skeleton — - // veiling that would replace a useful affordance with an - // opaque panel. `hasCachedIndex` is the honest check: uiState - // still reads Loading until the screen subscribes, so on a - // process restore over a warm cache it would say "no content" - // right before the cache emits. - uiState.value is UiState.Success || homeRepository.hasCachedIndex() - }, - onSessionEnd = ::reportRefreshOutcome, - work = ::runRefresh, - ) - - /** - * Tells the user how a refresh *they asked for* went, in the one case - * the veil can't: when nothing changed there's no veil to see, and a - * pull that produces no visible response at all reads as broken. - * - * Only user-initiated sessions say anything. The same outcome from a - * background check — the initial load, the 03:00 rebuild, a reconnect — - * is noise, and "Already up to date" on every launch would be worse - * than silence. - */ - private fun reportRefreshOutcome(result: VeilSessionResult) { - if (!result.userInitiated) return - when (result.outcome) { - // The veil was the feedback. - VeilOutcome.CHANGED -> return - VeilOutcome.UNCHANGED -> snackbarMessages.trySend("Already up to date") - VeilOutcome.FAILED -> snackbarMessages.trySend("Couldn't check for updates") - } - } - - /** - * True while the "Updating your mixes…" veil should be raised. - * - * Raised only when a refresh actually changes what's on screen, and then - * held until Home settles — tiles hydrated, artwork loaded — instead of - * for a fixed delay after the network pull returns. A - * refresh that returns what's already cached shows no veil at all; - * [reportRefreshOutcome] tells the user instead, if they asked. - */ - val isUpdating: StateFlow = veil.visible - - init { - // Every refresh path goes through the controller, which decides - // per session whether to raise the veil. That includes the initial - // load: over a warm cache it's a full re-pull that churns every - // section. - veil.request() - // Screen-level auto-recovery: a Home that failed to - // load while the server was unreachable re-pulls itself the moment - // health returns — same idiom as SyncController, one layer up. - // This is also the recovery that keeps trying after the veil has - // given up and lowered; the controller sets no latch against it. - viewModelScope.launch { - networkStatus.recoveries().collect { veil.request() } - } - // Server-side changes that rewrite what Home renders re-pull - // behind the veil, as the web SSE consumer does. - viewModelScope.launch { - eventsStream.events - .filter { it.kind in VEILED_EVENT_KINDS } - .collect { veil.request() } - } - } - - private companion object { /** - * Events that change what Home shows. `playlist.system_rebuilt` - * is the 03:00 daily rebuild; the other `playlist.*` kinds move - * the Playlists and Songs-like rows; `scan.run_finished` changes - * Recently added (and Home never reacted to it at all before). + * Tap the album play-button overlay: fetch the album detail and + * play its tracks from the first. Suspending so the button's spinner + * waits for the fetch + queue setup; the inner work is launched in + * viewModelScope so cancellation from leaving the screen mid-fetch + * doesn't kill playback. Errors surface via the snackbar channel, + * like the ArtistDetail play handler. */ - private val VEILED_EVENT_KINDS = setOf( - "playlist.system_rebuilt", - "playlist.created", - "playlist.updated", - "playlist.deleted", - "playlist.tracks_changed", - "scan.run_finished", - ) + suspend fun playAlbum(albumId: String) { + viewModelScope + .launch { + playAlbumFromStart(albumId, libraryRepository, player) { snackbarMessages.trySend(it) } + }.join() + } + + /** + * Tap the artist play-button overlay: fetch every track across the + * artist's albums, shuffle, play from index 0 (shufflePlayArtist, as + * the Artist page's Play does). + */ + suspend fun playArtistShuffled(artistId: String) { + viewModelScope + .launch { + shufflePlayArtist(artistId, libraryRepository, player) { snackbarMessages.trySend(it) } + }.join() + } + + /** + * Tap the playlist play-button overlay: fetch the playlist's tracks + * (rotation-aware shuffle for refreshable system playlists, stored + * order for everything else), 8s timeout, play from index 0. + * Empty-mix and timeout get their own copy strings; other errors + * fall through to [ErrorCopy.fromThrowable]. + */ + suspend fun playPlaylist(playlist: PlaylistRef) { + viewModelScope + .launch { + playPlaylistShuffled(playlist, playlistsRepository, player) { + snackbarMessages.trySend(it) + } + }.join() + } + + /** + * Pulls /home/index, the playlists list and the system-playlist + * status. Returns true when the load-bearing /home/index pull + * succeeded — the veil controller retries on false and reports the + * outcome, so this must report failure rather than swallow it. + */ + private suspend fun runRefresh(): Boolean = + coroutineScope { + // /home/index is the load-bearing pull: its failure drives the + // empty-cache Error state. A failure over a populated cache + // stays silent — cached sections beat a full-screen error. + // + // Cleared on success, NOT at the start of each attempt: with the + // veil's retries, clearing up front made a failing cold start + // flash the "Welcome to Minstrel" empty state (empty cache + no + // error reads as Empty) between one attempt and the next. + val home = + async { + runCatching { homeRepository.refreshIndex() } + .onSuccess { refreshError.value = null } + .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } + .isSuccess + } + val lists = launch { runCatching { playlistsRepository.refreshList() } } + val status = + launch { + runCatching { homeRepository.getSystemPlaylistsStatus() } + .onSuccess { systemStatusInternal.value = it } + } + lists.join() + status.join() + home.await() + } + + /** + * The Error state's explicit Retry button. User-initiated, so it gets + * the controller's retries and reports its outcome; over an empty cache + * there's no content to protect, so no veil goes up. + */ + fun retry() = veil.request(userInitiated = true) + + /** + * Manual pull-to-refresh. Goes behind the veil like every other + * refresh: a pull churns the screen exactly as the automatic paths + * do, and a small spinner does not hide it. + * + * Suspends until the veil has taken over OR the session has finished, + * so the pull indicator hands off to exactly one successor: the veil if + * content changed, the "Already up to date" snackbar if it didn't. The + * timeout is only a backstop against a session that outlives it. + */ + suspend fun refreshFromPull() { + val before = veil.finishedSessions.value + veil.request(userInitiated = true) + withTimeoutOrNull(PULL_HANDOFF_TIMEOUT_MS) { + combine(veil.visible, veil.finishedSessions) { veiled, finished -> + veiled || finished != before + }.first { it } + } + } + + val uiState: StateFlow> = + combineHomeFlows().asCacheFirstStateFlow(viewModelScope) + + /** + * The core five section flows merged into the sections struct. Split + * out so each combine call stays inside the coroutines built-in arity + * limit (5) and avoids the typed-vararg acrobatics a wider combine + * across heterogeneous types would need. [observeHomeSections] then + * folds in the two you-might-like flows, and [combineHomeFlows] the + * playlists flow. + */ + private fun observeCoreSections() = + combine( + homeRepository.observeRecentlyAddedAlbums(), + homeRepository.observeRediscoverAlbums(), + homeRepository.observeRediscoverArtists(), + homeRepository.observeMostPlayedTracks(), + homeRepository.observeLastPlayedArtists(), + ) { recent, rediscoverAlbums, rediscoverArtists, mostPlayed, lastPlayed -> + HomeSections( + recentlyAddedAlbums = recent, + rediscoverAlbums = rediscoverAlbums, + rediscoverArtists = rediscoverArtists, + mostPlayedTracks = mostPlayed, + lastPlayedArtists = lastPlayed, + ) + } + + private fun observeHomeSections() = + combine( + observeCoreSections(), + homeRepository.observeYouMightLikeAlbums(), + homeRepository.observeYouMightLikeArtists(), + ) { core, ymlAlbums, ymlArtists -> + core.copy(youMightLikeAlbums = ymlAlbums, youMightLikeArtists = ymlArtists) + } + + private fun combineHomeFlows() = + combine( + observeHomeSections(), + playlistsRepository.observeAll(), + refreshError, + ) { sections, playlists, err -> + val merged = sections.copy(playlists = playlists) + when { + !merged.isAllEmpty -> UiState.Success(merged) + err != null -> UiState.Error(err) + else -> UiState.Empty + } + } + + // ─── Updating veil ─────────────────────────────────────────────── + // Declared after uiState: these initialisers read it, and Kotlin runs + // property initialisers and init blocks in declaration order. + + /** + * What the veil watches to decide Home has stopped moving: the whole + * rendered state, plus how many covers are still loading. + * + * [UiState.Success] wraps a [HomeSections] data class, so any visible + * change — a section swapping ids, one tile hydrating from skeleton to + * album — changes this value and re-arms the veil's quiet window. + * + * Unhydrated tiles deliberately do NOT gate `quiescent`. A tile whose + * on-miss fetch soft-fails keeps a null value indefinitely + * ([MetadataProvider] swallows those errors), so treating "no + * skeletons left" as the settle condition would pin the veil to its + * hard ceiling on every refresh. They're covered by the content key + * instead: each tile that lands re-arms the window, and once they stop + * landing the screen is genuinely still. + */ + private val settleSignal: Flow = + combine(uiState, artTracker.inFlight) { state, artInFlight -> + VeilSettleState( + contentKey = state, + hasContent = state is UiState.Success, + quiescent = artInFlight == 0, + ) + } + + private val veil = + UpdateVeilController( + scope = viewModelScope, + settleSignal = settleSignal, + shouldVeil = { + // Only worth hiding churn when there's already content to + // hide. A cold load over an empty cache keeps its skeleton — + // veiling that would replace a useful affordance with an + // opaque panel. `hasCachedIndex` is the honest check: uiState + // still reads Loading until the screen subscribes, so on a + // process restore over a warm cache it would say "no content" + // right before the cache emits. + uiState.value is UiState.Success || homeRepository.hasCachedIndex() + }, + onSessionEnd = ::reportRefreshOutcome, + work = ::runRefresh, + ) + + /** + * Tells the user how a refresh *they asked for* went, in the one case + * the veil can't: when nothing changed there's no veil to see, and a + * pull that produces no visible response at all reads as broken. + * + * Only user-initiated sessions say anything. The same outcome from a + * background check — the initial load, the 03:00 rebuild, a reconnect — + * is noise, and "Already up to date" on every launch would be worse + * than silence. + */ + private fun reportRefreshOutcome(result: VeilSessionResult) { + if (!result.userInitiated) return + when (result.outcome) { + // The veil was the feedback. + VeilOutcome.CHANGED -> return + VeilOutcome.UNCHANGED -> snackbarMessages.trySend("Already up to date") + VeilOutcome.FAILED -> snackbarMessages.trySend("Couldn't check for updates") + } + } + + /** + * True while the "Updating your mixes…" veil should be raised. + * + * Raised only when a refresh actually changes what's on screen, and then + * held until Home settles — tiles hydrated, artwork loaded — instead of + * for a fixed delay after the network pull returns. A + * refresh that returns what's already cached shows no veil at all; + * [reportRefreshOutcome] tells the user instead, if they asked. + */ + val isUpdating: StateFlow = veil.visible + + init { + // Every refresh path goes through the controller, which decides + // per session whether to raise the veil. That includes the initial + // load: over a warm cache it's a full re-pull that churns every + // section. + veil.request() + // Screen-level auto-recovery: a Home that failed to + // load while the server was unreachable re-pulls itself the moment + // health returns — same idiom as SyncController, one layer up. + // This is also the recovery that keeps trying after the veil has + // given up and lowered; the controller sets no latch against it. + viewModelScope.launch { + networkStatus.recoveries().collect { veil.request() } + } + // Server-side changes that rewrite what Home renders re-pull + // behind the veil, as the web SSE consumer does. + viewModelScope.launch { + eventsStream.events + .filter { it.kind in VEILED_EVENT_KINDS } + .collect { veil.request() } + } + } + + private companion object { + /** + * Events that change what Home shows. `playlist.system_rebuilt` + * is the 03:00 daily rebuild; the other `playlist.*` kinds move + * the Playlists and Songs-like rows; `scan.run_finished` changes + * Recently added (and Home never reacted to it at all before). + */ + private val VEILED_EVENT_KINDS = + setOf( + "playlist.system_rebuilt", + "playlist.created", + "playlist.updated", + "playlist.deleted", + "playlist.tracks_changed", + "scan.run_finished", + ) + } } -} // ─── Screen ────────────────────────────────────────────────────────── @@ -607,30 +625,34 @@ private fun HomeStateCrossfade( Crossfade(targetState = state::class, label = "home-state") { _ -> when (val s = state) { UiState.Loading -> HomeSkeletonContent() - UiState.Empty -> EmptyState( - title = "Welcome to Minstrel", - body = "Nothing to show yet — scan a folder in your server " + - "settings, then come back here for system playlists " + - "and recommendations.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load home", - message = s.message, - onRetry = { viewModel.retry() }, - ) - is UiState.Success -> HomeSuccessContent( - sections = s.data, - systemStatus = systemStatus, - offline = offline, - onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, - onArtistClick = { id -> navController.navigate(ArtistDetail(id)) }, - onPlaylistClick = { id -> navController.navigate(PlaylistDetail(id)) }, - onMostPlayedTap = viewModel::playMostPlayed, - onPlayPool = viewModel::playPool, - onPlayAlbum = viewModel::playAlbum, - onPlayArtist = viewModel::playArtistShuffled, - onPlayPlaylist = viewModel::playPlaylist, - ) + UiState.Empty -> + EmptyState( + title = "Welcome to Minstrel", + body = + "Nothing to show yet — scan a folder in your server " + + "settings, then come back here for system playlists " + + "and recommendations.", + ) + is UiState.Error -> + ErrorRetry( + title = "Couldn't load home", + message = s.message, + onRetry = { viewModel.retry() }, + ) + is UiState.Success -> + HomeSuccessContent( + sections = s.data, + systemStatus = systemStatus, + offline = offline, + onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, + onArtistClick = { id -> navController.navigate(ArtistDetail(id)) }, + onPlaylistClick = { id -> navController.navigate(PlaylistDetail(id)) }, + onMostPlayedTap = viewModel::playMostPlayed, + onPlayPool = viewModel::playPool, + onPlayAlbum = viewModel::playAlbum, + onPlayArtist = viewModel::playArtistShuffled, + onPlayPlaylist = viewModel::playPlaylist, + ) } } } @@ -650,13 +672,14 @@ private fun BoxScope.UpdatingVeil(visible: Boolean) { modifier = Modifier.matchParentSize(), ) { Box( - modifier = Modifier - .fillMaxSize() - .background(MaterialTheme.colorScheme.background.copy(alpha = VEIL_ALPHA)) - .clickable( - interactionSource = remember { MutableInteractionSource() }, - indication = null, - ) {}, + modifier = + Modifier + .fillMaxSize() + .background(MaterialTheme.colorScheme.background.copy(alpha = VEIL_ALPHA)) + .clickable( + interactionSource = remember { MutableInteractionSource() }, + indication = null, + ) {}, contentAlignment = Alignment.Center, ) { Row(verticalAlignment = Alignment.CenterVertically) { @@ -901,21 +924,23 @@ private fun RecentlyAddedGrid( val perRow = (albums.size + RECENTLY_ADDED_GRID_ROWS - 1) / RECENTLY_ADDED_GRID_ROWS val rows = albums.chunked(perRow.coerceAtLeast(1)) val cols = rows.maxOfOrNull { it.size } ?: 0 - val ordered = buildList { - for (c in 0 until cols) { - for (r in 0 until RECENTLY_ADDED_GRID_ROWS) { - rows.getOrNull(r)?.getOrNull(c)?.let { add(it) } + val ordered = + buildList { + for (c in 0 until cols) { + for (r in 0 until RECENTLY_ADDED_GRID_ROWS) { + rows.getOrNull(r)?.getOrNull(c)?.let { add(it) } + } } } - } LazyHorizontalGrid( rows = GridCells.Fixed(RECENTLY_ADDED_GRID_ROWS), contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier - .fillMaxWidth() - .height(RECENTLY_ADDED_GRID_HEIGHT_DP.dp), + modifier = + Modifier + .fillMaxWidth() + .height(RECENTLY_ADDED_GRID_HEIGHT_DP.dp), ) { gridItems(items = ordered, key = { it.id }) { tile -> val album = tile.value @@ -994,11 +1019,15 @@ private fun LazyListScope.lastPlayedSection( } @Composable -private fun EmptySection(title: String, body: String) { +private fun EmptySection( + title: String, + body: String, +) { Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), ) { Text( text = title, @@ -1067,8 +1096,9 @@ private fun LazyListScope.youMightLikeSection( } else { EmptySection( title = "You might like", - body = "We're still learning your taste — keep listening and " + - "picks you might like will show up here.", + body = + "We're still learning your taste — keep listening and " + + "picks you might like will show up here.", ) } } @@ -1134,37 +1164,41 @@ private fun PlaylistsRow( onPlayPlaylist: suspend (PlaylistRef) -> Unit, ) { val reals = rowItems.filterIsInstance().map { it.playlist } - val covers = remember(reals, shape) { - reals.map { it.id }.zip(assignShelfCovers(reals, shape.coversPerTile)).toMap() - } + val covers = + remember(reals, shape) { + reals.map { it.id }.zip(assignShelfCovers(reals, shape.coversPerTile)).toMap() + } val meta = remember(reals) { shelfMeta(reals) } val tallWidth = tallCardWidth(shape) HorizontalScrollRow(title = title, meta = meta) { itemsIndexed(items = rowItems) { _, item -> when (item) { - is PlaylistRowItem.OfflinePool -> OfflinePoolCard( - label = item.kind.label, - icon = iconForPool(item.kind), - onClick = { onPlayPool(item.kind) }, - ) - is PlaylistRowItem.Real -> ShelfTile( - shape = shape, - tallWidth = tallWidth, - playlist = item.playlist, - covers = covers[item.playlist.id].orEmpty(), - // Greyed offline when the tile needs the live server or - // isn't fully cached — dimmed but still tappable into the - // detail to shuffle whatever subset is cached. - greyed = offline && item.playlist.unavailableOffline, - onClick = { onPlaylistClick(item.playlist.id) }, - onPlay = { onPlayPlaylist(item.playlist) }, - ) - is PlaylistRowItem.Placeholder -> PlaylistPlaceholderCard( - label = item.label, - variant = item.variant, - shape = if (tallWidth != null) PlaceholderShape.TALL else shape.placeholder, - modifier = if (tallWidth != null) Modifier.width(tallWidth) else Modifier, - ) + is PlaylistRowItem.OfflinePool -> + OfflinePoolCard( + label = item.kind.label, + icon = iconForPool(item.kind), + onClick = { onPlayPool(item.kind) }, + ) + is PlaylistRowItem.Real -> + ShelfTile( + shape = shape, + tallWidth = tallWidth, + playlist = item.playlist, + covers = covers[item.playlist.id].orEmpty(), + // Greyed offline when the tile needs the live server or + // isn't fully cached — dimmed but still tappable into the + // detail to shuffle whatever subset is cached. + greyed = offline && item.playlist.unavailableOffline, + onClick = { onPlaylistClick(item.playlist.id) }, + onPlay = { onPlayPlaylist(item.playlist) }, + ) + is PlaylistRowItem.Placeholder -> + PlaylistPlaceholderCard( + label = item.label, + variant = item.variant, + shape = if (tallWidth != null) PlaceholderShape.TALL else shape.placeholder, + modifier = if (tallWidth != null) Modifier.width(tallWidth) else Modifier, + ) } } } @@ -1213,26 +1247,41 @@ private fun ShelfTile( * covers for genres. [coversPerTile] is how many distinct covers a tile * shows; [placeholder] is the shape a not-yet-built mix takes on the shelf. */ -internal enum class ShelfShape(val coversPerTile: Int, val placeholder: PlaceholderShape) { +internal enum class ShelfShape( + val coversPerTile: Int, + val placeholder: PlaceholderShape, +) { WIDE(coversPerTile = 1, placeholder = PlaceholderShape.WIDE), ROUND(coversPerTile = 1, placeholder = PlaceholderShape.ROUND), BAND(coversPerTile = 3, placeholder = PlaceholderShape.SQUARE), } -private fun iconForPool(kind: OfflinePoolKind) = when (kind) { - OfflinePoolKind.RECENTLY_PLAYED -> Lucide.History - OfflinePoolKind.LIKED -> Lucide.Heart -} +private fun iconForPool(kind: OfflinePoolKind) = + when (kind) { + OfflinePoolKind.RECENTLY_PLAYED -> Lucide.History + OfflinePoolKind.LIKED -> Lucide.Heart + } /** A cache-backed offline pool, a real playlist tile, or a not-yet-generated slot. */ internal sealed interface PlaylistRowItem { - data class OfflinePool(val kind: OfflinePoolKind) : PlaylistRowItem - data class Real(val playlist: PlaylistRef) : PlaylistRowItem - data class Placeholder(val label: String, val variant: String) : PlaylistRowItem + data class OfflinePool( + val kind: OfflinePoolKind, + ) : PlaylistRowItem + + data class Real( + val playlist: PlaylistRef, + ) : PlaylistRowItem + + data class Placeholder( + val label: String, + val variant: String, + ) : PlaylistRowItem } /** The two offline cache pools surfaced on Home when offline. */ -enum class OfflinePoolKind(val label: String) { +enum class OfflinePoolKind( + val label: String, +) { RECENTLY_PLAYED("Recently played"), LIKED("Liked"), } @@ -1257,10 +1306,11 @@ internal fun buildPlaylistsRow( offline: Boolean, ): List { if (!offline) return buildOnlineRow(owned, status) - val out = mutableListOf( - PlaylistRowItem.OfflinePool(OfflinePoolKind.RECENTLY_PLAYED), - PlaylistRowItem.OfflinePool(OfflinePoolKind.LIKED), - ) + val out = + mutableListOf( + PlaylistRowItem.OfflinePool(OfflinePoolKind.RECENTLY_PLAYED), + PlaylistRowItem.OfflinePool(OfflinePoolKind.LIKED), + ) val (available, greyed) = orderedRealPlaylists(owned).partition { !it.unavailableOffline } (available + greyed).forEach { out += PlaylistRowItem.Real(it) } return out @@ -1272,10 +1322,12 @@ private fun buildOnlineRow( status: SystemPlaylistsStatus, ): List { val out = mutableListOf() - out += owned.firstOrNull { it.systemVariant == "for_you" } + out += owned + .firstOrNull { it.systemVariant == "for_you" } ?.let { PlaylistRowItem.Real(it) } ?: PlaylistRowItem.Placeholder("For You", variantFor("for-you", status)) - out += owned.firstOrNull { it.systemVariant == "discover" } + out += owned + .firstOrNull { it.systemVariant == "discover" } ?.let { PlaylistRowItem.Real(it) } ?: PlaylistRowItem.Placeholder("Discover", variantFor("discover", status)) // Songs-like is not here: it has its own row. @@ -1307,9 +1359,10 @@ internal fun buildSongsLikeRow( (available + greyed).map { PlaylistRowItem.Real(it) } } mixes.isNotEmpty() -> mixes.map { PlaylistRowItem.Real(it) } - else -> List(SONGS_LIKE_PLACEHOLDER_SLOTS) { - PlaylistRowItem.Placeholder("Songs like…", variantFor("songs-like", status)) - } + else -> + List(SONGS_LIKE_PLACEHOLDER_SLOTS) { + PlaylistRowItem.Placeholder("Songs like…", variantFor("songs-like", status)) + } } } @@ -1324,9 +1377,10 @@ internal fun buildGenreMixRow( owned: List, offline: Boolean, ): List { - val mixes = owned - .filter { it.systemVariant == "genre_mix" } - .sortedWith(byShelfRank) + val mixes = + owned + .filter { it.systemVariant == "genre_mix" } + .sortedWith(byShelfRank) if (!offline) return mixes.map { PlaylistRowItem.Real(it) } val (available, greyed) = mixes.partition { !it.unavailableOffline } return (available + greyed).map { PlaylistRowItem.Real(it) } @@ -1350,12 +1404,16 @@ private fun orderedRealPlaylists(owned: List): List { return out } -private fun variantFor(slot: String, s: SystemPlaylistsStatus): String = when { - s.inFlight -> "building" - s.lastError != null -> "failed" - slot == "songs-like" && s.lastRunAt != null -> "seed-needed" - else -> "pending" -} +private fun variantFor( + slot: String, + s: SystemPlaylistsStatus, +): String = + when { + s.inFlight -> "building" + s.lastError != null -> "failed" + slot == "songs-like" && s.lastRunAt != null -> "seed-needed" + else -> "pending" + } // How many "Songs like…" placeholder cards the dedicated row shows while // the mixes haven't generated yet (building / seed-needed). Real mixes, @@ -1381,13 +1439,14 @@ private val ARTIST_ART = 104.dp * to Home's primary slots. Order matches `systemPlaylistRegistry` in * `internal/playlists/system.go`. */ -private val SECONDARY_SYSTEM_VARIANTS = listOf( - "deep_cuts", - "rediscover", - "new_for_you", - "on_this_day", - "first_listens", -) +private val SECONDARY_SYSTEM_VARIANTS = + listOf( + "deep_cuts", + "rediscover", + "new_for_you", + "on_this_day", + "first_listens", + ) @Composable private fun ArtistsRow( @@ -1440,21 +1499,23 @@ private fun MostPlayedRow( val perRow = (tracks.size + MOST_PLAYED_ROWS - 1) / MOST_PLAYED_ROWS val rows = tracks.chunked(perRow.coerceAtLeast(1)) val cols = rows.maxOfOrNull { it.size } ?: 0 - val ordered = buildList { - for (c in 0 until cols) { - for (r in 0 until MOST_PLAYED_ROWS) { - rows.getOrNull(r)?.getOrNull(c)?.let { add(it) } + val ordered = + buildList { + for (c in 0 until cols) { + for (r in 0 until MOST_PLAYED_ROWS) { + rows.getOrNull(r)?.getOrNull(c)?.let { add(it) } + } } } - } LazyHorizontalGrid( rows = GridCells.Fixed(MOST_PLAYED_ROWS), contentPadding = PaddingValues(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp), - modifier = Modifier - .fillMaxWidth() - .height(MOST_PLAYED_GRID_HEIGHT_DP.dp), + modifier = + Modifier + .fillMaxWidth() + .height(MOST_PLAYED_GRID_HEIGHT_DP.dp), ) { gridItems(items = ordered, key = { it.id }) { tile -> val track = tile.value @@ -1487,17 +1548,19 @@ private const val MOST_PLAYED_GRID_HEIGHT_DP = 200 @Composable private fun SkeletonCompactTrackTile() { Row( - modifier = Modifier - .width(MOST_PLAYED_TILE_WIDTH_DP.dp) - .height(MOST_PLAYED_TILE_HEIGHT_DP.dp) - .padding(horizontal = 8.dp, vertical = 4.dp), + modifier = + Modifier + .width(MOST_PLAYED_TILE_WIDTH_DP.dp) + .height(MOST_PLAYED_TILE_HEIGHT_DP.dp) + .padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, ) { Box( - modifier = Modifier - .size(MOST_PLAYED_COVER_DP.dp) - .clip(RoundedCornerShape(4.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + Modifier + .size(MOST_PLAYED_COVER_DP.dp) + .clip(RoundedCornerShape(4.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant), ) } } @@ -1508,11 +1571,12 @@ private fun CompactTrackTile( onClick: () -> Unit, ) { Row( - modifier = Modifier - .width(MOST_PLAYED_TILE_WIDTH_DP.dp) - .height(MOST_PLAYED_TILE_HEIGHT_DP.dp) - .clickable(onClick = onClick) - .padding(horizontal = 8.dp, vertical = 4.dp), + modifier = + Modifier + .width(MOST_PLAYED_TILE_WIDTH_DP.dp) + .height(MOST_PLAYED_TILE_HEIGHT_DP.dp) + .clickable(onClick = onClick) + .padding(horizontal = 8.dp, vertical = 4.dp), verticalAlignment = Alignment.CenterVertically, ) { TrackCoverThumb( @@ -1522,9 +1586,10 @@ private fun CompactTrackTile( ) Spacer(Modifier.width(8.dp)) Column( - modifier = Modifier - .weight(1f) - .fillMaxHeight(), + modifier = + Modifier + .weight(1f) + .fillMaxHeight(), verticalArrangement = Arrangement.Center, ) { Text( @@ -1544,4 +1609,3 @@ private fun CompactTrackTile( } } } - diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryRepository.kt index 517a38b3..5decc12d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/data/LibraryRepository.kt @@ -17,6 +17,11 @@ import retrofit2.create import javax.inject.Inject import javax.inject.Singleton +// LibraryRepository owns reads + refreshes for three entity families +// (artists / albums / tracks) plus shuffle. Function count scales with +// entity-family count; splitting into per-family repos would +// scatter the shared dao + retrofit plumbing for no real gain. + /** * Cache-first reads of artists/albums/tracks. The Room DAOs are the * source of truth ViewModels observe; refresh* methods pull from the @@ -27,183 +32,196 @@ import javax.inject.Singleton * own their interfaces (see NetworkModule), so there is no @Provides * per endpoint — fewer Hilt bindings, locality of reference. */ -// LibraryRepository owns reads + refreshes for three entity families -// (artists / albums / tracks) plus shuffle. Function count scales with -// entity-family count; splitting into per-family repos would -// scatter the shared dao + retrofit plumbing for no real gain. @Suppress("TooManyFunctions") @Singleton -class LibraryRepository @Inject constructor( - private val artistDao: CachedArtistDao, - private val albumDao: CachedAlbumDao, - private val trackDao: CachedTrackDao, - retrofit: Retrofit, -) { - private val api: LibraryApi = retrofit.create() +class LibraryRepository + @Inject + constructor( + private val artistDao: CachedArtistDao, + private val albumDao: CachedAlbumDao, + private val trackDao: CachedTrackDao, + retrofit: Retrofit, + ) { + private val api: LibraryApi = retrofit.create() - // ---- Reads (Flow, cache-first; the cache is the source of truth) ---- + // ---- Reads (Flow, cache-first; the cache is the source of truth) ---- - // Joins each artist to its first cached album (by sort title) so the - // tile cover derives from /api/albums/{id}/cover — cached_artists - // stores no cover and sync carries none. - fun observeArtists(): Flow> = - combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums -> - val firstAlbumByArtist = albums - .groupBy { it.artistId } - .mapValues { (_, list) -> list.minByOrNull { it.sortTitle }?.id ?: "" } - artists.map { it.toDomain(coverAlbumId = firstAlbumByArtist[it.id] ?: "") } + // Joins each artist to its first cached album (by sort title) so the + // tile cover derives from /api/albums/{id}/cover — cached_artists + // stores no cover and sync carries none. + fun observeArtists(): Flow> = + combine(artistDao.observeAll(), albumDao.observeAll()) { artists, albums -> + val firstAlbumByArtist = + albums + .groupBy { it.artistId } + .mapValues { (_, list) -> list.minByOrNull { it.sortTitle }?.id ?: "" } + artists.map { it.toDomain(coverAlbumId = firstAlbumByArtist[it.id] ?: "") } + } + + fun observeAlbums(): Flow> = albumDao.observeAll().map { rows -> rows.map { it.toDomain() } } + + fun observeAlbumsForArtist(artistId: String): Flow> = + albumDao.observeByArtist(artistId).map { rows -> rows.map { it.toDomain() } } + + fun observeTracksForAlbum(albumId: String): Flow> = + trackDao.observeByAlbum(albumId).map { rows -> rows.map { it.toDomain() } } + + // ---- Single-shot lookups ---- + + suspend fun getArtist(id: String): ArtistRef? = artistDao.getById(id)?.toDomain() + + suspend fun getAlbum(id: String): AlbumRef? = albumDao.getById(id)?.toDomain() + + suspend fun getTrack(id: String): TrackRef? = trackDao.getById(id)?.toDomain() + + // ---- Server refreshes (sync-style writes; errors propagate) ---- + + /** + * Pulls the full artist detail (ArtistRef + albums), persists both, + * and returns the in-memory snapshot. Lets the ArtistDetail screen + * render from the wire response without the Room round-trip. + */ + suspend fun refreshArtistDetail(id: String): ArtistDetailRef { + val wire = api.getArtistDetail(id) + artistDao.upsertAll(listOf(wire.toArtistEntity())) + albumDao.upsertAll(wire.albums.map { it.toEntity() }) + return ArtistDetailRef( + artist = + ArtistRef( + id = wire.id, + name = wire.name, + sortName = wire.sortName, + albumCount = wire.albumCount, + coverUrl = wire.coverUrl, + ), + albums = wire.albums.map { it.toDomain() }, + ) } - fun observeAlbums(): Flow> = - albumDao.observeAll().map { rows -> rows.map { it.toDomain() } } + /** + * Pulls every track for an artist (across all their albums). Used + * by the "Play artist" button on the ArtistDetail header. No + * persistence — the response is consumed straight into a player + * queue. + */ + suspend fun fetchArtistTracks(id: String): List = api.getArtistTracks(id).map { it.toDomain() } - fun observeAlbumsForArtist(artistId: String): Flow> = - albumDao.observeByArtist(artistId).map { rows -> rows.map { it.toDomain() } } + /** + * Pulls related artists for the ArtistDetail "Similar artists" + * strip. Network-only — non-critical UI, callers swallow failures + * and render nothing rather than blocking the screen. + */ + suspend fun fetchSimilarArtists(id: String): List = api.getSimilarArtists(id).map { it.toDomain() } - fun observeTracksForAlbum(albumId: String): Flow> = - trackDao.observeByAlbum(albumId).map { rows -> rows.map { it.toDomain() } } + /** + * Pulls the artist's top tracks for the ArtistDetail "Top tracks" + * panel. Network-only; tapping a row plays this exact list as a + * queue, so no persistence is needed. + */ + suspend fun fetchArtistTopTracks(id: String): List = api.getArtistTopTracks(id).map { it.toDomain() } - // ---- Single-shot lookups ---- + /** + * Pulls the album detail (AlbumRef + tracks), persists both, and + * returns the in-memory snapshot. Lets the AlbumDetail screen + * render immediately from the wire response without waiting for + * the Room round-trip. + */ + suspend fun refreshAlbumDetail(id: String): AlbumDetailRef { + val wire = api.getAlbumDetail(id) + albumDao.upsertAll(listOf(wire.toAlbumEntity())) + trackDao.upsertAll(wire.tracks.map { it.toEntity() }) + return AlbumDetailRef( + album = + AlbumRef( + id = wire.id, + title = wire.title, + artistId = wire.artistId, + sortTitle = wire.sortTitle, + artistName = wire.artistName, + year = wire.year, + trackCount = wire.trackCount, + durationSec = wire.durationSec, + coverUrl = wire.coverUrl, + ), + tracks = wire.tracks.map { it.toDomain() }, + ) + } - suspend fun getArtist(id: String): ArtistRef? = artistDao.getById(id)?.toDomain() + /** Track detail — single track, mainly for the hydration queue. */ + suspend fun refreshTrack(id: String) { + val wire = api.getTrack(id) + trackDao.upsertAll(listOf(wire.toEntity())) + } - suspend fun getAlbum(id: String): AlbumRef? = albumDao.getById(id)?.toDomain() + /** + * "Shuffle all" — server picks random tracks across the entire + * library. Backs the Library AppBar Shuffle button. No cache hit; + * the user-facing semantics are "give me something fresh". + */ + suspend fun shuffleLibrary(limit: Int = SHUFFLE_DEFAULT_LIMIT): List = + api.shuffleLibrary(limit = limit).map { it.toDomain() } - suspend fun getTrack(id: String): TrackRef? = trackDao.getById(id)?.toDomain() + // ---- Browse axes ---- + // + // Server-backed rather than cache-first, unlike everything above: the + // server's index leaves out tracks whose files are missing and is the + // one the web client shows. See LibraryApi for why the cache's own + // missing mark is not used to build it locally. - // ---- Server refreshes (sync-style writes; errors propagate) ---- + /** Genre index, ordered by track count then name (server order). */ + suspend fun genres(): List = api.getGenres().map { GenreCount(genre = it.genre, trackCount = it.trackCount) } - /** - * Pulls the full artist detail (ArtistRef + albums), persists both, - * and returns the in-memory snapshot. Lets the ArtistDetail screen - * render from the wire response without the Room round-trip. - */ - suspend fun refreshArtistDetail(id: String): ArtistDetailRef { - val wire = api.getArtistDetail(id) - artistDao.upsertAll(listOf(wire.toArtistEntity())) - albumDao.upsertAll(wire.albums.map { it.toEntity() }) - return ArtistDetailRef( - artist = ArtistRef( - id = wire.id, - name = wire.name, - sortName = wire.sortName, - albumCount = wire.albumCount, - coverUrl = wire.coverUrl, - ), - albums = wire.albums.map { it.toDomain() }, - ) + /** Year index, newest first. Albums with no release date are absent. */ + suspend fun albumYears(): List = api.getAlbumYears().map { YearCount(year = it.year, albumCount = it.albumCount) } + + /** One page of albums carrying [genre] on any track. */ + suspend fun albumsByGenre( + genre: String, + limit: Int, + offset: Int, + ): AlbumPage { + val page = api.getAlbumsByGenre(genre = genre, limit = limit, offset = offset) + return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total) + } + + /** One page of albums released in [year]. */ + suspend fun albumsByYear( + year: Int, + limit: Int, + offset: Int, + ): AlbumPage { + val page = + api.getAlbumsByYear( + yearFrom = year, + yearTo = year, + limit = limit, + offset = offset, + ) + return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total) + } + + private companion object { + const val SHUFFLE_DEFAULT_LIMIT = 100 + } } - /** - * Pulls every track for an artist (across all their albums). Used - * by the "Play artist" button on the ArtistDetail header. No - * persistence — the response is consumed straight into a player - * queue. - */ - suspend fun fetchArtistTracks(id: String): List = - api.getArtistTracks(id).map { it.toDomain() } - - /** - * Pulls related artists for the ArtistDetail "Similar artists" - * strip. Network-only — non-critical UI, callers swallow failures - * and render nothing rather than blocking the screen. - */ - suspend fun fetchSimilarArtists(id: String): List = - api.getSimilarArtists(id).map { it.toDomain() } - - /** - * Pulls the artist's top tracks for the ArtistDetail "Top tracks" - * panel. Network-only; tapping a row plays this exact list as a - * queue, so no persistence is needed. - */ - suspend fun fetchArtistTopTracks(id: String): List = - api.getArtistTopTracks(id).map { it.toDomain() } - - /** - * Pulls the album detail (AlbumRef + tracks), persists both, and - * returns the in-memory snapshot. Lets the AlbumDetail screen - * render immediately from the wire response without waiting for - * the Room round-trip. - */ - suspend fun refreshAlbumDetail(id: String): AlbumDetailRef { - val wire = api.getAlbumDetail(id) - albumDao.upsertAll(listOf(wire.toAlbumEntity())) - trackDao.upsertAll(wire.tracks.map { it.toEntity() }) - return AlbumDetailRef( - album = AlbumRef( - id = wire.id, - title = wire.title, - artistId = wire.artistId, - sortTitle = wire.sortTitle, - artistName = wire.artistName, - year = wire.year, - trackCount = wire.trackCount, - durationSec = wire.durationSec, - coverUrl = wire.coverUrl, - ), - tracks = wire.tracks.map { it.toDomain() }, - ) - } - - /** Track detail — single track, mainly for the hydration queue. */ - suspend fun refreshTrack(id: String) { - val wire = api.getTrack(id) - trackDao.upsertAll(listOf(wire.toEntity())) - } - - /** - * "Shuffle all" — server picks random tracks across the entire - * library. Backs the Library AppBar Shuffle button. No cache hit; - * the user-facing semantics are "give me something fresh". - */ - suspend fun shuffleLibrary(limit: Int = SHUFFLE_DEFAULT_LIMIT): List = - api.shuffleLibrary(limit = limit).map { it.toDomain() } - - // ---- Browse axes ---- - // - // Server-backed rather than cache-first, unlike everything above: the - // server's index leaves out tracks whose files are missing and is the - // one the web client shows. See LibraryApi for why the cache's own - // missing mark is not used to build it locally. - - /** Genre index, ordered by track count then name (server order). */ - suspend fun genres(): List = - api.getGenres().map { GenreCount(genre = it.genre, trackCount = it.trackCount) } - - /** Year index, newest first. Albums with no release date are absent. */ - suspend fun albumYears(): List = - api.getAlbumYears().map { YearCount(year = it.year, albumCount = it.albumCount) } - - /** One page of albums carrying [genre] on any track. */ - suspend fun albumsByGenre(genre: String, limit: Int, offset: Int): AlbumPage { - val page = api.getAlbumsByGenre(genre = genre, limit = limit, offset = offset) - return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total) - } - - /** One page of albums released in [year]. */ - suspend fun albumsByYear(year: Int, limit: Int, offset: Int): AlbumPage { - val page = api.getAlbumsByYear( - yearFrom = year, - yearTo = year, - limit = limit, - offset = offset, - ) - return AlbumPage(items = page.items.map { it.toDomain() }, total = page.total) - } - - private companion object { - const val SHUFFLE_DEFAULT_LIMIT = 100 - } -} - /** One row of the genre index. */ -data class GenreCount(val genre: String, val trackCount: Int) +data class GenreCount( + val genre: String, + val trackCount: Int, +) /** One row of the year index. */ -data class YearCount(val year: Int, val albumCount: Int) +data class YearCount( + val year: Int, + val albumCount: Int, +) /** * A page of albums plus the server's total for the whole filter, which is * what lets the UI say how many are left rather than just offering "more". */ -data class AlbumPage(val items: List, val total: Int) +data class AlbumPage( + val items: List, + val total: Int, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailScreen.kt index 9978e220..6e37770e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailScreen.kt @@ -2,6 +2,7 @@ package com.fabledsword.minstrel.library.ui +import androidx.compose.animation.Crossfade import androidx.compose.foundation.background import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Column @@ -12,7 +13,6 @@ import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size -import androidx.compose.animation.Crossfade import androidx.compose.foundation.layout.width import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items @@ -29,7 +29,6 @@ import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.text.style.TextOverflow @@ -51,12 +50,12 @@ import com.fabledsword.minstrel.shared.formatDuration import com.fabledsword.minstrel.shared.plural import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.CoverTile -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets -import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow +import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton @OptIn(ExperimentalMaterial3Api::class) @@ -95,11 +94,12 @@ fun AlbumDetailScreen( } } -private fun titleFor(state: AlbumDetailUiState): String = when (state) { - is AlbumDetailUiState.Success -> state.detail.album.title - is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album" - is AlbumDetailUiState.Error -> "Album" -} +private fun titleFor(state: AlbumDetailUiState): String = + when (state) { + is AlbumDetailUiState.Success -> state.detail.album.title + is AlbumDetailUiState.Loading -> state.seed?.title ?: "Album" + is AlbumDetailUiState.Error -> "Album" + } @Composable private fun AlbumDetailStateContent( @@ -115,11 +115,12 @@ private fun AlbumDetailStateContent( when (val s = state) { is AlbumDetailUiState.Loading -> if (s.seed != null) SeededAlbumLoading(s.seed) else SkeletonTrackList() - is AlbumDetailUiState.Error -> ErrorRetry( - title = "Couldn't load album", - message = s.message, - onRetry = { viewModel.refresh() }, - ) + is AlbumDetailUiState.Error -> + ErrorRetry( + title = "Couldn't load album", + message = s.message, + onRetry = { viewModel.refresh() }, + ) is AlbumDetailUiState.Success -> { val albumLiked by viewModel.albumLiked.collectAsStateWithLifecycle() val likedTrackIds by viewModel.likedTrackIds @@ -209,9 +210,10 @@ private fun AlbumHeader( onToggleAlbumLike: () -> Unit, ) { Column( - modifier = Modifier - .fillMaxWidth() - .padding(16.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { Row( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailViewModel.kt index 4673b634..3913ab0f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/AlbumDetailViewModel.kt @@ -28,112 +28,126 @@ import javax.inject.Inject private const val SHARE_STOP_TIMEOUT_MS = 5_000L sealed interface AlbumDetailUiState { - data class Loading(val seed: AlbumRef? = null) : AlbumDetailUiState - data class Success(val detail: AlbumDetailRef) : AlbumDetailUiState - data class Error(val message: String) : AlbumDetailUiState + data class Loading( + val seed: AlbumRef? = null, + ) : AlbumDetailUiState + + data class Success( + val detail: AlbumDetailRef, + ) : AlbumDetailUiState + + data class Error( + val message: String, + ) : AlbumDetailUiState } @HiltViewModel -class AlbumDetailViewModel @Inject constructor( - private val repository: LibraryRepository, - private val likes: LikesRepository, - private val player: PlayerController, - private val seedCache: DetailSeedCache, - networkStatus: NetworkStatusController, - savedStateHandle: SavedStateHandle, -) : ViewModel() { +class AlbumDetailViewModel + @Inject + constructor( + private val repository: LibraryRepository, + private val likes: LikesRepository, + private val player: PlayerController, + private val seedCache: DetailSeedCache, + networkStatus: NetworkStatusController, + savedStateHandle: SavedStateHandle, + ) : ViewModel() { + private val route: AlbumDetail = savedStateHandle.toRoute() + val albumId: String = route.id - private val route: AlbumDetail = savedStateHandle.toRoute() - val albumId: String = route.id + private val internal = + MutableStateFlow(AlbumDetailUiState.Loading()) + val uiState: StateFlow = internal.asStateFlow() - private val internal = - MutableStateFlow(AlbumDetailUiState.Loading()) - val uiState: StateFlow = internal.asStateFlow() + val albumLiked: StateFlow = + likes + .observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId) + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = false, + ) - val albumLiked: StateFlow = - likes.observeIsLiked(LikesRepository.ENTITY_ALBUM, albumId) - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = false, - ) + val likedTrackIds: StateFlow> = + likes + .observeLikedTrackIds() + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = emptySet(), + ) - val likedTrackIds: StateFlow> = - likes.observeLikedTrackIds() - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = emptySet(), - ) - - init { - refresh() - // Screen-level auto-recovery: a detail that failed to - // load while the server was unreachable re-fetches when health - // returns, so coming back to the screen shows content, not an error. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value is AlbumDetailUiState.Error) refresh() + init { + refresh() + // Screen-level auto-recovery: a detail that failed to + // load while the server was unreachable re-fetches when health + // returns, so coming back to the screen shows content, not an error. + viewModelScope.launch { + networkStatus.recoveries().collect { + if (internal.value is AlbumDetailUiState.Error) refresh() + } } } - } - fun refresh(): Job = viewModelScope.launch { - val carried = when (val cur = internal.value) { - is AlbumDetailUiState.Loading -> cur.seed - is AlbumDetailUiState.Success -> cur.detail.album - is AlbumDetailUiState.Error -> null + fun refresh(): Job = + viewModelScope.launch { + val carried = + when (val cur = internal.value) { + is AlbumDetailUiState.Loading -> cur.seed + is AlbumDetailUiState.Success -> cur.detail.album + is AlbumDetailUiState.Error -> null + } + internal.value = AlbumDetailUiState.Loading(carried ?: seedCache.peekAlbum(albumId)) + try { + val detail = repository.refreshAlbumDetail(albumId) + internal.value = AlbumDetailUiState.Success(detail) + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.value = AlbumDetailUiState.Error(ErrorCopy.fromThrowable(e)) + } + } + + /** Play the album starting at [startTrackId] (or the first track when null). */ + fun play(startTrackId: String?) { + val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return + if (detail.tracks.isEmpty()) return + val startIndex = + detail.tracks + .indexOfFirst { it.id == startTrackId } + .coerceAtLeast(0) + player.setQueue( + tracks = detail.tracks, + initialIndex = startIndex, + source = "album:${detail.album.id}", + ) } - internal.value = AlbumDetailUiState.Loading(carried ?: seedCache.peekAlbum(albumId)) - try { - val detail = repository.refreshAlbumDetail(albumId) - internal.value = AlbumDetailUiState.Success(detail) - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = AlbumDetailUiState.Error(ErrorCopy.fromThrowable(e)) + + /** + * Play the album in shuffled order. Pre-shuffles the list and hands + * the result to the player — matches the PlaylistDetail shuffle + * pattern. A future refinement could use Media3's + * `setShuffleModeEnabled` for play-then-shuffle without disturbing + * the original queue ordering. + */ + fun shuffle() { + val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return + if (detail.tracks.isEmpty()) return + player.setQueue( + tracks = detail.tracks.shuffled(), + initialIndex = 0, + source = "album:${detail.album.id}", + ) + } + + fun toggleLikeAlbum() { + val desired = !albumLiked.value + viewModelScope.launch { + likes.toggleLike(LikesRepository.ENTITY_ALBUM, albumId, desired) + } + } + + fun toggleLikeTrack(trackId: String) { + viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } } } - - /** Play the album starting at [startTrackId] (or the first track when null). */ - fun play(startTrackId: String?) { - val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return - if (detail.tracks.isEmpty()) return - val startIndex = detail.tracks - .indexOfFirst { it.id == startTrackId } - .coerceAtLeast(0) - player.setQueue( - tracks = detail.tracks, - initialIndex = startIndex, - source = "album:${detail.album.id}", - ) - } - - /** - * Play the album in shuffled order. Pre-shuffles the list and hands - * the result to the player — matches the PlaylistDetail shuffle - * pattern. A future refinement could use Media3's - * `setShuffleModeEnabled` for play-then-shuffle without disturbing - * the original queue ordering. - */ - fun shuffle() { - val detail = (internal.value as? AlbumDetailUiState.Success)?.detail ?: return - if (detail.tracks.isEmpty()) return - player.setQueue( - tracks = detail.tracks.shuffled(), - initialIndex = 0, - source = "album:${detail.album.id}", - ) - } - - fun toggleLikeAlbum() { - val desired = !albumLiked.value - viewModelScope.launch { - likes.toggleLike(LikesRepository.ENTITY_ALBUM, albumId, desired) - } - } - - fun toggleLikeTrack(trackId: String) { - viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailScreen.kt index e7760375..126c9158 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailScreen.kt @@ -20,16 +20,15 @@ import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items -import androidx.compose.foundation.lazy.items as lazyItems import androidx.compose.foundation.shape.CircleShape import androidx.compose.material3.Button import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.TopAppBar import androidx.compose.runtime.Composable @@ -58,14 +57,15 @@ import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.shared.formatDuration import com.fabledsword.minstrel.shared.plural import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.ServerImage +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile import com.fabledsword.minstrel.shared.widgets.TrackRow +import androidx.compose.foundation.lazy.items as lazyItems @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -111,11 +111,12 @@ fun ArtistDetailScreen( } else { SkeletonArtistAlbumsGrid() } - is ArtistDetailUiState.Error -> ErrorRetry( - title = "Couldn't load artist", - message = s.message, - onRetry = { viewModel.refresh() }, - ) + is ArtistDetailUiState.Error -> + ErrorRetry( + title = "Couldn't load artist", + message = s.message, + onRetry = { viewModel.refresh() }, + ) is ArtistDetailUiState.Success -> ArtistSuccessBody(s, viewModel, playerViewModel, navController) } @@ -145,11 +146,12 @@ private fun ArtistSuccessBody( ) } -private fun titleFor(state: ArtistDetailUiState): String = when (state) { - is ArtistDetailUiState.Success -> state.detail.artist.name - is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist" - is ArtistDetailUiState.Error -> "Artist" -} +private fun titleFor(state: ArtistDetailUiState): String = + when (state) { + is ArtistDetailUiState.Success -> state.detail.artist.name + is ArtistDetailUiState.Loading -> state.seed?.name ?: "Artist" + is ArtistDetailUiState.Error -> "Artist" + } @Composable private fun ArtistBody( @@ -278,9 +280,10 @@ private fun ArtistHeader( onToggleLike: () -> Unit, ) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(16.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { @@ -311,20 +314,25 @@ private fun ArtistHeader( } @Composable -private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) { +private fun ArtistAvatar( + artist: ArtistRef, + fallbackAlbumId: String? = null, +) { // Server coverUrl wins; otherwise use the first loaded album's // cover, the same rule the server applies. Bare Lucide.User only // when neither exists. - val model = when { - artist.coverUrl.isNotEmpty() -> artist.coverUrl - fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId) - else -> null - } + val model = + when { + artist.coverUrl.isNotEmpty() -> artist.coverUrl + fallbackAlbumId != null -> albumCoverPath(fallbackAlbumId) + else -> null + } Box( - modifier = Modifier - .size(96.dp) - .clip(CircleShape) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + Modifier + .size(96.dp) + .clip(CircleShape) + .background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center, ) { ServerImage( @@ -335,15 +343,15 @@ private fun ArtistAvatar(artist: ArtistRef, fallbackAlbumId: String? = null) { } } -private fun albumCountLine(artist: ArtistRef): String = - plural(artist.albumCount, "album", "albums") +private fun albumCountLine(artist: ArtistRef): String = plural(artist.albumCount, "album", "albums") @Composable private fun EmptyAlbumsHint() { Column( - modifier = Modifier - .fillMaxWidth() - .padding(24.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(24.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { Text( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailViewModel.kt index 76ec2991..d678afe8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/ArtistDetailViewModel.kt @@ -33,136 +33,146 @@ import javax.inject.Inject private const val SHARE_STOP_TIMEOUT_MS = 5_000L sealed interface ArtistDetailUiState { - data class Loading(val seed: ArtistRef? = null) : ArtistDetailUiState + data class Loading( + val seed: ArtistRef? = null, + ) : ArtistDetailUiState + data class Success( val detail: ArtistDetailRef, val similarArtists: List = emptyList(), val topTracks: List = emptyList(), ) : ArtistDetailUiState - data class Error(val message: String) : ArtistDetailUiState + + data class Error( + val message: String, + ) : ArtistDetailUiState } @HiltViewModel -class ArtistDetailViewModel @Inject constructor( - private val repository: LibraryRepository, - private val likes: LikesRepository, - private val player: PlayerController, - private val seedCache: DetailSeedCache, - networkStatus: NetworkStatusController, - savedStateHandle: SavedStateHandle, -) : ViewModel() { +class ArtistDetailViewModel + @Inject + constructor( + private val repository: LibraryRepository, + private val likes: LikesRepository, + private val player: PlayerController, + private val seedCache: DetailSeedCache, + networkStatus: NetworkStatusController, + savedStateHandle: SavedStateHandle, + ) : ViewModel() { + private val route: ArtistDetail = savedStateHandle.toRoute() + val artistId: String = route.id - private val route: ArtistDetail = savedStateHandle.toRoute() - val artistId: String = route.id + private val internal = + MutableStateFlow(ArtistDetailUiState.Loading()) + val uiState: StateFlow = internal.asStateFlow() - private val internal = - MutableStateFlow(ArtistDetailUiState.Loading()) - val uiState: StateFlow = internal.asStateFlow() + /** Transient one-shot messages for the screen-level snackbar (e.g. Play-button failure). */ + private val transientMessagesChannel = Channel(Channel.BUFFERED) + val transientMessages: Flow = transientMessagesChannel.receiveAsFlow() - /** Transient one-shot messages for the screen-level snackbar (e.g. Play-button failure). */ - private val transientMessagesChannel = Channel(Channel.BUFFERED) - val transientMessages: Flow = transientMessagesChannel.receiveAsFlow() + val artistLiked: StateFlow = + likes + .observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId) + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = false, + ) - val artistLiked: StateFlow = - likes.observeIsLiked(LikesRepository.ENTITY_ARTIST, artistId) - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = false, - ) - - init { - refresh() - // Screen-level auto-recovery. From Error, redo the - // whole load; from Success, re-pull just the secondary sections — - // their fetch failures are swallowed to emptyList, so a dead zone - // during the first load leaves them permanently absent otherwise. - viewModelScope.launch { - networkStatus.recoveries().collect { - when (internal.value) { - is ArtistDetailUiState.Error -> refresh() - is ArtistDetailUiState.Success -> loadSecondarySections() - is ArtistDetailUiState.Loading -> Unit + init { + refresh() + // Screen-level auto-recovery. From Error, redo the + // whole load; from Success, re-pull just the secondary sections — + // their fetch failures are swallowed to emptyList, so a dead zone + // during the first load leaves them permanently absent otherwise. + viewModelScope.launch { + networkStatus.recoveries().collect { + when (internal.value) { + is ArtistDetailUiState.Error -> refresh() + is ArtistDetailUiState.Success -> loadSecondarySections() + is ArtistDetailUiState.Loading -> Unit + } } } } - } - fun toggleLikeArtist() { - val desired = !artistLiked.value - viewModelScope.launch { - likes.toggleLike(LikesRepository.ENTITY_ARTIST, artistId, desired) - } - } - - fun refresh(): Job = viewModelScope.launch { - val carried = when (val cur = internal.value) { - is ArtistDetailUiState.Loading -> cur.seed - is ArtistDetailUiState.Success -> cur.detail.artist - is ArtistDetailUiState.Error -> null - } - internal.value = ArtistDetailUiState.Loading(carried ?: seedCache.peekArtist(artistId)) - try { - val detail = repository.refreshArtistDetail(artistId) - internal.value = ArtistDetailUiState.Success(detail) - loadSecondarySections() - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = ArtistDetailUiState.Error(ErrorCopy.fromThrowable(e)) - } - } - - /** - * Pulls the non-critical "Similar artists" + "Top tracks" sections - * and folds them into the live Success state. Each failure is - * swallowed (logged only) — these sections render absent rather than - * blocking, so the core artist view never depends on them. - */ - private suspend fun loadSecondarySections() { - val similar = sectionOrEmpty { repository.fetchSimilarArtists(artistId) } - val top = sectionOrEmpty { repository.fetchArtistTopTracks(artistId) } - val current = internal.value - if (current is ArtistDetailUiState.Success) { - internal.value = current.copy(similarArtists = similar, topTracks = top) - } - } - - private inline fun sectionOrEmpty(block: () -> List): List = - try { - block() - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.w(e, "Artist secondary section fetch failed for %s", artistId) - emptyList() + fun toggleLikeArtist() { + val desired = !artistLiked.value + viewModelScope.launch { + likes.toggleLike(LikesRepository.ENTITY_ARTIST, artistId, desired) + } } - /** - * Pull every track across the artist's albums, shuffle, and start - * playing. Pressing Play on an artist means "shuffle this artist", - * not "play album by album in tracklist order". One network - * round-trip per click; fine because the user explicitly tapped Play. - */ - fun playArtist() { - viewModelScope.launch { - shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) } + fun refresh(): Job = + viewModelScope.launch { + val carried = + when (val cur = internal.value) { + is ArtistDetailUiState.Loading -> cur.seed + is ArtistDetailUiState.Success -> cur.detail.artist + is ArtistDetailUiState.Error -> null + } + internal.value = ArtistDetailUiState.Loading(carried ?: seedCache.peekArtist(artistId)) + try { + val detail = repository.refreshArtistDetail(artistId) + internal.value = ArtistDetailUiState.Success(detail) + loadSecondarySections() + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.value = ArtistDetailUiState.Error(ErrorCopy.fromThrowable(e)) + } + } + + /** + * Pulls the non-critical "Similar artists" + "Top tracks" sections + * and folds them into the live Success state. Each failure is + * swallowed (logged only) — these sections render absent rather than + * blocking, so the core artist view never depends on them. + */ + private suspend fun loadSecondarySections() { + val similar = sectionOrEmpty { repository.fetchSimilarArtists(artistId) } + val top = sectionOrEmpty { repository.fetchArtistTopTracks(artistId) } + val current = internal.value + if (current is ArtistDetailUiState.Success) { + internal.value = current.copy(similarArtists = similar, topTracks = top) + } + } + + private inline fun sectionOrEmpty(block: () -> List): List = + try { + block() + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + Timber.w(e, "Artist secondary section fetch failed for %s", artistId) + emptyList() + } + + /** + * Pull every track across the artist's albums, shuffle, and start + * playing. Pressing Play on an artist means "shuffle this artist", + * not "play album by album in tracklist order". One network + * round-trip per click; fine because the user explicitly tapped Play. + */ + fun playArtist() { + viewModelScope.launch { + shufflePlayArtist(artistId, repository, player) { transientMessagesChannel.trySend(it) } + } + } + + /** + * Plays the loaded "Top tracks" list starting at [index] — the top + * tracks are themselves the playable queue (mirrors the web client's + * sectionTracks = top-tracks behaviour). No network round-trip; the + * list is already in the Success state. + */ + fun playTopTracks(index: Int) { + val tracks = (internal.value as? ArtistDetailUiState.Success)?.topTracks.orEmpty() + if (tracks.isEmpty()) return + player.setQueue( + tracks = tracks, + initialIndex = index.coerceIn(0, tracks.lastIndex), + source = "artist-top:$artistId", + ) } } - - /** - * Plays the loaded "Top tracks" list starting at [index] — the top - * tracks are themselves the playable queue (mirrors the web client's - * sectionTracks = top-tracks behaviour). No network round-trip; the - * list is already in the Success state. - */ - fun playTopTracks(index: Int) { - val tracks = (internal.value as? ArtistDetailUiState.Success)?.topTracks.orEmpty() - if (tracks.isEmpty()) return - player.setQueue( - tracks = tracks, - initialIndex = index.coerceIn(0, tracks.lastIndex), - source = "artist-top:$artistId", - ) - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/BrowseViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/BrowseViewModel.kt index 393a1a73..1d2a61df 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/BrowseViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/BrowseViewModel.kt @@ -41,6 +41,11 @@ data class AlbumBrowseState( val remaining: Int get() = (total - albums.size).coerceAtLeast(0) } +// Two browse axes, each with an index, a filter/sort or grouping, a +// drill-down and a pager. The function count is two axes' worth of a +// cohesive surface; splitting into GenresViewModel + YearsViewModel would +// duplicate the shared paging body for no gain. + /** * Backs the Genres and Years tabs, the same browse axes the web client has. * @@ -49,171 +54,183 @@ data class AlbumBrowseState( * missing and matches the web client's. These two tabs therefore need a * connection; the empty states say so rather than looking broken. */ -// Two browse axes, each with an index, a filter/sort or grouping, a -// drill-down and a pager. The function count is two axes' worth of a -// cohesive surface; splitting into GenresViewModel + YearsViewModel would -// duplicate the shared paging body for no gain. @Suppress("TooManyFunctions") @HiltViewModel -class BrowseViewModel @Inject constructor( - private val repository: LibraryRepository, -) : ViewModel() { +class BrowseViewModel + @Inject + constructor( + private val repository: LibraryRepository, + ) : ViewModel() { + private val genresInternal = MutableStateFlow>>(UiState.Loading) + val genres: StateFlow>> = genresInternal.asStateFlow() - private val genresInternal = MutableStateFlow>>(UiState.Loading) - val genres: StateFlow>> = genresInternal.asStateFlow() + private val yearsInternal = MutableStateFlow>>(UiState.Loading) + val years: StateFlow>> = yearsInternal.asStateFlow() - private val yearsInternal = MutableStateFlow>>(UiState.Loading) - val years: StateFlow>> = yearsInternal.asStateFlow() + private val genreFilterInternal = MutableStateFlow("") + val genreFilter: StateFlow = genreFilterInternal.asStateFlow() - private val genreFilterInternal = MutableStateFlow("") - val genreFilter: StateFlow = genreFilterInternal.asStateFlow() + private val genreSortInternal = MutableStateFlow(GenreSort.COUNT) + val genreSort: StateFlow = genreSortInternal.asStateFlow() - private val genreSortInternal = MutableStateFlow(GenreSort.COUNT) - val genreSort: StateFlow = genreSortInternal.asStateFlow() + private val selectedGenreInternal = MutableStateFlow(null) + val selectedGenre: StateFlow = selectedGenreInternal.asStateFlow() - private val selectedGenreInternal = MutableStateFlow(null) - val selectedGenre: StateFlow = selectedGenreInternal.asStateFlow() + private val selectedYearInternal = MutableStateFlow(null) + val selectedYear: StateFlow = selectedYearInternal.asStateFlow() - private val selectedYearInternal = MutableStateFlow(null) - val selectedYear: StateFlow = selectedYearInternal.asStateFlow() + private val genreAlbumsInternal = MutableStateFlow(AlbumBrowseState()) + val genreAlbums: StateFlow = genreAlbumsInternal.asStateFlow() - private val genreAlbumsInternal = MutableStateFlow(AlbumBrowseState()) - val genreAlbums: StateFlow = genreAlbumsInternal.asStateFlow() + private val yearAlbumsInternal = MutableStateFlow(AlbumBrowseState()) + val yearAlbums: StateFlow = yearAlbumsInternal.asStateFlow() - private val yearAlbumsInternal = MutableStateFlow(AlbumBrowseState()) - val yearAlbums: StateFlow = yearAlbumsInternal.asStateFlow() + // Guards against a slow response for a previously-selected genre/year + // landing after the user has moved on and painting over the new list. + // One counter per axis, since the two drill-downs are independent. + private var genreRequestToken = 0 + private var yearRequestToken = 0 - // Guards against a slow response for a previously-selected genre/year - // landing after the user has moved on and painting over the new list. - // One counter per axis, since the two drill-downs are independent. - private var genreRequestToken = 0 - private var yearRequestToken = 0 - - init { - loadGenres() - loadYears() - } - - fun loadGenres() { - viewModelScope.launch { - genresInternal.value = UiState.Loading - genresInternal.value = runCatching { repository.genres() }.fold( - onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) }, - onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) }, - ) + init { + loadGenres() + loadYears() } - } - fun loadYears() { - viewModelScope.launch { - yearsInternal.value = UiState.Loading - yearsInternal.value = runCatching { repository.albumYears() }.fold( - onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) }, - onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) }, - ) - } - } - - fun setGenreFilter(value: String) { genreFilterInternal.value = value } - - fun setGenreSort(sort: GenreSort) { genreSortInternal.value = sort } - - /** Drill into [genre], or pass null to go back to the index. */ - fun selectGenre(genre: String?) { - selectedGenreInternal.value = genre - genreRequestToken += 1 - genreAlbumsInternal.value = AlbumBrowseState() - if (genre == null) return - fetchGenrePage(genre, offset = 0, token = genreRequestToken) - } - - fun loadMoreGenreAlbums() { - val genre = selectedGenreInternal.value ?: return - val state = genreAlbumsInternal.value - if (state.loading || !state.hasMore) return - fetchGenrePage(genre, offset = state.albums.size, token = genreRequestToken) - } - - fun retryGenreAlbums() { - selectedGenreInternal.value?.let { selectGenre(it) } - } - - /** Drill into [year], or pass null to go back to the index. */ - fun selectYear(year: Int?) { - selectedYearInternal.value = year - yearRequestToken += 1 - yearAlbumsInternal.value = AlbumBrowseState() - if (year == null) return - fetchYearPage(year, offset = 0, token = yearRequestToken) - } - - fun loadMoreYearAlbums() { - val year = selectedYearInternal.value ?: return - val state = yearAlbumsInternal.value - if (state.loading || !state.hasMore) return - fetchYearPage(year, offset = state.albums.size, token = yearRequestToken) - } - - fun retryYearAlbums() { - selectedYearInternal.value?.let { selectYear(it) } - } - - private fun fetchGenrePage(genre: String, offset: Int, token: Int) { - fetchPage( - state = genreAlbumsInternal, - offset = offset, - isCurrent = { token == genreRequestToken }, - fetch = { repository.albumsByGenre(genre, PAGE_SIZE, offset) }, - ) - } - - private fun fetchYearPage(year: Int, offset: Int, token: Int) { - fetchPage( - state = yearAlbumsInternal, - offset = offset, - isCurrent = { token == yearRequestToken }, - fetch = { repository.albumsByYear(year, PAGE_SIZE, offset) }, - ) - } - - /** - * The paging body both axes share: append on success, and drop the result - * entirely if the selection moved while the request was in flight. - */ - private fun fetchPage( - state: MutableStateFlow, - offset: Int, - isCurrent: () -> Boolean, - fetch: suspend () -> AlbumPage, - ) { - viewModelScope.launch { - state.value = state.value.copy(loading = true, failed = false) - runCatching { fetch() }.fold( - onSuccess = { page -> - if (!isCurrent()) return@launch - val merged = - if (offset == 0) page.items else state.value.albums + page.items - state.value = AlbumBrowseState( - albums = merged, - total = page.total, - loading = false, - failed = false, + fun loadGenres() { + viewModelScope.launch { + genresInternal.value = UiState.Loading + genresInternal.value = + runCatching { repository.genres() }.fold( + onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) }, + onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) }, ) - }, - onFailure = { - if (!isCurrent()) return@launch - state.value = state.value.copy(loading = false, failed = true) - }, + } + } + + fun loadYears() { + viewModelScope.launch { + yearsInternal.value = UiState.Loading + yearsInternal.value = + runCatching { repository.albumYears() }.fold( + onSuccess = { if (it.isEmpty()) UiState.Empty else UiState.Success(it) }, + onFailure = { UiState.Error(ErrorCopy.fromThrowable(it)) }, + ) + } + } + + fun setGenreFilter(value: String) { + genreFilterInternal.value = value + } + + fun setGenreSort(sort: GenreSort) { + genreSortInternal.value = sort + } + + /** Drill into [genre], or pass null to go back to the index. */ + fun selectGenre(genre: String?) { + selectedGenreInternal.value = genre + genreRequestToken += 1 + genreAlbumsInternal.value = AlbumBrowseState() + if (genre == null) return + fetchGenrePage(genre, offset = 0, token = genreRequestToken) + } + + fun loadMoreGenreAlbums() { + val genre = selectedGenreInternal.value ?: return + val state = genreAlbumsInternal.value + if (state.loading || !state.hasMore) return + fetchGenrePage(genre, offset = state.albums.size, token = genreRequestToken) + } + + fun retryGenreAlbums() { + selectedGenreInternal.value?.let { selectGenre(it) } + } + + /** Drill into [year], or pass null to go back to the index. */ + fun selectYear(year: Int?) { + selectedYearInternal.value = year + yearRequestToken += 1 + yearAlbumsInternal.value = AlbumBrowseState() + if (year == null) return + fetchYearPage(year, offset = 0, token = yearRequestToken) + } + + fun loadMoreYearAlbums() { + val year = selectedYearInternal.value ?: return + val state = yearAlbumsInternal.value + if (state.loading || !state.hasMore) return + fetchYearPage(year, offset = state.albums.size, token = yearRequestToken) + } + + fun retryYearAlbums() { + selectedYearInternal.value?.let { selectYear(it) } + } + + private fun fetchGenrePage( + genre: String, + offset: Int, + token: Int, + ) { + fetchPage( + state = genreAlbumsInternal, + offset = offset, + isCurrent = { token == genreRequestToken }, + fetch = { repository.albumsByGenre(genre, PAGE_SIZE, offset) }, ) } - } - private companion object { - // Matches the web client's BROWSE_PAGE_SIZE so "Load more (N left)" - // steps at the same rate on both clients. - const val PAGE_SIZE = 50 + private fun fetchYearPage( + year: Int, + offset: Int, + token: Int, + ) { + fetchPage( + state = yearAlbumsInternal, + offset = offset, + isCurrent = { token == yearRequestToken }, + fetch = { repository.albumsByYear(year, PAGE_SIZE, offset) }, + ) + } + + /** + * The paging body both axes share: append on success, and drop the result + * entirely if the selection moved while the request was in flight. + */ + private fun fetchPage( + state: MutableStateFlow, + offset: Int, + isCurrent: () -> Boolean, + fetch: suspend () -> AlbumPage, + ) { + viewModelScope.launch { + state.value = state.value.copy(loading = true, failed = false) + runCatching { fetch() }.fold( + onSuccess = { page -> + if (!isCurrent()) return@launch + val merged = + if (offset == 0) page.items else state.value.albums + page.items + state.value = + AlbumBrowseState( + albums = merged, + total = page.total, + loading = false, + failed = false, + ) + }, + onFailure = { + if (!isCurrent()) return@launch + state.value = state.value.copy(loading = false, failed = true) + }, + ) + } + } + + private companion object { + // Matches the web client's BROWSE_PAGE_SIZE so "Load more (N left)" + // steps at the same rate on both clients. + const val PAGE_SIZE = 50 + } } -} /** * Apply the current filter and sort to a genre index. @@ -257,12 +274,12 @@ data class DecadeGroup( * same reason as [visibleGenres]. */ fun groupByDecade(years: List): List = - years.groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE } + years + .groupBy { (it.year / YEARS_PER_DECADE) * YEARS_PER_DECADE } .map { (decade, entries) -> DecadeGroup( decade = decade, years = entries.sortedByDescending { it.year }, albumCount = entries.sumOf { it.albumCount }, ) - } - .sortedByDescending { it.decade } + }.sortedByDescending { it.decade } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/GenresTab.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/GenresTab.kt index b9153327..32d5ddaf 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/GenresTab.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/GenresTab.kt @@ -10,11 +10,11 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.grid.GridCells import androidx.compose.foundation.lazy.grid.GridItemSpan import androidx.compose.foundation.lazy.grid.LazyVerticalGrid import androidx.compose.foundation.lazy.grid.items +import androidx.compose.foundation.lazy.items import androidx.compose.material3.FilterChip import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon @@ -32,8 +32,8 @@ import androidx.compose.ui.unit.dp import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import com.composables.icons.lucide.ArrowLeft -import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.LibraryBig +import com.composables.icons.lucide.Lucide import com.fabledsword.minstrel.library.widgets.AlbumCard import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.shared.UiState @@ -74,22 +74,26 @@ private fun GenreIndex(viewModel: BrowseViewModel) { val sort by viewModel.genreSort.collectAsStateWithLifecycle() when (val s = state) { - UiState.Loading -> EmptyState( - title = "Reading your genres…", - body = "", - icon = Lucide.LibraryBig, - ) - UiState.Empty -> EmptyState( - title = "No genres found", - body = "Genres come from the genre tag on your audio files. If your " + - "library is tagged but this is empty, try a rescan from the admin " + - "screen.", - icon = Lucide.LibraryBig, - ) - is UiState.Error -> ErrorRetry( - message = s.message, - onRetry = viewModel::loadGenres, - ) + UiState.Loading -> + EmptyState( + title = "Reading your genres…", + body = "", + icon = Lucide.LibraryBig, + ) + UiState.Empty -> + EmptyState( + title = "No genres found", + body = + "Genres come from the genre tag on your audio files. If your " + + "library is tagged but this is empty, try a rescan from the admin " + + "screen.", + icon = Lucide.LibraryBig, + ) + is UiState.Error -> + ErrorRetry( + message = s.message, + onRetry = viewModel::loadGenres, + ) is UiState.Success -> { val visible = visibleGenres(s.data, filter, sort) Column(modifier = Modifier.fillMaxSize()) { @@ -161,11 +165,12 @@ private fun GenreIndexControls( label = { Text("A–Z") }, ) Text( - text = if (filter.isBlank()) { - "$total genres" - } else { - "$shown of $total" - }, + text = + if (filter.isBlank()) { + "$total genres" + } else { + "$shown of $total" + }, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -174,12 +179,17 @@ private fun GenreIndexControls( } @Composable -private fun GenreRow(genre: String, trackCount: Int, onClick: () -> Unit) { +private fun GenreRow( + genre: String, + trackCount: Int, + onClick: () -> Unit, +) { Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .padding(horizontal = 16.dp, vertical = 14.dp), + modifier = + Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( @@ -263,20 +273,23 @@ fun BrowseAlbumResults( } when { - state.failed && state.albums.isEmpty() -> ErrorRetry( - message = "Couldn't load albums.", - onRetry = onRetry, - ) - state.loading && state.albums.isEmpty() -> EmptyState( - title = "Loading…", - body = "", - ) + state.failed && state.albums.isEmpty() -> + ErrorRetry( + message = "Couldn't load albums.", + onRetry = onRetry, + ) + state.loading && state.albums.isEmpty() -> + EmptyState( + title = "Loading…", + body = "", + ) state.albums.isEmpty() -> EmptyState(title = emptyTitle, body = emptyBody) - else -> BrowseAlbumGrid( - state = state, - onLoadMore = onLoadMore, - onAlbumClick = onAlbumClick, - ) + else -> + BrowseAlbumGrid( + state = state, + onLoadMore = onLoadMore, + onAlbumClick = onAlbumClick, + ) } } } @@ -334,8 +347,13 @@ private fun BrowseAlbumGrid( * is still in flight — a count that appears as 0 and then corrects itself reads * as a bug. */ -internal fun albumCountLabel(total: Int, loading: Boolean, loaded: Int): String = when { - loading && loaded == 0 -> "" - total == 1 -> "1 album" - else -> "$total albums" -} +internal fun albumCountLabel( + total: Int, + loading: Boolean, + loaded: Int, +): String = + when { + loading && loaded == 0 -> "" + total == 1 -> "1 album" + else -> "$total albums" + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/LibraryScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/LibraryScreen.kt index 50f5f8a2..9cc82e2e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/LibraryScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/LibraryScreen.kt @@ -26,30 +26,30 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp -import kotlinx.coroutines.launch import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController +import com.composables.icons.lucide.Lucide +import com.composables.icons.lucide.Shuffle import com.fabledsword.minstrel.history.ui.HistoryTab import com.fabledsword.minstrel.library.widgets.AlbumCard import com.fabledsword.minstrel.library.widgets.ArtistCard import com.fabledsword.minstrel.likes.ui.LikedTab -import com.fabledsword.minstrel.quarantine.ui.HiddenTab import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.ArtistRef import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.nav.Library -import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.Shuffle +import com.fabledsword.minstrel.quarantine.ui.HiddenTab import com.fabledsword.minstrel.shared.UiState -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.SkeletonAlbumTile import com.fabledsword.minstrel.shared.widgets.SkeletonArtistTile +import kotlinx.coroutines.launch /** * Library tab. Seven-tab TabBar (Artists / Albums / Genres / Years / @@ -130,16 +130,19 @@ private fun LibraryTabPage( when (page) { TAB_ARTISTS -> ArtistsTab(viewModel = viewModel, navController = navController) TAB_ALBUMS -> AlbumsTab(viewModel = viewModel, navController = navController) - TAB_GENRES -> GenresTab( - onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, - ) - TAB_YEARS -> YearsTab( - onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, - ) - TAB_HISTORY -> HistoryTab( - onNavigateToAlbum = { id -> navController.navigate(AlbumDetail(id)) }, - onNavigateToArtist = { id -> navController.navigate(ArtistDetail(id)) }, - ) + TAB_GENRES -> + GenresTab( + onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, + ) + TAB_YEARS -> + YearsTab( + onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, + ) + TAB_HISTORY -> + HistoryTab( + onNavigateToAlbum = { id -> navController.navigate(AlbumDetail(id)) }, + onNavigateToArtist = { id -> navController.navigate(ArtistDetail(id)) }, + ) TAB_LIKED -> LikedTab(navController = navController) TAB_HIDDEN -> HiddenTab() } @@ -174,19 +177,23 @@ private fun ArtistsTab( Crossfade(targetState = state::class, label = "library-artists") { _ -> when (val s = state) { UiState.Loading -> SkeletonArtistsGrid() - UiState.Empty -> EmptyState( - title = "No artists yet", - body = "Scan a folder in your server settings to " + - "populate the library.", - ) - is UiState.Error -> ErrorRetry( - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> ArtistsGrid( - artists = s.data.artists, - onArtistClick = { id -> navController.navigate(ArtistDetail(id)) }, - ) + UiState.Empty -> + EmptyState( + title = "No artists yet", + body = + "Scan a folder in your server settings to " + + "populate the library.", + ) + is UiState.Error -> + ErrorRetry( + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> + ArtistsGrid( + artists = s.data.artists, + onArtistClick = { id -> navController.navigate(ArtistDetail(id)) }, + ) } } } @@ -202,19 +209,23 @@ private fun AlbumsTab( Crossfade(targetState = state::class, label = "library-albums") { _ -> when (val s = state) { UiState.Loading -> SkeletonAlbumsGrid() - UiState.Empty -> EmptyState( - title = "No albums yet", - body = "Scan a folder in your server settings to " + - "populate the library.", - ) - is UiState.Error -> ErrorRetry( - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> AlbumsGrid( - albums = s.data.albums, - onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, - ) + UiState.Empty -> + EmptyState( + title = "No albums yet", + body = + "Scan a folder in your server settings to " + + "populate the library.", + ) + is UiState.Error -> + ErrorRetry( + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> + AlbumsGrid( + albums = s.data.albums, + onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, + ) } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/LibraryViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/LibraryViewModel.kt index beded2e3..390039bc 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/LibraryViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/LibraryViewModel.kt @@ -14,54 +14,57 @@ import kotlinx.coroutines.launch import javax.inject.Inject @HiltViewModel -class LibraryViewModel @Inject constructor( - private val repository: LibraryRepository, - private val syncController: SyncController, - private val player: com.fabledsword.minstrel.player.PlayerController, -) : ViewModel() { +class LibraryViewModel + @Inject + constructor( + private val repository: LibraryRepository, + private val syncController: SyncController, + private val player: com.fabledsword.minstrel.player.PlayerController, + ) : ViewModel() { + val uiState: StateFlow> = + combine( + repository.observeArtists(), + repository.observeAlbums(), + syncController.lastSyncError, + ) { artists, albums, syncError -> + when { + artists.isNotEmpty() || albums.isNotEmpty() -> + UiState.Success(LibraryData(artists, albums)) + // Empty cache + failed sync is a load failure, not an empty + // library — surface it so the user gets a Retry instead of + // the welcome copy. Heals automatically: SyncController + // re-syncs on health recovery, clearing lastSyncError. + syncError != null -> UiState.Error(syncError) + else -> UiState.Empty + } + }.asCacheFirstStateFlow(viewModelScope) - val uiState: StateFlow> = - combine( - repository.observeArtists(), - repository.observeAlbums(), - syncController.lastSyncError, - ) { artists, albums, syncError -> - when { - artists.isNotEmpty() || albums.isNotEmpty() -> - UiState.Success(LibraryData(artists, albums)) - // Empty cache + failed sync is a load failure, not an empty - // library — surface it so the user gets a Retry instead of - // the welcome copy. Heals automatically: SyncController - // re-syncs on health recovery, clearing lastSyncError. - syncError != null -> UiState.Error(syncError) - else -> UiState.Empty + /** + * Pull-to-refresh entry point. Triggers /api/library/sync via the + * SyncController; the resulting Room writes flow through the + * observeArtists/observeAlbums flows to re-render the grids. + */ + fun refresh(): Job = + viewModelScope.launch { + syncController.syncSafe() } - } - .asCacheFirstStateFlow(viewModelScope) - /** - * Pull-to-refresh entry point. Triggers /api/library/sync via the - * SyncController; the resulting Room writes flow through the - * observeArtists/observeAlbums flows to re-render the grids. - */ - fun refresh(): Job = viewModelScope.launch { - syncController.syncSafe() - } - - /** - * "Shuffle all" — fetches a random sample across the entire - * library and starts playback. Silent on transport failure (user - * can re-tap; the action has no inline error surface). - */ - fun shuffleAll() { - viewModelScope.launch { - runCatching { - val tracks = repository.shuffleLibrary() - .filter { it.streamUrl.isNotEmpty() } - if (tracks.isNotEmpty()) { - player.setQueue(tracks, initialIndex = 0, source = "library_shuffle") + /** + * "Shuffle all" — fetches a random sample across the entire + * library and starts playback. Silent on transport failure (user + * can re-tap; the action has no inline error surface). + */ + fun shuffleAll() { + viewModelScope.launch { + runCatching { + val tracks = + repository + .shuffleLibrary() + .filter { it.streamUrl.isNotEmpty() } + if (tracks.isNotEmpty()) { + player.setQueue(tracks, initialIndex = 0, source = "library_shuffle") + } } } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/YearsTab.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/YearsTab.kt index eb15d504..3209e2eb 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/ui/YearsTab.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/ui/YearsTab.kt @@ -2,7 +2,6 @@ package com.fabledsword.minstrel.library.ui import androidx.compose.foundation.clickable import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.fillMaxSize @@ -52,21 +51,25 @@ private fun YearIndex(viewModel: BrowseViewModel) { val state by viewModel.years.collectAsStateWithLifecycle() when (val s = state) { - UiState.Loading -> EmptyState( - title = "Reading release years…", - body = "", - icon = Lucide.Clock, - ) - UiState.Empty -> EmptyState( - title = "No release years found", - body = "Years come from the release date on your albums. Albums " + - "without one don't appear on this axis at all.", - icon = Lucide.Clock, - ) - is UiState.Error -> ErrorRetry( - message = s.message, - onRetry = viewModel::loadYears, - ) + UiState.Loading -> + EmptyState( + title = "Reading release years…", + body = "", + icon = Lucide.Clock, + ) + UiState.Empty -> + EmptyState( + title = "No release years found", + body = + "Years come from the release date on your albums. Albums " + + "without one don't appear on this axis at all.", + icon = Lucide.Clock, + ) + is UiState.Error -> + ErrorRetry( + message = s.message, + onRetry = viewModel::loadYears, + ) is UiState.Success -> { val decades = groupByDecade(s.data) LazyColumn( @@ -96,11 +99,15 @@ private fun YearIndex(viewModel: BrowseViewModel) { } @Composable -private fun DecadeHeader(decade: Int, albumCount: Int) { +private fun DecadeHeader( + decade: Int, + albumCount: Int, +) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 10.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween, ) { @@ -118,12 +125,17 @@ private fun DecadeHeader(decade: Int, albumCount: Int) { } @Composable -private fun YearRow(year: Int, albumCount: Int, onClick: () -> Unit) { +private fun YearRow( + year: Int, + albumCount: Int, + onClick: () -> Unit, +) { Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .padding(horizontal = 16.dp, vertical = 14.dp), + modifier = + Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, ) { Text( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/AlbumCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/AlbumCard.kt index 19205a0d..056387a8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/AlbumCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/AlbumCard.kt @@ -11,6 +11,7 @@ import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable +import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.Color import androidx.compose.ui.text.style.TextOverflow @@ -23,7 +24,6 @@ import com.fabledsword.minstrel.nav.LocalDetailSeedCache import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.CoverTile import com.fabledsword.minstrel.shared.widgets.PlayCircleButton -import androidx.compose.ui.Alignment /** * One album tile (~176dp wide, 144dp square cover). Tap fires @@ -49,12 +49,13 @@ fun AlbumCard( ) { val seedCache = LocalDetailSeedCache.current Surface( - modifier = modifier - .width(artSize + 32.dp) - .clickable { - seedCache.stashAlbum(album) - onClick() - }, + modifier = + modifier + .width(artSize + 32.dp) + .clickable { + seedCache.stashAlbum(album) + onClick() + }, color = Color.Transparent, ) { Column(modifier = Modifier.padding(horizontal = 8.dp)) { @@ -68,9 +69,10 @@ fun AlbumCard( if (onPlay != null) { PlayCircleButton( onPlay = onPlay, - modifier = Modifier - .align(Alignment.BottomEnd) - .padding(6.dp), + modifier = + Modifier + .align(Alignment.BottomEnd) + .padding(6.dp), ) } }, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/ArtistCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/ArtistCard.kt index fee0c6af..9655e3d6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/ArtistCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/library/widgets/ArtistCard.kt @@ -50,12 +50,13 @@ fun ArtistCard( ) { val seedCache = LocalDetailSeedCache.current Surface( - modifier = modifier - .width(artSize + 16.dp) - .clickable { - seedCache.stashArtist(artist) - onClick() - }, + modifier = + modifier + .width(artSize + 16.dp) + .clickable { + seedCache.stashArtist(artist) + onClick() + }, color = Color.Transparent, ) { Column( @@ -72,9 +73,10 @@ fun ArtistCard( if (onPlay != null) { PlayCircleButton( onPlay = onPlay, - modifier = Modifier - .align(Alignment.BottomEnd) - .padding(4.dp), + modifier = + Modifier + .align(Alignment.BottomEnd) + .padding(4.dp), ) } }, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt index b16ad99a..06dac7a9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt @@ -1,7 +1,5 @@ package com.fabledsword.minstrel.likes.data -import com.fabledsword.minstrel.cache.mutations.WriteOutcome -import com.fabledsword.minstrel.cache.mutations.likeToggleKey import com.fabledsword.minstrel.api.endpoints.LikesApi import com.fabledsword.minstrel.auth.AuthController import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao @@ -10,6 +8,8 @@ import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.likeToggleKey import com.fabledsword.minstrel.cache.mutations.sendOrQueue import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.library.data.toDomain @@ -28,10 +28,10 @@ import kotlinx.coroutines.launch import kotlinx.datetime.Clock import retrofit2.Retrofit import retrofit2.create +import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton import kotlin.time.Duration.Companion.milliseconds -import timber.log.Timber /** * Cache-first reads + offline-first writes for likes. @@ -54,203 +54,214 @@ import timber.log.Timber * are silently dropped (the SyncController fills the gap async). */ @Singleton -class LikesRepository @Inject constructor( - private val likeDao: CachedLikeDao, - private val albumDao: CachedAlbumDao, - private val artistDao: CachedArtistDao, - private val trackDao: CachedTrackDao, - private val mutationQueue: MutationQueue, - private val authController: AuthController, - @ApplicationScope private val scope: CoroutineScope, - retrofit: Retrofit, -) { - private val api: LikesApi = retrofit.create() +class LikesRepository + @Inject + constructor( + private val likeDao: CachedLikeDao, + private val albumDao: CachedAlbumDao, + private val artistDao: CachedArtistDao, + private val trackDao: CachedTrackDao, + private val mutationQueue: MutationQueue, + private val authController: AuthController, + @ApplicationScope private val scope: CoroutineScope, + retrofit: Retrofit, + ) { + private val api: LikesApi = retrofit.create() - init { - // Clear the outgoing user's cached_likes rows when the signed-in - // user changes. Discriminator-based queries already keep the wrong - // user from SEEING them; without this the rows pile up forever as - // different accounts sign in/out on the same device. - scope.launch { - var previousId: String? = null - authController.currentUser.collect { user -> - val newId = user?.id - val prev = previousId - if (prev != null && prev != newId) { - likeDao.clearForUser(prev) + init { + // Clear the outgoing user's cached_likes rows when the signed-in + // user changes. Discriminator-based queries already keep the wrong + // user from SEEING them; without this the rows pile up forever as + // different accounts sign in/out on the same device. + scope.launch { + var previousId: String? = null + authController.currentUser.collect { user -> + val newId = user?.id + val prev = previousId + if (prev != null && prev != newId) { + likeDao.clearForUser(prev) + } + previousId = newId } - previousId = newId } } - } - /** - * Server-user-uuid for the current session, or [ANONYMOUS_USER_ID] - * fallback when there's no signed-in user. Used as the - * `cached_likes.userId` discriminator so each account's likes are - * stored under its own bucket. - */ - private fun currentUserId(): String = - authController.currentUser.value?.id ?: ANONYMOUS_USER_ID + /** + * Server-user-uuid for the current session, or [ANONYMOUS_USER_ID] + * fallback when there's no signed-in user. Used as the + * `cached_likes.userId` discriminator so each account's likes are + * stored under its own bucket. + */ + private fun currentUserId(): String = authController.currentUser.value?.id ?: ANONYMOUS_USER_ID - // ── Reads ───────────────────────────────────────────────────────── + // ── Reads ───────────────────────────────────────────────────────── - fun observeLikedArtists(): Flow> = - likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_ARTIST).map { ids -> - ids.mapNotNull { artistDao.getById(it)?.toDomain() } + fun observeLikedArtists(): Flow> = + likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_ARTIST).map { ids -> + ids.mapNotNull { artistDao.getById(it)?.toDomain() } + } + + fun observeLikedAlbums(): Flow> = + likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_ALBUM).map { ids -> + ids.mapNotNull { albumDao.getById(it)?.toDomain() } + } + + fun observeLikedTracks(): Flow> = + likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_TRACK).map { ids -> + ids.mapNotNull { trackDao.getById(it)?.toDomain() } + } + + fun observeIsLiked( + entityType: String, + entityId: String, + ): Flow = likeDao.observeIsLiked(currentUserId(), entityType, entityId) + + /** + * Reactive set of liked track ids. Use this when the caller only + * needs "is X in liked set", NOT when it needs to render the liked + * tracks themselves — [observeLikedTracks] does a `mapNotNull` join + * against `trackDao` and drops any liked id whose track isn't in + * local cache yet, so an "is liked" UI built on `observeLikedTracks` + * misses cross-device likes whose track row hasn't cached. + * + * Used by playlist/album detail screens to color a row's like + * button independent of whether the track is in the local library. + */ + fun observeLikedTrackIds(): Flow> = likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_TRACK).map { it.toSet() } + + /** + * The liked track ids of whoever is signed in, most recently liked + * first, following sign-in and account changes. Emits nothing while + * signed out, so a long-lived collector never mistakes the anonymous + * empty set for "no likes". + */ + @OptIn(ExperimentalCoroutinesApi::class) + fun observeSignedInLikedTrackIdsNewestFirst(): Flow> = + authController.currentUser + .map { it?.id } + .distinctUntilChanged() + .filterNotNull() + .flatMapLatest { userId -> likeDao.observeLikedTrackIdsNewestFirst(userId) } + + /** [observeSignedInLikedTrackIdsNewestFirst] as a set. */ + fun observeSignedInLikedTrackIds(): Flow> = observeSignedInLikedTrackIdsNewestFirst().map { it.toSet() } + + /** One-shot snapshot of the liked track-id set — for the offline pool filter. */ + suspend fun likedTrackIds(): Set = likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_TRACK).first().toSet() + + // ── Writes (optimistic local → best-effort REST → enqueue on fail) ── + + /** + * Toggle like state for [entityType]/[entityId]. UI doesn't need to + * await this; the Flow re-emits immediately from the optimistic + * Room write. Returns true if the call reached the server, false + * if it got enqueued for later replay. + */ + suspend fun toggleLike( + entityType: String, + entityId: String, + desiredState: Boolean, + ): Boolean { + // 1. Optimistic Room mutation — scoped to the signed-in user + // (or the "local" bucket when nobody is signed in). + val uid = currentUserId() + if (desiredState) { + likeDao.upsertAll( + listOf(CachedLikeEntity(uid, entityType, entityId)), + ) + } else { + likeDao.delete(uid, entityType, entityId) + } + // An older toggle for this entity is still queued: going live would + // let it replay after this one and undo it. Queue behind it instead; + // the replayer sends only the newest toggle per entity. + if (mutationQueue.pendingLikeStates().containsKey(likeToggleKey(entityType, entityId))) { + mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) + return false + } + // 2. Best-effort REST call; 3. enqueue on failure. + val kindPath = serverPathFor(entityType) + // A refusal isn't surfaced: the heart buttons don't wait on this call, + // and the next likes refresh puts the server's answer back on screen. + return sendOrQueue( + send = { if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) }, + queue = { mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) }, + onRefused = { e -> + Timber.i(e, "likes: %s %s refused (%d)", entityType, entityId, e.code()) + WriteOutcome.Refused + }, + ) == WriteOutcome.Synced } - fun observeLikedAlbums(): Flow> = - likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_ALBUM).map { ids -> - ids.mapNotNull { albumDao.getById(it)?.toDomain() } - } + /** + * Pulls `GET /api/likes/ids` and atomically replaces the user's + * cached_likes set with the server's canonical view. Called by the + * LikedTab ViewModel on init and on a live likes event. + * + * A replace, not an upsert: upserts add rows for IDs the server has + * but never remove the ones it dropped, so an unlike made on another + * device would stay on the Liked tab forever. The replaceAllForUser + * DAO method runs a transactional delete-then-insert so the local + * set is exactly what the server reports. + * + * The server lists each kind most recently liked first but sends no + * times, so the rows are stamped a millisecond apart in that order; + * `likedAt` then sorts the way the server does. + * + * A like or unlike still queued here wins over the server's answer, + * which hasn't seen it yet: taking the server's would undo it on + * screen until the replay landed. + */ + suspend fun refreshIds() { + val uid = currentUserId() + val wire = api.ids() + val pending = mutationQueue.pendingLikeStates() + val now = Clock.System.now() - fun observeLikedTracks(): Flow> = - likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_TRACK).map { ids -> - ids.mapNotNull { trackDao.getById(it)?.toDomain() } - } - - fun observeIsLiked(entityType: String, entityId: String): Flow = - likeDao.observeIsLiked(currentUserId(), entityType, entityId) - - /** - * Reactive set of liked track ids. Use this when the caller only - * needs "is X in liked set", NOT when it needs to render the liked - * tracks themselves — [observeLikedTracks] does a `mapNotNull` join - * against `trackDao` and drops any liked id whose track isn't in - * local cache yet, so an "is liked" UI built on `observeLikedTracks` - * misses cross-device likes whose track row hasn't cached. - * - * Used by playlist/album detail screens to color a row's like - * button independent of whether the track is in the local library. - */ - fun observeLikedTrackIds(): Flow> = - likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_TRACK).map { it.toSet() } - - /** - * The liked track ids of whoever is signed in, most recently liked - * first, following sign-in and account changes. Emits nothing while - * signed out, so a long-lived collector never mistakes the anonymous - * empty set for "no likes". - */ - @OptIn(ExperimentalCoroutinesApi::class) - fun observeSignedInLikedTrackIdsNewestFirst(): Flow> = - authController.currentUser - .map { it?.id } - .distinctUntilChanged() - .filterNotNull() - .flatMapLatest { userId -> likeDao.observeLikedTrackIdsNewestFirst(userId) } - - /** [observeSignedInLikedTrackIdsNewestFirst] as a set. */ - fun observeSignedInLikedTrackIds(): Flow> = - observeSignedInLikedTrackIdsNewestFirst().map { it.toSet() } - - /** One-shot snapshot of the liked track-id set — for the offline pool filter. */ - suspend fun likedTrackIds(): Set = - likeDao.observeLikedIdsOfType(currentUserId(), ENTITY_TRACK).first().toSet() - - // ── Writes (optimistic local → best-effort REST → enqueue on fail) ── - - /** - * Toggle like state for [entityType]/[entityId]. UI doesn't need to - * await this; the Flow re-emits immediately from the optimistic - * Room write. Returns true if the call reached the server, false - * if it got enqueued for later replay. - */ - suspend fun toggleLike(entityType: String, entityId: String, desiredState: Boolean): Boolean { - // 1. Optimistic Room mutation — scoped to the signed-in user - // (or the "local" bucket when nobody is signed in). - val uid = currentUserId() - if (desiredState) { - likeDao.upsertAll( - listOf(CachedLikeEntity(uid, entityType, entityId)), - ) - } else { - likeDao.delete(uid, entityType, entityId) - } - // An older toggle for this entity is still queued: going live would - // let it replay after this one and undo it. Queue behind it instead; - // the replayer sends only the newest toggle per entity. - if (mutationQueue.pendingLikeStates().containsKey(likeToggleKey(entityType, entityId))) { - mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) - return false - } - // 2. Best-effort REST call; 3. enqueue on failure. - val kindPath = serverPathFor(entityType) - // A refusal isn't surfaced: the heart buttons don't wait on this call, - // and the next likes refresh puts the server's answer back on screen. - return sendOrQueue( - send = { if (desiredState) api.like(kindPath, entityId) else api.unlike(kindPath, entityId) }, - queue = { mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState) }, - onRefused = { e -> - Timber.i(e, "likes: %s %s refused (%d)", entityType, entityId, e.code()) - WriteOutcome.Refused - }, - ) == WriteOutcome.Synced - } - - /** - * Pulls `GET /api/likes/ids` and atomically replaces the user's - * cached_likes set with the server's canonical view. Called by the - * LikedTab ViewModel on init and on a live likes event. - * - * A replace, not an upsert: upserts add rows for IDs the server has - * but never remove the ones it dropped, so an unlike made on another - * device would stay on the Liked tab forever. The replaceAllForUser - * DAO method runs a transactional delete-then-insert so the local - * set is exactly what the server reports. - * - * The server lists each kind most recently liked first but sends no - * times, so the rows are stamped a millisecond apart in that order; - * `likedAt` then sorts the way the server does. - * - * A like or unlike still queued here wins over the server's answer, - * which hasn't seen it yet: taking the server's would undo it on - * screen until the replay landed. - */ - suspend fun refreshIds() { - val uid = currentUserId() - val wire = api.ids() - val pending = mutationQueue.pendingLikeStates() - val now = Clock.System.now() - fun rowsOf(type: String, ids: List) = - ids.filter { pending[likeToggleKey(type, it)] != false } + fun rowsOf( + type: String, + ids: List, + ) = ids + .filter { pending[likeToggleKey(type, it)] != false } .mapIndexed { i, id -> CachedLikeEntity(uid, type, id, likedAt = now - i.milliseconds) } - val rows = mutableListOf() - rows += rowsOf(ENTITY_ARTIST, wire.artistIds) - rows += rowsOf(ENTITY_ALBUM, wire.albumIds) - rows += rowsOf(ENTITY_TRACK, wire.trackIds) - val listed = rows.mapTo(HashSet()) { likeToggleKey(it.entityType, it.entityId) } - pending.filterValues { it }.keys.filter { it !in listed }.forEach { key -> - val (type, id) = key.split(":", limit = 2) - rows += CachedLikeEntity(uid, type, id, likedAt = now) + val rows = mutableListOf() + rows += rowsOf(ENTITY_ARTIST, wire.artistIds) + rows += rowsOf(ENTITY_ALBUM, wire.albumIds) + rows += rowsOf(ENTITY_TRACK, wire.trackIds) + val listed = rows.mapTo(HashSet()) { likeToggleKey(it.entityType, it.entityId) } + pending.filterValues { it }.keys.filter { it !in listed }.forEach { key -> + val (type, id) = key.split(":", limit = 2) + rows += CachedLikeEntity(uid, type, id, likedAt = now) + } + likeDao.replaceAllForUser(uid, rows) } - likeDao.replaceAllForUser(uid, rows) - } - companion object { - // Fallback discriminator for when no user is signed in. Reads - // query this bucket until the first authenticated refreshIds() - // writes rows under the real user UUID; reads then switch over - // via currentUserId(). - const val ANONYMOUS_USER_ID: String = "local" - const val ENTITY_ARTIST: String = "artist" - const val ENTITY_ALBUM: String = "album" - const val ENTITY_TRACK: String = "track" + companion object { + // Fallback discriminator for when no user is signed in. Reads + // query this bucket until the first authenticated refreshIds() + // writes rows under the real user UUID; reads then switch over + // via currentUserId(). + const val ANONYMOUS_USER_ID: String = "local" + const val ENTITY_ARTIST: String = "artist" + const val ENTITY_ALBUM: String = "album" + const val ENTITY_TRACK: String = "track" - private fun serverPathFor(entityType: String): String = when (entityType) { - ENTITY_ARTIST -> "artists" - ENTITY_ALBUM -> "albums" - ENTITY_TRACK -> "tracks" - else -> error("Unknown entity type: $entityType") + private fun serverPathFor(entityType: String): String = + when (entityType) { + ENTITY_ARTIST -> "artists" + ENTITY_ALBUM -> "albums" + ENTITY_TRACK -> "tracks" + else -> error("Unknown entity type: $entityType") + } } } -} /** * Flips a track's like, reading whether it is liked now from [likedIds], the * set the screen is already showing. The heart buttons on track lists (an * album, a playlist, the player) call this. */ -suspend fun LikesRepository.toggleTrackLike(trackId: String, likedIds: Set): Boolean = - toggleLike(LikesRepository.ENTITY_TRACK, trackId, desiredState = trackId !in likedIds) +suspend fun LikesRepository.toggleTrackLike( + trackId: String, + likedIds: Set, +): Boolean = toggleLike(LikesRepository.ENTITY_TRACK, trackId, desiredState = trackId !in likedIds) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/likes/ui/LikedTab.kt b/android/app/src/main/java/com/fabledsword/minstrel/likes/ui/LikedTab.kt index 72af673f..d959d39d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/likes/ui/LikedTab.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/likes/ui/LikedTab.kt @@ -1,7 +1,6 @@ package com.fabledsword.minstrel.likes.ui import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -28,9 +27,9 @@ import androidx.navigation.NavHostController import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries -import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.library.widgets.AlbumCard import com.fabledsword.minstrel.library.widgets.ArtistCard +import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.models.AlbumRef import com.fabledsword.minstrel.models.ArtistRef import com.fabledsword.minstrel.models.TrackRef @@ -39,7 +38,6 @@ import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.asCacheFirstStateFlow -import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.HorizontalScrollRow @@ -47,6 +45,7 @@ import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb +import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job @@ -70,70 +69,76 @@ data class LikedSections( // ─── ViewModel ─────────────────────────────────────────────────────── @HiltViewModel -class LikedTabViewModel @Inject constructor( - private val repository: LikesRepository, - private val player: PlayerController, - networkStatus: NetworkStatusController, -) : ViewModel() { +class LikedTabViewModel + @Inject + constructor( + private val repository: LikesRepository, + private val player: PlayerController, + networkStatus: NetworkStatusController, + ) : ViewModel() { + /** Copy for the most recent refresh failure; null once one succeeds. */ + private val refreshError = MutableStateFlow(null) - /** Copy for the most recent refresh failure; null once one succeeds. */ - private val refreshError = MutableStateFlow(null) + init { + refresh() + // Screen-level auto-recovery: re-pull when server + // health returns, so a load that failed offline heals unprompted. + viewModelScope.launch { + networkStatus.recoveries().collect { refresh() } + } + } - init { - refresh() - // Screen-level auto-recovery: re-pull when server - // health returns, so a load that failed offline heals unprompted. - viewModelScope.launch { - networkStatus.recoveries().collect { refresh() } + fun refresh(): Job = + viewModelScope.launch { + refreshError.value = null + runCatching { repository.refreshIds() } + .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } + } + + /** + * Unlike a track from inline heart-tap. The LikesRepository write + * routes through the MutationQueue so offline taps replay later. + */ + fun unlikeTrack(trackId: String) { + viewModelScope.launch { + repository.toggleLike(LikesRepository.ENTITY_TRACK, trackId, desiredState = false) + } + } + + val uiState: StateFlow> = + combine( + repository.observeLikedArtists(), + repository.observeLikedAlbums(), + repository.observeLikedTracks(), + refreshError, + ) { artists, albums, tracks, err -> + val sections = LikedSections(artists, albums, tracks) + when { + !sections.isAllEmpty -> UiState.Success(sections) + // Empty cache + failed refresh is a load failure, not "no + // likes yet" — surface Error so the user gets a Retry. + err != null -> UiState.Error(err) + else -> UiState.Empty + } + }.asCacheFirstStateFlow(viewModelScope) + + /** + * Build a queue from the currently-displayed liked tracks and start + * playback at [initialIndex]: the visible track list becomes the + * play queue. Tracks + * with empty streamUrl are ignored as queue entries (the row that + * routes here is itself click-gated on streamUrl). + */ + fun playTracks( + tracks: List, + initialIndex: Int, + ) { + if (tracks.isEmpty() || initialIndex !in tracks.indices) return + if (tracks[initialIndex].streamUrl.isEmpty()) return + player.setQueue(tracks, initialIndex = initialIndex, source = "liked") } } - fun refresh(): Job = viewModelScope.launch { - refreshError.value = null - runCatching { repository.refreshIds() } - .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } - } - - /** - * Unlike a track from inline heart-tap. The LikesRepository write - * routes through the MutationQueue so offline taps replay later. - */ - fun unlikeTrack(trackId: String) { - viewModelScope.launch { - repository.toggleLike(LikesRepository.ENTITY_TRACK, trackId, desiredState = false) - } - } - - val uiState: StateFlow> = combine( - repository.observeLikedArtists(), - repository.observeLikedAlbums(), - repository.observeLikedTracks(), - refreshError, - ) { artists, albums, tracks, err -> - val sections = LikedSections(artists, albums, tracks) - when { - !sections.isAllEmpty -> UiState.Success(sections) - // Empty cache + failed refresh is a load failure, not "no - // likes yet" — surface Error so the user gets a Retry. - err != null -> UiState.Error(err) - else -> UiState.Empty - } - }.asCacheFirstStateFlow(viewModelScope) - - /** - * Build a queue from the currently-displayed liked tracks and start - * playback at [initialIndex]: the visible track list becomes the - * play queue. Tracks - * with empty streamUrl are ignored as queue entries (the row that - * routes here is itself click-gated on streamUrl). - */ - fun playTracks(tracks: List, initialIndex: Int) { - if (tracks.isEmpty() || initialIndex !in tracks.indices) return - if (tracks[initialIndex].streamUrl.isEmpty()) return - player.setQueue(tracks, initialIndex = initialIndex, source = "liked") - } -} - // ─── Composable ────────────────────────────────────────────────────── @Composable @@ -148,28 +153,32 @@ fun LikedTab( PullToRefreshScaffold(onRefresh = { viewModel.refresh().join() }) { when (val s = state) { UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "No likes yet", - body = "Tap the heart on an artist, album, or track to start " + - "building your liked collection.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load likes", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> LikedContent( - sections = s.data, - playingTrackId = playingTrackId, - onArtistClick = { id -> navController.navigate(ArtistDetail(id)) }, - onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, - onTrackClick = { index -> - viewModel.playTracks(s.data.tracks, index) - }, - onUnlike = viewModel::unlikeTrack, - onNavigateToAlbum = { id -> navController.navigate(AlbumDetail(id)) }, - onNavigateToArtist = { id -> navController.navigate(ArtistDetail(id)) }, - ) + UiState.Empty -> + EmptyState( + title = "No likes yet", + body = + "Tap the heart on an artist, album, or track to start " + + "building your liked collection.", + ) + is UiState.Error -> + ErrorRetry( + title = "Couldn't load likes", + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> + LikedContent( + sections = s.data, + playingTrackId = playingTrackId, + onArtistClick = { id -> navController.navigate(ArtistDetail(id)) }, + onAlbumClick = { id -> navController.navigate(AlbumDetail(id)) }, + onTrackClick = { index -> + viewModel.playTracks(s.data.tracks, index) + }, + onUnlike = viewModel::unlikeTrack, + onNavigateToAlbum = { id -> navController.navigate(AlbumDetail(id)) }, + onNavigateToArtist = { id -> navController.navigate(ArtistDetail(id)) }, + ) } } } @@ -234,11 +243,15 @@ private fun LikedContent( } @Composable -private fun SectionHeader(label: String, count: Int) { +private fun SectionHeader( + label: String, + count: Int, +) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/metadata/FreshnessSweeper.kt b/android/app/src/main/java/com/fabledsword/minstrel/metadata/FreshnessSweeper.kt index 96550e1a..66575a27 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/metadata/FreshnessSweeper.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/metadata/FreshnessSweeper.kt @@ -34,43 +34,45 @@ private const val SWEEP_CONCURRENCY = 4 * in [com.fabledsword.minstrel.MinstrelApplication]. */ @Singleton -class FreshnessSweeper @Inject constructor( - private val albumDao: CachedAlbumDao, - private val artistDao: CachedArtistDao, - private val trackDao: CachedTrackDao, - private val metadataProvider: MetadataProvider, - @ApplicationScope private val appScope: CoroutineScope, -) { - init { - appScope.launch { - while (true) { - sweep() - delay(SWEEP_INTERVAL_MS) +class FreshnessSweeper + @Inject + constructor( + private val albumDao: CachedAlbumDao, + private val artistDao: CachedArtistDao, + private val trackDao: CachedTrackDao, + private val metadataProvider: MetadataProvider, + @ApplicationScope private val appScope: CoroutineScope, + ) { + init { + appScope.launch { + while (true) { + sweep() + delay(SWEEP_INTERVAL_MS) + } + } + } + + private suspend fun sweep() { + val cutoff = System.currentTimeMillis() - STALENESS_MS + val sem = Semaphore(SWEEP_CONCURRENCY) + sweepBucket(albumDao.idsStaleBefore(cutoff, SWEEP_BATCH_SIZE), sem) { id -> + metadataProvider.refreshAlbum(id).join() + } + sweepBucket(artistDao.idsStaleBefore(cutoff, SWEEP_BATCH_SIZE), sem) { id -> + metadataProvider.refreshArtist(id).join() + } + sweepBucket(trackDao.idsStaleBefore(cutoff, SWEEP_BATCH_SIZE), sem) { id -> + metadataProvider.refreshTrack(id).join() + } + } + + private suspend fun sweepBucket( + ids: List, + sem: Semaphore, + refresh: suspend (String) -> Unit, + ) { + ids.forEach { id -> + sem.withPermit { refresh(id) } } } } - - private suspend fun sweep() { - val cutoff = System.currentTimeMillis() - STALENESS_MS - val sem = Semaphore(SWEEP_CONCURRENCY) - sweepBucket(albumDao.idsStaleBefore(cutoff, SWEEP_BATCH_SIZE), sem) { id -> - metadataProvider.refreshAlbum(id).join() - } - sweepBucket(artistDao.idsStaleBefore(cutoff, SWEEP_BATCH_SIZE), sem) { id -> - metadataProvider.refreshArtist(id).join() - } - sweepBucket(trackDao.idsStaleBefore(cutoff, SWEEP_BATCH_SIZE), sem) { id -> - metadataProvider.refreshTrack(id).join() - } - } - - private suspend fun sweepBucket( - ids: List, - sem: Semaphore, - refresh: suspend (String) -> Unit, - ) { - ids.forEach { id -> - sem.withPermit { refresh(id) } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/metadata/HomeArtistPrewarmer.kt b/android/app/src/main/java/com/fabledsword/minstrel/metadata/HomeArtistPrewarmer.kt index d944cfaa..80e375bf 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/metadata/HomeArtistPrewarmer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/metadata/HomeArtistPrewarmer.kt @@ -18,16 +18,19 @@ private const val TOP_N = 8 * hydration — the prewarm can't starve the tiles the user is looking at. */ @Singleton -class HomeArtistPrewarmer @Inject constructor( - private val metadataProvider: MetadataProvider, -) { - private val warmed = Collections.synchronizedSet(mutableSetOf()) +class HomeArtistPrewarmer + @Inject + constructor( + private val metadataProvider: MetadataProvider, + ) { + private val warmed = Collections.synchronizedSet(mutableSetOf()) - fun warm(artistIds: List) { - artistIds.asSequence() - .filter { it.isNotEmpty() } - .filter { warmed.add(it) } - .take(TOP_N) - .forEach { metadataProvider.refreshArtist(it) } + fun warm(artistIds: List) { + artistIds + .asSequence() + .filter { it.isNotEmpty() } + .filter { warmed.add(it) } + .take(TOP_N) + .forEach { metadataProvider.refreshArtist(it) } + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/metadata/MetadataProvider.kt b/android/app/src/main/java/com/fabledsword/minstrel/metadata/MetadataProvider.kt index 3ffdb9c0..69ce0da8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/metadata/MetadataProvider.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/metadata/MetadataProvider.kt @@ -43,104 +43,114 @@ private const val HTTP_NOT_FOUND = 404 * automatically when the fetch lands. */ @Singleton -class MetadataProvider @Inject constructor( - private val albumDao: CachedAlbumDao, - private val artistDao: CachedArtistDao, - private val trackDao: CachedTrackDao, - private val libraryRepository: LibraryRepository, - @ApplicationScope private val appScope: CoroutineScope, -) { - private val inFlightAlbums = ConcurrentHashMap() - private val inFlightArtists = ConcurrentHashMap() - private val inFlightTracks = ConcurrentHashMap() - - // Caps concurrent on-miss fetches so a cold Home (~30 tiles) doesn't - // fire ~30 parallel /api calls. Per-id dedup (above) is orthogonal: - // the gate bounds distinct-id fetches; extras suspend on the semaphore. - private val fetchGate = Semaphore(MAX_CONCURRENT_FETCHES) - - /** - * Live AlbumRef? for [id]. Fires a background fetch the first - * time the cache emits null. Safe to subscribe concurrently from - * multiple tiles — fetch is deduplicated. - */ - fun observeAlbum(id: String): Flow = - albumDao.observeById(id) - .map { it?.toDomain() } - .onEach { row -> if (row == null) fetchAlbum(id) } - - fun observeArtist(id: String): Flow = - combine( - artistDao.observeById(id), - albumDao.observeByArtist(id), - ) { artist, albums -> - artist?.toDomain(coverAlbumId = albums.minByOrNull { it.sortTitle }?.id ?: "") - }.onEach { row -> if (row == null) fetchArtist(id) } - - fun observeTrack(id: String): Flow = - trackDao.observeById(id) - .map { it?.toDomain() } - .onEach { row -> if (row == null) fetchTrack(id) } - - /** - * Force-refresh [id] from the server even if the cache has it. - * Used by [FreshnessSweeper] to walk stale rows. Same dedup as - * the on-miss path — repeated calls during an in-flight fetch - * are no-ops. - */ - fun refreshAlbum(id: String): Job = fetchAlbum(id) - fun refreshArtist(id: String): Job = fetchArtist(id) - fun refreshTrack(id: String): Job = fetchTrack(id) - - private fun fetchAlbum(id: String): Job = launchDeduped( - inFlightAlbums, - id, - onGone = { albumDao.deleteByIds(listOf(id)) }, +class MetadataProvider + @Inject + constructor( + private val albumDao: CachedAlbumDao, + private val artistDao: CachedArtistDao, + private val trackDao: CachedTrackDao, + private val libraryRepository: LibraryRepository, + @ApplicationScope private val appScope: CoroutineScope, ) { - libraryRepository.refreshAlbumDetail(id) - } + private val inFlightAlbums = ConcurrentHashMap() + private val inFlightArtists = ConcurrentHashMap() + private val inFlightTracks = ConcurrentHashMap() - private fun fetchArtist(id: String): Job = launchDeduped( - inFlightArtists, - id, - onGone = { artistDao.deleteByIds(listOf(id)) }, - ) { - libraryRepository.refreshArtistDetail(id) - } + // Caps concurrent on-miss fetches so a cold Home (~30 tiles) doesn't + // fire ~30 parallel /api calls. Per-id dedup (above) is orthogonal: + // the gate bounds distinct-id fetches; extras suspend on the semaphore. + private val fetchGate = Semaphore(MAX_CONCURRENT_FETCHES) - private fun fetchTrack(id: String): Job = launchDeduped( - inFlightTracks, - id, - onGone = { trackDao.deleteByIds(listOf(id)) }, - ) { - libraryRepository.refreshTrack(id) - } + /** + * Live AlbumRef? for [id]. Fires a background fetch the first + * time the cache emits null. Safe to subscribe concurrently from + * multiple tiles — fetch is deduplicated. + */ + fun observeAlbum(id: String): Flow = + albumDao + .observeById(id) + .map { it?.toDomain() } + .onEach { row -> if (row == null) fetchAlbum(id) } - /** - * [onGone] runs when the server answers 404: the row no longer exists - * there (a duplicate merge, a deleted file), so the cached copy is - * dropped. Kept, it stays stale forever and [FreshnessSweeper] asks for - * it every pass. Any other failure leaves the row for a retry. - */ - private fun launchDeduped( - inFlight: ConcurrentHashMap, - id: String, - onGone: suspend () -> Unit, - block: suspend () -> Unit, - ): Job = inFlight.computeIfAbsent(id) { - appScope.launch { - try { - fetchGate.withPermit { block() } - } catch (e: HttpException) { - if (e.code() == HTTP_NOT_FOUND) onGone() - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + fun observeArtist(id: String): Flow = + combine( + artistDao.observeById(id), + albumDao.observeByArtist(id), + ) { artist, albums -> + artist?.toDomain(coverAlbumId = albums.minByOrNull { it.sortTitle }?.id ?: "") + }.onEach { row -> if (row == null) fetchArtist(id) } + + fun observeTrack(id: String): Flow = + trackDao + .observeById(id) + .map { it?.toDomain() } + .onEach { row -> if (row == null) fetchTrack(id) } + + /** + * Force-refresh [id] from the server even if the cache has it. + * Used by [FreshnessSweeper] to walk stale rows. Same dedup as + * the on-miss path — repeated calls during an in-flight fetch + * are no-ops. + */ + fun refreshAlbum(id: String): Job = fetchAlbum(id) + + fun refreshArtist(id: String): Job = fetchArtist(id) + + fun refreshTrack(id: String): Job = fetchTrack(id) + + private fun fetchAlbum(id: String): Job = + launchDeduped( + inFlightAlbums, + id, + onGone = { albumDao.deleteByIds(listOf(id)) }, ) { - // Soft-fail. Row stays null; tile stays skeletal until - // FreshnessSweeper retries or the user pulls to refresh. - } finally { - inFlight.remove(id) + libraryRepository.refreshAlbumDetail(id) + } + + private fun fetchArtist(id: String): Job = + launchDeduped( + inFlightArtists, + id, + onGone = { artistDao.deleteByIds(listOf(id)) }, + ) { + libraryRepository.refreshArtistDetail(id) + } + + private fun fetchTrack(id: String): Job = + launchDeduped( + inFlightTracks, + id, + onGone = { trackDao.deleteByIds(listOf(id)) }, + ) { + libraryRepository.refreshTrack(id) + } + + /** + * [onGone] runs when the server answers 404: the row no longer exists + * there (a duplicate merge, a deleted file), so the cached copy is + * dropped. Kept, it stays stale forever and [FreshnessSweeper] asks for + * it every pass. Any other failure leaves the row for a retry. + */ + private fun launchDeduped( + inFlight: ConcurrentHashMap, + id: String, + onGone: suspend () -> Unit, + block: suspend () -> Unit, + ): Job = + inFlight.computeIfAbsent(id) { + appScope.launch { + try { + fetchGate.withPermit { block() } + } catch (e: HttpException) { + if (e.code() == HTTP_NOT_FOUND) onGone() + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + // Soft-fail. Row stays null; tile stays skeletal until + // FreshnessSweeper retries or the user pulls to refresh. + } finally { + inFlight.remove(id) + } + } } - } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/ArtistRef.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/ArtistRef.kt index 190fba87..96b2887f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/ArtistRef.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/ArtistRef.kt @@ -26,9 +26,10 @@ data class ArtistRef( * the first album's cover instead. Resolve through `ServerImage`. */ val displayCoverUrl: String? - get() = when { - coverUrl.isNotEmpty() -> coverUrl - coverAlbumId.isNotEmpty() -> albumCoverPath(coverAlbumId) - else -> null - } + get() = + when { + coverUrl.isNotEmpty() -> coverUrl + coverAlbumId.isNotEmpty() -> albumCoverPath(coverAlbumId) + else -> null + } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt index d92a62a2..a86b179c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/CoverUrls.kt @@ -7,13 +7,11 @@ package com.fabledsword.minstrel.models * and the raw-AsyncImage cover surfaces still load it. The single * album-cover URL builder for the whole client. */ -fun albumCoverPath(albumId: String): String = - if (albumId.isEmpty()) "" else "http://placeholder.invalid/api/albums/$albumId/cover" +fun albumCoverPath(albumId: String): String = if (albumId.isEmpty()) "" else "http://placeholder.invalid/api/albums/$albumId/cover" /** * Absolute URL of an artist's image, or "" when [artistId] is blank. The * server answers with the artist's picture, or else their newest album * cover, through the same placeholder host as [albumCoverPath]. */ -fun artistImagePath(artistId: String): String = - if (artistId.isEmpty()) "" else "http://placeholder.invalid/api/artists/$artistId/image" +fun artistImagePath(artistId: String): String = if (artistId.isEmpty()) "" else "http://placeholder.invalid/api/artists/$artistId/image" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/HomeTile.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/HomeTile.kt index 7ca9365b..86cbb26a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/HomeTile.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/HomeTile.kt @@ -7,4 +7,7 @@ package com.fabledsword.minstrel.models * for null and the real card for non-null, keyed by [id] so the swap is * a content change rather than a re-key. */ -data class HomeTile(val id: String, val value: T?) +data class HomeTile( + val id: String, + val value: T?, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/QuarantineRef.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/QuarantineRef.kt index 8f6ecb48..a8d444c4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/QuarantineRef.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/QuarantineRef.kt @@ -20,13 +20,14 @@ data class QuarantineRef( val artistName: String = "", ) { val reasonLabel: String - get() = when (reason) { - "bad_rip" -> "Bad rip" - "wrong_file" -> "Wrong file" - "wrong_tags" -> "Wrong tags" - "duplicate" -> "Duplicate" - else -> "Other" - } + get() = + when (reason) { + "bad_rip" -> "Bad rip" + "wrong_file" -> "Wrong file" + "wrong_tags" -> "Wrong tags" + "duplicate" -> "Duplicate" + else -> "Other" + } /** * Cover URL derived from the parent album's diff --git a/android/app/src/main/java/com/fabledsword/minstrel/nav/DetailSeedCache.kt b/android/app/src/main/java/com/fabledsword/minstrel/nav/DetailSeedCache.kt index b79cd331..3c02fda9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/nav/DetailSeedCache.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/nav/DetailSeedCache.kt @@ -18,34 +18,48 @@ import javax.inject.Singleton * doesn't grow unbounded. */ @Singleton -class DetailSeedCache @Inject constructor() { - private val albums = lru(MAX_ENTRIES) - private val artists = lru(MAX_ENTRIES) - private val playlists = lru(MAX_ENTRIES) +class DetailSeedCache + @Inject + constructor() { + private val albums = lru(MAX_ENTRIES) + private val artists = lru(MAX_ENTRIES) + private val playlists = lru(MAX_ENTRIES) - @Synchronized fun stashAlbum(ref: AlbumRef) { albums[ref.id] = ref } - @Synchronized fun stashArtist(ref: ArtistRef) { artists[ref.id] = ref } - @Synchronized fun stashPlaylist(ref: PlaylistRef) { playlists[ref.id] = ref } + @Synchronized fun stashAlbum(ref: AlbumRef) { + albums[ref.id] = ref + } - @Synchronized fun peekAlbum(id: String): AlbumRef? = albums[id] - @Synchronized fun peekArtist(id: String): ArtistRef? = artists[id] - @Synchronized fun peekPlaylist(id: String): PlaylistRef? = playlists[id] + @Synchronized fun stashArtist(ref: ArtistRef) { + artists[ref.id] = ref + } - private companion object { - private const val MAX_ENTRIES = 32 - private const val LOAD_FACTOR = 0.75f - private fun lru(max: Int): MutableMap = - object : LinkedHashMap(max, LOAD_FACTOR, true) { - override fun removeEldestEntry(eldest: Map.Entry) = size > max - } + @Synchronized fun stashPlaylist(ref: PlaylistRef) { + playlists[ref.id] = ref + } + + @Synchronized fun peekAlbum(id: String): AlbumRef? = albums[id] + + @Synchronized fun peekArtist(id: String): ArtistRef? = artists[id] + + @Synchronized fun peekPlaylist(id: String): PlaylistRef? = playlists[id] + + private companion object { + private const val MAX_ENTRIES = 32 + private const val LOAD_FACTOR = 0.75f + + private fun lru(max: Int): MutableMap = + object : LinkedHashMap(max, LOAD_FACTOR, true) { + override fun removeEldestEntry(eldest: Map.Entry) = size > max + } + } } -} /** * CompositionLocal carrying the app's [DetailSeedCache]. Provided * at the [com.fabledsword.minstrel.MainActivity] root so any screen * can stash a seed before calling `navController.navigate(...)`. */ -val LocalDetailSeedCache = staticCompositionLocalOf { - error("DetailSeedCache not provided — wrap content in CompositionLocalProvider") -} +val LocalDetailSeedCache = + staticCompositionLocalOf { + error("DetailSeedCache not provided — wrap content in CompositionLocalProvider") + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/nav/MinstrelNavGraph.kt b/android/app/src/main/java/com/fabledsword/minstrel/nav/MinstrelNavGraph.kt index 0a5ec914..3f98fdfb 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/nav/MinstrelNavGraph.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/nav/MinstrelNavGraph.kt @@ -122,9 +122,7 @@ private fun NavGraphBuilder.inShellTopLevel( * is the [AnimatedContentScope]. */ @Composable -private fun AnimatedContentScope.WithAnimatedScope( - content: @Composable () -> Unit, -) { +private fun AnimatedContentScope.WithAnimatedScope(content: @Composable () -> Unit) { CompositionLocalProvider(LocalAnimatedContentScope provides this) { content() } @@ -215,4 +213,3 @@ private fun NavGraphBuilder.outsideShell(navController: NavHostController) { composable { ServerUrlScreen(navController = navController) } composable { LoginScreen(navController = navController) } } - diff --git a/android/app/src/main/java/com/fabledsword/minstrel/nav/Routes.kt b/android/app/src/main/java/com/fabledsword/minstrel/nav/Routes.kt index 53d87db6..6c7dc5d4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/nav/Routes.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/nav/Routes.kt @@ -6,26 +6,47 @@ import kotlinx.serialization.Serializable // icons + kebab) ────────────────────────────────────────────────────── @Serializable data object Home + @Serializable data object Library + @Serializable data object Search + @Serializable data object Playlists + @Serializable data object Settings + @Serializable data object Admin + @Serializable data object Notifications + @Serializable data object NotificationSettings // ── In-shell detail / push-on-top destinations ──────────────────────── -@Serializable data class AlbumDetail(val id: String) -@Serializable data class ArtistDetail(val id: String) -@Serializable data class PlaylistDetail(val id: String) +@Serializable data class AlbumDetail( + val id: String, +) + +@Serializable data class ArtistDetail( + val id: String, +) + +@Serializable data class PlaylistDetail( + val id: String, +) + @Serializable data object AdminQuarantine + @Serializable data object AdminUsers + @Serializable data object AdminTagSources // ── Outside-shell full-screen routes ────────────────────────────────── -@Serializable data object NowPlaying // slide-up modal transition -@Serializable data object Queue // standard push -@Serializable data object ServerUrl // unauthenticated layer -@Serializable data object Login // unauthenticated layer +@Serializable data object NowPlaying // slide-up modal transition + +@Serializable data object Queue // standard push + +@Serializable data object ServerUrl // unauthenticated layer + +@Serializable data object Login // unauthenticated layer diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt index dfac124c..79ea6dbd 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepository.kt @@ -22,7 +22,13 @@ import javax.inject.Inject import javax.inject.Singleton /** A notification channel, as the server names it. */ -enum class NotificationChannel(val wire: String) { INBOX("inbox"), PHONE("phone"), EMAIL("email") } +enum class NotificationChannel( + val wire: String, +) { + INBOX("inbox"), + PHONE("phone"), + EMAIL("email"), +} /** * Per-user notification settings, offline-first: the device copy (a @@ -30,74 +36,82 @@ enum class NotificationChannel(val wire: String) { INBOX("inbox"), PHONE("phone" * failed or out-of-order one is queued for the MutationReplayer. */ @Singleton -class NotificationSettingsRepository @Inject constructor( - retrofit: Retrofit, - private val dao: CachedNotificationDao, - private val mutationDao: CachedMutationDao, - private val mutationQueue: MutationQueue, - private val json: Json, -) { - private val api: NotificationsApi = retrofit.create() +class NotificationSettingsRepository + @Inject + constructor( + retrofit: Retrofit, + private val dao: CachedNotificationDao, + private val mutationDao: CachedMutationDao, + private val mutationQueue: MutationQueue, + private val json: Json, + ) { + private val api: NotificationsApi = retrofit.create() - val settings: Flow = dao.observeSettings().map { it?.let(::decode) } + val settings: Flow = dao.observeSettings().map { it?.let(::decode) } - /** - * Takes the server's settings unless a change made here is still queued: - * the server has not seen it, and its older value would undo the change - * on screen until the replay lands. Throws on a network failure. - */ - suspend fun refresh() { - val server = api.getSettings() - if (mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET)) return - save(server) - } + /** + * Takes the server's settings unless a change made here is still queued: + * the server has not seen it, and its older value would undo the change + * on screen until the replay lands. Throws on a network failure. + */ + suspend fun refresh() { + val server = api.getSettings() + if (mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET)) return + save(server) + } - suspend fun set(kind: String, channel: NotificationChannel, value: Boolean) { - current()?.let { save(it.withChannel(kind, channel, value)) } - val payload = NotificationSettingPayload(kind = kind, channel = channel.wire, value = value) - // An earlier change still queued would replay after this PUT; queue - // behind it instead, and the replayer sends the newest per channel. - if (mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET)) { - mutationQueue.enqueueNotificationSettingSet(payload) - return + suspend fun set( + kind: String, + channel: NotificationChannel, + value: Boolean, + ) { + current()?.let { save(it.withChannel(kind, channel, value)) } + val payload = NotificationSettingPayload(kind = kind, channel = channel.wire, value = value) + // An earlier change still queued would replay after this PUT; queue + // behind it instead, and the replayer sends the newest per channel. + if (mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET)) { + mutationQueue.enqueueNotificationSettingSet(payload) + return + } + val change = notificationSettingChange(payload) ?: return + sendOrQueue( + send = { save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) }, + queue = { mutationQueue.enqueueNotificationSettingSet(payload) }, + onRefused = { e -> + Timber.i(e, "notification settings: PUT refused (%d)", e.code()) + WriteOutcome.Refused + }, + ) + } + + private suspend fun current(): NotificationSettingsWire? = dao.getSettings()?.let(::decode) + + /** Null for an unreadable row: the next refresh writes a good one. */ + private fun decode(row: CachedNotificationSettingsEntity): NotificationSettingsWire? = + runCatching { json.decodeFromString(NotificationSettingsWire.serializer(), row.json) }.getOrNull() + + private suspend fun save(s: NotificationSettingsWire) { + val encoded = json.encodeToString(NotificationSettingsWire.serializer(), s) + dao.upsertSettings(CachedNotificationSettingsEntity(json = encoded)) } - val change = notificationSettingChange(payload) ?: return - sendOrQueue( - send = { save(api.putSettings(PutNotificationSettingsBody(listOf(change)))) }, - queue = { mutationQueue.enqueueNotificationSettingSet(payload) }, - onRefused = { e -> - Timber.i(e, "notification settings: PUT refused (%d)", e.code()) - WriteOutcome.Refused - }, - ) } - private suspend fun current(): NotificationSettingsWire? = dao.getSettings()?.let(::decode) - - /** Null for an unreadable row: the next refresh writes a good one. */ - private fun decode(row: CachedNotificationSettingsEntity): NotificationSettingsWire? = - runCatching { json.decodeFromString(NotificationSettingsWire.serializer(), row.json) }.getOrNull() - - private suspend fun save(s: NotificationSettingsWire) { - val encoded = json.encodeToString(NotificationSettingsWire.serializer(), s) - dao.upsertSettings(CachedNotificationSettingsEntity(json = encoded)) - } -} - internal fun NotificationSettingsWire.withChannel( kind: String, channel: NotificationChannel, value: Boolean, -): NotificationSettingsWire = copy( - kinds = kinds.map { k -> - if (k.kind != kind) { - k - } else { - when (channel) { - NotificationChannel.INBOX -> k.copy(inbox = value) - NotificationChannel.PHONE -> k.copy(phone = value) - NotificationChannel.EMAIL -> k.copy(email = value) - } - } - }, -) +): NotificationSettingsWire = + copy( + kinds = + kinds.map { k -> + if (k.kind != kind) { + k + } else { + when (channel) { + NotificationChannel.INBOX -> k.copy(inbox = value) + NotificationChannel.PHONE -> k.copy(phone = value) + NotificationChannel.EMAIL -> k.copy(email = value) + } + } + }, + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt index f8e76e8b..9b618035 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/data/NotificationsRepository.kt @@ -27,81 +27,85 @@ import kotlin.time.Duration.Companion.milliseconds * effort, and a failed call is queued for the MutationReplayer. */ @Singleton -class NotificationsRepository @Inject constructor( - retrofit: Retrofit, - private val dao: CachedNotificationDao, - private val mutationQueue: MutationQueue, -) { - private val api: NotificationsApi = retrofit.create() +class NotificationsRepository + @Inject + constructor( + retrofit: Retrofit, + private val dao: CachedNotificationDao, + private val mutationQueue: MutationQueue, + ) { + private val api: NotificationsApi = retrofit.create() - val notifications: Flow> = dao.observeAll().distinctUntilChanged() + val notifications: Flow> = dao.observeAll().distinctUntilChanged() - /** Unread notices in the cached page, which is what the badge shows. */ - val unreadCount: Flow = dao.observeUnreadCount().distinctUntilChanged() + /** Unread notices in the cached page, which is what the badge shows. */ + val unreadCount: Flow = dao.observeUnreadCount().distinctUntilChanged() - /** - * Replaces the cache with the server's newest page. A read made on this - * device and not yet replayed stays read: a read never goes back to - * unread, so the device's mark wins over the server's older view. - * Throws on a network failure; the cache then stands. - */ - suspend fun refresh() { - val page = api.list(limit = PAGE_SIZE) - val localReads = dao.getAll().associate { it.id to it.readAt } - dao.replaceAll(page.items.mapNotNull { it.toEntity(localReads[it.id]) }) + /** + * Replaces the cache with the server's newest page. A read made on this + * device and not yet replayed stays read: a read never goes back to + * unread, so the device's mark wins over the server's older view. + * Throws on a network failure; the cache then stands. + */ + suspend fun refresh() { + val page = api.list(limit = PAGE_SIZE) + val localReads = dao.getAll().associate { it.id to it.readAt } + dao.replaceAll(page.items.mapNotNull { it.toEntity(localReads[it.id]) }) + } + + suspend fun markRead(id: String) { + dao.markRead(id, Clock.System.now()) + // A refusal (404: trimmed or gone server-side) leaves nothing to mark. + sendOrQueue( + send = { api.markRead(id) }, + queue = { mutationQueue.enqueueNotificationRead(id) }, + onRefused = { e -> refused("mark read", e) }, + ) + } + + /** + * Marks everything the device holds read. The server is asked to mark + * only what existed up to the newest notice shown here, so a replay that + * lands later leaves anything newer unread. + */ + suspend fun markAllRead() { + val upTo = readAllCutoff(dao.getAll().map { it.createdAt })?.toString() + dao.markAllRead(Clock.System.now()) + sendOrQueue( + send = { api.readAll(ReadAllBody(upTo = upTo)) }, + queue = { mutationQueue.enqueueNotificationsReadAll(upTo) }, + onRefused = { e -> refused("mark all read", e) }, + ) + } + + private fun refused( + what: String, + e: HttpException, + ): WriteOutcome { + Timber.i(e, "notifications: %s refused (%d)", what, e.code()) + return WriteOutcome.Refused + } + + /** The page the device holds, newest first. */ + suspend fun cachedPage(): List = dao.getAll() + + /** On sign-out: the next account on this device must not see these. */ + suspend fun clearLocal() { + dao.clear() + } + + companion object { + /** The newest page the device keeps; older notices stay on the server. */ + const val PAGE_SIZE = 50 + } } - suspend fun markRead(id: String) { - dao.markRead(id, Clock.System.now()) - // A refusal (404: trimmed or gone server-side) leaves nothing to mark. - sendOrQueue( - send = { api.markRead(id) }, - queue = { mutationQueue.enqueueNotificationRead(id) }, - onRefused = { e -> refused("mark read", e) }, - ) - } - - /** - * Marks everything the device holds read. The server is asked to mark - * only what existed up to the newest notice shown here, so a replay that - * lands later leaves anything newer unread. - */ - suspend fun markAllRead() { - val upTo = readAllCutoff(dao.getAll().map { it.createdAt })?.toString() - dao.markAllRead(Clock.System.now()) - sendOrQueue( - send = { api.readAll(ReadAllBody(upTo = upTo)) }, - queue = { mutationQueue.enqueueNotificationsReadAll(upTo) }, - onRefused = { e -> refused("mark all read", e) }, - ) - } - - private fun refused(what: String, e: HttpException): WriteOutcome { - Timber.i(e, "notifications: %s refused (%d)", what, e.code()) - return WriteOutcome.Refused - } - - /** The page the device holds, newest first. */ - suspend fun cachedPage(): List = dao.getAll() - - /** On sign-out: the next account on this device must not see these. */ - suspend fun clearLocal() { - dao.clear() - } - - companion object { - /** The newest page the device keeps; older notices stay on the server. */ - const val PAGE_SIZE = 50 - } -} - /** * The newest notice shown, rounded up a millisecond. Room keeps milliseconds * and the server microseconds, so the stored time can sit just before the * server's; without rounding up, the newest notice would stay unread. */ -internal fun readAllCutoff(createdAts: List): Instant? = - createdAts.maxOrNull()?.plus(1.milliseconds) +internal fun readAllCutoff(createdAts: List): Instant? = createdAts.maxOrNull()?.plus(1.milliseconds) /** Null for a row whose timestamp will not parse, rather than failing the page. */ internal fun NotificationWire.toEntity(localReadAt: Instant?): CachedNotificationEntity? { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/BootReceiver.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/BootReceiver.kt index 87c2c922..fbe1108e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/BootReceiver.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/BootReceiver.kt @@ -21,12 +21,15 @@ import javax.inject.Inject */ @AndroidEntryPoint class BootReceiver : BroadcastReceiver() { - @Inject lateinit var authStore: AuthStore - @Inject @ApplicationScope lateinit var scope: CoroutineScope + @Inject @ApplicationScope + lateinit var scope: CoroutineScope - override fun onReceive(context: Context, intent: Intent) { + override fun onReceive( + context: Context, + intent: Intent, + ) { if (intent.action != Intent.ACTION_BOOT_COMPLETED && intent.action != Intent.ACTION_MY_PACKAGE_REPLACED) return val pending = goAsync() scope.launch { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryLauncher.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryLauncher.kt index 5da6d5f0..e7446e46 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryLauncher.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryLauncher.kt @@ -25,45 +25,47 @@ import javax.inject.Singleton * process is alive (the app open, or music playing). */ @Singleton -class DeliveryLauncher @Inject constructor( - @ApplicationContext private val context: Context, - authStore: AuthStore, - eventsStream: EventsStream, - sync: NotificationSync, - @ApplicationScope scope: CoroutineScope, -) { - init { - val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() }.distinctUntilChanged() +class DeliveryLauncher + @Inject + constructor( + @ApplicationContext private val context: Context, + authStore: AuthStore, + eventsStream: EventsStream, + sync: NotificationSync, + @ApplicationScope scope: CoroutineScope, + ) { + init { + val signedIn = authStore.sessionCookie.map { !it.isNullOrEmpty() }.distinctUntilChanged() - scope.launch { - combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted) - .distinctUntilChanged() - .collect { wanted -> if (wanted) DeliveryService.start(context) else DeliveryService.stop(context) } - } + scope.launch { + combine(signedIn, authStore.backgroundDelivery, ::deliveryWanted) + .distinctUntilChanged() + .collect { wanted -> if (wanted) DeliveryService.start(context) else DeliveryService.stop(context) } + } - // A nudge and a reconnect mean the same thing: go and look. The - // stream only runs while signed in, so neither fires signed out. - scope.launch { - eventsStream.events - .filter { it.kind == NOTIFICATION_CREATED } - .collect { sync.catchUp() } - } - scope.launch { - eventsStream.connected.filter { it }.collect { sync.catchUp() } - } + // A nudge and a reconnect mean the same thing: go and look. The + // stream only runs while signed in, so neither fires signed out. + scope.launch { + eventsStream.events + .filter { it.kind == NOTIFICATION_CREATED } + .collect { sync.catchUp() } + } + scope.launch { + eventsStream.connected.filter { it }.collect { sync.catchUp() } + } - // A sign-out, not the signed-out start a cold launch begins with - // before the session loads: that would wipe the mark on every start. - scope.launch { - var wasSignedIn = false - signedIn.collect { now -> - if (wasSignedIn && !now) sync.forget() - wasSignedIn = now + // A sign-out, not the signed-out start a cold launch begins with + // before the session loads: that would wipe the mark on every start. + scope.launch { + var wasSignedIn = false + signedIn.collect { now -> + if (wasSignedIn && !now) sync.forget() + wasSignedIn = now + } } } - } - private companion object { - const val NOTIFICATION_CREATED = "notification.created" + private companion object { + const val NOTIFICATION_CREATED = "notification.created" + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlan.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlan.kt index df642dd4..8d05b53e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlan.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlan.kt @@ -4,10 +4,8 @@ import com.fabledsword.minstrel.api.endpoints.NotificationSettingsWire import com.fabledsword.minstrel.cache.db.entities.CachedNotificationEntity import kotlinx.datetime.Instant -/** - * The decisions behind phone notifications, kept free of Android - * so they can be tested as plain functions. - */ +// The decisions behind phone notifications, kept free of Android +// so they can be tested as plain functions. /** A handful each get a line; more than this become one line with a count. */ internal const val INDIVIDUAL_LIMIT = 3 @@ -41,16 +39,19 @@ internal fun planCatchUp( ): CatchUp { val newest = page.maxOfOrNull { it.createdAt } if (mark == null) return CatchUp(emptyList(), newest ?: Instant.DISTANT_PAST) - val fresh = page - .filter { it.readAt == null && it.createdAt > mark && phoneOn(it.kind) } - .sortedBy { it.createdAt } + val fresh = + page + .filter { it.readAt == null && it.createdAt > mark && phoneOn(it.kind) } + .sortedBy { it.createdAt } val upTo = if (newest != null && newest > mark) newest else mark return CatchUp(fresh, upTo) } /** How a catch-up reaches the shade. */ internal sealed interface Announcement { - data class Each(val items: List) : Announcement + data class Each( + val items: List, + ) : Announcement /** * Coming back from a day offline is one line, not forty buzzes. [lines] @@ -66,21 +67,24 @@ internal sealed interface Announcement { /** How many titles an expanded pile lists, newest first. */ internal const val PILE_LINES = 5 -internal fun announcementFor(fresh: List): Announcement? = when { - fresh.isEmpty() -> null - fresh.size <= INDIVIDUAL_LIMIT -> Announcement.Each(fresh) - else -> Announcement.Pile( - count = fresh.size, - // A pile goes where its notices would: library health only when every - // one of them is, so a listener's own news is never filed under it. - channel = if (fresh.all { shadeChannelFor(it.kind) == ShadeChannel.LIBRARY_HEALTH }) { - ShadeChannel.LIBRARY_HEALTH - } else { - ShadeChannel.NEW_MUSIC - }, - lines = fresh.sortedByDescending { it.createdAt }.take(PILE_LINES).map { it.title }, - ) -} +internal fun announcementFor(fresh: List): Announcement? = + when { + fresh.isEmpty() -> null + fresh.size <= INDIVIDUAL_LIMIT -> Announcement.Each(fresh) + else -> + Announcement.Pile( + count = fresh.size, + // A pile goes where its notices would: library health only when every + // one of them is, so a listener's own news is never filed under it. + channel = + if (fresh.all { shadeChannelFor(it.kind) == ShadeChannel.LIBRARY_HEALTH }) { + ShadeChannel.LIBRARY_HEALTH + } else { + ShadeChannel.NEW_MUSIC + }, + lines = fresh.sortedByDescending { it.createdAt }.take(PILE_LINES).map { it.title }, + ) + } /** The phone channel per kind, as the user set it. No settings cached: on, the default for every kind. */ internal fun phoneOnFor(settings: NotificationSettingsWire?): (String) -> Boolean { @@ -93,7 +97,11 @@ internal fun phoneOnFor(settings: NotificationSettingsWire?): (String) -> Boolea * well as in Minstrel's. The ids are permanent: renaming one orphans the * user's system-level choice for it. */ -internal enum class ShadeChannel(val id: String, val title: String, val description: String) { +internal enum class ShadeChannel( + val id: String, + val title: String, + val description: String, +) { NEW_MUSIC("new_music", "New music", "Albums arriving in the library"), LIBRARY_HEALTH("library_health", "Library health", "For admins: flagged tracks and library problems"), } @@ -108,11 +116,13 @@ internal fun shadeChannelFor(kind: String): ShadeChannel = if (kind in listenerKinds) ShadeChannel.NEW_MUSIC else ShadeChannel.LIBRARY_HEALTH /** The delivery service runs exactly while signed in with background delivery on. */ -internal fun deliveryWanted(signedIn: Boolean, enabled: Boolean): Boolean = signedIn && enabled +internal fun deliveryWanted( + signedIn: Boolean, + enabled: Boolean, +): Boolean = signedIn && enabled /** One line for a pile. */ internal fun pileText(count: Int): String = "$count new notifications" /** Under an expanded pile's titles: how many it holds beyond them, or null. */ -internal fun pileMore(p: Announcement.Pile): String? = - (p.count - p.lines.size).takeIf { it > 0 }?.let { "and $it more" } +internal fun pileMore(p: Announcement.Pile): String? = (p.count - p.lines.size).takeIf { it > 0 }?.let { "and $it more" } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryService.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryService.kt index 49b8a95d..1141e97a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryService.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/DeliveryService.kt @@ -41,21 +41,25 @@ import timber.log.Timber * push, and the settings screen says so. */ class DeliveryService : Service() { - override fun onBind(intent: Intent?): IBinder? = null - override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int { + override fun onStartCommand( + intent: Intent?, + flags: Int, + startId: Int, + ): Int { if (intent?.action == ACTION_STOP) { ServiceCompat.stopForeground(this, ServiceCompat.STOP_FOREGROUND_REMOVE) stopSelf() return START_NOT_STICKY } ensureChannel() - val type = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { - ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE - } else { - 0 - } + val type = + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) { + ServiceInfo.FOREGROUND_SERVICE_TYPE_SPECIAL_USE + } else { + 0 + } ServiceCompat.startForeground(this, NOTIFICATION_ID, ongoing(), type) // If the system reclaims the process, bring it back: the point is to // be running when nothing else is. @@ -63,13 +67,15 @@ class DeliveryService : Service() { } private fun ongoing(): Notification { - val open = PendingIntent.getActivity( - this, - 0, - Intent(this, MainActivity::class.java), - PendingIntent.FLAG_IMMUTABLE, - ) - return NotificationCompat.Builder(this, CHANNEL_ID) + val open = + PendingIntent.getActivity( + this, + 0, + Intent(this, MainActivity::class.java), + PendingIntent.FLAG_IMMUTABLE, + ) + return NotificationCompat + .Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.ic_notification) .setContentTitle("Minstrel") .setContentText("Listening for notifications") diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationPoster.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationPoster.kt index 73829ad0..0bc4005d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationPoster.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationPoster.kt @@ -22,73 +22,80 @@ import javax.inject.Singleton * is about; tapping a pile opens the inbox. */ @Singleton -class NotificationPoster @Inject constructor( - @ApplicationContext private val context: Context, -) { - // Checked just below: posting is skipped when the user has said no. - @SuppressLint("MissingPermission") - internal fun post(announcement: Announcement) { - val manager = NotificationManagerCompat.from(context) - // Denied POST_NOTIFICATIONS, or every channel silenced: say nothing. - // The inbox still has it all. - if (!manager.areNotificationsEnabled()) return - ensureChannels() - when (announcement) { - is Announcement.Each -> announcement.items.forEach { manager.notify(it.id.hashCode(), single(it)) } - is Announcement.Pile -> manager.notify(PILE_ID, pile(announcement)) +class NotificationPoster + @Inject + constructor( + @ApplicationContext private val context: Context, + ) { + // Checked just below: posting is skipped when the user has said no. + @SuppressLint("MissingPermission") + internal fun post(announcement: Announcement) { + val manager = NotificationManagerCompat.from(context) + // Denied POST_NOTIFICATIONS, or every channel silenced: say nothing. + // The inbox still has it all. + if (!manager.areNotificationsEnabled()) return + ensureChannels() + when (announcement) { + is Announcement.Each -> announcement.items.forEach { manager.notify(it.id.hashCode(), single(it)) } + is Announcement.Pile -> manager.notify(PILE_ID, pile(announcement)) + } } - } - private fun single(item: CachedNotificationEntity) = - NotificationCompat.Builder(context, shadeChannelFor(item.kind).id) - .setSmallIcon(R.drawable.ic_notification) - .setContentTitle(item.title) - .setContentText(item.body) - .setStyle(NotificationCompat.BigTextStyle().bigText(item.body)) - .setWhen(item.createdAt.toEpochMilliseconds()) - .setShowWhen(true) - .setAutoCancel(true) - .setContentIntent(openIntent(item.link, item.id.hashCode())) - .build() + private fun single(item: CachedNotificationEntity) = + NotificationCompat + .Builder(context, shadeChannelFor(item.kind).id) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(item.title) + .setContentText(item.body) + .setStyle(NotificationCompat.BigTextStyle().bigText(item.body)) + .setWhen(item.createdAt.toEpochMilliseconds()) + .setShowWhen(true) + .setAutoCancel(true) + .setContentIntent(openIntent(item.link, item.id.hashCode())) + .build() - /** Collapsed, the count; expanded, the newest titles and how many more. */ - private fun pile(p: Announcement.Pile): Notification { - val style = NotificationCompat.InboxStyle().setBigContentTitle(pileText(p.count)) - p.lines.forEach { style.addLine(it) } - pileMore(p)?.let { style.setSummaryText(it) } - return NotificationCompat.Builder(context, p.channel.id) - .setSmallIcon(R.drawable.ic_notification) - .setContentTitle(pileText(p.count)) - .setContentText(p.lines.joinToString(" · ")) - .setStyle(style) - .setAutoCancel(true) - .setContentIntent(openIntent(link = null, requestCode = PILE_ID)) - .build() - } + /** Collapsed, the count; expanded, the newest titles and how many more. */ + private fun pile(p: Announcement.Pile): Notification { + val style = NotificationCompat.InboxStyle().setBigContentTitle(pileText(p.count)) + p.lines.forEach { style.addLine(it) } + pileMore(p)?.let { style.setSummaryText(it) } + return NotificationCompat + .Builder(context, p.channel.id) + .setSmallIcon(R.drawable.ic_notification) + .setContentTitle(pileText(p.count)) + .setContentText(p.lines.joinToString(" · ")) + .setStyle(style) + .setAutoCancel(true) + .setContentIntent(openIntent(link = null, requestCode = PILE_ID)) + .build() + } - /** Each notice gets its own request code, so their links stay apart. */ - private fun openIntent(link: String?, requestCode: Int): PendingIntent = - PendingIntent.getActivity( - context, - requestCode, - Intent(context, MainActivity::class.java) - .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) - .putExtra(MainActivity.EXTRA_NOTIFICATION_LINK, link.orEmpty()), - PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, - ) - - private fun ensureChannels() { - val manager = context.getSystemService(NotificationManager::class.java) ?: return - retiredShadeChannelIds.forEach { manager.deleteNotificationChannel(it) } - ShadeChannel.entries.forEach { c -> - manager.createNotificationChannel( - NotificationChannel(c.id, c.title, NotificationManager.IMPORTANCE_DEFAULT) - .apply { description = c.description }, + /** Each notice gets its own request code, so their links stay apart. */ + private fun openIntent( + link: String?, + requestCode: Int, + ): PendingIntent = + PendingIntent.getActivity( + context, + requestCode, + Intent(context, MainActivity::class.java) + .addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP or Intent.FLAG_ACTIVITY_CLEAR_TOP) + .putExtra(MainActivity.EXTRA_NOTIFICATION_LINK, link.orEmpty()), + PendingIntent.FLAG_IMMUTABLE or PendingIntent.FLAG_UPDATE_CURRENT, ) + + private fun ensureChannels() { + val manager = context.getSystemService(NotificationManager::class.java) ?: return + retiredShadeChannelIds.forEach { manager.deleteNotificationChannel(it) } + ShadeChannel.entries.forEach { c -> + manager.createNotificationChannel( + NotificationChannel(c.id, c.title, NotificationManager.IMPORTANCE_DEFAULT) + .apply { description = c.description }, + ) + } + } + + private companion object { + const val PILE_ID = 4802 } } - - private companion object { - const val PILE_ID = 4802 - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationSync.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationSync.kt index 05bfc2e9..1fe4b75d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationSync.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/delivery/NotificationSync.kt @@ -27,53 +27,60 @@ import javax.inject.Singleton * is still there, unread. */ @Singleton -class NotificationSync @Inject constructor( - private val notifications: NotificationsRepository, - private val settings: NotificationSettingsRepository, - private val prefs: AuthSessionDao, - private val poster: NotificationPoster, -) { - // One catch-up at a time: a nudge arriving with a reconnect must not - // read the mark before the other has moved it. - private val mutex = Mutex() +class NotificationSync + @Inject + constructor( + private val notifications: NotificationsRepository, + private val settings: NotificationSettingsRepository, + private val prefs: AuthSessionDao, + private val poster: NotificationPoster, + ) { + // One catch-up at a time: a nudge arriving with a reconnect must not + // read the mark before the other has moved it. + private val mutex = Mutex() - /** - * Announces what is new since the mark, then moves it. Failure is quiet on - * purpose: this runs on a reconnect, exactly when a request is most likely - * to lose a race with a network still settling, and the next trigger tries - * again. While the app is on screen nothing is posted (the bell shows it), - * but the mark still moves, so it is not announced later either. - */ - suspend fun catchUp() { - mutex.withLock { catchUpLocked() } - } - - private suspend fun catchUpLocked() { - try { - notifications.refresh() - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.i(e, "notification catch-up: refresh failed; next trigger retries") - return + /** + * Announces what is new since the mark, then moves it. Failure is quiet on + * purpose: this runs on a reconnect, exactly when a request is most likely + * to lose a race with a network still settling, and the next trigger tries + * again. While the app is on screen nothing is posted (the bell shows it), + * but the mark still moves, so it is not announced later either. + */ + suspend fun catchUp() { + mutex.withLock { catchUpLocked() } } - val plan = planCatchUp( - page = notifications.cachedPage(), - mark = prefs.get()?.notifiedUpTo, - phoneOn = phoneOnFor(settings.settings.first()), - ) - if (!appOnScreen()) announcementFor(plan.announce)?.let(poster::post) - plan.upTo?.let { prefs.setNotifiedUpTo(it) } - } - /** On sign-out: the next account starts with no mark, so it announces no backlog. */ - suspend fun forget() { - mutex.withLock { prefs.setNotifiedUpTo(null) } - } + private suspend fun catchUpLocked() { + try { + notifications.refresh() + } catch (e: CancellationException) { + throw e + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + Timber.i(e, "notification catch-up: refresh failed; next trigger retries") + return + } + val plan = + planCatchUp( + page = notifications.cachedPage(), + mark = prefs.get()?.notifiedUpTo, + phoneOn = phoneOnFor(settings.settings.first()), + ) + if (!appOnScreen()) announcementFor(plan.announce)?.let(poster::post) + plan.upTo?.let { prefs.setNotifiedUpTo(it) } + } - private suspend fun appOnScreen(): Boolean = withContext(Dispatchers.Main) { - ProcessLifecycleOwner.get().lifecycle.currentState.isAtLeast(Lifecycle.State.STARTED) + /** On sign-out: the next account starts with no mark, so it announces no backlog. */ + suspend fun forget() { + mutex.withLock { prefs.setNotifiedUpTo(null) } + } + + private suspend fun appOnScreen(): Boolean = + withContext(Dispatchers.Main) { + ProcessLifecycleOwner + .get() + .lifecycle.currentState + .isAtLeast(Lifecycle.State.STARTED) + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationLinks.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationLinks.kt index 0d163cf8..6655f1de 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationLinks.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationLinks.kt @@ -18,7 +18,12 @@ import com.fabledsword.minstrel.nav.Home private val ADMIN_COLLECTION_PAGES = setOf("duplicates", "suspect-sources", "missing") internal fun routeForLink(link: String): Any? { - val parts = link.substringBefore('?').trim('/').split('/').filter { it.isNotEmpty() } + val parts = + link + .substringBefore('?') + .trim('/') + .split('/') + .filter { it.isNotEmpty() } return when { link.isBlank() -> null parts.isEmpty() -> Home diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsScreen.kt index 08505b9c..7a1ca459 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsScreen.kt @@ -103,10 +103,11 @@ private fun SettingsBody( modifier: Modifier = Modifier, ) { Column( - modifier = modifier - .fillMaxSize() - .verticalScroll(rememberScrollState()) - .padding(horizontal = SectionEdge, vertical = SectionEdge), + modifier = + modifier + .fillMaxSize() + .verticalScroll(rememberScrollState()) + .padding(horizontal = SectionEdge, vertical = SectionEdge), verticalArrangement = Arrangement.spacedBy(SectionGap), ) { Section("This device") { deviceRows() } @@ -167,7 +168,10 @@ private fun KindRow( * the system lets Minstrel post them at all. */ @Composable -private fun DeviceRows(backgroundDelivery: Boolean, onBackgroundDelivery: (Boolean) -> Unit) { +private fun DeviceRows( + backgroundDelivery: Boolean, + onBackgroundDelivery: (Boolean) -> Unit, +) { val context = LocalContext.current // Re-read on every resume: the user may come back from system settings. var phoneAllowed by remember { mutableStateOf(true) } @@ -175,9 +179,10 @@ private fun DeviceRows(backgroundDelivery: Boolean, onBackgroundDelivery: (Boole phoneAllowed = NotificationManagerCompat.from(context).areNotificationsEnabled() onPauseOrDispose { } } - val askToNotify = rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> - phoneAllowed = granted - } + val askToNotify = + rememberLauncherForActivityResult(ActivityResultContracts.RequestPermission()) { granted -> + phoneAllowed = granted + } BackgroundDeliveryRow( checked = backgroundDelivery, onChange = { on -> @@ -194,7 +199,10 @@ private fun DeviceRows(backgroundDelivery: Boolean, onBackgroundDelivery: (Boole } @Composable -private fun BackgroundDeliveryRow(checked: Boolean, onChange: (Boolean) -> Unit) { +private fun BackgroundDeliveryRow( + checked: Boolean, + onChange: (Boolean) -> Unit, +) { // The ongoing notice is the price of not using Google's push; said // plainly rather than left to be discovered. SwitchRow( @@ -216,9 +224,10 @@ private fun PhoneBlockedRow(onClick: () -> Unit) { } private fun openAppNotificationSettings(context: Context) { - val intent = Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) - .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) - .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + val intent = + Intent(Settings.ACTION_APP_NOTIFICATION_SETTINGS) + .putExtra(Settings.EXTRA_APP_PACKAGE, context.packageName) + .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) runCatching { context.startActivity(intent) } } @@ -227,39 +236,49 @@ internal fun channelEnabled( row: NotificationKindSettingWire, channel: NotificationChannel, emailAvailable: Boolean, -): Boolean = when (channel) { - NotificationChannel.INBOX -> true - NotificationChannel.PHONE -> row.inbox - NotificationChannel.EMAIL -> row.inbox && emailAvailable -} +): Boolean = + when (channel) { + NotificationChannel.INBOX -> true + NotificationChannel.PHONE -> row.inbox + NotificationChannel.EMAIL -> row.inbox && emailAvailable + } -internal fun channelValue(row: NotificationKindSettingWire, channel: NotificationChannel): Boolean = +internal fun channelValue( + row: NotificationKindSettingWire, + channel: NotificationChannel, +): Boolean = when (channel) { NotificationChannel.INBOX -> row.inbox NotificationChannel.PHONE -> row.phone NotificationChannel.EMAIL -> row.email } -internal fun channelLabel(c: NotificationChannel): String = when (c) { - NotificationChannel.INBOX -> "Inbox" - NotificationChannel.PHONE -> "Phone" - NotificationChannel.EMAIL -> "Email" -} +internal fun channelLabel(c: NotificationChannel): String = + when (c) { + NotificationChannel.INBOX -> "Inbox" + NotificationChannel.PHONE -> "Phone" + NotificationChannel.EMAIL -> "Email" + } /** Short row labels, the same as the web's. Unknown kinds show their key. */ -internal fun kindLabel(kind: String): String = when (kind) { - "new_music" -> "New music arrived" - "quarantine_flagged" -> "Tracks flagged" - "scan_failed" -> "Library scan failed" - "tracks_missing" -> "Tracks gone missing" - "duplicates_found" -> "Duplicates to review" - "duplicates_resolved" -> "Duplicates resolved" - "playback_errors" -> "Playback errors" - else -> kind -} +internal fun kindLabel(kind: String): String = + when (kind) { + "new_music" -> "New music arrived" + "quarantine_flagged" -> "Tracks flagged" + "scan_failed" -> "Library scan failed" + "tracks_missing" -> "Tracks gone missing" + "duplicates_found" -> "Duplicates to review" + "duplicates_resolved" -> "Duplicates resolved" + "playback_errors" -> "Playback errors" + else -> kind + } -internal fun emailUnavailableLine(reason: String?, isAdmin: Boolean): String = when { - reason == "no_address" -> "Email is off: add an email address in your profile" - isAdmin -> "Email is off: SMTP isn't set up on the server" - else -> "Email is off: this server doesn't send email" -} +internal fun emailUnavailableLine( + reason: String?, + isAdmin: Boolean, +): String = + when { + reason == "no_address" -> "Email is off: add an email address in your profile" + isAdmin -> "Email is off: SMTP isn't set up on the server" + else -> "Email is off: this server doesn't send email" + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsViewModel.kt index b90dc60f..1ddbf004 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationSettingsViewModel.kt @@ -18,31 +18,39 @@ import javax.inject.Inject private const val SHARE_STOP_TIMEOUT_MS = 5_000L @HiltViewModel -class NotificationSettingsViewModel @Inject constructor( - private val repository: NotificationSettingsRepository, - authController: AuthController, - private val authStore: AuthStore, -) : ViewModel() { - /** "Notifications when the app is closed": this device's choice. */ - val backgroundDelivery: StateFlow = authStore.backgroundDelivery +class NotificationSettingsViewModel + @Inject + constructor( + private val repository: NotificationSettingsRepository, + authController: AuthController, + private val authStore: AuthStore, + ) : ViewModel() { + /** "Notifications when the app is closed": this device's choice. */ + val backgroundDelivery: StateFlow = authStore.backgroundDelivery - val settings: StateFlow = repository.settings - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), null) + val settings: StateFlow = + repository.settings + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), null) - val isAdmin: StateFlow = authController.currentUser - .map { it?.isAdmin == true } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), false) + val isAdmin: StateFlow = + authController.currentUser + .map { it?.isAdmin == true } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), false) - init { - // Offline, the device's copy stands. - viewModelScope.launch { runCatching { repository.refresh() } } + init { + // Offline, the device's copy stands. + viewModelScope.launch { runCatching { repository.refresh() } } + } + + fun set( + kind: String, + channel: NotificationChannel, + value: Boolean, + ) { + viewModelScope.launch { repository.set(kind, channel, value) } + } + + fun setBackgroundDelivery(on: Boolean) { + authStore.setBackgroundDelivery(on) + } } - - fun set(kind: String, channel: NotificationChannel, value: Boolean) { - viewModelScope.launch { repository.set(kind, channel, value) } - } - - fun setBackgroundDelivery(on: Boolean) { - authStore.setBackgroundDelivery(on) - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsScreen.kt index 82e34875..dea588aa 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsScreen.kt @@ -78,52 +78,60 @@ fun NotificationsScreen( val list = items when { list == null -> LoadingCentered() - list.isEmpty() -> EmptyState( - title = "Nothing waiting for you", - body = "Library problems and anything needing a look will gather here.", - icon = Lucide.Bell, - ) - else -> LazyColumn(modifier = Modifier.fillMaxSize()) { - items(list, key = { it.id }) { item -> - NotificationRow( - item = item, - unread = item.readAt == null || item.id in fresh, - onClick = { - viewModel.open(item) - routeForLink(item.link)?.let { navController.navigate(it) } - }, - ) - HorizontalDivider() + list.isEmpty() -> + EmptyState( + title = "Nothing waiting for you", + body = "Library problems and anything needing a look will gather here.", + icon = Lucide.Bell, + ) + else -> + LazyColumn(modifier = Modifier.fillMaxSize()) { + items(list, key = { it.id }) { item -> + NotificationRow( + item = item, + unread = item.readAt == null || item.id in fresh, + onClick = { + viewModel.open(item) + routeForLink(item.link)?.let { navController.navigate(it) } + }, + ) + HorizontalDivider() + } } - } } } } } @Composable -private fun NotificationRow(item: CachedNotificationEntity, unread: Boolean, onClick: () -> Unit) { +private fun NotificationRow( + item: CachedNotificationEntity, + unread: Boolean, + onClick: () -> Unit, +) { Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .padding(horizontal = 16.dp, vertical = 14.dp) - .semantics(mergeDescendants = true) { - if (unread) contentDescription = "New: ${item.title}" - }, + modifier = + Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 16.dp, vertical = 14.dp) + .semantics(mergeDescendants = true) { + if (unread) contentDescription = "New: ${item.title}" + }, verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { Box( - modifier = Modifier - .size(8.dp) - .then( - if (unread) { - Modifier.background(MaterialTheme.colorScheme.onSurface, CircleShape) - } else { - Modifier - }, - ), + modifier = + Modifier + .size(8.dp) + .then( + if (unread) { + Modifier.background(MaterialTheme.colorScheme.onSurface, CircleShape) + } else { + Modifier + }, + ), ) Text( text = item.title, @@ -143,7 +151,10 @@ private fun NotificationRow(item: CachedNotificationEntity, unread: Boolean, onC } /** "just now", "12m", "5h", "3d": the same coarse steps as the web inbox. */ -internal fun ago(at: Instant, now: Instant = Clock.System.now()): String { +internal fun ago( + at: Instant, + now: Instant = Clock.System.now(), +): String { val d = now - at return when { d >= 1.days -> "${d.inWholeDays}d" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModel.kt index 66760d4b..128b1482 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModel.kt @@ -26,45 +26,49 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L * [fresh], so it still looks new while the screen is up. */ @HiltViewModel -class NotificationsViewModel @Inject constructor( - private val repository: NotificationsRepository, - networkStatus: NetworkStatusController, -) : ViewModel() { - val items: StateFlow?> = repository.notifications - .map, List?> { it } - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), null) +class NotificationsViewModel + @Inject + constructor( + private val repository: NotificationsRepository, + networkStatus: NetworkStatusController, + ) : ViewModel() { + val items: StateFlow?> = + repository.notifications + .map, List?> { it } + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), null) - private val freshIds = MutableStateFlow>(emptySet()) + private val freshIds = MutableStateFlow>(emptySet()) - /** Notices that were unread when the screen showed them. */ - val fresh: StateFlow> = freshIds.asStateFlow() + /** Notices that were unread when the screen showed them. */ + val fresh: StateFlow> = freshIds.asStateFlow() - init { - refresh() - // Back online: the cached page may be stale, so refetch it. - viewModelScope.launch { networkStatus.recoveries().collect { refresh() } } + init { + refresh() + // Back online: the cached page may be stale, so refetch it. + viewModelScope.launch { networkStatus.recoveries().collect { refresh() } } + } + + /** Offline, the cached page stands. */ + fun refresh(): Job = + viewModelScope.launch { + runCatching { repository.refresh() } + } + + fun open(item: CachedNotificationEntity) { + if (item.readAt != null) return + viewModelScope.launch { repository.markRead(item.id) } + } + + /** The screen is showing [shown]: any unread among them are now read. */ + fun seen(shown: List) { + val unread = shown.filter { it.readAt == null && it.id !in freshIds.value } + if (unread.isEmpty()) return + freshIds.update { it + unread.map(CachedNotificationEntity::id) } + viewModelScope.launch { repository.markAllRead() } + } + + /** The screen has gone: next time, only what arrived since looks new. */ + fun left() { + freshIds.value = emptySet() + } } - - /** Offline, the cached page stands. */ - fun refresh(): Job = viewModelScope.launch { - runCatching { repository.refresh() } - } - - fun open(item: CachedNotificationEntity) { - if (item.readAt != null) return - viewModelScope.launch { repository.markRead(item.id) } - } - - /** The screen is showing [shown]: any unread among them are now read. */ - fun seen(shown: List) { - val unread = shown.filter { it.readAt == null && it.id !in freshIds.value } - if (unread.isEmpty()) return - freshIds.update { it + unread.map(CachedNotificationEntity::id) } - viewModelScope.launch { repository.markAllRead() } - } - - /** The screen has gone: next time, only what arrived since looks new. */ - fun left() { - freshIds.value = emptySet() - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/AudioPrefetcher.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/AudioPrefetcher.kt index 805d68d9..02b0b5ac 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/AudioPrefetcher.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/AudioPrefetcher.kt @@ -37,146 +37,157 @@ import javax.inject.Singleton * the observer. */ @Singleton -class AudioPrefetcher @Inject constructor( - @ApplicationScope private val scope: CoroutineScope, - private val playerController: PlayerController, - private val playerFactory: PlayerFactory, - private val authStore: AuthStore, - private val okHttpClient: OkHttpClient, -) { - // Reuse the same cache + upstream chain the player uses. Without the - // SimpleCache reference here the prefetcher would write to a - // disjoint store and playback would never read what we pinned. - private val cacheDataSourceFactory: CacheDataSource.Factory = - CacheDataSource.Factory() - .setCache(playerFactory.simpleCache) - .setUpstreamDataSourceFactory(OkHttpDataSource.Factory(okHttpClient)) +class AudioPrefetcher + @Inject + constructor( + @ApplicationScope private val scope: CoroutineScope, + private val playerController: PlayerController, + private val playerFactory: PlayerFactory, + private val authStore: AuthStore, + private val okHttpClient: OkHttpClient, + ) { + // Reuse the same cache + upstream chain the player uses. Without the + // SimpleCache reference here the prefetcher would write to a + // disjoint store and playback would never read what we pinned. + private val cacheDataSourceFactory: CacheDataSource.Factory = + CacheDataSource + .Factory() + .setCache(playerFactory.simpleCache) + .setUpstreamDataSourceFactory(OkHttpDataSource.Factory(okHttpClient)) - // trackId -> in-flight job. Reconcile cancels jobs whose track has - // dropped out of the window (skip-prev, queue rebuild) so a stale - // prefetch doesn't keep the network busy. - private val activeJobs = mutableMapOf() - private val mutex = Mutex() + // trackId -> in-flight job. Reconcile cancels jobs whose track has + // dropped out of the window (skip-prev, queue rebuild) so a stale + // prefetch doesn't keep the network busy. + private val activeJobs = mutableMapOf() + private val mutex = Mutex() - private data class ReconcileInput( - val queue: List>, - val index: Int, - val window: Int, - val isPlaying: Boolean, - ) + private data class ReconcileInput( + val queue: List>, + val index: Int, + val window: Int, + val isPlaying: Boolean, + ) - init { - scope.launch { - combine( - playerController.uiState.map { it.queue.map { t -> t.id to t.streamUrl } }, - playerController.uiState.map { it.queueIndex }, - authStore.cacheSettings.map { it.prefetchWindow }, - playerController.uiState.map { it.isPlaying }, - ) { queue, index, window, isPlaying -> - ReconcileInput(queue, index, window, isPlaying) + init { + scope.launch { + combine( + playerController.uiState.map { it.queue.map { t -> t.id to t.streamUrl } }, + playerController.uiState.map { it.queueIndex }, + authStore.cacheSettings.map { it.prefetchWindow }, + playerController.uiState.map { it.isPlaying }, + ) { queue, index, window, isPlaying -> + ReconcileInput(queue, index, window, isPlaying) + }.distinctUntilChanged() + .collect { input -> + reconcile(input.queue, input.index, input.window, input.isPlaying) + } } - .distinctUntilChanged() - .collect { input -> - reconcile(input.queue, input.index, input.window, input.isPlaying) + } + + /** + * Apply the prefetch window to the current queue. + * + * Cancellation of out-of-window jobs always runs -- a queue mutation + * or skip should free bandwidth from stale prefetches immediately. + * Starting new prefetches is gated on [isPlaying]: until the current + * track is actually playing, every byte of upstream bandwidth should + * land on it, not on upcoming-track prefetches. Without this gate a + * cold start fanned out 4-6 concurrent CacheWriter jobs against the + * same OkHttp client as the playback DataSource and the user waited + * ~25 s for the first audio to start; with the gate the current + * track gets the full pipe to its first STATE_READY, then the + * prefetcher fills in the next window. + */ + private suspend fun reconcile( + queue: List>, + index: Int, + window: Int, + isPlaying: Boolean, + ) { + mutex.withLock { + val targets = computeTargets(queue, index, window) + if (targets.isEmpty()) { + cancelAllLocked() + return + } + val targetIds = targets.mapTo(mutableSetOf()) { it.first } + // Cancellation always runs so a queue mutation or skip frees + // the pipe immediately, even while paused. + cancelOutOfWindowLocked(targetIds) + if (isPlaying) startInWindowLocked(targets) + } + } + + private fun computeTargets( + queue: List>, + index: Int, + window: Int, + ): List> { + // Exclude the currently-playing track (it's loaded by the player + // itself) and walk `window` tracks forward. + val firstIdx = index + 1 + val lastIdx = (index + window).coerceAtMost(queue.size - 1) + val isValid = index >= 0 && queue.isNotEmpty() && window > 0 && firstIdx <= lastIdx + return if (isValid) queue.subList(firstIdx, lastIdx + 1) else emptyList() + } + + private fun cancelOutOfWindowLocked(targetIds: Set) { + activeJobs.entries + .filter { it.key !in targetIds } + .toList() + .forEach { (id, job) -> + job.cancel() + activeJobs.remove(id) } } - } - /** - * Apply the prefetch window to the current queue. - * - * Cancellation of out-of-window jobs always runs -- a queue mutation - * or skip should free bandwidth from stale prefetches immediately. - * Starting new prefetches is gated on [isPlaying]: until the current - * track is actually playing, every byte of upstream bandwidth should - * land on it, not on upcoming-track prefetches. Without this gate a - * cold start fanned out 4-6 concurrent CacheWriter jobs against the - * same OkHttp client as the playback DataSource and the user waited - * ~25 s for the first audio to start; with the gate the current - * track gets the full pipe to its first STATE_READY, then the - * prefetcher fills in the next window. - */ - private suspend fun reconcile( - queue: List>, - index: Int, - window: Int, - isPlaying: Boolean, - ) { - mutex.withLock { - val targets = computeTargets(queue, index, window) - if (targets.isEmpty()) { - cancelAllLocked() - return + private fun startInWindowLocked(targets: List>) { + // Skip blank URLs (these come from minimal TrackRefs synthesized + // from playlist rows when the upstream track was removed from + // the library). + for ((trackId, streamUrl) in targets) { + if (trackId in activeJobs || streamUrl.isBlank()) continue + val job = + scope.launch(Dispatchers.IO) { + runCatching { prefetchOne(trackId, streamUrl) } + mutex.withLock { activeJobs.remove(trackId) } + } + activeJobs[trackId] = job } - val targetIds = targets.mapTo(mutableSetOf()) { it.first } - // Cancellation always runs so a queue mutation or skip frees - // the pipe immediately, even while paused. - cancelOutOfWindowLocked(targetIds) - if (isPlaying) startInWindowLocked(targets) + } + + private fun cancelAllLocked() { + activeJobs.values.forEach { it.cancel() } + activeJobs.clear() + } + + private fun prefetchOne( + trackId: String, + streamUrl: String, + ) { + // Match PlayerController.toMediaItem's resolveServerUrl + + // setCustomCacheKey(id) so the cached bytes are keyed exactly + // like a normal playback request — otherwise the player would + // miss them on read-through. + val resolved = resolveServerUrl(streamUrl) ?: streamUrl + val dataSpec = + DataSpec + .Builder() + .setUri(Uri.parse(resolved)) + .setKey(trackId) + .build() + val writer = + CacheWriter( + cacheDataSourceFactory.createDataSource(), + dataSpec, + // temporaryBuffer = + null, + // progressListener = + null, + ) + // Blocking, but we're on Dispatchers.IO. Throws on network + // failure — outer runCatching swallows so a single failed + // prefetch doesn't trip the whole reconcile. + writer.cache() } } - - private fun computeTargets( - queue: List>, - index: Int, - window: Int, - ): List> { - // Exclude the currently-playing track (it's loaded by the player - // itself) and walk `window` tracks forward. - val firstIdx = index + 1 - val lastIdx = (index + window).coerceAtMost(queue.size - 1) - val isValid = index >= 0 && queue.isNotEmpty() && window > 0 && firstIdx <= lastIdx - return if (isValid) queue.subList(firstIdx, lastIdx + 1) else emptyList() - } - - private fun cancelOutOfWindowLocked(targetIds: Set) { - activeJobs.entries - .filter { it.key !in targetIds } - .toList() - .forEach { (id, job) -> - job.cancel() - activeJobs.remove(id) - } - } - - private fun startInWindowLocked(targets: List>) { - // Skip blank URLs (these come from minimal TrackRefs synthesized - // from playlist rows when the upstream track was removed from - // the library). - for ((trackId, streamUrl) in targets) { - if (trackId in activeJobs || streamUrl.isBlank()) continue - val job = scope.launch(Dispatchers.IO) { - runCatching { prefetchOne(trackId, streamUrl) } - mutex.withLock { activeJobs.remove(trackId) } - } - activeJobs[trackId] = job - } - } - - private fun cancelAllLocked() { - activeJobs.values.forEach { it.cancel() } - activeJobs.clear() - } - - private fun prefetchOne(trackId: String, streamUrl: String) { - // Match PlayerController.toMediaItem's resolveServerUrl + - // setCustomCacheKey(id) so the cached bytes are keyed exactly - // like a normal playback request — otherwise the player would - // miss them on read-through. - val resolved = resolveServerUrl(streamUrl) ?: streamUrl - val dataSpec = DataSpec.Builder() - .setUri(Uri.parse(resolved)) - .setKey(trackId) - .build() - val writer = CacheWriter( - cacheDataSourceFactory.createDataSource(), - dataSpec, - /* temporaryBuffer = */ null, - /* progressListener = */ null, - ) - // Blocking, but we're on Dispatchers.IO. Throws on network - // failure — outer runCatching swallows so a single failed - // prefetch doesn't trip the whole reconcile. - writer.cache() - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/CastNetworkLock.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/CastNetworkLock.kt index 0d96ebf8..57499120 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/CastNetworkLock.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/CastNetworkLock.kt @@ -25,8 +25,9 @@ import timber.log.Timber * All methods are idempotent (`setReferenceCounted(false)` + held-checks) and * synchronized, so they are safe to call from any thread. */ -class CastNetworkLock(context: Context) { - +class CastNetworkLock( + context: Context, +) { private val appContext = context.applicationContext private val wifiLock: WifiManager.WifiLock? = @@ -47,7 +48,8 @@ class CastNetworkLock(context: Context) { .onFailure { Timber.w(it, "CastNetworkLock: wake acquire failed") } Timber.w( "CastNetworkLock acquired (wifi=%s wake=%s)", - wifiLock?.isHeld, wakeLock?.isHeld, + wifiLock?.isHeld, + wakeLock?.isHeld, ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/CoverPrefetcher.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/CoverPrefetcher.kt index 5b80d260..12be2049 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/CoverPrefetcher.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/CoverPrefetcher.kt @@ -29,33 +29,36 @@ import javax.inject.Singleton * in [com.fabledsword.minstrel.MinstrelApplication]. */ @Singleton -class CoverPrefetcher @Inject constructor( - @ApplicationContext private val context: Context, - private val playerController: PlayerController, - @ApplicationScope private val scope: CoroutineScope, -) { - init { - scope.launch { - playerController.uiState - .mapNotNull { it.peekNextCoverUrl() } - .filter { it.isNotEmpty() } - .distinctUntilChanged() - .collect(::prefetch) +class CoverPrefetcher + @Inject + constructor( + @ApplicationContext private val context: Context, + private val playerController: PlayerController, + @ApplicationScope private val scope: CoroutineScope, + ) { + init { + scope.launch { + playerController.uiState + .mapNotNull { it.peekNextCoverUrl() } + .filter { it.isNotEmpty() } + .distinctUntilChanged() + .collect(::prefetch) + } + } + + private fun prefetch(url: String) { + val request = + ImageRequest + .Builder(context) + .data(url) + .build() + SingletonImageLoader.get(context).enqueue(request) } } - private fun prefetch(url: String) { - val request = ImageRequest.Builder(context) - .data(url) - .build() - SingletonImageLoader.get(context).enqueue(request) - } -} - /** * Cover URL for `queueIndex + 1`, or null when the player is at the * end of the queue / has no queue. Empty string is preserved so the * caller can filter it; we don't want to prefetch a placeholder URL. */ -private fun PlayerUiState.peekNextCoverUrl(): String? = - queue.getOrNull(queueIndex + 1)?.coverUrl +private fun PlayerUiState.peekNextCoverUrl(): String? = queue.getOrNull(queueIndex + 1)?.coverUrl diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/LikeMediaCallback.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/LikeMediaCallback.kt index 1ac606b3..382fb23a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/LikeMediaCallback.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/LikeMediaCallback.kt @@ -31,16 +31,17 @@ class LikeMediaCallback( private val likes: LikesRepository, private val scope: CoroutineScope, ) : MediaSession.Callback { - override fun onConnect( session: MediaSession, controller: MediaSession.ControllerInfo, ): MediaSession.ConnectionResult { - val grants = MediaSession.ConnectionResult.DEFAULT_SESSION_COMMANDS - .buildUpon() - .add(SessionCommand(CMD_TOGGLE_LIKE, Bundle.EMPTY)) - .build() - return MediaSession.ConnectionResult.AcceptedResultBuilder(session) + val grants = + MediaSession.ConnectionResult.DEFAULT_SESSION_COMMANDS + .buildUpon() + .add(SessionCommand(CMD_TOGGLE_LIKE, Bundle.EMPTY)) + .build() + return MediaSession.ConnectionResult + .AcceptedResultBuilder(session) .setAvailableSessionCommands(grants) .build() } @@ -51,17 +52,19 @@ class LikeMediaCallback( customCommand: SessionCommand, args: Bundle, ): ListenableFuture { - val code = if (customCommand.customAction == CMD_TOGGLE_LIKE) { - launchToggleForCurrent(session) - } else { - SessionResult.RESULT_ERROR_NOT_SUPPORTED - } + val code = + if (customCommand.customAction == CMD_TOGGLE_LIKE) { + launchToggleForCurrent(session) + } else { + SessionResult.RESULT_ERROR_NOT_SUPPORTED + } return Futures.immediateFuture(SessionResult(code)) } private fun launchToggleForCurrent(session: MediaSession): Int { - val mediaId = session.player.currentMediaItem?.mediaId - ?: return SessionResult.RESULT_INFO_SKIPPED + val mediaId = + session.player.currentMediaItem?.mediaId + ?: return SessionResult.RESULT_INFO_SKIPPED scope.launch { val current = likes.observeIsLiked(ENTITY_TRACK, mediaId).first() likes.toggleLike(ENTITY_TRACK, mediaId, !current) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/LikedAudioPinner.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/LikedAudioPinner.kt index 8c507b8c..4843f504 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/LikedAudioPinner.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/LikedAudioPinner.kt @@ -62,71 +62,82 @@ private const val UNKNOWN_DURATION_SEC = 600 * `MinstrelApplication`. */ @Singleton -class LikedAudioPinner @Inject constructor( - @ApplicationScope scope: CoroutineScope, - likes: LikesRepository, - authStore: AuthStore, - connectivity: ConnectivityObserver, - serverHealth: NetworkStatusController, - private val playerFactory: PlayerFactory, - private val evictor: TwoBucketCacheEvictor, - private val trackDao: CachedTrackDao, - okHttpClient: OkHttpClient, -) { - private val cacheDataSourceFactory: CacheDataSource.Factory = - CacheDataSource.Factory() - .setCache(playerFactory.simpleCache) - .setUpstreamDataSourceFactory(OkHttpDataSource.Factory(okHttpClient)) +class LikedAudioPinner + @Inject + constructor( + @ApplicationScope scope: CoroutineScope, + likes: LikesRepository, + authStore: AuthStore, + connectivity: ConnectivityObserver, + serverHealth: NetworkStatusController, + private val playerFactory: PlayerFactory, + private val evictor: TwoBucketCacheEvictor, + private val trackDao: CachedTrackDao, + okHttpClient: OkHttpClient, + ) { + private val cacheDataSourceFactory: CacheDataSource.Factory = + CacheDataSource + .Factory() + .setCache(playerFactory.simpleCache) + .setUpstreamDataSourceFactory(OkHttpDataSource.Factory(okHttpClient)) - private data class Pass(val likedNewestFirst: List, val enabled: Boolean, val canDownload: Boolean) + private data class Pass( + val likedNewestFirst: List, + val enabled: Boolean, + val canDownload: Boolean, + ) - init { - scope.launch(Dispatchers.IO) { - combine( - likes.observeSignedInLikedTrackIdsNewestFirst(), - authStore.cacheSettings.map { it.cacheLikedTracks }, - connectivity.unmetered, - serverHealth.state.map { it == ServerHealth.Healthy || it == ServerHealth.Unstable }, - ) { liked, enabled, unmetered, reachable -> - Pass(liked, enabled, unmetered && reachable) + init { + scope.launch(Dispatchers.IO) { + combine( + likes.observeSignedInLikedTrackIdsNewestFirst(), + authStore.cacheSettings.map { it.cacheLikedTracks }, + connectivity.unmetered, + serverHealth.state.map { it == ServerHealth.Healthy || it == ServerHealth.Unstable }, + ) { liked, enabled, unmetered, reachable -> + Pass(liked, enabled, unmetered && reachable) + }.distinctUntilChanged() + .collectLatest { pass -> + if (pass.enabled && pass.canDownload) pinAll(pass.likedNewestFirst) + } } - .distinctUntilChanged() - .collectLatest { pass -> - if (pass.enabled && pass.canDownload) pinAll(pass.likedNewestFirst) + } + + private suspend fun pinAll(likedNewestFirst: List) { + for (trackId in likedNewestFirst) { + val track = downloadable(trackId) + if (track != null) { + val durationSec = track.durationSec.takeIf { it > 0 } ?: UNKNOWN_DURATION_SEC + if (evictor.usage().likedRoomBytes < durationSec * CD_BYTES_PER_SECOND) return + runCatching { runInterruptible { download(track.id, track.streamUrl) } } + .onFailure { Timber.d(it, "liked audio: download of %s failed; next pass retries", track.id) } } - } - } - - private suspend fun pinAll(likedNewestFirst: List) { - for (trackId in likedNewestFirst) { - val track = downloadable(trackId) - if (track != null) { - val durationSec = track.durationSec.takeIf { it > 0 } ?: UNKNOWN_DURATION_SEC - if (evictor.usage().likedRoomBytes < durationSec * CD_BYTES_PER_SECOND) return - runCatching { runInterruptible { download(track.id, track.streamUrl) } } - .onFailure { Timber.d(it, "liked audio: download of %s failed; next pass retries", track.id) } } } - } - /** The track, when it still needs downloading and the server can serve it. */ - private suspend fun downloadable(trackId: String): TrackRef? { - if (isFullyCached(trackId)) return null - val track = trackDao.getById(trackId)?.toDomain() - return track?.takeIf { !it.unavailable && it.streamUrl.isNotBlank() } - } + /** The track, when it still needs downloading and the server can serve it. */ + private suspend fun downloadable(trackId: String): TrackRef? { + if (isFullyCached(trackId)) return null + val track = trackDao.getById(trackId)?.toDomain() + return track?.takeIf { !it.unavailable && it.streamUrl.isNotBlank() } + } - private fun isFullyCached(trackId: String): Boolean { - val cache = playerFactory.simpleCache - val length = ContentMetadata.getContentLength(cache.getContentMetadata(trackId)) - return length != C.LENGTH_UNSET.toLong() && cache.isCached(trackId, 0, length) - } + private fun isFullyCached(trackId: String): Boolean { + val cache = playerFactory.simpleCache + val length = ContentMetadata.getContentLength(cache.getContentMetadata(trackId)) + return length != C.LENGTH_UNSET.toLong() && cache.isCached(trackId, 0, length) + } - private fun download(trackId: String, streamUrl: String) { - val dataSpec = DataSpec.Builder() - .setUri(Uri.parse(resolveServerUrl(streamUrl) ?: streamUrl)) - .setKey(trackId) - .build() - CacheWriter(cacheDataSourceFactory.createDataSource(), dataSpec, null, null).cache() + private fun download( + trackId: String, + streamUrl: String, + ) { + val dataSpec = + DataSpec + .Builder() + .setUri(Uri.parse(resolveServerUrl(streamUrl) ?: streamUrl)) + .setKey(trackId) + .build() + CacheWriter(cacheDataSourceFactory.createDataSource(), dataSpec, null, null).cache() + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/MinstrelForwardingPlayer.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/MinstrelForwardingPlayer.kt index d93767c8..7655133b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/MinstrelForwardingPlayer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/MinstrelForwardingPlayer.kt @@ -21,21 +21,21 @@ import com.fabledsword.minstrel.player.output.upnp.PositionInfo import com.fabledsword.minstrel.player.output.upnp.SoapFaultException import com.fabledsword.minstrel.player.output.upnp.TransportInfo import com.fabledsword.minstrel.player.output.upnp.TransportState -import java.io.IOException -import kotlin.math.abs import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.ExperimentalCoroutinesApi import kotlinx.coroutines.Job import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.cancel -import kotlinx.coroutines.delay import kotlinx.coroutines.channels.Channel -import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.delay import kotlinx.coroutines.isActive import kotlinx.coroutines.launch import kotlinx.coroutines.selects.onTimeout import kotlinx.coroutines.selects.select import timber.log.Timber +import java.io.IOException +import kotlin.math.abs /** * Integration point for UPnP transport parity. Wraps the local @@ -85,7 +85,6 @@ class MinstrelForwardingPlayer( private val singleTrack: SingleTrackLoader, private val events: RemoteEvents = RemoteEvents(), ) : ForwardingPlayer(delegate) { - /** * The ways remote playback reports trouble outward. Grouped rather than * passed as three more constructor lambdas: they share a lifetime, they @@ -134,6 +133,7 @@ class MinstrelForwardingPlayer( // a stopped renderer is polled once a second and its queue does not change // by itself, so re-asking every tick is pure round-trips. @Volatile private var cachedNrTracks: Int = 0 + @Volatile private var lastMediaInfoAtMs: Long = 0L // Previous raw transport reading, so [TransportObservation]s are emitted @@ -161,13 +161,15 @@ class MinstrelForwardingPlayer( private val externalListeners = mutableListOf() @Volatile private var lastNotifiedIsPlaying: Boolean = false + @Volatile private var lastNotifiedTrackIdx: Int = -1 - private val lifecycleObserver = object : DefaultLifecycleObserver { - override fun onResume(owner: LifecycleOwner) { - pollTrigger.trySend(Unit) + private val lifecycleObserver = + object : DefaultLifecycleObserver { + override fun onResume(owner: LifecycleOwner) { + pollTrigger.trySend(Unit) + } } - } init { scope.launch { @@ -202,8 +204,7 @@ class MinstrelForwardingPlayer( * window we drop transport commands silently -- they would hit Sonos's * stale state from a prior session and trigger restarts. */ - private fun isLoadingUpnp(): Boolean = - holder.target.value != null && holder.active.value == null + private fun isLoadingUpnp(): Boolean = holder.target.value != null && holder.active.value == null // ─── setMediaItems intercepts ────────────────────────────────────── // When PlayerController.setQueue replaces the queue while Sonos is the @@ -230,13 +231,20 @@ class MinstrelForwardingPlayer( afterQueueSet(sameQueue) } - override fun setMediaItems(mediaItems: List, resetPosition: Boolean) { + override fun setMediaItems( + mediaItems: List, + resetPosition: Boolean, + ) { val sameQueue = holdsSameItems(mediaItems) super.setMediaItems(mediaItems, resetPosition) afterQueueSet(sameQueue) } - override fun setMediaItems(mediaItems: List, startIndex: Int, startPositionMs: Long) { + override fun setMediaItems( + mediaItems: List, + startIndex: Int, + startPositionMs: Long, + ) { val sameQueue = holdsSameItems(mediaItems) super.setMediaItems(mediaItems, startIndex, startPositionMs) afterQueueSet(sameQueue) @@ -290,8 +298,7 @@ class MinstrelForwardingPlayer( .onSuccess { remoteState.applyTransportPlaying() notifyRemoteStateChanged() - } - .onFailure { handleTransportFailure(active, it) } + }.onFailure { handleTransportFailure(active, it) } } } } @@ -312,8 +319,7 @@ class MinstrelForwardingPlayer( .onSuccess { remoteState.applyTransportPaused() notifyRemoteStateChanged() - } - .onFailure { handleTransportFailure(active, it) } + }.onFailure { handleTransportFailure(active, it) } } } } @@ -347,7 +353,10 @@ class MinstrelForwardingPlayer( * Seeks Sonos to the correct queue slot, then seeks within-track if * [positionMs] is non-zero. */ - override fun seekTo(mediaItemIndex: Int, positionMs: Long) { + override fun seekTo( + mediaItemIndex: Int, + positionMs: Long, + ) { if (isLoadingUpnp()) { Timber.w("ForwardingPlayer.seekTo(idx, positionMs) dropped -- UPnP loading") return @@ -355,7 +364,9 @@ class MinstrelForwardingPlayer( val active = holder.active.value Timber.w( "ForwardingPlayer.seekTo(idx=%d, %dms) active=%s", - mediaItemIndex, positionMs, active?.routeName, + mediaItemIndex, + positionMs, + active?.routeName, ) if (active == null) { super.seekTo(mediaItemIndex, positionMs) @@ -368,7 +379,11 @@ class MinstrelForwardingPlayer( } } - private fun seekNativeQueue(active: ActiveUpnp, index: Int, positionMs: Long) { + private fun seekNativeQueue( + active: ActiveUpnp, + index: Int, + positionMs: Long, + ) { sendNativeQueueCommand(active) { active.avTransport.seekToTrack(index + 1) if (positionMs > 0L) { @@ -423,7 +438,10 @@ class MinstrelForwardingPlayer( * already moved; the pending window holds the poll's cursor sync off * until Sonos reports the new track, so it can't undo the press. */ - private fun sendNativeQueueCommand(active: ActiveUpnp, command: suspend () -> Unit) { + private fun sendNativeQueueCommand( + active: ActiveUpnp, + command: suspend () -> Unit, + ) { remoteState.beginPendingTransport( SystemClock.elapsedRealtime() + PENDING_TRANSPORT_SAFETY_TIMEOUT_MS, ) @@ -441,7 +459,11 @@ class MinstrelForwardingPlayer( * best-effort: a renderer still loading the URI may refuse it, and the * track playing from the start beats it not playing. */ - private fun playSingleTrackAt(active: ActiveUpnp, index: Int, positionMs: Long = 0L) { + private fun playSingleTrackAt( + active: ActiveUpnp, + index: Int, + positionMs: Long = 0L, + ) { if (index == singleTrack.currentIndex) { if (positionMs > 0L) seekTo(positionMs) } else { @@ -449,7 +471,11 @@ class MinstrelForwardingPlayer( } } - private fun startSingleTrack(active: ActiveUpnp, index: Int, positionMs: Long) { + private fun startSingleTrack( + active: ActiveUpnp, + index: Int, + positionMs: Long, + ) { remoteState.beginPendingTransport( SystemClock.elapsedRealtime() + PENDING_TRANSPORT_SAFETY_TIMEOUT_MS, ) @@ -461,8 +487,7 @@ class MinstrelForwardingPlayer( .onFailure { Timber.w(it, "UPnP seek after track change refused") } } pollTrigger.trySend(Unit) - } - .onFailure { handleTransportFailure(active, it) } + }.onFailure { handleTransportFailure(active, it) } } } @@ -483,25 +508,20 @@ class MinstrelForwardingPlayer( if (isRemote() || isLoadingUpnp()) seekToPreviousMediaItem() else super.seekToPrevious() } - override fun getCurrentPosition(): Long = - if (isRemote()) remoteState.positionMs else super.getCurrentPosition() + override fun getCurrentPosition(): Long = if (isRemote()) remoteState.positionMs else super.getCurrentPosition() - override fun getDuration(): Long = - if (isRemote()) remoteState.durationMs else super.getDuration() + override fun getDuration(): Long = if (isRemote()) remoteState.durationMs else super.getDuration() - override fun isPlaying(): Boolean = - if (isRemote()) remoteState.isPlaying else super.isPlaying() + override fun isPlaying(): Boolean = if (isRemote()) remoteState.isPlaying else super.isPlaying() - override fun getPlaybackState(): Int = - if (isRemote()) Player.STATE_READY else super.getPlaybackState() + override fun getPlaybackState(): Int = if (isRemote()) Player.STATE_READY else super.getPlaybackState() // Mirror remote state so any consumer that gates on playWhenReady -- // notably MediaSessionService's foreground-keepalive checks and our own // onTaskRemoved -- sees the remote renderer as the source of truth. // Without this, swiping the app away with Sonos playing would stop the // service, kill the poll loop, and leave Sonos orphaned. - override fun getPlayWhenReady(): Boolean = - if (isRemote()) remoteState.isPlaying else super.getPlayWhenReady() + override fun getPlayWhenReady(): Boolean = if (isRemote()) remoteState.isPlaying else super.getPlayWhenReady() override fun addListener(listener: Player.Listener) { super.addListener(listener) @@ -540,11 +560,12 @@ class MinstrelForwardingPlayer( l.onPlaybackStateChanged(Player.STATE_READY) } if (trackChanged) { - val item = if (trackIdx < delegate.mediaItemCount) { - delegate.getMediaItemAt(trackIdx) - } else { - null - } + val item = + if (trackIdx < delegate.mediaItemCount) { + delegate.getMediaItemAt(trackIdx) + } else { + null + } l.onMediaItemTransition(item, Player.MEDIA_ITEM_TRANSITION_REASON_AUTO) } } @@ -581,7 +602,10 @@ class MinstrelForwardingPlayer( * poll so the UI reconciles to Sonos's actual state -- if the renderer is * truly gone, the poll loop trips the drop on its own. */ - private fun handleTransportFailure(active: ActiveUpnp, t: Throwable) { + private fun handleTransportFailure( + active: ActiveUpnp, + t: Throwable, + ) { if (t is SoapFaultException) { Timber.w(t, "UPnP transport rejected by %s -- device alive, no drop", active.routeName) } else { @@ -678,11 +702,15 @@ class MinstrelForwardingPlayer( * the first post-recovery hiccup. Returns the (latched) suppression flag so * the rationale logs once per outage, not every tick. */ - private fun suppressDropForNetwork(active: ActiveUpnp, alreadySuppressed: Boolean): Boolean { + private fun suppressDropForNetwork( + active: ActiveUpnp, + alreadySuppressed: Boolean, + ): Boolean { if (!alreadySuppressed) { Timber.w( "UPnP drop suppressed for %s -- phone network %s, holding route", - active.routeName, networkStatus.state.value, + active.routeName, + networkStatus.state.value, ) } remoteState.recordPollSuccess() // clear streak; not a renderer failure @@ -705,17 +733,19 @@ class MinstrelForwardingPlayer( val rendererTrack = single?.trackNumber ?: info.track val trackUri = if (advanced) "" else info.trackUri val now = SystemClock.elapsedRealtime() - val inSeekAckWindow = lastSeekIssuedAtMs > 0L && - (now - lastSeekIssuedAtMs) < SEEK_ACK_WINDOW_MS + val inSeekAckWindow = + lastSeekIssuedAtMs > 0L && + (now - lastSeekIssuedAtMs) < SEEK_ACK_WINDOW_MS // Inside the seek-ack window, keep the optimistic position we wrote in // seekTo -- the poll's reported position is stale until Sonos finishes // processing the Seek SOAP. Other fields still refresh from the poll. remoteState.applyPositionInfo( - positionMs = when { - advanced -> 0L - inSeekAckWindow -> remoteState.positionMs - else -> info.relTimeMs - }, + positionMs = + when { + advanced -> 0L + inSeekAckWindow -> remoteState.positionMs + else -> info.relTimeMs + }, durationMs = durationFor(info, single), trackUri = trackUri, trackNumber = rendererTrack, @@ -782,8 +812,10 @@ class MinstrelForwardingPlayer( * that reports none (some leave TrackDuration at 0:00:00) falls back to * the library's duration, so the scrubber has an end to run to. */ - private fun durationFor(info: PositionInfo, single: SingleTrackLoader.PollOutcome?): Long = - if (single != null && info.trackDurationMs <= 0L) single.knownDurationMs else info.trackDurationMs + private fun durationFor( + info: PositionInfo, + single: SingleTrackLoader.PollOutcome?, + ): Long = if (single != null && info.trackDurationMs <= 0L) single.knownDurationMs else info.trackDurationMs /** * Ask the watchdog what to make of this poll, and act on its answer. @@ -799,23 +831,27 @@ class MinstrelForwardingPlayer( trackUri: String, transport: TransportInfo, ) { - val decision = stallWatchdog.onPoll( - RemoteStallWatchdog.Poll( - trackUri = trackUri, - state = transport.state, - statusOk = transport.statusOk, - playIntent = remoteState.lastPlayIntent, - positionMs = remoteState.positionMs, - nowMs = SystemClock.elapsedRealtime(), - queue = queueStateFor(active, transport), - ), - ) + val decision = + stallWatchdog.onPoll( + RemoteStallWatchdog.Poll( + trackUri = trackUri, + state = transport.state, + statusOk = transport.statusOk, + playIntent = remoteState.lastPlayIntent, + positionMs = remoteState.positionMs, + nowMs = SystemClock.elapsedRealtime(), + queue = queueStateFor(active, transport), + ), + ) when (decision) { is RemoteStallWatchdog.Decision.Resume -> { Timber.w( "UPnP stall on %s: renderer stopped unasked (status_ok=%b), " + "resume attempt %d at %dms", - active.routeName, transport.statusOk, decision.attempt, decision.resumeAtMs, + active.routeName, + transport.statusOk, + decision.attempt, + decision.resumeAtMs, ) runCatching { retryTransport { active.avTransport.play() } @@ -832,7 +868,9 @@ class MinstrelForwardingPlayer( Timber.w( "UPnP queue truncated on %s: renderer ended at its last track " + "while %d local tracks remain; repair attempt %d", - active.routeName, delegate.mediaItemCount, decision.attempt, + active.routeName, + delegate.mediaItemCount, + decision.attempt, ) // The renderer isn't broken -- it played everything it was // given. Rebuilding the queue is the fix; the controller owns @@ -861,7 +899,10 @@ class MinstrelForwardingPlayer( * playback happens a couple of times per track, and during a flap * repeatedly within a few seconds. */ - private fun observeTransport(transport: TransportInfo, info: PositionInfo) { + private fun observeTransport( + transport: TransportInfo, + info: PositionInfo, + ) { val key = transport.state to transport.statusOk if (key == lastObservedTransport) return lastObservedTransport = key @@ -905,9 +946,10 @@ class MinstrelForwardingPlayer( val now = SystemClock.elapsedRealtime() if (now - lastMediaInfoAtMs > MEDIA_INFO_TTL_MS) { lastMediaInfoAtMs = now - cachedNrTracks = runCatching { active.avTransport.getMediaInfo().nrTracks } - .onFailure { Timber.w(it, "UPnP GetMediaInfo failed on %s", active.routeName) } - .getOrDefault(0) + cachedNrTracks = + runCatching { active.avTransport.getMediaInfo().nrTracks } + .onFailure { Timber.w(it, "UPnP GetMediaInfo failed on %s", active.routeName) } + .getOrDefault(0) } val nrTracks = cachedNrTracks val rendererTrack = remoteState.trackNumber @@ -949,7 +991,10 @@ class MinstrelForwardingPlayer( * user's press. The pending deadline is honoured directly so a missed * clear can't wedge the sync. */ - private fun syncLocalCursorToRemote(sonosTrack: Int, trackUri: String) { + private fun syncLocalCursorToRemote( + sonosTrack: Int, + trackUri: String, + ) { if (isLoadingUpnp()) return val pendingDeadline = remoteState.pendingTransportDeadlineMs if (pendingDeadline > 0L && SystemClock.elapsedRealtime() < pendingDeadline) return @@ -958,7 +1003,8 @@ class MinstrelForwardingPlayer( if (target != delegate.currentMediaItemIndex) { Timber.w( "UPnP cursor sync: local=%d -> %d", - delegate.currentMediaItemIndex, target, + delegate.currentMediaItemIndex, + target, ) delegate.seekTo(target, 0L) } @@ -971,10 +1017,14 @@ class MinstrelForwardingPlayer( * index; else null (leave the cursor put rather than surface a wrong track). * Must run on the application looper -- reads the delegate timeline. */ - private fun resolveRemoteCursorIndex(sonosTrack: Int, trackUri: String): Int? { - val byId = streamUriTrackId(trackUri)?.let { id -> - nearestIndexWithMediaId(id, preferNear = sonosTrack - 1) - } + private fun resolveRemoteCursorIndex( + sonosTrack: Int, + trackUri: String, + ): Int? { + val byId = + streamUriTrackId(trackUri)?.let { id -> + nearestIndexWithMediaId(id, preferNear = sonosTrack - 1) + } return byId ?: (sonosTrack - 1).takeIf { it in 0 until delegate.mediaItemCount } } @@ -983,7 +1033,10 @@ class MinstrelForwardingPlayer( * occurrence nearest [preferNear] so a track that appears twice in the queue * doesn't snap the cursor across the queue. null if the id isn't present. */ - private fun nearestIndexWithMediaId(mediaId: String, preferNear: Int): Int? { + private fun nearestIndexWithMediaId( + mediaId: String, + preferNear: Int, + ): Int? { var best: Int? = null var bestDist = Int.MAX_VALUE for (i in 0 until delegate.mediaItemCount) { @@ -1002,15 +1055,18 @@ class MinstrelForwardingPlayer( const val POLL_INTERVAL_MS = 1_000L const val NON_PLAYING_CONFIRM = 2 const val SEEK_ACK_WINDOW_MS = 2_000L + // How long a GetMediaInfo queue-length reading stays good for. The // watchdog needs three agreeing polls (~3s) before it acts, so one // read comfortably covers a decision without asking every tick. const val MEDIA_INFO_TTL_MS = 5_000L + // Safety upper bound on how long the polling tick will wait for // Sonos to ack a user transport. The common case clears event-driven // when Sonos's reported Track matches the wrapped player; this only // kicks in if SOAP fails or Sonos drops the ack entirely. const val PENDING_TRANSPORT_SAFETY_TIMEOUT_MS = 5_000L + // Transport commands retry transient IO failures so a single WiFi // power-save stall (locked phone) doesn't abandon the command. 3 // attempts x the SoapClient's 2s connect timeout + backoff bounds the diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/MinstrelPlayerService.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/MinstrelPlayerService.kt index 94881db8..84aadb43 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/MinstrelPlayerService.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/MinstrelPlayerService.kt @@ -64,7 +64,6 @@ import javax.inject.Inject */ @AndroidEntryPoint class MinstrelPlayerService : MediaSessionService() { - @Inject lateinit var playerFactory: PlayerFactory @Inject lateinit var likesRepository: LikesRepository @@ -79,12 +78,14 @@ class MinstrelPlayerService : MediaSessionService() { super.onCreate() val player: Player = playerFactory.build() val callback = LikeMediaCallback(likesRepository, serviceScope) - val session = MediaSession.Builder(this, player) - .setSessionActivity(buildNowPlayingPendingIntent()) - .setCallback(callback) - .setBitmapLoader(playerFactory.buildBitmapLoader()) - .setMediaButtonPreferences(ImmutableList.of(buildLikeButton(isLiked = false))) - .build() + val session = + MediaSession + .Builder(this, player) + .setSessionActivity(buildNowPlayingPendingIntent()) + .setCallback(callback) + .setBitmapLoader(playerFactory.buildBitmapLoader()) + .setMediaButtonPreferences(ImmutableList.of(buildLikeButton(isLiked = false))) + .build() mediaSession = session serviceScope.launch { observeLikeState(session, player) } serviceScope.launch { refreshNormalization() } @@ -119,10 +120,11 @@ class MinstrelPlayerService : MediaSessionService() { * Builder rebuilds the PendingIntent. */ private fun buildNowPlayingPendingIntent(): PendingIntent { - val intent = Intent(this, MainActivity::class.java).apply { - flags = Intent.FLAG_ACTIVITY_SINGLE_TOP - putExtra(MainActivity.EXTRA_OPEN_NOW_PLAYING, true) - } + val intent = + Intent(this, MainActivity::class.java).apply { + flags = Intent.FLAG_ACTIVITY_SINGLE_TOP + putExtra(MainActivity.EXTRA_OPEN_NOW_PLAYING, true) + } return PendingIntent.getActivity( this, REQUEST_OPEN_NOW_PLAYING, @@ -140,12 +142,14 @@ class MinstrelPlayerService : MediaSessionService() { * tapped). */ private fun buildLikeButton(isLiked: Boolean): CommandButton { - val icon = if (isLiked) { - CommandButton.ICON_HEART_FILLED - } else { - CommandButton.ICON_HEART_UNFILLED - } - return CommandButton.Builder(icon) + val icon = + if (isLiked) { + CommandButton.ICON_HEART_FILLED + } else { + CommandButton.ICON_HEART_UNFILLED + } + return CommandButton + .Builder(icon) .setDisplayName(if (isLiked) "Unlike" else "Like") .setSessionCommand(SessionCommand(LikeMediaCallback.CMD_TOGGLE_LIKE, Bundle.EMPTY)) .build() @@ -160,7 +164,10 @@ class MinstrelPlayerService : MediaSessionService() { * never leak Flows across track transitions. */ @OptIn(ExperimentalCoroutinesApi::class) - private suspend fun observeLikeState(session: MediaSession, player: Player) { + private suspend fun observeLikeState( + session: MediaSession, + player: Player, + ) { currentMediaIdFlow(player) .flatMapLatest { mediaId -> if (mediaId == null) { @@ -168,8 +175,7 @@ class MinstrelPlayerService : MediaSessionService() { } else { likesRepository.observeIsLiked(ENTITY_TRACK, mediaId) } - } - .collect { isLiked -> + }.collect { isLiked -> session.setMediaButtonPreferences( ImmutableList.of(buildLikeButton(isLiked = isLiked)), ) @@ -182,26 +188,31 @@ class MinstrelPlayerService : MediaSessionService() { * correct on the first frame the controller renders (no * unfilled-then-flips flicker). */ - private fun currentMediaIdFlow(player: Player) = callbackFlow { - val listener = object : Player.Listener { - override fun onMediaItemTransition(item: MediaItem?, reason: Int) { - trySend(item?.mediaId) - } - } - player.addListener(listener) - awaitClose { player.removeListener(listener) } - }.onStart { emit(player.currentMediaItem?.mediaId) } + private fun currentMediaIdFlow(player: Player) = + callbackFlow { + val listener = + object : Player.Listener { + override fun onMediaItemTransition( + item: MediaItem?, + reason: Int, + ) { + trySend(item?.mediaId) + } + } + player.addListener(listener) + awaitClose { player.removeListener(listener) } + }.onStart { emit(player.currentMediaItem?.mediaId) } - override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = - mediaSession + override fun onGetSession(controllerInfo: MediaSession.ControllerInfo): MediaSession? = mediaSession override fun onTaskRemoved(rootIntent: Intent?) { val player = mediaSession?.player ?: return super.onTaskRemoved(rootIntent) // player.isPlaying is overridden on MinstrelForwardingPlayer to return // remoteState.isPlaying while UPnP is active, so a swipe-away with // Sonos playing keeps the service (and its UPnP poll loop) alive. - val activelyPlaying = player.isPlaying || - (player.playWhenReady && player.playbackState != Player.STATE_ENDED) + val activelyPlaying = + player.isPlaying || + (player.playWhenReady && player.playbackState != Player.STATE_ENDED) if (!activelyPlaying) { stopSelf() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/OfflineGatedDataSource.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/OfflineGatedDataSource.kt index 314597f0..d22f0c93 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/OfflineGatedDataSource.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/OfflineGatedDataSource.kt @@ -24,7 +24,6 @@ class OfflineGatedDataSource( private val delegate: DataSource, private val health: NetworkStatusController, ) : DataSource { - override fun open(dataSpec: DataSpec): Long { gateOnHealth() return try { @@ -52,11 +51,17 @@ class OfflineGatedDataSource( } override fun close() = delegate.close() + override fun getUri() = delegate.uri - override fun read(buffer: ByteArray, offset: Int, length: Int): Int = - delegate.read(buffer, offset, length) - override fun addTransferListener(transferListener: TransferListener) = - delegate.addTransferListener(transferListener) + + override fun read( + buffer: ByteArray, + offset: Int, + length: Int, + ): Int = delegate.read(buffer, offset, length) + + override fun addTransferListener(transferListener: TransferListener) = delegate.addTransferListener(transferListener) + override fun getResponseHeaders() = delegate.responseHeaders } @@ -64,8 +69,7 @@ class OfflineGatedDataSourceFactory( private val upstream: DataSource.Factory, private val health: NetworkStatusController, ) : DataSource.Factory { - override fun createDataSource(): DataSource = - OfflineGatedDataSource(upstream.createDataSource(), health) + override fun createDataSource(): DataSource = OfflineGatedDataSource(upstream.createDataSource(), health) } /** @@ -75,4 +79,6 @@ class OfflineGatedDataSourceFactory( * `IOException` ancestor and surfaces it as a SOURCE error, which then flows * through the existing [PlaybackErrorReporter] -> snackbar path. */ -class OfflineException(message: String) : IOException(message) +class OfflineException( + message: String, +) : IOException(message) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayEventsReporter.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayEventsReporter.kt index c4a8b56a..3686127e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayEventsReporter.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayEventsReporter.kt @@ -47,258 +47,272 @@ import javax.inject.Singleton * unreliable; the queue survives a process kill). */ @Singleton -class PlayEventsReporter @Inject constructor( - private val playerController: PlayerController, - private val authStore: AuthStore, - private val mutationQueue: MutationQueue, - @ApplicationScope private val scope: CoroutineScope, - retrofit: Retrofit, -) : DefaultLifecycleObserver { +class PlayEventsReporter + @Inject + constructor( + private val playerController: PlayerController, + private val authStore: AuthStore, + private val mutationQueue: MutationQueue, + @ApplicationScope private val scope: CoroutineScope, + retrofit: Retrofit, + ) : DefaultLifecycleObserver { + private val api: EventsApi = retrofit.create() - private val api: EventsApi = retrofit.create() + private var curTrackId: String? = null + private var curStartedAt: Instant? = null + private var curSource: String? = null + private var curLastPositionMs: Long = 0 + private var curDurationMs: Long = 0 - private var curTrackId: String? = null - private var curStartedAt: Instant? = null - private var curSource: String? = null - private var curLastPositionMs: Long = 0 - private var curDurationMs: Long = 0 + // Whether the currently-tracked play is actively playing (vs paused). + // onStop reads this: a backgrounded play that's still playing is left + // to the live path (the foreground service keeps us alive), while a + // paused one is durably closed so a kill can't orphan its open row. + private var curPlaying: Boolean = false - // Whether the currently-tracked play is actively playing (vs paused). - // onStop reads this: a backgrounded play that's still playing is left - // to the live path (the foreground service keeps us alive), while a - // paused one is durably closed so a kill can't orphan its open row. - private var curPlaying: Boolean = false + // Server play_event_id when the live play_started succeeded; + // null if start failed/offline — then the close is captured into + // the offline mutation queue instead of a live ended/skipped. + private var openPlayEventId: String? = null - // Server play_event_id when the live play_started succeeded; - // null if start failed/offline — then the close is captured into - // the offline mutation queue instead of a live ended/skipped. - private var openPlayEventId: String? = null + // True from beginTrack until startLive's play_started resolves. When a + // close races an in-flight start (id still null), the server row is + // being created but we've lost its id — we must NOT also enqueue an + // offline play (that would duplicate); the server auto-closes the + // orphan on the next play_started instead. + private var startInFlight: Boolean = false - // True from beginTrack until startLive's play_started resolves. When a - // close races an in-flight start (id still null), the server row is - // being created but we've lost its id — we must NOT also enqueue an - // offline play (that would duplicate); the server auto-closes the - // orphan on the next play_started instead. - private var startInFlight: Boolean = false + // The listen the tracked play belongs to (PlayerUiState.listenSeq), and + // the one last seen. A repeat keeps the track id but moves the listen, + // so a song on repeat is a play per time through. + private var curListenSeq: Long = -1 + private var prevTrackId: String? = null + private var prevListenSeq: Long = -1 - // The listen the tracked play belongs to (PlayerUiState.listenSeq), and - // the one last seen. A repeat keeps the track id but moves the listen, - // so a song on repeat is a play per time through. - private var curListenSeq: Long = -1 - private var prevTrackId: String? = null - private var prevListenSeq: Long = -1 + // Identifies the tracked play to its own play_started call. A reply that + // lands after the play it was for has closed must neither adopt its id + // nor clear the in-flight flag the NEXT play's start has set: clearing it + // would make a quick skip of that next play record it offline as well as + // live. + private var curPlayToken: Long = 0 - // Identifies the tracked play to its own play_started call. A reply that - // lands after the play it was for has closed must neither adopt its id - // nor clear the in-flight flag the NEXT play's start has set: clearing it - // would make a quick skip of that next play record it offline as well as - // live. - private var curPlayToken: Long = 0 - - init { - ProcessLifecycleOwner.get().lifecycle.addObserver(this) - scope.launch { - playerController.uiState.collect { state -> evaluate(state) } - } - } - - private fun evaluate(state: PlayerUiState) { - val trackId = state.currentTrack?.id - val listenSeq = state.listenSeq - val playing = state.isPlaying - val durationMs = state.durationMs - val listenChanged = trackId != prevTrackId || listenSeq != prevListenSeq - // Listen change (a new track, or the same one again) → close the - // prior tracked play. - if (listenChanged && curTrackId != null) { - closeCurrent() + init { + ProcessLifecycleOwner.get().lifecycle.addObserver(this) + scope.launch { + playerController.uiState.collect { state -> evaluate(state) } + } } - // Entered playing for a new listen → begin tracking it. - val tracked = curTrackId == trackId && curListenSeq == listenSeq - if (trackId != null && playing && !tracked) { - beginTrack( - trackId = trackId, - listenSeq = listenSeq, - source = state.currentSource, - durationMs = durationMs, - ) + private fun evaluate(state: PlayerUiState) { + val trackId = state.currentTrack?.id + val listenSeq = state.listenSeq + val playing = state.isPlaying + val durationMs = state.durationMs + val listenChanged = trackId != prevTrackId || listenSeq != prevListenSeq + // Listen change (a new track, or the same one again) → close the + // prior tracked play. + if (listenChanged && curTrackId != null) { + closeCurrent() + } + + // Entered playing for a new listen → begin tracking it. + val tracked = curTrackId == trackId && curListenSeq == listenSeq + if (trackId != null && playing && !tracked) { + beginTrack( + trackId = trackId, + listenSeq = listenSeq, + source = state.currentSource, + durationMs = durationMs, + ) + } + + // Advance the tracked play's progress. The gate on the tracked + // listen keeps a finishing track's last-known position intact + // across the moment the listener fires for a track change or a + // repeat (where the position has already gone back to 0). + if (curTrackId != null && trackId == curTrackId && listenSeq == curListenSeq) { + curLastPositionMs = state.positionMs + if (durationMs > 0) curDurationMs = durationMs + curPlaying = playing + } + + prevTrackId = trackId + prevListenSeq = listenSeq } - // Advance the tracked play's progress. The gate on the tracked - // listen keeps a finishing track's last-known position intact - // across the moment the listener fires for a track change or a - // repeat (where the position has already gone back to 0). - if (curTrackId != null && trackId == curTrackId && listenSeq == curListenSeq) { - curLastPositionMs = state.positionMs - if (durationMs > 0) curDurationMs = durationMs - curPlaying = playing + private fun beginTrack( + trackId: String, + listenSeq: Long, + source: String?, + durationMs: Long, + ) { + curTrackId = trackId + curListenSeq = listenSeq + curStartedAt = Clock.System.now() + curSource = source + curLastPositionMs = 0 + curDurationMs = durationMs + curPlaying = true + openPlayEventId = null + startInFlight = true + curPlayToken++ + startLive(trackId = trackId, source = source, token = curPlayToken) } - prevTrackId = trackId - prevListenSeq = listenSeq - } + private fun startLive( + trackId: String, + source: String?, + token: Long, + ) { + val cid = resolveClientId() + if (cid == null) { + startInFlight = false + return + } + scope.launch { + try { + val response = + api.playStarted( + PlayStartedRequest( + trackId = trackId, + clientId = cid, + source = source.takeIf { !it.isNullOrEmpty() }, + deviceClass = DEVICE_CLASS, + ), + ) + if (curPlayToken == token) { + openPlayEventId = response.playEventId + } + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + // Offline / flaky — openPlayEventId stays null; close + // path will enqueue the completed play for replay. + } finally { + if (curPlayToken == token) startInFlight = false + } + } + } - private fun beginTrack(trackId: String, listenSeq: Long, source: String?, durationMs: Long) { - curTrackId = trackId - curListenSeq = listenSeq - curStartedAt = Clock.System.now() - curSource = source - curLastPositionMs = 0 - curDurationMs = durationMs - curPlaying = true - openPlayEventId = null - startInFlight = true - curPlayToken++ - startLive(trackId = trackId, source = source, token = curPlayToken) - } + /** + * Closes the tracked play. Routes by whether the server already has an + * open row, NOT by caller context — this is what keeps background / + * track-change / failure paths from each minting a second row: + * - open server row (id) → close it by id; on failure enqueue a durable + * close-by-id (never an offline play). + * - start in flight (no id yet) → leave it; the server auto-closes the + * orphan on the next play_started. Enqueuing offline here would + * duplicate the in-flight row. + * - no server row at all → record the whole play offline. + * + * Always uses the actual position played; the server's skip rule + * (50%/30s defaults) classifies was_skipped from it. + */ + private fun closeCurrent() { + val trackId = curTrackId + val startedAt = curStartedAt + if (trackId == null || startedAt == null) { + resetCurrent() + return + } + val durationMs = curLastPositionMs + val source = curSource + val id = openPlayEventId + val inFlight = startInFlight + when { + id != null -> closeById(id, durationMs) + inFlight -> Unit + else -> enqueueOffline(trackId, startedAt, source, durationMs) + } + resetCurrent() + } - private fun startLive(trackId: String, source: String?, token: Long) { - val cid = resolveClientId() - if (cid == null) { + private fun closeById( + id: String, + durationMs: Long, + ) { + scope.launch { + try { + api.playEnded( + PlayEndedRequest(playEventId = id, durationPlayedMs = durationMs), + ) + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + // Durable close-by-id (idempotent server-side) — survives a + // process kill without orphaning the open row or duplicating. + mutationQueue.enqueuePlayEnded( + PlayEndedPayload(playEventId = id, durationPlayedMs = durationMs), + ) + } + } + } + + private fun resetCurrent() { + curTrackId = null + curListenSeq = -1 + curStartedAt = null + curSource = null + curLastPositionMs = 0 + curDurationMs = 0 + curPlaying = false + openPlayEventId = null startInFlight = false - return } - scope.launch { - try { - val response = api.playStarted( - PlayStartedRequest( + + private fun enqueueOffline( + trackId: String, + startedAt: Instant, + source: String?, + durationPlayedMs: Long, + ) { + val cid = resolveClientId() ?: return + scope.launch { + mutationQueue.enqueuePlayOffline( + PlayOfflinePayload( trackId = trackId, clientId = cid, + atIso = startedAt.toString(), + durationPlayedMs = durationPlayedMs, source = source.takeIf { !it.isNullOrEmpty() }, deviceClass = DEVICE_CLASS, ), ) - if (curPlayToken == token) { - openPlayEventId = response.playEventId - } - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Offline / flaky — openPlayEventId stays null; close - // path will enqueue the completed play for replay. - } finally { - if (curPlayToken == token) startInFlight = false + } + } + + /** + * Returns the persisted client id, generating + persisting one on + * first read. The setter is fire-and-forget on the app scope so + * this stays synchronous; the in-memory StateFlow update is + * immediate so the next caller observes the new value. + */ + private fun resolveClientId(): String? { + authStore.clientId.value?.let { return it } + val fresh = UUID.randomUUID().toString() + authStore.setClientId(fresh) + return fresh + } + + // ── Lifecycle: durable-close on app background / detach ──────── + + companion object { + // Android is a mobile client. Refine to tablet/tv via device + // configuration later if the metrics trend view shows it matters. + private const val DEVICE_CLASS = "mobile" + } + + override fun onStop(owner: LifecycleOwner) { + // App backgrounded. If the tracked play is still PLAYING, leave it + // alone: the foreground media service keeps the process — and this + // app-scope uiState collector — alive, so the live state machine + // closes the play accurately on the next real track change. Closing + // here would race the collector's re-begin and mint a duplicate, + // skip-misclassified row on every screen-lock. Only durably close a + // PAUSED play, where no further progress will happen and a process + // kill would otherwise orphan the open server row. + if (curTrackId != null && !curPlaying) { + closeCurrent() } } } - - /** - * Closes the tracked play. Routes by whether the server already has an - * open row, NOT by caller context — this is what keeps background / - * track-change / failure paths from each minting a second row: - * - open server row (id) → close it by id; on failure enqueue a durable - * close-by-id (never an offline play). - * - start in flight (no id yet) → leave it; the server auto-closes the - * orphan on the next play_started. Enqueuing offline here would - * duplicate the in-flight row. - * - no server row at all → record the whole play offline. - * - * Always uses the actual position played; the server's skip rule - * (50%/30s defaults) classifies was_skipped from it. - */ - private fun closeCurrent() { - val trackId = curTrackId - val startedAt = curStartedAt - if (trackId == null || startedAt == null) { - resetCurrent() - return - } - val durationMs = curLastPositionMs - val source = curSource - val id = openPlayEventId - val inFlight = startInFlight - when { - id != null -> closeById(id, durationMs) - inFlight -> Unit - else -> enqueueOffline(trackId, startedAt, source, durationMs) - } - resetCurrent() - } - - private fun closeById(id: String, durationMs: Long) { - scope.launch { - try { - api.playEnded( - PlayEndedRequest(playEventId = id, durationPlayedMs = durationMs), - ) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Durable close-by-id (idempotent server-side) — survives a - // process kill without orphaning the open row or duplicating. - mutationQueue.enqueuePlayEnded( - PlayEndedPayload(playEventId = id, durationPlayedMs = durationMs), - ) - } - } - } - - private fun resetCurrent() { - curTrackId = null - curListenSeq = -1 - curStartedAt = null - curSource = null - curLastPositionMs = 0 - curDurationMs = 0 - curPlaying = false - openPlayEventId = null - startInFlight = false - } - - private fun enqueueOffline( - trackId: String, - startedAt: Instant, - source: String?, - durationPlayedMs: Long, - ) { - val cid = resolveClientId() ?: return - scope.launch { - mutationQueue.enqueuePlayOffline( - PlayOfflinePayload( - trackId = trackId, - clientId = cid, - atIso = startedAt.toString(), - durationPlayedMs = durationPlayedMs, - source = source.takeIf { !it.isNullOrEmpty() }, - deviceClass = DEVICE_CLASS, - ), - ) - } - } - - /** - * Returns the persisted client id, generating + persisting one on - * first read. The setter is fire-and-forget on the app scope so - * this stays synchronous; the in-memory StateFlow update is - * immediate so the next caller observes the new value. - */ - private fun resolveClientId(): String? { - authStore.clientId.value?.let { return it } - val fresh = UUID.randomUUID().toString() - authStore.setClientId(fresh) - return fresh - } - - // ── Lifecycle: durable-close on app background / detach ──────── - - companion object { - // Android is a mobile client. Refine to tablet/tv via device - // configuration later if the metrics trend view shows it matters. - private const val DEVICE_CLASS = "mobile" - } - - override fun onStop(owner: LifecycleOwner) { - // App backgrounded. If the tracked play is still PLAYING, leave it - // alone: the foreground media service keeps the process — and this - // app-scope uiState collector — alive, so the live state machine - // closes the play accurately on the next real track change. Closing - // here would race the collector's re-begin and mint a duplicate, - // skip-misclassified row on every screen-lock. Only durably close a - // PAUSED play, where no further progress will happen and a process - // kill would otherwise orphan the open server row. - if (curTrackId != null && !curPlaying) { - closeCurrent() - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlaybackErrorReporter.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlaybackErrorReporter.kt index 0a8bef38..f0f63d75 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlaybackErrorReporter.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlaybackErrorReporter.kt @@ -37,45 +37,49 @@ private const val DEBOUNCE_MS = 2_000L * [com.fabledsword.minstrel.MinstrelApplication]. */ @Singleton -class PlaybackErrorReporter @Inject constructor( - private val playerController: PlayerController, - private val repository: PlaybackErrorRepository, - private val networkStatus: NetworkStatusController, - @ApplicationScope private val scope: CoroutineScope, -) { - private val outChannel = Channel(Channel.BUFFERED) +class PlaybackErrorReporter + @Inject + constructor( + private val playerController: PlayerController, + private val repository: PlaybackErrorRepository, + private val networkStatus: NetworkStatusController, + @ApplicationScope private val scope: CoroutineScope, + ) { + private val outChannel = Channel(Channel.BUFFERED) - /** Coalesced user-facing snackbar text. Subscribers should show in a SnackbarHost. */ - val messages: Flow = outChannel.receiveAsFlow() + /** Coalesced user-facing snackbar text. Subscribers should show in a SnackbarHost. */ + val messages: Flow = outChannel.receiveAsFlow() - init { - scope.launch { - val buffer = mutableListOf() - var debounceJob: kotlinx.coroutines.Job? = null - playerController.playbackErrorEvents.collect { event -> - // A track failing to play is ambiguous (dead server vs. one bad - // file) — let the controller arbitrate via /healthz. No-op when - // already Offline; cheap otherwise. - networkStatus.reportFailure() - // Fire-and-forget the server report — repository handles - // success/queue branching so callers don't see throws. - scope.launch { repository.report(event) } - buffer.add(event.title) - debounceJob?.cancel() - debounceJob = scope.launch { - delay(DEBOUNCE_MS) - if (buffer.isEmpty()) return@launch - val n = buffer.size - val first = buffer.first() - buffer.clear() - val msg = if (n == 1) { - "Couldn't play \"$first\" — skipping" - } else { - "Skipped $n unplayable tracks" - } - outChannel.trySend(msg) + init { + scope.launch { + val buffer = mutableListOf() + var debounceJob: kotlinx.coroutines.Job? = null + playerController.playbackErrorEvents.collect { event -> + // A track failing to play is ambiguous (dead server vs. one bad + // file) — let the controller arbitrate via /healthz. No-op when + // already Offline; cheap otherwise. + networkStatus.reportFailure() + // Fire-and-forget the server report — repository handles + // success/queue branching so callers don't see throws. + scope.launch { repository.report(event) } + buffer.add(event.title) + debounceJob?.cancel() + debounceJob = + scope.launch { + delay(DEBOUNCE_MS) + if (buffer.isEmpty()) return@launch + val n = buffer.size + val first = buffer.first() + buffer.clear() + val msg = + if (n == 1) { + "Couldn't play \"$first\" — skipping" + } else { + "Skipped $n unplayable tracks" + } + outChannel.trySend(msg) + } } } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlaybackErrorRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlaybackErrorRepository.kt index 197d7452..7bcdc99c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlaybackErrorRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlaybackErrorRepository.kt @@ -22,57 +22,60 @@ import javax.inject.Singleton * support can correlate playback errors with the surrounding plays. */ @Singleton -class PlaybackErrorRepository @Inject constructor( - private val authStore: AuthStore, - private val mutationQueue: MutationQueue, - retrofit: Retrofit, -) { - private val api: PlaybackErrorsApi = retrofit.create() +class PlaybackErrorRepository + @Inject + constructor( + private val authStore: AuthStore, + private val mutationQueue: MutationQueue, + retrofit: Retrofit, + ) { + private val api: PlaybackErrorsApi = retrofit.create() - /** - * Reports a playback failure. Returns [Outcome.ACCEPTED] on a 2xx, - * [Outcome.QUEUED] when the call was buffered to the MutationQueue - * for later replay. Never throws — callers don't need a try block. - */ - suspend fun report(event: PlaybackErrorEvent): Outcome { - val clientId = resolveClientId() - val payload = PlaybackErrorReportPayload( - trackId = event.trackId, - kind = event.kind, - detail = event.detail, - clientId = clientId, - ) - return try { - api.report( - PlaybackErrorReportRequest( - trackId = payload.trackId, - kind = payload.kind, - detail = payload.detail, - clientId = payload.clientId, - ), - ) - Outcome.ACCEPTED - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Intentional swallow — see LikesRepository.toggleLike for - // the same offline-first rationale. - mutationQueue.enqueuePlaybackErrorReport(payload) - Outcome.QUEUED + /** + * Reports a playback failure. Returns [Outcome.ACCEPTED] on a 2xx, + * [Outcome.QUEUED] when the call was buffered to the MutationQueue + * for later replay. Never throws — callers don't need a try block. + */ + suspend fun report(event: PlaybackErrorEvent): Outcome { + val clientId = resolveClientId() + val payload = + PlaybackErrorReportPayload( + trackId = event.trackId, + kind = event.kind, + detail = event.detail, + clientId = clientId, + ) + return try { + api.report( + PlaybackErrorReportRequest( + trackId = payload.trackId, + kind = payload.kind, + detail = payload.detail, + clientId = payload.clientId, + ), + ) + Outcome.ACCEPTED + } catch ( + @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, + ) { + // Intentional swallow — see LikesRepository.toggleLike for + // the same offline-first rationale. + mutationQueue.enqueuePlaybackErrorReport(payload) + Outcome.QUEUED + } } - } - /** - * Returns the persisted client id, generating + persisting one on - * first read. Mirrors [PlayEventsReporter.resolveClientId] — the - * value is shared across all client-id-carrying surfaces. - */ - private fun resolveClientId(): String { - authStore.clientId.value?.let { return it } - val fresh = UUID.randomUUID().toString() - authStore.setClientId(fresh) - return fresh - } + /** + * Returns the persisted client id, generating + persisting one on + * first read. Mirrors [PlayEventsReporter.resolveClientId] — the + * value is shared across all client-id-carrying surfaces. + */ + private fun resolveClientId(): String { + authStore.clientId.value?.let { return it } + val fresh = UUID.randomUUID().toString() + authStore.setClientId(fresh) + return fresh + } - enum class Outcome { ACCEPTED, QUEUED } -} + enum class Outcome { ACCEPTED, QUEUED } + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt index 3708cbc6..35239048 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerController.kt @@ -39,6 +39,13 @@ import javax.inject.Singleton import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException +// PlayerController is the UI-side facade over the full Media3 surface +// (transport + queue + radio + lifecycle). All the public methods are +// legitimately part of one cohesive controller — splitting into +// "TransportController", "QueueController", etc. would scatter related +// state for no gain. Suppress the per-class function-count cap rather +// than fragment. + /** * UI-facing facade over Media3's [MediaController] — the IPC client to * [MinstrelPlayerService]'s [androidx.media3.session.MediaSession]. @@ -55,856 +62,902 @@ import kotlin.coroutines.resumeWithException * the StateFlow projection means each ViewModel doesn't have to attach * its own Player.Listener. */ -// PlayerController is the UI-side facade over the full Media3 surface -// (transport + queue + radio + lifecycle). All the public methods are -// legitimately part of one cohesive controller — splitting into -// "TransportController", "QueueController", etc. would scatter related -// state for no gain. Suppress the per-class function-count cap rather -// than fragment. @Suppress("TooManyFunctions") @Singleton -class PlayerController @Inject constructor( - @ApplicationContext private val context: Context, - @ApplicationScope private val scope: CoroutineScope, - private val radio: RadioController, - private val playlists: PlaylistsRepository, - private val playerFactory: PlayerFactory, - private val activeUpnpHolder: com.fabledsword.minstrel.player.output.ActiveUpnpHolder, - private val remoteState: RemotePlayerState, - private val replayGains: ReplayGainStore, -) { - - /** - * UPnP drop events surfaced from [PlayerFactory.dropEvents]. NowPlaying - * collects this into its snackbar host so a transport / poll failure - * during UPnP playback shows "Disconnected from " to the user. - */ - val dropEvents: SharedFlow = playerFactory.dropEvents - - /** - * Raw UPnP transport readings from [PlayerFactory.transportEvents], for - * the diagnostics reporter. Read-only tap — nothing in the playback path - * consumes it. - */ - val transportEvents: SharedFlow = playerFactory.transportEvents - private val sessionToken = - SessionToken(context, ComponentName(context, MinstrelPlayerService::class.java)) - - private var mediaController: MediaController? = null - - private val uiStateInternal = MutableStateFlow(PlayerUiState()) - val uiState: StateFlow = uiStateInternal.asStateFlow() - - /** - * Per-error events for [com.fabledsword.minstrel.player.PlaybackErrorReporter]. - * Fires twice: once when Media3's `onPlayerError` surfaces a load - * failure (decoder, transport, EOS), and once when the player - * reaches STATE_READY with a duration of zero / TIME_UNSET — the - * "track loaded but has no audio" case the user sees as the - * player sitting frozen on a track. - * - * Buffered, not CONFLATED: a conflated channel drops every emission - * but the latest while the reporter loop isn't reading, so a network - * blip that failed 5 tracks back-to-back would surface only the last - * failure (the "Skipped 5 unplayable tracks" coalescing would never - * run) and POST one playback_errors row instead of 5. The default - * capacity of 64 is well above any real burst rate. - */ - private val playbackErrorEventsChannel = Channel(Channel.BUFFERED) - val playbackErrorEvents: Flow = playbackErrorEventsChannel.receiveAsFlow() - - /** - * Tracks which queue index has already been evaluated for the - * zero-duration / load-failed checks so STATE_READY firing - * repeatedly (after every seek, pause/resume) doesn't re-emit - * the same error event. Reset on each onMediaItemTransition. - */ - private var lastEvaluatedItemIndex: Int = -1 - - /** - * Listens begun, published as [PlayerUiState.listenSeq]. Bumped on every - * onMediaItemTransition: Media3 reports a repeat of the same item as a - * transition too (MEDIA_ITEM_TRANSITION_REASON_REPEAT), though the - * current track id doesn't change. - */ - private var listenSeq: Long = 0 - - /** - * Self-heal budget — re-pulls of a stale refreshable queue since - * the last successful play. Capped so a still-broken refresh can't loop; - * reset when any track loads with real audio. - */ - private var selfHealAttempts = 0 - - /** - * Stable queue snapshot kept in sync with the player's MediaItems — - * the player's own getMediaItem(index) returns Media3 types; we keep - * our domain TrackRef list alongside for the UiState projection. - */ - private var queueRefs: List = emptyList() - - init { - // A remote stall that survived the watchdog's retries is a playback - // failure like any other: the user gets the snackbar and admins get - // an admin-inbox row, via the same reporter that handles dead - // files. Without this the session just ends in silence -- the exact - // failure the watchdog exists to surface. - scope.launch { - playerFactory.stallEvents.collect { trackId -> - val title = queueRefs.firstOrNull { it.id == trackId }?.title - ?.takeIf { it.isNotEmpty() } ?: "Track" - playbackErrorEventsChannel.trySend( - PlaybackErrorEvent( - trackId = trackId, - kind = "stalled", - title = title, - detail = "remote renderer stopped and would not resume", - ), - ) - } - } - } - - /** - * Completes when [mediaController] is non-null and the listener has - * been attached. Used by [awaitReady] so cold-boot callers like - * [ResumeController] can wait for the IPC bind before calling - * transport methods that would otherwise no-op silently: a fast - * restore() landing before the MediaSessionService connection is up - * would drop the restored queue. - */ - private val readyDeferred = kotlinx.coroutines.CompletableDeferred() - - init { - scope.launch { connectAndObserve() } - } - - /** - * Suspends until the MediaController binding to - * [MinstrelPlayerService] is up and a Player.Listener is attached, - * so a subsequent transport call (setQueue, startRadio, playNext, - * …) will actually reach the player rather than being silently - * swallowed by the `mediaController ?: return` guards. - */ - suspend fun awaitReady(): Unit = readyDeferred.await() - - // ── Transport (no-op until the controller is connected) ────────────── - - // Each transport call must run on the MediaController's - // applicationLooper; calling from a background coroutine throws - // IllegalStateException (see PlayerController.setQueue's note). - // UI tap handlers are already on Main so the in-place branch hits; - // the background path only fires for cross-thread callers like - // OutputPickerController.selectUpnp (which calls pause() after - // handing playback off to a UPnP renderer). - fun play() { mediaController?.let { runOnControllerThread(it) { it.play() } } } - fun pause() { mediaController?.let { runOnControllerThread(it) { it.pause() } } } - fun seekTo(positionMs: Long) { - mediaController?.let { runOnControllerThread(it) { it.seekTo(positionMs) } } - } - fun skipToNext() { - mediaController?.let { runOnControllerThread(it) { it.seekToNextMediaItem() } } - } - /** - * Previous, as the web player does it: past the first few seconds of a - * song it starts the song over, otherwise it goes back a song. Decided - * here rather than by Media3's seekToPrevious so a cast to a Sonos speaker - * behaves the same (the restart is a seek to 0 on the speaker). - */ - fun skipToPrevious() { - val restart = uiStateInternal.value.previousRestarts - mediaController?.let { c -> - runOnControllerThread(c) { if (restart) c.seekTo(0L) else c.seekToPreviousMediaItem() } - } - } - - /** Flip shuffle on/off. Media3 emits onEvents → uiState reflects. */ - fun toggleShuffle() { - val controller = mediaController ?: return - controller.shuffleModeEnabled = !controller.shuffleModeEnabled - } - - /** - * Cycles the player's repeat mode: off → all → one → off. The wire - * order (none/all/one) matches - * what the Now Playing icon swap expects — Lucide.Repeat for off - * and all, Lucide.Repeat1 for one. - */ - fun cycleRepeat() { - val controller = mediaController ?: return - controller.repeatMode = when (controller.repeatMode) { - Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL - Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE - else -> Player.REPEAT_MODE_OFF - } - } - - /** Jump to [index] in the current queue. No-op if index is out of range. */ - fun seekToIndex(index: Int) { - val controller = mediaController ?: return - if (index !in queueRefs.indices) return - controller.seekTo(index, /* positionMs = */ 0L) - controller.play() - } - - /** - * Align the local cursor to [index] + [positionMs] WITHOUT auto-playing. - * Used by the UPnP adopt path: when attaching to a renderer that's already - * playing our queue, we sync the local cursor to the renderer's current - * track/position so skip/seek and the UI map onto its live session — the - * renderer keeps the audio, the local player stays paused. Unlike - * [seekToIndex] this issues no play(). - */ - fun moveCursorTo(index: Int, positionMs: Long) { - val controller = mediaController ?: return - if (index !in queueRefs.indices) return - runOnControllerThread(controller) { controller.seekTo(index, positionMs) } - } - - /** - * Replace the queue with [tracks] starting at [initialIndex]. - * [source] tags the queue with its origin (e.g. "for_you") so the - * server-side rotation reporter can advance it; carried in - * MediaItem extras. - * - * [autoplay] controls whether playback starts immediately. The - * default is true: the user pressed play on a tile. Cold-boot - * resume passes autoplay = false so the persisted queue is restored - * without starting audio after the user has been away from the app. - */ - fun setQueue( - tracks: List, - initialIndex: Int = 0, - source: String? = null, - autoplay: Boolean = true, +class PlayerController + @Inject + constructor( + @ApplicationContext private val context: Context, + @ApplicationScope private val scope: CoroutineScope, + private val radio: RadioController, + private val playlists: PlaylistsRepository, + private val playerFactory: PlayerFactory, + private val activeUpnpHolder: com.fabledsword.minstrel.player.output.ActiveUpnpHolder, + private val remoteState: RemotePlayerState, + private val replayGains: ReplayGainStore, ) { - val controller = mediaController ?: return - // One choke point: a track whose file the server has lost - // must not take a queue slot, whichever surface built the list. - // Playlists already drop them earlier (toPlayableTrackRefs), but - // album play-all, search, radio and cold-boot resume all arrive here - // too, and catching it once beats remembering at five call sites. - val playable = dropUnavailable(tracks, initialIndex) - if (playable.tracks.isEmpty()) return - queueRefs = playable.tracks - val items = playable.tracks.map { it.toMediaItem(source) } - val startIndex = playable.initialIndex - // Gains for the first tracks, so the first one levels from its first - // sample rather than ramping in once the lookup lands. - replayGains.request( - playable.tracks.drop(startIndex).take(GAIN_PREFETCH).map { it.id }, - ) - // Cold-boot resume calls this from a non-Main suspend - // context after awaitReady() unblocks (ResumeController launches - // on Dispatchers.Default by the time it reaches us). MediaController - // enforces application-thread access and throws - // IllegalStateException otherwise — post to its applicationLooper - // if we're already there, run directly to avoid the re-dispatch - // latency UI callers depend on. - runOnControllerThread(controller) { - controller.setMediaItems(items, startIndex, /* startPositionMs = */ 0L) - controller.prepare() - if (autoplay) controller.play() - } - } + /** + * UPnP drop events surfaced from [PlayerFactory.dropEvents]. NowPlaying + * collects this into its snackbar host so a transport / poll failure + * during UPnP playback shows "Disconnected from " to the user. + */ + val dropEvents: SharedFlow = playerFactory.dropEvents - private fun runOnControllerThread(controller: MediaController, block: () -> Unit) { - if (Looper.myLooper() == controller.applicationLooper) { - block() - } else { - Handler(controller.applicationLooper).post(block) - } - } + /** + * Raw UPnP transport readings from [PlayerFactory.transportEvents], for + * the diagnostics reporter. Read-only tap — nothing in the playback path + * consumes it. + */ + val transportEvents: SharedFlow = playerFactory.transportEvents + private val sessionToken = + SessionToken(context, ComponentName(context, MinstrelPlayerService::class.java)) - /** - * Insert [track] into the queue immediately after the currently - * playing item. Does NOT auto-play — playback state is preserved - * (Media3's [Player.addMediaItem] doesn't disturb the current - * window). No-op when the player isn't connected or the track has - * no streamUrl. - */ - fun playNext(track: TrackRef) { - val controller = mediaController ?: return - if (track.streamUrl.isEmpty()) return - val insertAt = (controller.currentMediaItemIndex + 1).coerceAtLeast(0) - queueRefs = queueRefs.toMutableList().apply { add(insertAt, track) } - controller.addMediaItem(insertAt, track.toMediaItem(source = null)) - } + private var mediaController: MediaController? = null - /** - * Append [track] to the end of the queue. Does NOT auto-play. - * Same streamUrl + connectivity guards as [playNext]. - */ - fun enqueue(track: TrackRef) { - val controller = mediaController ?: return - if (track.streamUrl.isEmpty()) return - queueRefs = queueRefs + track - controller.addMediaItem(track.toMediaItem(source = null)) - } + private val uiStateInternal = MutableStateFlow(PlayerUiState()) + val uiState: StateFlow = uiStateInternal.asStateFlow() - /** - * Reorder the queue: move the item at [from] to [to], keeping the domain - * snapshot in lock-step with the player's MediaItem timeline. Media3 emits - * onEvents → uiState reflects the new order (and the still-playing item's - * index). No-op on bad indices or a no-move. - */ - fun moveInQueue(from: Int, to: Int) { - val controller = mediaController ?: return - if (from !in queueRefs.indices || to !in queueRefs.indices || from == to) return - queueRefs = queueRefs.toMutableList().apply { add(to, removeAt(from)) } - controller.moveMediaItem(from, to) - } + /** + * Per-error events for [com.fabledsword.minstrel.player.PlaybackErrorReporter]. + * Fires twice: once when Media3's `onPlayerError` surfaces a load + * failure (decoder, transport, EOS), and once when the player + * reaches STATE_READY with a duration of zero / TIME_UNSET — the + * "track loaded but has no audio" case the user sees as the + * player sitting frozen on a track. + * + * Buffered, not CONFLATED: a conflated channel drops every emission + * but the latest while the reporter loop isn't reading, so a network + * blip that failed 5 tracks back-to-back would surface only the last + * failure (the "Skipped 5 unplayable tracks" coalescing would never + * run) and POST one playback_errors row instead of 5. The default + * capacity of 64 is well above any real burst rate. + */ + private val playbackErrorEventsChannel = Channel(Channel.BUFFERED) + val playbackErrorEvents: Flow = playbackErrorEventsChannel.receiveAsFlow() - /** - * Remove the queue item at [index]. When it's the currently-playing item - * Media3 advances to the next automatically. No-op on a bad index. - */ - fun removeFromQueue(index: Int) { - val controller = mediaController ?: return - if (index !in queueRefs.indices) return - queueRefs = queueRefs.toMutableList().apply { removeAt(index) } - controller.removeMediaItem(index) - } + /** + * Tracks which queue index has already been evaluated for the + * zero-duration / load-failed checks so STATE_READY firing + * repeatedly (after every seek, pause/resume) doesn't re-emit + * the same error event. Reset on each onMediaItemTransition. + */ + private var lastEvaluatedItemIndex: Int = -1 - /** Empty the queue and stop playback. Safe to call from any thread. */ - fun clearQueue() { - val controller = mediaController ?: return - runOnControllerThread(controller) { - queueRefs = emptyList() - controller.clearMediaItems() - } - } + /** + * Listens begun, published as [PlayerUiState.listenSeq]. Bumped on every + * onMediaItemTransition: Media3 reports a repeat of the same item as a + * transition too (MEDIA_ITEM_TRANSITION_REASON_REPEAT), though the + * current track id doesn't change. + */ + private var listenSeq: Long = 0 - /** - * Seed a fresh radio queue from [trackId]. The `source` tag is - * "radio:" so the server-side rotation reporter can - * distinguish radio plays from album / playlist plays. - * - * Two modes: - * - Nothing in the queue: start the radio cold from track 0 - * (the seed plays first, recommendations follow). - * - Queue already populated: do NOT interrupt — keep the current - * track playing as-is, trim every upcoming track, and append - * the radio results after the current item. If the seed is the - * currently playing track (the common "tap Start Radio on the - * song I'm listening to" case), drop it from the appended list - * so it doesn't immediately repeat. - * - * No-op on an empty server response; throws on transport / non-2xx - * for the caller to surface in a snackbar. - */ - suspend fun startRadio(trackId: String) { - val controller = mediaController ?: return - val tracks = radio.seed(trackId) - if (tracks.isEmpty()) return - val source = "radio:$trackId" - if (controller.mediaItemCount == 0) { - setQueue(tracks, initialIndex = 0, source = source) - } else { - appendRadioToQueue(controller, tracks, trackId, source) - } - } + /** + * Self-heal budget — re-pulls of a stale refreshable queue since + * the last successful play. Capped so a still-broken refresh can't loop; + * reset when any track loads with real audio. + */ + private var selfHealAttempts = 0 - /** - * Plays radio seeded from [trackId] now, replacing the queue: the seed - * plays first, then songs like it. Tapping a search result uses this. - * The track menu's Start radio ([startRadio]) differs on purpose: it - * keeps the current song playing and queues the radio after it. - * - * Returns false on an empty server response; throws on transport or - * non-2xx for the caller to handle. - */ - suspend fun playRadio(trackId: String): Boolean { - val tracks = radio.seed(trackId) - if (tracks.isEmpty()) return false - setQueue(tracks, initialIndex = 0, source = "radio:$trackId") - return true - } + /** + * Stable queue snapshot kept in sync with the player's MediaItems — + * the player's own getMediaItem(index) returns Media3 types; we keep + * our domain TrackRef list alongside for the UiState projection. + */ + private var queueRefs: List = emptyList() - /** - * Mid-queue radio insert. The current track keeps playing; every - * upcoming item is removed; the radio results are appended after. - * Drops the seed from the appended list when it matches the - * currently-playing track so it doesn't immediately repeat. - */ - private fun appendRadioToQueue( - controller: MediaController, - tracks: List, - seedTrackId: String, - source: String, - ) { - val currentIdx = controller.currentMediaItemIndex - val currentTrack = queueRefs.getOrNull(currentIdx) - val toAppend = if (currentTrack?.id == seedTrackId) tracks.drop(1) else tracks - if (toAppend.isEmpty()) return - val nextIdx = currentIdx + 1 - if (nextIdx < controller.mediaItemCount) { - controller.removeMediaItems(nextIdx, controller.mediaItemCount) - } - queueRefs = queueRefs.take(nextIdx) + toAppend - controller.addMediaItems(toAppend.map { it.toMediaItem(source) }) - } - - /** - * When a STATE_READY transition for a freshly-loaded item reports - * a zero / TIME_UNSET duration, fire a `zero_duration` error event - * and advance past the dead track. Otherwise no-op. - */ - private fun handleZeroDurationIfNeeded(controller: MediaController, idx: Int) { - // Skip during UPnP playback (active) AND during the activation load - // window (target set, active not yet wired). ExoPlayer is intentionally - // paused throughout both windows so its STATE_READY duration is always - // 0 / TIME_UNSET -- without this guard we rapid-advance through the - // entire local queue (and spam /api/playback-errors). - val current = queueRefs.getOrNull(idx) - val upnpEngaged = activeUpnpHolder.active.value != null || - activeUpnpHolder.target.value != null - if (current == null || upnpEngaged) return - val duration = controller.duration - val isZeroDuration = duration <= 0L || duration == androidx.media3.common.C.TIME_UNSET - if (!isZeroDuration) { - // A track loaded with real audio — clear the self-heal budget so - // a later stale queue can recover again. - selfHealAttempts = 0 - return - } - playbackErrorEventsChannel.trySend( - PlaybackErrorEvent( - trackId = current.id, - kind = "zero_duration", - title = current.title.ifEmpty { "Track" }, - detail = "duration=$duration", - ), - ) - if (controller.hasNextMediaItem()) { - controller.seekToNextMediaItem() - } else { - controller.stop() - } - } - - /** - * The queue is fully unplayable (every track failed to load). If it - * came from a refreshable source — a system playlist (bare-variant source) - * or radio ("radio:") — the snapshot is probably stale (app/tab left - * open across the daily rebuild); re-pull it and resume instead of stopping. - * Bounded by [selfHealAttempts]. Album / artist / user-playlist / offline - * sources have nothing to refresh — stop. - */ - private fun selfHealOrStop(controller: MediaController) { - val source = controller.currentMediaItem - ?.mediaMetadata?.extras?.getString(MINSTREL_SOURCE_KEY) - if (source == null || selfHealAttempts >= MAX_SELF_HEAL_ATTEMPTS) { - controller.stop() - return - } - when { - source.startsWith("radio:") -> { - selfHealAttempts++ - scope.launch { selfHealRadio(source.removePrefix("radio:")) } - } - !source.contains(':') -> { // bare variant = refreshable system playlist - selfHealAttempts++ - scope.launch { selfHealSystem(source) } - } - else -> controller.stop() - } - } - - private suspend fun selfHealSystem(variant: String) { - val refs = runCatching { playlists.systemShuffle(variant).tracks.toPlayableTrackRefs() } - .getOrDefault(emptyList()) - if (refs.isEmpty()) { - stopOnControllerThread() - return - } - setQueue(refs, initialIndex = 0, source = variant) - } - - private suspend fun selfHealRadio(seedTrackId: String) { - val refs = runCatching { radio.seed(seedTrackId) }.getOrDefault(emptyList()) - if (refs.isEmpty()) { - stopOnControllerThread() - return - } - setQueue(refs, initialIndex = 0, source = "radio:$seedTrackId") - } - - private fun stopOnControllerThread() { - val controller = mediaController ?: return - runOnControllerThread(controller) { controller.stop() } - } - - // ── Internal: async connect + Listener-driven UI state sync ────────── - - private suspend fun connectAndObserve() { - val controller = - try { - connectController() - } catch ( - // Service-connection failure is a "show error, move on" boundary — - // any throwable from the Media3 IPC handshake gets surfaced via - // playbackError. Specific-exception handling buys nothing here. - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - uiStateInternal.value = - uiStateInternal.value.copy(playbackError = e.message ?: "Player unavailable") - return - } - mediaController = controller - // Signal awaitReady() callers (ResumeController et al.) - // that the controller is bound. Listener is attached below in - // the same coroutine so by the time downstream code runs after - // awaitReady, the Player.Listener is wired too. - if (!readyDeferred.isCompleted) readyDeferred.complete(Unit) - startPositionPolling(controller) - // Keep isUpnpLoading current between player-event fires: holder state - // changes (setTarget / set(active)) are independent of Media3 events, so - // onEvents alone would lag behind by up to one event cycle. This collector - // runs for the process lifetime alongside the position poller. - scope.launch { - combine( - activeUpnpHolder.target, - activeUpnpHolder.active, - ) { target, active -> target != null && active == null } - .collect { isLoading -> - uiStateInternal.value = uiStateInternal.value.copy(isUpnpLoading = isLoading) - } - } - controller.addListener( - object : Player.Listener { - override fun onPlayerError(error: androidx.media3.common.PlaybackException) { - val current = queueRefs.getOrNull(controller.currentMediaItemIndex) - val title = current?.title?.takeIf { it.isNotEmpty() } ?: "Track" - val trackId = current?.id ?: return + init { + // A remote stall that survived the watchdog's retries is a playback + // failure like any other: the user gets the snackbar and admins get + // an admin-inbox row, via the same reporter that handles dead + // files. Without this the session just ends in silence -- the exact + // failure the watchdog exists to surface. + scope.launch { + playerFactory.stallEvents.collect { trackId -> + val title = + queueRefs + .firstOrNull { it.id == trackId } + ?.title + ?.takeIf { it.isNotEmpty() } ?: "Track" playbackErrorEventsChannel.trySend( PlaybackErrorEvent( trackId = trackId, - kind = "load_failed", + kind = "stalled", title = title, - detail = error.message, + detail = "remote renderer stopped and would not resume", ), ) - // A failed load leaves the player IDLE; advance past the bad - // track and re-prepare so one unplayable item doesn't strand - // playback (mirrors the zero_duration skip). At the end of a - // fully-unplayable queue, try to self-heal a stale refreshable - // source before stopping. - if (controller.hasNextMediaItem()) { - controller.seekToNextMediaItem() - controller.prepare() - } else { - selfHealOrStop(controller) - } } - - override fun onMediaItemTransition( - mediaItem: androidx.media3.common.MediaItem?, - reason: Int, - ) { - // A new listen begins, the same item on repeat included. - listenSeq++ - // Reset the per-item evaluation guard so the new - // item's STATE_READY transition gets a fresh check. - lastEvaluatedItemIndex = -1 - // The track flipped -- re-anchor the position interpolator - // so the next polling tick treats the new track's - // remoteState.positionMs as fresh rather than carrying the - // old anchor + elapsed forward. - lastSeenRemotePositionMs = -1L - } - - override fun onPlaybackStateChanged(playbackState: Int) { - if (playbackState != Player.STATE_READY) return - val idx = controller.currentMediaItemIndex - if (idx == lastEvaluatedItemIndex) return - lastEvaluatedItemIndex = idx - handleZeroDurationIfNeeded(controller, idx) - } - - override fun onEvents(player: Player, events: Player.Events) { - val idx = player.currentMediaItemIndex - val current = queueRefs.getOrNull(idx) - val source = player.currentMediaItem - ?.mediaMetadata - ?.extras - ?.getString(MINSTREL_SOURCE_KEY) - val isUpnpLoading = activeUpnpHolder.target.value != null && - activeUpnpHolder.active.value == null - // When UPnP is active, the wrapped ExoPlayer is paused with - // no real audio loaded -- player.duration / isPlaying / - // currentPosition all reflect that. Read from remoteState - // instead so an onEvents fire (e.g. activity resume) doesn't - // clobber the UI with zeros. Duration falls back to the - // wrapped player's value when Sonos hasn't reported one yet - // (pre-first-poll window, or Sonos still buffering) -- the - // wrapped ExoPlayer was prepared with the same MediaItem so - // it knows the real duration before any SOAP poll lands. - val upnpActive = activeUpnpHolder.active.value != null - uiStateInternal.value = - PlayerUiState( - currentTrack = current, - queue = queueRefs, - queueIndex = idx, - isPlaying = if (upnpActive) remoteState.isPlaying else player.isPlaying, - isBuffering = !upnpActive && - player.playbackState == Player.STATE_BUFFERING, - positionMs = if (upnpActive) { - remoteState.positionMs - } else { - player.currentPosition - }.coerceAtLeast(0), - durationMs = effectiveDuration( - upnpActive, - remoteState.durationMs, - player.duration, - desiredIdx = idx, - controllerIdx = idx, - ), - bufferedPositionMs = player.bufferedPosition.coerceAtLeast(0), - playbackError = player.playerError?.message, - currentSource = source, - shuffleEnabled = player.shuffleModeEnabled, - repeatMode = when (player.repeatMode) { - Player.REPEAT_MODE_ALL -> RepeatMode.ALL - Player.REPEAT_MODE_ONE -> RepeatMode.ONE - else -> RepeatMode.OFF - }, - isUpnpLoading = isUpnpLoading, - listenSeq = listenSeq, - hasPrevious = player.hasPreviousMediaItem(), - hasNext = player.hasNextMediaItem(), - ) - } - }, - ) - } - - /** - * Periodic `currentPosition` / `bufferedPosition` poller. Media3's - * `Player.Events` callbacks only fire at boundaries (track change, - * pause/play, buffer state), never on normal position advancement, - * so the seek bar would otherwise sit static between events. Polls - * at [POSITION_POLL_INTERVAL_MS], which reads as smooth on a slider - * without being battery-hostile. - * - * The poll only patches position fields via `.copy()` so a stale - * `onEvents` snapshot can't clobber the latest state. MediaController - * is touched only from the main dispatcher. - */ - private fun startPositionPolling(controller: MediaController) { - scope.launch(Dispatchers.Main.immediate) { - while (isActive) { - delay(POSITION_POLL_INTERVAL_MS) - tickPositionPoll(controller) } } - } - /** - * One position-polling tick. Patches ONLY the smoothly-changing transport - * fields (position / duration / play-pause / buffer) via `.copy()`. The - * queue index + current track are owned solely by [onEvents], which reads - * the authoritative delegate cursor: during a cast, - * [MinstrelForwardingPlayer.syncLocalCursorToRemote] keeps that cursor on - * the track the renderer is actually playing (matched by identity), so there - * is exactly one writer of "what's playing" and a stale tick can never - * revert it to the old track. (Previously the tick was a second index writer - * that fought onEvents — the flicker-to-stale-track bug.) - */ - private fun tickPositionPoll(controller: MediaController) { - val upnpActive = activeUpnpHolder.active.value != null - resolvePendingTransport(controller, upnpActive) - val effectiveIsPlaying = - if (upnpActive) remoteState.isPlaying else controller.isPlaying - val effectivePosition = if (upnpActive) { - interpolatedRemotePosition(effectiveIsPlaying) - } else { - controller.currentPosition + /** + * Completes when [mediaController] is non-null and the listener has + * been attached. Used by [awaitReady] so cold-boot callers like + * [ResumeController] can wait for the IPC bind before calling + * transport methods that would otherwise no-op silently: a fast + * restore() landing before the MediaSessionService connection is up + * would drop the restored queue. + */ + private val readyDeferred = kotlinx.coroutines.CompletableDeferred() + + init { + scope.launch { connectAndObserve() } } - val idx = controller.currentMediaItemIndex - val current = uiStateInternal.value - val newPos = effectivePosition.coerceAtLeast(0) - val newDur = effectiveDuration( - upnpActive, - remoteState.durationMs, - controller.duration, - desiredIdx = idx, - controllerIdx = idx, - ) - val newBuf = controller.bufferedPosition.coerceAtLeast(0) - val somethingChanged = current.isPlaying != effectiveIsPlaying || - current.positionMs != newPos || - current.durationMs != newDur || - current.bufferedPositionMs != newBuf - if (somethingChanged) { - uiStateInternal.value = current.copy( - isPlaying = effectiveIsPlaying, - positionMs = newPos, - durationMs = newDur, - bufferedPositionMs = newBuf, + + /** + * Suspends until the MediaController binding to + * [MinstrelPlayerService] is up and a Player.Listener is attached, + * so a subsequent transport call (setQueue, startRadio, playNext, + * …) will actually reach the player rather than being silently + * swallowed by the `mediaController ?: return` guards. + */ + suspend fun awaitReady(): Unit = readyDeferred.await() + + // ── Transport (no-op until the controller is connected) ────────────── + + // Each transport call must run on the MediaController's + // applicationLooper; calling from a background coroutine throws + // IllegalStateException (see PlayerController.setQueue's note). + // UI tap handlers are already on Main so the in-place branch hits; + // the background path only fires for cross-thread callers like + // OutputPickerController.selectUpnp (which calls pause() after + // handing playback off to a UPnP renderer). + fun play() { + mediaController?.let { runOnControllerThread(it) { it.play() } } + } + + fun pause() { + mediaController?.let { runOnControllerThread(it) { it.pause() } } + } + + fun seekTo(positionMs: Long) { + mediaController?.let { runOnControllerThread(it) { it.seekTo(positionMs) } } + } + + fun skipToNext() { + mediaController?.let { runOnControllerThread(it) { it.seekToNextMediaItem() } } + } + + /** + * Previous, as the web player does it: past the first few seconds of a + * song it starts the song over, otherwise it goes back a song. Decided + * here rather than by Media3's seekToPrevious so a cast to a Sonos speaker + * behaves the same (the restart is a seek to 0 on the speaker). + */ + fun skipToPrevious() { + val restart = uiStateInternal.value.previousRestarts + mediaController?.let { c -> + runOnControllerThread(c) { if (restart) c.seekTo(0L) else c.seekToPreviousMediaItem() } + } + } + + /** Flip shuffle on/off. Media3 emits onEvents → uiState reflects. */ + fun toggleShuffle() { + val controller = mediaController ?: return + controller.shuffleModeEnabled = !controller.shuffleModeEnabled + } + + /** + * Cycles the player's repeat mode: off → all → one → off. The wire + * order (none/all/one) matches + * what the Now Playing icon swap expects — Lucide.Repeat for off + * and all, Lucide.Repeat1 for one. + */ + fun cycleRepeat() { + val controller = mediaController ?: return + controller.repeatMode = + when (controller.repeatMode) { + Player.REPEAT_MODE_OFF -> Player.REPEAT_MODE_ALL + Player.REPEAT_MODE_ALL -> Player.REPEAT_MODE_ONE + else -> Player.REPEAT_MODE_OFF + } + } + + /** Jump to [index] in the current queue. No-op if index is out of range. */ + fun seekToIndex(index: Int) { + val controller = mediaController ?: return + if (index !in queueRefs.indices) return + controller.seekTo(index, 0L) // positionMs + controller.play() + } + + /** + * Align the local cursor to [index] + [positionMs] WITHOUT auto-playing. + * Used by the UPnP adopt path: when attaching to a renderer that's already + * playing our queue, we sync the local cursor to the renderer's current + * track/position so skip/seek and the UI map onto its live session — the + * renderer keeps the audio, the local player stays paused. Unlike + * [seekToIndex] this issues no play(). + */ + fun moveCursorTo( + index: Int, + positionMs: Long, + ) { + val controller = mediaController ?: return + if (index !in queueRefs.indices) return + runOnControllerThread(controller) { controller.seekTo(index, positionMs) } + } + + /** + * Replace the queue with [tracks] starting at [initialIndex]. + * [source] tags the queue with its origin (e.g. "for_you") so the + * server-side rotation reporter can advance it; carried in + * MediaItem extras. + * + * [autoplay] controls whether playback starts immediately. The + * default is true: the user pressed play on a tile. Cold-boot + * resume passes autoplay = false so the persisted queue is restored + * without starting audio after the user has been away from the app. + */ + fun setQueue( + tracks: List, + initialIndex: Int = 0, + source: String? = null, + autoplay: Boolean = true, + ) { + val controller = mediaController ?: return + // One choke point: a track whose file the server has lost + // must not take a queue slot, whichever surface built the list. + // Playlists already drop them earlier (toPlayableTrackRefs), but + // album play-all, search, radio and cold-boot resume all arrive here + // too, and catching it once beats remembering at five call sites. + val playable = dropUnavailable(tracks, initialIndex) + if (playable.tracks.isEmpty()) return + queueRefs = playable.tracks + val items = playable.tracks.map { it.toMediaItem(source) } + val startIndex = playable.initialIndex + // Gains for the first tracks, so the first one levels from its first + // sample rather than ramping in once the lookup lands. + replayGains.request( + playable.tracks + .drop(startIndex) + .take(GAIN_PREFETCH) + .map { it.id }, ) + // Cold-boot resume calls this from a non-Main suspend + // context after awaitReady() unblocks (ResumeController launches + // on Dispatchers.Default by the time it reaches us). MediaController + // enforces application-thread access and throws + // IllegalStateException otherwise — post to its applicationLooper + // if we're already there, run directly to avoid the re-dispatch + // latency UI callers depend on. + runOnControllerThread(controller) { + controller.setMediaItems(items, startIndex, 0L) // startPositionMs + controller.prepare() + if (autoplay) controller.play() + } } - } - /** - * Event-driven primary path: clear pending the moment Sonos's reported - * Track matches the wrapped player's index. Safety fallback: clear on - * deadline so we don't ignore Sonos's actual state forever if SOAP fails. - */ - private fun resolvePendingTransport(controller: MediaController, upnpActive: Boolean) { - if (!upnpActive || remoteState.pendingTransportDeadlineMs <= 0L) return - val sonosIdx = (remoteState.trackNumber - 1).coerceAtLeast(0) - val timedOut = SystemClock.elapsedRealtime() > remoteState.pendingTransportDeadlineMs - if (sonosIdx == controller.currentMediaItemIndex || timedOut) { - remoteState.clearPendingTransport() + private fun runOnControllerThread( + controller: MediaController, + block: () -> Unit, + ) { + if (Looper.myLooper() == controller.applicationLooper) { + block() + } else { + Handler(controller.applicationLooper).post(block) + } } - } - // ── Remote position interpolation state ────────────────────────────── - // remoteState.positionMs is only refreshed by ForwardingPlayer's 1Hz - // SOAP poll (and only when the round-trip completes -- screen-off WiFi - // sleep can stall it for many seconds). To keep the scrubber moving - // smoothly we anchor each fresh reading + an elapsed-realtime stamp; - // between updates we display anchor + elapsed when Sonos is playing. - // A real correction lands as soon as the next poll arrives. - @Volatile private var lastSeenRemotePositionMs: Long = -1L - @Volatile private var positionAnchorMs: Long = 0L - @Volatile private var positionAnchorAtRealtimeMs: Long = 0L - - private fun interpolatedRemotePosition(isPlaying: Boolean): Long { - val raw = remoteState.positionMs - val now = SystemClock.elapsedRealtime() - if (raw != lastSeenRemotePositionMs) { - lastSeenRemotePositionMs = raw - positionAnchorMs = raw - positionAnchorAtRealtimeMs = now + /** + * Insert [track] into the queue immediately after the currently + * playing item. Does NOT auto-play — playback state is preserved + * (Media3's [Player.addMediaItem] doesn't disturb the current + * window). No-op when the player isn't connected or the track has + * no streamUrl. + */ + fun playNext(track: TrackRef) { + val controller = mediaController ?: return + if (track.streamUrl.isEmpty()) return + val insertAt = (controller.currentMediaItemIndex + 1).coerceAtLeast(0) + queueRefs = queueRefs.toMutableList().apply { add(insertAt, track) } + controller.addMediaItem(insertAt, track.toMediaItem(source = null)) } - if (!isPlaying) return positionAnchorMs - // Cap how far past the last anchor we extrapolate. After - // MAX_INTERPOLATION_DRIFT_MS without a poll update, freeze the - // displayed position at anchor + cap rather than projecting wildly. - // The next successful poll re-anchors and motion resumes. - val delta = (now - positionAnchorAtRealtimeMs).coerceAtMost(MAX_INTERPOLATION_DRIFT_MS) - return positionAnchorMs + delta - } - /** - * Bridges Media3's `ListenableFuture.buildAsync()` - * to a suspend function without pulling in `kotlinx-coroutines-guava` - * — the future's `addListener` callback is enough. `Runnable::run` - * is a direct executor (no extra threading) since the callback only - * unparks our continuation. - */ - private suspend fun connectController(): MediaController = - suspendCancellableCoroutine { cont -> - val future = MediaController.Builder(context, sessionToken).buildAsync() - future.addListener( - { - try { - cont.resume(future.get()) - } catch ( - // ListenableFuture.get() throws ExecutionException + - // InterruptedException + CancellationException — handle - // them uniformly by forwarding to the continuation; - // the caller catches at the outer boundary. - @Suppress("TooGenericExceptionCaught") e: Throwable, + /** + * Append [track] to the end of the queue. Does NOT auto-play. + * Same streamUrl + connectivity guards as [playNext]. + */ + fun enqueue(track: TrackRef) { + val controller = mediaController ?: return + if (track.streamUrl.isEmpty()) return + queueRefs = queueRefs + track + controller.addMediaItem(track.toMediaItem(source = null)) + } + + /** + * Reorder the queue: move the item at [from] to [to], keeping the domain + * snapshot in lock-step with the player's MediaItem timeline. Media3 emits + * onEvents → uiState reflects the new order (and the still-playing item's + * index). No-op on bad indices or a no-move. + */ + fun moveInQueue( + from: Int, + to: Int, + ) { + val controller = mediaController ?: return + if (from !in queueRefs.indices || to !in queueRefs.indices || from == to) return + queueRefs = queueRefs.toMutableList().apply { add(to, removeAt(from)) } + controller.moveMediaItem(from, to) + } + + /** + * Remove the queue item at [index]. When it's the currently-playing item + * Media3 advances to the next automatically. No-op on a bad index. + */ + fun removeFromQueue(index: Int) { + val controller = mediaController ?: return + if (index !in queueRefs.indices) return + queueRefs = queueRefs.toMutableList().apply { removeAt(index) } + controller.removeMediaItem(index) + } + + /** Empty the queue and stop playback. Safe to call from any thread. */ + fun clearQueue() { + val controller = mediaController ?: return + runOnControllerThread(controller) { + queueRefs = emptyList() + controller.clearMediaItems() + } + } + + /** + * Seed a fresh radio queue from [trackId]. The `source` tag is + * "radio:" so the server-side rotation reporter can + * distinguish radio plays from album / playlist plays. + * + * Two modes: + * - Nothing in the queue: start the radio cold from track 0 + * (the seed plays first, recommendations follow). + * - Queue already populated: do NOT interrupt — keep the current + * track playing as-is, trim every upcoming track, and append + * the radio results after the current item. If the seed is the + * currently playing track (the common "tap Start Radio on the + * song I'm listening to" case), drop it from the appended list + * so it doesn't immediately repeat. + * + * No-op on an empty server response; throws on transport / non-2xx + * for the caller to surface in a snackbar. + */ + suspend fun startRadio(trackId: String) { + val controller = mediaController ?: return + val tracks = radio.seed(trackId) + if (tracks.isEmpty()) return + val source = "radio:$trackId" + if (controller.mediaItemCount == 0) { + setQueue(tracks, initialIndex = 0, source = source) + } else { + appendRadioToQueue(controller, tracks, trackId, source) + } + } + + /** + * Plays radio seeded from [trackId] now, replacing the queue: the seed + * plays first, then songs like it. Tapping a search result uses this. + * The track menu's Start radio ([startRadio]) differs on purpose: it + * keeps the current song playing and queues the radio after it. + * + * Returns false on an empty server response; throws on transport or + * non-2xx for the caller to handle. + */ + suspend fun playRadio(trackId: String): Boolean { + val tracks = radio.seed(trackId) + if (tracks.isEmpty()) return false + setQueue(tracks, initialIndex = 0, source = "radio:$trackId") + return true + } + + /** + * Mid-queue radio insert. The current track keeps playing; every + * upcoming item is removed; the radio results are appended after. + * Drops the seed from the appended list when it matches the + * currently-playing track so it doesn't immediately repeat. + */ + private fun appendRadioToQueue( + controller: MediaController, + tracks: List, + seedTrackId: String, + source: String, + ) { + val currentIdx = controller.currentMediaItemIndex + val currentTrack = queueRefs.getOrNull(currentIdx) + val toAppend = if (currentTrack?.id == seedTrackId) tracks.drop(1) else tracks + if (toAppend.isEmpty()) return + val nextIdx = currentIdx + 1 + if (nextIdx < controller.mediaItemCount) { + controller.removeMediaItems(nextIdx, controller.mediaItemCount) + } + queueRefs = queueRefs.take(nextIdx) + toAppend + controller.addMediaItems(toAppend.map { it.toMediaItem(source) }) + } + + /** + * When a STATE_READY transition for a freshly-loaded item reports + * a zero / TIME_UNSET duration, fire a `zero_duration` error event + * and advance past the dead track. Otherwise no-op. + */ + private fun handleZeroDurationIfNeeded( + controller: MediaController, + idx: Int, + ) { + // Skip during UPnP playback (active) AND during the activation load + // window (target set, active not yet wired). ExoPlayer is intentionally + // paused throughout both windows so its STATE_READY duration is always + // 0 / TIME_UNSET -- without this guard we rapid-advance through the + // entire local queue (and spam /api/playback-errors). + val current = queueRefs.getOrNull(idx) + val upnpEngaged = + activeUpnpHolder.active.value != null || + activeUpnpHolder.target.value != null + if (current == null || upnpEngaged) return + val duration = controller.duration + val isZeroDuration = duration <= 0L || duration == androidx.media3.common.C.TIME_UNSET + if (!isZeroDuration) { + // A track loaded with real audio — clear the self-heal budget so + // a later stale queue can recover again. + selfHealAttempts = 0 + return + } + playbackErrorEventsChannel.trySend( + PlaybackErrorEvent( + trackId = current.id, + kind = "zero_duration", + title = current.title.ifEmpty { "Track" }, + detail = "duration=$duration", + ), + ) + if (controller.hasNextMediaItem()) { + controller.seekToNextMediaItem() + } else { + controller.stop() + } + } + + /** + * The queue is fully unplayable (every track failed to load). If it + * came from a refreshable source — a system playlist (bare-variant source) + * or radio ("radio:") — the snapshot is probably stale (app/tab left + * open across the daily rebuild); re-pull it and resume instead of stopping. + * Bounded by [selfHealAttempts]. Album / artist / user-playlist / offline + * sources have nothing to refresh — stop. + */ + private fun selfHealOrStop(controller: MediaController) { + val source = + controller.currentMediaItem + ?.mediaMetadata + ?.extras + ?.getString(MINSTREL_SOURCE_KEY) + if (source == null || selfHealAttempts >= MAX_SELF_HEAL_ATTEMPTS) { + controller.stop() + return + } + when { + source.startsWith("radio:") -> { + selfHealAttempts++ + scope.launch { selfHealRadio(source.removePrefix("radio:")) } + } + !source.contains(':') -> { // bare variant = refreshable system playlist + selfHealAttempts++ + scope.launch { selfHealSystem(source) } + } + else -> controller.stop() + } + } + + private suspend fun selfHealSystem(variant: String) { + val refs = + runCatching { playlists.systemShuffle(variant).tracks.toPlayableTrackRefs() } + .getOrDefault(emptyList()) + if (refs.isEmpty()) { + stopOnControllerThread() + return + } + setQueue(refs, initialIndex = 0, source = variant) + } + + private suspend fun selfHealRadio(seedTrackId: String) { + val refs = runCatching { radio.seed(seedTrackId) }.getOrDefault(emptyList()) + if (refs.isEmpty()) { + stopOnControllerThread() + return + } + setQueue(refs, initialIndex = 0, source = "radio:$seedTrackId") + } + + private fun stopOnControllerThread() { + val controller = mediaController ?: return + runOnControllerThread(controller) { controller.stop() } + } + + // ── Internal: async connect + Listener-driven UI state sync ────────── + + private suspend fun connectAndObserve() { + val controller = + try { + connectController() + } catch ( + // Service-connection failure is a "show error, move on" boundary — + // any throwable from the Media3 IPC handshake gets surfaced via + // playbackError. Specific-exception handling buys nothing here. + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + uiStateInternal.value = + uiStateInternal.value.copy(playbackError = e.message ?: "Player unavailable") + return + } + mediaController = controller + // Signal awaitReady() callers (ResumeController et al.) + // that the controller is bound. Listener is attached below in + // the same coroutine so by the time downstream code runs after + // awaitReady, the Player.Listener is wired too. + if (!readyDeferred.isCompleted) readyDeferred.complete(Unit) + startPositionPolling(controller) + // Keep isUpnpLoading current between player-event fires: holder state + // changes (setTarget / set(active)) are independent of Media3 events, so + // onEvents alone would lag behind by up to one event cycle. This collector + // runs for the process lifetime alongside the position poller. + scope.launch { + combine( + activeUpnpHolder.target, + activeUpnpHolder.active, + ) { target, active -> target != null && active == null } + .collect { isLoading -> + uiStateInternal.value = uiStateInternal.value.copy(isUpnpLoading = isLoading) + } + } + controller.addListener( + object : Player.Listener { + override fun onPlayerError(error: androidx.media3.common.PlaybackException) { + val current = queueRefs.getOrNull(controller.currentMediaItemIndex) + val title = current?.title?.takeIf { it.isNotEmpty() } ?: "Track" + val trackId = current?.id ?: return + playbackErrorEventsChannel.trySend( + PlaybackErrorEvent( + trackId = trackId, + kind = "load_failed", + title = title, + detail = error.message, + ), + ) + // A failed load leaves the player IDLE; advance past the bad + // track and re-prepare so one unplayable item doesn't strand + // playback (mirrors the zero_duration skip). At the end of a + // fully-unplayable queue, try to self-heal a stale refreshable + // source before stopping. + if (controller.hasNextMediaItem()) { + controller.seekToNextMediaItem() + controller.prepare() + } else { + selfHealOrStop(controller) + } + } + + override fun onMediaItemTransition( + mediaItem: androidx.media3.common.MediaItem?, + reason: Int, ) { - cont.resumeWithException(e) + // A new listen begins, the same item on repeat included. + listenSeq++ + // Reset the per-item evaluation guard so the new + // item's STATE_READY transition gets a fresh check. + lastEvaluatedItemIndex = -1 + // The track flipped -- re-anchor the position interpolator + // so the next polling tick treats the new track's + // remoteState.positionMs as fresh rather than carrying the + // old anchor + elapsed forward. + lastSeenRemotePositionMs = -1L + } + + override fun onPlaybackStateChanged(playbackState: Int) { + if (playbackState != Player.STATE_READY) return + val idx = controller.currentMediaItemIndex + if (idx == lastEvaluatedItemIndex) return + lastEvaluatedItemIndex = idx + handleZeroDurationIfNeeded(controller, idx) + } + + override fun onEvents( + player: Player, + events: Player.Events, + ) { + val idx = player.currentMediaItemIndex + val current = queueRefs.getOrNull(idx) + val source = + player.currentMediaItem + ?.mediaMetadata + ?.extras + ?.getString(MINSTREL_SOURCE_KEY) + val isUpnpLoading = + activeUpnpHolder.target.value != null && + activeUpnpHolder.active.value == null + // When UPnP is active, the wrapped ExoPlayer is paused with + // no real audio loaded -- player.duration / isPlaying / + // currentPosition all reflect that. Read from remoteState + // instead so an onEvents fire (e.g. activity resume) doesn't + // clobber the UI with zeros. Duration falls back to the + // wrapped player's value when Sonos hasn't reported one yet + // (pre-first-poll window, or Sonos still buffering) -- the + // wrapped ExoPlayer was prepared with the same MediaItem so + // it knows the real duration before any SOAP poll lands. + val upnpActive = activeUpnpHolder.active.value != null + uiStateInternal.value = + PlayerUiState( + currentTrack = current, + queue = queueRefs, + queueIndex = idx, + isPlaying = if (upnpActive) remoteState.isPlaying else player.isPlaying, + isBuffering = + !upnpActive && + player.playbackState == Player.STATE_BUFFERING, + positionMs = + if (upnpActive) { + remoteState.positionMs + } else { + player.currentPosition + }.coerceAtLeast(0), + durationMs = + effectiveDuration( + upnpActive, + remoteState.durationMs, + player.duration, + desiredIdx = idx, + controllerIdx = idx, + ), + bufferedPositionMs = player.bufferedPosition.coerceAtLeast(0), + playbackError = player.playerError?.message, + currentSource = source, + shuffleEnabled = player.shuffleModeEnabled, + repeatMode = + when (player.repeatMode) { + Player.REPEAT_MODE_ALL -> RepeatMode.ALL + Player.REPEAT_MODE_ONE -> RepeatMode.ONE + else -> RepeatMode.OFF + }, + isUpnpLoading = isUpnpLoading, + listenSeq = listenSeq, + hasPrevious = player.hasPreviousMediaItem(), + hasNext = player.hasNextMediaItem(), + ) } }, - Runnable::run, ) - cont.invokeOnCancellation { future.cancel(/* mayInterruptIfRunning = */ false) } } - private fun TrackRef.toMediaItem(source: String?): MediaItem { - val metadata = MediaMetadata.Builder() - .setTitle(title) - .setArtist(artistName) - .setAlbumTitle(albumTitle) - .apply { - // Server-known duration -- gives the lock-screen / notification - // scrubber a real total even when the wrapped ExoPlayer is - // paused under UPnP (it never probes a duration in that state). - if (durationSec > 0) setDurationMs(durationSec.toLong() * MS_PER_SECOND) - // Album and track position let the gain processor tell an - // album played in order from a mix. - trackNumber?.let { setTrackNumber(it) } - discNumber?.let { setDiscNumber(it) } - val extras = GainAudioProcessor.albumExtras(albumId) - if (source != null) extras.putAll(sourceExtras(source)) - setExtras(extras) - // Point the notification / lock-screen art at the SAME album - // cover the in-app surfaces use (TrackRef.coverUrl -> - // /api/albums/{id}/cover). Without this, Media3 falls back to - // whatever art is embedded in the stream's tags, which can be a - // different image than the server's album cover. Setting - // artworkUri here is load-bearing: MediaMetadata.populate() - // overwrites artworkUri + artworkData as a pair, so the - // MediaItem's URI clears any embedded artworkData ExoPlayer - // extracts from the stream -- the cover endpoint wins on both - // surfaces. The session's OkHttp-backed BitmapLoader (see - // PlayerFactory) is what makes this authed placeholder URL load. - if (coverUrl.isNotEmpty()) setArtworkUri(coverUrl.toUri()) + /** + * Periodic `currentPosition` / `bufferedPosition` poller. Media3's + * `Player.Events` callbacks only fire at boundaries (track change, + * pause/play, buffer state), never on normal position advancement, + * so the seek bar would otherwise sit static between events. Polls + * at [POSITION_POLL_INTERVAL_MS], which reads as smooth on a slider + * without being battery-hostile. + * + * The poll only patches position fields via `.copy()` so a stale + * `onEvents` snapshot can't clobber the latest state. MediaController + * is touched only from the main dispatcher. + */ + private fun startPositionPolling(controller: MediaController) { + scope.launch(Dispatchers.Main.immediate) { + while (isActive) { + delay(POSITION_POLL_INTERVAL_MS) + tickPositionPoll(controller) + } } - .build() - // Server's stream_url is a relative path (/api/tracks/{id}/stream); - // resolve to the placeholder.invalid form so OkHttpDataSource (sharing - // BaseUrlInterceptor) rewrites it to the live server with the auth - // cookie. Same resolver as covers — one place for /api/* URLs. - val resolvedUri = resolveServerUrl(streamUrl) ?: streamUrl - return MediaItem.Builder() - .setMediaId(id) - .setUri(resolvedUri) - // Key the Media3 SimpleCache by trackId (not the stream URL) so - // cache residency can be queried per track for the cached dot + - // offline pools, independent of URL/host rewrites. - .setCustomCacheKey(id) - .setMediaMetadata(metadata) - .build() - } + } - private fun sourceExtras(source: String): Bundle = - Bundle().apply { putString(MINSTREL_SOURCE_KEY, source) } + /** + * One position-polling tick. Patches ONLY the smoothly-changing transport + * fields (position / duration / play-pause / buffer) via `.copy()`. The + * queue index + current track are owned solely by [onEvents], which reads + * the authoritative delegate cursor: during a cast, + * [MinstrelForwardingPlayer.syncLocalCursorToRemote] keeps that cursor on + * the track the renderer is actually playing (matched by identity), so there + * is exactly one writer of "what's playing" and a stale tick can never + * revert it to the old track. (Previously the tick was a second index writer + * that fought onEvents — the flicker-to-stale-track bug.) + */ + private fun tickPositionPoll(controller: MediaController) { + val upnpActive = activeUpnpHolder.active.value != null + resolvePendingTransport(controller, upnpActive) + val effectiveIsPlaying = + if (upnpActive) remoteState.isPlaying else controller.isPlaying + val effectivePosition = + if (upnpActive) { + interpolatedRemotePosition(effectiveIsPlaying) + } else { + controller.currentPosition + } + val idx = controller.currentMediaItemIndex + val current = uiStateInternal.value + val newPos = effectivePosition.coerceAtLeast(0) + val newDur = + effectiveDuration( + upnpActive, + remoteState.durationMs, + controller.duration, + desiredIdx = idx, + controllerIdx = idx, + ) + val newBuf = controller.bufferedPosition.coerceAtLeast(0) + val somethingChanged = + current.isPlaying != effectiveIsPlaying || + current.positionMs != newPos || + current.durationMs != newDur || + current.bufferedPositionMs != newBuf + if (somethingChanged) { + uiStateInternal.value = + current.copy( + isPlaying = effectiveIsPlaying, + positionMs = newPos, + durationMs = newDur, + bufferedPositionMs = newBuf, + ) + } + } - /** - * Duration to surface to the UI. Priority: Sonos's reported duration - * (only when UPnP active and non-zero) -> wrapped ExoPlayer's value - * (only valid once it's probed the stream) -> TrackRef.durationSec - * (always known from the server response). The third tier is what - * keeps the scrubber populated when the user taps Sonos before the - * wrapped player has had time to probe its own duration -- without - * it, both top tiers report 0/TIME_UNSET and the field reads empty - * until the first SOAP poll lands. - */ - @Suppress("ReturnCount") // 3-tier fallback reads cleanest as a ladder of early returns - private fun effectiveDuration( - upnpActive: Boolean, - remoteMs: Long, - localMs: Long, - desiredIdx: Int, - controllerIdx: Int, - ): Long { - if (upnpActive && remoteMs > 0) return remoteMs - // Tier 2 (wrapped player's probed duration) only valid when the - // wrapped player is on the same track we're trying to show. After a - // Sonos natural advance the polling tick updates desiredIdx from - // Sonos's truth while controllerIdx is briefly stale -- using the - // wrapped player's duration here would surface the old track's - // length under the new track's title. - if (localMs > 0 && controllerIdx == desiredIdx) return localMs - val ref = queueRefs.getOrNull(desiredIdx) ?: return 0 - return ref.durationSec.toLong() * MS_PER_SECOND - } + /** + * Event-driven primary path: clear pending the moment Sonos's reported + * Track matches the wrapped player's index. Safety fallback: clear on + * deadline so we don't ignore Sonos's actual state forever if SOAP fails. + */ + private fun resolvePendingTransport( + controller: MediaController, + upnpActive: Boolean, + ) { + if (!upnpActive || remoteState.pendingTransportDeadlineMs <= 0L) return + val sonosIdx = (remoteState.trackNumber - 1).coerceAtLeast(0) + val timedOut = SystemClock.elapsedRealtime() > remoteState.pendingTransportDeadlineMs + if (sonosIdx == controller.currentMediaItemIndex || timedOut) { + remoteState.clearPendingTransport() + } + } - companion object { - const val MINSTREL_SOURCE_KEY: String = "minstrel_source" - private const val MS_PER_SECOND = 1_000L - private const val MAX_INTERPOLATION_DRIFT_MS = 5_000L - private const val GAIN_PREFETCH = 20 + // ── Remote position interpolation state ────────────────────────────── + // remoteState.positionMs is only refreshed by ForwardingPlayer's 1Hz + // SOAP poll (and only when the round-trip completes -- screen-off WiFi + // sleep can stall it for many seconds). To keep the scrubber moving + // smoothly we anchor each fresh reading + an elapsed-realtime stamp; + // between updates we display anchor + elapsed when Sonos is playing. + // A real correction lands as soon as the next poll arrives. + @Volatile private var lastSeenRemotePositionMs: Long = -1L + + @Volatile private var positionAnchorMs: Long = 0L + + @Volatile private var positionAnchorAtRealtimeMs: Long = 0L + + private fun interpolatedRemotePosition(isPlaying: Boolean): Long { + val raw = remoteState.positionMs + val now = SystemClock.elapsedRealtime() + if (raw != lastSeenRemotePositionMs) { + lastSeenRemotePositionMs = raw + positionAnchorMs = raw + positionAnchorAtRealtimeMs = now + } + if (!isPlaying) return positionAnchorMs + // Cap how far past the last anchor we extrapolate. After + // MAX_INTERPOLATION_DRIFT_MS without a poll update, freeze the + // displayed position at anchor + cap rather than projecting wildly. + // The next successful poll re-anchors and motion resumes. + val delta = (now - positionAnchorAtRealtimeMs).coerceAtMost(MAX_INTERPOLATION_DRIFT_MS) + return positionAnchorMs + delta + } + + /** + * Bridges Media3's `ListenableFuture.buildAsync()` + * to a suspend function without pulling in `kotlinx-coroutines-guava` + * — the future's `addListener` callback is enough. `Runnable::run` + * is a direct executor (no extra threading) since the callback only + * unparks our continuation. + */ + private suspend fun connectController(): MediaController = + suspendCancellableCoroutine { cont -> + val future = MediaController.Builder(context, sessionToken).buildAsync() + future.addListener( + { + try { + cont.resume(future.get()) + } catch ( + // ListenableFuture.get() throws ExecutionException + + // InterruptedException + CancellationException — handle + // them uniformly by forwarding to the continuation; + // the caller catches at the outer boundary. + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + cont.resumeWithException(e) + } + }, + Runnable::run, + ) + cont.invokeOnCancellation { future.cancel(false) } // mayInterruptIfRunning + } + + private fun TrackRef.toMediaItem(source: String?): MediaItem { + val metadata = + MediaMetadata + .Builder() + .setTitle(title) + .setArtist(artistName) + .setAlbumTitle(albumTitle) + .apply { + // Server-known duration -- gives the lock-screen / notification + // scrubber a real total even when the wrapped ExoPlayer is + // paused under UPnP (it never probes a duration in that state). + if (durationSec > 0) setDurationMs(durationSec.toLong() * MS_PER_SECOND) + // Album and track position let the gain processor tell an + // album played in order from a mix. + trackNumber?.let { setTrackNumber(it) } + discNumber?.let { setDiscNumber(it) } + val extras = GainAudioProcessor.albumExtras(albumId) + if (source != null) extras.putAll(sourceExtras(source)) + setExtras(extras) + // Point the notification / lock-screen art at the SAME album + // cover the in-app surfaces use (TrackRef.coverUrl -> + // /api/albums/{id}/cover). Without this, Media3 falls back to + // whatever art is embedded in the stream's tags, which can be a + // different image than the server's album cover. Setting + // artworkUri here is load-bearing: MediaMetadata.populate() + // overwrites artworkUri + artworkData as a pair, so the + // MediaItem's URI clears any embedded artworkData ExoPlayer + // extracts from the stream -- the cover endpoint wins on both + // surfaces. The session's OkHttp-backed BitmapLoader (see + // PlayerFactory) is what makes this authed placeholder URL load. + if (coverUrl.isNotEmpty()) setArtworkUri(coverUrl.toUri()) + }.build() + // Server's stream_url is a relative path (/api/tracks/{id}/stream); + // resolve to the placeholder.invalid form so OkHttpDataSource (sharing + // BaseUrlInterceptor) rewrites it to the live server with the auth + // cookie. Same resolver as covers — one place for /api/* URLs. + val resolvedUri = resolveServerUrl(streamUrl) ?: streamUrl + return MediaItem + .Builder() + .setMediaId(id) + .setUri(resolvedUri) + // Key the Media3 SimpleCache by trackId (not the stream URL) so + // cache residency can be queried per track for the cached dot + + // offline pools, independent of URL/host rewrites. + .setCustomCacheKey(id) + .setMediaMetadata(metadata) + .build() + } + + private fun sourceExtras(source: String): Bundle = Bundle().apply { putString(MINSTREL_SOURCE_KEY, source) } + + /** + * Duration to surface to the UI. Priority: Sonos's reported duration + * (only when UPnP active and non-zero) -> wrapped ExoPlayer's value + * (only valid once it's probed the stream) -> TrackRef.durationSec + * (always known from the server response). The third tier is what + * keeps the scrubber populated when the user taps Sonos before the + * wrapped player has had time to probe its own duration -- without + * it, both top tiers report 0/TIME_UNSET and the field reads empty + * until the first SOAP poll lands. + */ + @Suppress("ReturnCount") // 3-tier fallback reads cleanest as a ladder of early returns + private fun effectiveDuration( + upnpActive: Boolean, + remoteMs: Long, + localMs: Long, + desiredIdx: Int, + controllerIdx: Int, + ): Long { + if (upnpActive && remoteMs > 0) return remoteMs + // Tier 2 (wrapped player's probed duration) only valid when the + // wrapped player is on the same track we're trying to show. After a + // Sonos natural advance the polling tick updates desiredIdx from + // Sonos's truth while controllerIdx is briefly stale -- using the + // wrapped player's duration here would surface the old track's + // length under the new track's title. + if (localMs > 0 && controllerIdx == desiredIdx) return localMs + val ref = queueRefs.getOrNull(desiredIdx) ?: return 0 + return ref.durationSec.toLong() * MS_PER_SECOND + } + + companion object { + const val MINSTREL_SOURCE_KEY: String = "minstrel_source" + private const val MS_PER_SECOND = 1_000L + private const val MAX_INTERPOLATION_DRIFT_MS = 5_000L + private const val GAIN_PREFETCH = 20 + } } -} // 500ms: smooth-enough on a slider without being battery-hostile. // Lock-screen / notification surfaces are driven by Media3's @@ -935,7 +988,10 @@ data class PlaybackErrorEvent( * A queue with the server-missing tracks removed, and the caller's starting * index moved to match. */ -data class PlayableQueue(val tracks: List, val initialIndex: Int) +data class PlayableQueue( + val tracks: List, + val initialIndex: Int, +) /** * Drop tracks the server has no file for, keeping [initialIndex] pointing at @@ -953,7 +1009,10 @@ data class PlayableQueue(val tracks: List, val initialIndex: Int) * stale list turned out to be entirely missing would be worse than ignoring * the request. */ -fun dropUnavailable(tracks: List, initialIndex: Int): PlayableQueue { +fun dropUnavailable( + tracks: List, + initialIndex: Int, +): PlayableQueue { if (tracks.none { it.unavailable }) return PlayableQueue(tracks, initialIndex) val kept = ArrayList(tracks.size) var newIndex = 0 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerFactory.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerFactory.kt index 680f9a46..588535ae 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerFactory.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerFactory.kt @@ -53,175 +53,195 @@ import javax.inject.Singleton * tear-down surfaces as one event rather than queueing N. */ @Singleton -class PlayerFactory @Inject constructor( - @ApplicationContext private val context: Context, - private val okHttpClient: OkHttpClient, - private val cacheEvictor: TwoBucketCacheEvictor, - private val activeUpnpHolder: ActiveUpnpHolder, - private val remoteState: RemotePlayerState, - private val serverHealth: com.fabledsword.minstrel.connectivity.NetworkStatusController, - private val authStore: AuthStore, - private val replayGains: ReplayGainStore, - private val sonosQueue: SonosQueueLoader, - private val singleTrack: SingleTrackLoader, -) { - private val cacheDir: File = File(context.cacheDir, "audio_cache").apply { mkdirs() } +class PlayerFactory + @Inject + constructor( + @ApplicationContext private val context: Context, + private val okHttpClient: OkHttpClient, + private val cacheEvictor: TwoBucketCacheEvictor, + private val activeUpnpHolder: ActiveUpnpHolder, + private val remoteState: RemotePlayerState, + private val serverHealth: com.fabledsword.minstrel.connectivity.NetworkStatusController, + private val authStore: AuthStore, + private val replayGains: ReplayGainStore, + private val sonosQueue: SonosQueueLoader, + private val singleTrack: SingleTrackLoader, + ) { + private val cacheDir: File = File(context.cacheDir, "audio_cache").apply { mkdirs() } - val simpleCache: SimpleCache = SimpleCache( - cacheDir, - cacheEvictor, - StandaloneDatabaseProvider(context), - ).also(cacheEvictor::attach) + val simpleCache: SimpleCache = + SimpleCache( + cacheDir, + cacheEvictor, + StandaloneDatabaseProvider(context), + ).also(cacheEvictor::attach) - // MutableSharedFlow with extraBufferCapacity=1 + DROP_OLDEST so a burst - // of drop events (rapid SOAP failures during a single tear-down) surfaces - // as one snackbar rather than queueing N. - private val dropEventsInternal = MutableSharedFlow( - replay = 0, - extraBufferCapacity = 1, - onBufferOverflow = BufferOverflow.DROP_OLDEST, - ) - val dropEvents: SharedFlow = dropEventsInternal.asSharedFlow() - - // Track ids whose remote playback stalled and could not be resumed. Same - // buffering rationale as dropEvents: a burst is one problem, not N. - private val stallEventsInternal = MutableSharedFlow( - replay = 0, - extraBufferCapacity = 1, - onBufferOverflow = BufferOverflow.DROP_OLDEST, - ) - val stallEvents: SharedFlow = stallEventsInternal.asSharedFlow() - - // Fires when the renderer is found to have reached the end of a queue - // shorter than ours -- i.e. part of the queue load never landed. The - // controller owns queue loading, so it collects this and rebuilds. - // Same one-is-enough buffering: repeated notices are the same problem. - private val queueRepairInternal = MutableSharedFlow( - replay = 0, - extraBufferCapacity = 1, - onBufferOverflow = BufferOverflow.DROP_OLDEST, - ) - val queueRepairEvents: SharedFlow = queueRepairInternal.asSharedFlow() - - // Raw renderer transport readings, change-gated. Unlike the flows above - // this one carries a SEQUENCE — the diagnostics flap detector needs - // several readings in a row to tell oscillation from a normal track - // transition — so it buffers more than one and drops oldest under - // pressure rather than collapsing to the latest. - private val transportInternal = MutableSharedFlow( - replay = 0, - extraBufferCapacity = TRANSPORT_EVENT_BUFFER, - onBufferOverflow = BufferOverflow.DROP_OLDEST, - ) - val transportEvents: SharedFlow = transportInternal.asSharedFlow() - - fun build(): Player { - val exo = buildExoPlayer() - return MinstrelForwardingPlayer( - delegate = exo, - holder = activeUpnpHolder, - remoteState = remoteState, - castNetworkLock = CastNetworkLock(context), - networkStatus = serverHealth, - singleTrack = singleTrack, - events = MinstrelForwardingPlayer.RemoteEvents( - onDrop = { name -> emitDrop(name) }, - onStalled = { trackId -> stallEventsInternal.tryEmit(trackId) }, - onQueueTruncated = { queueRepairInternal.tryEmit(Unit) }, - onTransport = { transportInternal.tryEmit(it) }, - onRendererTrack = { sonosQueue.onRendererTrack(it) }, - ), - ) - } - - private fun buildExoPlayer(): ExoPlayer { - val httpDataSource = OkHttpDataSource.Factory(okHttpClient) - // Gate network reads on ServerHealth so a cache miss while offline - // fails fast with an OfflineException instead of hitting an OkHttp - // timeout. CacheDataSource only consults the upstream factory on a - // cache miss, so playback of cached audio is unaffected. - val gatedUpstream = OfflineGatedDataSourceFactory(httpDataSource, serverHealth) - val cacheDataSource = CacheDataSource.Factory() - .setCache(simpleCache) - .setUpstreamDataSourceFactory(gatedUpstream) - .setCacheWriteDataSinkFactory( - CacheDataSink.Factory() - .setCache(simpleCache) - .setFragmentSize(C.LENGTH_UNSET.toLong()), + // MutableSharedFlow with extraBufferCapacity=1 + DROP_OLDEST so a burst + // of drop events (rapid SOAP failures during a single tear-down) surfaces + // as one snackbar rather than queueing N. + private val dropEventsInternal = + MutableSharedFlow( + replay = 0, + extraBufferCapacity = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST, ) - val mediaSourceFactory = DefaultMediaSourceFactory(context) - .setDataSourceFactory(cacheDataSource) + val dropEvents: SharedFlow = dropEventsInternal.asSharedFlow() - // Loudness normalization runs inside the audio sink so - // each track's gain starts on its first sample. Audio offload would - // bypass the sink's processors; ExoPlayer leaves it off unless asked - // (TrackSelectionParameters.audioOffloadPreferences), and nothing here - // asks, so leveling always applies. - val gainProcessor = GainAudioProcessor( - prefs = { authStore.normalization.value }, - store = replayGains, - ) - val renderersFactory = object : DefaultRenderersFactory(context) { - override fun buildAudioSink( - context: Context, - enableFloatOutput: Boolean, - enableAudioOutputPlaybackParams: Boolean, - ): AudioSink = DefaultAudioSink.Builder(context) - .setEnableFloatOutput(enableFloatOutput) - .setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams) - .setAudioProcessors(arrayOf(gainProcessor)) - .build() + // Track ids whose remote playback stalled and could not be resumed. Same + // buffering rationale as dropEvents: a burst is one problem, not N. + private val stallEventsInternal = + MutableSharedFlow( + replay = 0, + extraBufferCapacity = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + val stallEvents: SharedFlow = stallEventsInternal.asSharedFlow() + + // Fires when the renderer is found to have reached the end of a queue + // shorter than ours -- i.e. part of the queue load never landed. The + // controller owns queue loading, so it collects this and rebuilds. + // Same one-is-enough buffering: repeated notices are the same problem. + private val queueRepairInternal = + MutableSharedFlow( + replay = 0, + extraBufferCapacity = 1, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + val queueRepairEvents: SharedFlow = queueRepairInternal.asSharedFlow() + + // Raw renderer transport readings, change-gated. Unlike the flows above + // this one carries a SEQUENCE — the diagnostics flap detector needs + // several readings in a row to tell oscillation from a normal track + // transition — so it buffers more than one and drops oldest under + // pressure rather than collapsing to the latest. + private val transportInternal = + MutableSharedFlow( + replay = 0, + extraBufferCapacity = TRANSPORT_EVENT_BUFFER, + onBufferOverflow = BufferOverflow.DROP_OLDEST, + ) + val transportEvents: SharedFlow = transportInternal.asSharedFlow() + + fun build(): Player { + val exo = buildExoPlayer() + return MinstrelForwardingPlayer( + delegate = exo, + holder = activeUpnpHolder, + remoteState = remoteState, + castNetworkLock = CastNetworkLock(context), + networkStatus = serverHealth, + singleTrack = singleTrack, + events = + MinstrelForwardingPlayer.RemoteEvents( + onDrop = { name -> emitDrop(name) }, + onStalled = { trackId -> stallEventsInternal.tryEmit(trackId) }, + onQueueTruncated = { queueRepairInternal.tryEmit(Unit) }, + onTransport = { transportInternal.tryEmit(it) }, + onRendererTrack = { sonosQueue.onRendererTrack(it) }, + ), + ) } - val exo = ExoPlayer.Builder(context, renderersFactory) - .setMediaSourceFactory(mediaSourceFactory) - .setAudioAttributes( - AudioAttributes.Builder() - .setUsage(C.USAGE_MEDIA) - .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC) - .build(), - /* handleAudioFocus = */ true, - ) - .setHandleAudioBecomingNoisy(true) - .build() - // The processor finds a track's neighbours in play order, which - // depends on shuffle mode. - gainProcessor.shuffleEnabled = exo.shuffleModeEnabled - exo.addListener( - object : Player.Listener { - override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) { - gainProcessor.shuffleEnabled = shuffleModeEnabled + private fun buildExoPlayer(): ExoPlayer { + val httpDataSource = OkHttpDataSource.Factory(okHttpClient) + // Gate network reads on ServerHealth so a cache miss while offline + // fails fast with an OfflineException instead of hitting an OkHttp + // timeout. CacheDataSource only consults the upstream factory on a + // cache miss, so playback of cached audio is unaffected. + val gatedUpstream = OfflineGatedDataSourceFactory(httpDataSource, serverHealth) + val cacheDataSource = + CacheDataSource + .Factory() + .setCache(simpleCache) + .setUpstreamDataSourceFactory(gatedUpstream) + .setCacheWriteDataSinkFactory( + CacheDataSink + .Factory() + .setCache(simpleCache) + .setFragmentSize(C.LENGTH_UNSET.toLong()), + ) + val mediaSourceFactory = + DefaultMediaSourceFactory(context) + .setDataSourceFactory(cacheDataSource) + + // Loudness normalization runs inside the audio sink so + // each track's gain starts on its first sample. Audio offload would + // bypass the sink's processors; ExoPlayer leaves it off unless asked + // (TrackSelectionParameters.audioOffloadPreferences), and nothing here + // asks, so leveling always applies. + val gainProcessor = + GainAudioProcessor( + prefs = { authStore.normalization.value }, + store = replayGains, + ) + val renderersFactory = + object : DefaultRenderersFactory(context) { + override fun buildAudioSink( + context: Context, + enableFloatOutput: Boolean, + enableAudioOutputPlaybackParams: Boolean, + ): AudioSink = + DefaultAudioSink + .Builder(context) + .setEnableFloatOutput(enableFloatOutput) + .setEnableAudioOutputPlaybackParameters(enableAudioOutputPlaybackParams) + .setAudioProcessors(arrayOf(gainProcessor)) + .build() } - }, - ) - return exo - } - /** - * BitmapLoader for the MediaSession's notification / lock-screen art. - * Backed by the shared [okHttpClient] so it inherits the same - * BaseUrlInterceptor placeholder rewrite + auth cookie that Coil uses - * for in-app covers — without it the default DefaultHttpDataSource - * loader can't resolve `http://placeholder.invalid/...` and would 401 - * on the cover endpoint. Wrapped in CacheBitmapLoader so a cover the - * notification already fetched isn't re-loaded on every metadata - * refresh. Lets the album-cover artworkUri set in - * [PlayerController.toMediaItem] actually render on the media card. - */ - fun buildBitmapLoader(): BitmapLoader = - CacheBitmapLoader( - DataSourceBitmapLoader.Builder(context) - .setDataSourceFactory(OkHttpDataSource.Factory(okHttpClient)) - .build(), - ) + val exo = + ExoPlayer + .Builder(context, renderersFactory) + .setMediaSourceFactory(mediaSourceFactory) + .setAudioAttributes( + AudioAttributes + .Builder() + .setUsage(C.USAGE_MEDIA) + .setContentType(C.AUDIO_CONTENT_TYPE_MUSIC) + .build(), + // handleAudioFocus = + true, + ).setHandleAudioBecomingNoisy(true) + .build() + // The processor finds a track's neighbours in play order, which + // depends on shuffle mode. + gainProcessor.shuffleEnabled = exo.shuffleModeEnabled + exo.addListener( + object : Player.Listener { + override fun onShuffleModeEnabledChanged(shuffleModeEnabled: Boolean) { + gainProcessor.shuffleEnabled = shuffleModeEnabled + } + }, + ) + return exo + } - private companion object { - // Enough readings to hold a whole flap episode plus the normal - // transitions around it; the detector's window is only a few seconds. - const val TRANSPORT_EVENT_BUFFER = 32 - } + /** + * BitmapLoader for the MediaSession's notification / lock-screen art. + * Backed by the shared [okHttpClient] so it inherits the same + * BaseUrlInterceptor placeholder rewrite + auth cookie that Coil uses + * for in-app covers — without it the default DefaultHttpDataSource + * loader can't resolve `http://placeholder.invalid/...` and would 401 + * on the cover endpoint. Wrapped in CacheBitmapLoader so a cover the + * notification already fetched isn't re-loaded on every metadata + * refresh. Lets the album-cover artworkUri set in + * [PlayerController.toMediaItem] actually render on the media card. + */ + fun buildBitmapLoader(): BitmapLoader = + CacheBitmapLoader( + DataSourceBitmapLoader + .Builder(context) + .setDataSourceFactory(OkHttpDataSource.Factory(okHttpClient)) + .build(), + ) - private fun emitDrop(routeName: String) { - dropEventsInternal.tryEmit(routeName) + private companion object { + // Enough readings to hold a whole flap episode plus the normal + // transitions around it; the detector's window is only a few seconds. + const val TRANSPORT_EVENT_BUFFER = 32 + } + + private fun emitDrop(routeName: String) { + dropEventsInternal.tryEmit(routeName) + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerUiState.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerUiState.kt index db0fe1ed..137e1d5d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerUiState.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/PlayerUiState.kt @@ -61,5 +61,7 @@ data class PlayerUiState( const val RESTART_THRESHOLD_MS = 3_000L /** Previous restarts the song once it is [RESTART_THRESHOLD_MS] in, or when nothing comes before it. */ -fun previousRestarts(positionMs: Long, hasPrevious: Boolean): Boolean = - positionMs >= RESTART_THRESHOLD_MS || !hasPrevious +fun previousRestarts( + positionMs: Long, + hasPrevious: Boolean, +): Boolean = positionMs >= RESTART_THRESHOLD_MS || !hasPrevious diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/RadioController.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/RadioController.kt index a146dc16..3ff98f4b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/RadioController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/RadioController.kt @@ -19,15 +19,18 @@ import javax.inject.Singleton * inject the shared `Retrofit` and call `.create()` themselves. */ @Singleton -class RadioController @Inject constructor(retrofit: Retrofit) { - private val api: RadioApi = retrofit.create() +class RadioController + @Inject + constructor( + retrofit: Retrofit, + ) { + private val api: RadioApi = retrofit.create() - /** - * Calls `GET /api/radio?seed_track=` and maps the - * response into domain TrackRefs. Returns an empty list on a - * 2xx-but-empty server response; throws on any transport or - * non-2xx status (caller surfaces the error). - */ - suspend fun seed(trackId: String): List = - api.seedTrack(trackId).tracks.map { it.toDomain() } -} + /** + * Calls `GET /api/radio?seed_track=` and maps the + * response into domain TrackRefs. Returns an empty list on a + * 2xx-but-empty server response; throws on any transport or + * non-2xx status (caller surfaces the error). + */ + suspend fun seed(trackId: String): List = api.seedTrack(trackId).tracks.map { it.toDomain() } + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/RemotePlayerState.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/RemotePlayerState.kt index 4d750586..1f1c8cdd 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/RemotePlayerState.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/RemotePlayerState.kt @@ -20,91 +20,120 @@ import javax.inject.Singleton * otherwise defer to this counter (see MinstrelForwardingPlayer). */ @Singleton -class RemotePlayerState @Inject constructor() { +class RemotePlayerState + @Inject + constructor() { + @Volatile var positionMs: Long = 0L + private set - @Volatile var positionMs: Long = 0L; private set - @Volatile var durationMs: Long = 0L; private set - @Volatile var isPlaying: Boolean = false; private set - @Volatile var currentTrackUri: String = ""; private set - @Volatile var lastError: Throwable? = null; private set - @Volatile var trackNumber: Int = 0; private set + @Volatile var durationMs: Long = 0L + private set - // The user's last explicit transport intent (play=true, pause=false), - // distinct from the observed remote isPlaying. handleRemoteDrop resumes - // local playback based on THIS, not isPlaying -- so a play() that fails - // its SOAP (stale/dead renderer) still resumes on the phone instead of - // swallowing the tap. Deliberately NOT cleared by applyError. - @Volatile var lastPlayIntent: Boolean = false; private set + @Volatile var isPlaying: Boolean = false + private set - // Pending-transport deadline (SystemClock.elapsedRealtime() at which we - // give up waiting). When > 0, a user transport action (next/prev/seekTo - // idx) is in flight: ForwardingPlayer has already moved the wrapped - // player's index, but Sonos's reported Track hasn't refreshed via a - // SOAP poll yet. PlayerController.tickPositionPoll skips track - // adjustments while pending is non-zero. Pending clears when: - // (a) [event-driven, primary] a poll lands and Sonos's reported Track - // matches the wrapped player's currentMediaItemIndex; or - // (b) [safety fallback] the deadline expires (covers SOAP-fail cases - // where Sonos never acks). - @Volatile var pendingTransportDeadlineMs: Long = 0L; private set + @Volatile var currentTrackUri: String = "" + private set - fun beginPendingTransport(deadlineMs: Long) { - pendingTransportDeadlineMs = deadlineMs + @Volatile var lastError: Throwable? = null + private set + + @Volatile var trackNumber: Int = 0 + private set + + // The user's last explicit transport intent (play=true, pause=false), + // distinct from the observed remote isPlaying. handleRemoteDrop resumes + // local playback based on THIS, not isPlaying -- so a play() that fails + // its SOAP (stale/dead renderer) still resumes on the phone instead of + // swallowing the tap. Deliberately NOT cleared by applyError. + @Volatile var lastPlayIntent: Boolean = false + private set + + // Pending-transport deadline (SystemClock.elapsedRealtime() at which we + // give up waiting). When > 0, a user transport action (next/prev/seekTo + // idx) is in flight: ForwardingPlayer has already moved the wrapped + // player's index, but Sonos's reported Track hasn't refreshed via a + // SOAP poll yet. PlayerController.tickPositionPoll skips track + // adjustments while pending is non-zero. Pending clears when: + // (a) [event-driven, primary] a poll lands and Sonos's reported Track + // matches the wrapped player's currentMediaItemIndex; or + // (b) [safety fallback] the deadline expires (covers SOAP-fail cases + // where Sonos never acks). + @Volatile var pendingTransportDeadlineMs: Long = 0L + private set + + fun beginPendingTransport(deadlineMs: Long) { + pendingTransportDeadlineMs = deadlineMs + } + + fun clearPendingTransport() { + pendingTransportDeadlineMs = 0L + } + + @Volatile private var consecutivePollFailures: Int = 0 + + fun applyPositionInfo( + positionMs: Long, + durationMs: Long, + trackUri: String, + trackNumber: Int, + ) { + this.positionMs = positionMs + this.durationMs = durationMs + this.currentTrackUri = trackUri + this.trackNumber = trackNumber + } + + fun applyTransportPlaying() { + isPlaying = true + } + + fun applyTransportPaused() { + isPlaying = false + } + + fun applyTransportStopped() { + isPlaying = false + positionMs = 0L + } + + fun setPlayIntent(intended: Boolean) { + lastPlayIntent = intended + } + + fun applyError(t: Throwable) { + isPlaying = false + lastError = t + } + + /** Returns true when the rolling threshold trips this call. */ + fun recordPollFailure(): Boolean { + consecutivePollFailures += 1 + return consecutivePollFailures >= DROP_THRESHOLD + } + + fun recordPollSuccess() { + consecutivePollFailures = 0 + } + + fun reset() { + positionMs = 0L + durationMs = 0L + isPlaying = false + lastPlayIntent = false + currentTrackUri = "" + lastError = null + consecutivePollFailures = 0 + trackNumber = 0 + pendingTransportDeadlineMs = 0L + } + + private companion object { + // ~30 seconds of consecutive poll failures before declaring the route + // dropped. Bumped from 3 because screen-off WiFi sleep / brief Doze + // can stall socket I/O for several seconds without the renderer + // actually being unreachable -- a 3-failure drop kicked us back to + // local audio every time the phone went into a pocket. + const val DROP_THRESHOLD = 30 + } } - - fun clearPendingTransport() { - pendingTransportDeadlineMs = 0L - } - - @Volatile private var consecutivePollFailures: Int = 0 - - fun applyPositionInfo(positionMs: Long, durationMs: Long, trackUri: String, trackNumber: Int) { - this.positionMs = positionMs - this.durationMs = durationMs - this.currentTrackUri = trackUri - this.trackNumber = trackNumber - } - - fun applyTransportPlaying() { isPlaying = true } - fun applyTransportPaused() { isPlaying = false } - fun applyTransportStopped() { - isPlaying = false - positionMs = 0L - } - - fun setPlayIntent(intended: Boolean) { lastPlayIntent = intended } - - fun applyError(t: Throwable) { - isPlaying = false - lastError = t - } - - /** Returns true when the rolling threshold trips this call. */ - fun recordPollFailure(): Boolean { - consecutivePollFailures += 1 - return consecutivePollFailures >= DROP_THRESHOLD - } - - fun recordPollSuccess() { consecutivePollFailures = 0 } - - fun reset() { - positionMs = 0L - durationMs = 0L - isPlaying = false - lastPlayIntent = false - currentTrackUri = "" - lastError = null - consecutivePollFailures = 0 - trackNumber = 0 - pendingTransportDeadlineMs = 0L - } - - private companion object { - // ~30 seconds of consecutive poll failures before declaring the route - // dropped. Bumped from 3 because screen-off WiFi sleep / brief Doze - // can stall socket I/O for several seconds without the renderer - // actually being unreachable -- a 3-failure drop kicked us back to - // local audio every time the phone went into a pocket. - const val DROP_THRESHOLD = 30 - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/RemoteStallWatchdog.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/RemoteStallWatchdog.kt index f670c876..36d21173 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/RemoteStallWatchdog.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/RemoteStallWatchdog.kt @@ -49,7 +49,6 @@ import com.fabledsword.minstrel.player.output.upnp.TransportState * without a renderer. */ class RemoteStallWatchdog { - /** * What the renderer's queue looks like relative to ours, as of this poll. * The caller derives it from GetMediaInfo's NrTracks against the local @@ -99,7 +98,10 @@ class RemoteStallWatchdog { * observed while it was actually playing, so the caller can seek back * to roughly where the listener was rather than restarting the track. */ - data class Resume(val attempt: Int, val resumeAtMs: Long) : Decision + data class Resume( + val attempt: Int, + val resumeAtMs: Long, + ) : Decision /** * The renderer ran off the end of a queue we failed to fully load. @@ -107,7 +109,9 @@ class RemoteStallWatchdog { * next track — re-playing the current one would just replay a track * the listener already heard. */ - data class RepairQueue(val attempt: Int) : Decision + data class RepairQueue( + val attempt: Int, + ) : Decision /** Attempts are exhausted. Report it and stop trying for this track. */ data object GiveUp : Decision diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ResumeController.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ResumeController.kt index 517dbaa1..55d9ba0a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ResumeController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ResumeController.kt @@ -28,78 +28,81 @@ import javax.inject.Singleton * if the user never opened the in-app UI this run. */ @Singleton -class ResumeController @Inject constructor( - private val playerController: PlayerController, - private val dao: CachedResumeStateDao, - private val json: Json, - @ApplicationScope private val scope: CoroutineScope, -) { - init { - scope.launch { observeAndPersist() } - } +class ResumeController + @Inject + constructor( + private val playerController: PlayerController, + private val dao: CachedResumeStateDao, + private val json: Json, + @ApplicationScope private val scope: CoroutineScope, + ) { + init { + scope.launch { observeAndPersist() } + } - suspend fun restore() { - // runCatching folds row-missing + decode-failure + empty-tracks into - // a single null-or-go-ahead expression so detekt's ReturnCount rule - // is satisfied. The .onFailure side effect drops a corrupted row - // rather than leaving a poison pill across launches. - val row = dao.get() ?: return - val payload = - runCatching { json.decodeFromString(row.json) } - .onFailure { - Timber.w(it, "ResumeController: dropping unreadable resume state") - dao.clear() - } - .getOrNull() - ?.takeIf { it.tracks.isNotEmpty() } - ?: return - // Wait for the MediaController binding before - // calling setQueue, otherwise restore() racing the IPC - // handshake silently drops the persisted queue (PlayerController - // setQueue early-returns when mediaController is null). - playerController.awaitReady() - playerController.setQueue( - tracks = payload.tracks, - initialIndex = payload.queueIndex - .coerceAtLeast(0) - .coerceAtMost(payload.tracks.lastIndex), - source = payload.source, - // Cold-boot resume must NOT auto-start - // playback. The user has been away from the app; starting - // audio on cold launch is surprising. They tap play to - // resume. Queue + position are restored; transport is idle. - autoplay = false, - ) - // PositionMs not seeked yet — Player connection may still be - // establishing; the seek call would no-op. Acceptable to start - // from 0 on resume for now; #future-polish if it bothers anyone. - } + suspend fun restore() { + // runCatching folds row-missing + decode-failure + empty-tracks into + // a single null-or-go-ahead expression so detekt's ReturnCount rule + // is satisfied. The .onFailure side effect drops a corrupted row + // rather than leaving a poison pill across launches. + val row = dao.get() ?: return + val payload = + runCatching { json.decodeFromString(row.json) } + .onFailure { + Timber.w(it, "ResumeController: dropping unreadable resume state") + dao.clear() + }.getOrNull() + ?.takeIf { it.tracks.isNotEmpty() } + ?: return + // Wait for the MediaController binding before + // calling setQueue, otherwise restore() racing the IPC + // handshake silently drops the persisted queue (PlayerController + // setQueue early-returns when mediaController is null). + playerController.awaitReady() + playerController.setQueue( + tracks = payload.tracks, + initialIndex = + payload.queueIndex + .coerceAtLeast(0) + .coerceAtMost(payload.tracks.lastIndex), + source = payload.source, + // Cold-boot resume must NOT auto-start + // playback. The user has been away from the app; starting + // audio on cold launch is surprising. They tap play to + // resume. Queue + position are restored; transport is idle. + autoplay = false, + ) + // PositionMs not seeked yet — Player connection may still be + // establishing; the seek call would no-op. Acceptable to start + // from 0 on resume for now; #future-polish if it bothers anyone. + } - private suspend fun observeAndPersist() { - playerController.uiState - // Skip the initial "empty" snapshot before anything has been played. - .drop(1) - .map { Triple(it.currentTrack?.id, it.queueIndex, it.queue.size) } - .distinctUntilChanged() - .collect { persistCurrentSnapshot() } - } + private suspend fun observeAndPersist() { + playerController.uiState + // Skip the initial "empty" snapshot before anything has been played. + .drop(1) + .map { Triple(it.currentTrack?.id, it.queueIndex, it.queue.size) } + .distinctUntilChanged() + .collect { persistCurrentSnapshot() } + } - private suspend fun persistCurrentSnapshot() { - val state = playerController.uiState.value - if (state.queue.isEmpty()) { - // Clear so an emptied queue doesn't auto-restore stale tracks. - dao.clear() - return + private suspend fun persistCurrentSnapshot() { + val state = playerController.uiState.value + if (state.queue.isEmpty()) { + // Clear so an emptied queue doesn't auto-restore stale tracks. + dao.clear() + return + } + val payload = + ResumePayload( + tracks = state.queue, + queueIndex = state.queueIndex.coerceAtLeast(0), + positionMs = state.positionMs, + ) + dao.upsert( + CachedResumeStateEntity( + json = json.encodeToString(ResumePayload.serializer(), payload), + ), + ) } - val payload = ResumePayload( - tracks = state.queue, - queueIndex = state.queueIndex.coerceAtLeast(0), - positionMs = state.positionMs, - ) - dao.upsert( - CachedResumeStateEntity( - json = json.encodeToString(ResumePayload.serializer(), payload), - ), - ) } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/StreamTokenProvider.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/StreamTokenProvider.kt index a8dbfbf9..c4d5fc3d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/StreamTokenProvider.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/StreamTokenProvider.kt @@ -16,16 +16,24 @@ import javax.inject.Singleton * Retrofit. The shared Retrofit instance is unchanged. */ @Singleton -class StreamTokenProvider @Inject constructor(retrofit: Retrofit) { - private val api: CastApi = retrofit.create() +class StreamTokenProvider + @Inject + constructor( + retrofit: Retrofit, + ) { + private val api: CastApi = retrofit.create() - /** - * Mints a URL for a speaker, leveled when the user's setting calls for - * it. The server answers with the plain stream when it does - * not, so every speaker URL asks. - */ - suspend fun mint(trackId: String, asAlbum: Boolean = false, prerender: Boolean = false): StreamTokenResponse = - api.streamToken( - StreamTokenRequest(trackId = trackId, level = true, asAlbum = asAlbum, prerender = prerender), - ) -} + /** + * Mints a URL for a speaker, leveled when the user's setting calls for + * it. The server answers with the plain stream when it does + * not, so every speaker URL asks. + */ + suspend fun mint( + trackId: String, + asAlbum: Boolean = false, + prerender: Boolean = false, + ): StreamTokenResponse = + api.streamToken( + StreamTokenRequest(trackId = trackId, level = true, asAlbum = asAlbum, prerender = prerender), + ) + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainAudioProcessor.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainAudioProcessor.kt index 1380961a..4fb0d7cb 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainAudioProcessor.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainAudioProcessor.kt @@ -35,7 +35,6 @@ class GainAudioProcessor( private val prefs: () -> NormalizationPrefs, private val store: ReplayGainStore, ) : BaseAudioProcessor() { - /** Mirrors the player's shuffle mode, so neighbours are found in play order. */ @Volatile var shuffleEnabled: Boolean = false @@ -99,8 +98,9 @@ class GainAudioProcessor( val timeline = meta.timeline val index = timeline.getPeriodByUid(uid, Timeline.Period()).windowIndex val window = Timeline.Window() - fun itemAt(i: Int): MediaItem? = - if (i == C.INDEX_UNSET) null else timeline.getWindow(i, window).mediaItem + + fun itemAt(i: Int): MediaItem? = if (i == C.INDEX_UNSET) null else timeline.getWindow(i, window).mediaItem + fun nextOf(i: Int) = timeline.getNextWindowIndex(i, Player.REPEAT_MODE_OFF, shuffleEnabled) val cur = itemAt(index) @@ -127,13 +127,16 @@ class GainAudioProcessor( private const val LOOKAHEAD = 20 /** Puts what [albumPosition] reads into a MediaItem's metadata extras. */ - fun albumExtras(albumId: String, into: Bundle = Bundle()): Bundle = - into.apply { putString(EXTRA_ALBUM_ID, albumId) } + fun albumExtras( + albumId: String, + into: Bundle = Bundle(), + ): Bundle = into.apply { putString(EXTRA_ALBUM_ID, albumId) } } } -private fun MediaItem.albumPosition(): AlbumPosition = AlbumPosition( - albumId = mediaMetadata.extras?.getString(GainAudioProcessor.EXTRA_ALBUM_ID), - discNumber = mediaMetadata.discNumber, - trackNumber = mediaMetadata.trackNumber, -) +private fun MediaItem.albumPosition(): AlbumPosition = + AlbumPosition( + albumId = mediaMetadata.extras?.getString(GainAudioProcessor.EXTRA_ALBUM_ID), + discNumber = mediaMetadata.discNumber, + trackNumber = mediaMetadata.trackNumber, + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainMath.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainMath.kt index aaa6ac1e..21c9da04 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainMath.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainMath.kt @@ -24,7 +24,11 @@ data class ReplayGain( } /** Where a queue item sits in its album, for the auto-mode album rule. */ -data class AlbumPosition(val albumId: String?, val discNumber: Int?, val trackNumber: Int?) +data class AlbumPosition( + val albumId: String?, + val discNumber: Int?, + val trackNumber: Int?, +) /** * Loudness-normalization math. The same rules as the web @@ -52,10 +56,15 @@ object GainMath { * The gain to apply, in dB. 0 when leveling is off or the track has not * been measured: an unmeasured track plays as mastered. */ - fun gainDb(prefs: NormalizationPrefs, g: ReplayGain?, asAlbum: Boolean): Float { + fun gainDb( + prefs: NormalizationPrefs, + g: ReplayGain?, + asAlbum: Boolean, + ): Float { if (prefs.mode == NormalizationMode.OFF || g == null) return 0f - val wantAlbum = prefs.mode == NormalizationMode.ALBUM || - (prefs.mode == NormalizationMode.AUTO && asAlbum) + val wantAlbum = + prefs.mode == NormalizationMode.ALBUM || + (prefs.mode == NormalizationMode.AUTO && asAlbum) // Album gain falls back to track gain while the album is still being // measured; track gain never falls back to album gain. val useAlbum = wantAlbum && g.albumGain != null @@ -64,7 +73,11 @@ object GainMath { return gain?.let { leveled(prefs, it, peak) } ?: 0f } - private fun leveled(prefs: NormalizationPrefs, gain: Float, peak: Float?): Float { + private fun leveled( + prefs: NormalizationPrefs, + gain: Float, + peak: Float?, + ): Float { var db = gain + (prefs.targetLufs - REFERENCE_LUFS) if (prefs.boost == NormalizationBoost.HEADROOM && peak != null && peak > 0f) { db = min(db, PEAK_CEILING_DBTP - DB_PER_DECADE * log10(peak)) @@ -79,7 +92,11 @@ object GainMath { * dynamics (a quiet intro stays quiet); anywhere else track gain levels * the mix. */ - fun playingAsAlbum(prev: AlbumPosition?, cur: AlbumPosition, next: AlbumPosition?): Boolean { + fun playingAsAlbum( + prev: AlbumPosition?, + cur: AlbumPosition, + next: AlbumPosition?, + ): Boolean { val curOrder = order(cur) if (cur.albumId == null || curOrder == null) return false val prevOrder = prev?.takeIf { it.albumId == cur.albumId }?.let { order(it) } @@ -89,8 +106,7 @@ object GainMath { // Disc-major track order. A track with no number has no place in the // order and is never evidence of album play. - private fun order(p: AlbumPosition): Int? = - p.trackNumber?.let { (p.discNumber ?: 1) * DISC_STRIDE + it } + private fun order(p: AlbumPosition): Int? = p.trackNumber?.let { (p.discNumber ?: 1) * DISC_STRIDE + it } fun dbToLinear(db: Float): Float = 10f.pow(db / DB_PER_DECADE) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainStage.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainStage.kt index d8d40c12..7c97e800 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainStage.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/gain/GainStage.kt @@ -20,7 +20,11 @@ internal class GainStage { private var frame = FloatArray(2) /** Sets the sample rate and channel count, and starts the gain at [startGain]. */ - fun reset(sampleRate: Int, channels: Int, startGain: Float) { + fun reset( + sampleRate: Int, + channels: Int, + startGain: Float, + ) { val rate = sampleRate.coerceAtLeast(1).toFloat() rampCoeff = 1f - exp(-1f / (RAMP_SECONDS * rate)) releaseCoeff = exp(-1f / (RELEASE_SECONDS * rate)) @@ -30,7 +34,10 @@ internal class GainStage { } /** True when processing would copy the input unchanged. */ - fun isUnity(target: Float, limiting: Boolean): Boolean = gain == 1f && target == 1f && !limiting + fun isUnity( + target: Float, + limiting: Boolean, + ): Boolean = gain == 1f && target == 1f && !limiting /** * Processes every whole frame of [input] into [out]. A trailing partial diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/gain/ReplayGainStore.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/gain/ReplayGainStore.kt index b1bff0fb..8ffe7ab8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/gain/ReplayGainStore.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/gain/ReplayGainStore.kt @@ -37,7 +37,8 @@ class ReplayGainStore internal constructor( private val serverHealth: () -> ServerHealth, private val clock: () -> Long, ) { - @Inject constructor( + @Inject + constructor( @ApplicationScope scope: CoroutineScope, trackDao: CachedTrackDao, retrofit: Retrofit, @@ -63,11 +64,12 @@ class ReplayGainStore internal constructor( /** Starts loading gains for any of [trackIds] not already known or loading. */ fun request(trackIds: Collection) { val now = clock() - val wanted = trackIds.filter { id -> - !gains.containsKey(id) && - (missedAt[id]?.let { now - it > MISS_RETRY_MS } ?: true) && - inflight.add(id) - } + val wanted = + trackIds.filter { id -> + !gains.containsKey(id) && + (missedAt[id]?.let { now - it > MISS_RETRY_MS } ?: true) && + inflight.add(id) + } if (wanted.isEmpty()) return scope.launch { try { @@ -90,16 +92,17 @@ class ReplayGainStore internal constructor( } private suspend fun fromCache(ids: List) { - val rows = try { - trackDao.replayGains(ids) - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.w(e, "replay gain: cache read failed") - emptyList() - } + val rows = + try { + trackDao.replayGains(ids) + } catch (e: CancellationException) { + throw e + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + Timber.w(e, "replay gain: cache read failed") + emptyList() + } for (row in rows) { // A cached row without a track gain is not an answer: the server // may have measured the track since this device last synced. @@ -110,16 +113,17 @@ class ReplayGainStore internal constructor( /** Asks the server about [batch]; false when it could not be asked. */ private suspend fun fromServer(batch: List): Boolean { - val res = try { - withTimeoutOrNull(REQUEST_TIMEOUT_MS) { api.getReplayGain(batch.joinToString(",")) } - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - Timber.w(e, "replay gain: lookup failed") - null - } ?: return false + val res = + try { + withTimeoutOrNull(REQUEST_TIMEOUT_MS) { api.getReplayGain(batch.joinToString(",")) } + } catch (e: CancellationException) { + throw e + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + Timber.w(e, "replay gain: lookup failed") + null + } ?: return false val now = clock() for (id in batch) { val w = res.items[id] diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/ActiveUpnpHolder.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/ActiveUpnpHolder.kt index f09a30c8..5818505a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/ActiveUpnpHolder.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/ActiveUpnpHolder.kt @@ -39,22 +39,27 @@ enum class QueueMode { } @Singleton -class ActiveUpnpHolder @Inject constructor() { +class ActiveUpnpHolder + @Inject + constructor() { + private val internal = MutableStateFlow(null) + val active: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(null) - val active: StateFlow = internal.asStateFlow() + /** + * Pending route id during selectUpnp's queue-load window. Set when + * loadQueueOnSonos starts; cleared on completion (success or failure). + * ForwardingPlayer overrides treat (target != null && active == null) + * as "UPnP intended but SOAP not yet wired" -- drop transport commands + * silently rather than send them to a half-loaded queue. + */ + private val targetInternal = MutableStateFlow(null) + val target: StateFlow = targetInternal.asStateFlow() - /** - * Pending route id during selectUpnp's queue-load window. Set when - * loadQueueOnSonos starts; cleared on completion (success or failure). - * ForwardingPlayer overrides treat (target != null && active == null) - * as "UPnP intended but SOAP not yet wired" -- drop transport commands - * silently rather than send them to a half-loaded queue. - */ - private val targetInternal = MutableStateFlow(null) - val target: StateFlow = targetInternal.asStateFlow() + fun set(active: ActiveUpnp?) { + internal.value = active + } - fun set(active: ActiveUpnp?) { internal.value = active } - - fun setTarget(routeId: String?) { targetInternal.value = routeId } -} + fun setTarget(routeId: String?) { + targetInternal.value = routeId + } + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/DeviceChip.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/DeviceChip.kt index ebe28ca4..1f1235c3 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/DeviceChip.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/DeviceChip.kt @@ -72,13 +72,14 @@ fun DeviceChip( } } -internal fun iconFor(kind: OutputRoute.Kind): ImageVector = when (kind) { - OutputRoute.Kind.BuiltIn -> Lucide.Smartphone - OutputRoute.Kind.Wired -> Lucide.Headphones - OutputRoute.Kind.Bluetooth -> Lucide.Bluetooth - OutputRoute.Kind.Cast -> Lucide.Cast - OutputRoute.Kind.Other -> Lucide.Speaker -} +internal fun iconFor(kind: OutputRoute.Kind): ImageVector = + when (kind) { + OutputRoute.Kind.BuiltIn -> Lucide.Smartphone + OutputRoute.Kind.Wired -> Lucide.Headphones + OutputRoute.Kind.Bluetooth -> Lucide.Bluetooth + OutputRoute.Kind.Cast -> Lucide.Cast + OutputRoute.Kind.Other -> Lucide.Speaker + } private const val CHIP_ICON_DP = 16 private const val CHIP_CHEVRON_DP = 14 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/IdleRevertAction.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/IdleRevertAction.kt index 07d5f341..d6cdf3d0 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/IdleRevertAction.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/IdleRevertAction.kt @@ -14,8 +14,9 @@ internal fun idleRevertAction( upnpEngaged: Boolean, isPlaying: Boolean, armed: Boolean, -): IdleRevertAction = when { - upnpEngaged && !isPlaying -> if (armed) IdleRevertAction.IGNORE else IdleRevertAction.ARM - armed -> IdleRevertAction.CANCEL - else -> IdleRevertAction.IGNORE -} +): IdleRevertAction = + when { + upnpEngaged && !isPlaying -> if (armed) IdleRevertAction.IGNORE else IdleRevertAction.ARM + armed -> IdleRevertAction.CANCEL + else -> IdleRevertAction.IGNORE + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerController.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerController.kt index ecacb8ec..b5254bf7 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerController.kt @@ -1,4 +1,5 @@ @file:Suppress("TooManyFunctions") // 5 MediaRouter.Callback overrides inflate the count + package com.fabledsword.minstrel.player.output import android.content.Context @@ -67,733 +68,771 @@ data class RouteSnapshot( * not implemented; selecting one does nothing. */ @Singleton -class OutputPickerController @Inject constructor( - @ApplicationContext private val context: Context, - @ApplicationScope private val scope: CoroutineScope, - private val upnpDiscovery: UpnpDiscoveryController, - private val playerController: PlayerController, - private val playerFactory: PlayerFactory, - private val sonosQueue: SonosQueueLoader, - private val singleTrack: SingleTrackLoader, - private val activeUpnpHolder: ActiveUpnpHolder, - private val remoteState: RemotePlayerState, - private val okHttp: OkHttpClient, -) { - private val mediaRouter = MediaRouter.getInstance(context) - - private val selector = MediaRouteSelector.Builder() - .addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO) - .build() - - /** - * Internal projection of the live MediaRouter snapshot. Refreshed - * on every Callback event; combined downstream with UPnP routes - * into the public [routesState]. - */ - private val systemRoutesInternal = MutableStateFlow(snapshotFromRouter()) - - private val selectedUpnpRouteIdInternal = MutableStateFlow(null) - private val selectUpnpMutex = Mutex() - - val routesState: StateFlow = combine( - systemRoutesInternal, - upnpDiscovery.routes, - upnpDiscovery.sonosTopology, - selectedUpnpRouteIdInternal, - ) { sys, upnp, _, upnpSelected -> - val suppressed = upnpDiscovery.nonCoordinatorMemberUdns() - val visibleUpnp = upnp - .filter { it.id.bareUdn() !in suppressed } // suppressed set is bare UDNs - .map { OutputRoute.fromUpnpRoute(it) } - val merged = sys.available + visibleUpnp - val current = if (upnpSelected != null) { - merged.firstOrNull { it.id == upnpSelected } ?: sys.current - } else { - sys.current - } - RouteSnapshot(current = current, available = sortRoutes(merged)) - }.stateIn(scope, SharingStarted.Eagerly, systemRoutesInternal.value) - - private val callback = object : MediaRouter.Callback() { - override fun onRouteAdded(router: MediaRouter, route: MediaRouter.RouteInfo) = - refresh() - - override fun onRouteChanged(router: MediaRouter, route: MediaRouter.RouteInfo) = - refresh() - - override fun onRouteRemoved(router: MediaRouter, route: MediaRouter.RouteInfo) = - refresh() - - override fun onRouteSelected( - router: MediaRouter, - route: MediaRouter.RouteInfo, - reason: Int, - ) = refresh() - - override fun onRouteUnselected( - router: MediaRouter, - route: MediaRouter.RouteInfo, - reason: Int, - ) = refresh() - } - - // Last-synced queue identity. Used by observeQueueChangesForSonosResync - // to detect when the user has mutated the queue (full replacement, - // playNext insert, or radio-append) while UPnP is active and apply the - // minimum-incremental set of Sonos SOAP operations to bring its native - // queue back in sync. Stored as the full id list (not a join-key) so we - // can run the longest-common-prefix / common-suffix diff. - private var lastSyncedQueueIds: List? = null - - // Idle-revert timer. Armed when playback is paused/stopped on a UPnP - // route; fires revertToPhoneOnIdle after IDLE_REVERT_MS of continuous - // non-playing. Cancelled on resume, route change, or explicit disconnect. - // See idleRevertAction for the arm/cancel decision. - private var idleRevertJob: Job? = null - - init { - // Two-arg addCallback registers with no discovery flag — - // androidx.mediarouter 1.7.0's default passive behavior: - // route-list updates flow through onRouteAdded/Removed/Changed - // without forcing Bluetooth scans. (There is no - // CALLBACK_FLAG_PASSIVE_DISCOVERY constant; absent flag = passive.) - mediaRouter.addCallback(selector, callback) - // When MinstrelForwardingPlayer reports the active UPnP route has - // dropped (the poll loop's consecutive-failure threshold tripping -- - // the sole drop arbiter; a failed transport command does not drop), - // clear the UPnP selection state and fall back to local ExoPlayer at - // the last-known remote position. This mirrors selectSystem's disconnect - // path but skips the Stop SOAP since the device is already unreachable. - scope.launch { - playerFactory.dropEvents.collect { handleRemoteDrop() } - } - scope.launch { observeQueueChangesForSonosResync() } - scope.launch { observeQueueRepairRequests() } - scope.launch { observeIdleRevertWhileUpnp() } - scope.launch { observeSelectedRouteDisappearance() } - } - - /** - * Revert the UPnP selection to the phone when the selected renderer leaves - * discovery (powered off / off the LAN) while we are NOT actively casting - * to it. Without this the selection could pin to a ghost route, so a later - * "play" would target a speaker that's gone. An *active* cast is left alone - * -- its own poll loop arbitrates liveness and won't drop on a mere - * discovery gap. Routes leave discovery via [UpnpDiscoveryController]'s - * post-picker-scan prune; this reacts to the resulting routes change. - */ - private suspend fun observeSelectedRouteDisappearance() { - upnpDiscovery.routes.collect { routes -> - val selected = selectedUpnpRouteIdInternal.value - val present = routes.any { it.id == selected } - val casting = activeUpnpHolder.active.value?.routeId == selected - if (selected != null && !present && !casting) { - Timber.w( - "Output: selected UPnP route %s left discovery; reverting to phone", - selected, - ) - selectedUpnpRouteIdInternal.value = null - } - } - } - - /** - * Arm/cancel the idle-revert timer as playback state changes while a - * UPnP route is engaged. "Engaged" = active OR target set, so the brief - * selectUpnp/resync window (active momentarily null, target set) doesn't - * spuriously fire. The arm/cancel choice is the pure idleRevertAction. - */ - private suspend fun observeIdleRevertWhileUpnp() { - playerController.uiState.collect { state -> - val engaged = activeUpnpHolder.active.value != null || - activeUpnpHolder.target.value != null - val armed = idleRevertJob?.isActive == true - when (idleRevertAction(engaged, state.isPlaying, armed)) { - IdleRevertAction.ARM -> - idleRevertJob = scope.launch { - delay(IDLE_REVERT_MS) - revertToPhoneOnIdle() - } - IdleRevertAction.CANCEL -> { - idleRevertJob?.cancel() - idleRevertJob = null - } - IdleRevertAction.IGNORE -> Unit - } - } - } - - /** - * Timer fired: the user paused on a UPnP route and never resumed. - * Stop the renderer (best-effort -- it's reachable, unlike a drop), - * clear the UPnP overlay so routesState falls back to the phone, and - * seek local ExoPlayer to the last remote position. No play(): the - * user was paused, so we revert routing silently. Guarded by the - * selectUpnpMutex so it can't race selectUpnp/resync. - */ - private suspend fun revertToPhoneOnIdle() = selectUpnpMutex.withLock { - if (remoteState.isPlaying) return@withLock // resumed at the boundary - val active = activeUpnpHolder.active.value - val capturedPositionMs = remoteState.positionMs - runCatching { active?.avTransport?.stop() } - .onFailure { Timber.w(it, "UPnP Stop failed during idle revert") } - activeUpnpHolder.set(null) - activeUpnpHolder.setTarget(null) - selectedUpnpRouteIdInternal.value = null - idleRevertJob = null - playerController.seekTo(capturedPositionMs) - } - - /** - * When the user plays a different playlist while Sonos is active, - * PlayerController.setQueue replaces the local queue but Sonos's - * native queue still holds the OLD tracks. MinstrelForwardingPlayer's - * setMediaItems override clears holder.active + sets target so the - * imminent play() call drops (drops via isLoadingUpnp() = true). Then - * this collector observes the uiState.queue change and re-runs - * SonosQueueLoader.load to push the new tracks to Sonos. - * - * Discrimination: selectUpnp's initial-load path doesn't change - * uiState.queue (the queue was already populated before route - * selection), so this collector doesn't fire during that window. Only - * a fresh setQueue from PlayerController bumps the joined-ids key. - */ - private suspend fun observeQueueChangesForSonosResync() { - playerController.uiState.collect { state -> - val newIds = state.queue.map { it.id } - val oldIds = lastSyncedQueueIds - if (newIds == oldIds) return@collect - lastSyncedQueueIds = newIds - // Route can be in target (setMediaItems-induced clearing already - // ran in ForwardingPlayer) OR in active (queue changed via - // addMediaItem / removeMediaItems etc. which don't hit the - // markPending hook). - val routeId = activeUpnpHolder.target.value - ?: activeUpnpHolder.active.value?.routeId - ?: return@collect - if (state.queue.isEmpty()) { - Timber.w("Sonos resync skipped: empty queue (clearing target)") - activeUpnpHolder.setTarget(null) - return@collect - } - scope.launch { - resyncSonosQueue(routeId, oldIds.orEmpty(), state.queue, state.queueIndex) - } - } - } - - /** - * Rebuild the renderer's queue when playback stopped because the renderer - * ran off the end of a queue shorter than ours. - * - * [SonosQueueLoader] tolerates individual AddURIToQueue failures and - * gives up appending after a few consecutive ones - * -- Sonos rate-limits burst adds. Until this existed that left a short - * queue on the renderer and nothing to notice it: the renderer played what - * it had and stopped, and the app went on believing there were forty - * tracks left. [MinstrelForwardingPlayer] now compares GetMediaInfo's - * NrTracks against the local queue and asks for this. - * - * A full reload, not an incremental diff: the renderer's copy is known to - * be wrong, and the diff path reasons from what we *think* it holds, which - * is exactly the assumption that failed. The load re-seeks to the - * current track and plays, so recovery lands where the listener was. - */ - private suspend fun observeQueueRepairRequests() { - playerFactory.queueRepairEvents.collect { - val routeId = selectedUpnpRouteIdInternal.value - ?: activeUpnpHolder.active.value?.routeId - if (routeId == null) { - Timber.w("Sonos queue repair skipped: no UPnP route selected") - return@collect - } - val state = playerController.uiState.value - if (state.queue.isEmpty()) { - Timber.w("Sonos queue repair skipped: local queue is empty") - return@collect - } - // Resume on the track AFTER the current one. The renderer stopped - // because it finished the last track it had; the local cursor is - // synced to that track, so reloading at it would replay something - // the listener just heard. The next one is what they never got. - val resumeAt = (state.queueIndex + 1).coerceAtMost(state.queue.size - 1) - repairSonosQueue(routeId, state.queue, resumeAt) - } - } - - private suspend fun repairSonosQueue( - routeId: String, - queue: List, - currentIndex: Int, - ) = selectUpnpMutex.withLock { - val upnpRoute = upnpDiscovery.routes.value.firstOrNull { it.id == routeId } - val transport = upnpDiscovery.transportFor(routeId) - if (upnpRoute == null || transport == null) { - Timber.w("Sonos queue repair: route or transport gone for %s", routeId) - return@withLock - } - if (!upnpRoute.isSonos) { - // Only a native queue can be truncated; a one-track renderer - // never asks for this. - Timber.w("Sonos queue repair skipped: %s holds no queue", upnpRoute.name) - return@withLock - } - val outputRoute = OutputRoute.fromUpnpRoute(upnpRoute) - Timber.w( - "Sonos queue repair: reloading %d tracks on %s (resuming at index %d)", - queue.size, outputRoute.name, currentIndex, - ) - runCatching { - sonosQueue.load(transport, outputRoute, queue, currentIndex) - }.onFailure { e -> - // Leave the route active: the renderer is reachable enough to have - // told us its queue length, so dropping to local would be a harsher - // remedy than letting the next stall re-decide. - Timber.w(e, "Sonos queue repair failed on %s", outputRoute.name) - } - } - - /** - * Bring Sonos's native queue back in sync with the local queue after a - * mutation. Tries an incremental SOAP diff first (RemoveTrackRangeFromQueue - * + AddURIToQueue at the insertion point) so playback continues without - * interruption -- that's what playNext / radio-append want. Falls back to - * the full removeAllTracks + reload path when the diff implies the current - * Sonos track was deleted (e.g. user switched playlists), which is what - * the user-reported "Sonos queue does not update" bug needed. - */ - private suspend fun resyncSonosQueue( - routeId: String, - oldIds: List, - newQueue: List, - newCurrentIndex: Int, - ) = selectUpnpMutex.withLock { - val upnpRoute = upnpDiscovery.routes.value.firstOrNull { it.id == routeId } - val transport = upnpDiscovery.transportFor(routeId) - if (upnpRoute == null || transport == null) { - Timber.w( - "Sonos resync: route or transport gone for %s, dropping to local", - routeId, - ) - activeUpnpHolder.setTarget(null) - selectedUpnpRouteIdInternal.value = null - return@withLock - } - if (!upnpRoute.isSonos) { - resyncSingleTrack(upnpRoute, transport, newQueue, newCurrentIndex) - return@withLock - } - // The incremental diff is for a queue changed under a cast that kept - // running (play next, an append, a removal): it leaves the playing - // track alone. A queue REPLACED through setMediaItems has already - // cleared active, and the listener asked for its start track and for - // it to play -- both of which the diff would ignore, and with active - // never restored the app would think it had gone back to the phone - // while the speaker played on. That case reloads in full below. - val stillActive = activeUpnpHolder.active.value?.routeId == routeId - val handledIncrementally = stillActive && runCatching { - sonosQueue.tryIncrementalResync(transport, oldIds, newQueue) - }.getOrElse { e -> - Timber.w(e, "Sonos incremental resync errored; falling back to full reload") - false - } - if (handledIncrementally) { - activeUpnpHolder.setTarget(null) - return@withLock - } - // Full rebuild: ensure active is cleared so transport calls drop - // (the forwarding player has already done this on the setMediaItems - // path). - if (activeUpnpHolder.active.value != null) { - activeUpnpHolder.set(null) - activeUpnpHolder.setTarget(routeId) - } - val outputRoute = OutputRoute.fromUpnpRoute(upnpRoute) - val rendering = renderingClientFor(routeId) - Timber.w("Sonos resync: full reload of %d tracks on %s", newQueue.size, outputRoute.name) - runCatching { - sonosQueue.load(transport, outputRoute, newQueue, newCurrentIndex) - activeUpnpHolder.set( - ActiveUpnp( - routeId = routeId, - routeName = outputRoute.name, - avTransport = transport, - rendering = rendering, - queueMode = QueueMode.NATIVE_QUEUE, - ), - ) - activeUpnpHolder.setTarget(null) - }.onFailure { e -> - Timber.w(e, "Sonos resync (full) failed -- dropping to local") - activeUpnpHolder.setTarget(null) - selectedUpnpRouteIdInternal.value = null - } - } - - /** - * The one-track counterpart of the Sonos resync. A mutation that left the - * cast running (play next, radio append, a removal) keeps the current - * track playing and only re-arms what follows it. A queue replaced - * through setMediaItems -- the forwarding player has already cleared - * active, and dropped the play() that came with it -- starts the new - * queue at its current index, as the listener asked. So does a mutation - * that removed the playing track. - */ - private suspend fun resyncSingleTrack( - upnpRoute: UpnpRoute, - transport: AVTransportClient, - newQueue: List, - newCurrentIndex: Int, +class OutputPickerController + @Inject + constructor( + @ApplicationContext private val context: Context, + @ApplicationScope private val scope: CoroutineScope, + private val upnpDiscovery: UpnpDiscoveryController, + private val playerController: PlayerController, + private val playerFactory: PlayerFactory, + private val sonosQueue: SonosQueueLoader, + private val singleTrack: SingleTrackLoader, + private val activeUpnpHolder: ActiveUpnpHolder, + private val remoteState: RemotePlayerState, + private val okHttp: OkHttpClient, ) { - val stillActive = activeUpnpHolder.active.value?.routeId == upnpRoute.id - if (stillActive && requeueKeepsTrack(transport, newQueue)) { - activeUpnpHolder.setTarget(null) - return - } - if (activeUpnpHolder.active.value != null) { - activeUpnpHolder.set(null) - activeUpnpHolder.setTarget(upnpRoute.id) - } - Timber.w("UPnP single-track resync: starting track %d on %s", newCurrentIndex + 1, upnpRoute.name) - runCatching { - singleTrack.load(transport, newQueue, newCurrentIndex) - activeUpnpHolder.set( - ActiveUpnp( - routeId = upnpRoute.id, - routeName = upnpRoute.name, - avTransport = transport, - rendering = renderingClientFor(upnpRoute.id), - queueMode = QueueMode.SINGLE_TRACK, - ), - ) - activeUpnpHolder.setTarget(null) - remoteState.setPlayIntent(true) - }.onFailure { e -> - Timber.w(e, "UPnP single-track resync failed -- dropping to local") - activeUpnpHolder.setTarget(null) - selectedUpnpRouteIdInternal.value = null - } - } + private val mediaRouter = MediaRouter.getInstance(context) - /** True when the playing track survived the change and was kept playing. */ - private suspend fun requeueKeepsTrack(transport: AVTransportClient, newQueue: List): Boolean = - runCatching { singleTrack.requeue(transport, newQueue) } - .onFailure { Timber.w(it, "UPnP single-track requeue failed; restarting the queue") } - .getOrDefault(false) + private val selector = + MediaRouteSelector + .Builder() + .addControlCategory(MediaControlIntent.CATEGORY_LIVE_AUDIO) + .build() + /** + * Internal projection of the live MediaRouter snapshot. Refreshed + * on every Callback event; combined downstream with UPnP routes + * into the public [routesState]. + */ + private val systemRoutesInternal = MutableStateFlow(snapshotFromRouter()) - /** - * Called when the active UPnP route drops unexpectedly (the poll loop's - * consecutive-failure threshold tripping). Captures the last remote - * position + play state, clears UPnP selection, and resumes local ExoPlayer at - * the same point. Skips the Stop SOAP (device already unreachable). - * The snackbar is handled independently by the NowPlaying surface - * collecting the same [PlayerFactory.dropEvents] via PlayerController. - */ - private fun handleRemoteDrop() { - val capturedPositionMs = remoteState.positionMs - // Resume on the user's last play-intent, not the observed remote - // state: after a pause, isPlaying is false, but a failed play() that - // triggered this drop means the user DID ask to play -- honor it. - val wasPlayingRemote = remoteState.lastPlayIntent - activeUpnpHolder.set(null) - activeUpnpHolder.setTarget(null) - selectedUpnpRouteIdInternal.value = null - playerController.seekTo(capturedPositionMs) - if (wasPlayingRemote) playerController.play() - } + private val selectedUpnpRouteIdInternal = MutableStateFlow(null) + private val selectUpnpMutex = Mutex() - /** - * Upgrade callback registration to active discovery — call when - * the picker sheet opens so newly-paired Bluetooth devices - * surface within a few seconds, and fire an SSDP M-SEARCH burst - * for UPnP renderers. Idempotent: re-registering with a - * new flag set replaces the prior registration in MediaRouter. - */ - fun upgradeDiscovery() { - mediaRouter.addCallback(selector, callback, MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY) - upnpDiscovery.upgradeDiscovery() - } + val routesState: StateFlow = + combine( + systemRoutesInternal, + upnpDiscovery.routes, + upnpDiscovery.sonosTopology, + selectedUpnpRouteIdInternal, + ) { sys, upnp, _, upnpSelected -> + val suppressed = upnpDiscovery.nonCoordinatorMemberUdns() + val visibleUpnp = + upnp + .filter { it.id.bareUdn() !in suppressed } // suppressed set is bare UDNs + .map { OutputRoute.fromUpnpRoute(it) } + val merged = sys.available + visibleUpnp + val current = + if (upnpSelected != null) { + merged.firstOrNull { it.id == upnpSelected } ?: sys.current + } else { + sys.current + } + RouteSnapshot(current = current, available = sortRoutes(merged)) + }.stateIn(scope, SharingStarted.Eagerly, systemRoutesInternal.value) - /** - * Downgrade callback registration back to default passive behavior - * — call when the picker sheet closes so we don't keep Bluetooth - * scanning on for battery cost. Two-arg overload = no flag = - * passive. Same idempotent re-registration semantics. The UPnP - * side has no symmetric downgrade (passive SSDP NOTIFY listen is - * always on); the call is preserved for API parity. - */ - fun downgradeDiscovery() { - mediaRouter.addCallback(selector, callback) - upnpDiscovery.downgradeDiscovery() - } + private val callback = + object : MediaRouter.Callback() { + override fun onRouteAdded( + router: MediaRouter, + route: MediaRouter.RouteInfo, + ) = refresh() - /** - * Select [route]. SYSTEM routes hand off to [MediaRouter]; UPNP - * routes mint a signed stream token + drive AVTransport on the - * discovered renderer + pause local playback. Other protocols - * (CAST / SONOS) are not implemented and are silently ignored — the - * picker doesn't show them. - */ - fun select(route: OutputRoute) { - when (route.protocol) { - OutputRoute.Protocol.SYSTEM -> selectSystem(route) - OutputRoute.Protocol.UPNP -> scope.launch { selectUpnp(route) } - OutputRoute.Protocol.CAST, OutputRoute.Protocol.SONOS -> Unit - } - } + override fun onRouteChanged( + router: MediaRouter, + route: MediaRouter.RouteInfo, + ) = refresh() - private fun selectSystem(route: OutputRoute) { - val wasUpnp = selectedUpnpRouteIdInternal.value - if (wasUpnp != null) { - val active = activeUpnpHolder.active.value - val capturedPositionMs = remoteState.positionMs - val wasPlayingRemote = remoteState.isPlaying + override fun onRouteRemoved( + router: MediaRouter, + route: MediaRouter.RouteInfo, + ) = refresh() + + override fun onRouteSelected( + router: MediaRouter, + route: MediaRouter.RouteInfo, + reason: Int, + ) = refresh() + + override fun onRouteUnselected( + router: MediaRouter, + route: MediaRouter.RouteInfo, + reason: Int, + ) = refresh() + } + + // Last-synced queue identity. Used by observeQueueChangesForSonosResync + // to detect when the user has mutated the queue (full replacement, + // playNext insert, or radio-append) while UPnP is active and apply the + // minimum-incremental set of Sonos SOAP operations to bring its native + // queue back in sync. Stored as the full id list (not a join-key) so we + // can run the longest-common-prefix / common-suffix diff. + private var lastSyncedQueueIds: List? = null + + // Idle-revert timer. Armed when playback is paused/stopped on a UPnP + // route; fires revertToPhoneOnIdle after IDLE_REVERT_MS of continuous + // non-playing. Cancelled on resume, route change, or explicit disconnect. + // See idleRevertAction for the arm/cancel decision. + private var idleRevertJob: Job? = null + + init { + // Two-arg addCallback registers with no discovery flag — + // androidx.mediarouter 1.7.0's default passive behavior: + // route-list updates flow through onRouteAdded/Removed/Changed + // without forcing Bluetooth scans. (There is no + // CALLBACK_FLAG_PASSIVE_DISCOVERY constant; absent flag = passive.) + mediaRouter.addCallback(selector, callback) + // When MinstrelForwardingPlayer reports the active UPnP route has + // dropped (the poll loop's consecutive-failure threshold tripping -- + // the sole drop arbiter; a failed transport command does not drop), + // clear the UPnP selection state and fall back to local ExoPlayer at + // the last-known remote position. This mirrors selectSystem's disconnect + // path but skips the Stop SOAP since the device is already unreachable. scope.launch { + playerFactory.dropEvents.collect { handleRemoteDrop() } + } + scope.launch { observeQueueChangesForSonosResync() } + scope.launch { observeQueueRepairRequests() } + scope.launch { observeIdleRevertWhileUpnp() } + scope.launch { observeSelectedRouteDisappearance() } + } + + /** + * Revert the UPnP selection to the phone when the selected renderer leaves + * discovery (powered off / off the LAN) while we are NOT actively casting + * to it. Without this the selection could pin to a ghost route, so a later + * "play" would target a speaker that's gone. An *active* cast is left alone + * -- its own poll loop arbitrates liveness and won't drop on a mere + * discovery gap. Routes leave discovery via [UpnpDiscoveryController]'s + * post-picker-scan prune; this reacts to the resulting routes change. + */ + private suspend fun observeSelectedRouteDisappearance() { + upnpDiscovery.routes.collect { routes -> + val selected = selectedUpnpRouteIdInternal.value + val present = routes.any { it.id == selected } + val casting = activeUpnpHolder.active.value?.routeId == selected + if (selected != null && !present && !casting) { + Timber.w( + "Output: selected UPnP route %s left discovery; reverting to phone", + selected, + ) + selectedUpnpRouteIdInternal.value = null + } + } + } + + /** + * Arm/cancel the idle-revert timer as playback state changes while a + * UPnP route is engaged. "Engaged" = active OR target set, so the brief + * selectUpnp/resync window (active momentarily null, target set) doesn't + * spuriously fire. The arm/cancel choice is the pure idleRevertAction. + */ + private suspend fun observeIdleRevertWhileUpnp() { + playerController.uiState.collect { state -> + val engaged = + activeUpnpHolder.active.value != null || + activeUpnpHolder.target.value != null + val armed = idleRevertJob?.isActive == true + when (idleRevertAction(engaged, state.isPlaying, armed)) { + IdleRevertAction.ARM -> + idleRevertJob = + scope.launch { + delay(IDLE_REVERT_MS) + revertToPhoneOnIdle() + } + IdleRevertAction.CANCEL -> { + idleRevertJob?.cancel() + idleRevertJob = null + } + IdleRevertAction.IGNORE -> Unit + } + } + } + + /** + * Timer fired: the user paused on a UPnP route and never resumed. + * Stop the renderer (best-effort -- it's reachable, unlike a drop), + * clear the UPnP overlay so routesState falls back to the phone, and + * seek local ExoPlayer to the last remote position. No play(): the + * user was paused, so we revert routing silently. Guarded by the + * selectUpnpMutex so it can't race selectUpnp/resync. + */ + private suspend fun revertToPhoneOnIdle() = + selectUpnpMutex.withLock { + if (remoteState.isPlaying) return@withLock // resumed at the boundary + val active = activeUpnpHolder.active.value + val capturedPositionMs = remoteState.positionMs runCatching { active?.avTransport?.stop() } - .onFailure { Timber.w(it, "UPnP Stop failed during disconnect") } + .onFailure { Timber.w(it, "UPnP Stop failed during idle revert") } activeUpnpHolder.set(null) activeUpnpHolder.setTarget(null) selectedUpnpRouteIdInternal.value = null + idleRevertJob = null playerController.seekTo(capturedPositionMs) - if (wasPlayingRemote) playerController.play() } - } - val target = mediaRouter.routes.firstOrNull { it.id == route.id } ?: return - mediaRouter.selectRoute(target) - } - /** - * Hand the renderer the local queue and play it. A Sonos gets its native - * queue loaded ([SonosQueueLoader]); any other renderer is started on the - * current track with the next one armed ([SingleTrackLoader]). Wrapped in - * `runCatching` — SOAP failure abandons the selection cleanly. - * - * Order of operations is deliberate: - * 1. Pause local so the user doesn't keep hearing local audio. - * 2. Set target early so ForwardingPlayer drops transport taps - * while the 17-second queue load is in progress. - * 3. Wire active LAST (after the queue load) so SOAP commands - * are never routed to a half-loaded Sonos queue. - */ - private suspend fun selectUpnp(route: OutputRoute) = selectUpnpMutex.withLock { - val uiState = playerController.uiState.value - val currentTrack = uiState.currentTrack - if (currentTrack == null) { - Timber.w("UPnP select skipped: no currentTrack (start playback first)") - return@withLock - } - // Honor Sonos topology: pick the coordinator's route when the user - // tapped a group row. Suppression in routesState already keeps the - // visible row at the coordinator's id, so this is identity in the - // common case -- defensive for any other caller. - val effectiveRoute = upnpDiscovery.coordinatorRouteFor(route.id) - ?.let { OutputRoute.fromUpnpRoute(it) } ?: route - val transport = upnpDiscovery.transportFor(effectiveRoute.id) - if (transport == null) { - Timber.w( - "UPnP select skipped: no transport for route id=${effectiveRoute.id} " + - "(route disappeared or id mismatch with discovery list)", - ) - return@withLock - } - val rendering = renderingClientFor(effectiveRoute.id) - val queueMode = queueModeFor(effectiveRoute.id) - // Pause local before flipping UI state -- user shouldn't keep hearing - // local audio while we queue up Sonos. - playerController.pause() - selectedUpnpRouteIdInternal.value = effectiveRoute.id - // If the renderer is already playing this exact queue (a "stray" - // session we got disconnected from), attach to it in place instead of - // wiping + reloading -- no jarring restart, and skip/seek land on its - // live queue. Falls through to the clear+reload path when it isn't ours. - val adopted = tryAdoptRunningSession( - AdoptTarget(transport, rendering, effectiveRoute, queueMode), - uiState.queue, - uiState.queueIndex, - ) - if (adopted) { - return@withLock - } - // Mark UPnP loading. ForwardingPlayer overrides drop transport commands - // silently while target is set but active is null -- the user's premature - // taps don't hit Sonos's stale state from a prior session. - activeUpnpHolder.setTarget(effectiveRoute.id) - runCatching { - when (queueMode) { - QueueMode.NATIVE_QUEUE -> - sonosQueue.load(transport, effectiveRoute, uiState.queue, uiState.queueIndex) - QueueMode.SINGLE_TRACK -> - singleTrack.load(transport, uiState.queue, uiState.queueIndex) + /** + * When the user plays a different playlist while Sonos is active, + * PlayerController.setQueue replaces the local queue but Sonos's + * native queue still holds the OLD tracks. MinstrelForwardingPlayer's + * setMediaItems override clears holder.active + sets target so the + * imminent play() call drops (drops via isLoadingUpnp() = true). Then + * this collector observes the uiState.queue change and re-runs + * SonosQueueLoader.load to push the new tracks to Sonos. + * + * Discrimination: selectUpnp's initial-load path doesn't change + * uiState.queue (the queue was already populated before route + * selection), so this collector doesn't fire during that window. Only + * a fresh setQueue from PlayerController bumps the joined-ids key. + */ + private suspend fun observeQueueChangesForSonosResync() { + playerController.uiState.collect { state -> + val newIds = state.queue.map { it.id } + val oldIds = lastSyncedQueueIds + if (newIds == oldIds) return@collect + lastSyncedQueueIds = newIds + // Route can be in target (setMediaItems-induced clearing already + // ran in ForwardingPlayer) OR in active (queue changed via + // addMediaItem / removeMediaItems etc. which don't hit the + // markPending hook). + val routeId = + activeUpnpHolder.target.value + ?: activeUpnpHolder.active.value?.routeId + ?: return@collect + if (state.queue.isEmpty()) { + Timber.w("Sonos resync skipped: empty queue (clearing target)") + activeUpnpHolder.setTarget(null) + return@collect + } + scope.launch { + resyncSonosQueue(routeId, oldIds.orEmpty(), state.queue, state.queueIndex) + } } - // Wire active LAST -- SOAP path is now safe to use. - activeUpnpHolder.set( - ActiveUpnp( - routeId = effectiveRoute.id, - routeName = effectiveRoute.name, - avTransport = transport, - rendering = rendering, - queueMode = queueMode, - ), + } + + /** + * Rebuild the renderer's queue when playback stopped because the renderer + * ran off the end of a queue shorter than ours. + * + * [SonosQueueLoader] tolerates individual AddURIToQueue failures and + * gives up appending after a few consecutive ones + * -- Sonos rate-limits burst adds. Until this existed that left a short + * queue on the renderer and nothing to notice it: the renderer played what + * it had and stopped, and the app went on believing there were forty + * tracks left. [MinstrelForwardingPlayer] now compares GetMediaInfo's + * NrTracks against the local queue and asks for this. + * + * A full reload, not an incremental diff: the renderer's copy is known to + * be wrong, and the diff path reasons from what we *think* it holds, which + * is exactly the assumption that failed. The load re-seeks to the + * current track and plays, so recovery lands where the listener was. + */ + private suspend fun observeQueueRepairRequests() { + playerFactory.queueRepairEvents.collect { + val routeId = + selectedUpnpRouteIdInternal.value + ?: activeUpnpHolder.active.value?.routeId + if (routeId == null) { + Timber.w("Sonos queue repair skipped: no UPnP route selected") + return@collect + } + val state = playerController.uiState.value + if (state.queue.isEmpty()) { + Timber.w("Sonos queue repair skipped: local queue is empty") + return@collect + } + // Resume on the track AFTER the current one. The renderer stopped + // because it finished the last track it had; the local cursor is + // synced to that track, so reloading at it would replay something + // the listener just heard. The next one is what they never got. + val resumeAt = (state.queueIndex + 1).coerceAtMost(state.queue.size - 1) + repairSonosQueue(routeId, state.queue, resumeAt) + } + } + + private suspend fun repairSonosQueue( + routeId: String, + queue: List, + currentIndex: Int, + ) = selectUpnpMutex.withLock { + val upnpRoute = upnpDiscovery.routes.value.firstOrNull { it.id == routeId } + val transport = upnpDiscovery.transportFor(routeId) + if (upnpRoute == null || transport == null) { + Timber.w("Sonos queue repair: route or transport gone for %s", routeId) + return@withLock + } + if (!upnpRoute.isSonos) { + // Only a native queue can be truncated; a one-track renderer + // never asks for this. + Timber.w("Sonos queue repair skipped: %s holds no queue", upnpRoute.name) + return@withLock + } + val outputRoute = OutputRoute.fromUpnpRoute(upnpRoute) + Timber.w( + "Sonos queue repair: reloading %d tracks on %s (resuming at index %d)", + queue.size, + outputRoute.name, + currentIndex, ) - // Selecting a route loads the queue and Plays on the renderer, so - // the standing intent is "play" -- a later drop should resume local. - remoteState.setPlayIntent(true) - }.onFailure { e -> - Timber.w(e, "UPnP select failed for route ${effectiveRoute.id}") + runCatching { + sonosQueue.load(transport, outputRoute, queue, currentIndex) + }.onFailure { e -> + // Leave the route active: the renderer is reachable enough to have + // told us its queue length, so dropping to local would be a harsher + // remedy than letting the next stall re-decide. + Timber.w(e, "Sonos queue repair failed on %s", outputRoute.name) + } + } + + /** + * Bring Sonos's native queue back in sync with the local queue after a + * mutation. Tries an incremental SOAP diff first (RemoveTrackRangeFromQueue + * + AddURIToQueue at the insertion point) so playback continues without + * interruption -- that's what playNext / radio-append want. Falls back to + * the full removeAllTracks + reload path when the diff implies the current + * Sonos track was deleted (e.g. user switched playlists), which is what + * the user-reported "Sonos queue does not update" bug needed. + */ + private suspend fun resyncSonosQueue( + routeId: String, + oldIds: List, + newQueue: List, + newCurrentIndex: Int, + ) = selectUpnpMutex.withLock { + val upnpRoute = upnpDiscovery.routes.value.firstOrNull { it.id == routeId } + val transport = upnpDiscovery.transportFor(routeId) + if (upnpRoute == null || transport == null) { + Timber.w( + "Sonos resync: route or transport gone for %s, dropping to local", + routeId, + ) + activeUpnpHolder.setTarget(null) + selectedUpnpRouteIdInternal.value = null + return@withLock + } + if (!upnpRoute.isSonos) { + resyncSingleTrack(upnpRoute, transport, newQueue, newCurrentIndex) + return@withLock + } + // The incremental diff is for a queue changed under a cast that kept + // running (play next, an append, a removal): it leaves the playing + // track alone. A queue REPLACED through setMediaItems has already + // cleared active, and the listener asked for its start track and for + // it to play -- both of which the diff would ignore, and with active + // never restored the app would think it had gone back to the phone + // while the speaker played on. That case reloads in full below. + val stillActive = activeUpnpHolder.active.value?.routeId == routeId + val handledIncrementally = + stillActive && + runCatching { + sonosQueue.tryIncrementalResync(transport, oldIds, newQueue) + }.getOrElse { e -> + Timber.w(e, "Sonos incremental resync errored; falling back to full reload") + false + } + if (handledIncrementally) { + activeUpnpHolder.setTarget(null) + return@withLock + } + // Full rebuild: ensure active is cleared so transport calls drop + // (the forwarding player has already done this on the setMediaItems + // path). + if (activeUpnpHolder.active.value != null) { + activeUpnpHolder.set(null) + activeUpnpHolder.setTarget(routeId) + } + val outputRoute = OutputRoute.fromUpnpRoute(upnpRoute) + val rendering = renderingClientFor(routeId) + Timber.w("Sonos resync: full reload of %d tracks on %s", newQueue.size, outputRoute.name) + runCatching { + sonosQueue.load(transport, outputRoute, newQueue, newCurrentIndex) + activeUpnpHolder.set( + ActiveUpnp( + routeId = routeId, + routeName = outputRoute.name, + avTransport = transport, + rendering = rendering, + queueMode = QueueMode.NATIVE_QUEUE, + ), + ) + activeUpnpHolder.setTarget(null) + }.onFailure { e -> + Timber.w(e, "Sonos resync (full) failed -- dropping to local") + activeUpnpHolder.setTarget(null) + selectedUpnpRouteIdInternal.value = null + } + } + + /** + * The one-track counterpart of the Sonos resync. A mutation that left the + * cast running (play next, radio append, a removal) keeps the current + * track playing and only re-arms what follows it. A queue replaced + * through setMediaItems -- the forwarding player has already cleared + * active, and dropped the play() that came with it -- starts the new + * queue at its current index, as the listener asked. So does a mutation + * that removed the playing track. + */ + private suspend fun resyncSingleTrack( + upnpRoute: UpnpRoute, + transport: AVTransportClient, + newQueue: List, + newCurrentIndex: Int, + ) { + val stillActive = activeUpnpHolder.active.value?.routeId == upnpRoute.id + if (stillActive && requeueKeepsTrack(transport, newQueue)) { + activeUpnpHolder.setTarget(null) + return + } + if (activeUpnpHolder.active.value != null) { + activeUpnpHolder.set(null) + activeUpnpHolder.setTarget(upnpRoute.id) + } + Timber.w("UPnP single-track resync: starting track %d on %s", newCurrentIndex + 1, upnpRoute.name) + runCatching { + singleTrack.load(transport, newQueue, newCurrentIndex) + activeUpnpHolder.set( + ActiveUpnp( + routeId = upnpRoute.id, + routeName = upnpRoute.name, + avTransport = transport, + rendering = renderingClientFor(upnpRoute.id), + queueMode = QueueMode.SINGLE_TRACK, + ), + ) + activeUpnpHolder.setTarget(null) + remoteState.setPlayIntent(true) + }.onFailure { e -> + Timber.w(e, "UPnP single-track resync failed -- dropping to local") + activeUpnpHolder.setTarget(null) + selectedUpnpRouteIdInternal.value = null + } + } + + /** True when the playing track survived the change and was kept playing. */ + private suspend fun requeueKeepsTrack( + transport: AVTransportClient, + newQueue: List, + ): Boolean = + runCatching { singleTrack.requeue(transport, newQueue) } + .onFailure { Timber.w(it, "UPnP single-track requeue failed; restarting the queue") } + .getOrDefault(false) + + /** + * Called when the active UPnP route drops unexpectedly (the poll loop's + * consecutive-failure threshold tripping). Captures the last remote + * position + play state, clears UPnP selection, and resumes local ExoPlayer at + * the same point. Skips the Stop SOAP (device already unreachable). + * The snackbar is handled independently by the NowPlaying surface + * collecting the same [PlayerFactory.dropEvents] via PlayerController. + */ + private fun handleRemoteDrop() { + val capturedPositionMs = remoteState.positionMs + // Resume on the user's last play-intent, not the observed remote + // state: after a pause, isPlaying is false, but a failed play() that + // triggered this drop means the user DID ask to play -- honor it. + val wasPlayingRemote = remoteState.lastPlayIntent activeUpnpHolder.set(null) activeUpnpHolder.setTarget(null) selectedUpnpRouteIdInternal.value = null + playerController.seekTo(capturedPositionMs) + if (wasPlayingRemote) playerController.play() } - } - /** - * The renderer's current position + transport state, validated as an - * adoptable continuation of our local queue. Null means "not ours / not - * playing" -> caller reloads. - */ - private data class AdoptPlan( - val localIndex: Int, - val positionMs: Long, - val durationMs: Long, - val trackUri: String, - val playing: Boolean, - ) - - /** The renderer a select is about to drive, and how. */ - private data class AdoptTarget( - val transport: AVTransportClient, - val rendering: RenderingControlClient?, - val route: OutputRoute, - val queueMode: QueueMode, - ) - - /** - * Attach to a renderer that is *already* playing our queue (a session the - * phone got disconnected from but the speaker kept streaming) instead of - * clearing + reloading it. Probes the renderer's live state, and if it's - * mid-playback on one of our tracks where our queue has it, syncs the - * local cursor to match and wires [ActiveUpnpHolder] -- the speaker never - * skips a beat, and skip/seek now drive it. Returns false (and the caller - * does the full load) when the renderer isn't playing our queue. The - * local player is already paused by the caller. - */ - private suspend fun tryAdoptRunningSession( - target: AdoptTarget, - localQueue: List, - localIndex: Int, - ): Boolean { - val route = target.route - val plan = probeAdoptable(target, localQueue, localIndex) ?: return false - if (target.queueMode == QueueMode.SINGLE_TRACK) { - // The renderer holds only this track; arm the one after it. - singleTrack.adopt(target.transport, localQueue, plan.localIndex, plan.trackUri) + /** + * Upgrade callback registration to active discovery — call when + * the picker sheet opens so newly-paired Bluetooth devices + * surface within a few seconds, and fire an SSDP M-SEARCH burst + * for UPnP renderers. Idempotent: re-registering with a + * new flag set replaces the prior registration in MediaRouter. + */ + fun upgradeDiscovery() { + mediaRouter.addCallback(selector, callback, MediaRouter.CALLBACK_FLAG_REQUEST_DISCOVERY) + upnpDiscovery.upgradeDiscovery() } - Timber.w( - "UPnP adopt: attaching to live session on %s at track %d (%dms)", - route.name, plan.localIndex + 1, plan.positionMs, + + /** + * Downgrade callback registration back to default passive behavior + * — call when the picker sheet closes so we don't keep Bluetooth + * scanning on for battery cost. Two-arg overload = no flag = + * passive. Same idempotent re-registration semantics. The UPnP + * side has no symmetric downgrade (passive SSDP NOTIFY listen is + * always on); the call is preserved for API parity. + */ + fun downgradeDiscovery() { + mediaRouter.addCallback(selector, callback) + upnpDiscovery.downgradeDiscovery() + } + + /** + * Select [route]. SYSTEM routes hand off to [MediaRouter]; UPNP + * routes mint a signed stream token + drive AVTransport on the + * discovered renderer + pause local playback. Other protocols + * (CAST / SONOS) are not implemented and are silently ignored — the + * picker doesn't show them. + */ + fun select(route: OutputRoute) { + when (route.protocol) { + OutputRoute.Protocol.SYSTEM -> selectSystem(route) + OutputRoute.Protocol.UPNP -> scope.launch { selectUpnp(route) } + OutputRoute.Protocol.CAST, OutputRoute.Protocol.SONOS -> Unit + } + } + + private fun selectSystem(route: OutputRoute) { + val wasUpnp = selectedUpnpRouteIdInternal.value + if (wasUpnp != null) { + val active = activeUpnpHolder.active.value + val capturedPositionMs = remoteState.positionMs + val wasPlayingRemote = remoteState.isPlaying + scope.launch { + runCatching { active?.avTransport?.stop() } + .onFailure { Timber.w(it, "UPnP Stop failed during disconnect") } + activeUpnpHolder.set(null) + activeUpnpHolder.setTarget(null) + selectedUpnpRouteIdInternal.value = null + playerController.seekTo(capturedPositionMs) + if (wasPlayingRemote) playerController.play() + } + } + val target = mediaRouter.routes.firstOrNull { it.id == route.id } ?: return + mediaRouter.selectRoute(target) + } + + /** + * Hand the renderer the local queue and play it. A Sonos gets its native + * queue loaded ([SonosQueueLoader]); any other renderer is started on the + * current track with the next one armed ([SingleTrackLoader]). Wrapped in + * `runCatching` — SOAP failure abandons the selection cleanly. + * + * Order of operations is deliberate: + * 1. Pause local so the user doesn't keep hearing local audio. + * 2. Set target early so ForwardingPlayer drops transport taps + * while the 17-second queue load is in progress. + * 3. Wire active LAST (after the queue load) so SOAP commands + * are never routed to a half-loaded Sonos queue. + */ + private suspend fun selectUpnp(route: OutputRoute) = + selectUpnpMutex.withLock { + val uiState = playerController.uiState.value + val currentTrack = uiState.currentTrack + if (currentTrack == null) { + Timber.w("UPnP select skipped: no currentTrack (start playback first)") + return@withLock + } + // Honor Sonos topology: pick the coordinator's route when the user + // tapped a group row. Suppression in routesState already keeps the + // visible row at the coordinator's id, so this is identity in the + // common case -- defensive for any other caller. + val effectiveRoute = + upnpDiscovery + .coordinatorRouteFor(route.id) + ?.let { OutputRoute.fromUpnpRoute(it) } ?: route + val transport = upnpDiscovery.transportFor(effectiveRoute.id) + if (transport == null) { + Timber.w( + "UPnP select skipped: no transport for route id=${effectiveRoute.id} " + + "(route disappeared or id mismatch with discovery list)", + ) + return@withLock + } + val rendering = renderingClientFor(effectiveRoute.id) + val queueMode = queueModeFor(effectiveRoute.id) + // Pause local before flipping UI state -- user shouldn't keep hearing + // local audio while we queue up Sonos. + playerController.pause() + selectedUpnpRouteIdInternal.value = effectiveRoute.id + // If the renderer is already playing this exact queue (a "stray" + // session we got disconnected from), attach to it in place instead of + // wiping + reloading -- no jarring restart, and skip/seek land on its + // live queue. Falls through to the clear+reload path when it isn't ours. + val adopted = + tryAdoptRunningSession( + AdoptTarget(transport, rendering, effectiveRoute, queueMode), + uiState.queue, + uiState.queueIndex, + ) + if (adopted) { + return@withLock + } + // Mark UPnP loading. ForwardingPlayer overrides drop transport commands + // silently while target is set but active is null -- the user's premature + // taps don't hit Sonos's stale state from a prior session. + activeUpnpHolder.setTarget(effectiveRoute.id) + runCatching { + when (queueMode) { + QueueMode.NATIVE_QUEUE -> + sonosQueue.load(transport, effectiveRoute, uiState.queue, uiState.queueIndex) + QueueMode.SINGLE_TRACK -> + singleTrack.load(transport, uiState.queue, uiState.queueIndex) + } + // Wire active LAST -- SOAP path is now safe to use. + activeUpnpHolder.set( + ActiveUpnp( + routeId = effectiveRoute.id, + routeName = effectiveRoute.name, + avTransport = transport, + rendering = rendering, + queueMode = queueMode, + ), + ) + // Selecting a route loads the queue and Plays on the renderer, so + // the standing intent is "play" -- a later drop should resume local. + remoteState.setPlayIntent(true) + }.onFailure { e -> + Timber.w(e, "UPnP select failed for route ${effectiveRoute.id}") + activeUpnpHolder.set(null) + activeUpnpHolder.setTarget(null) + selectedUpnpRouteIdInternal.value = null + } + } + + /** + * The renderer's current position + transport state, validated as an + * adoptable continuation of our local queue. Null means "not ours / not + * playing" -> caller reloads. + */ + private data class AdoptPlan( + val localIndex: Int, + val positionMs: Long, + val durationMs: Long, + val trackUri: String, + val playing: Boolean, ) - // active is still null here, so this aligns the *local* cursor without - // emitting SOAP; the holder.set below then starts the poll loop, which - // reconciles to the renderer's advancing position from here. - playerController.moveCursorTo(plan.localIndex, plan.positionMs) - remoteState.applyPositionInfo( - positionMs = plan.positionMs, - durationMs = plan.durationMs, - trackUri = plan.trackUri, - trackNumber = plan.localIndex + 1, - ) - remoteState.setPlayIntent(plan.playing) - activeUpnpHolder.set( - ActiveUpnp( - routeId = route.id, - routeName = route.name, - avTransport = target.transport, - rendering = target.rendering, - queueMode = target.queueMode, - ), - ) - return true - } - /** - * A Sonos must be on our track at the same 1-based index of its native - * queue, since skips drive that queue. A one-track renderer has no index - * to agree on: it is ours if it is playing one of our tracks, taken - * nearest the local cursor. - */ - private suspend fun probeAdoptable( - target: AdoptTarget, - localQueue: List, - localIndex: Int, - ): AdoptPlan? { - val probe = runCatching { - target.transport.getTransportInfo() to target.transport.getPositionInfo() - }.getOrElse { - Timber.w(it, "UPnP adopt: probe failed for %s; will reload", target.route.name) - return null - } - val (info, pos) = probe - val playingId = streamUriTrackId(pos.trackUri) - val midPlayback = - info.state == TransportState.PLAYING || info.state == TransportState.PAUSED - val idx0 = when { - playingId == null -> null - target.queueMode == QueueMode.SINGLE_TRACK -> - nearestIndexOf(localQueue, playingId, localIndex) - else -> (pos.track - 1).takeIf { it in localQueue.indices && localQueue[it].id == playingId } - } - return if (midPlayback && idx0 != null) { - AdoptPlan( - localIndex = idx0, - positionMs = pos.relTimeMs, - durationMs = pos.trackDurationMs, - trackUri = pos.trackUri, - playing = info.state == TransportState.PLAYING, + /** The renderer a select is about to drive, and how. */ + private data class AdoptTarget( + val transport: AVTransportClient, + val rendering: RenderingControlClient?, + val route: OutputRoute, + val queueMode: QueueMode, + ) + + /** + * Attach to a renderer that is *already* playing our queue (a session the + * phone got disconnected from but the speaker kept streaming) instead of + * clearing + reloading it. Probes the renderer's live state, and if it's + * mid-playback on one of our tracks where our queue has it, syncs the + * local cursor to match and wires [ActiveUpnpHolder] -- the speaker never + * skips a beat, and skip/seek now drive it. Returns false (and the caller + * does the full load) when the renderer isn't playing our queue. The + * local player is already paused by the caller. + */ + private suspend fun tryAdoptRunningSession( + target: AdoptTarget, + localQueue: List, + localIndex: Int, + ): Boolean { + val route = target.route + val plan = probeAdoptable(target, localQueue, localIndex) ?: return false + if (target.queueMode == QueueMode.SINGLE_TRACK) { + // The renderer holds only this track; arm the one after it. + singleTrack.adopt(target.transport, localQueue, plan.localIndex, plan.trackUri) + } + Timber.w( + "UPnP adopt: attaching to live session on %s at track %d (%dms)", + route.name, + plan.localIndex + 1, + plan.positionMs, ) - } else { - null + // active is still null here, so this aligns the *local* cursor without + // emitting SOAP; the holder.set below then starts the poll loop, which + // reconciles to the renderer's advancing position from here. + playerController.moveCursorTo(plan.localIndex, plan.positionMs) + remoteState.applyPositionInfo( + positionMs = plan.positionMs, + durationMs = plan.durationMs, + trackUri = plan.trackUri, + trackNumber = plan.localIndex + 1, + ) + remoteState.setPlayIntent(plan.playing) + activeUpnpHolder.set( + ActiveUpnp( + routeId = route.id, + routeName = route.name, + avTransport = target.transport, + rendering = target.rendering, + queueMode = target.queueMode, + ), + ) + return true + } + + /** + * A Sonos must be on our track at the same 1-based index of its native + * queue, since skips drive that queue. A one-track renderer has no index + * to agree on: it is ours if it is playing one of our tracks, taken + * nearest the local cursor. + */ + private suspend fun probeAdoptable( + target: AdoptTarget, + localQueue: List, + localIndex: Int, + ): AdoptPlan? { + val probe = + runCatching { + target.transport.getTransportInfo() to target.transport.getPositionInfo() + }.getOrElse { + Timber.w(it, "UPnP adopt: probe failed for %s; will reload", target.route.name) + return null + } + val (info, pos) = probe + val playingId = streamUriTrackId(pos.trackUri) + val midPlayback = + info.state == TransportState.PLAYING || info.state == TransportState.PAUSED + val idx0 = + when { + playingId == null -> null + target.queueMode == QueueMode.SINGLE_TRACK -> + nearestIndexOf(localQueue, playingId, localIndex) + else -> (pos.track - 1).takeIf { it in localQueue.indices && localQueue[it].id == playingId } + } + return if (midPlayback && idx0 != null) { + AdoptPlan( + localIndex = idx0, + positionMs = pos.relTimeMs, + durationMs = pos.trackDurationMs, + trackUri = pos.trackUri, + playing = info.state == TransportState.PLAYING, + ) + } else { + null + } + } + + /** How the route is fed tracks; a route gone from discovery reads as not-Sonos. */ + private fun queueModeFor(routeId: String): QueueMode = + QueueMode.forRoute( + upnpDiscovery.routes.value + .firstOrNull { it.id == routeId } + ?.isSonos == true, + ) + + private fun renderingClientFor(routeId: String): RenderingControlClient? { + val rcUrl = + upnpDiscovery.routes.value + .firstOrNull { it.id == routeId } + ?.renderingControlUrl ?: return null + return RenderingControlClient(SoapClient(okHttp), rcUrl) + } + + private fun refresh() { + systemRoutesInternal.value = snapshotFromRouter() + } + + private fun snapshotFromRouter(): RouteSnapshot { + val all = + mediaRouter.routes + .filter { it.matchesSelector(selector) } + .map { OutputRoute.fromRouteInfo(it) } + val current = OutputRoute.fromRouteInfo(mediaRouter.selectedRoute) + return RouteSnapshot(current = current, available = sortRoutes(all)) + } + + /** + * BuiltIn "Phone speaker" pinned first; everything else + * alphabetical. Selection state is conveyed by the radio button + * indicator in the picker row, not by sort order. + */ + private fun sortRoutes(all: List): List { + val (builtIn, rest) = all.partition { it.kind == OutputRoute.Kind.BuiltIn } + return builtIn + rest.sortedBy { it.name.lowercase() } + } + + private companion object { + // 5 minutes of continuous non-playing on a UPnP route before we + // revert to the phone speaker, so a stale Sonos selection can't make + // a later "tap play" do nothing. + const val IDLE_REVERT_MS = 5 * 60 * 1000L } } - - /** How the route is fed tracks; a route gone from discovery reads as not-Sonos. */ - private fun queueModeFor(routeId: String): QueueMode = - QueueMode.forRoute(upnpDiscovery.routes.value.firstOrNull { it.id == routeId }?.isSonos == true) - - - private fun renderingClientFor(routeId: String): RenderingControlClient? { - val rcUrl = upnpDiscovery.routes.value - .firstOrNull { it.id == routeId } - ?.renderingControlUrl ?: return null - return RenderingControlClient(SoapClient(okHttp), rcUrl) - } - - private fun refresh() { - systemRoutesInternal.value = snapshotFromRouter() - } - - private fun snapshotFromRouter(): RouteSnapshot { - val all = mediaRouter.routes - .filter { it.matchesSelector(selector) } - .map { OutputRoute.fromRouteInfo(it) } - val current = OutputRoute.fromRouteInfo(mediaRouter.selectedRoute) - return RouteSnapshot(current = current, available = sortRoutes(all)) - } - - /** - * BuiltIn "Phone speaker" pinned first; everything else - * alphabetical. Selection state is conveyed by the radio button - * indicator in the picker row, not by sort order. - */ - private fun sortRoutes(all: List): List { - val (builtIn, rest) = all.partition { it.kind == OutputRoute.Kind.BuiltIn } - return builtIn + rest.sortedBy { it.name.lowercase() } - } - - private companion object { - // 5 minutes of continuous non-playing on a UPnP route before we - // revert to the phone speaker, so a stale Sonos selection can't make - // a later "tap play" do nothing. - const val IDLE_REVERT_MS = 5 * 60 * 1000L - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerSheet.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerSheet.kt index 5f31d464..bc0616fa 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerSheet.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerSheet.kt @@ -61,9 +61,10 @@ fun OutputPickerSheet( sheetState = sheetState, ) { Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 24.dp, vertical = 8.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 24.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { Text( @@ -73,9 +74,10 @@ fun OutputPickerSheet( modifier = Modifier.padding(vertical = 8.dp), ) LazyColumn( - modifier = Modifier - .fillMaxWidth() - .heightIn(max = ROUTE_LIST_MAX_HEIGHT_DP.dp), + modifier = + Modifier + .fillMaxWidth() + .heightIn(max = ROUTE_LIST_MAX_HEIGHT_DP.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { items(items = snapshot.available, key = { it.id }) { route -> @@ -102,20 +104,22 @@ private fun RouteRow( isSelected: Boolean, onClick: () -> Unit, ) { - val tint = if (isSelected) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.onSurfaceVariant - } + val tint = + if (isSelected) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + } Surface( onClick = onClick, color = MaterialTheme.colorScheme.surface, modifier = Modifier.fillMaxWidth(), ) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), ) { @@ -155,9 +159,10 @@ private fun RouteRow( @Composable private fun PermissionHintRow() { Row( - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { @@ -178,9 +183,10 @@ private fun PermissionHintRow() { @Composable private fun MulticastHintRow() { Row( - modifier = Modifier - .fillMaxWidth() - .padding(vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { @@ -201,13 +207,17 @@ private fun MulticastHintRow() { // isSelected (route == the active/selected route) drives the Bluetooth // "Connected" subtitle. RouteInfo.connectionState can't — it stays // DISCONNECTED for local SYSTEM routes even when they're in use. -private fun defaultSubtitle(route: OutputRoute, isSelected: Boolean): String = when (route.kind) { - OutputRoute.Kind.BuiltIn -> "Phone speaker" - OutputRoute.Kind.Wired -> "Wired" - OutputRoute.Kind.Bluetooth -> if (isSelected) "Connected" else "Available" - OutputRoute.Kind.Cast -> "Cast" - OutputRoute.Kind.Other -> "Available" -} +private fun defaultSubtitle( + route: OutputRoute, + isSelected: Boolean, +): String = + when (route.kind) { + OutputRoute.Kind.BuiltIn -> "Phone speaker" + OutputRoute.Kind.Wired -> "Wired" + OutputRoute.Kind.Bluetooth -> if (isSelected) "Connected" else "Available" + OutputRoute.Kind.Cast -> "Cast" + OutputRoute.Kind.Other -> "Available" + } private const val ROW_ICON_DP = 24 private const val HINT_ICON_DP = 20 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerViewModel.kt index 6e3cd81a..1ba7c817 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputPickerViewModel.kt @@ -22,43 +22,46 @@ import javax.inject.Inject * is actually visible. */ @HiltViewModel -class OutputPickerViewModel @Inject constructor( - private val controller: OutputPickerController, - private val activeUpnpHolder: ActiveUpnpHolder, -) : ViewModel() { +class OutputPickerViewModel + @Inject + constructor( + private val controller: OutputPickerController, + private val activeUpnpHolder: ActiveUpnpHolder, + ) : ViewModel() { + val routes: StateFlow = + controller.routesState + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), + initialValue = controller.routesState.value, + ) - val routes: StateFlow = controller.routesState - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), - initialValue = controller.routesState.value, - ) + val activeUpnp: StateFlow = + activeUpnpHolder.active + .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null) - val activeUpnp: StateFlow = activeUpnpHolder.active - .stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), null) + private val sheetVisibleInternal = MutableStateFlow(false) + val sheetVisible: StateFlow = sheetVisibleInternal.asStateFlow() - private val sheetVisibleInternal = MutableStateFlow(false) - val sheetVisible: StateFlow = sheetVisibleInternal.asStateFlow() + fun onChipTapped() { + sheetVisibleInternal.value = true + controller.upgradeDiscovery() + } - fun onChipTapped() { - sheetVisibleInternal.value = true - controller.upgradeDiscovery() + fun onSheetDismissed() { + sheetVisibleInternal.value = false + controller.downgradeDiscovery() + } + + fun onRouteSelected(route: OutputRoute) { + controller.select(route) + sheetVisibleInternal.value = false + controller.downgradeDiscovery() + } + + private companion object { + // SharingStarted timeout so quick screen-orientation changes + // don't tear down + re-subscribe the controller's Flow. + const val STOP_TIMEOUT_MS = 5_000L + } } - - fun onSheetDismissed() { - sheetVisibleInternal.value = false - controller.downgradeDiscovery() - } - - fun onRouteSelected(route: OutputRoute) { - controller.select(route) - sheetVisibleInternal.value = false - controller.downgradeDiscovery() - } - - private companion object { - // SharingStarted timeout so quick screen-orientation changes - // don't tear down + re-subscribe the controller's Flow. - const val STOP_TIMEOUT_MS = 5_000L - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputRoute.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputRoute.kt index fb8131ec..dd231388 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputRoute.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/OutputRoute.kt @@ -47,16 +47,17 @@ data class OutputRoute( * and stays DISCONNECTED for local SYSTEM routes even when in use. */ fun fromRouteInfo(route: MediaRouter.RouteInfo): OutputRoute { - val kind = when (route.deviceType) { - MediaRouter.RouteInfo.DEVICE_TYPE_BUILTIN_SPEAKER -> Kind.BuiltIn - MediaRouter.RouteInfo.DEVICE_TYPE_WIRED_HEADSET, - MediaRouter.RouteInfo.DEVICE_TYPE_WIRED_HEADPHONES, - -> Kind.Wired - MediaRouter.RouteInfo.DEVICE_TYPE_BLUETOOTH_A2DP -> Kind.Bluetooth - MediaRouter.RouteInfo.DEVICE_TYPE_TV -> Kind.Other - MediaRouter.RouteInfo.DEVICE_TYPE_SPEAKER -> Kind.Other - else -> Kind.Other - } + val kind = + when (route.deviceType) { + MediaRouter.RouteInfo.DEVICE_TYPE_BUILTIN_SPEAKER -> Kind.BuiltIn + MediaRouter.RouteInfo.DEVICE_TYPE_WIRED_HEADSET, + MediaRouter.RouteInfo.DEVICE_TYPE_WIRED_HEADPHONES, + -> Kind.Wired + MediaRouter.RouteInfo.DEVICE_TYPE_BLUETOOTH_A2DP -> Kind.Bluetooth + MediaRouter.RouteInfo.DEVICE_TYPE_TV -> Kind.Other + MediaRouter.RouteInfo.DEVICE_TYPE_SPEAKER -> Kind.Other + else -> Kind.Other + } return OutputRoute( id = route.id, name = route.name, @@ -82,10 +83,11 @@ data class OutputRoute( * are blank. */ fun fromUpnpRoute(route: UpnpRoute): OutputRoute { - val description = listOfNotNull( - route.manufacturer.takeIf { it.isNotBlank() }, - route.modelName.takeIf { it.isNotBlank() }, - ).joinToString(" ").ifBlank { "Network speaker" } + val description = + listOfNotNull( + route.manufacturer.takeIf { it.isNotBlank() }, + route.modelName.takeIf { it.isNotBlank() }, + ).joinToString(" ").ifBlank { "Network speaker" } return OutputRoute( id = route.id, name = route.name, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/SingleTrackLoader.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/SingleTrackLoader.kt index cae5430b..ba3ee48a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/SingleTrackLoader.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/SingleTrackLoader.kt @@ -10,8 +10,8 @@ import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import timber.log.Timber import javax.inject.Inject -import kotlin.math.abs import javax.inject.Singleton +import kotlin.math.abs /** * Drives a UPnP / DLNA renderer that has no queue of its own — anything that @@ -34,224 +34,256 @@ import javax.inject.Singleton * listener's skip both point the renderer somewhere and must not interleave. */ @Singleton -class SingleTrackLoader @Inject constructor( - private val streamTokens: StreamTokenProvider, -) { - private val mutex = Mutex() +class SingleTrackLoader + @Inject + constructor( + private val streamTokens: StreamTokenProvider, + ) { + private val mutex = Mutex() - @Volatile private var queue: List = emptyList() + @Volatile private var queue: List = emptyList() - /** 0-based index of the track the renderer was last pointed at; -1 when none. */ - @Volatile var currentIndex: Int = -1 - private set + /** 0-based index of the track the renderer was last pointed at; -1 when none. */ + @Volatile var currentIndex: Int = -1 + private set - private var currentUri: String = "" - private var armedNextIndex: Int = -1 - private var armedNextUri: String = "" + private var currentUri: String = "" + private var armedNextIndex: Int = -1 + private var armedNextUri: String = "" - // Set when the renderer faults SetNextAVTransportURI: it does not have the - // action, and asking again per track would only collect the same fault. - // Cleared on every load, since a load may be a different renderer. - private var nextUnsupported = false + // Set when the renderer faults SetNextAVTransportURI: it does not have the + // action, and asking again per track would only collect the same fault. + // Cleared on every load, since a load may be a different renderer. + private var nextUnsupported = false - // Polls to wait before re-trying a SetNext that failed in transit. Each - // try mints a URL from the server, so a failure is not retried every - // second. - private var armRetryPolls = 0 + // Polls to wait before re-trying a SetNext that failed in transit. Each + // try mints a URL from the server, so a failure is not retried every + // second. + private var armRetryPolls = 0 - // Whether the last poll found the current track played to its end. Read - // by [queueState] for the stall watchdog. - private var endedOnLastPoll = false + // Whether the last poll found the current track played to its end. Read + // by [queueState] for the stall watchdog. + private var endedOnLastPoll = false - private val endDetector = TrackEndDetector() + private val endDetector = TrackEndDetector() - /** - * What a poll learned. [trackNumber] is the 1-based queue position the - * renderer is playing (0 when nothing is loaded). [advanced] is true when - * this poll started the next track itself, so the reading it was given is - * already stale and the caller should not judge a stall from it. - * [knownDurationMs] is the library's duration for that track, for a - * renderer that reports none. - */ - data class PollOutcome(val trackNumber: Int, val advanced: Boolean, val knownDurationMs: Long = 0L) + /** + * What a poll learned. [trackNumber] is the 1-based queue position the + * renderer is playing (0 when nothing is loaded). [advanced] is true when + * this poll started the next track itself, so the reading it was given is + * already stale and the caller should not judge a stall from it. + * [knownDurationMs] is the library's duration for that track, for a + * renderer that reports none. + */ + data class PollOutcome( + val trackNumber: Int, + val advanced: Boolean, + val knownDurationMs: Long = 0L, + ) - /** Take [queue] as the one to play, and start [index] on the renderer. */ - suspend fun load(transport: AVTransportClient, queue: List, index: Int) = - mutex.withLock { + /** Take [queue] as the one to play, and start [index] on the renderer. */ + suspend fun load( + transport: AVTransportClient, + queue: List, + index: Int, + ) = mutex.withLock { this.queue = queue nextUnsupported = false start(transport, index) } - /** - * Start [index] of the queue already held — a skip, a previous, or a tap - * on a queue row. Returns false when [index] is outside the queue. - */ - suspend fun playIndex(transport: AVTransportClient, index: Int): Boolean = - mutex.withLock { start(transport, index) } + /** + * Start [index] of the queue already held — a skip, a previous, or a tap + * on a queue row. Returns false when [index] is outside the queue. + */ + suspend fun playIndex( + transport: AVTransportClient, + index: Int, + ): Boolean = mutex.withLock { start(transport, index) } - /** - * Attach to a renderer already playing [index] of [queue] at [uri] — a - * session the phone lost touch with and the renderer carried on with — - * without restarting it. Only arms the next track. - */ - suspend fun adopt(transport: AVTransportClient, queue: List, index: Int, uri: String) = - mutex.withLock { + /** + * Attach to a renderer already playing [index] of [queue] at [uri] — a + * session the phone lost touch with and the renderer carried on with — + * without restarting it. Only arms the next track. + */ + suspend fun adopt( + transport: AVTransportClient, + queue: List, + index: Int, + uri: String, + ) = mutex.withLock { this.queue = queue nextUnsupported = false pointedAt(index, uri) armNext(transport) } - /** - * The local queue changed under a playing track (play next, radio - * append, a removal). Keep playing the current track and re-arm what - * follows it. Returns false when the current track is gone from - * [newQueue]; the caller then starts the new queue with [load]. - */ - suspend fun requeue(transport: AVTransportClient, newQueue: List): Boolean = - mutex.withLock { - val playingId = queue.getOrNull(currentIndex)?.id - val idx = playingId?.let { nearestIndexOf(newQueue, it, currentIndex) } - queue = newQueue - if (idx == null) return@withLock false - currentIndex = idx - // What was armed was chosen from the old queue; SetNext replaces it. + /** + * The local queue changed under a playing track (play next, radio + * append, a removal). Keep playing the current track and re-arm what + * follows it. Returns false when the current track is gone from + * [newQueue]; the caller then starts the new queue with [load]. + */ + suspend fun requeue( + transport: AVTransportClient, + newQueue: List, + ): Boolean = + mutex.withLock { + val playingId = queue.getOrNull(currentIndex)?.id + val idx = playingId?.let { nearestIndexOf(newQueue, it, currentIndex) } + queue = newQueue + if (idx == null) return@withLock false + currentIndex = idx + // What was armed was chosen from the old queue; SetNext replaces it. + armedNextIndex = -1 + armedNextUri = "" + armNext(transport) + true + } + + /** + * One poll's reading of the renderer. Follows a renderer that moved on by + * itself, re-tries arming the next track, and starts the next track when + * the current one has played to its end. + */ + suspend fun onPoll( + transport: AVTransportClient, + trackUri: String, + state: TransportState, + positionMs: Long, + durationMs: Long, + playIntent: Boolean, + ): PollOutcome = + mutex.withLock { + if (currentIndex !in queue.indices) return@withLock PollOutcome(0, advanced = false) + val moved = followRenderer(trackUri) + armNext(transport) + if (moved) return@withLock PollOutcome(currentIndex + 1, advanced = false, knownDurationMs(queue, currentIndex)) + endedOnLastPoll = endDetector.onPoll(state, positionMs, durationMs, knownDurationMs(queue, currentIndex)) + val next = currentIndex + 1 + val advance = endedOnLastPoll && playIntent && next in queue.indices + if (advance) { + Timber.w("UPnP single-track: track %d ended; starting %d", currentIndex + 1, next + 1) + runCatching { start(transport, next) } + .onFailure { Timber.w(it, "UPnP single-track: could not start track %d", next + 1) } + } + PollOutcome(currentIndex + 1, advanced = advance, knownDurationMs(queue, currentIndex)) + } + + /** + * For the stall watchdog: a renderer stopped at the end of the queue's + * last track has simply finished. Anything else is left for the watchdog + * to judge, as it would for a renderer that says nothing. + */ + fun queueState(): RemoteStallWatchdog.QueueState = + if (endedOnLastPoll && currentIndex == queue.lastIndex) { + RemoteStallWatchdog.QueueState.COMPLETE + } else { + RemoteStallWatchdog.QueueState.UNKNOWN + } + + private suspend fun start( + transport: AVTransportClient, + index: Int, + ): Boolean { + if (index !in queue.indices) return false + val token = mint(index) + transport.setAVTransportURIWithMetadata(token.url, token.mime, token.title) + transport.play() + pointedAt(index, token.url) + armNext(transport) + return true + } + + private fun pointedAt( + index: Int, + uri: String, + ) { + currentIndex = index + currentUri = uri armedNextIndex = -1 armedNextUri = "" - armNext(transport) - true + armRetryPolls = 0 + endedOnLastPoll = false + endDetector.reset() } - /** - * One poll's reading of the renderer. Follows a renderer that moved on by - * itself, re-tries arming the next track, and starts the next track when - * the current one has played to its end. - */ - suspend fun onPoll( - transport: AVTransportClient, - trackUri: String, - state: TransportState, - positionMs: Long, - durationMs: Long, - playIntent: Boolean, - ): PollOutcome = mutex.withLock { - if (currentIndex !in queue.indices) return@withLock PollOutcome(0, advanced = false) - val moved = followRenderer(trackUri) - armNext(transport) - if (moved) return@withLock PollOutcome(currentIndex + 1, advanced = false, knownDurationMs(queue, currentIndex)) - endedOnLastPoll = endDetector.onPoll(state, positionMs, durationMs, knownDurationMs(queue, currentIndex)) - val next = currentIndex + 1 - val advance = endedOnLastPoll && playIntent && next in queue.indices - if (advance) { - Timber.w("UPnP single-track: track %d ended; starting %d", currentIndex + 1, next + 1) - runCatching { start(transport, next) } - .onFailure { Timber.w(it, "UPnP single-track: could not start track %d", next + 1) } - } - PollOutcome(currentIndex + 1, advanced = advance, knownDurationMs(queue, currentIndex)) - } - - /** - * For the stall watchdog: a renderer stopped at the end of the queue's - * last track has simply finished. Anything else is left for the watchdog - * to judge, as it would for a renderer that says nothing. - */ - fun queueState(): RemoteStallWatchdog.QueueState = - if (endedOnLastPoll && currentIndex == queue.lastIndex) { - RemoteStallWatchdog.QueueState.COMPLETE - } else { - RemoteStallWatchdog.QueueState.UNKNOWN + /** + * Update [currentIndex] when the renderer's URI says it is playing + * something other than the track we started. The armed next URI is the + * common case (it advanced by itself); otherwise the track id in the URI + * is looked up, for a renderer that was re-pointed some other way. + * Returns true when the index moved. + */ + private fun followRenderer(trackUri: String): Boolean { + val idx = + when { + trackUri.isEmpty() || trackUri == currentUri -> null + trackUri == armedNextUri -> armedNextIndex + else -> streamUriTrackId(trackUri)?.let { nearestIndexOf(queue, it, currentIndex + 1) } + } + if (idx == null || idx == currentIndex) return false + Timber.w("UPnP single-track: renderer moved on to track %d", idx + 1) + pointedAt(idx, trackUri) + return true } - private suspend fun start(transport: AVTransportClient, index: Int): Boolean { - if (index !in queue.indices) return false - val token = mint(index) - transport.setAVTransportURIWithMetadata(token.url, token.mime, token.title) - transport.play() - pointedAt(index, token.url) - armNext(transport) - return true - } - - private fun pointedAt(index: Int, uri: String) { - currentIndex = index - currentUri = uri - armedNextIndex = -1 - armedNextUri = "" - armRetryPolls = 0 - endedOnLastPoll = false - endDetector.reset() - } - - /** - * Update [currentIndex] when the renderer's URI says it is playing - * something other than the track we started. The armed next URI is the - * common case (it advanced by itself); otherwise the track id in the URI - * is looked up, for a renderer that was re-pointed some other way. - * Returns true when the index moved. - */ - private fun followRenderer(trackUri: String): Boolean { - val idx = when { - trackUri.isEmpty() || trackUri == currentUri -> null - trackUri == armedNextUri -> armedNextIndex - else -> streamUriTrackId(trackUri)?.let { nearestIndexOf(queue, it, currentIndex + 1) } - } - if (idx == null || idx == currentIndex) return false - Timber.w("UPnP single-track: renderer moved on to track %d", idx + 1) - pointedAt(idx, trackUri) - return true - } - - private suspend fun armNext(transport: AVTransportClient) { - val next = currentIndex + 1 - if (nextUnsupported || next !in queue.indices || next == armedNextIndex) return - if (armRetryPolls > 0) { - armRetryPolls -= 1 - return - } - runCatching { - val token = mint(next) - transport.setNextAVTransportURI(token.url, token.mime, token.title) - token.url - }.onSuccess { url -> - armedNextIndex = next - armedNextUri = url - }.onFailure { e -> - if (e is SoapFaultException) { - // The renderer answered: it has no SetNext. The app advances it. - Timber.w("UPnP single-track: SetNext refused (%s); advancing from the app", e.code) - nextUnsupported = true - } else { - Timber.w(e, "UPnP single-track: SetNext failed; retrying later") - armRetryPolls = ARM_RETRY_POLLS + private suspend fun armNext(transport: AVTransportClient) { + val next = currentIndex + 1 + if (nextUnsupported || next !in queue.indices || next == armedNextIndex) return + if (armRetryPolls > 0) { + armRetryPolls -= 1 + return + } + runCatching { + val token = mint(next) + transport.setNextAVTransportURI(token.url, token.mime, token.title) + token.url + }.onSuccess { url -> + armedNextIndex = next + armedNextUri = url + }.onFailure { e -> + if (e is SoapFaultException) { + // The renderer answered: it has no SetNext. The app advances it. + Timber.w("UPnP single-track: SetNext refused (%s); advancing from the app", e.code) + nextUnsupported = true + } else { + Timber.w(e, "UPnP single-track: SetNext failed; retrying later") + armRetryPolls = ARM_RETRY_POLLS + } } } - } - // Prerender both: the current track is about to be fetched, and the next - // one is fetched the moment the renderer moves on. - private suspend fun mint(index: Int) = streamTokens.mint( - queue[index].id, - asAlbum = SonosQueueLoader.playingAsAlbum(queue, index), - prerender = true, - ) + // Prerender both: the current track is about to be fetched, and the next + // one is fetched the moment the renderer moves on. + private suspend fun mint(index: Int) = + streamTokens.mint( + queue[index].id, + asAlbum = SonosQueueLoader.playingAsAlbum(queue, index), + prerender = true, + ) - private companion object { - const val ARM_RETRY_POLLS = 10 + private companion object { + const val ARM_RETRY_POLLS = 10 + } } -} /** The library's duration of [queue]'s track at [index], or 0 when there is none. */ -private fun knownDurationMs(queue: List, index: Int): Long = - queue.getOrNull(index)?.durationSec?.times(MILLIS_PER_SECOND) ?: 0L +private fun knownDurationMs( + queue: List, + index: Int, +): Long = queue.getOrNull(index)?.durationSec?.times(MILLIS_PER_SECOND) ?: 0L /** * Index in [queue] of the track with [id], taking the occurrence nearest * [preferNear] so a track queued twice does not send the cursor across the * queue. Null when [id] is not queued. */ -internal fun nearestIndexOf(queue: List, id: String, preferNear: Int): Int? = - queue.indices.filter { queue[it].id == id }.minByOrNull { abs(it - preferNear) } +internal fun nearestIndexOf( + queue: List, + id: String, + preferNear: Int, +): Int? = queue.indices.filter { queue[it].id == id }.minByOrNull { abs(it - preferNear) } /** The track id in a `.../api/tracks/{id}/stream...` URL, or null for any other URL. */ internal fun streamUriTrackId(uri: String): String? { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/SonosQueueLoader.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/SonosQueueLoader.kt index 54e17d3a..87f12b8b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/SonosQueueLoader.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/SonosQueueLoader.kt @@ -32,332 +32,359 @@ import javax.inject.Singleton * one after it are rendered ahead; the rest render when the speaker asks. */ @Singleton -class SonosQueueLoader @Inject constructor( - @ApplicationScope private val scope: CoroutineScope, - private val streamTokens: StreamTokenProvider, - private val activeUpnpHolder: ActiveUpnpHolder, - private val remoteState: RemotePlayerState, -) { - // The queue as last sent to the renderer, for looking up the track after - // the one it is playing. - @Volatile private var sent: List = emptyList() - - // The renderer track the next one was last prerendered for. - @Volatile private var prerenderedAfter = 0 - - suspend fun load( - transport: AVTransportClient, - route: OutputRoute, - queue: List, - currentIndex: Int, +class SonosQueueLoader + @Inject + constructor( + @ApplicationScope private val scope: CoroutineScope, + private val streamTokens: StreamTokenProvider, + private val activeUpnpHolder: ActiveUpnpHolder, + private val remoteState: RemotePlayerState, ) { - Timber.w("UPnP select: clear queue on %s", route.name) - transport.removeAllTracksFromQueue() - val initialEnd = (currentIndex + 1).coerceAtMost(queue.size) - val initialBatch = queue.subList(0, initialEnd) - Timber.w( - "UPnP select: add %d initial tracks (currentIndex=%d, totalQueue=%d)", - initialBatch.size, currentIndex, queue.size, - ) - sent = queue - prerenderedAfter = currentIndex + 1 - initialBatch.indices.forEach { idx -> - val token = mint(queue, idx, prerender = idx == currentIndex) - transport.addURIToQueue( - uri = token.url, - mime = token.mime, - title = token.title, - enqueuedURIPosition = idx + 1, + // The queue as last sent to the renderer, for looking up the track after + // the one it is playing. + @Volatile private var sent: List = emptyList() + + // The renderer track the next one was last prerendered for. + @Volatile private var prerenderedAfter = 0 + + suspend fun load( + transport: AVTransportClient, + route: OutputRoute, + queue: List, + currentIndex: Int, + ) { + Timber.w("UPnP select: clear queue on %s", route.name) + transport.removeAllTracksFromQueue() + val initialEnd = (currentIndex + 1).coerceAtMost(queue.size) + val initialBatch = queue.subList(0, initialEnd) + Timber.w( + "UPnP select: add %d initial tracks (currentIndex=%d, totalQueue=%d)", + initialBatch.size, + currentIndex, + queue.size, ) - } - val coordinatorUdn = route.id.bareUdn() - val queueUri = "x-rincon-queue:$coordinatorUdn#0" - Timber.w("UPnP select: SetAVTransportURI %s", queueUri) - transport.setAVTransportURI(queueUri, "") - Timber.w("UPnP select: Seek to track %d", currentIndex + 1) - transport.seekToTrack(currentIndex + 1) - Timber.w("UPnP select: Play") - transport.play() - Timber.w("UPnP select: initial done; backgrounding remainder") - // Verify even when there is no tail to append: the initial batch is - // sent the same way and can be dropped the same way. - scope.launch { - prerender(queue, currentIndex + 1) - if (initialEnd < queue.size) { - extendQueueOnSonos(transport, route, queue, initialEnd) + sent = queue + prerenderedAfter = currentIndex + 1 + initialBatch.indices.forEach { idx -> + val token = mint(queue, idx, prerender = idx == currentIndex) + transport.addURIToQueue( + uri = token.url, + mime = token.mime, + title = token.title, + enqueuedURIPosition = idx + 1, + ) + } + val coordinatorUdn = route.id.bareUdn() + val queueUri = "x-rincon-queue:$coordinatorUdn#0" + Timber.w("UPnP select: SetAVTransportURI %s", queueUri) + transport.setAVTransportURI(queueUri, "") + Timber.w("UPnP select: Seek to track %d", currentIndex + 1) + transport.seekToTrack(currentIndex + 1) + Timber.w("UPnP select: Play") + transport.play() + Timber.w("UPnP select: initial done; backgrounding remainder") + // Verify even when there is no tail to append: the initial batch is + // sent the same way and can be dropped the same way. + scope.launch { + prerender(queue, currentIndex + 1) + if (initialEnd < queue.size) { + extendQueueOnSonos(transport, route, queue, initialEnd) + } + verifyQueueLength(transport, route, queue) } - verifyQueueLength(transport, route, queue) } - } - /** - * Background-append tracks after activation. Runs concurrently with Sonos - * playback. Cancels if the user disconnects from this route (active.routeId - * changes or becomes null). Correctness of the result is [verifyQueueLength]'s - * job, not this function's. - */ - private suspend fun extendQueueOnSonos( - transport: AVTransportClient, - route: OutputRoute, - queue: List, - startPosition: Int, - ) { - val count = queue.size - startPosition - Timber.w( - "UPnP extend: appending %d tracks starting at position %d", - count, startPosition + 1, - ) - val succeeded = appendTracksToQueue(transport, route, queue, startPosition) - Timber.w("UPnP extend: done (%d / %d appended)", succeeded, count) - } + /** + * Background-append tracks after activation. Runs concurrently with Sonos + * playback. Cancels if the user disconnects from this route (active.routeId + * changes or becomes null). Correctness of the result is [verifyQueueLength]'s + * job, not this function's. + */ + private suspend fun extendQueueOnSonos( + transport: AVTransportClient, + route: OutputRoute, + queue: List, + startPosition: Int, + ) { + val count = queue.size - startPosition + Timber.w( + "UPnP extend: appending %d tracks starting at position %d", + count, + startPosition + 1, + ) + val succeeded = appendTracksToQueue(transport, route, queue, startPosition) + Timber.w("UPnP extend: done (%d / %d appended)", succeeded, count) + } - /** - * Confirm the renderer holds as many tracks as we sent, and append the - * tail it dropped. - * - * [appendTracksToQueue] tolerates individual failures and gives up after - * [EXTEND_ABORT_AFTER_FAILURES] consecutive ones, because Sonos rate-limits - * burst adds. Some tracks loaded beats none, but it leaves the renderer - * holding a queue shorter than ours; unchecked, the renderer plays what - * it has and stops, which looks exactly like playback dying for no - * reason. - * - * Sonos appends sequentially, so a short queue means a missing tail: taking - * `fullQueue.drop(nrTracks)` is the gap. Bounded at [VERIFY_ROUNDS] passes - * so a renderer that refuses to grow can't spin here forever. - */ - @Suppress("ReturnCount") // each bail-out is a distinct reason to stop verifying - private suspend fun verifyQueueLength( - transport: AVTransportClient, - route: OutputRoute, - fullQueue: List, - ) { - repeat(VERIFY_ROUNDS) { round -> - if (activeUpnpHolder.active.value?.routeId != route.id) return - val nrTracks = runCatching { transport.getMediaInfo().nrTracks } - .getOrElse { e -> - Timber.w(e, "UPnP verify: GetMediaInfo failed on %s", route.name) + /** + * Confirm the renderer holds as many tracks as we sent, and append the + * tail it dropped. + * + * [appendTracksToQueue] tolerates individual failures and gives up after + * [EXTEND_ABORT_AFTER_FAILURES] consecutive ones, because Sonos rate-limits + * burst adds. Some tracks loaded beats none, but it leaves the renderer + * holding a queue shorter than ours; unchecked, the renderer plays what + * it has and stops, which looks exactly like playback dying for no + * reason. + * + * Sonos appends sequentially, so a short queue means a missing tail: taking + * `fullQueue.drop(nrTracks)` is the gap. Bounded at [VERIFY_ROUNDS] passes + * so a renderer that refuses to grow can't spin here forever. + */ + @Suppress("ReturnCount") // each bail-out is a distinct reason to stop verifying + private suspend fun verifyQueueLength( + transport: AVTransportClient, + route: OutputRoute, + fullQueue: List, + ) { + repeat(VERIFY_ROUNDS) { round -> + if (activeUpnpHolder.active.value?.routeId != route.id) return + val nrTracks = + runCatching { transport.getMediaInfo().nrTracks } + .getOrElse { e -> + Timber.w(e, "UPnP verify: GetMediaInfo failed on %s", route.name) + return + } + // 0 means the renderer told us nothing usable, not that its queue + // is empty. Guessing "empty" here would re-send the whole queue to + // a renderer that is playing it perfectly well. + if (nrTracks <= 0) { + Timber.w("UPnP verify: no usable NrTracks from %s; skipping", route.name) return } - // 0 means the renderer told us nothing usable, not that its queue - // is empty. Guessing "empty" here would re-send the whole queue to - // a renderer that is playing it perfectly well. - if (nrTracks <= 0) { - Timber.w("UPnP verify: no usable NrTracks from %s; skipping", route.name) - return - } - if (nrTracks >= fullQueue.size) { - Timber.w("UPnP verify: renderer holds %d tracks, queue intact", nrTracks) - return - } - Timber.w( - "UPnP verify: %s holds %d of %d tracks; appending %d missing (round %d)", - route.name, nrTracks, fullQueue.size, fullQueue.size - nrTracks, round + 1, - ) - appendTracksToQueue(transport, route, fullQueue, nrTracks) - } - Timber.w("UPnP verify: gave up repairing queue length on %s", route.name) - } - - /** - * Append [queue] from [startPosition] (0-based) on, returning how many landed. - * Tolerates individual AddURIToQueue failures — log and continue so some - * tracks loaded is better than zero tracks loaded — and stops early after - * [EXTEND_ABORT_AFTER_FAILURES] consecutive ones. - */ - private suspend fun appendTracksToQueue( - transport: AVTransportClient, - route: OutputRoute, - queue: List, - startPosition: Int, - ): Int { - var consecutiveFailures = 0 - var succeeded = 0 - var aborted = false - for (i in 0 until queue.size - startPosition) { - if (aborted) break - if (activeUpnpHolder.active.value?.routeId != route.id) { - Timber.w("UPnP extend: cancelled at offset %d (route changed)", i) - aborted = true - } else { - val outcome = runCatching { - val token = mint(queue, startPosition + i) - transport.addURIToQueue( - uri = token.url, - mime = token.mime, - title = token.title, - enqueuedURIPosition = startPosition + i + 1, - ) + if (nrTracks >= fullQueue.size) { + Timber.w("UPnP verify: renderer holds %d tracks, queue intact", nrTracks) + return } - if (outcome.isSuccess) { - consecutiveFailures = 0 - succeeded += 1 - // Throttle the burst so Sonos's burst-add rejection does not - // kick in (rapid adds start failing in a run, which looks like a - // rate limit). The delay is small enough that extending 100 - // tracks adds only ~5s to background work that's already async. - delay(EXTEND_THROTTLE_MS) + Timber.w( + "UPnP verify: %s holds %d of %d tracks; appending %d missing (round %d)", + route.name, + nrTracks, + fullQueue.size, + fullQueue.size - nrTracks, + round + 1, + ) + appendTracksToQueue(transport, route, fullQueue, nrTracks) + } + Timber.w("UPnP verify: gave up repairing queue length on %s", route.name) + } + + /** + * Append [queue] from [startPosition] (0-based) on, returning how many landed. + * Tolerates individual AddURIToQueue failures — log and continue so some + * tracks loaded is better than zero tracks loaded — and stops early after + * [EXTEND_ABORT_AFTER_FAILURES] consecutive ones. + */ + private suspend fun appendTracksToQueue( + transport: AVTransportClient, + route: OutputRoute, + queue: List, + startPosition: Int, + ): Int { + var consecutiveFailures = 0 + var succeeded = 0 + var aborted = false + for (i in 0 until queue.size - startPosition) { + if (aborted) break + if (activeUpnpHolder.active.value?.routeId != route.id) { + Timber.w("UPnP extend: cancelled at offset %d (route changed)", i) + aborted = true } else { - consecutiveFailures += 1 - val e = outcome.exceptionOrNull() - val detail = (e as? SoapFaultException)?.let { - "code=${it.code} desc=${it.description}" - } ?: e?.message - Timber.w(e, "UPnP extend: append failed at offset %d -- %s", i, detail) - if (consecutiveFailures >= EXTEND_ABORT_AFTER_FAILURES) { - Timber.w( - "UPnP extend: aborting after %d consecutive failures", - consecutiveFailures, - ) - aborted = true + val outcome = + runCatching { + val token = mint(queue, startPosition + i) + transport.addURIToQueue( + uri = token.url, + mime = token.mime, + title = token.title, + enqueuedURIPosition = startPosition + i + 1, + ) + } + if (outcome.isSuccess) { + consecutiveFailures = 0 + succeeded += 1 + // Throttle the burst so Sonos's burst-add rejection does not + // kick in (rapid adds start failing in a run, which looks like a + // rate limit). The delay is small enough that extending 100 + // tracks adds only ~5s to background work that's already async. + delay(EXTEND_THROTTLE_MS) + } else { + consecutiveFailures += 1 + val e = outcome.exceptionOrNull() + val detail = + (e as? SoapFaultException)?.let { + "code=${it.code} desc=${it.description}" + } ?: e?.message + Timber.w(e, "UPnP extend: append failed at offset %d -- %s", i, detail) + if (consecutiveFailures >= EXTEND_ABORT_AFTER_FAILURES) { + Timber.w( + "UPnP extend: aborting after %d consecutive failures", + consecutiveFailures, + ) + aborted = true + } } } } + return succeeded } - return succeeded - } - /** - * Diff-based incremental Sonos queue sync. Returns true when the new - * queue can be produced from the old one with a remove-then-insert at - * the same middle slice -- the common-prefix and common-suffix portions - * stay untouched, and the current Sonos track must lie in the preserved - * prefix (otherwise the diff would orphan playback). Returns false to - * signal the caller to fall back to a full reload. - */ - suspend fun tryIncrementalResync( - transport: AVTransportClient, - oldIds: List, - newQueue: List, - ): Boolean { - val newIds = newQueue.map { it.id } - sent = newQueue - if (oldIds == newIds) return true - val prefixLen = commonPrefixLength(oldIds, newIds) - val suffixLen = commonSuffixLength( - oldIds.subList(prefixLen, oldIds.size), - newIds.subList(prefixLen, newIds.size), - ) - val removedCount = oldIds.size - prefixLen - suffixLen - val addedCount = newIds.size - prefixLen - suffixLen - // Sonos's current track number is 1-based; compare against the - // preserved-prefix range as 0-based. If the current track is in - // the removed slice, incremental can't preserve playback -- caller - // falls back to full rebuild. - val currentSonosIdx0 = remoteState.trackNumber - 1 - val canApply = currentSonosIdx0 in 0 until prefixLen - if (canApply) { - applyQueueDiff(transport, newQueue, prefixLen, removedCount, addedCount) - } else { - Timber.w( - "Sonos incremental: current track %d not in preserved prefix [0,%d); full rebuild", - currentSonosIdx0, - prefixLen, - ) - } - return canApply - } - - private suspend fun applyQueueDiff( - transport: AVTransportClient, - newQueue: List, - prefixLen: Int, - removedCount: Int, - addedCount: Int, - ) { - if (removedCount > 0) { - Timber.w( - "Sonos incremental: RemoveTrackRangeFromQueue start=%d count=%d", - prefixLen + 1, - removedCount, - ) - transport.removeTrackRangeFromQueue( - startingIndex = prefixLen + 1, - numberOfTracks = removedCount, - ) - } - if (addedCount == 0) return - Timber.w( - "Sonos incremental: AddURIToQueue x%d starting at position %d", - addedCount, - prefixLen + 1, - ) - for (i in 0 until addedCount) { - val token = mint(newQueue, prefixLen + i) - transport.addURIToQueue( - uri = token.url, - mime = token.mime, - title = token.title, - enqueuedURIPosition = prefixLen + i + 1, - ) - if (i > 0) delay(EXTEND_THROTTLE_MS) - } - } - - /** - * Called on every poll with the renderer's 1-based track number. When it - * moves, the track after it is rendered ahead, so the speaker's fetch of - * it finds the render ready. - */ - fun onRendererTrack(trackNumber: Int) { - if (trackNumber <= 0 || trackNumber == prerenderedAfter) return - prerenderedAfter = trackNumber - val queue = sent - scope.launch { prerender(queue, trackNumber) } - } - - private suspend fun prerender(queue: List, index: Int) { - if (index !in queue.indices) return - runCatching { mint(queue, index, prerender = true) } - .onFailure { Timber.w(it, "UPnP prerender failed for %s", queue[index].id) } - } - - private suspend fun mint(queue: List, index: Int, prerender: Boolean = false) = - streamTokens.mint(queue[index].id, asAlbum = playingAsAlbum(queue, index), prerender = prerender) - - private fun commonPrefixLength(a: List, b: List): Int { - val limit = minOf(a.size, b.size) - for (i in 0 until limit) { - if (a[i] != b[i]) return i - } - return limit - } - - private fun commonSuffixLength(a: List, b: List): Int { - val limit = minOf(a.size, b.size) - for (i in 0 until limit) { - if (a[a.size - 1 - i] != b[b.size - 1 - i]) return i - } - return limit - } - - companion object { /** - * Whether [queue]'s track at [index] plays among its album in order, - * judged by its neighbours in the renderer's queue, which plays - * straight through. + * Diff-based incremental Sonos queue sync. Returns true when the new + * queue can be produced from the old one with a remove-then-insert at + * the same middle slice -- the common-prefix and common-suffix portions + * stay untouched, and the current Sonos track must lie in the preserved + * prefix (otherwise the diff would orphan playback). Returns false to + * signal the caller to fall back to a full reload. */ - internal fun playingAsAlbum(queue: List, index: Int): Boolean = - GainMath.playingAsAlbum( - prev = queue.getOrNull(index - 1)?.let(::position), - cur = position(queue[index]), - next = queue.getOrNull(index + 1)?.let(::position), + suspend fun tryIncrementalResync( + transport: AVTransportClient, + oldIds: List, + newQueue: List, + ): Boolean { + val newIds = newQueue.map { it.id } + sent = newQueue + if (oldIds == newIds) return true + val prefixLen = commonPrefixLength(oldIds, newIds) + val suffixLen = + commonSuffixLength( + oldIds.subList(prefixLen, oldIds.size), + newIds.subList(prefixLen, newIds.size), + ) + val removedCount = oldIds.size - prefixLen - suffixLen + val addedCount = newIds.size - prefixLen - suffixLen + // Sonos's current track number is 1-based; compare against the + // preserved-prefix range as 0-based. If the current track is in + // the removed slice, incremental can't preserve playback -- caller + // falls back to full rebuild. + val currentSonosIdx0 = remoteState.trackNumber - 1 + val canApply = currentSonosIdx0 in 0 until prefixLen + if (canApply) { + applyQueueDiff(transport, newQueue, prefixLen, removedCount, addedCount) + } else { + Timber.w( + "Sonos incremental: current track %d not in preserved prefix [0,%d); full rebuild", + currentSonosIdx0, + prefixLen, + ) + } + return canApply + } + + private suspend fun applyQueueDiff( + transport: AVTransportClient, + newQueue: List, + prefixLen: Int, + removedCount: Int, + addedCount: Int, + ) { + if (removedCount > 0) { + Timber.w( + "Sonos incremental: RemoveTrackRangeFromQueue start=%d count=%d", + prefixLen + 1, + removedCount, + ) + transport.removeTrackRangeFromQueue( + startingIndex = prefixLen + 1, + numberOfTracks = removedCount, + ) + } + if (addedCount == 0) return + Timber.w( + "Sonos incremental: AddURIToQueue x%d starting at position %d", + addedCount, + prefixLen + 1, ) + for (i in 0 until addedCount) { + val token = mint(newQueue, prefixLen + i) + transport.addURIToQueue( + uri = token.url, + mime = token.mime, + title = token.title, + enqueuedURIPosition = prefixLen + i + 1, + ) + if (i > 0) delay(EXTEND_THROTTLE_MS) + } + } - private fun position(t: TrackRef) = - AlbumPosition(t.albumId.ifEmpty { null }, t.discNumber, t.trackNumber) + /** + * Called on every poll with the renderer's 1-based track number. When it + * moves, the track after it is rendered ahead, so the speaker's fetch of + * it finds the render ready. + */ + fun onRendererTrack(trackNumber: Int) { + if (trackNumber <= 0 || trackNumber == prerenderedAfter) return + prerenderedAfter = trackNumber + val queue = sent + scope.launch { prerender(queue, trackNumber) } + } - // Abort the append loop after this many consecutive AddURIToQueue - // failures; Sonos rate-limits burst adds and a wall of failures means - // it has stopped accepting, not that the next one might land. - private const val EXTEND_ABORT_AFTER_FAILURES = 3 - private const val EXTEND_THROTTLE_MS = 50L + private suspend fun prerender( + queue: List, + index: Int, + ) { + if (index !in queue.indices) return + runCatching { mint(queue, index, prerender = true) } + .onFailure { Timber.w(it, "UPnP prerender failed for %s", queue[index].id) } + } - // Verify/repair passes after a queue load. Two: one to catch the - // common case (a rate-limit burst dropped a chunk), one to catch a - // repair that itself got rate-limited. Beyond that the renderer is - // refusing for a reason retrying won't fix, and the stall watchdog - // becomes the backstop. - private const val VERIFY_ROUNDS = 2 + private suspend fun mint( + queue: List, + index: Int, + prerender: Boolean = false, + ) = streamTokens.mint(queue[index].id, asAlbum = playingAsAlbum(queue, index), prerender = prerender) + + private fun commonPrefixLength( + a: List, + b: List, + ): Int { + val limit = minOf(a.size, b.size) + for (i in 0 until limit) { + if (a[i] != b[i]) return i + } + return limit + } + + private fun commonSuffixLength( + a: List, + b: List, + ): Int { + val limit = minOf(a.size, b.size) + for (i in 0 until limit) { + if (a[a.size - 1 - i] != b[b.size - 1 - i]) return i + } + return limit + } + + companion object { + /** + * Whether [queue]'s track at [index] plays among its album in order, + * judged by its neighbours in the renderer's queue, which plays + * straight through. + */ + internal fun playingAsAlbum( + queue: List, + index: Int, + ): Boolean = + GainMath.playingAsAlbum( + prev = queue.getOrNull(index - 1)?.let(::position), + cur = position(queue[index]), + next = queue.getOrNull(index + 1)?.let(::position), + ) + + private fun position(t: TrackRef) = AlbumPosition(t.albumId.ifEmpty { null }, t.discNumber, t.trackNumber) + + // Abort the append loop after this many consecutive AddURIToQueue + // failures; Sonos rate-limits burst adds and a wall of failures means + // it has stopped accepting, not that the next one might land. + private const val EXTEND_ABORT_AFTER_FAILURES = 3 + private const val EXTEND_THROTTLE_MS = 50L + + // Verify/repair passes after a queue load. Two: one to catch the + // common case (a rate-limit burst dropped a chunk), one to catch a + // repair that itself got rate-limited. Beyond that the renderer is + // refusing for a reason retrying won't fix, and the stall watchdog + // becomes the backstop. + private const val VERIFY_ROUNDS = 2 + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/TrackEndDetector.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/TrackEndDetector.kt index 5efd09b3..0cc588a6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/TrackEndDetector.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/TrackEndDetector.kt @@ -19,7 +19,6 @@ import com.fabledsword.minstrel.player.output.upnp.TransportState * Pure state, no SOAP: [SingleTrackLoader] feeds it each poll. */ internal class TrackEndDetector { - private var sawPlaying = false private var lastPlayingPositionMs = 0L private var durationMs = 0L diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClient.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClient.kt index aecb3a90..d67911ed 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClient.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClient.kt @@ -2,6 +2,8 @@ package com.fabledsword.minstrel.player.output.upnp import okhttp3.HttpUrl +// One method per AVTransport SOAP verb; splitting would obscure the 1:1 protocol mapping. + /** * High-level wrapper for the UPnP AVTransport service. * Covers SetAVTransportURI / SetNextAVTransportURI / Play / Pause / Stop / @@ -13,23 +15,26 @@ import okhttp3.HttpUrl * DIDL-Lite every track is described with, so it is fixed at construction * rather than chosen per call. */ -// One method per AVTransport SOAP verb; splitting would obscure the 1:1 protocol mapping. @Suppress("TooManyFunctions") class AVTransportClient( private val soap: SoapClient, private val controlUrl: HttpUrl, private val sonos: Boolean, ) { - suspend fun setAVTransportURI(uri: String, metadata: String = "") { + suspend fun setAVTransportURI( + uri: String, + metadata: String = "", + ) { soap.call( controlUrl = controlUrl, serviceType = SERVICE_TYPE, action = "SetAVTransportURI", - args = mapOf( - "InstanceID" to "0", - "CurrentURI" to uri, - "CurrentURIMetaData" to metadata, - ), + args = + mapOf( + "InstanceID" to "0", + "CurrentURI" to uri, + "CurrentURIMetaData" to metadata, + ), ) } @@ -49,7 +54,11 @@ class AVTransportClient( * [buildDidlLite]. Title falls back to "Minstrel" when the caller * doesn't supply one. */ - suspend fun setAVTransportURIWithMetadata(uri: String, mime: String, title: String) { + suspend fun setAVTransportURIWithMetadata( + uri: String, + mime: String, + title: String, + ) { val safeTitle = title.ifBlank { "Minstrel" } setAVTransportURI(uri, buildDidlLite(uri, mime, safeTitle)) } @@ -60,16 +69,21 @@ class AVTransportClient( * UPnP spec: a renderer without it faults (401 Invalid Action, or 602 * Not Implemented), and the caller then advances the renderer itself. */ - suspend fun setNextAVTransportURI(uri: String, mime: String, title: String) { + suspend fun setNextAVTransportURI( + uri: String, + mime: String, + title: String, + ) { soap.call( controlUrl = controlUrl, serviceType = SERVICE_TYPE, action = "SetNextAVTransportURI", - args = mapOf( - "InstanceID" to "0", - "NextURI" to uri, - "NextURIMetaData" to buildDidlLite(uri, mime, title), - ), + args = + mapOf( + "InstanceID" to "0", + "NextURI" to uri, + "NextURIMetaData" to buildDidlLite(uri, mime, title), + ), ) } @@ -98,17 +112,21 @@ class AVTransportClient( * queue resync path (radio-append: remove tail, then AddURIToQueue * the new items). */ - suspend fun removeTrackRangeFromQueue(startingIndex: Int, numberOfTracks: Int) { + suspend fun removeTrackRangeFromQueue( + startingIndex: Int, + numberOfTracks: Int, + ) { soap.call( controlUrl = controlUrl, serviceType = SERVICE_TYPE, action = "RemoveTrackRangeFromQueue", - args = mapOf( - "InstanceID" to "0", - "UpdateID" to "0", - "StartingIndex" to startingIndex.toString(), - "NumberOfTracks" to numberOfTracks.toString(), - ), + args = + mapOf( + "InstanceID" to "0", + "UpdateID" to "0", + "StartingIndex" to startingIndex.toString(), + "NumberOfTracks" to numberOfTracks.toString(), + ), ) } @@ -133,13 +151,14 @@ class AVTransportClient( controlUrl = controlUrl, serviceType = SERVICE_TYPE, action = "AddURIToQueue", - args = mapOf( - "InstanceID" to "0", - "EnqueuedURI" to uri, - "EnqueuedURIMetaData" to didl, - "DesiredFirstTrackNumberEnqueued" to enqueuedURIPosition.toString(), - "EnqueueAsNext" to "0", - ), + args = + mapOf( + "InstanceID" to "0", + "EnqueuedURI" to uri, + "EnqueuedURIMetaData" to didl, + "DesiredFirstTrackNumberEnqueued" to enqueuedURIPosition.toString(), + "EnqueueAsNext" to "0", + ), ) } @@ -173,11 +192,12 @@ class AVTransportClient( controlUrl = controlUrl, serviceType = SERVICE_TYPE, action = "Seek", - args = mapOf( - "InstanceID" to "0", - "Unit" to "TRACK_NR", - "Target" to trackNumber.toString(), - ), + args = + mapOf( + "InstanceID" to "0", + "Unit" to "TRACK_NR", + "Target" to trackNumber.toString(), + ), ) } @@ -213,21 +233,23 @@ class AVTransportClient( controlUrl = controlUrl, serviceType = SERVICE_TYPE, action = "Seek", - args = mapOf( - "InstanceID" to "0", - "Unit" to "REL_TIME", - "Target" to formatHhMmSs(positionMs), - ), + args = + mapOf( + "InstanceID" to "0", + "Unit" to "REL_TIME", + "Target" to formatHhMmSs(positionMs), + ), ) } suspend fun getPositionInfo(): PositionInfo { - val result = soap.call( - controlUrl = controlUrl, - serviceType = SERVICE_TYPE, - action = "GetPositionInfo", - args = mapOf("InstanceID" to "0"), - ) + val result = + soap.call( + controlUrl = controlUrl, + serviceType = SERVICE_TYPE, + action = "GetPositionInfo", + args = mapOf("InstanceID" to "0"), + ) return PositionInfo( track = result["Track"]?.toIntOrNull() ?: 0, trackUri = result["TrackURI"].orEmpty(), @@ -248,12 +270,13 @@ class AVTransportClient( * detect and repair rather than infer. */ suspend fun getMediaInfo(): MediaInfo { - val result = soap.call( - controlUrl = controlUrl, - serviceType = SERVICE_TYPE, - action = "GetMediaInfo", - args = mapOf("InstanceID" to "0"), - ) + val result = + soap.call( + controlUrl = controlUrl, + serviceType = SERVICE_TYPE, + action = "GetMediaInfo", + args = mapOf("InstanceID" to "0"), + ) return MediaInfo( nrTracks = result["NrTracks"]?.toIntOrNull() ?: 0, currentUri = result["CurrentURI"].orEmpty(), @@ -261,20 +284,22 @@ class AVTransportClient( } suspend fun getTransportInfo(): TransportInfo { - val result = soap.call( - controlUrl = controlUrl, - serviceType = SERVICE_TYPE, - action = "GetTransportInfo", - args = mapOf("InstanceID" to "0"), - ) - val state = when (result["CurrentTransportState"]) { - "PLAYING" -> TransportState.PLAYING - "PAUSED_PLAYBACK" -> TransportState.PAUSED - "STOPPED" -> TransportState.STOPPED - "TRANSITIONING" -> TransportState.TRANSITIONING - "NO_MEDIA_PRESENT" -> TransportState.NO_MEDIA - else -> TransportState.UNKNOWN - } + val result = + soap.call( + controlUrl = controlUrl, + serviceType = SERVICE_TYPE, + action = "GetTransportInfo", + args = mapOf("InstanceID" to "0"), + ) + val state = + when (result["CurrentTransportState"]) { + "PLAYING" -> TransportState.PLAYING + "PAUSED_PLAYBACK" -> TransportState.PAUSED + "STOPPED" -> TransportState.STOPPED + "TRANSITIONING" -> TransportState.TRANSITIONING + "NO_MEDIA_PRESENT" -> TransportState.NO_MEDIA + else -> TransportState.UNKNOWN + } // CurrentTransportStatus is the renderer's own verdict on whether it is // healthy, and it is the one unambiguous way to tell "the stream died" // from "somebody pressed stop" — both of which land in STOPPED. The @@ -285,7 +310,11 @@ class AVTransportClient( return TransportInfo(state, statusOk) } - private fun buildDidlLite(uri: String, mime: String, title: String): String { + private fun buildDidlLite( + uri: String, + mime: String, + title: String, + ): String { // Sonos requires (a) the rinconnetworks namespace declared on // even if we don't use Rincon elements directly, and // (b) a element identifying the URI as an @@ -311,7 +340,11 @@ class AVTransportClient( append("").append(xmlEscape(safeTitle)).append("") append("object.item.audioItem.musicTrack") append("").append(xmlEscape(uri)).append("") + append(":") + .append(fourthField) + .append("\">") + .append(xmlEscape(uri)) + .append("") if (sonos) { append("") @@ -364,7 +397,10 @@ data class PositionInfo( * renderer that does not implement GetMediaInfo usefully must not be * mistaken for one with an empty queue. */ -data class MediaInfo(val nrTracks: Int, val currentUri: String) +data class MediaInfo( + val nrTracks: Int, + val currentUri: String, +) /** * [NO_MEDIA] is NO_MEDIA_PRESENT: nothing loaded. Several DLNA renderers land @@ -378,4 +414,7 @@ enum class TransportState { PLAYING, PAUSED, STOPPED, TRANSITIONING, NO_MEDIA, U * that only care about [state] read unchanged and an older/quieter renderer is * never mistaken for a failing one. */ -data class TransportInfo(val state: TransportState, val statusOk: Boolean = true) +data class TransportInfo( + val state: TransportState, + val statusOk: Boolean = true, +) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescription.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescription.kt index 4dcb8f94..28f9706c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescription.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescription.kt @@ -43,11 +43,15 @@ data class DeviceDescription( * Returns null when AVTransport is missing — we have no way * to control the device without it. */ - fun parse(xml: String, base: HttpUrl): DeviceDescription? { - val parser = XmlPullParserFactory.newInstance().newPullParser().apply { - setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) - setInput(xml.reader()) - } + fun parse( + xml: String, + base: HttpUrl, + ): DeviceDescription? { + val parser = + XmlPullParserFactory.newInstance().newPullParser().apply { + setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) + setInput(xml.reader()) + } val acc = ParseState() while (parser.eventType != XmlPullParser.END_DOCUMENT) { handleEvent(parser, acc, base) @@ -65,7 +69,11 @@ data class DeviceDescription( ) } - private fun handleEvent(parser: XmlPullParser, acc: ParseState, base: HttpUrl) { + private fun handleEvent( + parser: XmlPullParser, + acc: ParseState, + base: HttpUrl, + ) { when (parser.eventType) { XmlPullParser.START_TAG -> handleStartTag(parser, acc) XmlPullParser.END_TAG -> handleEndTag(parser, acc, base) @@ -73,7 +81,10 @@ data class DeviceDescription( } } - private fun handleStartTag(parser: XmlPullParser, acc: ParseState) { + private fun handleStartTag( + parser: XmlPullParser, + acc: ParseState, + ) { when (parser.name) { TAG_SERVICE -> { acc.inService = true @@ -89,7 +100,11 @@ data class DeviceDescription( } } - private fun handleEndTag(parser: XmlPullParser, acc: ParseState, base: HttpUrl) { + private fun handleEndTag( + parser: XmlPullParser, + acc: ParseState, + base: HttpUrl, + ) { if (parser.name != TAG_SERVICE) return val resolved = resolveControlUrl(base, acc.serviceControlUrl) when (acc.serviceType) { @@ -100,13 +115,15 @@ data class DeviceDescription( acc.inService = false } - private fun resolveControlUrl(base: HttpUrl, path: String): HttpUrl? { + private fun resolveControlUrl( + base: HttpUrl, + path: String, + ): HttpUrl? { if (path.isBlank()) return null return path.toHttpUrlOrNull() ?: base.resolve(path) } - private fun XmlPullParser.nextTextSafe(): String = - runCatching { nextText() }.getOrDefault("") + private fun XmlPullParser.nextTextSafe(): String = runCatching { nextText() }.getOrDefault("") } /** diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClient.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClient.kt index a5f20c9a..d74e18c5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClient.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClient.kt @@ -13,26 +13,31 @@ class RenderingControlClient( private val controlUrl: HttpUrl, ) { suspend fun getVolume(channel: String = "Master"): Int { - val args = soap.call( - controlUrl = controlUrl, - serviceType = SERVICE_TYPE, - action = "GetVolume", - args = mapOf("InstanceID" to "0", "Channel" to channel), - ) + val args = + soap.call( + controlUrl = controlUrl, + serviceType = SERVICE_TYPE, + action = "GetVolume", + args = mapOf("InstanceID" to "0", "Channel" to channel), + ) return args["CurrentVolume"]?.toIntOrNull() ?: 0 } - suspend fun setVolume(volume: Int, channel: String = "Master") { + suspend fun setVolume( + volume: Int, + channel: String = "Master", + ) { val clamped = volume.coerceIn(VOLUME_MIN, VOLUME_MAX) soap.call( controlUrl = controlUrl, serviceType = SERVICE_TYPE, action = "SetVolume", - args = mapOf( - "InstanceID" to "0", - "Channel" to channel, - "DesiredVolume" to clamped.toString(), - ), + args = + mapOf( + "InstanceID" to "0", + "Channel" to channel, + "DesiredVolume" to clamped.toString(), + ), ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/SoapClient.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/SoapClient.kt index 4a25fde3..355781c5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/SoapClient.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/SoapClient.kt @@ -1,6 +1,5 @@ package com.fabledsword.minstrel.player.output.upnp -import java.util.concurrent.atomic.AtomicInteger import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext import okhttp3.HttpUrl @@ -10,6 +9,7 @@ import okhttp3.RequestBody.Companion.toRequestBody import org.xmlpull.v1.XmlPullParser import org.xmlpull.v1.XmlPullParserFactory import timber.log.Timber +import java.util.concurrent.atomic.AtomicInteger /** * Minimal SOAP/UPnP envelope builder + POST. Hand-rolled rather than @@ -34,50 +34,58 @@ class SoapClient( serviceType: String, action: String, args: Map = emptyMap(), - ): Map = withContext(Dispatchers.IO) { - val envelope = buildEnvelope(serviceType, action, args) - val request = Request.Builder() - .url(controlUrl) - .post(envelope.toRequestBody(null)) - .header("Content-Type", SOAP_CONTENT_TYPE) - .header("SOAPACTION", "\"$serviceType#$action\"") - .build() - okHttp.newCall(request).execute().use { response -> - val body = response.body?.string().orEmpty() - onRawResponse?.invoke(action, body) - if (!response.isSuccessful) { - throw SoapFaultException(faultCodeOf(body), faultDescriptionOf(body)) + ): Map = + withContext(Dispatchers.IO) { + val envelope = buildEnvelope(serviceType, action, args) + val request = + Request + .Builder() + .url(controlUrl) + .post(envelope.toRequestBody(null)) + .header("Content-Type", SOAP_CONTENT_TYPE) + .header("SOAPACTION", "\"$serviceType#$action\"") + .build() + okHttp.newCall(request).execute().use { response -> + val body = response.body?.string().orEmpty() + onRawResponse?.invoke(action, body) + if (!response.isSuccessful) { + throw SoapFaultException(faultCodeOf(body), faultDescriptionOf(body)) + } + parseResponseArgs(body, action) } - parseResponseArgs(body, action) } - } private fun buildEnvelope( serviceType: String, action: String, args: Map, - ): String = buildString { - append("") - append("") - append("") - append("") - args.forEach { (k, v) -> - append("<").append(k).append(">") - append(xmlEscape(v)) - append("") + ): String = + buildString { + append("") + append("") + append("") + append("") + args.forEach { (k, v) -> + append("<").append(k).append(">") + append(xmlEscape(v)) + append("") + } + append("") + append("") + append("") } - append("") - append("") - append("") - } - private fun parseResponseArgs(body: String, action: String): Map { - val parser = XmlPullParserFactory.newInstance().newPullParser().apply { - setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) - setInput(body.reader()) - } + private fun parseResponseArgs( + body: String, + action: String, + ): Map { + val parser = + XmlPullParserFactory.newInstance().newPullParser().apply { + setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) + setInput(body.reader()) + } val responseTag = "${action}Response" val args = mutableMapOf() var inResponse = false @@ -93,22 +101,23 @@ class SoapClient( responseTag: String, inResponse: Boolean, args: MutableMap, - ): Boolean = when (parser.eventType) { - XmlPullParser.START_TAG -> { - if (parser.name == responseTag) { - true - } else { - if (inResponse) { - val name = parser.name - val text = readElementContent(parser, name) - args[name] = text + ): Boolean = + when (parser.eventType) { + XmlPullParser.START_TAG -> { + if (parser.name == responseTag) { + true + } else { + if (inResponse) { + val name = parser.name + val text = readElementContent(parser, name) + args[name] = text + } + inResponse } - inResponse } + XmlPullParser.END_TAG -> if (parser.name == responseTag) false else inResponse + else -> inResponse } - XmlPullParser.END_TAG -> if (parser.name == responseTag) false else inResponse - else -> inResponse - } /** * Read the content of the currently-started element. Try nextText() first @@ -119,13 +128,18 @@ class SoapClient( * Some Sonos firmware sends the GetZoneGroupState payload as nested XML * elements without escaping; this fallback recovers that path. */ - private fun readElementContent(parser: XmlPullParser, tagName: String): String { - return runCatching { parser.nextText() }.getOrElse { + private fun readElementContent( + parser: XmlPullParser, + tagName: String, + ): String = + runCatching { parser.nextText() }.getOrElse { readUntilEndTag(parser, tagName) } - } - private fun readUntilEndTag(parser: XmlPullParser, tagName: String): String { + private fun readUntilEndTag( + parser: XmlPullParser, + tagName: String, + ): String { val sb = StringBuilder() var depth = 1 var done = false @@ -151,10 +165,14 @@ class SoapClient( return sb.toString() } - private fun appendStartTag(sb: StringBuilder, parser: XmlPullParser) { + private fun appendStartTag( + sb: StringBuilder, + parser: XmlPullParser, + ) { sb.append('<').append(parser.name) for (i in 0 until parser.attributeCount) { - sb.append(' ') + sb + .append(' ') .append(parser.getAttributeName(i)) .append("=\"") .append(parser.getAttributeValue(i)) @@ -163,13 +181,15 @@ class SoapClient( sb.append('>') } - private fun faultCodeOf(body: String): String = - extractBetween(body, "", "") ?: "unknown" + private fun faultCodeOf(body: String): String = extractBetween(body, "", "") ?: "unknown" - private fun faultDescriptionOf(body: String): String = - extractBetween(body, "", "").orEmpty() + private fun faultDescriptionOf(body: String): String = extractBetween(body, "", "").orEmpty() - private fun extractBetween(body: String, open: String, close: String): String? { + private fun extractBetween( + body: String, + open: String, + close: String, + ): String? { val start = body.indexOf(open) if (start < 0) return null val contentStart = start + open.length @@ -187,10 +207,12 @@ class SoapClient( * a UPnPError with `errorCode` + `errorDescription`. Code is preserved * as a string (UPnP codes are numeric in spec but we don't constrain). */ -class SoapFaultException(val code: String, val description: String) : - Exception("SOAP fault $code: $description") +class SoapFaultException( + val code: String, + val description: String, +) : Exception("SOAP fault $code: $description") -private const val MAX_DIAGNOSTIC_RESPONSES = 6 // 3 polls x 2 action types +private const val MAX_DIAGNOSTIC_RESPONSES = 6 // 3 polls x 2 action types private const val MAX_BODY_LOG_CHARS = 2048 /** @@ -200,7 +222,10 @@ private const val MAX_BODY_LOG_CHARS = 2048 * callback is a no-op so there is no persistent log spam. Logged at WARN * so release builds capture it without a separate log-level override. */ -internal fun loggingSoapClient(okHttp: OkHttpClient, label: String): SoapClient { +internal fun loggingSoapClient( + okHttp: OkHttpClient, + label: String, +): SoapClient { val counter = AtomicInteger(0) return SoapClient(okHttp) { action, body -> if (action !in DIAGNOSTIC_ACTIONS) return@SoapClient @@ -208,23 +233,27 @@ internal fun loggingSoapClient(okHttp: OkHttpClient, label: String): SoapClient if (n <= MAX_DIAGNOSTIC_RESPONSES) { Timber.w( "UPnP %s response #%d (%s): %s", - label, n, action, + label, + n, + action, body.take(MAX_BODY_LOG_CHARS), ) } } } -private val DIAGNOSTIC_ACTIONS = setOf( - "GetPositionInfo", - "GetTransportInfo", - "GetZoneGroupState", -) +private val DIAGNOSTIC_ACTIONS = + setOf( + "GetPositionInfo", + "GetTransportInfo", + "GetZoneGroupState", + ) /** XML-escapes a string value for embedding as text content inside a SOAP envelope. */ -internal fun xmlEscape(v: String): String = v - .replace("&", "&") - .replace("<", "<") - .replace(">", ">") - .replace("\"", """) - .replace("'", "'") +internal fun xmlEscape(v: String): String = + v + .replace("&", "&") + .replace("<", "<") + .replace(">", ">") + .replace("\"", """) + .replace("'", "'") diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/SsdpDiscovery.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/SsdpDiscovery.kt index 13984112..3542d57e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/SsdpDiscovery.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/SsdpDiscovery.kt @@ -46,24 +46,27 @@ class SsdpDiscovery( fun start(scope: CoroutineScope) { if (listenJob != null) return val wifi = context.getSystemService() ?: return - multicastLock = wifi.createMulticastLock(MULTICAST_LOCK_TAG).apply { - setReferenceCounted(false) - acquire() - } - val sock = MulticastSocket(ANY_LOCAL_PORT).apply { - joinGroup(InetAddress.getByName(SSDP_MULTICAST_ADDR)) - } + multicastLock = + wifi.createMulticastLock(MULTICAST_LOCK_TAG).apply { + setReferenceCounted(false) + acquire() + } + val sock = + MulticastSocket(ANY_LOCAL_PORT).apply { + joinGroup(InetAddress.getByName(SSDP_MULTICAST_ADDR)) + } socket = sock - listenJob = scope.launch(Dispatchers.IO) { - val buf = ByteArray(SOCKET_READ_BUFFER_BYTES) - val packet = DatagramPacket(buf, buf.size) - while (isActive) { - runCatching { sock.receive(packet) }.onSuccess { - val raw = String(packet.data, 0, packet.length, StandardCharsets.UTF_8) - parseLocation(raw)?.let { discoveriesInternal.tryEmit(it) } + listenJob = + scope.launch(Dispatchers.IO) { + val buf = ByteArray(SOCKET_READ_BUFFER_BYTES) + val packet = DatagramPacket(buf, buf.size) + while (isActive) { + runCatching { sock.receive(packet) }.onSuccess { + val raw = String(packet.data, 0, packet.length, StandardCharsets.UTF_8) + parseLocation(raw)?.let { discoveriesInternal.tryEmit(it) } + } } } - } } fun stop() { @@ -80,27 +83,34 @@ class SsdpDiscovery( * Responses arrive on the listener socket and emit via * [discoveries] as their LOCATION URL. */ - suspend fun requestActiveScan() = withContext(Dispatchers.IO) { - val sock = socket ?: return@withContext - val payload = buildMSearchPayload().toByteArray(StandardCharsets.UTF_8) - val packet = DatagramPacket( - payload, - payload.size, - InetAddress.getByName(SSDP_MULTICAST_ADDR), - SSDP_PORT, - ) - runCatching { sock.send(packet) } - Unit - } + suspend fun requestActiveScan() = + withContext(Dispatchers.IO) { + val sock = socket ?: return@withContext + val payload = buildMSearchPayload().toByteArray(StandardCharsets.UTF_8) + val packet = + DatagramPacket( + payload, + payload.size, + InetAddress.getByName(SSDP_MULTICAST_ADDR), + SSDP_PORT, + ) + runCatching { sock.send(packet) } + Unit + } - private fun buildMSearchPayload(): String = buildString { - append("M-SEARCH * HTTP/1.1\r\n") - append("HOST: ").append(SSDP_MULTICAST_ADDR).append(":").append(SSDP_PORT).append("\r\n") - append("MAN: \"ssdp:discover\"\r\n") - append("MX: ").append(MSEARCH_MX_SECONDS).append("\r\n") - append("ST: ").append(MEDIA_RENDERER_TARGET).append("\r\n") - append("\r\n") - } + private fun buildMSearchPayload(): String = + buildString { + append("M-SEARCH * HTTP/1.1\r\n") + append("HOST: ") + .append(SSDP_MULTICAST_ADDR) + .append(":") + .append(SSDP_PORT) + .append("\r\n") + append("MAN: \"ssdp:discover\"\r\n") + append("MX: ").append(MSEARCH_MX_SECONDS).append("\r\n") + append("ST: ").append(MEDIA_RENDERER_TARGET).append("\r\n") + append("\r\n") + } private fun parseLocation(raw: String): String? { raw.lineSequence().forEach { line -> diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpDiscoveryController.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpDiscoveryController.kt index 64d45fa6..823a9dbe 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpDiscoveryController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpDiscoveryController.kt @@ -1,4 +1,5 @@ @file:Suppress("TooManyFunctions") // discovery + Sonos topology + transport-lookup density + package com.fabledsword.minstrel.player.output.upnp import android.content.Context @@ -41,247 +42,260 @@ import javax.inject.Singleton * duplicate row to the picker. */ @Singleton -class UpnpDiscoveryController @Inject constructor( - @ApplicationContext context: Context, - @ApplicationScope private val appScope: CoroutineScope, - private val okHttp: OkHttpClient, -) { - private val ssdp = SsdpDiscovery(context) +class UpnpDiscoveryController + @Inject + constructor( + @ApplicationContext context: Context, + @ApplicationScope private val appScope: CoroutineScope, + private val okHttp: OkHttpClient, + ) { + private val ssdp = SsdpDiscovery(context) - // Transport commands (play/pause/seek/next) and the 1 Hz poll go through - // this client. A dead renderer should fail fast so OutputPickerController's - // drop-recovery reverts to the phone in ~2 s instead of the shared client's - // 10 s connect timeout. Derived via newBuilder() so the connection pool + - // dispatcher stay shared with the app client. - private val controlHttp: OkHttpClient = okHttp.newBuilder() - .connectTimeout(CONTROL_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS) - .build() + // Transport commands (play/pause/seek/next) and the 1 Hz poll go through + // this client. A dead renderer should fail fast so OutputPickerController's + // drop-recovery reverts to the phone in ~2 s instead of the shared client's + // 10 s connect timeout. Derived via newBuilder() so the connection pool + + // dispatcher stay shared with the app client. + private val controlHttp: OkHttpClient = + okHttp + .newBuilder() + .connectTimeout(CONTROL_CONNECT_TIMEOUT_SECONDS, TimeUnit.SECONDS) + .build() - private val routesInternal = MutableStateFlow>(emptyList()) - val routes: StateFlow> = routesInternal.asStateFlow() + private val routesInternal = MutableStateFlow>(emptyList()) + val routes: StateFlow> = routesInternal.asStateFlow() - // Wall-clock of the last NOTIFY / M-SEARCH response per route id. Drives - // post-active-scan pruning so a powered-off renderer leaves the picker - // (and can't pin a stale selection) instead of lingering for the process - // lifetime -- upsert only ever added before. - private val lastSeenMs = ConcurrentHashMap() + // Wall-clock of the last NOTIFY / M-SEARCH response per route id. Drives + // post-active-scan pruning so a powered-off renderer leaves the picker + // (and can't pin a stale selection) instead of lingering for the process + // lifetime -- upsert only ever added before. + private val lastSeenMs = ConcurrentHashMap() - private val sonosTopologyInternal = MutableStateFlow>(emptyList()) - val sonosTopology: StateFlow> = sonosTopologyInternal.asStateFlow() + private val sonosTopologyInternal = MutableStateFlow>(emptyList()) + val sonosTopology: StateFlow> = sonosTopologyInternal.asStateFlow() - init { - ssdp.start(appScope) - // appScope is process-lifetime (SupervisorJob + Dispatchers.Default), - // so the launched collector dies with the process — no explicit - // cancellation needed. - appScope.launch(Dispatchers.IO) { - ssdp.discoveries.collect { locationUrl -> handleDiscovery(locationUrl) } + init { + ssdp.start(appScope) + // appScope is process-lifetime (SupervisorJob + Dispatchers.Default), + // so the launched collector dies with the process — no explicit + // cancellation needed. + appScope.launch(Dispatchers.IO) { + ssdp.discoveries.collect { locationUrl -> handleDiscovery(locationUrl) } + } } - } - /** - * Fire an M-SEARCH burst so newly-paired speakers appear within a - * few seconds rather than waiting for the next NOTIFY beacon - * (typical SSDP cadence: every ~30min — far too slow for a UI - * that just opened). - */ - fun upgradeDiscovery() { - appScope.launch { - val scanStartMs = System.currentTimeMillis() - ssdp.requestActiveScan() - // Give present devices time to answer the M-SEARCH (+ our follow-up - // description fetch), then drop any route that didn't re-announce. - // Pruning is tied to picker-open scans only -- no background timer, - // so route rows never flicker while the user isn't looking. - delay(ACTIVE_SCAN_PRUNE_DELAY_MS) - pruneRoutesNotSeenSince(scanStartMs) + /** + * Fire an M-SEARCH burst so newly-paired speakers appear within a + * few seconds rather than waiting for the next NOTIFY beacon + * (typical SSDP cadence: every ~30min — far too slow for a UI + * that just opened). + */ + fun upgradeDiscovery() { + appScope.launch { + val scanStartMs = System.currentTimeMillis() + ssdp.requestActiveScan() + // Give present devices time to answer the M-SEARCH (+ our follow-up + // description fetch), then drop any route that didn't re-announce. + // Pruning is tied to picker-open scans only -- no background timer, + // so route rows never flicker while the user isn't looking. + delay(ACTIVE_SCAN_PRUNE_DELAY_MS) + pruneRoutesNotSeenSince(scanStartMs) + } } - } - /** - * Drop routes whose last NOTIFY / M-SEARCH response predates [cutoffMs] - * -- i.e. they didn't answer the active scan that just ran, so they're - * gone from the LAN. Called only after [upgradeDiscovery]'s scan window. - */ - private fun pruneRoutesNotSeenSince(cutoffMs: Long) { - val before = routesInternal.value - val survivors = before.filter { (lastSeenMs[it.id] ?: 0L) >= cutoffMs } - if (survivors.size == before.size) return - val removed = before.filterNot { it in survivors }.map { it.id } - removed.forEach { lastSeenMs.remove(it) } - Timber.w("UPnP discovery: pruned %d stale route(s): %s", removed.size, removed) - routesInternal.value = survivors - } - - /** - * No-op for the SSDP socket — passive NOTIFY listen is always on - * once [init] has run. Kept symmetric with the MediaRouter side's - * `downgradeDiscovery` so the picker controller fans out to both - * without conditional logic. - */ - fun downgradeDiscovery() { - // intentionally empty: see kdoc - } - - /** - * Build an [AVTransportClient] bound to the previously-discovered - * route's control URL. Returns null when the routeId isn't in the - * current snapshot — the speaker disappeared between picker open - * and tap, or the caller passed a non-UPnP routeId. Callers handle - * the null by abandoning the selection (no crash, no fallback). - */ - fun transportFor(routeId: String): AVTransportClient? { - val route = routesInternal.value.firstOrNull { it.id == routeId } ?: return null - return AVTransportClient( - loggingSoapClient(controlHttp, route.name), - route.avTransportControlUrl, - sonos = route.isSonos, - ) - } - - private suspend fun handleDiscovery(locationUrl: String) { - val route = fetchRoute(locationUrl) ?: return - upsertRoute(route) - if (route.isSonos) { - refreshSonosTopology(route) + /** + * Drop routes whose last NOTIFY / M-SEARCH response predates [cutoffMs] + * -- i.e. they didn't answer the active scan that just ran, so they're + * gone from the LAN. Called only after [upgradeDiscovery]'s scan window. + */ + private fun pruneRoutesNotSeenSince(cutoffMs: Long) { + val before = routesInternal.value + val survivors = before.filter { (lastSeenMs[it.id] ?: 0L) >= cutoffMs } + if (survivors.size == before.size) return + val removed = before.filterNot { it in survivors }.map { it.id } + removed.forEach { lastSeenMs.remove(it) } + Timber.w("UPnP discovery: pruned %d stale route(s): %s", removed.size, removed) + routesInternal.value = survivors } - } - private fun upsertRoute(route: UpnpRoute) { - lastSeenMs[route.id] = System.currentTimeMillis() - val current = routesInternal.value - val idx = current.indexOfFirst { it.id == route.id } - routesInternal.value = if (idx < 0) { - current + route - } else { - current.toMutableList().also { it[idx] = route } + /** + * No-op for the SSDP socket — passive NOTIFY listen is always on + * once [init] has run. Kept symmetric with the MediaRouter side's + * `downgradeDiscovery` so the picker controller fans out to both + * without conditional logic. + */ + fun downgradeDiscovery() { + // intentionally empty: see kdoc } - } - private suspend fun refreshSonosTopology(anySonos: UpnpRoute) { - val zgtUrl = anySonos.zoneGroupTopologyControlUrl ?: run { - Timber.w( - "Sonos %s has no ZoneGroupTopology URL -- topology grouping disabled", - anySonos.id, + /** + * Build an [AVTransportClient] bound to the previously-discovered + * route's control URL. Returns null when the routeId isn't in the + * current snapshot — the speaker disappeared between picker open + * and tap, or the caller passed a non-UPnP routeId. Callers handle + * the null by abandoning the selection (no crash, no fallback). + */ + fun transportFor(routeId: String): AVTransportClient? { + val route = routesInternal.value.firstOrNull { it.id == routeId } ?: return null + return AVTransportClient( + loggingSoapClient(controlHttp, route.name), + route.avTransportControlUrl, + sonos = route.isSonos, ) - return } - val groups = runCatching { - ZoneGroupTopologyClient( - loggingSoapClient(okHttp, "ZGT-${anySonos.id}"), - zgtUrl, - ).getZoneGroupState() + + private suspend fun handleDiscovery(locationUrl: String) { + val route = fetchRoute(locationUrl) ?: return + upsertRoute(route) + if (route.isSonos) { + refreshSonosTopology(route) + } } - .onFailure { Timber.w(it, "refreshSonosTopology failed for %s", anySonos.id) } - .getOrNull() ?: return - Timber.w( - "Sonos topology refreshed for %s: %d group(s)", - anySonos.id, - groups.size, - ) - sonosTopologyInternal.value = groups - } - /** - * Returns the coordinator UDN's full route for the group [udn] belongs - * to, or null if topology hasn't loaded / the udn is in no group. UDN - * normalization strips the "uuid:" prefix because DeviceDescription's - * carries it but Sonos's ZoneGroupState Coordinator attr does not. - */ - fun coordinatorRouteFor(udn: String): UpnpRoute? { - val bare = udn.bareUdn() - val coord = sonosTopologyInternal.value - .firstOrNull { g -> g.members.any { it.udn.bareUdn() == bare } } - ?.coordinatorUdn ?: return null - return routesInternal.value.firstOrNull { it.id.bareUdn() == coord.bareUdn() } - } + private fun upsertRoute(route: UpnpRoute) { + lastSeenMs[route.id] = System.currentTimeMillis() + val current = routesInternal.value + val idx = current.indexOfFirst { it.id == route.id } + routesInternal.value = + if (idx < 0) { + current + route + } else { + current.toMutableList().also { it[idx] = route } + } + } - /** - * UDNs of every NON-coordinator Sonos group member. The picker - * controller suppresses these from the visible list. - */ - fun nonCoordinatorMemberUdns(): Set { - return sonosTopologyInternal.value.flatMap { g -> - g.members.map { it.udn.bareUdn() } - .filter { it != g.coordinatorUdn.bareUdn() } - }.toSet() - } + private suspend fun refreshSonosTopology(anySonos: UpnpRoute) { + val zgtUrl = + anySonos.zoneGroupTopologyControlUrl ?: run { + Timber.w( + "Sonos %s has no ZoneGroupTopology URL -- topology grouping disabled", + anySonos.id, + ) + return + } + val groups = + runCatching { + ZoneGroupTopologyClient( + loggingSoapClient(okHttp, "ZGT-${anySonos.id}"), + zgtUrl, + ).getZoneGroupState() + }.onFailure { Timber.w(it, "refreshSonosTopology failed for %s", anySonos.id) } + .getOrNull() ?: return + Timber.w( + "Sonos topology refreshed for %s: %d group(s)", + anySonos.id, + groups.size, + ) + sonosTopologyInternal.value = groups + } - /** - * Fetch + parse the device description at [locationUrl] into a - * [UpnpRoute]. Returns null on URL parse failure, transport - * failure, empty body, or non-renderer device. Single-return form - * (chained `let`s + an early null guard) so detekt's default - * ReturnCount cap is respected. - */ - private fun fetchRoute(locationUrl: String): UpnpRoute? { - val url = locationUrl.toHttpUrlOrNull() ?: return null - return fetchBody(url) - ?.let { DeviceDescription.parse(it, url) } - ?.let { desc -> - UpnpRoute( - id = desc.udn, - name = displayName(desc.friendlyName, desc.manufacturer), - manufacturer = desc.manufacturer, - modelName = desc.modelName, - avTransportControlUrl = desc.avTransportControlUrl, - renderingControlUrl = desc.renderingControlUrl, - zoneGroupTopologyControlUrl = desc.zoneGroupTopologyControlUrl, - ) - } - } + /** + * Returns the coordinator UDN's full route for the group [udn] belongs + * to, or null if topology hasn't loaded / the udn is in no group. UDN + * normalization strips the "uuid:" prefix because DeviceDescription's + * carries it but Sonos's ZoneGroupState Coordinator attr does not. + */ + fun coordinatorRouteFor(udn: String): UpnpRoute? { + val bare = udn.bareUdn() + val coord = + sonosTopologyInternal.value + .firstOrNull { g -> g.members.any { it.udn.bareUdn() == bare } } + ?.coordinatorUdn ?: return null + return routesInternal.value.firstOrNull { it.id.bareUdn() == coord.bareUdn() } + } - /** - * Clean the raw UPnP friendlyName for picker display. Sonos uses - * the format `Room - Device Type - RINCON_`; we strip - * everything after the first " - " so the chip shows just "Living - * Room" / "Kitchen" / etc. Generic UPnP devices (Yamaha, Samsung - * TV, etc.) often append a "(192.168.x.x)" IP suffix; strip that - * too. Empty / blank → "Network speaker" fallback. - * - * Device subtitle (manufacturer + model) is rendered separately - * by the picker sheet, so room-only here doesn't lose information. - */ - private fun displayName(friendlyName: String, manufacturer: String): String { - val trimmed = friendlyName.trim() - if (trimmed.isBlank()) return "Network speaker" - val byVendor = when { - manufacturer.contains("Sonos", ignoreCase = true) -> { - trimmed.substringBefore(" - ", trimmed) - } - else -> trimmed + /** + * UDNs of every NON-coordinator Sonos group member. The picker + * controller suppresses these from the visible list. + */ + fun nonCoordinatorMemberUdns(): Set = + sonosTopologyInternal.value + .flatMap { g -> + g.members + .map { it.udn.bareUdn() } + .filter { it != g.coordinatorUdn.bareUdn() } + }.toSet() + + /** + * Fetch + parse the device description at [locationUrl] into a + * [UpnpRoute]. Returns null on URL parse failure, transport + * failure, empty body, or non-renderer device. Single-return form + * (chained `let`s + an early null guard) so detekt's default + * ReturnCount cap is respected. + */ + private fun fetchRoute(locationUrl: String): UpnpRoute? { + val url = locationUrl.toHttpUrlOrNull() ?: return null + return fetchBody(url) + ?.let { DeviceDescription.parse(it, url) } + ?.let { desc -> + UpnpRoute( + id = desc.udn, + name = displayName(desc.friendlyName, desc.manufacturer), + manufacturer = desc.manufacturer, + modelName = desc.modelName, + avTransportControlUrl = desc.avTransportControlUrl, + renderingControlUrl = desc.renderingControlUrl, + zoneGroupTopologyControlUrl = desc.zoneGroupTopologyControlUrl, + ) + } + } + + /** + * Clean the raw UPnP friendlyName for picker display. Sonos uses + * the format `Room - Device Type - RINCON_`; we strip + * everything after the first " - " so the chip shows just "Living + * Room" / "Kitchen" / etc. Generic UPnP devices (Yamaha, Samsung + * TV, etc.) often append a "(192.168.x.x)" IP suffix; strip that + * too. Empty / blank → "Network speaker" fallback. + * + * Device subtitle (manufacturer + model) is rendered separately + * by the picker sheet, so room-only here doesn't lose information. + */ + private fun displayName( + friendlyName: String, + manufacturer: String, + ): String { + val trimmed = friendlyName.trim() + if (trimmed.isBlank()) return "Network speaker" + val byVendor = + when { + manufacturer.contains("Sonos", ignoreCase = true) -> { + trimmed.substringBefore(" - ", trimmed) + } + else -> trimmed + } + val withoutIpSuffix = byVendor.replace(IP_SUFFIX_REGEX, "").trim() + return withoutIpSuffix.ifBlank { "Network speaker" } + } + + private fun fetchBody(url: HttpUrl): String? { + val body = + runCatching { + okHttp.newCall(Request.Builder().url(url).build()).execute().use { + it.body?.string() + } + }.getOrNull().orEmpty() + return body.ifEmpty { null } + } + + private companion object { + // " (198.51.100.77)" trailing host suffix some generic UPnP + // devices append. Anchored to end-of-string so it never eats + // a legitimate parenthetical inside a name. + val IP_SUFFIX_REGEX = Regex("""\s*\(\d+\.\d+\.\d+\.\d+\)$""") + + // Aggressive connect timeout for transport SOAP so a dead renderer + // trips the drop-recovery quickly. Conservative enough not to false-drop + // a slow-but-alive LAN; read timeout still inherits the shared client. + const val CONTROL_CONNECT_TIMEOUT_SECONDS = 2L + + // Grace window after an M-SEARCH burst before pruning non-responders. + // Covers the SSDP round-trip plus our per-device description fetch; + // generous enough that a present-but-slow renderer isn't false-pruned. + const val ACTIVE_SCAN_PRUNE_DELAY_MS = 4_000L } - val withoutIpSuffix = byVendor.replace(IP_SUFFIX_REGEX, "").trim() - return withoutIpSuffix.ifBlank { "Network speaker" } } - private fun fetchBody(url: HttpUrl): String? { - val body = runCatching { - okHttp.newCall(Request.Builder().url(url).build()).execute().use { - it.body?.string() - } - }.getOrNull().orEmpty() - return body.ifEmpty { null } - } - - private companion object { - // " (198.51.100.77)" trailing host suffix some generic UPnP - // devices append. Anchored to end-of-string so it never eats - // a legitimate parenthetical inside a name. - val IP_SUFFIX_REGEX = Regex("""\s*\(\d+\.\d+\.\d+\.\d+\)$""") - - // Aggressive connect timeout for transport SOAP so a dead renderer - // trips the drop-recovery quickly. Conservative enough not to false-drop - // a slow-but-alive LAN; read timeout still inherits the shared client. - const val CONTROL_CONNECT_TIMEOUT_SECONDS = 2L - - // Grace window after an M-SEARCH burst before pruning non-responders. - // Covers the SSDP round-trip plus our per-device description fetch; - // generous enough that a present-but-slow renderer isn't false-pruned. - const val ACTIVE_SCAN_PRUNE_DELAY_MS = 4_000L - } -} - /** * Normalize a Sonos UDN to its bare RINCON form for cross-comparison. * @@ -295,6 +309,7 @@ class UpnpDiscoveryController @Inject constructor( * To compare any pair of those, strip the prefix and the suffix so * everything reduces to the underlying speaker identity. */ -internal fun String.bareUdn(): String = removePrefix("uuid:") - .removeSuffix("_MR") - .removeSuffix("_MS") +internal fun String.bareUdn(): String = + removePrefix("uuid:") + .removeSuffix("_MR") + .removeSuffix("_MS") diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpRoute.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpRoute.kt index 7bd1099f..bb403731 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpRoute.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/UpnpRoute.kt @@ -32,6 +32,7 @@ data class UpnpRoute( * are vendor extensions a generic renderer faults on. */ val isSonos: Boolean - get() = zoneGroupTopologyControlUrl != null || - manufacturer.contains("Sonos", ignoreCase = true) + get() = + zoneGroupTopologyControlUrl != null || + manufacturer.contains("Sonos", ignoreCase = true) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopology.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopology.kt index a823de2d..96d971d1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopology.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopology.kt @@ -22,63 +22,69 @@ data class SonosZoneMember( ) object SonosTopology { - fun parse(xml: String): List { - val effective = if (xml.contains("<ZoneGroup")) { - unescapeXmlEntities(xml) - } else { - xml - } + val effective = + if (xml.contains("<ZoneGroup")) { + unescapeXmlEntities(xml) + } else { + xml + } return runCatching { parseStrict(effective) }.getOrDefault(emptyList()) } - private fun unescapeXmlEntities(s: String): String = s - .replace("<", "<") - .replace(">", ">") - .replace(""", "\"") - .replace("'", "'") - .replace("&", "&") // must be last to avoid double-decoding + private fun unescapeXmlEntities(s: String): String = + s + .replace("<", "<") + .replace(">", ">") + .replace(""", "\"") + .replace("'", "'") + .replace("&", "&") // must be last to avoid double-decoding private fun parseStrict(xml: String): List { - val parser = XmlPullParserFactory.newInstance().newPullParser().apply { - setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) - setInput(xml.reader()) - } + val parser = + XmlPullParserFactory.newInstance().newPullParser().apply { + setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, true) + setInput(xml.reader()) + } val groups = mutableListOf() var currentCoordinator: String? = null var currentMembers: MutableList? = null while (parser.eventType != XmlPullParser.END_DOCUMENT) { when (parser.eventType) { - XmlPullParser.START_TAG -> when (parser.name) { - TAG_ZONE_GROUP -> { - currentCoordinator = parser.getAttributeValue(null, ATTR_COORDINATOR) - currentMembers = mutableListOf() + XmlPullParser.START_TAG -> + when (parser.name) { + TAG_ZONE_GROUP -> { + currentCoordinator = parser.getAttributeValue(null, ATTR_COORDINATOR) + currentMembers = mutableListOf() + } + TAG_ZONE_GROUP_MEMBER -> currentMembers?.add(memberOf(parser)) } - TAG_ZONE_GROUP_MEMBER -> currentMembers?.add(memberOf(parser)) - } - XmlPullParser.END_TAG -> if (parser.name == TAG_ZONE_GROUP) { - val members = currentMembers ?: emptyList() - val coord = currentCoordinator - if (coord != null && members.isNotEmpty()) { - val name = members.firstOrNull { it.udn == coord }?.roomName - ?: members.first().roomName - groups.add(SonosZoneGroup(coord, name, members)) + XmlPullParser.END_TAG -> + if (parser.name == TAG_ZONE_GROUP) { + val members = currentMembers ?: emptyList() + val coord = currentCoordinator + if (coord != null && members.isNotEmpty()) { + val name = + members.firstOrNull { it.udn == coord }?.roomName + ?: members.first().roomName + groups.add(SonosZoneGroup(coord, name, members)) + } + currentCoordinator = null + currentMembers = null } - currentCoordinator = null - currentMembers = null - } } parser.next() } return groups } - private fun memberOf(parser: XmlPullParser): SonosZoneMember = SonosZoneMember( - udn = parser.getAttributeValue(null, ATTR_UUID).orEmpty(), - roomName = parser.getAttributeValue(null, ATTR_ZONE_NAME).orEmpty(), - location = parser.getAttributeValue(null, ATTR_LOCATION), - channelMapSet = parser.getAttributeValue(null, ATTR_CHANNEL_MAP_SET), - ) + private fun memberOf(parser: XmlPullParser): SonosZoneMember = + SonosZoneMember( + udn = parser.getAttributeValue(null, ATTR_UUID).orEmpty(), + roomName = parser.getAttributeValue(null, ATTR_ZONE_NAME).orEmpty(), + location = parser.getAttributeValue(null, ATTR_LOCATION), + channelMapSet = parser.getAttributeValue(null, ATTR_CHANNEL_MAP_SET), + ) private const val TAG_ZONE_GROUP = "ZoneGroup" private const val TAG_ZONE_GROUP_MEMBER = "ZoneGroupMember" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/sonos/ZoneGroupTopologyClient.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/sonos/ZoneGroupTopologyClient.kt index 35cc0665..183f5779 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/sonos/ZoneGroupTopologyClient.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/output/upnp/sonos/ZoneGroupTopologyClient.kt @@ -15,12 +15,13 @@ class ZoneGroupTopologyClient( private val controlUrl: HttpUrl, ) { suspend fun getZoneGroupState(): List { - val args = soap.call( - controlUrl = controlUrl, - serviceType = SERVICE_TYPE, - action = "GetZoneGroupState", - args = emptyMap(), - ) + val args = + soap.call( + controlUrl = controlUrl, + serviceType = SERVICE_TYPE, + action = "GetZoneGroupState", + args = emptyMap(), + ) val inner = args["ZoneGroupState"].orEmpty() Timber.w( "ZGT extracted ZoneGroupState (%d chars): %s", diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/DominantColor.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/DominantColor.kt index acaa72ef..5dc79d24 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/DominantColor.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/DominantColor.kt @@ -48,17 +48,20 @@ fun rememberDominantColor(coverUrl: String?): Color { extracted = Color.Transparent return@LaunchedEffect } - val request = ImageRequest.Builder(context) - .data(coverUrl) - .allowHardware(false) - .build() + val request = + ImageRequest + .Builder(context) + .data(coverUrl) + .allowHardware(false) + .build() val result = SingletonImageLoader.get(context).execute(request) // Keep the previous dominant on load failure rather than dropping. if (result !is SuccessResult) return@LaunchedEffect val bitmap = result.image.toBitmap() - val palette = withContext(Dispatchers.Default) { - Palette.from(bitmap).generate() - } + val palette = + withContext(Dispatchers.Default) { + Palette.from(bitmap).generate() + } // Always use the dominant (majority-by-pixel-count) swatch. // The cover art is the main feature of this view; a vibrant // accent on the cover should pop against the background, not @@ -74,7 +77,9 @@ fun rememberDominantColor(coverUrl: String?): Color { val animated by animateColorAsState( targetValue = extracted, - animationSpec = androidx.compose.animation.core.tween(GRADIENT_TWEEN_MS), + animationSpec = + androidx.compose.animation.core + .tween(GRADIENT_TWEEN_MS), label = "now-playing-dominant", ) return animated diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/MiniPlayer.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/MiniPlayer.kt index 8b8095cb..8eb2ceb9 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/MiniPlayer.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/MiniPlayer.kt @@ -10,6 +10,7 @@ import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer +import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding @@ -17,7 +18,6 @@ import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.width import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.material3.MaterialTheme -import androidx.compose.foundation.layout.fillMaxHeight import androidx.compose.material3.Surface import androidx.compose.material3.Text import androidx.compose.runtime.Composable @@ -52,12 +52,16 @@ private const val SCRUBBER_ROW_HEIGHT_DP = 4 private const val SWIPE_UP_VELOCITY_DP = 200 @Composable -private fun MiniCover(coverUrl: String, contentDescription: String) { +private fun MiniCover( + coverUrl: String, + contentDescription: String, +) { Box( - modifier = nowPlayingCoverHero() - .size(COVER_SIZE_DP.dp) - .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + nowPlayingCoverHero() + .size(COVER_SIZE_DP.dp) + .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) + .background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center, ) { // Cross-fade the artwork when the track changes so the cover @@ -99,7 +103,8 @@ fun MiniPlayer( ) { val state by viewModel.uiState.collectAsStateWithLifecycle() val track = state.currentTrack ?: return - val isLiked by trackActionsViewModel.isLikedFlow(track.id) + val isLiked by trackActionsViewModel + .isLikedFlow(track.id) .collectAsStateWithLifecycle(initialValue = false) // Swipe up anywhere on the bar to expand into the full player — @@ -110,14 +115,15 @@ fun MiniPlayer( // vertical-dominant drags. val flickThresholdPx = with(LocalDensity.current) { SWIPE_UP_VELOCITY_DP.dp.toPx() } Surface( - modifier = modifier - .fillMaxWidth() - .height(MINI_BAR_HEIGHT_DP.dp) - .draggable( - orientation = Orientation.Vertical, - state = rememberDraggableState { }, - onDragStopped = { velocity -> if (velocity < -flickThresholdPx) onExpandClick() }, - ), + modifier = + modifier + .fillMaxWidth() + .height(MINI_BAR_HEIGHT_DP.dp) + .draggable( + orientation = Orientation.Vertical, + state = rememberDraggableState { }, + onDragStopped = { velocity -> if (velocity < -flickThresholdPx) onExpandClick() }, + ), color = MaterialTheme.colorScheme.surface, tonalElevation = MINI_BAR_TONAL_ELEVATION_DP.dp, ) { @@ -162,23 +168,29 @@ fun MiniPlayer( } @Composable -private fun MiniProgressFill(positionMs: Long, durationMs: Long) { - val fraction = if (durationMs > 0) { - (positionMs.toFloat() / durationMs.toFloat()).coerceIn(0f, 1f) - } else { - 0f - } +private fun MiniProgressFill( + positionMs: Long, + durationMs: Long, +) { + val fraction = + if (durationMs > 0) { + (positionMs.toFloat() / durationMs.toFloat()).coerceIn(0f, 1f) + } else { + 0f + } Box( - modifier = Modifier - .fillMaxWidth() - .height(SCRUBBER_ROW_HEIGHT_DP.dp) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + Modifier + .fillMaxWidth() + .height(SCRUBBER_ROW_HEIGHT_DP.dp) + .background(MaterialTheme.colorScheme.surfaceVariant), ) { Box( - modifier = Modifier - .fillMaxHeight() - .fillMaxWidth(fraction) - .background(MaterialTheme.colorScheme.primary), + modifier = + Modifier + .fillMaxHeight() + .fillMaxWidth(fraction) + .background(MaterialTheme.colorScheme.primary), ) } } @@ -200,9 +212,10 @@ private fun MiniRow( onToggleLike: () -> Unit, ) { Row( - modifier = modifier - .fillMaxWidth() - .padding(horizontal = 12.dp), + modifier = + modifier + .fillMaxWidth() + .padding(horizontal = 12.dp), verticalAlignment = Alignment.CenterVertically, ) { // Cover + title area expands to NowPlaying on tap, but the @@ -210,9 +223,10 @@ private fun MiniRow( // clicks). Wrap only the cover-and-title region with the // clickable modifier rather than the whole row. Row( - modifier = Modifier - .weight(1f) - .clickable(onClick = onExpandClick), + modifier = + Modifier + .weight(1f) + .clickable(onClick = onExpandClick), verticalAlignment = Alignment.CenterVertically, ) { MiniCover(coverUrl = track.coverUrl, contentDescription = track.title) @@ -265,4 +279,3 @@ private fun MiniRow( /** The mini player's transport icons, at Material's standard icon size. */ private const val MINI_TRANSPORT_ICON_DP = 24 - diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingScreen.kt index 81ba8d1e..4830ecf8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/NowPlayingScreen.kt @@ -8,8 +8,7 @@ import androidx.activity.compose.rememberLauncherForActivityResult import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.foundation.background import androidx.compose.foundation.focusable -import androidx.compose.foundation.rememberScrollState -import androidx.compose.foundation.verticalScroll +import androidx.compose.foundation.interaction.MutableInteractionSource import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column @@ -23,28 +22,22 @@ import androidx.compose.foundation.layout.height import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.layout.widthIn +import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.foundation.verticalScroll +import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme -import androidx.compose.ui.geometry.Offset -import androidx.compose.ui.input.nestedscroll.NestedScrollConnection -import androidx.compose.ui.input.nestedscroll.NestedScrollSource -import androidx.compose.ui.input.nestedscroll.nestedScroll -import androidx.compose.ui.unit.Velocity import androidx.compose.material3.Scaffold -import androidx.compose.foundation.interaction.MutableInteractionSource -import androidx.compose.material3.ExperimentalMaterial3Api import androidx.compose.material3.Slider -import androidx.compose.material3.TopAppBar -import androidx.compose.material3.TopAppBarDefaults -import androidx.compose.ui.graphics.Brush -import androidx.compose.ui.graphics.Color import androidx.compose.material3.SliderDefaults import androidx.compose.material3.SnackbarHost import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text +import androidx.compose.material3.TopAppBar +import androidx.compose.material3.TopAppBarDefaults import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.getValue @@ -53,19 +46,26 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment -import androidx.compose.ui.focus.FocusRequester -import androidx.compose.ui.focus.focusRequester import androidx.compose.ui.Modifier import androidx.compose.ui.draw.clip +import androidx.compose.ui.focus.FocusRequester +import androidx.compose.ui.focus.focusRequester +import androidx.compose.ui.geometry.Offset +import androidx.compose.ui.graphics.Brush +import androidx.compose.ui.graphics.Color import androidx.compose.ui.input.key.Key import androidx.compose.ui.input.key.KeyEvent import androidx.compose.ui.input.key.KeyEventType import androidx.compose.ui.input.key.key import androidx.compose.ui.input.key.onKeyEvent import androidx.compose.ui.input.key.type +import androidx.compose.ui.input.nestedscroll.NestedScrollConnection +import androidx.compose.ui.input.nestedscroll.NestedScrollSource +import androidx.compose.ui.input.nestedscroll.nestedScroll import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.unit.Velocity import androidx.compose.ui.unit.dp import androidx.core.content.ContextCompat import androidx.hilt.navigation.compose.hiltViewModel @@ -80,6 +80,10 @@ import com.composables.icons.lucide.Repeat1 import com.composables.icons.lucide.Shuffle import com.composables.icons.lucide.SkipBack import com.composables.icons.lucide.SkipForward +import com.fabledsword.minstrel.nav.AlbumDetail +import com.fabledsword.minstrel.nav.ArtistDetail +import com.fabledsword.minstrel.nav.NowPlaying +import com.fabledsword.minstrel.nav.Queue import com.fabledsword.minstrel.player.RepeatMode import com.fabledsword.minstrel.player.output.ActiveUpnp import com.fabledsword.minstrel.player.output.DeviceChip @@ -87,20 +91,16 @@ import com.fabledsword.minstrel.player.output.OutputPickerSheet import com.fabledsword.minstrel.player.output.OutputPickerViewModel import com.fabledsword.minstrel.player.output.OutputRoute import com.fabledsword.minstrel.player.output.RouteSnapshot -import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon -import kotlinx.coroutines.launch -import com.fabledsword.minstrel.nav.AlbumDetail -import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.NowPlaying -import com.fabledsword.minstrel.nav.Queue import com.fabledsword.minstrel.shared.formatDuration import com.fabledsword.minstrel.shared.millisToSeconds +import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.ServerImage import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsViewModel import com.fabledsword.minstrel.theme.FabledSwordFlatTokens import com.fabledsword.minstrel.theme.LocalActionColors +import kotlinx.coroutines.launch private const val COVER_MAX_WIDTH_DP = 320 private const val TRANSPORT_ICON_DP = 36 @@ -149,24 +149,27 @@ fun NowPlayingScreen( val focusRequester = remember { FocusRequester() } LaunchedEffect(activeUpnp) { if (activeUpnp != null) focusRequester.requestFocus() } val dominant = rememberDominantColor(track.coverUrl) - val dismissConnection = rememberDragDismissConnection( - onDismiss = { navController.popBackStack() }, - ) + val dismissConnection = + rememberDragDismissConnection( + onDismiss = { navController.popBackStack() }, + ) Scaffold( - modifier = Modifier - .fillMaxSize() - .nestedScroll(dismissConnection) - .focusRequester(focusRequester) - .focusable() - .onKeyEvent(onKeyEvent), + modifier = + Modifier + .fillMaxSize() + .nestedScroll(dismissConnection) + .focusRequester(focusRequester) + .focusable() + .onKeyEvent(onKeyEvent), topBar = { NowPlayingTopBar(onClose = { navController.popBackStack() }) }, snackbarHost = { SnackbarHost(snackbarHostState) }, containerColor = Color.Transparent, ) { inner -> Box( - modifier = Modifier - .fillMaxSize() - .background(dominantGradient(dominant)), + modifier = + Modifier + .fillMaxSize() + .background(dominantGradient(dominant)), ) { NowPlayingBody( inner = inner, @@ -233,52 +236,53 @@ private const val DOMINANT_TINT_MID_STOP = 0.45f private fun rememberDragDismissConnection( onDismiss: () -> Unit, thresholdPx: Float = DRAG_DISMISS_THRESHOLD_PX, -): NestedScrollConnection = remember(onDismiss, thresholdPx) { - object : NestedScrollConnection { - private var accumulated = 0f +): NestedScrollConnection = + remember(onDismiss, thresholdPx) { + object : NestedScrollConnection { + private var accumulated = 0f - // One-shot latch. popBackStack is async — between the first - // dismissal and the screen actually leaving the composition, - // the user's finger is still down and more onPostScroll - // frames arrive. Without this guard the accumulator rebuilds - // and onDismiss() fires a second time, popping the screen - // BENEATH NowPlaying. If that leaves the back stack empty - // the NavHost renders nothing → black screen on resume. - private var dismissed = false + // One-shot latch. popBackStack is async — between the first + // dismissal and the screen actually leaving the composition, + // the user's finger is still down and more onPostScroll + // frames arrive. Without this guard the accumulator rebuilds + // and onDismiss() fires a second time, popping the screen + // BENEATH NowPlaying. If that leaves the back stack empty + // the NavHost renders nothing → black screen on resume. + private var dismissed = false - override fun onPostScroll( - consumed: Offset, - available: Offset, - source: NestedScrollSource, - ): Offset { - // After dismissal, eat all remaining drag so the - // scrollable doesn't paint over-scroll deltas during the - // pop transition. Source guard folded into the `else if` - // chain so the function stays under detekt's ReturnCount - // ceiling of 2. - if (dismissed) return available - return if (source != NestedScrollSource.UserInput) { - Offset.Zero - } else if (available.y > 0f) { - accumulated += available.y - if (accumulated >= thresholdPx) { - dismissed = true - onDismiss() + override fun onPostScroll( + consumed: Offset, + available: Offset, + source: NestedScrollSource, + ): Offset { + // After dismissal, eat all remaining drag so the + // scrollable doesn't paint over-scroll deltas during the + // pop transition. Source guard folded into the `else if` + // chain so the function stays under detekt's ReturnCount + // ceiling of 2. + if (dismissed) return available + return if (source != NestedScrollSource.UserInput) { + Offset.Zero + } else if (available.y > 0f) { + accumulated += available.y + if (accumulated >= thresholdPx) { + dismissed = true + onDismiss() + } + Offset(0f, available.y) + } else { + if (consumed.y != 0f || available.y < 0f) accumulated = 0f + Offset.Zero } - Offset(0f, available.y) - } else { - if (consumed.y != 0f || available.y < 0f) accumulated = 0f - Offset.Zero + } + + override suspend fun onPreFling(available: Velocity): Velocity { + if (dismissed) return available + accumulated = 0f + return Velocity.Zero } } - - override suspend fun onPreFling(available: Velocity): Velocity { - if (dismissed) return available - accumulated = 0f - return Velocity.Zero - } } -} @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -294,9 +298,10 @@ private fun NowPlayingTopBar(onClose: () -> Unit) { ) } }, - colors = TopAppBarDefaults.topAppBarColors( - containerColor = Color.Transparent, - ), + colors = + TopAppBarDefaults.topAppBarColors( + containerColor = Color.Transparent, + ), ) } @@ -311,7 +316,8 @@ private fun NowPlayingBody( trackActionsViewModel: TrackActionsViewModel, outputViewModel: OutputPickerViewModel, ) { - val isLiked by trackActionsViewModel.isLikedFlow(track.id) + val isLiked by trackActionsViewModel + .isLikedFlow(track.id) .collectAsStateWithLifecycle(initialValue = false) val routes by outputViewModel.routes.collectAsStateWithLifecycle() val sheetVisible by outputViewModel.sheetVisible.collectAsStateWithLifecycle() @@ -351,11 +357,12 @@ private fun NowPlayingContent( onChipTapped: () -> Unit, ) { Column( - modifier = Modifier - .fillMaxSize() - .padding(inner) - .verticalScroll(rememberScrollState()) - .padding(horizontal = 24.dp), + modifier = + Modifier + .fillMaxSize() + .padding(inner) + .verticalScroll(rememberScrollState()) + .padding(horizontal = 24.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -441,11 +448,12 @@ private fun PlaybackControlsBlock( private fun rememberBluetoothPermissionState(sheetVisible: Boolean): Boolean { val context = LocalContext.current var permissionDenied by remember { mutableStateOf(false) } - val permissionLauncher = rememberLauncherForActivityResult( - contract = ActivityResultContracts.RequestPermission(), - ) { granted -> - permissionDenied = !granted - } + val permissionLauncher = + rememberLauncherForActivityResult( + contract = ActivityResultContracts.RequestPermission(), + ) { granted -> + permissionDenied = !granted + } LaunchedEffect(sheetVisible) { if (sheetVisible && ContextCompat.checkSelfPermission( @@ -460,8 +468,9 @@ private fun rememberBluetoothPermissionState(sheetVisible: Boolean): Boolean { } private fun shouldShowChip(snapshot: RouteSnapshot): Boolean { - val onlyBuiltIn = snapshot.available.size == 1 && - snapshot.available.first().kind == OutputRoute.Kind.BuiltIn + val onlyBuiltIn = + snapshot.available.size == 1 && + snapshot.available.first().kind == OutputRoute.Kind.BuiltIn return !onlyBuiltIn } @@ -493,11 +502,12 @@ private fun BottomActionsRow( IconButton(onClick = onCycleRepeat) { Icon( imageVector = if (repeatMode == RepeatMode.ONE) Lucide.Repeat1 else Lucide.Repeat, - contentDescription = when (repeatMode) { - RepeatMode.OFF -> "Repeat off" - RepeatMode.ALL -> "Repeat all" - RepeatMode.ONE -> "Repeat one" - }, + contentDescription = + when (repeatMode) { + RepeatMode.OFF -> "Repeat off" + RepeatMode.ALL -> "Repeat all" + RepeatMode.ONE -> "Repeat one" + }, tint = if (repeatMode == RepeatMode.OFF) muted else accent, ) } @@ -534,14 +544,18 @@ private fun ViewQueueButton(onClick: () -> Unit) { } @Composable -private fun NowPlayingCover(coverUrl: String, contentDescription: String) { +private fun NowPlayingCover( + coverUrl: String, + contentDescription: String, +) { Box( - modifier = nowPlayingCoverHero() - .widthIn(max = COVER_MAX_WIDTH_DP.dp) - .fillMaxWidth() - .aspectRatio(1f) - .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusLg)) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + nowPlayingCoverHero() + .widthIn(max = COVER_MAX_WIDTH_DP.dp) + .fillMaxWidth() + .aspectRatio(1f) + .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusLg)) + .background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center, ) { ServerImage( @@ -553,7 +567,11 @@ private fun NowPlayingCover(coverUrl: String, contentDescription: String) { } @Composable -private fun TrackHeader(title: String, artist: String, album: String) { +private fun TrackHeader( + title: String, + artist: String, + album: String, +) { Text( text = title, style = MaterialTheme.typography.headlineMedium, @@ -584,21 +602,27 @@ private fun TrackHeader(title: String, artist: String, album: String) { @OptIn(ExperimentalMaterial3Api::class) @Composable -private fun ScrubberRow(positionMs: Long, durationMs: Long, onSeek: (Long) -> Unit) { +private fun ScrubberRow( + positionMs: Long, + durationMs: Long, + onSeek: (Long) -> Unit, +) { val accent = MaterialTheme.colorScheme.primary - val fraction = if (durationMs > 0) { - (positionMs.toFloat() / durationMs.toFloat()).coerceIn(0f, 1f) - } else { - 0f - } + val fraction = + if (durationMs > 0) { + (positionMs.toFloat() / durationMs.toFloat()).coerceIn(0f, 1f) + } else { + 0f + } val interactionSource = remember { MutableInteractionSource() } - val sliderColors = SliderDefaults.colors( - thumbColor = accent, - activeTrackColor = accent, - // M3 inactive default is secondaryContainer (purple baseline); - // pin to surfaceVariant (= slate). - inactiveTrackColor = MaterialTheme.colorScheme.surfaceVariant, - ) + val sliderColors = + SliderDefaults.colors( + thumbColor = accent, + activeTrackColor = accent, + // M3 inactive default is secondaryContainer (purple baseline); + // pin to surfaceVariant (= slate). + inactiveTrackColor = MaterialTheme.colorScheme.surfaceVariant, + ) Slider( value = fraction, onValueChange = { newFraction -> @@ -621,10 +645,11 @@ private fun ScrubberRow(positionMs: Long, durationMs: Long, onSeek: (Long) -> Un // unchanged. thumb = { Box( - modifier = Modifier - .size(width = SCRUB_THUMB_WIDTH_DP, height = SCRUB_THUMB_HEIGHT_DP) - .clip(CircleShape) - .background(accent), + modifier = + Modifier + .size(width = SCRUB_THUMB_WIDTH_DP, height = SCRUB_THUMB_HEIGHT_DP) + .clip(CircleShape) + .background(accent), ) }, // Custom 4dp rounded track — see ScrubTrack for rationale. @@ -656,20 +681,25 @@ private fun ScrubberRow(positionMs: Long, durationMs: Long, onSeek: (Long) -> Un * [ScrubberRow] stays under detekt's LongMethod ceiling. */ @Composable -private fun ScrubTrack(fraction: Float, accent: Color) { +private fun ScrubTrack( + fraction: Float, + accent: Color, +) { Box(modifier = Modifier.fillMaxWidth().height(SCRUB_TRACK_HEIGHT_DP)) { Box( - modifier = Modifier - .matchParentSize() - .clip(RoundedCornerShape(SCRUB_TRACK_CORNER_DP)) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + Modifier + .matchParentSize() + .clip(RoundedCornerShape(SCRUB_TRACK_CORNER_DP)) + .background(MaterialTheme.colorScheme.surfaceVariant), ) Box( - modifier = Modifier - .fillMaxWidth(fraction) - .fillMaxHeight() - .clip(RoundedCornerShape(SCRUB_TRACK_CORNER_DP)) - .background(accent), + modifier = + Modifier + .fillMaxWidth(fraction) + .fillMaxHeight() + .clip(RoundedCornerShape(SCRUB_TRACK_CORNER_DP)) + .background(accent), ) } } @@ -734,11 +764,12 @@ private fun rememberUpnpVolumeKeyHandler(activeUpnp: ActiveUpnp?): (KeyEvent) -> handler@{ event: KeyEvent -> val rc = activeUpnp?.rendering ?: return@handler false if (event.type != KeyEventType.KeyDown) return@handler false - val delta = when (event.key) { - Key.VolumeUp -> VOLUME_KEY_STEP - Key.VolumeDown -> -VOLUME_KEY_STEP - else -> return@handler false - } + val delta = + when (event.key) { + Key.VolumeUp -> VOLUME_KEY_STEP + Key.VolumeDown -> -VOLUME_KEY_STEP + else -> return@handler false + } scope.launch { val current = cache.value ?: runCatching { rc.getVolume() }.getOrNull() ?: 0 val next = (current + delta).coerceIn(VOLUME_MIN_PERCENT, VOLUME_MAX_PERCENT) @@ -750,7 +781,9 @@ private fun rememberUpnpVolumeKeyHandler(activeUpnp: ActiveUpnp?): (KeyEvent) -> } } -private class VolumeCache(var value: Int? = null) +private class VolumeCache( + var value: Int? = null, +) private const val VOLUME_KEY_STEP = 5 private const val VOLUME_MIN_PERCENT = 0 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlaybackErrorViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlaybackErrorViewModel.kt index 2c0c479e..e966d93b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlaybackErrorViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlaybackErrorViewModel.kt @@ -14,8 +14,10 @@ import javax.inject.Inject * accessor. */ @HiltViewModel -class PlaybackErrorViewModel @Inject constructor( - reporter: PlaybackErrorReporter, -) : ViewModel() { - val messages: Flow = reporter.messages -} +class PlaybackErrorViewModel + @Inject + constructor( + reporter: PlaybackErrorReporter, + ) : ViewModel() { + val messages: Flow = reporter.messages + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlayerViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlayerViewModel.kt index 0799b693..9865cd84 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlayerViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/PlayerViewModel.kt @@ -27,43 +27,58 @@ import javax.inject.Inject */ @HiltViewModel @Suppress("TooManyFunctions") // Thin transport facade — each fun forwards to PlayerController. -class PlayerViewModel @Inject constructor( - private val controller: PlayerController, - private val likes: LikesRepository, -) : ViewModel() { +class PlayerViewModel + @Inject + constructor( + private val controller: PlayerController, + private val likes: LikesRepository, + ) : ViewModel() { + val uiState: StateFlow = controller.uiState + val dropEvents: SharedFlow = controller.dropEvents - val uiState: StateFlow = controller.uiState - val dropEvents: SharedFlow = controller.dropEvents + /** + * Reactive set of liked track ids — the set-based pattern the queue + * (and playlist/album/artist detail) uses to color each row's + * [com.fabledsword.minstrel.shared.widgets.LikeButton] without a + * per-row Flow subscription. + */ + val likedTrackIds: StateFlow> = + likes + .observeLikedTrackIds() + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = emptySet(), + ) - /** - * Reactive set of liked track ids — the set-based pattern the queue - * (and playlist/album/artist detail) uses to color each row's - * [com.fabledsword.minstrel.shared.widgets.LikeButton] without a - * per-row Flow subscription. - */ - val likedTrackIds: StateFlow> = - likes.observeLikedTrackIds() - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = emptySet(), - ) + fun play() = controller.play() - fun play() = controller.play() - fun pause() = controller.pause() - fun seekTo(positionMs: Long) = controller.seekTo(positionMs) - fun skipToNext() = controller.skipToNext() - fun skipToPrevious() = controller.skipToPrevious() - fun seekToIndex(index: Int) = controller.seekToIndex(index) - fun toggleShuffle() = controller.toggleShuffle() - fun cycleRepeat() = controller.cycleRepeat() - fun moveInQueue(from: Int, to: Int) = controller.moveInQueue(from, to) - fun removeFromQueue(index: Int) = controller.removeFromQueue(index) - fun clearQueue() = controller.clearQueue() + fun pause() = controller.pause() - fun toggleLikeTrack(trackId: String) { - viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } + fun seekTo(positionMs: Long) = controller.seekTo(positionMs) + + fun skipToNext() = controller.skipToNext() + + fun skipToPrevious() = controller.skipToPrevious() + + fun seekToIndex(index: Int) = controller.seekToIndex(index) + + fun toggleShuffle() = controller.toggleShuffle() + + fun cycleRepeat() = controller.cycleRepeat() + + fun moveInQueue( + from: Int, + to: Int, + ) = controller.moveInQueue(from, to) + + fun removeFromQueue(index: Int) = controller.removeFromQueue(index) + + fun clearQueue() = controller.clearQueue() + + fun toggleLikeTrack(trackId: String) { + viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } + } } -} private const val SHARE_STOP_TIMEOUT_MS = 5_000L diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt index e74be1c4..80dbc2c7 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueRow.kt @@ -49,11 +49,12 @@ internal fun QueueRow( onRemove: () -> Unit, onMove: (Int, Int) -> Unit, ) { - val highlight = if (isCurrent) { - MaterialTheme.colorScheme.primary.copy(alpha = HIGHLIGHT_ALPHA) - } else { - Color.Transparent - } + val highlight = + if (isCurrent) { + MaterialTheme.colorScheme.primary.copy(alpha = HIGHLIGHT_ALPHA) + } else { + Color.Transparent + } ReorderableRemovableRow( index = index, count = queueSize, @@ -62,15 +63,16 @@ internal fun QueueRow( onMove = onMove, ) { handles -> Row( - modifier = Modifier - .fillMaxWidth() - // Opaque: this sits ON TOP of the red remove background, so a - // transparent row would show the fill through it at rest. - .background(MaterialTheme.colorScheme.surface) - .background(highlight) - .clickable(onClick = onClick) - .then(handles.actions) - .padding(horizontal = 16.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + // Opaque: this sits ON TOP of the red remove background, so a + // transparent row would show the fill through it at rest. + .background(MaterialTheme.colorScheme.surface) + .background(highlight) + .clickable(onClick = onClick) + .then(handles.actions) + .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { @@ -99,13 +101,17 @@ internal fun QueueRow( } @Composable -private fun QueueRowThumbnail(track: TrackRef, dragModifier: Modifier = Modifier) { +private fun QueueRowThumbnail( + track: TrackRef, + dragModifier: Modifier = Modifier, +) { Box( - modifier = Modifier - .size(48.dp) - .clip(RoundedCornerShape(4.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant) - .then(dragModifier), + modifier = + Modifier + .size(48.dp) + .clip(RoundedCornerShape(4.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant) + .then(dragModifier), contentAlignment = Alignment.Center, ) { ServerImage( @@ -123,7 +129,11 @@ private fun QueueRowThumbnail(track: TrackRef, dragModifier: Modifier = Modifier } @Composable -private fun QueueRowText(track: TrackRef, isCurrent: Boolean, modifier: Modifier = Modifier) { +private fun QueueRowText( + track: TrackRef, + isCurrent: Boolean, + modifier: Modifier = Modifier, +) { Column(modifier = modifier) { Text( text = track.title, @@ -147,8 +157,9 @@ private fun QueueRowText(track: TrackRef, isCurrent: Boolean, modifier: Modifier } /** "Artist · Album" — collapses gracefully when either is missing. */ -private fun queueSubtitle(track: TrackRef): String = listOf(track.artistName, track.albumTitle) - .filter { it.isNotEmpty() } - .joinToString(" · ") +private fun queueSubtitle(track: TrackRef): String = + listOf(track.artistName, track.albumTitle) + .filter { it.isNotEmpty() } + .joinToString(" · ") private const val HIGHLIGHT_ALPHA = 0.12f diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueScreen.kt index 214edb6b..0d28233d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/QueueScreen.kt @@ -112,9 +112,10 @@ private fun QueueList( onMove: (Int, Int) -> Unit, onRemove: (Int) -> Unit, ) { - val listState = rememberLazyListState( - initialFirstVisibleItemIndex = currentIndex.coerceIn(0, tracks.lastIndex), - ) + val listState = + rememberLazyListState( + initialFirstVisibleItemIndex = currentIndex.coerceIn(0, tracks.lastIndex), + ) val scope = rememberCoroutineScope() // Follow the now-playing row as the track auto-advances, but only while it's @@ -178,15 +179,15 @@ private fun JumpToCurrentPill( } } - /** "N tracks · 12 min" header summary. */ private fun queueSummary(tracks: List): String { val minutes = tracks.sumOf { it.durationSec } / SECONDS_PER_MINUTE - val length = if (minutes >= MINUTES_PER_HOUR) { - "${minutes / MINUTES_PER_HOUR}h ${minutes % MINUTES_PER_HOUR}m" - } else { - "$minutes min" - } + val length = + if (minutes >= MINUTES_PER_HOUR) { + "${minutes / MINUTES_PER_HOUR}h ${minutes % MINUTES_PER_HOUR}m" + } else { + "$minutes min" + } return "${plural(tracks.size, "track", "tracks")} · $length" } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/SmoothPosition.kt b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/SmoothPosition.kt index 18003011..750dc84c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/player/ui/SmoothPosition.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/player/ui/SmoothPosition.kt @@ -29,20 +29,21 @@ fun rememberSmoothPositionMs( positionMs: Long, durationMs: Long, isPlaying: Boolean, -): State = produceState( - initialValue = positionMs, - key1 = positionMs, - key2 = isPlaying, - key3 = durationMs, -) { - value = positionMs - if (!isPlaying || durationMs <= 0L) return@produceState - val startFrame = withFrameMillis { it } - val startPos = positionMs - while (isActive) { - withFrameMillis { now -> - val advanced = startPos + (now - startFrame) - value = advanced.coerceAtMost(durationMs) +): State = + produceState( + initialValue = positionMs, + key1 = positionMs, + key2 = isPlaying, + key3 = durationMs, + ) { + value = positionMs + if (!isPlaying || durationMs <= 0L) return@produceState + val startFrame = withFrameMillis { it } + val startPos = positionMs + while (isActive) { + withFrameMillis { now -> + val advanced = startPos + (now - startFrame) + value = advanced.coerceAtMost(durationMs) + } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt index 4d566217..5a157ce6 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/Shelf.kt @@ -23,7 +23,10 @@ import kotlin.math.roundToInt * reuses its own first albums rather than showing nothing. [perTile] is * how many covers a tile shows (one for a card, three for a genre band). */ -fun assignShelfCovers(playlists: List, perTile: Int): List> { +fun assignShelfCovers( + playlists: List, + perTile: Int, +): List> { val used = mutableSetOf() return playlists.map { p -> val fresh = p.coverAlbumIds.filter { it !in used }.take(perTile) @@ -105,7 +108,11 @@ val byShelfRank: Comparator = fun songsLikeArtist(p: PlaylistRef): String = p.name.replace(SONGS_LIKE_PREFIX, "") /** An sRGB colour as 0–255 channels; kept free of Compose so it unit-tests. */ -data class Rgb(val r: Int, val g: Int, val b: Int) +data class Rgb( + val r: Int, + val g: Int, + val b: Int, +) /** * The colour a wide card or genre band is washed in, from its lead cover's @@ -119,24 +126,34 @@ fun washTone(c: Rgb): Rgb { return fromHsl(h, min(s, MAX_WASH_SATURATION), min(l, MAX_WASH_LIGHTNESS)) } -private fun toHsl(r: Double, g: Double, b: Double): Triple { +private fun toHsl( + r: Double, + g: Double, + b: Double, +): Triple { val mx = maxOf(r, g, b) val mn = minOf(r, g, b) val l = (mx + mn) / 2 if (mx == mn) return Triple(0.0, 0.0, l) val d = mx - mn val s = if (l > HALF) d / (2 - mx - mn) else d / (mx + mn) - val h = when (mx) { - r -> (g - b) / d + (if (g < b) HUE_SECTORS else 0.0) - g -> (b - r) / d + 2 - else -> (r - g) / d + 4 - } + val h = + when (mx) { + r -> (g - b) / d + (if (g < b) HUE_SECTORS else 0.0) + g -> (b - r) / d + 2 + else -> (r - g) / d + 4 + } return Triple(h / HUE_SECTORS, s, l) } -private fun fromHsl(h: Double, s: Double, l: Double): Rgb { +private fun fromHsl( + h: Double, + s: Double, + l: Double, +): Rgb { val q = if (l < HALF) l * (1 + s) else l + s - l * s val p = 2 * l - q + fun channel(t0: Double): Double { var t = t0 if (t < 0) t += 1 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt index 294cfb49..9882f5c1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistEdits.kt @@ -18,7 +18,10 @@ fun PlaylistDetailRef.withoutEntry(index: Int): PlaylistDetailRef { } /** The playlist with its entry at [from] moved to [to]. */ -fun PlaylistDetailRef.withEntryMoved(from: Int, to: Int): PlaylistDetailRef { +fun PlaylistDetailRef.withEntryMoved( + from: Int, + to: Int, +): PlaylistDetailRef { if (from !in tracks.indices || to !in tracks.indices || from == to) return this val moved = tracks.toMutableList().apply { add(to, removeAt(from)) } return copy(tracks = moved.mapIndexed { i, row -> row.copy(position = i) }) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistPlayback.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistPlayback.kt index f2c6d2c4..eb6a9f82 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistPlayback.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistPlayback.kt @@ -1,8 +1,8 @@ package com.fabledsword.minstrel.playlists.data +import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.player.PlayerController -import com.fabledsword.minstrel.api.ErrorCopy import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.withTimeout @@ -50,22 +50,23 @@ private suspend fun fetchPlaylistDetail( playlist: PlaylistRef, repository: PlaylistsRepository, onMessage: (String) -> Unit, -): PlaylistDetailRef? = try { - withTimeout(PLAYLIST_FETCH_TIMEOUT_MS) { - if (playlist.refreshable && playlist.systemVariant != null) { - repository.systemShuffle(playlist.systemVariant) - } else { - repository.refreshDetail(playlist.id) +): PlaylistDetailRef? = + try { + withTimeout(PLAYLIST_FETCH_TIMEOUT_MS) { + if (playlist.refreshable && playlist.systemVariant != null) { + repository.systemShuffle(playlist.systemVariant) + } else { + repository.refreshDetail(playlist.id) + } } + } catch ( + @Suppress("SwallowedException") _: TimeoutCancellationException, + ) { + onMessage("Couldn't load playlist - check your connection") + null + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + onMessage("Couldn't load playlist: ${ErrorCopy.fromThrowable(e)}") + null } -} catch ( - @Suppress("SwallowedException") _: TimeoutCancellationException, -) { - onMessage("Couldn't load playlist - check your connection") - null -} catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, -) { - onMessage("Couldn't load playlist: ${ErrorCopy.fromThrowable(e)}") - null -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt index 3c98f881..5e757305 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepository.kt @@ -6,10 +6,6 @@ import com.fabledsword.minstrel.api.endpoints.PlaylistsApi import com.fabledsword.minstrel.api.endpoints.ReorderTracksRequest import com.fabledsword.minstrel.api.endpoints.UpdatePlaylistRequest import com.fabledsword.minstrel.auth.AuthController -import com.fabledsword.minstrel.cache.mutations.WriteOutcome -import com.fabledsword.minstrel.cache.mutations.sendOrQueue -import retrofit2.HttpException -import java.net.HttpURLConnection import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistDao import com.fabledsword.minstrel.cache.db.dao.CachedPlaylistTrackDao import com.fabledsword.minstrel.cache.db.dao.PlaylistCachedCount @@ -21,6 +17,8 @@ import com.fabledsword.minstrel.cache.mutations.PlaylistCreatePayload import com.fabledsword.minstrel.cache.mutations.PlaylistRemoveTrackPayload import com.fabledsword.minstrel.cache.mutations.PlaylistReorderPayload import com.fabledsword.minstrel.cache.mutations.PlaylistUpdatePayload +import com.fabledsword.minstrel.cache.mutations.WriteOutcome +import com.fabledsword.minstrel.cache.mutations.sendOrQueue import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.models.PlaylistTrackRef import com.fabledsword.minstrel.models.TrackRef @@ -34,8 +32,10 @@ import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flatMapLatest import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.flow.map +import retrofit2.HttpException import retrofit2.Retrofit import retrofit2.create +import java.net.HttpURLConnection import java.util.UUID import javax.inject.Inject import javax.inject.Singleton @@ -54,231 +54,256 @@ import javax.inject.Singleton */ @Suppress("TooManyFunctions") // one method per playlist read or write @Singleton -class PlaylistsRepository @Inject constructor( - private val playlistDao: CachedPlaylistDao, - private val playlistTrackDao: CachedPlaylistTrackDao, - private val mutationQueue: MutationQueue, - private val authController: AuthController, - retrofit: Retrofit, -) { - private val api: PlaylistsApi = retrofit.create() +class PlaylistsRepository + @Inject + constructor( + private val playlistDao: CachedPlaylistDao, + private val playlistTrackDao: CachedPlaylistTrackDao, + private val mutationQueue: MutationQueue, + private val authController: AuthController, + retrofit: Retrofit, + ) { + private val api: PlaylistsApi = retrofit.create() - // ── Reads (Flow, cache-first; the cache is the source of truth) ── + // ── Reads (Flow, cache-first; the cache is the source of truth) ── - /** - * Owned + public; UI splits by isSystem / userId comparison. Joined with - * per-playlist cache counts so [PlaylistRef.fullyCached] drives the offline - * greying without each consumer re-querying the cache index. - */ - fun observeAll(): Flow> = - combine( - playlistDao.observeAll(), - playlistDao.observeCachedCounts(), - ) { rows, counts -> mergePlaylistsWithCache(rows, counts) } + /** + * Owned + public; UI splits by isSystem / userId comparison. Joined with + * per-playlist cache counts so [PlaylistRef.fullyCached] drives the offline + * greying without each consumer re-querying the cache index. + */ + fun observeAll(): Flow> = + combine( + playlistDao.observeAll(), + playlistDao.observeCachedCounts(), + ) { rows, counts -> mergePlaylistsWithCache(rows, counts) } - /** - * The signed-in listener's own playlists, not mixes and not other - * people's public lists: the ones a song can be added to. - */ - @OptIn(ExperimentalCoroutinesApi::class) - fun observeOwnPlaylists(): Flow> = - authController.currentUser.flatMapLatest { user -> - if (user == null) { - flowOf(emptyList()) - } else { - playlistDao.observeOwnedUserPlaylists(user.id).map { rows -> rows.map { it.toDomain() } } - } - } - - /** Server-generated system playlists (for_you / discover / etc.). */ - fun observeSystemPlaylists(): Flow> = - playlistDao.observeSystemPlaylists().map { rows -> rows.map { it.toDomain() } } - - suspend fun getPlaylist(id: String): PlaylistRef? = playlistDao.getById(id)?.toDomain() - - // ── Server refreshes ────────────────────────────────────────────── - - /** - * Pulls `GET /api/playlists?kind=all` and replaces the local - * playlist cache. Per-playlist track rows come from refreshDetail. - */ - suspend fun refreshList() { - val wire = api.list(kind = "all") - val all = (wire.owned + wire.public).map { it.toEntity() } - val userId = authController.currentUser.value?.id - if (userId != null) { - // Reconcile: BuildSystemPlaylists rotates system-playlist - // UUIDs every rebuild, so upsert alone leaves stale rows - // whose detail fetch 404s ("That playlist no longer - // exists"). - // A list made offline isn't on the server yet; keep it. - playlistDao.replaceList( - userId = userId, - freshOwnedIds = wire.owned.map { it.id } + mutationQueue.pendingPlaylistCreateIds(), - all = all, - ) - } else { - playlistDao.upsertAll(all) - } - } - - /** - * Pulls `GET /api/playlists/{id}` and persists both the playlist - * row and its ordered track membership. Returns the freshly- - * hydrated detail (with full per-track display fields) for the - * detail screen to render immediately — Room only persists the - * track-membership IDs, not the display fields. - */ - suspend fun refreshDetail(id: String): PlaylistDetailRef { - val wire = try { - api.get(id) - } catch (e: HttpException) { - // Server says this playlist is gone — drop the stale cache - // row so the list stops showing it. - if (e.code() == HttpURLConnection.HTTP_NOT_FOUND) { - playlistDao.deleteByIds(listOf(id)) - } - throw e - } - playlistDao.upsertAll(listOf(wire.toPlaylistEntity())) - playlistTrackDao.replacePlaylistTracks( - playlistId = id, - rows = wire.tracks.mapNotNull { row -> - row.trackId?.let { trackId -> - CachedPlaylistTrackEntity( - playlistId = id, - trackId = trackId, - position = row.position, - ) + /** + * The signed-in listener's own playlists, not mixes and not other + * people's public lists: the ones a song can be added to. + */ + @OptIn(ExperimentalCoroutinesApi::class) + fun observeOwnPlaylists(): Flow> = + authController.currentUser.flatMapLatest { user -> + if (user == null) { + flowOf(emptyList()) + } else { + playlistDao.observeOwnedUserPlaylists(user.id).map { rows -> rows.map { it.toDomain() } } } - }, - ) - return PlaylistDetailRef( - playlist = wire.toPlaylistRef(), - tracks = wire.tracks.map { it.toDomain() }, - ) - } + } - /** - * Rebuilds the caller's system playlist of [variant]. The server - * rotates the playlist's UUID on rebuild — the returned id (null - * when the library can't seed a build) is what callers should - * navigate to. List cache is refreshed so home-row tiles point at - * the fresh uuid. - */ - suspend fun refreshSystemPlaylist(variant: String): String? { - val response = api.refreshSystem(variant) - runCatching { refreshList() } - return response.playlistId - } + /** Server-generated system playlists (for_you / discover / etc.). */ + fun observeSystemPlaylists(): Flow> = + playlistDao.observeSystemPlaylists().map { rows -> + rows.map { it.toDomain() } + } - /** - * Pulls the rotation-aware shuffled tracks for a refreshable system - * playlist without rebuilding. Used by Home's play-button overlay - * to advance For You / Discover / Today's mix rotation on tap. No - * Room write — the server's rotation order is per-call, not stored. - */ - suspend fun systemShuffle(variant: String): PlaylistDetailRef { - val wire = api.systemShuffle(variant) - return PlaylistDetailRef( - playlist = wire.toPlaylistRef(), - tracks = wire.tracks.map { it.toDomain() }, - ) - } + suspend fun getPlaylist(id: String): PlaylistRef? = playlistDao.getById(id)?.toDomain() - // ── Writes to the listener's own playlists ─────────────────────── - // - // Each follows the offline-first write contract: change Room first so - // every screen shows it at once, send it, and on a transport failure - // queue it for MutationReplayer. Membership positions in Room are - // best-effort; the next detail fetch puts the server's back. + // ── Server refreshes ────────────────────────────────────────────── - /** - * Append a single track to a user-owned playlist. The (playlistId, - * trackId) key means a song already in the list keeps its place in - * Room. The send and its queued replay carry one request id, so a - * replay of a send that reached the server, but whose reply didn't - * reach the phone, doesn't add the song a second time. - */ - suspend fun appendTrack(playlistId: String, trackId: String): WriteOutcome { - val nextPos = (playlistTrackDao.maxPosition(playlistId) ?: -1) + 1 - playlistTrackDao.insertOrIgnore( - CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = nextPos), - ) - val append = PlaylistAppendPayload(playlistId, listOf(trackId), requestId = UUID.randomUUID().toString()) - return sendOrQueue( - send = { api.appendTracks(playlistId, AppendTracksRequest(append.trackIds, append.requestId)) }, - queue = { mutationQueue.enqueuePlaylistAppend(append) }, - ) - } + /** + * Pulls `GET /api/playlists?kind=all` and replaces the local + * playlist cache. Per-playlist track rows come from refreshDetail. + */ + suspend fun refreshList() { + val wire = api.list(kind = "all") + val all = (wire.owned + wire.public).map { it.toEntity() } + val userId = authController.currentUser.value?.id + if (userId != null) { + // Reconcile: BuildSystemPlaylists rotates system-playlist + // UUIDs every rebuild, so upsert alone leaves stale rows + // whose detail fetch 404s ("That playlist no longer + // exists"). + // A list made offline isn't on the server yet; keep it. + playlistDao.replaceList( + userId = userId, + freshOwnedIds = wire.owned.map { it.id } + mutationQueue.pendingPlaylistCreateIds(), + all = all, + ) + } else { + playlistDao.upsertAll(all) + } + } - /** - * Makes a private playlist called [name] and returns its id. The id is - * made here, so the list can be opened, filled and shown before the - * server has heard of it. - */ - suspend fun createPlaylist(name: String): Pair { - val id = UUID.randomUUID().toString() - val userId = authController.currentUser.value?.id.orEmpty() - playlistDao.upsertAll(listOf(CachedPlaylistEntity(id = id, userId = userId, name = name))) - val outcome = sendOrQueue( - send = { api.create(CreatePlaylistRequest(id = id, name = name)) }, - queue = { mutationQueue.enqueuePlaylistCreate(PlaylistCreatePayload(id = id, name = name)) }, - ) - return id to outcome - } - - /** Renames a playlist or makes it public or private; a null argument is left as it is. */ - suspend fun updatePlaylist(id: String, name: String? = null, isPublic: Boolean? = null): WriteOutcome { - playlistDao.getById(id)?.let { row -> - playlistDao.upsertAll( - listOf(row.copy(name = name ?: row.name, isPublic = isPublic ?: row.isPublic)), + /** + * Pulls `GET /api/playlists/{id}` and persists both the playlist + * row and its ordered track membership. Returns the freshly- + * hydrated detail (with full per-track display fields) for the + * detail screen to render immediately — Room only persists the + * track-membership IDs, not the display fields. + */ + suspend fun refreshDetail(id: String): PlaylistDetailRef { + val wire = + try { + api.get(id) + } catch (e: HttpException) { + // Server says this playlist is gone — drop the stale cache + // row so the list stops showing it. + if (e.code() == HttpURLConnection.HTTP_NOT_FOUND) { + playlistDao.deleteByIds(listOf(id)) + } + throw e + } + playlistDao.upsertAll(listOf(wire.toPlaylistEntity())) + playlistTrackDao.replacePlaylistTracks( + playlistId = id, + rows = + wire.tracks.mapNotNull { row -> + row.trackId?.let { trackId -> + CachedPlaylistTrackEntity( + playlistId = id, + trackId = trackId, + position = row.position, + ) + } + }, + ) + return PlaylistDetailRef( + playlist = wire.toPlaylistRef(), + tracks = wire.tracks.map { it.toDomain() }, ) } - return sendOrQueue( - send = { api.update(id, UpdatePlaylistRequest(name = name, isPublic = isPublic)) }, - queue = { mutationQueue.enqueuePlaylistUpdate(PlaylistUpdatePayload(id, name, isPublic)) }, - ) - } - suspend fun deletePlaylist(id: String): WriteOutcome { - playlistTrackDao.deleteByPlaylist(id) - playlistDao.deleteByIds(listOf(id)) - return sendOrQueue( - send = { api.delete(id) }, - queue = { mutationQueue.enqueuePlaylistDelete(id) }, - ) - } + /** + * Rebuilds the caller's system playlist of [variant]. The server + * rotates the playlist's UUID on rebuild — the returned id (null + * when the library can't seed a build) is what callers should + * navigate to. List cache is refreshed so home-row tiles point at + * the fresh uuid. + */ + suspend fun refreshSystemPlaylist(variant: String): String? { + val response = api.refreshSystem(variant) + runCatching { refreshList() } + return response.playlistId + } - /** - * Removes the entry at [position], which holds [trackId] (null for a - * song that has left the library). The server removes it only if that - * song is still there. - */ - suspend fun removeTrack(playlistId: String, position: Int, trackId: String?): WriteOutcome { - if (trackId != null) playlistTrackDao.deleteTracksFromPlaylist(playlistId, listOf(trackId)) - return sendOrQueue( - send = { api.removeTrack(playlistId, position, trackId) }, - queue = { - mutationQueue.enqueuePlaylistRemoveTrack(PlaylistRemoveTrackPayload(playlistId, position, trackId)) - }, - ) - } + /** + * Pulls the rotation-aware shuffled tracks for a refreshable system + * playlist without rebuilding. Used by Home's play-button overlay + * to advance For You / Discover / Today's mix rotation on tap. No + * Room write — the server's rotation order is per-call, not stored. + */ + suspend fun systemShuffle(variant: String): PlaylistDetailRef { + val wire = api.systemShuffle(variant) + return PlaylistDetailRef( + playlist = wire.toPlaylistRef(), + tracks = wire.tracks.map { it.toDomain() }, + ) + } - /** Puts the playlist's songs in the order [trackIds] gives. */ - suspend fun reorderTracks(playlistId: String, trackIds: List): WriteOutcome { - playlistTrackDao.replacePlaylistTracks( - playlistId = playlistId, - rows = trackIds.distinct().mapIndexed { i, trackId -> - CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = i) - }, - ) - return sendOrQueue( - send = { api.reorder(playlistId, ReorderTracksRequest(trackIds = trackIds)) }, - queue = { mutationQueue.enqueuePlaylistReorder(PlaylistReorderPayload(playlistId, trackIds)) }, - ) + // ── Writes to the listener's own playlists ─────────────────────── + // + // Each follows the offline-first write contract: change Room first so + // every screen shows it at once, send it, and on a transport failure + // queue it for MutationReplayer. Membership positions in Room are + // best-effort; the next detail fetch puts the server's back. + + /** + * Append a single track to a user-owned playlist. The (playlistId, + * trackId) key means a song already in the list keeps its place in + * Room. The send and its queued replay carry one request id, so a + * replay of a send that reached the server, but whose reply didn't + * reach the phone, doesn't add the song a second time. + */ + suspend fun appendTrack( + playlistId: String, + trackId: String, + ): WriteOutcome { + val nextPos = (playlistTrackDao.maxPosition(playlistId) ?: -1) + 1 + playlistTrackDao.insertOrIgnore( + CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = nextPos), + ) + val append = PlaylistAppendPayload(playlistId, listOf(trackId), requestId = UUID.randomUUID().toString()) + return sendOrQueue( + send = { api.appendTracks(playlistId, AppendTracksRequest(append.trackIds, append.requestId)) }, + queue = { mutationQueue.enqueuePlaylistAppend(append) }, + ) + } + + /** + * Makes a private playlist called [name] and returns its id. The id is + * made here, so the list can be opened, filled and shown before the + * server has heard of it. + */ + suspend fun createPlaylist(name: String): Pair { + val id = UUID.randomUUID().toString() + val userId = + authController.currentUser.value + ?.id + .orEmpty() + playlistDao.upsertAll(listOf(CachedPlaylistEntity(id = id, userId = userId, name = name))) + val outcome = + sendOrQueue( + send = { api.create(CreatePlaylistRequest(id = id, name = name)) }, + queue = { mutationQueue.enqueuePlaylistCreate(PlaylistCreatePayload(id = id, name = name)) }, + ) + return id to outcome + } + + /** Renames a playlist or makes it public or private; a null argument is left as it is. */ + suspend fun updatePlaylist( + id: String, + name: String? = null, + isPublic: Boolean? = null, + ): WriteOutcome { + playlistDao.getById(id)?.let { row -> + playlistDao.upsertAll( + listOf(row.copy(name = name ?: row.name, isPublic = isPublic ?: row.isPublic)), + ) + } + return sendOrQueue( + send = { api.update(id, UpdatePlaylistRequest(name = name, isPublic = isPublic)) }, + queue = { mutationQueue.enqueuePlaylistUpdate(PlaylistUpdatePayload(id, name, isPublic)) }, + ) + } + + suspend fun deletePlaylist(id: String): WriteOutcome { + playlistTrackDao.deleteByPlaylist(id) + playlistDao.deleteByIds(listOf(id)) + return sendOrQueue( + send = { api.delete(id) }, + queue = { mutationQueue.enqueuePlaylistDelete(id) }, + ) + } + + /** + * Removes the entry at [position], which holds [trackId] (null for a + * song that has left the library). The server removes it only if that + * song is still there. + */ + suspend fun removeTrack( + playlistId: String, + position: Int, + trackId: String?, + ): WriteOutcome { + if (trackId != null) playlistTrackDao.deleteTracksFromPlaylist(playlistId, listOf(trackId)) + return sendOrQueue( + send = { api.removeTrack(playlistId, position, trackId) }, + queue = { + mutationQueue.enqueuePlaylistRemoveTrack(PlaylistRemoveTrackPayload(playlistId, position, trackId)) + }, + ) + } + + /** Puts the playlist's songs in the order [trackIds] gives. */ + suspend fun reorderTracks( + playlistId: String, + trackIds: List, + ): WriteOutcome { + playlistTrackDao.replacePlaylistTracks( + playlistId = playlistId, + rows = + trackIds.distinct().mapIndexed { i, trackId -> + CachedPlaylistTrackEntity(playlistId = playlistId, trackId = trackId, position = i) + }, + ) + return sendOrQueue( + send = { api.reorder(playlistId, ReorderTracksRequest(trackIds = trackIds)) }, + queue = { mutationQueue.enqueuePlaylistReorder(PlaylistReorderPayload(playlistId, trackIds)) }, + ) + } } -} /** * Snapshot of a playlist + its per-track display fields, as returned diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt index ad1741b5..397f1831 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistDetailScreen.kt @@ -66,6 +66,7 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.events.EventsStream import com.fabledsword.minstrel.events.LiveEvent +import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.likes.data.toggleTrackLike import com.fabledsword.minstrel.models.PlaylistRef import com.fabledsword.minstrel.models.PlaylistTrackRef @@ -75,7 +76,6 @@ import com.fabledsword.minstrel.nav.ArtistDetail import com.fabledsword.minstrel.nav.DetailSeedCache import com.fabledsword.minstrel.nav.PlaylistDetail import com.fabledsword.minstrel.player.PlayerController -import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.playlists.data.PlaylistDetailRef import com.fabledsword.minstrel.playlists.data.PlaylistsRepository import com.fabledsword.minstrel.playlists.data.entryKeys @@ -88,16 +88,16 @@ import com.fabledsword.minstrel.shared.plural import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog import com.fabledsword.minstrel.shared.widgets.CoverFallbackIcon import com.fabledsword.minstrel.shared.widgets.CoverTile +import com.fabledsword.minstrel.shared.widgets.ErrorRetry +import com.fabledsword.minstrel.shared.widgets.LikeButton import com.fabledsword.minstrel.shared.widgets.NameDialog +import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.ReorderHandles import com.fabledsword.minstrel.shared.widgets.ReorderableRemovableRow import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets -import com.fabledsword.minstrel.shared.widgets.TrackRow -import com.fabledsword.minstrel.shared.widgets.ErrorRetry -import com.fabledsword.minstrel.shared.widgets.LikeButton -import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold import com.fabledsword.minstrel.shared.widgets.SkeletonTrackRow import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb +import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job @@ -121,268 +121,292 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L // ─── State ─────────────────────────────────────────────────────────── sealed interface PlaylistDetailUiState { - data class Loading(val seed: PlaylistRef? = null) : PlaylistDetailUiState - data class Success(val detail: PlaylistDetailRef) : PlaylistDetailUiState - data class Error(val message: String) : PlaylistDetailUiState + data class Loading( + val seed: PlaylistRef? = null, + ) : PlaylistDetailUiState + + data class Success( + val detail: PlaylistDetailRef, + ) : PlaylistDetailUiState + + data class Error( + val message: String, + ) : PlaylistDetailUiState } // ─── ViewModel ─────────────────────────────────────────────────────── @HiltViewModel -class PlaylistDetailViewModel @Inject constructor( - private val repository: PlaylistsRepository, - private val likes: LikesRepository, - private val player: PlayerController, - private val eventsStream: EventsStream, - private val seedCache: DetailSeedCache, - private val authController: AuthController, - networkStatus: NetworkStatusController, - savedStateHandle: SavedStateHandle, -) : ViewModel() { +class PlaylistDetailViewModel + @Inject + constructor( + private val repository: PlaylistsRepository, + private val likes: LikesRepository, + private val player: PlayerController, + private val eventsStream: EventsStream, + private val seedCache: DetailSeedCache, + private val authController: AuthController, + networkStatus: NetworkStatusController, + savedStateHandle: SavedStateHandle, + ) : ViewModel() { + private val route: PlaylistDetail = savedStateHandle.toRoute() + val playlistId: String = route.id - private val route: PlaylistDetail = savedStateHandle.toRoute() - val playlistId: String = route.id + private val internal = + MutableStateFlow(PlaylistDetailUiState.Loading()) + val uiState: StateFlow = internal.asStateFlow() - private val internal = - MutableStateFlow(PlaylistDetailUiState.Loading()) - val uiState: StateFlow = internal.asStateFlow() + /** + * One-shot signal: this playlist was deleted (server-side or from + * another client). The screen collects this and pops back so the + * user doesn't sit on a now-404 detail. + */ + private val deletedChannel = Channel(Channel.BUFFERED) + val deleted: Flow = deletedChannel.receiveAsFlow() - /** - * One-shot signal: this playlist was deleted (server-side or from - * another client). The screen collects this and pops back so the - * user doesn't sit on a now-404 detail. - */ - private val deletedChannel = Channel(Channel.BUFFERED) - val deleted: Flow = deletedChannel.receiveAsFlow() + /** + * One-shot signal: a system playlist regenerate landed and the + * server rotated the uuid. Screen replaces the current detail + * route with the new id so the user sees the fresh list. + */ + private val regeneratedChannel = Channel(Channel.BUFFERED) + val regenerated: Flow = regeneratedChannel.receiveAsFlow() - /** - * One-shot signal: a system playlist regenerate landed and the - * server rotated the uuid. Screen replaces the current detail - * route with the new id so the user sees the fresh list. - */ - private val regeneratedChannel = Channel(Channel.BUFFERED) - val regenerated: Flow = regeneratedChannel.receiveAsFlow() + /** + * A system-playlist rebuild landed (SSE) while this screen is open — + * its list is now stale and the uuid has rotated. Drives a "this mix was + * refreshed → Refresh" snackbar rather than yanking the user; Refresh + * re-resolves the variant via [reloadRebuilt]. + */ + private val staleInternal = MutableStateFlow(false) + val stale: StateFlow = staleInternal.asStateFlow() - /** - * A system-playlist rebuild landed (SSE) while this screen is open — - * its list is now stale and the uuid has rotated. Drives a "this mix was - * refreshed → Refresh" snackbar rather than yanking the user; Refresh - * re-resolves the variant via [reloadRebuilt]. - */ - private val staleInternal = MutableStateFlow(false) - val stale: StateFlow = staleInternal.asStateFlow() + /** A change the server refused, for the screen's snackbar. */ + private val messagesChannel = Channel(Channel.BUFFERED) + val messages: Flow = messagesChannel.receiveAsFlow() - /** A change the server refused, for the screen's snackbar. */ - private val messagesChannel = Channel(Channel.BUFFERED) - val messages: Flow = messagesChannel.receiveAsFlow() - - val likedTrackIds: StateFlow> = - likes.observeLikedTrackIds() - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = emptySet(), - ) - - init { - refresh() - viewModelScope.launch { - eventsStream.events - .filter { it.kind.startsWith("playlist.") } - .collect { handlePlaylistEvent(it) } - } - // Screen-level auto-recovery: a detail that failed to - // load while the server was unreachable re-fetches when health - // returns, instead of waiting for the Retry tap. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value is PlaylistDetailUiState.Error) refresh() - } - } - } - - /** - * Filters playlist.* events to those touching this screen's id. - * delete → pop the screen; updated / tracks_changed → re-fetch. - * Other kinds (e.g. playlist.created for a different list) are - * ignored — the playlists-list screen handles those. - */ - private fun handlePlaylistEvent(event: LiveEvent) { - // A system rebuild carries no playlist_id (it rebuilds all of the - // user's system mixes at once) — handle it before the per-id filter. - if (event.kind == "playlist.system_rebuilt") { - markStaleIfSystem() - return - } - val eventPlaylistId = event.data["playlist_id"]?.jsonPrimitive?.contentOrNull - if (eventPlaylistId != playlistId) return - when (event.kind) { - "playlist.deleted" -> deletedChannel.trySend(Unit) - "playlist.updated", "playlist.tracks_changed" -> refresh() - } - } - - private fun markStaleIfSystem() { - val playlist = (internal.value as? PlaylistDetailUiState.Success) - ?.detail?.playlist ?: return - if (playlist.systemVariant?.takeIf { playlist.refreshable } != null) { - staleInternal.value = true - } - } - - fun toggleLikeTrack(trackId: String) { - viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } - } - - /** - * Re-fetches the playlist. A list already on screen stays there while - * it loads, and stays if the fetch fails: a refresh after every change - * (the server's event for it) must not blank the list each time, and - * offline the list the listener just edited is the best one there is. - */ - fun refresh(): Job = viewModelScope.launch { - val shown = internal.value is PlaylistDetailUiState.Success - try { - if (!shown) { - val carried = (internal.value as? PlaylistDetailUiState.Loading)?.seed - internal.value = PlaylistDetailUiState.Loading( - carried ?: seedCache.peekPlaylist(playlistId), + val likedTrackIds: StateFlow> = + likes + .observeLikedTrackIds() + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = emptySet(), ) + + init { + refresh() + viewModelScope.launch { + eventsStream.events + .filter { it.kind.startsWith("playlist.") } + .collect { handlePlaylistEvent(it) } } - val detail = repository.refreshDetail(playlistId) - internal.value = PlaylistDetailUiState.Success(detail) - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - if (!shown) internal.value = PlaylistDetailUiState.Error(ErrorCopy.fromThrowable(e)) - } - } - - // ─── The owner's edits ────────────────────────────────────────── - // - // Each shows at once, then goes to the repository, which sends it or - // queues it for when the server is back. A change the server refuses - // says so and re-fetches, so the screen shows what is really there. - - /** Only the owner edits a playlist, and nobody edits a mix. */ - fun canEdit(playlist: PlaylistRef): Boolean = - !playlist.isSystem && playlist.userId == authController.currentUser.value?.id - - fun rename(name: String) { - val d = shownDetail() ?: return - show(d.copy(playlist = d.playlist.copy(name = name))) - save { repository.updatePlaylist(playlistId, name = name) } - } - - fun setPublic(isPublic: Boolean) { - val d = shownDetail() ?: return - show(d.copy(playlist = d.playlist.copy(isPublic = isPublic))) - save { repository.updatePlaylist(playlistId, isPublic = isPublic) } - } - - /** Deletes the playlist and leaves the screen. */ - fun delete() { - viewModelScope.launch { - runCatching { repository.deletePlaylist(playlistId) } - .onSuccess { deletedChannel.trySend(Unit) } - .onFailure { messagesChannel.trySend("Couldn't delete: ${ErrorCopy.fromThrowable(it)}") } - } - } - - fun removeAt(index: Int) { - val d = shownDetail() ?: return - val row = d.tracks.getOrNull(index) ?: return - show(d.withoutEntry(index)) - save { repository.removeTrack(playlistId, row.position, row.trackId) } - } - - fun move(from: Int, to: Int) { - val d = shownDetail() ?: return - val moved = d.withEntryMoved(from, to) - if (moved === d) return - show(moved) - save { repository.reorderTracks(playlistId, moved.trackOrder()) } - } - - private fun shownDetail(): PlaylistDetailRef? = - (internal.value as? PlaylistDetailUiState.Success)?.detail - - private fun show(detail: PlaylistDetailRef) { - internal.value = PlaylistDetailUiState.Success(detail) - } - - private fun save(write: suspend () -> WriteOutcome) { - viewModelScope.launch { - runCatching { write() }.onFailure { - messagesChannel.trySend("Couldn't save: ${ErrorCopy.fromThrowable(it)}") - refresh() + // Screen-level auto-recovery: a detail that failed to + // load while the server was unreachable re-fetches when health + // returns, instead of waiting for the Retry tap. + viewModelScope.launch { + networkStatus.recoveries().collect { + if (internal.value is PlaylistDetailUiState.Error) refresh() + } } } - } - /** - * Server-side rebuild of this system playlist. No-op when the - * playlist isn't a refreshable system variant. On success the - * server rotates the playlist uuid; the new id arrives on - * [regenerated] for the screen to navigate-replace to. - */ - fun regenerate() { - val playlist = (internal.value as? PlaylistDetailUiState.Success) - ?.detail?.playlist ?: return - val variant = playlist.systemVariant - ?.takeIf { playlist.refreshable } ?: return - viewModelScope.launch { - runCatching { repository.refreshSystemPlaylist(variant) } - .onSuccess { newId -> - if (!newId.isNullOrEmpty()) { - regeneratedChannel.trySend(newId) + /** + * Filters playlist.* events to those touching this screen's id. + * delete → pop the screen; updated / tracks_changed → re-fetch. + * Other kinds (e.g. playlist.created for a different list) are + * ignored — the playlists-list screen handles those. + */ + private fun handlePlaylistEvent(event: LiveEvent) { + // A system rebuild carries no playlist_id (it rebuilds all of the + // user's system mixes at once) — handle it before the per-id filter. + if (event.kind == "playlist.system_rebuilt") { + markStaleIfSystem() + return + } + val eventPlaylistId = event.data["playlist_id"]?.jsonPrimitive?.contentOrNull + if (eventPlaylistId != playlistId) return + when (event.kind) { + "playlist.deleted" -> deletedChannel.trySend(Unit) + "playlist.updated", "playlist.tracks_changed" -> refresh() + } + } + + private fun markStaleIfSystem() { + val playlist = + (internal.value as? PlaylistDetailUiState.Success) + ?.detail + ?.playlist ?: return + if (playlist.systemVariant?.takeIf { playlist.refreshable } != null) { + staleInternal.value = true + } + } + + fun toggleLikeTrack(trackId: String) { + viewModelScope.launch { likes.toggleTrackLike(trackId, likedTrackIds.value) } + } + + /** + * Re-fetches the playlist. A list already on screen stays there while + * it loads, and stays if the fetch fails: a refresh after every change + * (the server's event for it) must not blank the list each time, and + * offline the list the listener just edited is the best one there is. + */ + fun refresh(): Job = + viewModelScope.launch { + val shown = internal.value is PlaylistDetailUiState.Success + try { + if (!shown) { + val carried = (internal.value as? PlaylistDetailUiState.Loading)?.seed + internal.value = + PlaylistDetailUiState.Loading( + carried ?: seedCache.peekPlaylist(playlistId), + ) } + val detail = repository.refreshDetail(playlistId) + internal.value = PlaylistDetailUiState.Success(detail) + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + if (!shown) internal.value = PlaylistDetailUiState.Error(ErrorCopy.fromThrowable(e)) } + } + + // ─── The owner's edits ────────────────────────────────────────── + // + // Each shows at once, then goes to the repository, which sends it or + // queues it for when the server is back. A change the server refuses + // says so and re-fetches, so the screen shows what is really there. + + /** Only the owner edits a playlist, and nobody edits a mix. */ + fun canEdit(playlist: PlaylistRef): Boolean = !playlist.isSystem && playlist.userId == authController.currentUser.value?.id + + fun rename(name: String) { + val d = shownDetail() ?: return + show(d.copy(playlist = d.playlist.copy(name = name))) + save { repository.updatePlaylist(playlistId, name = name) } + } + + fun setPublic(isPublic: Boolean) { + val d = shownDetail() ?: return + show(d.copy(playlist = d.playlist.copy(isPublic = isPublic))) + save { repository.updatePlaylist(playlistId, isPublic = isPublic) } + } + + /** Deletes the playlist and leaves the screen. */ + fun delete() { + viewModelScope.launch { + runCatching { repository.deletePlaylist(playlistId) } + .onSuccess { deletedChannel.trySend(Unit) } + .onFailure { messagesChannel.trySend("Couldn't delete: ${ErrorCopy.fromThrowable(it)}") } + } + } + + fun removeAt(index: Int) { + val d = shownDetail() ?: return + val row = d.tracks.getOrNull(index) ?: return + show(d.withoutEntry(index)) + save { repository.removeTrack(playlistId, row.position, row.trackId) } + } + + fun move( + from: Int, + to: Int, + ) { + val d = shownDetail() ?: return + val moved = d.withEntryMoved(from, to) + if (moved === d) return + show(moved) + save { repository.reorderTracks(playlistId, moved.trackOrder()) } + } + + private fun shownDetail(): PlaylistDetailRef? = (internal.value as? PlaylistDetailUiState.Success)?.detail + + private fun show(detail: PlaylistDetailRef) { + internal.value = PlaylistDetailUiState.Success(detail) + } + + private fun save(write: suspend () -> WriteOutcome) { + viewModelScope.launch { + runCatching { write() }.onFailure { + messagesChannel.trySend("Couldn't save: ${ErrorCopy.fromThrowable(it)}") + refresh() + } + } + } + + /** + * Server-side rebuild of this system playlist. No-op when the + * playlist isn't a refreshable system variant. On success the + * server rotates the playlist uuid; the new id arrives on + * [regenerated] for the screen to navigate-replace to. + */ + fun regenerate() { + val playlist = + (internal.value as? PlaylistDetailUiState.Success) + ?.detail + ?.playlist ?: return + val variant = + playlist.systemVariant + ?.takeIf { playlist.refreshable } ?: return + viewModelScope.launch { + runCatching { repository.refreshSystemPlaylist(variant) } + .onSuccess { newId -> + if (!newId.isNullOrEmpty()) { + regeneratedChannel.trySend(newId) + } + } + } + } + + /** + * User tapped Refresh on the stale-view snackbar. The rebuild + * already ran server-side (uuid rotated) — re-resolve the variant to the + * fresh playlist id and hand it to [regenerated] for navigate-replace. + * Unlike [regenerate] this does NOT trigger another rebuild. + */ + fun reloadRebuilt() { + val playlist = + (internal.value as? PlaylistDetailUiState.Success) + ?.detail + ?.playlist ?: return + val variant = playlist.systemVariant?.takeIf { playlist.refreshable } ?: return + staleInternal.value = false + viewModelScope.launch { + runCatching { repository.systemShuffle(variant).playlist.id } + .onSuccess { newId -> + if (newId.isNotEmpty()) regeneratedChannel.trySend(newId) + } + } + } + + /** User dismissed the stale-view snackbar without refreshing. */ + fun dismissStale() { + staleInternal.value = false + } + + /** Play the available tracks starting at [startTrackId] (or first available). */ + fun play( + tracks: List, + startTrackId: String?, + ) { + val refs = tracks.toPlayableTrackRefs() + if (refs.isEmpty()) return + val startIndex = refs.indexOfFirst { it.id == startTrackId }.coerceAtLeast(0) + // For refreshable system playlists, send the bare + // systemVariant string so the rotation matcher + // (systemPlaylistSources in playevents/writer.go) sees the + // play. User playlists keep the "playlist:" tag for + // attribution but it doesn't trigger rotation (intentional — + // rotation only applies to system mixes). + val playlist = (internal.value as? PlaylistDetailUiState.Success)?.detail?.playlist + val source = + playlist?.systemVariant?.takeIf { playlist.refreshable } + ?: "playlist:$playlistId" + player.setQueue(refs, initialIndex = startIndex, source = source) } } - /** - * User tapped Refresh on the stale-view snackbar. The rebuild - * already ran server-side (uuid rotated) — re-resolve the variant to the - * fresh playlist id and hand it to [regenerated] for navigate-replace. - * Unlike [regenerate] this does NOT trigger another rebuild. - */ - fun reloadRebuilt() { - val playlist = (internal.value as? PlaylistDetailUiState.Success) - ?.detail?.playlist ?: return - val variant = playlist.systemVariant?.takeIf { playlist.refreshable } ?: return - staleInternal.value = false - viewModelScope.launch { - runCatching { repository.systemShuffle(variant).playlist.id } - .onSuccess { newId -> - if (newId.isNotEmpty()) regeneratedChannel.trySend(newId) - } - } - } - - /** User dismissed the stale-view snackbar without refreshing. */ - fun dismissStale() { - staleInternal.value = false - } - - /** Play the available tracks starting at [startTrackId] (or first available). */ - fun play(tracks: List, startTrackId: String?) { - val refs = tracks.toPlayableTrackRefs() - if (refs.isEmpty()) return - val startIndex = refs.indexOfFirst { it.id == startTrackId }.coerceAtLeast(0) - // For refreshable system playlists, send the bare - // systemVariant string so the rotation matcher - // (systemPlaylistSources in playevents/writer.go) sees the - // play. User playlists keep the "playlist:" tag for - // attribution but it doesn't trigger rotation (intentional — - // rotation only applies to system mixes). - val playlist = (internal.value as? PlaylistDetailUiState.Success)?.detail?.playlist - val source = playlist?.systemVariant?.takeIf { playlist.refreshable } - ?: "playlist:$playlistId" - player.setQueue(refs, initialIndex = startIndex, source = source) - } -} - // ─── Screen ────────────────────────────────────────────────────────── @OptIn(ExperimentalMaterial3Api::class) @@ -419,13 +443,17 @@ fun PlaylistDetailScreen( val stale by viewModel.stale.collectAsState() LaunchedEffect(stale) { if (stale) { - val result = snackbarHostState.showSnackbar( - message = "This mix was refreshed", - actionLabel = "Refresh", - duration = SnackbarDuration.Indefinite, - ) - if (result == SnackbarResult.ActionPerformed) viewModel.reloadRebuilt() - else viewModel.dismissStale() + val result = + snackbarHostState.showSnackbar( + message = "This mix was refreshed", + actionLabel = "Refresh", + duration = SnackbarDuration.Indefinite, + ) + if (result == SnackbarResult.ActionPerformed) { + viewModel.reloadRebuilt() + } else { + viewModel.dismissStale() + } } } Scaffold( @@ -489,45 +517,49 @@ private fun PlaylistDetailContent( // Crossfade keyed on `state::class` so refreshes that emit a // fresh Success (same kind, new detail) don't re-fade the body; // only Loading ↔ Success ↔ Error transitions animate. - Crossfade(targetState = state::class, label = "playlist-detail") { _ -> when (val s = state) { - is PlaylistDetailUiState.Loading -> - s.seed?.let { SeededPlaylistLoading(it) } ?: SkeletonPlaylistTrackList() - is PlaylistDetailUiState.Error -> ErrorRetry( - title = "Couldn't load playlist", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is PlaylistDetailUiState.Success -> { - val likedTrackIds by viewModel.likedTrackIds.collectAsState() - val playerState by playerViewModel.uiState.collectAsState() - PlaylistDetailBody( - detail = s.detail, - editable = viewModel.canEdit(s.detail.playlist), - onRemove = viewModel::removeAt, - onMove = viewModel::move, - likedTrackIds = likedTrackIds, - playingTrackId = playerState.currentTrack?.id, - onPlayAll = { viewModel.play(s.detail.tracks, startTrackId = null) }, - onShuffleAll = { - viewModel.play(s.detail.tracks.shuffled(), startTrackId = null) - }, - onRegenerate = viewModel::regenerate, - onTrackClick = { id -> - viewModel.play(s.detail.tracks, startTrackId = id) - }, - onToggleTrackLike = viewModel::toggleLikeTrack, - onNavigateToAlbum = { id -> navController.navigate(AlbumDetail(id)) }, - onNavigateToArtist = { id -> navController.navigate(ArtistDetail(id)) }, - ) + Crossfade(targetState = state::class, label = "playlist-detail") { _ -> + when (val s = state) { + is PlaylistDetailUiState.Loading -> + s.seed?.let { SeededPlaylistLoading(it) } ?: SkeletonPlaylistTrackList() + is PlaylistDetailUiState.Error -> + ErrorRetry( + title = "Couldn't load playlist", + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is PlaylistDetailUiState.Success -> { + val likedTrackIds by viewModel.likedTrackIds.collectAsState() + val playerState by playerViewModel.uiState.collectAsState() + PlaylistDetailBody( + detail = s.detail, + editable = viewModel.canEdit(s.detail.playlist), + onRemove = viewModel::removeAt, + onMove = viewModel::move, + likedTrackIds = likedTrackIds, + playingTrackId = playerState.currentTrack?.id, + onPlayAll = { viewModel.play(s.detail.tracks, startTrackId = null) }, + onShuffleAll = { + viewModel.play(s.detail.tracks.shuffled(), startTrackId = null) + }, + onRegenerate = viewModel::regenerate, + onTrackClick = { id -> + viewModel.play(s.detail.tracks, startTrackId = id) + }, + onToggleTrackLike = viewModel::toggleLikeTrack, + onNavigateToAlbum = { id -> navController.navigate(AlbumDetail(id)) }, + onNavigateToArtist = { id -> navController.navigate(ArtistDetail(id)) }, + ) + } } - } } + } } -private fun currentTitle(state: PlaylistDetailUiState): String = when (state) { - is PlaylistDetailUiState.Success -> state.detail.playlist.name - is PlaylistDetailUiState.Loading -> state.seed?.name ?: "Playlist" - is PlaylistDetailUiState.Error -> "Playlist" -} +private fun currentTitle(state: PlaylistDetailUiState): String = + when (state) { + is PlaylistDetailUiState.Success -> state.detail.playlist.name + is PlaylistDetailUiState.Loading -> state.seed?.name ?: "Playlist" + is PlaylistDetailUiState.Error -> "Playlist" + } // ─── Body composables ──────────────────────────────────────────────── @@ -601,9 +633,10 @@ private fun PlaylistHeader( onRegenerate: () -> Unit, ) { Column( - modifier = Modifier - .fillMaxWidth() - .padding(16.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { Row( @@ -711,11 +744,12 @@ private fun TrackRow( trackId = row.trackId.orEmpty(), onClick = onClick, // An editable row is opaque: it sits on the swipe's remove colour. - modifier = if (handles == null) { - Modifier - } else { - Modifier.background(MaterialTheme.colorScheme.background).then(handles.actions) - }, + modifier = + if (handles == null) { + Modifier + } else { + Modifier.background(MaterialTheme.colorScheme.background).then(handles.actions) + }, nowPlaying = nowPlaying, enabled = enabled, contentAlpha = rowAlpha, @@ -764,19 +798,31 @@ private fun PlaylistOwnerMenu( Icon(Lucide.EllipsisVertical, contentDescription = "Playlist options") } DropdownMenu(expanded = open, onDismissRequest = { open = false }) { - DropdownMenuItem(text = { Text("Rename") }, onClick = { open = false; renaming = true }) + DropdownMenuItem(text = { Text("Rename") }, onClick = { + open = false + renaming = true + }) DropdownMenuItem( text = { Text(if (playlist.isPublic) "Make private" else "Make public") }, - onClick = { open = false; onSetPublic(!playlist.isPublic) }, + onClick = { + open = false + onSetPublic(!playlist.isPublic) + }, ) - DropdownMenuItem(text = { Text("Delete") }, onClick = { open = false; deleting = true }) + DropdownMenuItem(text = { Text("Delete") }, onClick = { + open = false + deleting = true + }) } if (renaming) { NameDialog( title = "Rename playlist", confirmLabel = "Rename", initial = playlist.name, - onConfirm = { name -> renaming = false; onRename(name) }, + onConfirm = { name -> + renaming = false + onRename(name) + }, onDismiss = { renaming = false }, ) } @@ -785,7 +831,10 @@ private fun PlaylistOwnerMenu( title = "Delete playlist?", text = "Delete \"${playlist.name}\"? The songs stay in your library.", confirmLabel = "Delete", - onConfirm = { deleting = false; onDelete() }, + onConfirm = { + deleting = false + onDelete() + }, onDismiss = { deleting = false }, ) } @@ -855,13 +904,14 @@ private const val UNAVAILABLE_ALPHA = 0.4f * Lossy mapping: PlaylistTrackRef → TrackRef so the player can take it. * Caller must filter `isAvailable && streamUrl != null` first. */ -private fun PlaylistTrackRef.toTrackRef(): TrackRef = TrackRef( - id = trackId.orEmpty(), - title = title, - albumId = albumId.orEmpty(), - artistId = artistId.orEmpty(), - albumTitle = albumTitle, - artistName = artistName, - durationSec = durationSec, - streamUrl = streamUrl.orEmpty(), -) +private fun PlaylistTrackRef.toTrackRef(): TrackRef = + TrackRef( + id = trackId.orEmpty(), + title = title, + albumId = albumId.orEmpty(), + artistId = artistId.orEmpty(), + albumTitle = albumTitle, + artistName = artistName, + durationSec = durationSec, + streamUrl = streamUrl.orEmpty(), + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt index 41b0bfbf..647771c8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/ui/PlaylistsListScreen.kt @@ -46,16 +46,16 @@ import com.fabledsword.minstrel.nav.Playlists import com.fabledsword.minstrel.player.PlayerController import com.fabledsword.minstrel.playlists.data.PlaylistsRepository import com.fabledsword.minstrel.playlists.data.playPlaylistShuffled +import com.fabledsword.minstrel.playlists.widgets.PlaylistCard import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.shared.asCacheFirstStateFlow -import com.fabledsword.minstrel.playlists.widgets.PlaylistCard -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.EmptyState import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.NameDialog import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.channels.Channel @@ -78,91 +78,94 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L // ─── ViewModel ─────────────────────────────────────────────────────── @HiltViewModel -class PlaylistsListViewModel @Inject constructor( - private val repository: PlaylistsRepository, - private val player: PlayerController, - private val eventsStream: EventsStream, - networkStatus: NetworkStatusController, -) : ViewModel() { +class PlaylistsListViewModel + @Inject + constructor( + private val repository: PlaylistsRepository, + private val player: PlayerController, + private val eventsStream: EventsStream, + networkStatus: NetworkStatusController, + ) : ViewModel() { + private val poolMessages = Channel(Channel.BUFFERED) - private val poolMessages = Channel(Channel.BUFFERED) + /** Transient snackbar messages from playlist tile play taps. */ + val transientMessages: Flow = poolMessages.receiveAsFlow() - /** Transient snackbar messages from playlist tile play taps. */ - val transientMessages: Flow = poolMessages.receiveAsFlow() + /** The id of a playlist just made here, for the screen to open. */ + private val createdChannel = Channel(Channel.BUFFERED) + val created: Flow = createdChannel.receiveAsFlow() - /** The id of a playlist just made here, for the screen to open. */ - private val createdChannel = Channel(Channel.BUFFERED) - val created: Flow = createdChannel.receiveAsFlow() + /** Cache-only: no link OR server unreachable (Unstable stays calm). Greys tiles. */ + val offline: StateFlow = + networkStatus.state + .map { it == ServerHealth.Offline || it == ServerHealth.ServerDown } + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = false, + ) - /** Cache-only: no link OR server unreachable (Unstable stays calm). Greys tiles. */ - val offline: StateFlow = networkStatus.state - .map { it == ServerHealth.Offline || it == ServerHealth.ServerDown } - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = false, - ) + /** Copy for the most recent list-refresh failure; null once one succeeds. */ + private val refreshError = MutableStateFlow(null) - /** Copy for the most recent list-refresh failure; null once one succeeds. */ - private val refreshError = MutableStateFlow(null) - - init { - refresh() - // Live updates: a playlist created/updated/deleted from another - // client should reflect here without a manual refresh. - viewModelScope.launch { - eventsStream.events - .filter { it.kind.startsWith("playlist.") } - .collect { refresh() } - } - // Screen-level auto-recovery: re-pull when server - // health returns, so a load that failed offline heals unprompted. - viewModelScope.launch { - networkStatus.recoveries().collect { refresh() } - } - } - - /** Re-pull the playlists list. Returns the Job for pull-to-refresh awaits. */ - fun refresh(): Job = viewModelScope.launch { - refreshError.value = null - runCatching { repository.refreshList() } - .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } - } - - /** - * Makes an empty playlist called [name] and opens it. Made offline, it - * waits in the list instead: its page can't load until the server has - * it. - */ - fun createPlaylist(name: String) { - viewModelScope.launch { - runCatching { repository.createPlaylist(name) } - .onSuccess { (id, outcome) -> if (outcome == WriteOutcome.Synced) createdChannel.trySend(id) } - .onFailure { poolMessages.trySend("Couldn't make the playlist: ${ErrorCopy.fromThrowable(it)}") } - } - } - - /** Tile play button: shuffle the playlist's tracks and start at index 0. */ - suspend fun playPlaylist(playlist: PlaylistRef) { - viewModelScope.launch { - playPlaylistShuffled(playlist, repository, player) { - poolMessages.trySend(it) + init { + refresh() + // Live updates: a playlist created/updated/deleted from another + // client should reflect here without a manual refresh. + viewModelScope.launch { + eventsStream.events + .filter { it.kind.startsWith("playlist.") } + .collect { refresh() } } - }.join() - } - - val uiState: StateFlow>> = - combine(repository.observeAll(), refreshError) { list, err -> - when { - list.isNotEmpty() -> UiState.Success(list) - // Empty cache + failed refresh is a load failure, not "no - // playlists yet" — surface Error so the user gets a Retry. - err != null -> UiState.Error(err) - else -> UiState.Empty + // Screen-level auto-recovery: re-pull when server + // health returns, so a load that failed offline heals unprompted. + viewModelScope.launch { + networkStatus.recoveries().collect { refresh() } } } - .asCacheFirstStateFlow(viewModelScope) -} + + /** Re-pull the playlists list. Returns the Job for pull-to-refresh awaits. */ + fun refresh(): Job = + viewModelScope.launch { + refreshError.value = null + runCatching { repository.refreshList() } + .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } + } + + /** + * Makes an empty playlist called [name] and opens it. Made offline, it + * waits in the list instead: its page can't load until the server has + * it. + */ + fun createPlaylist(name: String) { + viewModelScope.launch { + runCatching { repository.createPlaylist(name) } + .onSuccess { (id, outcome) -> if (outcome == WriteOutcome.Synced) createdChannel.trySend(id) } + .onFailure { poolMessages.trySend("Couldn't make the playlist: ${ErrorCopy.fromThrowable(it)}") } + } + } + + /** Tile play button: shuffle the playlist's tracks and start at index 0. */ + suspend fun playPlaylist(playlist: PlaylistRef) { + viewModelScope + .launch { + playPlaylistShuffled(playlist, repository, player) { + poolMessages.trySend(it) + } + }.join() + } + + val uiState: StateFlow>> = + combine(repository.observeAll(), refreshError) { list, err -> + when { + list.isNotEmpty() -> UiState.Success(list) + // Empty cache + failed refresh is a load failure, not "no + // playlists yet" — surface Error so the user gets a Retry. + err != null -> UiState.Error(err) + else -> UiState.Empty + } + }.asCacheFirstStateFlow(viewModelScope) + } // ─── Screen ────────────────────────────────────────────────────────── @@ -183,7 +186,10 @@ fun PlaylistsListScreen( NameDialog( title = "New playlist", confirmLabel = "Create", - onConfirm = { name -> naming = false; viewModel.createPlaylist(name) }, + onConfirm = { name -> + naming = false + viewModel.createPlaylist(name) + }, onDismiss = { naming = false }, ) } @@ -215,28 +221,35 @@ fun PlaylistsListScreen( /** Loading, empty, error, or the grid of playlists. */ @Composable -private fun PlaylistsListBody(viewModel: PlaylistsListViewModel, onOpen: (String) -> Unit) { +private fun PlaylistsListBody( + viewModel: PlaylistsListViewModel, + onOpen: (String) -> Unit, +) { val state by viewModel.uiState.collectAsStateWithLifecycle() val offline by viewModel.offline.collectAsStateWithLifecycle() when (val s = state) { UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "No playlists yet", - body = "System playlists (For You / Discover / Songs like…) " + - "appear once your library has enough plays. Make your own " + - "with + above, or from any track's Add to playlist.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load playlists", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> PlaylistsGrid( - playlists = s.data, - offline = offline, - onPlaylistClick = onOpen, - onPlay = viewModel::playPlaylist, - ) + UiState.Empty -> + EmptyState( + title = "No playlists yet", + body = + "System playlists (For You / Discover / Songs like…) " + + "appear once your library has enough plays. Make your own " + + "with + above, or from any track's Add to playlist.", + ) + is UiState.Error -> + ErrorRetry( + title = "Couldn't load playlists", + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> + PlaylistsGrid( + playlists = s.data, + offline = offline, + onPlaylistClick = onOpen, + onPlay = viewModel::playPlaylist, + ) } } @@ -296,8 +309,9 @@ private fun SectionHeader(text: String) { text = text, style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.onBackground, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 8.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 8.dp, vertical = 12.dp), ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/OfflinePoolCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/OfflinePoolCard.kt index c0338cc2..7736114e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/OfflinePoolCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/OfflinePoolCard.kt @@ -36,16 +36,18 @@ fun OfflinePoolCard( modifier: Modifier = Modifier, ) { Column( - modifier = modifier - .width(176.dp) - .clickable(onClick = onClick) - .padding(horizontal = 8.dp), + modifier = + modifier + .width(176.dp) + .clickable(onClick = onClick) + .padding(horizontal = 8.dp), ) { Box( - modifier = Modifier - .size(144.dp) - .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + Modifier + .size(144.dp) + .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) + .background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center, ) { Icon( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistCard.kt index 951cf2ba..b3177808 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistCard.kt @@ -57,13 +57,14 @@ fun PlaylistCard( ) { val seedCache = LocalDetailSeedCache.current Surface( - modifier = modifier - .width(176.dp) - .alpha(if (greyed) GREYED_ALPHA else 1f) // dimmed, still clickable - .clickable { - seedCache.stashPlaylist(playlist) - onClick() - }, + modifier = + modifier + .width(176.dp) + .alpha(if (greyed) GREYED_ALPHA else 1f) // dimmed, still clickable + .clickable { + seedCache.stashPlaylist(playlist) + onClick() + }, color = Color.Transparent, ) { Column(modifier = Modifier.padding(horizontal = 8.dp)) { @@ -111,18 +112,20 @@ private fun PlaylistCardCover( if (playlist.isSystem) { VariantPill( label = systemLabelFor(playlist.systemVariant), - modifier = Modifier - .align(Alignment.TopStart) - .padding(6.dp), + modifier = + Modifier + .align(Alignment.TopStart) + .padding(6.dp), ) } if (onPlay != null) { PlayCircleButton( onPlay = onPlay, enabled = playEnabled, - modifier = Modifier - .align(Alignment.BottomEnd) - .padding(6.dp), + modifier = + Modifier + .align(Alignment.BottomEnd) + .padding(6.dp), ) } }, @@ -131,7 +134,10 @@ private fun PlaylistCardCover( /** Small label chip overlaid on a system playlist's cover. */ @Composable -private fun VariantPill(label: String, modifier: Modifier = Modifier) { +private fun VariantPill( + label: String, + modifier: Modifier = Modifier, +) { if (label.isEmpty()) return Surface( modifier = modifier, @@ -149,22 +155,24 @@ private fun VariantPill(label: String, modifier: Modifier = Modifier) { private const val PILL_BG_ALPHA = 0.85f -private fun subtitleFor(playlist: PlaylistRef): String = when { - playlist.trackCount > 0 -> plural(playlist.trackCount, "track", "tracks") - playlist.isSystem -> systemLabelFor(playlist.systemVariant) - else -> " " -} +private fun subtitleFor(playlist: PlaylistRef): String = + when { + playlist.trackCount > 0 -> plural(playlist.trackCount, "track", "tracks") + playlist.isSystem -> systemLabelFor(playlist.systemVariant) + else -> " " + } -private fun systemLabelFor(variant: String?): String = when (variant) { - "for_you" -> "For You" - "discover" -> "Discover" - "songs_like_artist" -> "Songs like…" - "deep_cuts" -> "Deep cuts" - "rediscover" -> "Rediscover" - "new_for_you" -> "New for you" - "on_this_day" -> "On this day" - "first_listens" -> "First listens" - "genre_mix" -> "Genre mix" - null -> "" - else -> variant.replace('_', ' ').replaceFirstChar { it.uppercase() } -} +private fun systemLabelFor(variant: String?): String = + when (variant) { + "for_you" -> "For You" + "discover" -> "Discover" + "songs_like_artist" -> "Songs like…" + "deep_cuts" -> "Deep cuts" + "rediscover" -> "Rediscover" + "new_for_you" -> "New for you" + "on_this_day" -> "On this day" + "first_listens" -> "First listens" + "genre_mix" -> "Genre mix" + null -> "" + else -> variant.replace('_', ' ').replaceFirstChar { it.uppercase() } + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistPlaceholderCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistPlaceholderCard.kt index 65c37d0c..50d2f563 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistPlaceholderCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/PlaylistPlaceholderCard.kt @@ -56,24 +56,25 @@ fun PlaylistPlaceholderCard( val round = shape == PlaceholderShape.ROUND val tall = shape == PlaceholderShape.TALL Column( - modifier = if (tall) { - modifier - } else { - modifier.width(if (round) 136.dp else 176.dp).padding(horizontal = 8.dp) - }, + modifier = + if (tall) { + modifier + } else { + modifier.width(if (round) 136.dp else 176.dp).padding(horizontal = 8.dp) + }, horizontalAlignment = if (round) Alignment.CenterHorizontally else Alignment.Start, ) { Box( - modifier = Modifier - .then( - if (tall) { - Modifier.fillMaxWidth().aspectRatio(1f) - } else { - Modifier.size(if (round) 120.dp else 144.dp) - }, - ) - .clip(if (round) CircleShape else RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + Modifier + .then( + if (tall) { + Modifier.fillMaxWidth().aspectRatio(1f) + } else { + Modifier.size(if (round) 120.dp else 144.dp) + }, + ).clip(if (round) CircleShape else RoundedCornerShape(FabledSwordFlatTokens.radiusSm)) + .background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center, ) { Icon( @@ -84,9 +85,10 @@ fun PlaylistPlaceholderCard( ) StatusPill( variant = variant, - modifier = Modifier - .align(if (round) Alignment.BottomCenter else Alignment.BottomStart) - .padding(6.dp), + modifier = + Modifier + .align(if (round) Alignment.BottomCenter else Alignment.BottomStart) + .padding(6.dp), ) } Spacer(Modifier.height(8.dp)) @@ -96,13 +98,18 @@ fun PlaylistPlaceholderCard( /** The wide placeholder, the same size as Home's wide playlist card. */ @Composable -private fun WidePlaceholder(label: String, variant: String, modifier: Modifier) { +private fun WidePlaceholder( + label: String, + variant: String, + modifier: Modifier, +) { Row( - modifier = modifier - .width(296.dp) - .height(125.dp) - .clip(RoundedCornerShape(12.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + modifier + .width(296.dp) + .height(125.dp) + .clip(RoundedCornerShape(12.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant), ) { Box(modifier = Modifier.size(125.dp), contentAlignment = Alignment.Center) { Icon( @@ -120,7 +127,10 @@ private fun WidePlaceholder(label: String, variant: String, modifier: Modifier) } @Composable -private fun StatusPill(variant: String, modifier: Modifier) { +private fun StatusPill( + variant: String, + modifier: Modifier, +) { Surface( modifier = modifier, shape = RoundedCornerShape(FabledSwordFlatTokens.radiusSm), @@ -136,7 +146,11 @@ private fun StatusPill(variant: String, modifier: Modifier) { } @Composable -private fun PlaceholderText(label: String, variant: String, centered: Boolean) { +private fun PlaceholderText( + label: String, + variant: String, + centered: Boolean, +) { val align = if (centered) TextAlign.Center else TextAlign.Start Text( text = label, @@ -158,22 +172,25 @@ private fun PlaceholderText(label: String, variant: String, centered: Boolean) { private const val STATUS_BG_ALPHA = 0.85f -private fun iconFor(variant: String) = when (variant) { - "failed" -> Lucide.TriangleAlert - "building" -> Lucide.RefreshCw - else -> Lucide.ListMusic -} +private fun iconFor(variant: String) = + when (variant) { + "failed" -> Lucide.TriangleAlert + "building" -> Lucide.RefreshCw + else -> Lucide.ListMusic + } -private fun statusLabelFor(variant: String): String = when (variant) { - "building" -> "Building" - "failed" -> "Failed" - "seed-needed" -> "Needs a seed" - else -> "Pending" -} +private fun statusLabelFor(variant: String): String = + when (variant) { + "building" -> "Building" + "failed" -> "Failed" + "seed-needed" -> "Needs a seed" + else -> "Pending" + } -private fun subtitleFor(variant: String): String = when (variant) { - "building" -> "Generating now…" - "failed" -> "Last build failed" - "seed-needed" -> "Like an artist to seed this" - else -> "Coming soon" -} +private fun subtitleFor(variant: String): String = + when (variant) { + "building" -> "Generating now…" + "failed" -> "Last build failed" + "seed-needed" -> "Like an artist to seed this" + else -> "Coming soon" + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/ShelfPlaylistCards.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/ShelfPlaylistCards.kt index 40238001..a60822a1 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/ShelfPlaylistCards.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/ShelfPlaylistCards.kt @@ -79,20 +79,22 @@ fun WidePlaylistCard( ) { val lead = leadCoverUrl(playlist, covers) Box( - modifier = Modifier - .width(WIDE_WIDTH) - .height(WIDE_HEIGHT) - .alpha(if (greyed) GREYED_ALPHA else 1f) - .clip(RoundedCornerShape(CARD_RADIUS)) - .background(washBrush(rememberWash(lead))) - .stashingClick(playlist, onClick), + modifier = + Modifier + .width(WIDE_WIDTH) + .height(WIDE_HEIGHT) + .alpha(if (greyed) GREYED_ALPHA else 1f) + .clip(RoundedCornerShape(CARD_RADIUS)) + .background(washBrush(rememberWash(lead))) + .stashingClick(playlist, onClick), ) { Row(modifier = Modifier.fillMaxSize()) { LeadArt(url = lead, modifier = Modifier.size(WIDE_HEIGHT)) Column( - modifier = Modifier - .weight(1f) - .padding(start = 12.dp, top = 12.dp, end = 52.dp, bottom = 12.dp), + modifier = + Modifier + .weight(1f) + .padding(start = 12.dp, top = 12.dp, end = 52.dp, bottom = 12.dp), ) { Text( text = playlist.name, @@ -114,9 +116,10 @@ fun WidePlaylistCard( PlayCircleButton( onPlay = onPlay, enabled = playEnabled && !greyed, - modifier = Modifier - .align(Alignment.BottomEnd) - .padding(8.dp), + modifier = + Modifier + .align(Alignment.BottomEnd) + .padding(8.dp), ) } } @@ -132,11 +135,12 @@ fun SongsLikeCard( greyed: Boolean, ) { Column( - modifier = Modifier - .width(ROUND_WIDTH) - .alpha(if (greyed) GREYED_ALPHA else 1f) - .stashingClick(playlist, onClick) - .padding(horizontal = 8.dp), + modifier = + Modifier + .width(ROUND_WIDTH) + .alpha(if (greyed) GREYED_ALPHA else 1f) + .stashingClick(playlist, onClick) + .padding(horizontal = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { CoverTile( @@ -150,9 +154,10 @@ fun SongsLikeCard( PlayCircleButton( onPlay = onPlay, enabled = playEnabled && !greyed, - modifier = Modifier - .align(Alignment.BottomEnd) - .padding(4.dp), + modifier = + Modifier + .align(Alignment.BottomEnd) + .padding(4.dp), ) }, ) @@ -189,39 +194,43 @@ fun GenreBandCard( ) { val fan = covers.map(::albumCoverPath).ifEmpty { listOfNotNull(playlist.coverUrl.ifEmpty { null }) } Box( - modifier = Modifier - .width(BAND_WIDTH) - .height(BAND_HEIGHT) - .alpha(if (greyed) GREYED_ALPHA else 1f) - .clip(RoundedCornerShape(CARD_RADIUS)) - .background(washBrush(rememberWash(fan.firstOrNull()))) - .stashingClick(playlist, onClick), + modifier = + Modifier + .width(BAND_WIDTH) + .height(BAND_HEIGHT) + .alpha(if (greyed) GREYED_ALPHA else 1f) + .clip(RoundedCornerShape(CARD_RADIUS)) + .background(washBrush(rememberWash(fan.firstOrNull()))) + .stashingClick(playlist, onClick), ) { CoverFan(urls = fan, modifier = Modifier.align(Alignment.CenterEnd).padding(end = 12.dp)) Text( text = playlist.name.replace(MIX_SUFFIX, ""), - style = MaterialTheme.typography.headlineSmall.copy( - shadow = Shadow(color = Color.Black.copy(alpha = NAME_SHADOW_ALPHA), blurRadius = 4f), - ), + style = + MaterialTheme.typography.headlineSmall.copy( + shadow = Shadow(color = Color.Black.copy(alpha = NAME_SHADOW_ALPHA), blurRadius = 4f), + ), color = OnWash, maxLines = 2, overflow = TextOverflow.Ellipsis, - modifier = Modifier - .align(Alignment.BottomStart) - .padding(start = 8.dp, bottom = 10.dp) - .widthIn(max = BAND_WIDTH * NAME_MAX_FRACTION) - .zIndex(FAN_LAYERS) - .clip(RoundedCornerShape(6.dp)) - .background(NameBacking) - .padding(horizontal = 8.dp, vertical = 2.dp), + modifier = + Modifier + .align(Alignment.BottomStart) + .padding(start = 8.dp, bottom = 10.dp) + .widthIn(max = BAND_WIDTH * NAME_MAX_FRACTION) + .zIndex(FAN_LAYERS) + .clip(RoundedCornerShape(6.dp)) + .background(NameBacking) + .padding(horizontal = 8.dp, vertical = 2.dp), ) PlayCircleButton( onPlay = onPlay, enabled = playEnabled && !greyed, - modifier = Modifier - .align(Alignment.BottomEnd) - .zIndex(FAN_LAYERS + 1) - .padding(8.dp), + modifier = + Modifier + .align(Alignment.BottomEnd) + .zIndex(FAN_LAYERS + 1) + .padding(8.dp), ) } } @@ -231,7 +240,10 @@ fun GenreBandCard( * band allows and overlapping to fit, tilted -8° / 0° / +8°. */ @Composable -private fun CoverFan(urls: List, modifier: Modifier = Modifier) { +private fun CoverFan( + urls: List, + modifier: Modifier = Modifier, +) { val n = urls.size.coerceAtMost(FAN_MAX) if (n == 0) return val span = BAND_WIDTH * FAN_SPAN @@ -242,25 +254,30 @@ private fun CoverFan(urls: List, modifier: Modifier = Modifier) { ServerImage( url = url, contentDescription = null, - modifier = Modifier - .align(Alignment.CenterStart) - .offset(x = step * i, y = if (tilt == 0f) (-4).dp else 4.dp) - .zIndex((n - i).toFloat()) - .rotate(tilt) - .shadow(elevation = 6.dp, shape = RoundedCornerShape(6.dp)) - .size(FAN_COVER) - .clip(RoundedCornerShape(6.dp)), + modifier = + Modifier + .align(Alignment.CenterStart) + .offset(x = step * i, y = if (tilt == 0f) (-4).dp else 4.dp) + .zIndex((n - i).toFloat()) + .rotate(tilt) + .shadow(elevation = 6.dp, shape = RoundedCornerShape(6.dp)) + .size(FAN_COVER) + .clip(RoundedCornerShape(6.dp)), ) } } } @Composable -internal fun LeadArt(url: String?, modifier: Modifier) { +internal fun LeadArt( + url: String?, + modifier: Modifier, +) { Box( - modifier = modifier - .fillMaxHeight() - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + modifier + .fillMaxHeight() + .background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center, ) { ServerImage( @@ -273,7 +290,10 @@ internal fun LeadArt(url: String?, modifier: Modifier) { } @Composable -internal fun Modifier.stashingClick(playlist: PlaylistRef, onClick: () -> Unit): Modifier { +internal fun Modifier.stashingClick( + playlist: PlaylistRef, + onClick: () -> Unit, +): Modifier { val seedCache = LocalDetailSeedCache.current return clickable { seedCache.stashPlaylist(playlist) @@ -290,13 +310,14 @@ internal fun Modifier.stashingClick(playlist: PlaylistRef, onClick: () -> Unit): internal fun rememberWash(url: String?): Color { val dominant = rememberDominantColor(url) if (dominant == Color.Transparent) return NeutralWash - val toned = washTone( - Rgb( - r = (dominant.red * CHANNEL_MAX).roundToInt(), - g = (dominant.green * CHANNEL_MAX).roundToInt(), - b = (dominant.blue * CHANNEL_MAX).roundToInt(), - ), - ) + val toned = + washTone( + Rgb( + r = (dominant.red * CHANNEL_MAX).roundToInt(), + g = (dominant.green * CHANNEL_MAX).roundToInt(), + b = (dominant.blue * CHANNEL_MAX).roundToInt(), + ), + ) return Color(red = toned.r, green = toned.g, blue = toned.b) } @@ -306,13 +327,18 @@ internal fun rememberWash(url: String?): Color { * With [washTone]'s caps this keeps [OnWash] text at 4.5:1 or better on any * cover (ShelfTest checks the numbers). */ -internal fun washBrush(wash: Color, vertical: Boolean = false): Brush { +internal fun washBrush( + wash: Color, + vertical: Boolean = false, +): Brush { val stops = listOf(lerp(WashBase, wash, WASH_NEAR), lerp(WashBase, wash, WASH_FAR)) return if (vertical) Brush.verticalGradient(stops) else Brush.horizontalGradient(stops) } -internal fun leadCoverUrl(playlist: PlaylistRef, covers: List): String? = - covers.firstOrNull()?.let(::albumCoverPath) ?: playlist.coverUrl.ifEmpty { null } +internal fun leadCoverUrl( + playlist: PlaylistRef, + covers: List, +): String? = covers.firstOrNull()?.let(::albumCoverPath) ?: playlist.coverUrl.ifEmpty { null } /** A system mix says what it is built from; anything else says its size and owner. */ internal fun sublineFor(p: PlaylistRef): String = diff --git a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/TallPlaylistCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/TallPlaylistCard.kt index f8484000..530bfd3d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/TallPlaylistCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/playlists/widgets/TallPlaylistCard.kt @@ -42,12 +42,13 @@ fun TallPlaylistCard( ) { val lead = leadCoverUrl(playlist, covers) Column( - modifier = Modifier - .width(width) - .alpha(if (greyed) GREYED_ALPHA else 1f) - .clip(RoundedCornerShape(CARD_RADIUS)) - .background(washBrush(rememberWash(lead), vertical = true)) - .stashingClick(playlist, onClick), + modifier = + Modifier + .width(width) + .alpha(if (greyed) GREYED_ALPHA else 1f) + .clip(RoundedCornerShape(CARD_RADIUS)) + .background(washBrush(rememberWash(lead), vertical = true)) + .stashingClick(playlist, onClick), ) { LeadArt(url = lead, modifier = Modifier.fillMaxWidth().aspectRatio(1f)) Box(modifier = Modifier.fillMaxWidth().height(TALL_PANEL_HEIGHT)) { @@ -74,9 +75,10 @@ fun TallPlaylistCard( onPlay = onPlay, enabled = playEnabled && !greyed, size = 36.dp, - modifier = Modifier - .align(Alignment.BottomEnd) - .padding(8.dp), + modifier = + Modifier + .align(Alignment.BottomEnd) + .padding(8.dp), ) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt index 2a9a706e..aa8d1c74 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt @@ -18,9 +18,9 @@ import kotlinx.datetime.Clock import retrofit2.HttpException import retrofit2.Retrofit import retrofit2.create +import timber.log.Timber import javax.inject.Inject import javax.inject.Singleton -import timber.log.Timber /** * Outcome of an `unflag` call — mirrors LikesRepository.toggleLike's @@ -50,119 +50,138 @@ enum class FlagOutcome { ACCEPTED, QUEUED } * back on failure. */ @Singleton -class QuarantineRepository @Inject constructor( - private val dao: CachedQuarantineDao, - private val mutationQueue: MutationQueue, - retrofit: Retrofit, -) { - private val api: QuarantineApi = retrofit.create() +class QuarantineRepository + @Inject + constructor( + private val dao: CachedQuarantineDao, + private val mutationQueue: MutationQueue, + retrofit: Retrofit, + ) { + private val api: QuarantineApi = retrofit.create() - /** Cache-first stream of the caller's hidden tracks (newest first). */ - fun observeMine(): Flow> = - dao.observeAll().map { rows -> rows.map { it.toDomain() } } + /** Cache-first stream of the caller's hidden tracks (newest first). */ + fun observeMine(): Flow> = dao.observeAll().map { rows -> rows.map { it.toDomain() } } - /** Pull the server snapshot and atomically replace the cached table. */ - suspend fun refresh() { - val fresh = api.listMine().map { it.toEntity() } - // A flag or unflag still queued wins over the server's list, which - // hasn't seen it yet; a queued flag keeps the row made when it was - // flagged here. - val pending = mutationQueue.pendingQuarantineStates() - if (pending.isEmpty()) { - dao.replaceAll(fresh) - return + /** Pull the server snapshot and atomically replace the cached table. */ + suspend fun refresh() { + val fresh = api.listMine().map { it.toEntity() } + // A flag or unflag still queued wins over the server's list, which + // hasn't seen it yet; a queued flag keeps the row made when it was + // flagged here. + val pending = mutationQueue.pendingQuarantineStates() + if (pending.isEmpty()) { + dao.replaceAll(fresh) + return + } + val kept = fresh.filter { pending[it.trackId] != false } + val listed = kept.mapTo(HashSet()) { it.trackId } + val flaggedHere = + dao + .observeAll() + .first() + .filter { pending[it.trackId] == true && it.trackId !in listed } + dao.replaceAll(kept + flaggedHere) } - val kept = fresh.filter { pending[it.trackId] != false } - val listed = kept.mapTo(HashSet()) { it.trackId } - val flaggedHere = dao.observeAll().first() - .filter { pending[it.trackId] == true && it.trackId !in listed } - dao.replaceAll(kept + flaggedHere) - } - /** Server snapshot without touching the cache — used by the TrackActions hidden check. */ - suspend fun listMine(): List = api.listMine().map { it.toDomain() } + /** Server snapshot without touching the cache — used by the TrackActions hidden check. */ + suspend fun listMine(): List = api.listMine().map { it.toDomain() } - /** - * Flag [track] for quarantine with [reason] (bad_rip / wrong_file / - * wrong_tags / duplicate / other) and optional admin-visible - * [notes]. Optimistically inserts the cache row (the Hidden tab + - * isHidden checks update instantly), then calls the server; - * transport failure enqueues for replay (server re-flag is - * idempotent). - */ - suspend fun flag(track: TrackRef, reason: String, notes: String): FlagOutcome { - dao.upsert(track.toQuarantineEntity(reason, notes)) - // An unflag for this track still queued would replay after a live - // flag and undo it: queue behind it instead. - if (mutationQueue.pendingQuarantineStates().containsKey(track.id)) { - mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) - return FlagOutcome.QUEUED + /** + * Flag [track] for quarantine with [reason] (bad_rip / wrong_file / + * wrong_tags / duplicate / other) and optional admin-visible + * [notes]. Optimistically inserts the cache row (the Hidden tab + + * isHidden checks update instantly), then calls the server; + * transport failure enqueues for replay (server re-flag is + * idempotent). + */ + suspend fun flag( + track: TrackRef, + reason: String, + notes: String, + ): FlagOutcome { + dao.upsert(track.toQuarantineEntity(reason, notes)) + // An unflag for this track still queued would replay after a live + // flag and undo it: queue behind it instead. + if (mutationQueue.pendingQuarantineStates().containsKey(track.id)) { + mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) + return FlagOutcome.QUEUED + } + val outcome = + sendOrQueue( + send = { api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes)) }, + queue = { mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) }, + onRefused = { e -> refused("flag", track.id, e) }, + ) + return if (outcome == WriteOutcome.Queued) FlagOutcome.QUEUED else FlagOutcome.ACCEPTED } - val outcome = sendOrQueue( - send = { api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes)) }, - queue = { mutationQueue.enqueueQuarantineFlag(track.id, reason, notes) }, - onRefused = { e -> refused("flag", track.id, e) }, - ) - return if (outcome == WriteOutcome.Queued) FlagOutcome.QUEUED else FlagOutcome.ACCEPTED - } - suspend fun unflag(trackId: String): UnflagOutcome { - dao.deleteByTrackId(trackId) - if (mutationQueue.pendingQuarantineStates().containsKey(trackId)) { - mutationQueue.enqueueQuarantineUnflag(trackId) - return UnflagOutcome.QUEUED + suspend fun unflag(trackId: String): UnflagOutcome { + dao.deleteByTrackId(trackId) + if (mutationQueue.pendingQuarantineStates().containsKey(trackId)) { + mutationQueue.enqueueQuarantineUnflag(trackId) + return UnflagOutcome.QUEUED + } + val outcome = + sendOrQueue( + send = { api.unflag(trackId) }, + queue = { mutationQueue.enqueueQuarantineUnflag(trackId) }, + onRefused = { e -> refused("unflag", trackId, e) }, + ) + return if (outcome == WriteOutcome.Queued) UnflagOutcome.QUEUED else UnflagOutcome.ACCEPTED } - val outcome = sendOrQueue( - send = { api.unflag(trackId) }, - queue = { mutationQueue.enqueueQuarantineUnflag(trackId) }, - onRefused = { e -> refused("unflag", trackId, e) }, - ) - return if (outcome == WriteOutcome.Queued) UnflagOutcome.QUEUED else UnflagOutcome.ACCEPTED - } - /** - * The server said no (say, the track is gone). Nothing is queued, since a - * replay would be refused too; the next refresh shows the server's list. - */ - private fun refused(what: String, trackId: String, e: HttpException): WriteOutcome { - Timber.i(e, "quarantine: %s %s refused (%d)", what, trackId, e.code()) - return WriteOutcome.Refused + /** + * The server said no (say, the track is gone). Nothing is queued, since a + * replay would be refused too; the next refresh shows the server's list. + */ + private fun refused( + what: String, + trackId: String, + e: HttpException, + ): WriteOutcome { + Timber.i(e, "quarantine: %s %s refused (%d)", what, trackId, e.code()) + return WriteOutcome.Refused + } } -} // ── Mappers (internal — wire/entity stay out of UI) ── -private fun QuarantineMineWire.toEntity(): CachedQuarantineEntity = CachedQuarantineEntity( - trackId = trackId, - reason = reason, - notes = notes, - createdAt = createdAt, - trackTitle = trackTitle, - trackDurationMs = trackDurationMs, - albumId = albumId, - albumTitle = albumTitle, - albumCoverArtPath = albumCoverArtPath, - artistId = artistId, - artistName = artistName, -) +private fun QuarantineMineWire.toEntity(): CachedQuarantineEntity = + CachedQuarantineEntity( + trackId = trackId, + reason = reason, + notes = notes, + createdAt = createdAt, + trackTitle = trackTitle, + trackDurationMs = trackDurationMs, + albumId = albumId, + albumTitle = albumTitle, + albumCoverArtPath = albumCoverArtPath, + artistId = artistId, + artistName = artistName, + ) -private fun CachedQuarantineEntity.toDomain(): QuarantineRef = QuarantineRef( - trackId = trackId, - reason = reason, - notes = notes, - createdAt = createdAt, - trackTitle = trackTitle, - trackDurationMs = trackDurationMs, - albumId = albumId, - albumTitle = albumTitle, - albumCoverArtPath = albumCoverArtPath, - artistId = artistId, - artistName = artistName, -) +private fun CachedQuarantineEntity.toDomain(): QuarantineRef = + QuarantineRef( + trackId = trackId, + reason = reason, + notes = notes, + createdAt = createdAt, + trackTitle = trackTitle, + trackDurationMs = trackDurationMs, + albumId = albumId, + albumTitle = albumTitle, + albumCoverArtPath = albumCoverArtPath, + artistId = artistId, + artistName = artistName, + ) private fun QuarantineMineWire.toDomain(): QuarantineRef = toEntity().toDomain() -private fun TrackRef.toQuarantineEntity(reason: String, notes: String): CachedQuarantineEntity = +private fun TrackRef.toQuarantineEntity( + reason: String, + notes: String, +): CachedQuarantineEntity = CachedQuarantineEntity( trackId = id, reason = reason, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/ui/HiddenTab.kt b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/ui/HiddenTab.kt index 91897bf0..c869b7a3 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/ui/HiddenTab.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/ui/HiddenTab.kt @@ -38,27 +38,34 @@ fun HiddenTab(viewModel: HiddenTabViewModel = hiltViewModel()) { PullToRefreshScaffold(onRefresh = { viewModel.refresh().join() }) { when (val s = state) { UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "No hidden tracks", - body = "Flag a track from its menu (bad rip, wrong tags, etc.) " + - "and it'll show up here. The track stays out of system " + - "playlists until you unhide it.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load hidden tracks", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> HiddenList( - rows = s.data, - onUnflag = viewModel::unflag, - ) + UiState.Empty -> + EmptyState( + title = "No hidden tracks", + body = + "Flag a track from its menu (bad rip, wrong tags, etc.) " + + "and it'll show up here. The track stays out of system " + + "playlists until you unhide it.", + ) + is UiState.Error -> + ErrorRetry( + title = "Couldn't load hidden tracks", + message = s.message, + onRetry = { viewModel.refresh() }, + ) + is UiState.Success -> + HiddenList( + rows = s.data, + onUnflag = viewModel::unflag, + ) } } } @Composable -private fun HiddenList(rows: List, onUnflag: (String) -> Unit) { +private fun HiddenList( + rows: List, + onUnflag: (String) -> Unit, +) { LazyColumn(modifier = Modifier.fillMaxSize()) { items(items = rows, key = { it.trackId }) { row -> HiddenRow(row = row, onUnflag = { onUnflag(row.trackId) }) @@ -68,11 +75,15 @@ private fun HiddenList(rows: List, onUnflag: (String) -> Unit) { } @Composable -private fun HiddenRow(row: QuarantineRef, onUnflag: () -> Unit) { +private fun HiddenRow( + row: QuarantineRef, + onUnflag: () -> Unit, +) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp), ) { @@ -128,28 +139,44 @@ private const val HOURS_PER_DAY = 24L private const val DAYS_PER_WEEK = 7L private fun relativeTime(iso: String): String { - val parsed = runCatching { java.time.OffsetDateTime.parse(iso) }.getOrNull() - ?: return iso + val parsed = + runCatching { java.time.OffsetDateTime.parse(iso) }.getOrNull() + ?: return iso val local = parsed.atZoneSameInstant(java.time.ZoneId.systemDefault()) val now = java.time.OffsetDateTime.now(java.time.ZoneId.systemDefault()) - val minutes = java.time.temporal.ChronoUnit.MINUTES.between(local, now) - val hours = java.time.temporal.ChronoUnit.HOURS.between(local, now) - val days = java.time.temporal.ChronoUnit.DAYS.between(local, now) + val minutes = + java.time.temporal.ChronoUnit.MINUTES + .between(local, now) + val hours = + java.time.temporal.ChronoUnit.HOURS + .between(local, now) + val days = + java.time.temporal.ChronoUnit.DAYS + .between(local, now) return when { minutes < MINUTES_PER_HOUR -> "${minutes.coerceAtLeast(1)}m ago" hours < HOURS_PER_DAY -> "${hours}h ago" days < DAYS_PER_WEEK -> { - val dow = local.dayOfWeek.getDisplayName( - java.time.format.TextStyle.SHORT, - java.util.Locale.getDefault(), - ) - val time = local.toLocalTime() - .format(java.time.format.DateTimeFormatter.ofPattern("HH:mm")) + val dow = + local.dayOfWeek.getDisplayName( + java.time.format.TextStyle.SHORT, + java.util.Locale.getDefault(), + ) + val time = + local + .toLocalTime() + .format( + java.time.format.DateTimeFormatter + .ofPattern("HH:mm"), + ) "$dow $time" } else -> { val pattern = if (local.year == now.year) "MMM d" else "MMM d, yyyy" - local.toLocalDate().format(java.time.format.DateTimeFormatter.ofPattern(pattern)) + local.toLocalDate().format( + java.time.format.DateTimeFormatter + .ofPattern(pattern), + ) } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/ui/HiddenTabViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/ui/HiddenTabViewModel.kt index 661b80ab..2d661a3a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/ui/HiddenTabViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/ui/HiddenTabViewModel.kt @@ -7,8 +7,8 @@ import com.fabledsword.minstrel.connectivity.NetworkStatusController import com.fabledsword.minstrel.connectivity.recoveries import com.fabledsword.minstrel.events.EventsStream import com.fabledsword.minstrel.models.QuarantineRef -import com.fabledsword.minstrel.shared.UiState import com.fabledsword.minstrel.quarantine.data.QuarantineRepository +import com.fabledsword.minstrel.shared.UiState import dagger.hilt.android.lifecycle.HiltViewModel import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow @@ -23,67 +23,69 @@ import javax.inject.Inject private const val SHARE_STOP_TIMEOUT_MS = 5_000L @HiltViewModel -class HiddenTabViewModel @Inject constructor( - private val repository: QuarantineRepository, - private val eventsStream: EventsStream, - networkStatus: NetworkStatusController, -) : ViewModel() { +class HiddenTabViewModel + @Inject + constructor( + private val repository: QuarantineRepository, + private val eventsStream: EventsStream, + networkStatus: NetworkStatusController, + ) : ViewModel() { + private val refreshError = MutableStateFlow(null) - private val refreshError = MutableStateFlow(null) + /** + * Cache-first: emits the cached `cached_quarantine_mine` rows + * instantly (paints from disk on cold open), SWR-refreshes + * underneath, and shows Error only when there's no cache AND the + * refresh failed. Optimistic flag/unflag write the cache, so the + * list updates without waiting on the server. + */ + val uiState: StateFlow>> = + combine(repository.observeMine(), refreshError) { rows, err -> + when { + rows.isNotEmpty() -> UiState.Success(rows) + err != null -> UiState.Error(err) + else -> UiState.Empty + } + }.stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = UiState.Loading, + ) - /** - * Cache-first: emits the cached `cached_quarantine_mine` rows - * instantly (paints from disk on cold open), SWR-refreshes - * underneath, and shows Error only when there's no cache AND the - * refresh failed. Optimistic flag/unflag write the cache, so the - * list updates without waiting on the server. - */ - val uiState: StateFlow>> = - combine(repository.observeMine(), refreshError) { rows, err -> - when { - rows.isNotEmpty() -> UiState.Success(rows) - err != null -> UiState.Error(err) - else -> UiState.Empty + init { + refresh() + // Live cross-device updates: any quarantine.* event (hide / + // unhide / resolve / delete from another device) re-fetches the + // snapshot while the tab is open. The screen-scoped VM subscribes + // directly, the dispatcher's documented pattern for screen-scoped + // state. + viewModelScope.launch { + eventsStream.events + .filter { it.kind.startsWith("quarantine.") } + .collect { refresh() } + } + // Screen-level auto-recovery: re-pull when server + // health returns, so a load that failed offline heals unprompted. + viewModelScope.launch { + networkStatus.recoveries().collect { refresh() } } - }.stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = UiState.Loading, - ) - - init { - refresh() - // Live cross-device updates: any quarantine.* event (hide / - // unhide / resolve / delete from another device) re-fetches the - // snapshot while the tab is open. The screen-scoped VM subscribes - // directly, the dispatcher's documented pattern for screen-scoped - // state. - viewModelScope.launch { - eventsStream.events - .filter { it.kind.startsWith("quarantine.") } - .collect { refresh() } } - // Screen-level auto-recovery: re-pull when server - // health returns, so a load that failed offline heals unprompted. - viewModelScope.launch { - networkStatus.recoveries().collect { refresh() } + + fun refresh(): Job = + viewModelScope.launch { + refreshError.value = null + runCatching { repository.refresh() } + .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } + } + + /** + * Optimistic unhide — the repository drops the cache row first (the + * observeMine Flow re-emits so the list updates instantly), then + * calls the server, enqueueing on failure so the intent persists. + */ + fun unflag(trackId: String) { + viewModelScope.launch { + runCatching { repository.unflag(trackId) } + } } } - - fun refresh(): Job = viewModelScope.launch { - refreshError.value = null - runCatching { repository.refresh() } - .onFailure { refreshError.value = ErrorCopy.fromThrowable(it) } - } - - /** - * Optimistic unhide — the repository drops the cache row first (the - * observeMine Flow re-emits so the list updates instantly), then - * calls the server, enqueueing on failure so the intent persists. - */ - fun unflag(trackId: String) { - viewModelScope.launch { - runCatching { repository.unflag(trackId) } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/search/data/SearchRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/search/data/SearchRepository.kt index 7785bbb3..46314aeb 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/search/data/SearchRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/search/data/SearchRepository.kt @@ -25,38 +25,42 @@ private const val LOCAL_SEARCH_LIMIT = 20 * results" hint instead of pretending the server answered. */ @Singleton -class SearchRepository @Inject constructor( - retrofit: Retrofit, - private val serverHealth: NetworkStatusController, - private val trackDao: CachedTrackDao, - private val albumDao: CachedAlbumDao, - private val artistDao: CachedArtistDao, -) { - private val api: SearchApi = retrofit.create() +class SearchRepository + @Inject + constructor( + retrofit: Retrofit, + private val serverHealth: NetworkStatusController, + private val trackDao: CachedTrackDao, + private val albumDao: CachedAlbumDao, + private val artistDao: CachedArtistDao, + ) { + private val api: SearchApi = retrofit.create() - suspend fun search(query: String): SearchOutcome = when (serverHealth.state.value) { - ServerHealth.Healthy, ServerHealth.Unstable -> - SearchOutcome(remoteSearch(query), localOnly = false) - ServerHealth.Offline, ServerHealth.ServerDown -> - SearchOutcome(localSearch(query), localOnly = true) + suspend fun search(query: String): SearchOutcome = + when (serverHealth.state.value) { + ServerHealth.Healthy, ServerHealth.Unstable -> + SearchOutcome(remoteSearch(query), localOnly = false) + ServerHealth.Offline, ServerHealth.ServerDown -> + SearchOutcome(localSearch(query), localOnly = true) + } + + private suspend fun remoteSearch(query: String): SearchResponseRef { + val wire = api.search(query) + return SearchResponseRef( + artists = wire.artists.items.map { it.toDomain() }, + albums = wire.albums.items.map { it.toDomain() }, + tracks = wire.tracks.items.map { it.toDomain() }, + ) + } + + private suspend fun localSearch(query: String): SearchResponseRef = + SearchResponseRef( + artists = artistDao.searchByName(query, LOCAL_SEARCH_LIMIT).map { it.toDomain() }, + albums = albumDao.searchByTitle(query, LOCAL_SEARCH_LIMIT).map { it.toDomain() }, + tracks = trackDao.searchByTitle(query, LOCAL_SEARCH_LIMIT).map { it.toDomain() }, + ) } - private suspend fun remoteSearch(query: String): SearchResponseRef { - val wire = api.search(query) - return SearchResponseRef( - artists = wire.artists.items.map { it.toDomain() }, - albums = wire.albums.items.map { it.toDomain() }, - tracks = wire.tracks.items.map { it.toDomain() }, - ) - } - - private suspend fun localSearch(query: String): SearchResponseRef = SearchResponseRef( - artists = artistDao.searchByName(query, LOCAL_SEARCH_LIMIT).map { it.toDomain() }, - albums = albumDao.searchByTitle(query, LOCAL_SEARCH_LIMIT).map { it.toDomain() }, - tracks = trackDao.searchByTitle(query, LOCAL_SEARCH_LIMIT).map { it.toDomain() }, - ) -} - /** * Wraps the search response with the signal of whether the result came * from the server or from the local cached entities. The screen renders diff --git a/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchScreen.kt index 55abfcc9..12611d6c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchScreen.kt @@ -54,14 +54,14 @@ import com.fabledsword.minstrel.models.SearchResponseRef import com.fabledsword.minstrel.models.TrackRef import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.Search as SearchRoute -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets -import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.ErrorRetry import com.fabledsword.minstrel.shared.widgets.LoadingCentered import com.fabledsword.minstrel.shared.widgets.MainAppBarActions +import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets import com.fabledsword.minstrel.shared.widgets.TrackCoverThumb +import com.fabledsword.minstrel.shared.widgets.TrackRow import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsButton +import com.fabledsword.minstrel.nav.Search as SearchRoute @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -131,18 +131,20 @@ private fun SearchField( TextField( value = query, onValueChange = onQueryChange, - modifier = Modifier - .fillMaxWidth() - .focusRequester(focusRequester), + modifier = + Modifier + .fillMaxWidth() + .focusRequester(focusRequester), placeholder = { Text("Search artists, albums, tracks") }, singleLine = true, keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), - colors = TextFieldDefaults.colors( - focusedContainerColor = Color.Transparent, - unfocusedContainerColor = Color.Transparent, - focusedIndicatorColor = Color.Transparent, - unfocusedIndicatorColor = Color.Transparent, - ), + colors = + TextFieldDefaults.colors( + focusedContainerColor = Color.Transparent, + unfocusedContainerColor = Color.Transparent, + focusedIndicatorColor = Color.Transparent, + unfocusedIndicatorColor = Color.Transparent, + ), ) } @@ -160,11 +162,12 @@ private fun ResultsPane( when (state) { SearchResultsState.Idle -> CenteredHint("Type to search your library.") SearchResultsState.Loading -> LoadingCentered() - is SearchResultsState.Error -> ErrorRetry( - title = "Search failed", - message = state.message, - onRetry = onRetry, - ) + is SearchResultsState.Error -> + ErrorRetry( + title = "Search failed", + message = state.message, + onRetry = onRetry, + ) is SearchResultsState.Loaded -> { if (state.response.isEmpty) { CenteredHint( @@ -307,11 +310,15 @@ private fun TrackResultRow( } @Composable -private fun SectionHeader(label: String, count: Int) { +private fun SectionHeader( + label: String, + count: Int, +) { Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { @@ -332,9 +339,10 @@ private fun SectionHeader(label: String, count: Int) { private fun OfflineResultsHint() { Text( text = "Showing on-device matches only — the server is unreachable.", - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 6.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 6.dp), style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -350,4 +358,3 @@ private fun CenteredHint(text: String) { ) } } - diff --git a/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchViewModel.kt index fc090c84..b5ccacd8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/search/ui/SearchViewModel.kt @@ -29,12 +29,17 @@ private const val DEBOUNCE_MS = 250L sealed interface SearchResultsState { /** Empty query — screen shows "type to search" hint. */ data object Idle : SearchResultsState + data object Loading : SearchResultsState + data class Loaded( val response: SearchResponseRef, val localOnly: Boolean = false, ) : SearchResultsState - data class Error(val message: String) : SearchResultsState + + data class Error( + val message: String, + ) : SearchResultsState } data class SearchState( @@ -44,111 +49,113 @@ data class SearchState( @OptIn(FlowPreview::class) @HiltViewModel -class SearchViewModel @Inject constructor( - private val repository: SearchRepository, - private val player: PlayerController, - networkStatus: NetworkStatusController, -) : ViewModel() { +class SearchViewModel + @Inject + constructor( + private val repository: SearchRepository, + private val player: PlayerController, + networkStatus: NetworkStatusController, + ) : ViewModel() { + private val queryFlow = MutableStateFlow("") + private val internal = MutableStateFlow(SearchState()) + val state: StateFlow = internal.asStateFlow() - private val queryFlow = MutableStateFlow("") - private val internal = MutableStateFlow(SearchState()) - val state: StateFlow = internal.asStateFlow() - - init { - viewModelScope.launch { - queryFlow - .map { it.trim() } - .distinctUntilChanged() - .onEach { q -> - // Empty query collapses results without firing the - // network call below. - if (q.isEmpty()) { - internal.update { - it.copy(results = SearchResultsState.Idle) + init { + viewModelScope.launch { + queryFlow + .map { it.trim() } + .distinctUntilChanged() + .onEach { q -> + // Empty query collapses results without firing the + // network call below. + if (q.isEmpty()) { + internal.update { + it.copy(results = SearchResultsState.Idle) + } } + }.debounce(DEBOUNCE_MS) + .collect { q -> + if (q.isEmpty()) return@collect + runSearch(q) } + } + // Screen-level auto-recovery: a search that failed + // while the server was unreachable re-runs when health returns — + // the queryFlow pipeline can't, since the text hasn't changed. + viewModelScope.launch { + networkStatus.recoveries().collect { + if (internal.value.results is SearchResultsState.Error) retry() } - .debounce(DEBOUNCE_MS) - .collect { q -> - if (q.isEmpty()) return@collect - runSearch(q) - } - } - // Screen-level auto-recovery: a search that failed - // while the server was unreachable re-runs when health returns — - // the queryFlow pipeline can't, since the text hasn't changed. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value.results is SearchResultsState.Error) retry() } } - } - fun setQuery(value: String) { - internal.update { it.copy(query = value) } - queryFlow.value = value - } + fun setQuery(value: String) { + internal.update { it.copy(query = value) } + queryFlow.value = value + } - fun clear() { - setQuery("") - } + fun clear() { + setQuery("") + } - /** - * Re-run the current query after a failure. Bypasses the queryFlow - * pipeline, whose distinctUntilChanged drops a same-text resubmit — - * without this, a transient error pins "Search failed" until the - * user edits the query. - */ - fun retry() { - val q = internal.value.query.trim() - if (q.isEmpty()) return - viewModelScope.launch { runSearch(q) } - } + /** + * Re-run the current query after a failure. Bypasses the queryFlow + * pipeline, whose distinctUntilChanged drops a same-text resubmit — + * without this, a transient error pins "Search failed" until the + * user edits the query. + */ + fun retry() { + val q = internal.value.query.trim() + if (q.isEmpty()) return + viewModelScope.launch { runSearch(q) } + } - /** - * Tapping a search result starts radio seeded from it: the tapped song - * plays first, then songs like it. The list of matches for a few typed - * words is rarely what someone wants to hear next. The web's search does - * the same (radioFromRow). - * - * When radio can't be had (offline, or the server returns nothing), the - * tapped song plays on its own, so a tap always plays what was tapped. - */ - fun playTrack(track: TrackRef) { - if (track.streamUrl.isEmpty()) return - viewModelScope.launch { - val started = try { - player.playRadio(track.id) - } catch (e: CancellationException) { - throw e + /** + * Tapping a search result starts radio seeded from it: the tapped song + * plays first, then songs like it. The list of matches for a few typed + * words is rarely what someone wants to hear next. The web's search does + * the same (radioFromRow). + * + * When radio can't be had (offline, or the server returns nothing), the + * tapped song plays on its own, so a tap always plays what was tapped. + */ + fun playTrack(track: TrackRef) { + if (track.streamUrl.isEmpty()) return + viewModelScope.launch { + val started = + try { + player.playRadio(track.id) + } catch (e: CancellationException) { + throw e + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + Timber.i(e, "search: radio for %s failed; playing the track alone", track.id) + false + } + if (!started) player.setQueue(listOf(track), initialIndex = 0, source = "search") + } + } + + private suspend fun runSearch(q: String) { + internal.update { it.copy(results = SearchResultsState.Loading) } + try { + val outcome = repository.search(q) + internal.update { + it.copy( + results = + SearchResultsState.Loaded( + response = outcome.response, + localOnly = outcome.localOnly, + ), + ) + } } catch ( @Suppress("TooGenericExceptionCaught") e: Throwable, ) { - Timber.i(e, "search: radio for %s failed; playing the track alone", track.id) - false - } - if (!started) player.setQueue(listOf(track), initialIndex = 0, source = "search") - } - } - - private suspend fun runSearch(q: String) { - internal.update { it.copy(results = SearchResultsState.Loading) } - try { - val outcome = repository.search(q) - internal.update { - it.copy( - results = SearchResultsState.Loaded( - response = outcome.response, - localOnly = outcome.localOnly, - ), - ) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy(results = SearchResultsState.Error(ErrorCopy.fromThrowable(e))) + internal.update { + it.copy(results = SearchResultsState.Error(ErrorCopy.fromThrowable(e))) + } } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt index 77b70534..cb0db5ba 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/MeRepository.kt @@ -20,46 +20,59 @@ import javax.inject.Singleton * path because changing your own password offline doesn't make sense. */ @Singleton -class MeRepository @Inject constructor(retrofit: Retrofit) { - private val api: MeApi = retrofit.create(MeApi::class.java) +class MeRepository + @Inject + constructor( + retrofit: Retrofit, + ) { + private val api: MeApi = retrofit.create(MeApi::class.java) - suspend fun getProfile(): MyProfile = api.getProfile().toDomain() + suspend fun getProfile(): MyProfile = api.getProfile().toDomain() - suspend fun updateProfile(displayName: String?, email: String?): MyProfile = - api.updateProfile( - UpdateProfileRequest(displayName = displayName, email = email), - ).toDomain() + suspend fun updateProfile( + displayName: String?, + email: String?, + ): MyProfile = + api + .updateProfile( + UpdateProfileRequest(displayName = displayName, email = email), + ).toDomain() - suspend fun changePassword(current: String, next: String, signOutSubsonic: Boolean = false) { - api.changePassword( - ChangePasswordRequest( - currentPassword = current, - newPassword = next, - signOutSubsonic = signOutSubsonic, - ), - ) + suspend fun changePassword( + current: String, + next: String, + signOutSubsonic: Boolean = false, + ) { + api.changePassword( + ChangePasswordRequest( + currentPassword = current, + newPassword = next, + signOutSubsonic = signOutSubsonic, + ), + ) + } + + suspend fun getListenBrainz(): ListenBrainzStatus = api.getListenBrainz().toDomain() + + suspend fun setListenBrainzToken(token: String): ListenBrainzStatus = + api.setListenBrainz(ListenBrainzPutBody(token = token)).toDomain() + + suspend fun setListenBrainzEnabled(enabled: Boolean): ListenBrainzStatus = + api.setListenBrainz(ListenBrainzPutBody(enabled = enabled)).toDomain() } - suspend fun getListenBrainz(): ListenBrainzStatus = - api.getListenBrainz().toDomain() +private fun MyProfileWire.toDomain(): MyProfile = + MyProfile( + id = id, + username = username, + displayName = displayName, + email = email, + isAdmin = isAdmin, + ) - suspend fun setListenBrainzToken(token: String): ListenBrainzStatus = - api.setListenBrainz(ListenBrainzPutBody(token = token)).toDomain() - - suspend fun setListenBrainzEnabled(enabled: Boolean): ListenBrainzStatus = - api.setListenBrainz(ListenBrainzPutBody(enabled = enabled)).toDomain() -} - -private fun MyProfileWire.toDomain(): MyProfile = MyProfile( - id = id, - username = username, - displayName = displayName, - email = email, - isAdmin = isAdmin, -) - -private fun ListenBrainzStatusWire.toDomain(): ListenBrainzStatus = ListenBrainzStatus( - enabled = enabled, - tokenSet = tokenSet, - lastScrobbledAt = lastScrobbledAt, -) +private fun ListenBrainzStatusWire.toDomain(): ListenBrainzStatus = + ListenBrainzStatus( + enabled = enabled, + tokenSet = tokenSet, + lastScrobbledAt = lastScrobbledAt, + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationPrefs.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationPrefs.kt index a77deeec..719cf5bc 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationPrefs.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationPrefs.kt @@ -24,32 +24,39 @@ data class NormalizationPrefs( val TARGETS: List = listOf(-18, -16, -14) /** Must match library.DefaultNormalizationPrefs on the server. */ - val DEFAULT: NormalizationPrefs = NormalizationPrefs( - mode = NormalizationMode.AUTO, - targetLufs = -18, - boost = NormalizationBoost.HEADROOM, - ) + val DEFAULT: NormalizationPrefs = + NormalizationPrefs( + mode = NormalizationMode.AUTO, + targetLufs = -18, + boost = NormalizationBoost.HEADROOM, + ) } } @Serializable enum class NormalizationMode { /** Tracks play at their mastered volume. */ - @SerialName("off") OFF, + @SerialName("off") + OFF, /** Album gain while an album plays in order, track gain otherwise. */ - @SerialName("auto") AUTO, + @SerialName("auto") + AUTO, - @SerialName("track") TRACK, + @SerialName("track") + TRACK, - @SerialName("album") ALBUM, + @SerialName("album") + ALBUM, } @Serializable enum class NormalizationBoost { /** Quiet tracks are raised only as far as their true peak allows. */ - @SerialName("headroom") HEADROOM, + @SerialName("headroom") + HEADROOM, /** Quiet tracks are raised all the way and a limiter holds the peaks. */ - @SerialName("limiter") LIMITER, + @SerialName("limiter") + LIMITER, } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt index 34a99fbb..bf7df421 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/data/NormalizationRepository.kt @@ -23,44 +23,46 @@ import javax.inject.Singleton * best effort, and a failed PUT is queued for the MutationReplayer. */ @Singleton -class NormalizationRepository @Inject constructor( - retrofit: Retrofit, - private val authStore: AuthStore, - private val mutationQueue: MutationQueue, - private val mutationDao: CachedMutationDao, -) { - private val api: MeApi = retrofit.create() +class NormalizationRepository + @Inject + constructor( + retrofit: Retrofit, + private val authStore: AuthStore, + private val mutationQueue: MutationQueue, + private val mutationDao: CachedMutationDao, + ) { + private val api: MeApi = retrofit.create() - val prefs: StateFlow = authStore.normalization + val prefs: StateFlow = authStore.normalization - /** - * Takes the server's value, unless a change made here is still queued: - * the server has not seen it yet, and taking its older value would undo - * the change on screen until the replay landed. Throws on a network - * failure; the device's copy then stands. - */ - suspend fun refresh() { - val server = api.getNormalization() - if (mutationDao.hasPending(MutationKind.NORMALIZATION_SET)) return - authStore.setNormalization(server) - } + /** + * Takes the server's value, unless a change made here is still queued: + * the server has not seen it yet, and taking its older value would undo + * the change on screen until the replay landed. Throws on a network + * failure; the device's copy then stands. + */ + suspend fun refresh() { + val server = api.getNormalization() + if (mutationDao.hasPending(MutationKind.NORMALIZATION_SET)) return + authStore.setNormalization(server) + } - suspend fun set(next: NormalizationPrefs) { - authStore.setNormalization(next) - // An earlier change still queued would be replayed after this PUT - // and undo it. Queue behind it instead: the replayer sends only the - // newest queued preference. - if (mutationDao.hasPending(MutationKind.NORMALIZATION_SET)) { - mutationQueue.enqueueNormalizationSet(next) - return + suspend fun set(next: NormalizationPrefs) { + authStore.setNormalization(next) + // An earlier change still queued would be replayed after this PUT + // and undo it. Queue behind it instead: the replayer sends only the + // newest queued preference. + if (mutationDao.hasPending(MutationKind.NORMALIZATION_SET)) { + mutationQueue.enqueueNormalizationSet(next) + return + } + sendOrQueue( + send = { api.putNormalization(next) }, + queue = { mutationQueue.enqueueNormalizationSet(next) }, + onRefused = { e -> + Timber.i(e, "normalization: PUT refused (%d)", e.code()) + WriteOutcome.Refused + }, + ) } - sendOrQueue( - send = { api.putNormalization(next) }, - queue = { mutationQueue.enqueueNormalizationSet(next) }, - onRefused = { e -> - Timber.i(e, "normalization: PUT refused (%d)", e.code()) - WriteOutcome.Refused - }, - ) } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzCard.kt index 3cce4374..c9a5caa8 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzCard.kt @@ -56,11 +56,12 @@ private fun ListenBrainzForm( val tokenSet = status?.tokenSet == true SwitchRow( title = "Send my plays to ListenBrainz", - summary = when { - !tokenSet -> "Save a token first" - status?.lastScrobbledAt != null -> "Last scrobble: ${status.lastScrobbledAt}" - else -> null - }, + summary = + when { + !tokenSet -> "Save a token first" + status?.lastScrobbledAt != null -> "Last scrobble: ${status.lastScrobbledAt}" + else -> null + }, checked = status?.enabled == true, onCheckedChange = onSetEnabled, enabled = !isSaving && tokenSet, @@ -75,7 +76,11 @@ private fun ListenBrainzForm( } @Composable -private fun TokenField(tokenInput: String, tokenSet: Boolean, onChange: (String) -> Unit) { +private fun TokenField( + tokenInput: String, + tokenSet: Boolean, + onChange: (String) -> Unit, +) { OutlinedTextField( value = tokenInput, onValueChange = onChange, @@ -89,7 +94,11 @@ private fun TokenField(tokenInput: String, tokenSet: Boolean, onChange: (String) } @Composable -private fun SaveTokenButton(isSaving: Boolean, enabled: Boolean, onClick: () -> Unit) { +private fun SaveTokenButton( + isSaving: Boolean, + enabled: Boolean, + onClick: () -> Unit, +) { Button( onClick = onClick, enabled = enabled, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzViewModel.kt index 551378cd..4f4cc820 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ListenBrainzViewModel.kt @@ -32,85 +32,86 @@ data class ListenBrainzUiState( * acts as a write-only entry. */ @HiltViewModel -class ListenBrainzViewModel @Inject constructor( - private val repository: MeRepository, -) : ViewModel() { +class ListenBrainzViewModel + @Inject + constructor( + private val repository: MeRepository, + ) : ViewModel() { + private val internal = MutableStateFlow(ListenBrainzUiState()) + val state: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(ListenBrainzUiState()) - val state: StateFlow = internal.asStateFlow() + init { + refresh() + } - init { - refresh() - } + fun setTokenInput(value: String) { + internal.update { it.copy(tokenInput = value) } + } - fun setTokenInput(value: String) { - internal.update { it.copy(tokenInput = value) } - } + fun refresh() { + viewModelScope.launch { + internal.update { it.copy(isLoading = true, message = null, loadError = null) } + try { + val s = repository.getListenBrainz() + internal.update { it.copy(isLoading = false, status = s) } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy( + isLoading = false, + loadError = ErrorCopy.fromThrowable(e), + ) + } + } + } + } - fun refresh() { - viewModelScope.launch { - internal.update { it.copy(isLoading = true, message = null, loadError = null) } - try { - val s = repository.getListenBrainz() - internal.update { it.copy(isLoading = false, status = s) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - isLoading = false, - loadError = ErrorCopy.fromThrowable(e), - ) + fun saveToken() { + val token = internal.value.tokenInput.trim() + if (token.isEmpty() || internal.value.isSaving) return + viewModelScope.launch { + internal.update { it.copy(isSaving = true, message = null) } + try { + val s = repository.setListenBrainzToken(token) + internal.update { + it.copy( + isSaving = false, + status = s, + tokenInput = "", + message = "Token saved.", + ) + } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy( + isSaving = false, + message = ErrorCopy.fromThrowable(e), + ) + } + } + } + } + + fun setEnabled(enabled: Boolean) { + if (internal.value.isSaving) return + viewModelScope.launch { + internal.update { it.copy(isSaving = true, message = null) } + try { + val s = repository.setListenBrainzEnabled(enabled) + internal.update { it.copy(isSaving = false, status = s) } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy( + isSaving = false, + message = ErrorCopy.fromThrowable(e), + ) + } } } } } - - fun saveToken() { - val token = internal.value.tokenInput.trim() - if (token.isEmpty() || internal.value.isSaving) return - viewModelScope.launch { - internal.update { it.copy(isSaving = true, message = null) } - try { - val s = repository.setListenBrainzToken(token) - internal.update { - it.copy( - isSaving = false, - status = s, - tokenInput = "", - message = "Token saved.", - ) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - isSaving = false, - message = ErrorCopy.fromThrowable(e), - ) - } - } - } - } - - fun setEnabled(enabled: Boolean) { - if (internal.value.isSaving) return - viewModelScope.launch { - internal.update { it.copy(isSaving = true, message = null) } - try { - val s = repository.setListenBrainzEnabled(enabled) - internal.update { it.copy(isSaving = false, status = s) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - isSaving = false, - message = ErrorCopy.fromThrowable(e), - ) - } - } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationCard.kt index eae7bab6..8ad2574b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationCard.kt @@ -54,16 +54,18 @@ internal fun NormalizationCardContent( } } -private fun modeLabel(mode: NormalizationMode): String = when (mode) { - NormalizationMode.OFF -> "Off" - NormalizationMode.AUTO -> "Auto" - NormalizationMode.TRACK -> "Track" - NormalizationMode.ALBUM -> "Album" -} +private fun modeLabel(mode: NormalizationMode): String = + when (mode) { + NormalizationMode.OFF -> "Off" + NormalizationMode.AUTO -> "Auto" + NormalizationMode.TRACK -> "Track" + NormalizationMode.ALBUM -> "Album" + } -private fun modeHint(mode: NormalizationMode): String = when (mode) { - NormalizationMode.OFF -> "Tracks play at their mastered volume." - NormalizationMode.AUTO -> "Album gain for whole albums, track gain otherwise." - NormalizationMode.TRACK -> "Every track at the same loudness." - NormalizationMode.ALBUM -> "Albums keep their own quiet and loud tracks." -} +private fun modeHint(mode: NormalizationMode): String = + when (mode) { + NormalizationMode.OFF -> "Tracks play at their mastered volume." + NormalizationMode.AUTO -> "Album gain for whole albums, track gain otherwise." + NormalizationMode.TRACK -> "Every track at the same loudness." + NormalizationMode.ALBUM -> "Albums keep their own quiet and loud tracks." + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationViewModel.kt index 7bcf3928..d4443259 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/NormalizationViewModel.kt @@ -17,28 +17,29 @@ import javax.inject.Inject * here too. */ @HiltViewModel -class NormalizationViewModel @Inject constructor( - private val repository: NormalizationRepository, -) : ViewModel() { +class NormalizationViewModel + @Inject + constructor( + private val repository: NormalizationRepository, + ) : ViewModel() { + val prefs: StateFlow = repository.prefs - val prefs: StateFlow = repository.prefs - - init { - viewModelScope.launch { - try { - repository.refresh() - } catch (e: CancellationException) { - throw e - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - // Offline: the device's copy stands. - Timber.i(e, "normalization: refresh failed") + init { + viewModelScope.launch { + try { + repository.refresh() + } catch (e: CancellationException) { + throw e + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + // Offline: the device's copy stands. + Timber.i(e, "normalization: refresh failed") + } } } - } - fun update(next: NormalizationPrefs) { - viewModelScope.launch { repository.set(next) } + fun update(next: NormalizationPrefs) { + viewModelScope.launch { repository.set(next) } + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt index 03cd431a..fe2939f4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordCard.kt @@ -3,7 +3,6 @@ package com.fabledsword.minstrel.settings.ui import androidx.compose.foundation.layout.Spacer import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.height -import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.Button diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt index ee9bf071..cddf664a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/PasswordViewModel.kt @@ -29,57 +29,61 @@ data class PasswordUiState( * for both success and error. */ @HiltViewModel -class PasswordViewModel @Inject constructor( - private val repository: MeRepository, -) : ViewModel() { +class PasswordViewModel + @Inject + constructor( + private val repository: MeRepository, + ) : ViewModel() { + private val internal = MutableStateFlow(PasswordUiState()) + val state: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(PasswordUiState()) - val state: StateFlow = internal.asStateFlow() + fun setCurrent(value: String) = internal.update { it.copy(current = value, message = null) } - fun setCurrent(value: String) = internal.update { it.copy(current = value, message = null) } - fun setNext(value: String) = internal.update { it.copy(next = value, message = null) } - fun setConfirm(value: String) = internal.update { it.copy(confirm = value, message = null) } - fun setSignOutSubsonic(value: Boolean) = - internal.update { it.copy(signOutSubsonic = value, message = null) } + fun setNext(value: String) = internal.update { it.copy(next = value, message = null) } - fun change() { - val s = internal.value - val validationError: String? = when { - s.isChanging -> "" // sentinel: silent no-op - s.current.isEmpty() || s.next.isEmpty() -> "All fields required." - !PasswordRules.isLongEnough(s.next) -> PasswordRules.TOO_SHORT - s.next != s.confirm -> PasswordRules.DIFFER - else -> null - } - if (validationError != null) { - if (validationError.isNotEmpty()) { - internal.update { it.copy(message = validationError) } - } - return - } - viewModelScope.launch { - internal.update { it.copy(isChanging = true, message = null) } - try { - repository.changePassword( - current = s.current, - next = s.next, - signOutSubsonic = s.signOutSubsonic, - ) - val signedOut = - if (s.signOutSubsonic) "Your other devices and Subsonic apps" else "Your other devices" - internal.update { - PasswordUiState(message = "Password changed. $signedOut have been signed out.") + fun setConfirm(value: String) = internal.update { it.copy(confirm = value, message = null) } + + fun setSignOutSubsonic(value: Boolean) = internal.update { it.copy(signOutSubsonic = value, message = null) } + + fun change() { + val s = internal.value + val validationError: String? = + when { + s.isChanging -> "" // sentinel: silent no-op + s.current.isEmpty() || s.next.isEmpty() -> "All fields required." + !PasswordRules.isLongEnough(s.next) -> PasswordRules.TOO_SHORT + s.next != s.confirm -> PasswordRules.DIFFER + else -> null } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - isChanging = false, - message = ErrorCopy.fromThrowable(e), + if (validationError != null) { + if (validationError.isNotEmpty()) { + internal.update { it.copy(message = validationError) } + } + return + } + viewModelScope.launch { + internal.update { it.copy(isChanging = true, message = null) } + try { + repository.changePassword( + current = s.current, + next = s.next, + signOutSubsonic = s.signOutSubsonic, ) + val signedOut = + if (s.signOutSubsonic) "Your other devices and Subsonic apps" else "Your other devices" + internal.update { + PasswordUiState(message = "Password changed. $signedOut have been signed out.") + } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy( + isChanging = false, + message = ErrorCopy.fromThrowable(e), + ) + } } } } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileViewModel.kt index 052968f1..e95ebd09 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/ProfileViewModel.kt @@ -36,79 +36,81 @@ data class ProfileUiState( * snackbar for the form cards. */ @HiltViewModel -class ProfileViewModel @Inject constructor( - private val repository: MeRepository, -) : ViewModel() { +class ProfileViewModel + @Inject + constructor( + private val repository: MeRepository, + ) : ViewModel() { + private val internal = MutableStateFlow(ProfileUiState()) + val state: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(ProfileUiState()) - val state: StateFlow = internal.asStateFlow() + init { + refresh() + } - init { - refresh() - } + fun setDisplayName(value: String) { + internal.update { it.copy(displayName = value) } + } - fun setDisplayName(value: String) { - internal.update { it.copy(displayName = value) } - } + fun setEmail(value: String) { + internal.update { it.copy(email = value) } + } - fun setEmail(value: String) { - internal.update { it.copy(email = value) } - } - - fun refresh() { - viewModelScope.launch { - internal.update { it.copy(isLoading = true, message = null, loadError = null) } - try { - val profile = repository.getProfile() - internal.update { - it.copy( - isLoading = false, - loadedProfile = profile, - displayName = profile.displayName.orEmpty(), - email = profile.email.orEmpty(), - ) + fun refresh() { + viewModelScope.launch { + internal.update { it.copy(isLoading = true, message = null, loadError = null) } + try { + val profile = repository.getProfile() + internal.update { + it.copy( + isLoading = false, + loadedProfile = profile, + displayName = profile.displayName.orEmpty(), + email = profile.email.orEmpty(), + ) + } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy( + isLoading = false, + loadError = ErrorCopy.fromThrowable(e), + ) + } } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - isLoading = false, - loadError = ErrorCopy.fromThrowable(e), - ) + } + } + + fun save() { + if (internal.value.isSaving) return + viewModelScope.launch { + internal.update { it.copy(isSaving = true, message = null) } + try { + val updated = + repository.updateProfile( + displayName = internal.value.displayName.trim(), + email = internal.value.email.trim(), + ) + internal.update { + it.copy( + isSaving = false, + loadedProfile = updated, + displayName = updated.displayName.orEmpty(), + email = updated.email.orEmpty(), + message = "Profile saved.", + ) + } + } catch ( + @Suppress("TooGenericExceptionCaught") e: Throwable, + ) { + internal.update { + it.copy( + isSaving = false, + message = ErrorCopy.fromThrowable(e), + ) + } } } } } - - fun save() { - if (internal.value.isSaving) return - viewModelScope.launch { - internal.update { it.copy(isSaving = true, message = null) } - try { - val updated = repository.updateProfile( - displayName = internal.value.displayName.trim(), - email = internal.value.email.trim(), - ) - internal.update { - it.copy( - isSaving = false, - loadedProfile = updated, - displayName = updated.displayName.orEmpty(), - email = updated.email.orEmpty(), - message = "Profile saved.", - ) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - isSaving = false, - message = ErrorCopy.fromThrowable(e), - ) - } - } - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsLoad.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsLoad.kt index 3854d46d..6efccadd 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsLoad.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsLoad.kt @@ -35,17 +35,19 @@ fun SettingsLoad( content: @Composable () -> Unit, ) { when { - isLoading -> Box( - modifier = Modifier.fillMaxWidth().padding(16.dp), - contentAlignment = Alignment.Center, - ) { CircularProgressIndicator() } - loadError != null -> SettingRow( - title = "Couldn't load $what", - summary = loadError, - icon = Lucide.TriangleAlert, - tone = MaterialTheme.colorScheme.error, - trailing = { TextButton(onClick = onRetry) { Text("Try again") } }, - ) + isLoading -> + Box( + modifier = Modifier.fillMaxWidth().padding(16.dp), + contentAlignment = Alignment.Center, + ) { CircularProgressIndicator() } + loadError != null -> + SettingRow( + title = "Couldn't load $what", + summary = loadError, + icon = Lucide.TriangleAlert, + tone = MaterialTheme.colorScheme.error, + trailing = { TextButton(onClick = onRetry) { Text("Try again") } }, + ) else -> content() } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsScreen.kt index 368dd5d3..6aac6b74 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsScreen.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsScreen.kt @@ -28,7 +28,6 @@ import com.composables.icons.lucide.Shield import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.NotificationSettings import com.fabledsword.minstrel.nav.ServerUrl -import com.fabledsword.minstrel.nav.Settings as SettingsRoute import com.fabledsword.minstrel.shared.widgets.ConfirmDestructiveDialog import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets @@ -45,6 +44,7 @@ import com.fabledsword.minstrel.theme.ThemePreferenceViewModel import com.fabledsword.minstrel.update.ui.AppVersionCard import com.fabledsword.minstrel.update.ui.CheckWhileShown import com.fabledsword.minstrel.update.ui.UpdateViewModel +import com.fabledsword.minstrel.nav.Settings as SettingsRoute @Composable fun SettingsScreen( @@ -110,11 +110,12 @@ private fun SettingsList( onSignOutClick: () -> Unit, ) { Column( - modifier = Modifier - .fillMaxSize() - .padding(inner) - .verticalScroll(rememberScrollState()) - .padding(horizontal = SectionEdge, vertical = SectionEdge), + modifier = + Modifier + .fillMaxSize() + .padding(inner) + .verticalScroll(rememberScrollState()) + .padding(horizontal = SectionEdge, vertical = SectionEdge), verticalArrangement = Arrangement.spacedBy(SectionGap), ) { AccountSection( @@ -137,11 +138,15 @@ private fun SettingsList( } @Composable -private fun SignOutConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { +private fun SignOutConfirmDialog( + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { ConfirmDestructiveDialog( title = "Sign out?", - text = "Sign out of this server? Your downloaded music and " + - "settings on this device will be removed.", + text = + "Sign out of this server? Your downloaded music and " + + "settings on this device will be removed.", confirmLabel = "Sign out", onConfirm = onConfirm, onDismiss = onDismiss, @@ -190,7 +195,10 @@ private fun AccountSection( // the user turn reporting OFF on this device (battery/privacy) without // touching the account flag. Checked = reporting on = NOT opted out. @Composable -private fun DiagnosticsSection(optOut: Boolean, onToggle: (Boolean) -> Unit) { +private fun DiagnosticsSection( + optOut: Boolean, + onToggle: (Boolean) -> Unit, +) { Section("Diagnostics") { SwitchRow( title = "Send diagnostic reports", @@ -202,7 +210,10 @@ private fun DiagnosticsSection(optOut: Boolean, onToggle: (Boolean) -> Unit) { } @Composable -private fun AppearanceSection(themeMode: ThemeMode, onPick: (ThemeMode) -> Unit) { +private fun AppearanceSection( + themeMode: ThemeMode, + onPick: (ThemeMode) -> Unit, +) { Section("Appearance") { ChoiceRow( title = "Theme", @@ -214,11 +225,12 @@ private fun AppearanceSection(themeMode: ThemeMode, onPick: (ThemeMode) -> Unit) } } -private fun displayName(mode: ThemeMode): String = when (mode) { - ThemeMode.SYSTEM -> "System" - ThemeMode.LIGHT -> "Light" - ThemeMode.DARK -> "Dark" -} +private fun displayName(mode: ThemeMode): String = + when (mode) { + ThemeMode.SYSTEM -> "System" + ThemeMode.LIGHT -> "Light" + ThemeMode.DARK -> "Dark" + } /** * The About card is the app-version card Home's update sheet holds too; on diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt index 41f104c9..1caf2452 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/SettingsViewModel.kt @@ -28,77 +28,78 @@ data class SettingsState( ) @HiltViewModel -class SettingsViewModel @Inject constructor( - private val authController: AuthController, - private val authStore: AuthStore, - private val notifications: NotificationsRepository, - private val replayer: MutationReplayer, -) : ViewModel() { +class SettingsViewModel + @Inject + constructor( + private val authController: AuthController, + private val authStore: AuthStore, + private val notifications: NotificationsRepository, + private val replayer: MutationReplayer, + ) : ViewModel() { + private val transient = MutableStateFlow(TransientState()) + private val internal: MutableStateFlow = MutableStateFlow(SettingsState()) + val state: StateFlow = internal.asStateFlow() - private val transient = MutableStateFlow(TransientState()) - private val internal: MutableStateFlow = MutableStateFlow(SettingsState()) - val state: StateFlow = internal.asStateFlow() + init { + // Compose the user-visible state from the auth observables + // (so cross-restart rehydration shows the right username) plus + // the local sign-out spinner. Snapshotting currentUser at + // construction time would miss the rehydration that arrives + // microseconds after; collecting it keeps the card live. + viewModelScope.launch { + combine( + authStore.baseUrl, + authController.currentUser, + authStore.diagnosticsOptOut, + transient, + ) { url, user, optOut, t -> + SettingsState( + serverUrl = url, + username = user?.username.orEmpty(), + isAdmin = user?.isAdmin == true, + isSigningOut = t.isSigningOut, + signedOut = t.signedOut, + diagnosticsEnabledByAdmin = user?.debugModeEnabled == true, + diagnosticsOptOut = optOut, + ) + }.collect { internal.value = it } + } + } - init { - // Compose the user-visible state from the auth observables - // (so cross-restart rehydration shows the right username) plus - // the local sign-out spinner. Snapshotting currentUser at - // construction time would miss the rehydration that arrives - // microseconds after; collecting it keeps the card live. - viewModelScope.launch { - combine( - authStore.baseUrl, - authController.currentUser, - authStore.diagnosticsOptOut, - transient, - ) { url, user, optOut, t -> - SettingsState( - serverUrl = url, - username = user?.username.orEmpty(), - isAdmin = user?.isAdmin == true, - isSigningOut = t.isSigningOut, - signedOut = t.signedOut, - diagnosticsEnabledByAdmin = user?.debugModeEnabled == true, - diagnosticsOptOut = optOut, - ) - }.collect { internal.value = it } + /** Per-device opt-out of diagnostics while the account flag is on. */ + fun setDiagnosticsOptOut(optOut: Boolean) { + authStore.setDiagnosticsOptOut(optOut) + } + + fun signOut() { + if (transient.value.isSigningOut) return + viewModelScope.launch { + 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() + // The inbox is this account's; the next one on the device must not see it. + runCatching { notifications.clearLocal() } + transient.update { it.copy(isSigningOut = false, signedOut = true) } + } + } + + fun consumeSignedOut() { + transient.update { it.copy(signedOut = false) } + } + + /** Local-only screen state that isn't owned by AuthStore/Controller. */ + private data class TransientState( + val isSigningOut: 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 } } - - /** Per-device opt-out of diagnostics while the account flag is on. */ - fun setDiagnosticsOptOut(optOut: Boolean) { - authStore.setDiagnosticsOptOut(optOut) - } - - fun signOut() { - if (transient.value.isSigningOut) return - viewModelScope.launch { - 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() - // The inbox is this account's; the next one on the device must not see it. - runCatching { notifications.clearLocal() } - transient.update { it.copy(isSigningOut = false, signedOut = true) } - } - } - - fun consumeSignedOut() { - transient.update { it.copy(signedOut = false) } - } - - /** Local-only screen state that isn't owned by AuthStore/Controller. */ - private data class TransientState( - val isSigningOut: 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 - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageCard.kt index 1c74f378..c964aa09 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageCard.kt @@ -19,13 +19,14 @@ private const val GIB: Long = 1024L * 1024 * 1024 private const val MIB: Long = 1024L * 1024 private const val KIB: Long = 1024L -private val CAP_OPTIONS: List> = listOf( - 1L * GIB to "1 GB", - 5L * GIB to "5 GB", - 10L * GIB to "10 GB", - 25L * GIB to "25 GB", - 0L to "Unlimited", -) +private val CAP_OPTIONS: List> = + listOf( + 1L * GIB to "1 GB", + 5L * GIB to "5 GB", + 10L * GIB to "10 GB", + 25L * GIB to "25 GB", + 0L to "Unlimited", + ) @Composable fun StorageCard(viewModel: StorageViewModel = hiltViewModel()) { @@ -78,7 +79,12 @@ fun StorageCard(viewModel: StorageViewModel = hiltViewModel()) { /** A storage budget: how much it holds now, and the cap it may grow to. */ @Composable -private fun CapRow(title: String, used: Long, value: Long, onSet: (Long) -> Unit) { +private fun CapRow( + title: String, + used: Long, + value: Long, + onSet: (Long) -> Unit, +) { ChoiceRow( title = title, summary = "${formatBytes(used)} used", @@ -90,11 +96,15 @@ private fun CapRow(title: String, used: Long, value: Long, onSet: (Long) -> Unit } @Composable -private fun ClearCacheConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { +private fun ClearCacheConfirmDialog( + onConfirm: () -> Unit, + onDismiss: () -> Unit, +) { ConfirmDestructiveDialog( title = "Clear cache?", - text = "This deletes all cached audio. The next play of any track " + - "re-downloads from the server.", + text = + "This deletes all cached audio. The next play of any track " + + "re-downloads from the server.", confirmLabel = "Clear", onConfirm = onConfirm, onDismiss = onDismiss, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageViewModel.kt index d168b4e9..e03a5c94 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/settings/ui/StorageViewModel.kt @@ -34,91 +34,92 @@ data class StorageUiState( * through to Room), and the evictor applies a new cap at once. */ @HiltViewModel -class StorageViewModel @Inject constructor( - private val authStore: AuthStore, - private val playerFactory: PlayerFactory, - private val cacheEvictor: TwoBucketCacheEvictor, - private val syncController: SyncController, -) : ViewModel() { +class StorageViewModel + @Inject + constructor( + private val authStore: AuthStore, + private val playerFactory: PlayerFactory, + private val cacheEvictor: TwoBucketCacheEvictor, + private val syncController: SyncController, + ) : ViewModel() { + private val internal = MutableStateFlow(StorageUiState()) + val state: StateFlow = internal.asStateFlow() - private val internal = MutableStateFlow(StorageUiState()) - val state: StateFlow = internal.asStateFlow() - - init { - viewModelScope.launch { - authStore.cacheSettings.collect { s -> - internal.update { it.copy(settings = s) } - // A smaller cap trims the cache, so re-read the usage. - refreshUsage() - } - } - } - - fun setLikedCapBytes(bytes: Long) { - val current = authStore.cacheSettings.value - authStore.setCacheSettings(current.copy(likedCapBytes = bytes)) - } - - fun setRollingCapBytes(bytes: Long) { - val current = authStore.cacheSettings.value - authStore.setCacheSettings(current.copy(rollingCapBytes = bytes)) - } - - fun setPrefetchWindow(n: Int) { - val clamped = n.coerceIn(1, MAX_PREFETCH_WINDOW) - val current = authStore.cacheSettings.value - authStore.setCacheSettings(current.copy(prefetchWindow = clamped)) - } - - fun setCacheLikedTracks(on: Boolean) { - val current = authStore.cacheSettings.value - authStore.setCacheSettings(current.copy(cacheLikedTracks = on)) - } - - fun syncNow() { - if (internal.value.isSyncing) return - viewModelScope.launch { - internal.update { it.copy(isSyncing = true) } - try { - syncController.syncSafe() - } finally { - internal.update { it.copy(isSyncing = false) } - } - } - } - - fun clearCache() { - if (internal.value.isClearing) return - viewModelScope.launch { - internal.update { it.copy(isClearing = true) } - try { - withContext(Dispatchers.IO) { - // SimpleCache.getKeys() + removeResource is the safe - // path — releasing the cache mid-flight would crash - // any in-progress playback. Iterating + removing - // works while the cache is in use. - val cache = playerFactory.simpleCache - val keys = cache.keys.toList() - for (k in keys) { - runCatching { cache.removeResource(k) } - } + init { + viewModelScope.launch { + authStore.cacheSettings.collect { s -> + internal.update { it.copy(settings = s) } + // A smaller cap trims the cache, so re-read the usage. + refreshUsage() } - refreshUsage() - } finally { - internal.update { it.copy(isClearing = false) } } } - } - /** Re-reads each budget's usage from the evictor. Cheap: two longs. */ - private fun refreshUsage() { - viewModelScope.launch { - val usage = withContext(Dispatchers.IO) { cacheEvictor.usage() } - internal.update { it.copy(likedBytes = usage.likedBytes, recentBytes = usage.recentBytes) } + fun setLikedCapBytes(bytes: Long) { + val current = authStore.cacheSettings.value + authStore.setCacheSettings(current.copy(likedCapBytes = bytes)) + } + + fun setRollingCapBytes(bytes: Long) { + val current = authStore.cacheSettings.value + authStore.setCacheSettings(current.copy(rollingCapBytes = bytes)) + } + + fun setPrefetchWindow(n: Int) { + val clamped = n.coerceIn(1, MAX_PREFETCH_WINDOW) + val current = authStore.cacheSettings.value + authStore.setCacheSettings(current.copy(prefetchWindow = clamped)) + } + + fun setCacheLikedTracks(on: Boolean) { + val current = authStore.cacheSettings.value + authStore.setCacheSettings(current.copy(cacheLikedTracks = on)) + } + + fun syncNow() { + if (internal.value.isSyncing) return + viewModelScope.launch { + internal.update { it.copy(isSyncing = true) } + try { + syncController.syncSafe() + } finally { + internal.update { it.copy(isSyncing = false) } + } + } + } + + fun clearCache() { + if (internal.value.isClearing) return + viewModelScope.launch { + internal.update { it.copy(isClearing = true) } + try { + withContext(Dispatchers.IO) { + // SimpleCache.getKeys() + removeResource is the safe + // path — releasing the cache mid-flight would crash + // any in-progress playback. Iterating + removing + // works while the cache is in use. + val cache = playerFactory.simpleCache + val keys = cache.keys.toList() + for (k in keys) { + runCatching { cache.removeResource(k) } + } + } + refreshUsage() + } finally { + internal.update { it.copy(isClearing = false) } + } + } + } + + /** Re-reads each budget's usage from the evictor. Cheap: two longs. */ + private fun refreshUsage() { + viewModelScope.launch { + val usage = withContext(Dispatchers.IO) { cacheEvictor.usage() } + internal.update { it.copy(likedBytes = usage.likedBytes, recentBytes = usage.recentBytes) } + } + } + + companion object { + private const val MAX_PREFETCH_WINDOW = 10 } } - - companion object { - private const val MAX_PREFETCH_WINDOW = 10 - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/CacheFirstStateFlow.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/CacheFirstStateFlow.kt index 39cd22e2..e3238f3b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/CacheFirstStateFlow.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/CacheFirstStateFlow.kt @@ -20,12 +20,11 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L * Replaces the catch + stateIn(viewModelScope, WhileSubscribed, * Loading) tail that every cache-first ViewModel writes today. */ -fun Flow>.asCacheFirstStateFlow( - scope: CoroutineScope, -): StateFlow> = this - .catch { e -> emit(UiState.Error(ErrorCopy.fromThrowable(e))) } - .stateIn( - scope = scope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = UiState.Loading, - ) +fun Flow>.asCacheFirstStateFlow(scope: CoroutineScope): StateFlow> = + this + .catch { e -> emit(UiState.Error(ErrorCopy.fromThrowable(e))) } + .stateIn( + scope = scope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = UiState.Loading, + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/Formatting.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/Formatting.kt index effba8d9..83ad50c4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/Formatting.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/Formatting.kt @@ -9,7 +9,10 @@ private const val SECONDS_PER_MINUTE = 60 * "--:--" for unknown track durations, "0:00" (default) for playback * position/duration. The single mm:ss formatter for the client. */ -fun formatDuration(seconds: Int, zero: String = "0:00"): String = +fun formatDuration( + seconds: Int, + zero: String = "0:00", +): String = if (seconds <= 0) { zero } else { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/Plural.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/Plural.kt index d762ceef..f434da59 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/Plural.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/Plural.kt @@ -7,5 +7,8 @@ import java.text.NumberFormat * for the listener's locale, as the web app's counts are. The app's one way to * say a count; PluralTest names any hand-written copy. */ -fun plural(n: Int, one: String, many: String): String = - "${NumberFormat.getIntegerInstance().format(n)} ${if (n == 1) one else many}" +fun plural( + n: Int, + one: String, + many: String, +): String = "${NumberFormat.getIntegerInstance().format(n)} ${if (n == 1) one else many}" diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/ServerUrls.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/ServerUrls.kt index 86d9bed5..002da475 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/ServerUrls.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/ServerUrls.kt @@ -17,9 +17,10 @@ package com.fabledsword.minstrel.shared * Any code handing a server-provided URL to a network client must * route through here — covers, stream URLs, anything `/api/...`. */ -fun resolveServerUrl(raw: String?): String? = when { - raw.isNullOrBlank() -> null - raw.startsWith("http://") || raw.startsWith("https://") -> raw - raw.startsWith("/") -> "http://placeholder.invalid$raw" - else -> "http://placeholder.invalid/$raw" -} +fun resolveServerUrl(raw: String?): String? = + when { + raw.isNullOrBlank() -> null + raw.startsWith("http://") || raw.startsWith("https://") -> raw + raw.startsWith("/") -> "http://placeholder.invalid$raw" + else -> "http://placeholder.invalid/$raw" + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/UiState.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/UiState.kt index b3fdce82..6d21c20a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/UiState.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/UiState.kt @@ -19,9 +19,16 @@ import kotlinx.coroutines.CancellationException */ sealed interface UiState { data object Loading : UiState + data object Empty : UiState - data class Success(val data: T) : UiState - data class Error(val message: String) : UiState + + data class Success( + val data: T, + ) : UiState + + data class Error( + val message: String, + ) : UiState } /** This list as a state: [UiState.Empty] when it has nothing in it, else [UiState.Success]. */ diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/UpdateVeilController.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/UpdateVeilController.kt index 79ebf602..d736bde2 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/UpdateVeilController.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/UpdateVeilController.kt @@ -204,15 +204,17 @@ class UpdateVeilController( val raiser = scope.launch { raiseWhenContentChanges(raised) } // Floor and ceiling are measured from the raise, not the request, // so a late raise still gets its full no-flash minimum. - val floor = scope.launch { - raised.await() - delay(timings.minHoldMs) - } - val ceiling = scope.launch { - raised.await() - delay(timings.maxHoldMs) - visibleInternal.value = false - } + val floor = + scope.launch { + raised.await() + delay(timings.minHoldMs) + } + val ceiling = + scope.launch { + raised.await() + delay(timings.maxHoldMs) + visibleInternal.value = false + } var succeeded = false try { succeeded = drainWork() @@ -259,12 +261,17 @@ class UpdateVeilController( raised.complete(Unit) } - private fun finish(succeeded: Boolean, changed: Boolean, userInitiated: Boolean) { - val outcome = when { - !succeeded -> VeilOutcome.FAILED - changed -> VeilOutcome.CHANGED - else -> VeilOutcome.UNCHANGED - } + private fun finish( + succeeded: Boolean, + changed: Boolean, + userInitiated: Boolean, + ) { + val outcome = + when { + !succeeded -> VeilOutcome.FAILED + changed -> VeilOutcome.CHANGED + else -> VeilOutcome.UNCHANGED + } onSessionEnd( VeilSessionResult( outcome = outcome, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/AppBarActionsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/AppBarActionsViewModel.kt index 718433b4..82efcc04 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/AppBarActionsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/AppBarActionsViewModel.kt @@ -21,23 +21,27 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L * sign-out, and role changes pushed via rehydration. */ @HiltViewModel -class AppBarActionsViewModel @Inject constructor( - authController: AuthController, - notifications: NotificationsRepository, -) : ViewModel() { - val isAdmin: StateFlow = authController.currentUser - .map { it?.isAdmin == true } - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = false, - ) +class AppBarActionsViewModel + @Inject + constructor( + authController: AuthController, + notifications: NotificationsRepository, + ) : ViewModel() { + val isAdmin: StateFlow = + authController.currentUser + .map { it?.isAdmin == true } + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = false, + ) - /** Unread notices for the bell's badge. */ - val unreadCount: StateFlow = notifications.unreadCount - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = 0, - ) -} + /** Unread notices for the bell's badge. */ + val unreadCount: StateFlow = + notifications.unreadCount + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = 0, + ) + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CachedDot.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CachedDot.kt index c17b749f..54734fc4 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CachedDot.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CachedDot.kt @@ -26,14 +26,18 @@ val LocalCachedTrackIds = staticCompositionLocalOf { emptySet() } * queries. */ @Composable -fun CachedDot(trackId: String, modifier: Modifier = Modifier) { +fun CachedDot( + trackId: String, + modifier: Modifier = Modifier, +) { if (trackId !in LocalCachedTrackIds.current) return Icon( imageVector = Lucide.CircleCheckBig, contentDescription = "Downloaded", tint = LocalFabledSwordTheme.current.accent, - modifier = modifier - .padding(start = 4.dp) - .size(14.dp), + modifier = + modifier + .padding(start = 4.dp) + .size(14.dp), ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CoverTile.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CoverTile.kt index a3e71e0c..d83fb47d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CoverTile.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/CoverTile.kt @@ -50,10 +50,11 @@ fun CoverTile( contentAlignment = Alignment.Center, ) { Box( - modifier = Modifier - .fillMaxSize() - .clip(shape) - .background(background), + modifier = + Modifier + .fillMaxSize() + .clip(shape) + .background(background), contentAlignment = Alignment.Center, ) { ServerImage( @@ -75,7 +76,10 @@ fun CoverTile( * library's cards; smaller and larger covers pass their own [size]. */ @Composable -fun CoverFallbackIcon(icon: ImageVector, size: Dp = 56.dp) { +fun CoverFallbackIcon( + icon: ImageVector, + size: Dp = 56.dp, +) { Icon( imageVector = icon, contentDescription = null, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt index 5427c37a..04018875 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Dialogs.kt @@ -46,10 +46,11 @@ fun NameDialog( onValueChange = { name = it }, label = { Text("Name") }, singleLine = true, - keyboardOptions = KeyboardOptions( - capitalization = KeyboardCapitalization.Sentences, - imeAction = ImeAction.Done, - ), + keyboardOptions = + KeyboardOptions( + capitalization = KeyboardCapitalization.Sentences, + imeAction = ImeAction.Done, + ), keyboardActions = KeyboardActions(onDone = { if (trimmed.isNotEmpty()) onConfirm(trimmed) }), modifier = Modifier.fillMaxWidth(), ) @@ -105,10 +106,11 @@ fun ConfirmDestructiveDialog( Button( onClick = onConfirm, enabled = armed, - colors = ButtonDefaults.buttonColors( - containerColor = actions.destructive, - contentColor = actions.onAction, - ), + colors = + ButtonDefaults.buttonColors( + containerColor = actions.destructive, + contentColor = actions.onAction, + ), ) { Text(confirmLabel) } }, dismissButton = { TextButton(onClick = onDismiss) { Text("Cancel") } }, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/EmptyState.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/EmptyState.kt index 2b1d0909..96e42b7b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/EmptyState.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/EmptyState.kt @@ -6,15 +6,15 @@ import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.size import androidx.compose.foundation.lazy.LazyColumn +import androidx.compose.material3.Icon import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Text import androidx.compose.runtime.Composable import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.text.style.TextAlign import androidx.compose.ui.unit.dp -import androidx.compose.material3.Icon -import androidx.compose.ui.graphics.vector.ImageVector import com.composables.icons.lucide.Inbox import com.composables.icons.lucide.Lucide @@ -43,9 +43,10 @@ fun EmptyState( LazyColumn(modifier = modifier.fillMaxSize()) { item { Box( - modifier = Modifier - .fillParentMaxSize() - .padding(32.dp), + modifier = + Modifier + .fillParentMaxSize() + .padding(32.dp), contentAlignment = Alignment.Center, ) { Column(horizontalAlignment = Alignment.CenterHorizontally) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ErrorRetry.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ErrorRetry.kt index 3768296e..3decba47 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ErrorRetry.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ErrorRetry.kt @@ -42,9 +42,10 @@ fun ErrorRetry( LazyColumn(modifier = modifier.fillMaxSize()) { item { Column( - modifier = Modifier - .fillParentMaxSize() - .padding(32.dp), + modifier = + Modifier + .fillParentMaxSize() + .padding(32.dp), verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally, ) { @@ -73,10 +74,11 @@ fun ErrorRetry( Button( onClick = onRetry, modifier = Modifier.padding(top = 16.dp), - colors = ButtonDefaults.buttonColors( - containerColor = actionColors.primary, - contentColor = actionColors.onAction, - ), + colors = + ButtonDefaults.buttonColors( + containerColor = actionColors.primary, + contentColor = actionColors.onAction, + ), ) { Text(retryLabel) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/LikeButton.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/LikeButton.kt index 78927cb4..4589b1dd 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/LikeButton.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/LikeButton.kt @@ -37,11 +37,12 @@ fun LikeButton( Icon( imageVector = if (liked) HeartFilled else Lucide.Heart, contentDescription = if (liked) "Unlike" else "Like", - tint = if (liked) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.onSurfaceVariant - }, + tint = + if (liked) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, ) } } @@ -53,27 +54,28 @@ fun LikeButton( * own pattern (heart.kt in the icons-lucide-cmp jar). */ private val HeartFilled: ImageVector by lazy { - ImageVector.Builder( - name = "heart_filled", - defaultWidth = 24.dp, - defaultHeight = 24.dp, - viewportWidth = 24f, - viewportHeight = 24f, - ).apply { - path( - fill = SolidColor(Color.Black), - stroke = null, - ) { - moveTo(2f, 9.5f) - arcToRelative(5.5f, 5.5f, 0f, false, true, 9.591f, -3.676f) - arcToRelative(0.56f, 0.56f, 0f, false, false, 0.818f, 0f) - arcTo(5.49f, 5.49f, 0f, false, true, 22f, 9.5f) - curveToRelative(0f, 2.29f, -1.5f, 4f, -3f, 5.5f) - lineToRelative(-5.492f, 5.313f) - arcToRelative(2f, 2f, 0f, false, true, -3f, 0.019f) - lineTo(5f, 15f) - curveToRelative(-1.5f, -1.5f, -3f, -3.2f, -3f, -5.5f) - close() - } - }.build() + ImageVector + .Builder( + name = "heart_filled", + defaultWidth = 24.dp, + defaultHeight = 24.dp, + viewportWidth = 24f, + viewportHeight = 24f, + ).apply { + path( + fill = SolidColor(Color.Black), + stroke = null, + ) { + moveTo(2f, 9.5f) + arcToRelative(5.5f, 5.5f, 0f, false, true, 9.591f, -3.676f) + arcToRelative(0.56f, 0.56f, 0f, false, false, 0.818f, 0f) + arcTo(5.49f, 5.49f, 0f, false, true, 22f, 9.5f) + curveToRelative(0f, 2.29f, -1.5f, 4f, -3f, 5.5f) + lineToRelative(-5.492f, 5.313f) + arcToRelative(2f, 2f, 0f, false, true, -3f, 0.019f) + lineTo(5f, 15f) + curveToRelative(-1.5f, -1.5f, -3f, -3.2f, -3f, -5.5f) + close() + } + }.build() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/MainAppBarActions.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/MainAppBarActions.kt index 4c0f62ad..bea4609c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/MainAppBarActions.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/MainAppBarActions.kt @@ -18,16 +18,16 @@ import androidx.hilt.navigation.compose.hiltViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.navigation.NavHostController import com.composables.icons.lucide.Bell +import com.composables.icons.lucide.EllipsisVertical import com.composables.icons.lucide.House import com.composables.icons.lucide.LibraryBig import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.EllipsisVertical -import com.composables.icons.lucide.Search as SearchIcon import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.Home import com.fabledsword.minstrel.nav.Library import com.fabledsword.minstrel.nav.Notifications import com.fabledsword.minstrel.nav.Playlists +import com.composables.icons.lucide.Search as SearchIcon import com.fabledsword.minstrel.nav.Search as SearchRoute import com.fabledsword.minstrel.nav.Settings as SettingsRoute @@ -80,7 +80,10 @@ fun MainAppBarActions( /** The inbox bell with its unread badge: the count to 9, then "9+". */ @Composable -private fun NotificationsBell(unread: Int, onClick: () -> Unit) { +private fun NotificationsBell( + unread: Int, + onClick: () -> Unit, +) { val label = badgeLabel(unread) IconButton(onClick = onClick) { // Inverse of the bar, not error red: an unread count is news, not a @@ -104,16 +107,20 @@ private fun NotificationsBell(unread: Int, onClick: () -> Unit) { } /** Badge text: nothing at zero, the count up to nine, then "9+". */ -internal fun badgeLabel(count: Int): String = when { - count <= 0 -> "" - count > MAX_BADGE -> "$MAX_BADGE+" - else -> count.toString() -} +internal fun badgeLabel(count: Int): String = + when { + count <= 0 -> "" + count > MAX_BADGE -> "$MAX_BADGE+" + else -> count.toString() + } private const val MAX_BADGE = 9 @Composable -private fun OverflowMenu(navController: NavHostController, isAdmin: Boolean) { +private fun OverflowMenu( + navController: NavHostController, + isAdmin: Boolean, +) { var expanded by remember { mutableStateOf(false) } IconButton(onClick = { expanded = true }) { Icon(Lucide.EllipsisVertical, contentDescription = "More") @@ -121,16 +128,25 @@ private fun OverflowMenu(navController: NavHostController, isAdmin: Boolean) { DropdownMenu(expanded = expanded, onDismissRequest = { expanded = false }) { DropdownMenuItem( text = { Text("Playlists") }, - onClick = { expanded = false; navController.navigate(Playlists) }, + onClick = { + expanded = false + navController.navigate(Playlists) + }, ) DropdownMenuItem( text = { Text("Settings") }, - onClick = { expanded = false; navController.navigate(SettingsRoute) }, + onClick = { + expanded = false + navController.navigate(SettingsRoute) + }, ) if (isAdmin) { DropdownMenuItem( text = { Text("Admin") }, - onClick = { expanded = false; navController.navigate(Admin) }, + onClick = { + expanded = false + navController.navigate(Admin) + }, ) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/PlayCircleButton.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/PlayCircleButton.kt index c7c7e677..2262eb14 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/PlayCircleButton.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/PlayCircleButton.kt @@ -54,9 +54,10 @@ fun PlayCircleButton( } } }, - modifier = modifier - .size(size) - .alpha(alpha), + modifier = + modifier + .size(size) + .alpha(alpha), enabled = enabled && !starting, shape = CircleShape, color = MaterialTheme.colorScheme.primary, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/PullRefreshNetworkViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/PullRefreshNetworkViewModel.kt index af28b155..3163557a 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/PullRefreshNetworkViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/PullRefreshNetworkViewModel.kt @@ -13,9 +13,11 @@ import javax.inject.Inject * [PullToRefreshScaffold]. */ @HiltViewModel -class PullRefreshNetworkViewModel @Inject constructor( - private val networkStatus: NetworkStatusController, - @Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle, -) : ViewModel() { - fun recheck() = networkStatus.recheck() -} +class PullRefreshNetworkViewModel + @Inject + constructor( + private val networkStatus: NetworkStatusController, + @Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle, + ) : ViewModel() { + fun recheck() = networkStatus.recheck() + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt index 556a6cd9..a1309e8b 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMath.kt @@ -12,8 +12,10 @@ import kotlin.math.roundToInt * down moves one row, half a row up stays put. A row not yet measured * (height 0) moves nothing. */ -internal fun reorderDragDelta(offsetPx: Float, rowHeightPx: Int): Int = - if (rowHeightPx > 0) (offsetPx / rowHeightPx).roundToInt() else 0 +internal fun reorderDragDelta( + offsetPx: Float, + rowHeightPx: Int, +): Int = if (rowHeightPx > 0) (offsetPx / rowHeightPx).roundToInt() else 0 /** * The index a row dragged from [index] lands on, in a list of [count] rows diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt index cb254268..9b2e3c14 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ReorderableRow.kt @@ -41,7 +41,10 @@ import com.fabledsword.minstrel.theme.LocalActionColors * (the album art), [actions] on the row's clickable container, where a * screen reader finds it. */ -class ReorderHandles(val drag: Modifier, val actions: Modifier) +class ReorderHandles( + val drag: Modifier, + val actions: Modifier, +) /** * A list row that can be dragged to a new place and swiped away: the queue's @@ -73,26 +76,28 @@ fun ReorderableRemovableRow( ) { var dragOffsetY by remember { mutableFloatStateOf(0f) } var rowHeightPx by remember { mutableIntStateOf(0) } - val dismissState = rememberSwipeToDismissBoxState( - confirmValueChange = { value -> - if (value == SwipeToDismissBoxValue.EndToStart) { - onRemove() - true - } else { - false - } - }, - ) + val dismissState = + rememberSwipeToDismissBoxState( + confirmValueChange = { value -> + if (value == SwipeToDismissBoxValue.EndToStart) { + onRemove() + true + } else { + false + } + }, + ) SwipeToDismissBox( state = dismissState, enableDismissFromStartToEnd = false, backgroundContent = { RemoveSwipeBackground() }, // The lift lives out here so a row being dragged vertically carries // its swipe container with it rather than sliding out of one. - modifier = Modifier - .onSizeChanged { rowHeightPx = it.height } - .zIndex(if (dragOffsetY != 0f) 1f else 0f) - .graphicsLayer { translationY = dragOffsetY }, + modifier = + Modifier + .onSizeChanged { rowHeightPx = it.height } + .zIndex(if (dragOffsetY != 0f) 1f else 0f) + .graphicsLayer { translationY = dragOffsetY }, ) { content( ReorderHandles( @@ -116,10 +121,11 @@ fun ReorderableRemovableRow( private fun RemoveSwipeBackground() { val actions = LocalActionColors.current Box( - modifier = Modifier - .fillMaxSize() - .background(actions.destructive) - .padding(horizontal = 24.dp), + modifier = + Modifier + .fillMaxSize() + .background(actions.destructive) + .padding(horizontal = 24.dp), contentAlignment = Alignment.CenterEnd, ) { Row( @@ -147,17 +153,32 @@ private fun Modifier.reorderActions( removeLabel: String, onMove: (Int, Int) -> Unit, onRemove: () -> Unit, -): Modifier = semantics { - customActions = listOf( - CustomAccessibilityAction("Move up") { - if (index > 0) { onMove(index, index - 1); true } else false - }, - CustomAccessibilityAction("Move down") { - if (index < count - 1) { onMove(index, index + 1); true } else false - }, - CustomAccessibilityAction(removeLabel) { onRemove(); true }, - ) -} +): Modifier = + semantics { + customActions = + listOf( + CustomAccessibilityAction("Move up") { + if (index > 0) { + onMove(index, index - 1) + true + } else { + false + } + }, + CustomAccessibilityAction("Move down") { + if (index < count - 1) { + onMove(index, index + 1) + true + } else { + false + } + }, + CustomAccessibilityAction(removeLabel) { + onRemove() + true + }, + ) + } /** * The long-press drag. The row follows the finger during the drag, as on @@ -169,25 +190,26 @@ private fun Modifier.reorderDrag( rowHeightPx: Int, onOffsetChange: (Float) -> Unit, onMove: (Int, Int) -> Unit, -): Modifier = composed { - var offset by remember { mutableFloatStateOf(0f) } - pointerInput(index, count, rowHeightPx) { - detectDragGesturesAfterLongPress( - onDrag = { change, dragAmount -> - change.consume() - offset += dragAmount.y - onOffsetChange(offset) - }, - onDragEnd = { - val target = reorderDragTarget(index, offset, rowHeightPx, count) - if (target != index) onMove(index, target) - offset = 0f - onOffsetChange(0f) - }, - onDragCancel = { - offset = 0f - onOffsetChange(0f) - }, - ) +): Modifier = + composed { + var offset by remember { mutableFloatStateOf(0f) } + pointerInput(index, count, rowHeightPx) { + detectDragGesturesAfterLongPress( + onDrag = { change, dragAmount -> + change.consume() + offset += dragAmount.y + onOffsetChange(offset) + }, + onDragEnd = { + val target = reorderDragTarget(index, offset, rowHeightPx, count) + if (target != index) onMove(index, target) + offset = 0f + onOffsetChange(0f) + }, + onDragCancel = { + offset = 0f + onOffsetChange(0f) + }, + ) + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ServerImage.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ServerImage.kt index 19310895..33984e6f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ServerImage.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ServerImage.kt @@ -57,8 +57,9 @@ fun ServerImage( } // Empty counts as loading: it's the pre-request state, so treating it // as settled would let a screen overlay lower before Coil even starts. - val loading = state is AsyncImagePainter.State.Empty || - state is AsyncImagePainter.State.Loading + val loading = + state is AsyncImagePainter.State.Empty || + state is AsyncImagePainter.State.Loading val tracker = LocalArtSettleTracker.current DisposableEffect(tracker, loading) { if (loading) tracker?.begin() diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ShellScaffold.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ShellScaffold.kt index 127a2bbf..2925132d 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ShellScaffold.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/ShellScaffold.kt @@ -21,8 +21,8 @@ import com.fabledsword.minstrel.cache.mutations.OfflineWriteHintViewModel import com.fabledsword.minstrel.connectivity.ui.ConnectionErrorBanner import com.fabledsword.minstrel.player.ui.MiniPlayer import com.fabledsword.minstrel.player.ui.PlaybackErrorViewModel -import com.fabledsword.minstrel.update.ui.VersionTooOldBanner import com.fabledsword.minstrel.shared.widgets.trackactions.TrackActionsViewModel +import com.fabledsword.minstrel.update.ui.VersionTooOldBanner /** * `contentWindowInsets` for a screen's own Scaffold when that screen @@ -111,10 +111,11 @@ fun ShellScaffold( // Un-owned, the inset re-appears inside each screen as a dead // strip between the last list row and the MiniPlayer. Box( - modifier = Modifier - .fillMaxWidth() - .weight(1f) - .consumeWindowInsets(WindowInsets.navigationBars), + modifier = + Modifier + .fillMaxWidth() + .weight(1f) + .consumeWindowInsets(WindowInsets.navigationBars), ) { content() } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Skeletons.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Skeletons.kt index 722b4dda..b21f6f75 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Skeletons.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/Skeletons.kt @@ -54,16 +54,18 @@ fun SkeletonBox( val alpha by transition.animateFloat( initialValue = PULSE_MIN_ALPHA, targetValue = PULSE_MAX_ALPHA, - animationSpec = infiniteRepeatable( - animation = tween(PULSE_DURATION_MS, easing = LinearEasing), - repeatMode = RepeatMode.Reverse, - ), + animationSpec = + infiniteRepeatable( + animation = tween(PULSE_DURATION_MS, easing = LinearEasing), + repeatMode = RepeatMode.Reverse, + ), label = "skeleton-alpha", ) Box( - modifier = modifier - .clip(shape) - .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)), + modifier = + modifier + .clip(shape) + .background(MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = alpha)), ) } @@ -72,11 +74,15 @@ fun SkeletonBox( * cover in a tile 32dp wider, and 2 caption lines). */ @Composable -fun SkeletonAlbumTile(modifier: Modifier = Modifier, artSize: Dp = 144.dp) { +fun SkeletonAlbumTile( + modifier: Modifier = Modifier, + artSize: Dp = 144.dp, +) { Column( - modifier = modifier - .width(artSize + 32.dp) - .padding(horizontal = 8.dp), + modifier = + modifier + .width(artSize + 32.dp) + .padding(horizontal = 8.dp), ) { SkeletonBox(modifier = Modifier.size(artSize)) Spacer(Modifier.height(8.dp)) @@ -91,11 +97,15 @@ fun SkeletonAlbumTile(modifier: Modifier = Modifier, artSize: Dp = 144.dp) { * wider, and 1 name line). */ @Composable -fun SkeletonArtistTile(modifier: Modifier = Modifier, artSize: Dp = 128.dp) { +fun SkeletonArtistTile( + modifier: Modifier = Modifier, + artSize: Dp = 128.dp, +) { Column( - modifier = modifier - .width(artSize + 16.dp) - .padding(horizontal = 8.dp), + modifier = + modifier + .width(artSize + 16.dp) + .padding(horizontal = 8.dp), horizontalAlignment = Alignment.CenterHorizontally, ) { SkeletonBox( @@ -113,16 +123,18 @@ fun SkeletonArtistTile(modifier: Modifier = Modifier, artSize: Dp = 128.dp) { @Composable fun SkeletonTrackRow(modifier: Modifier = Modifier) { Row( - modifier = modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), + modifier = + modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 8.dp), horizontalArrangement = Arrangement.spacedBy(12.dp), verticalAlignment = Alignment.CenterVertically, ) { SkeletonBox(modifier = Modifier.size(40.dp)) Column( - modifier = Modifier - .weight(1f, fill = true), + modifier = + Modifier + .weight(1f, fill = true), verticalArrangement = Arrangement.spacedBy(6.dp), ) { SkeletonBox(modifier = Modifier.fillMaxWidth().height(14.dp)) @@ -135,9 +147,10 @@ fun SkeletonTrackRow(modifier: Modifier = Modifier) { @Composable fun SkeletonSectionHeader(modifier: Modifier = Modifier) { Box( - modifier = modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), + modifier = + modifier + .fillMaxWidth() + .padding(horizontal = 16.dp, vertical = 12.dp), ) { SkeletonBox(modifier = Modifier.width(160.dp).height(20.dp)) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackCoverThumb.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackCoverThumb.kt index 2486ab85..5f2b887e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackCoverThumb.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackCoverThumb.kt @@ -36,10 +36,11 @@ fun TrackCoverThumb( size: Dp = DEFAULT_SIZE, ) { Box( - modifier = modifier - .size(size) - .clip(RoundedCornerShape(4.dp)) - .background(MaterialTheme.colorScheme.surfaceVariant), + modifier = + modifier + .size(size) + .clip(RoundedCornerShape(4.dp)) + .background(MaterialTheme.colorScheme.surfaceVariant), contentAlignment = Alignment.Center, ) { ServerImage( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackRow.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackRow.kt index d3d4eb67..105200ec 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackRow.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/TrackRow.kt @@ -65,26 +65,30 @@ fun TrackRow( val offlineUnavailable = (health == ServerHealth.Offline || health == ServerHealth.ServerDown) && trackId !in LocalCachedTrackIds.current - val titleColor = if (nowPlaying) { - MaterialTheme.colorScheme.primary - } else { - MaterialTheme.colorScheme.onSurface - } - val effectiveAlpha = if (offlineUnavailable) { - minOf(contentAlpha, OFFLINE_UNAVAILABLE_ALPHA) - } else { - contentAlpha - } - val effectiveOnClick: () -> Unit = if (offlineUnavailable) { - { Toast.makeText(context, OFFLINE_TAP_MESSAGE, Toast.LENGTH_SHORT).show() } - } else { - onClick - } + val titleColor = + if (nowPlaying) { + MaterialTheme.colorScheme.primary + } else { + MaterialTheme.colorScheme.onSurface + } + val effectiveAlpha = + if (offlineUnavailable) { + minOf(contentAlpha, OFFLINE_UNAVAILABLE_ALPHA) + } else { + contentAlpha + } + val effectiveOnClick: () -> Unit = + if (offlineUnavailable) { + { Toast.makeText(context, OFFLINE_TAP_MESSAGE, Toast.LENGTH_SHORT).show() } + } else { + onClick + } Row( - modifier = modifier - .fillMaxWidth() - .clickable(enabled = enabled, onClick = effectiveOnClick) - .padding(horizontal = 16.dp, vertical = 8.dp), + modifier = + modifier + .fillMaxWidth() + .clickable(enabled = enabled, onClick = effectiveOnClick) + .padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = horizontalArrangement, ) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt index 25f72b53..aa4ffafd 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistSheet.kt @@ -75,22 +75,25 @@ fun AddToPlaylistSheet( ) NewPlaylistRow(onClick = { naming = true }) when (val s = state) { - UiState.Loading -> Box( - modifier = Modifier.fillMaxWidth().padding(24.dp), - contentAlignment = Alignment.Center, - ) { CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) } + UiState.Loading -> + Box( + modifier = Modifier.fillMaxWidth().padding(24.dp), + contentAlignment = Alignment.Center, + ) { CircularProgressIndicator(color = MaterialTheme.colorScheme.primary) } // The New playlist row above is the way forward. UiState.Empty -> Unit - is UiState.Error -> Text( - text = s.message, - color = MaterialTheme.colorScheme.error, - modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp), - ) - is UiState.Success -> LazyColumn(modifier = Modifier.fillMaxWidth()) { - items(items = s.data, key = { it.id }) { p -> - PlaylistPickRow(playlist = p, onClick = { onPick(p.id) }) + is UiState.Error -> + Text( + text = s.message, + color = MaterialTheme.colorScheme.error, + modifier = Modifier.padding(horizontal = 20.dp, vertical = 12.dp), + ) + is UiState.Success -> + LazyColumn(modifier = Modifier.fillMaxWidth()) { + items(items = s.data, key = { it.id }) { p -> + PlaylistPickRow(playlist = p, onClick = { onPick(p.id) }) + } } - } } } } @@ -99,10 +102,11 @@ fun AddToPlaylistSheet( @Composable private fun NewPlaylistRow(onClick: () -> Unit) { Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .padding(horizontal = 20.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 20.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), ) { @@ -116,12 +120,16 @@ private fun NewPlaylistRow(onClick: () -> Unit) { } @Composable -private fun PlaylistPickRow(playlist: PlaylistRef, onClick: () -> Unit) { +private fun PlaylistPickRow( + playlist: PlaylistRef, + onClick: () -> Unit, +) { Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .padding(horizontal = 20.dp, vertical = 12.dp), + modifier = + Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 20.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), ) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt index c0f5f2b2..05c274f0 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/AddToPlaylistViewModel.kt @@ -18,23 +18,23 @@ import javax.inject.Inject * other people's public lists are left out: neither can take a song. */ @HiltViewModel -class AddToPlaylistViewModel @Inject constructor( - repository: PlaylistsRepository, -) : ViewModel() { - - val uiState: StateFlow>> = repository - .observeOwnPlaylists() - .map { list -> - if (list.isEmpty()) UiState.Empty else UiState.Success(list) - } - .onStart { - // Best-effort refresh so the sheet reflects newly-created - // playlists from another device. Cached list shows first; - // refresh emission updates the state once Room reflects it. - viewModelScope.launch { - runCatching { repository.refreshList() } - } - emit(UiState.Loading) - } - .asCacheFirstStateFlow(viewModelScope) -} +class AddToPlaylistViewModel + @Inject + constructor( + repository: PlaylistsRepository, + ) : ViewModel() { + val uiState: StateFlow>> = + repository + .observeOwnPlaylists() + .map { list -> + if (list.isEmpty()) UiState.Empty else UiState.Success(list) + }.onStart { + // Best-effort refresh so the sheet reflects newly-created + // playlists from another device. Cached list shows first; + // refresh emission updates the state once Room reflects it. + viewModelScope.launch { + runCatching { repository.refreshList() } + } + emit(UiState.Loading) + }.asCacheFirstStateFlow(viewModelScope) + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/HideTrackSheet.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/HideTrackSheet.kt index d4063d54..70bb3229 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/HideTrackSheet.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/HideTrackSheet.kt @@ -26,16 +26,20 @@ import androidx.compose.runtime.setValue import androidx.compose.ui.Modifier import androidx.compose.ui.unit.dp -private data class HideReason(val wire: String, val label: String) - -private val HIDE_REASONS = listOf( - HideReason("bad_rip", "Bad rip"), - HideReason("wrong_file", "Wrong file"), - HideReason("wrong_tags", "Wrong tags"), - HideReason("duplicate", "Duplicate"), - HideReason("other", "Other"), +private data class HideReason( + val wire: String, + val label: String, ) +private val HIDE_REASONS = + listOf( + HideReason("bad_rip", "Bad rip"), + HideReason("wrong_file", "Wrong file"), + HideReason("wrong_tags", "Wrong tags"), + HideReason("duplicate", "Duplicate"), + HideReason("other", "Other"), + ) + /** * ModalBottomSheet that collects a hide reason + optional notes and * pops back via [onSubmit]. The @@ -55,9 +59,10 @@ fun HideTrackSheet( sheetState = sheetState, ) { Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 20.dp, vertical = 8.dp), + modifier = + Modifier + .fillMaxWidth() + .padding(horizontal = 20.dp, vertical = 8.dp), ) { Text( text = "Hide this track", @@ -103,7 +108,10 @@ fun HideTrackSheet( } @Composable -private fun HideSheetButtons(onCancel: () -> Unit, onSubmit: () -> Unit) { +private fun HideSheetButtons( + onCancel: () -> Unit, + onSubmit: () -> Unit, +) { Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt index 3b81af88..8342d882 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsSheet.kt @@ -110,19 +110,23 @@ private fun TrackActionMenuItems( Column(modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) { if (!hideQueueActions) { MenuItem(Lucide.ListVideo, "Play next") { - viewModel.playNext(track); onDismiss() + viewModel.playNext(track) + onDismiss() } MenuItem(Lucide.ListMusic, "Add to queue") { - viewModel.enqueue(track); onDismiss() + viewModel.enqueue(track) + onDismiss() } HorizontalDivider() } MenuItem(Lucide.Heart, if (isLiked) "Unlike" else "Like") { - viewModel.toggleLike(track.id, isLiked); onDismiss() + viewModel.toggleLike(track.id, isLiked) + onDismiss() } MenuItem(Lucide.ListPlus, "Add to playlist…", onShowAddToPlaylist) MenuItem(Lucide.Radio, "Start radio") { - viewModel.startRadio(track.id); onDismiss() + viewModel.startRadio(track.id) + onDismiss() } HorizontalDivider() MenuItem(Lucide.Disc3, "Go to album") { @@ -139,7 +143,8 @@ private fun TrackActionMenuItems( label = if (isHidden) "Unhide" else "Hide", ) { if (isHidden) { - viewModel.unflag(track.id); onDismiss() + viewModel.unflag(track.id) + onDismiss() } else { onShowHideSheet() } @@ -185,12 +190,17 @@ private fun TrackActionSubSheets( } @Composable -private fun MenuItem(icon: ImageVector, label: String, onClick: () -> Unit) { +private fun MenuItem( + icon: ImageVector, + label: String, + onClick: () -> Unit, +) { Row( - modifier = Modifier - .fillMaxWidth() - .clickable(onClick = onClick) - .padding(horizontal = 20.dp, vertical = 14.dp), + modifier = + Modifier + .fillMaxWidth() + .clickable(onClick = onClick) + .padding(horizontal = 20.dp, vertical = 14.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), ) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt index cb5eda3e..c21807bc 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/shared/widgets/trackactions/TrackActionsViewModel.kt @@ -40,115 +40,126 @@ import javax.inject.Inject * a manual reload. */ @HiltViewModel -class TrackActionsViewModel @Inject constructor( - private val likes: LikesRepository, - private val quarantine: QuarantineRepository, - private val player: PlayerController, - private val playlists: PlaylistsRepository, - private val eventsStream: EventsStream, -) : ViewModel() { +class TrackActionsViewModel + @Inject + constructor( + private val likes: LikesRepository, + private val quarantine: QuarantineRepository, + private val player: PlayerController, + private val playlists: PlaylistsRepository, + private val eventsStream: EventsStream, + ) : ViewModel() { + private val messages = MutableSharedFlow(extraBufferCapacity = 4) + val transientMessages: SharedFlow = messages.asSharedFlow() - private val messages = MutableSharedFlow(extraBufferCapacity = 4) - val transientMessages: SharedFlow = messages.asSharedFlow() + private val hiddenTrackIdsInternal = MutableStateFlow>(emptySet()) + val hiddenTrackIds: StateFlow> = hiddenTrackIdsInternal.asStateFlow() - private val hiddenTrackIdsInternal = MutableStateFlow>(emptySet()) - val hiddenTrackIds: StateFlow> = hiddenTrackIdsInternal.asStateFlow() - - init { - refreshHidden() - viewModelScope.launch { - eventsStream.events - .filter { it.kind.startsWith("quarantine.") } - .collect { refreshHidden() } + init { + refreshHidden() + viewModelScope.launch { + eventsStream.events + .filter { it.kind.startsWith("quarantine.") } + .collect { refreshHidden() } + } } - } - fun isLikedFlow(trackId: String): Flow = - likes.observeIsLiked(LikesRepository.ENTITY_TRACK, trackId) + fun isLikedFlow(trackId: String): Flow = likes.observeIsLiked(LikesRepository.ENTITY_TRACK, trackId) - fun isHiddenFlow(trackId: String): Flow = - hiddenTrackIds.map { trackId in it } + fun isHiddenFlow(trackId: String): Flow = hiddenTrackIds.map { trackId in it } - fun playNext(track: TrackRef) { - player.playNext(track) - messages.tryEmit("Added to queue (next)") - } + fun playNext(track: TrackRef) { + player.playNext(track) + messages.tryEmit("Added to queue (next)") + } - fun enqueue(track: TrackRef) { - player.enqueue(track) - messages.tryEmit("Added to queue") - } + fun enqueue(track: TrackRef) { + player.enqueue(track) + messages.tryEmit("Added to queue") + } - fun toggleLike(trackId: String, currentlyLiked: Boolean) { - viewModelScope.launch { - runCatching { - likes.toggleLike( - entityType = LikesRepository.ENTITY_TRACK, - entityId = trackId, - desiredState = !currentlyLiked, - ) + fun toggleLike( + trackId: String, + currentlyLiked: Boolean, + ) { + viewModelScope.launch { + runCatching { + likes.toggleLike( + entityType = LikesRepository.ENTITY_TRACK, + entityId = trackId, + desiredState = !currentlyLiked, + ) + } + } + } + + fun startRadio(trackId: String) { + viewModelScope.launch { + runCatching { player.startRadio(trackId) } + .onFailure { + messages.tryEmit("Couldn't start radio: ${ErrorCopy.fromThrowable(it)}") + } + } + } + + fun appendToPlaylist( + playlistId: String, + trackId: String, + ) { + viewModelScope.launch { + runCatching { playlists.appendTrack(playlistId, trackId) } + .onSuccess { messages.tryEmit("Added to playlist") } + .onFailure { + messages.tryEmit("Couldn't add to playlist: ${ErrorCopy.fromThrowable(it)}") + } + } + } + + /** Makes a playlist called [name] holding just this song. */ + fun addToNewPlaylist( + name: String, + trackId: String, + ) { + viewModelScope.launch { + runCatching { + val (playlistId, _) = playlists.createPlaylist(name) + playlists.appendTrack(playlistId, trackId) + }.onSuccess { messages.tryEmit("Added to $name") } + .onFailure { + messages.tryEmit("Couldn't make the playlist: ${ErrorCopy.fromThrowable(it)}") + } + } + } + + fun flag( + track: TrackRef, + reason: String, + notes: String, + ) { + viewModelScope.launch { + runCatching { quarantine.flag(track, reason, notes) } + .onSuccess { refreshHidden() } + .onFailure { messages.tryEmit("Couldn't hide: ${ErrorCopy.fromThrowable(it)}") } + } + } + + fun unflag(trackId: String) { + viewModelScope.launch { + runCatching { quarantine.unflag(trackId) } + .onSuccess { refreshHidden() } + .onFailure { messages.tryEmit("Couldn't unhide: ${ErrorCopy.fromThrowable(it)}") } + } + } + + private fun refreshHidden() { + viewModelScope.launch { + runCatching { quarantine.listMine() } + .onSuccess { rows -> + hiddenTrackIdsInternal.value = rows.map { it.trackId }.toSet() + } + // Failure leaves the previous snapshot; the sheet still + // shows "Hide" by default which is safe (server is + // idempotent on re-flag). } } } - - fun startRadio(trackId: String) { - viewModelScope.launch { - runCatching { player.startRadio(trackId) } - .onFailure { - messages.tryEmit("Couldn't start radio: ${ErrorCopy.fromThrowable(it)}") - } - } - } - - fun appendToPlaylist(playlistId: String, trackId: String) { - viewModelScope.launch { - runCatching { playlists.appendTrack(playlistId, trackId) } - .onSuccess { messages.tryEmit("Added to playlist") } - .onFailure { - messages.tryEmit("Couldn't add to playlist: ${ErrorCopy.fromThrowable(it)}") - } - } - } - - /** Makes a playlist called [name] holding just this song. */ - fun addToNewPlaylist(name: String, trackId: String) { - viewModelScope.launch { - runCatching { - val (playlistId, _) = playlists.createPlaylist(name) - playlists.appendTrack(playlistId, trackId) - } - .onSuccess { messages.tryEmit("Added to $name") } - .onFailure { - messages.tryEmit("Couldn't make the playlist: ${ErrorCopy.fromThrowable(it)}") - } - } - } - - fun flag(track: TrackRef, reason: String, notes: String) { - viewModelScope.launch { - runCatching { quarantine.flag(track, reason, notes) } - .onSuccess { refreshHidden() } - .onFailure { messages.tryEmit("Couldn't hide: ${ErrorCopy.fromThrowable(it)}") } - } - } - - fun unflag(trackId: String) { - viewModelScope.launch { - runCatching { quarantine.unflag(trackId) } - .onSuccess { refreshHidden() } - .onFailure { messages.tryEmit("Couldn't unhide: ${ErrorCopy.fromThrowable(it)}") } - } - } - - private fun refreshHidden() { - viewModelScope.launch { - runCatching { quarantine.listMine() } - .onSuccess { rows -> - hiddenTrackIdsInternal.value = rows.map { it.trackId }.toSet() - } - // Failure leaves the previous snapshot; the sheet still - // shows "Hide" by default which is safe (server is - // idempotent on re-flag). - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/theme/ActionColors.kt b/android/app/src/main/java/com/fabledsword/minstrel/theme/ActionColors.kt index ab0adf0c..a7b598ae 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/theme/ActionColors.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/theme/ActionColors.kt @@ -13,17 +13,18 @@ import androidx.compose.ui.graphics.Color * rather than `MaterialTheme.colorScheme.primary`. */ data class ActionColors( - val primary: Color, // Moss — confirm, save, play - val secondary: Color, // Bronze — neutral, browse, accent action - val destructive: Color, // Oxblood — delete, unflag-as-destructive - val onAction: Color, // foreground / text on any of the above + val primary: Color, // Moss — confirm, save, play + val secondary: Color, // Bronze — neutral, browse, accent action + val destructive: Color, // Oxblood — delete, unflag-as-destructive + val onAction: Color, // foreground / text on any of the above ) -val LocalActionColors = staticCompositionLocalOf { - ActionColors( - primary = FabledSwordFlatTokens.moss, - secondary = FabledSwordFlatTokens.bronze, - destructive = FabledSwordFlatTokens.oxblood, - onAction = FabledSwordFlatTokens.onAction, - ) -} +val LocalActionColors = + staticCompositionLocalOf { + ActionColors( + primary = FabledSwordFlatTokens.moss, + secondary = FabledSwordFlatTokens.bronze, + destructive = FabledSwordFlatTokens.oxblood, + onAction = FabledSwordFlatTokens.onAction, + ) + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/theme/FabledSwordTheme.kt b/android/app/src/main/java/com/fabledsword/minstrel/theme/FabledSwordTheme.kt index 96d21e9f..e249245e 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/theme/FabledSwordTheme.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/theme/FabledSwordTheme.kt @@ -23,7 +23,6 @@ data class FabledSwordTheme( val slate: Color, val iron: Color, val obsidian: Color, - // Mode-independent action + status colors. val moss: Color, val bronze: Color, @@ -33,7 +32,6 @@ data class FabledSwordTheme( val info: Color, val accent: Color, val onAction: Color, - // Radii. val radiusSm: Dp, val radiusMd: Dp, @@ -41,49 +39,51 @@ data class FabledSwordTheme( val radiusXl: Dp, ) { companion object { - val Dark: FabledSwordTheme = FabledSwordTheme( - parchment = FabledSwordDarkTokens.parchment, - vellum = FabledSwordDarkTokens.vellum, - ash = FabledSwordDarkTokens.ash, - pewter = FabledSwordDarkTokens.pewter, - slate = FabledSwordDarkTokens.slate, - iron = FabledSwordDarkTokens.iron, - obsidian = FabledSwordDarkTokens.obsidian, - moss = FabledSwordFlatTokens.moss, - bronze = FabledSwordFlatTokens.bronze, - oxblood = FabledSwordFlatTokens.oxblood, - warning = FabledSwordFlatTokens.warning, - error = FabledSwordFlatTokens.error, - info = FabledSwordFlatTokens.info, - accent = FabledSwordFlatTokens.accent, - onAction = FabledSwordFlatTokens.onAction, - radiusSm = FabledSwordFlatTokens.radiusSm, - radiusMd = FabledSwordFlatTokens.radiusMd, - radiusLg = FabledSwordFlatTokens.radiusLg, - radiusXl = FabledSwordFlatTokens.radiusXl, - ) + val Dark: FabledSwordTheme = + FabledSwordTheme( + parchment = FabledSwordDarkTokens.parchment, + vellum = FabledSwordDarkTokens.vellum, + ash = FabledSwordDarkTokens.ash, + pewter = FabledSwordDarkTokens.pewter, + slate = FabledSwordDarkTokens.slate, + iron = FabledSwordDarkTokens.iron, + obsidian = FabledSwordDarkTokens.obsidian, + moss = FabledSwordFlatTokens.moss, + bronze = FabledSwordFlatTokens.bronze, + oxblood = FabledSwordFlatTokens.oxblood, + warning = FabledSwordFlatTokens.warning, + error = FabledSwordFlatTokens.error, + info = FabledSwordFlatTokens.info, + accent = FabledSwordFlatTokens.accent, + onAction = FabledSwordFlatTokens.onAction, + radiusSm = FabledSwordFlatTokens.radiusSm, + radiusMd = FabledSwordFlatTokens.radiusMd, + radiusLg = FabledSwordFlatTokens.radiusLg, + radiusXl = FabledSwordFlatTokens.radiusXl, + ) - val Light: FabledSwordTheme = FabledSwordTheme( - parchment = FabledSwordLightTokens.parchment, - vellum = FabledSwordLightTokens.vellum, - ash = FabledSwordLightTokens.ash, - pewter = FabledSwordLightTokens.pewter, - slate = FabledSwordLightTokens.slate, - iron = FabledSwordLightTokens.iron, - obsidian = FabledSwordLightTokens.obsidian, - moss = FabledSwordFlatTokens.moss, - bronze = FabledSwordFlatTokens.bronze, - oxblood = FabledSwordFlatTokens.oxblood, - warning = FabledSwordFlatTokens.warning, - error = FabledSwordFlatTokens.error, - info = FabledSwordFlatTokens.info, - accent = FabledSwordFlatTokens.accent, - onAction = FabledSwordFlatTokens.onAction, - radiusSm = FabledSwordFlatTokens.radiusSm, - radiusMd = FabledSwordFlatTokens.radiusMd, - radiusLg = FabledSwordFlatTokens.radiusLg, - radiusXl = FabledSwordFlatTokens.radiusXl, - ) + val Light: FabledSwordTheme = + FabledSwordTheme( + parchment = FabledSwordLightTokens.parchment, + vellum = FabledSwordLightTokens.vellum, + ash = FabledSwordLightTokens.ash, + pewter = FabledSwordLightTokens.pewter, + slate = FabledSwordLightTokens.slate, + iron = FabledSwordLightTokens.iron, + obsidian = FabledSwordLightTokens.obsidian, + moss = FabledSwordFlatTokens.moss, + bronze = FabledSwordFlatTokens.bronze, + oxblood = FabledSwordFlatTokens.oxblood, + warning = FabledSwordFlatTokens.warning, + error = FabledSwordFlatTokens.error, + info = FabledSwordFlatTokens.info, + accent = FabledSwordFlatTokens.accent, + onAction = FabledSwordFlatTokens.onAction, + radiusSm = FabledSwordFlatTokens.radiusSm, + radiusMd = FabledSwordFlatTokens.radiusMd, + radiusLg = FabledSwordFlatTokens.radiusLg, + radiusXl = FabledSwordFlatTokens.radiusXl, + ) } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/theme/MinstrelTheme.kt b/android/app/src/main/java/com/fabledsword/minstrel/theme/MinstrelTheme.kt index 69db9b51..84da389f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/theme/MinstrelTheme.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/theme/MinstrelTheme.kt @@ -86,12 +86,13 @@ fun MinstrelTheme( ) { CompositionLocalProvider( LocalFabledSwordTheme provides fabledTheme, - LocalActionColors provides ActionColors( - primary = FabledSwordFlatTokens.moss, - secondary = FabledSwordFlatTokens.bronze, - destructive = FabledSwordFlatTokens.oxblood, - onAction = FabledSwordFlatTokens.onAction, - ), + LocalActionColors provides + ActionColors( + primary = FabledSwordFlatTokens.moss, + secondary = FabledSwordFlatTokens.bronze, + destructive = FabledSwordFlatTokens.oxblood, + onAction = FabledSwordFlatTokens.onAction, + ), content = content, ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/theme/Section.kt b/android/app/src/main/java/com/fabledsword/minstrel/theme/Section.kt index d1245e21..84ce2778 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/theme/Section.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/theme/Section.kt @@ -38,8 +38,8 @@ import androidx.compose.ui.graphics.Color import androidx.compose.ui.graphics.vector.ImageVector import androidx.compose.ui.semantics.Role import androidx.compose.ui.unit.dp -import com.composables.icons.lucide.ChevronRight import com.composables.icons.lucide.ChevronDown +import com.composables.icons.lucide.ChevronRight import com.composables.icons.lucide.Lucide /** @@ -85,7 +85,11 @@ fun Section( /** The quiet line: a caption, a count, a consequence. */ @Composable -fun Muted(said: String, modifier: Modifier = Modifier, tone: Color = Color.Unspecified) { +fun Muted( + said: String, + modifier: Modifier = Modifier, + tone: Color = Color.Unspecified, +) { Text( said, style = MaterialTheme.typography.bodySmall, @@ -114,19 +118,21 @@ fun SettingRow( onClick: (() -> Unit)? = null, trailing: @Composable (RowScope.() -> Unit)? = null, ) { - val tappable = if (onClick != null) { - Modifier - .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusMd)) - .clickable(enabled = enabled, role = Role.Button, onClick = onClick) - } else { - Modifier - } + val tappable = + if (onClick != null) { + Modifier + .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusMd)) + .clickable(enabled = enabled, role = Role.Button, onClick = onClick) + } else { + Modifier + } Row( - modifier = modifier - .fillMaxWidth() - .heightIn(min = ROW_HEIGHT) - .then(tappable) - .alpha(if (enabled) 1f else DISABLED_ALPHA), + modifier = + modifier + .fillMaxWidth() + .heightIn(min = ROW_HEIGHT) + .then(tappable) + .alpha(if (enabled) 1f else DISABLED_ALPHA), verticalAlignment = Alignment.CenterVertically, ) { if (icon != null) { @@ -169,9 +175,10 @@ fun SwitchRow( title = title, summary = summary, enabled = enabled, - modifier = modifier - .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusMd)) - .toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onCheckedChange), + modifier = + modifier + .clip(RoundedCornerShape(FabledSwordFlatTokens.radiusMd)) + .toggleable(value = checked, enabled = enabled, role = Role.Switch, onValueChange = onCheckedChange), ) { Switch(checked = checked, onCheckedChange = null, enabled = enabled) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/theme/ThemeMode.kt b/android/app/src/main/java/com/fabledsword/minstrel/theme/ThemeMode.kt index b821e67b..b0a77bc0 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/theme/ThemeMode.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/theme/ThemeMode.kt @@ -9,7 +9,10 @@ package com.fabledsword.minstrel.theme * persistence value means "never set" which we treat as SYSTEM. */ enum class ThemeMode { - SYSTEM, LIGHT, DARK; + SYSTEM, + LIGHT, + DARK, + ; /** Stable string identifier used for persistence. */ val wire: String get() = name.lowercase() @@ -20,17 +23,19 @@ enum class ThemeMode { * - LIGHT → false * - DARK → true */ - fun toDarkOverride(): Boolean? = when (this) { - SYSTEM -> null - LIGHT -> false - DARK -> true - } + fun toDarkOverride(): Boolean? = + when (this) { + SYSTEM -> null + LIGHT -> false + DARK -> true + } companion object { - fun fromWire(wire: String?): ThemeMode = when (wire) { - "light" -> LIGHT - "dark" -> DARK - else -> SYSTEM - } + fun fromWire(wire: String?): ThemeMode = + when (wire) { + "light" -> LIGHT + "dark" -> DARK + else -> SYSTEM + } } } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/theme/ThemePreferenceViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/theme/ThemePreferenceViewModel.kt index 7234c90d..7f6eae93 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/theme/ThemePreferenceViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/theme/ThemePreferenceViewModel.kt @@ -23,23 +23,24 @@ private const val SHARE_STOP_TIMEOUT_MS = 5_000L * tightly coupled to the theme tokens; SettingsScreen just consumes it. */ @HiltViewModel -class ThemePreferenceViewModel @Inject constructor( - private val authStore: AuthStore, -) : ViewModel() { +class ThemePreferenceViewModel + @Inject + constructor( + private val authStore: AuthStore, + ) : ViewModel() { + val themeMode: StateFlow = + authStore.themeMode + .map { ThemeMode.fromWire(it) } + .stateIn( + scope = viewModelScope, + started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), + initialValue = ThemeMode.fromWire(authStore.themeMode.value), + ) - val themeMode: StateFlow = - authStore.themeMode - .map { ThemeMode.fromWire(it) } - .stateIn( - scope = viewModelScope, - started = SharingStarted.WhileSubscribed(SHARE_STOP_TIMEOUT_MS), - initialValue = ThemeMode.fromWire(authStore.themeMode.value), - ) - - fun setThemeMode(mode: ThemeMode) { - // Persist null for SYSTEM so a "never set" row reads identically - // to an explicit "follow system" pick — keeps the wire/storage - // round-trip clean. - authStore.setThemeMode(if (mode == ThemeMode.SYSTEM) null else mode.wire) + fun setThemeMode(mode: ThemeMode) { + // Persist null for SYSTEM so a "never set" row reads identically + // to an explicit "follow system" pick — keeps the wire/storage + // round-trip clean. + authStore.setThemeMode(if (mode == ThemeMode.SYSTEM) null else mode.wire) + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/theme/Typography.kt b/android/app/src/main/java/com/fabledsword/minstrel/theme/Typography.kt index 5f4c8905..442af856 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/theme/Typography.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/theme/Typography.kt @@ -28,19 +28,22 @@ import com.fabledsword.minstrel.R * weight declared beside it here must match the file's own OS/2 * usWeightClass, which the vendoring script asserts on download. */ -private val Fraunces = FontFamily( - Font(R.font.fraunces_regular, FontWeight.W400, FontStyle.Normal), - Font(R.font.fraunces_medium, FontWeight.W500, FontStyle.Normal), -) +private val Fraunces = + FontFamily( + Font(R.font.fraunces_regular, FontWeight.W400, FontStyle.Normal), + Font(R.font.fraunces_medium, FontWeight.W500, FontStyle.Normal), + ) -private val Inter = FontFamily( - Font(R.font.inter_regular, FontWeight.W400, FontStyle.Normal), - Font(R.font.inter_medium, FontWeight.W500, FontStyle.Normal), -) +private val Inter = + FontFamily( + Font(R.font.inter_regular, FontWeight.W400, FontStyle.Normal), + Font(R.font.inter_medium, FontWeight.W500, FontStyle.Normal), + ) -private val JetBrainsMono = FontFamily( - Font(R.font.jetbrains_mono_regular, FontWeight.W400, FontStyle.Normal), -) +private val JetBrainsMono = + FontFamily( + Font(R.font.jetbrains_mono_regular, FontWeight.W400, FontStyle.Normal), + ) /** * FabledSword Material 3 Typography mapping. Display/headline slots use @@ -49,20 +52,21 @@ private val JetBrainsMono = FontFamily( * defaults; the project's "Fraunces ≥18px" rule is satisfied because every * Fraunces-bearing slot is 18sp or larger. */ -val MinstrelTypography = Typography( - displayLarge = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 32.sp), - displayMedium = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 28.sp), - displaySmall = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 24.sp), - headlineLarge = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 22.sp), - headlineMedium = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 20.sp), - headlineSmall = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 18.sp), - titleLarge = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W500, fontSize = 18.sp), - titleMedium = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W500, fontSize = 16.sp), - titleSmall = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W500, fontSize = 14.sp), - bodyLarge = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W400, fontSize = 16.sp), - bodyMedium = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W400, fontSize = 14.sp), - bodySmall = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W400, fontSize = 12.sp), - labelLarge = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W500, fontSize = 14.sp), - labelMedium = TextStyle(fontFamily = JetBrainsMono, fontWeight = FontWeight.W400, fontSize = 12.sp), - labelSmall = TextStyle(fontFamily = JetBrainsMono, fontWeight = FontWeight.W400, fontSize = 11.sp), -) +val MinstrelTypography = + Typography( + displayLarge = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 32.sp), + displayMedium = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 28.sp), + displaySmall = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 24.sp), + headlineLarge = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 22.sp), + headlineMedium = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 20.sp), + headlineSmall = TextStyle(fontFamily = Fraunces, fontWeight = FontWeight.W500, fontSize = 18.sp), + titleLarge = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W500, fontSize = 18.sp), + titleMedium = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W500, fontSize = 16.sp), + titleSmall = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W500, fontSize = 14.sp), + bodyLarge = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W400, fontSize = 16.sp), + bodyMedium = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W400, fontSize = 14.sp), + bodySmall = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W400, fontSize = 12.sp), + labelLarge = TextStyle(fontFamily = Inter, fontWeight = FontWeight.W500, fontSize = 14.sp), + labelMedium = TextStyle(fontFamily = JetBrainsMono, fontWeight = FontWeight.W400, fontSize = 12.sp), + labelSmall = TextStyle(fontFamily = JetBrainsMono, fontWeight = FontWeight.W400, fontSize = 11.sp), + ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/ApkInstaller.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/ApkInstaller.kt index 405cbbe4..54d425bc 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/ApkInstaller.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/ApkInstaller.kt @@ -21,29 +21,32 @@ import javax.inject.Singleton * the session API — silent *updates* don't imply silent *permission*. */ @Singleton -class ApkInstaller @Inject constructor( - @ApplicationContext private val context: Context, - private val session: SelfUpdateSession, -) { - /** True when the system will accept an install intent without a permission detour. */ - fun canInstall(): Boolean = - Build.VERSION.SDK_INT < Build.VERSION_CODES.O || - context.packageManager.canRequestPackageInstalls() +class ApkInstaller + @Inject + constructor( + @ApplicationContext private val context: Context, + private val session: SelfUpdateSession, + ) { + /** True when the system will accept an install intent without a permission detour. */ + fun canInstall(): Boolean = + Build.VERSION.SDK_INT < Build.VERSION_CODES.O || + context.packageManager.canRequestPackageInstalls() - /** - * Install [apk] over ourselves, suspending until the platform decides. - * - * Note for callers: on a successful silent install this never returns — - * the process is replaced. Don't treat the absence of a verdict as failure. - */ - suspend fun install(apk: File): InstallOutcome = session.run(apk) + /** + * Install [apk] over ourselves, suspending until the platform decides. + * + * Note for callers: on a successful silent install this never returns — + * the process is replaced. Don't treat the absence of a verdict as failure. + */ + suspend fun install(apk: File): InstallOutcome = session.run(apk) - /** Open the "install unknown apps" settings page for Minstrel. */ - fun requestInstallPermission() { - val intent = Intent( - Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, - Uri.parse("package:${context.packageName}"), - ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) - context.startActivity(intent) + /** Open the "install unknown apps" settings page for Minstrel. */ + fun requestInstallPermission() { + val intent = + Intent( + Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, + Uri.parse("package:${context.packageName}"), + ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) + context.startActivity(intent) + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/AppUpdates.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/AppUpdates.kt index 1e09ab00..07092798 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/AppUpdates.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/AppUpdates.kt @@ -31,7 +31,10 @@ data class UpdateUiState( ) /** A newer build to tell the listener of, and whether it is already here to install. */ -data class UpdateNews(val offer: UpdateInfo, val ready: Boolean) +data class UpdateNews( + val offer: UpdateInfo, + val ready: Boolean, +) /** * The one record of whether a newer app is on offer and where installing it @@ -47,141 +50,146 @@ data class UpdateNews(val offer: UpdateInfo, val ready: Boolean) * ([UpdateTold]). */ @Singleton -class AppUpdates @Inject constructor( - @ApplicationScope private val scope: CoroutineScope, - private val updates: UpdateRepository, - private val installer: ApkInstaller, - private val told: UpdateTold, - private val fetching: UpdateScheduler, -) { - private val mutable = MutableStateFlow(UpdateUiState()) - val state: StateFlow = mutable.asStateFlow() +class AppUpdates + @Inject + constructor( + @ApplicationScope private val scope: CoroutineScope, + private val updates: UpdateRepository, + private val installer: ApkInstaller, + private val told: UpdateTold, + private val fetching: UpdateScheduler, + ) { + private val mutable = MutableStateFlow(UpdateUiState()) + val state: StateFlow = mutable.asStateFlow() - private val telling = Channel(Channel.BUFFERED) + private val telling = Channel(Channel.BUFFERED) - /** A newer build to tell of, once; a screen that shows it calls [tellHere] first. */ - val news: Flow = telling.receiveAsFlow() + /** A newer build to tell of, once; a screen that shows it calls [tellHere] first. */ + val news: Flow = telling.receiveAsFlow() - private var asking: Job? = null - private var tells = false + private var asking: Job? = null + private var tells = false - /** - * Asks the server which app it offers: when Home or Settings opens, on a - * pull, and every few minutes while one is up. A newer one being fetched - * or installed is never taken off the screen by a later answer. - */ - fun check(): Job { - asking?.takeIf { it.isActive }?.let { return it } - return scope.launch { refresh() }.also { asking = it } - } + /** + * Asks the server which app it offers: when Home or Settings opens, on a + * pull, and every few minutes while one is up. A newer one being fetched + * or installed is never taken off the screen by a later answer. + */ + fun check(): Job { + asking?.takeIf { it.isActive }?.let { return it } + return scope.launch { refresh() }.also { asking = it } + } - private suspend fun refresh() { - mutable.update { it.copy(checking = true) } - val offer = updates.check() - mutable.update { now -> - val busy = now.stage != InstallStage.IDLE + private suspend fun refresh() { + mutable.update { it.copy(checking = true) } + val offer = updates.check() + mutable.update { now -> + val busy = now.stage != InstallStage.IDLE + when (offer) { + is Offer.Newer -> now.copy(offer = if (busy) now.offer else offer.info, unchecked = null) + Offer.Current -> now.copy(offer = if (busy) now.offer else null, unchecked = null) + is Offer.Problem -> now.copy(unchecked = offer.message) + }.copy(checking = false) + } + fetchOrTidy(offer) + lookForReady() + tellIfDue() + } + + /** A newer build is fetched ahead; once none is offered, a package kept for one is only space. */ + private suspend fun fetchOrTidy(offer: Offer) { + if (mutable.value.stage != InstallStage.IDLE) return when (offer) { - is Offer.Newer -> now.copy(offer = if (busy) now.offer else offer.info, unchecked = null) - Offer.Current -> now.copy(offer = if (busy) now.offer else null, unchecked = null) - is Offer.Problem -> now.copy(unchecked = offer.message) - }.copy(checking = false) - } - fetchOrTidy(offer) - lookForReady() - tellIfDue() - } - - /** A newer build is fetched ahead; once none is offered, a package kept for one is only space. */ - private suspend fun fetchOrTidy(offer: Offer) { - if (mutable.value.stage != InstallStage.IDLE) return - when (offer) { - is Offer.Newer -> fetching.fetchAhead() - Offer.Current -> updates.tidy() - is Offer.Problem -> Unit - } - } - - /** Home is up: what is on offer now is told, if it is due. */ - fun tellHere() { - tells = true - tellIfDue() - } - - private fun tellIfDue() { - val now = mutable.value - val offer = now.offer - if (!tells || offer == null || now.stage != InstallStage.IDLE) return - val key = buildKey(offer.code, offer.version) - val at = System.currentTimeMillis() - if (dueToSay(key, told.build(), told.at(), at)) { - told.told(key, at) - telling.trySend(UpdateNews(offer, now.ready)) - } - } - - /** Whether the offer has been downloaded meanwhile, perhaps in the background. */ - fun lookForReady() { - mutable.update { it.copy(ready = it.offer?.let(updates::ready) != null) } - } - - fun mayInstall(): Boolean = installer.canInstall() - - /** Sends the listener to allow installs; the update carries on when they come back. */ - fun askToInstall() { - mutable.update { it.copy(problem = ALLOW) } - installer.requestInstallPermission() - } - - /** Came back from allowing installs without allowing them. */ - fun refused() { - mutable.update { it.copy(problem = REFUSED) } - } - - /** - * Downloads the offer (or takes the one already here) and installs it. - * Runs in the app's scope, so leaving the screen does not stop it. - */ - fun fetchAndInstall() { - val offer = mutable.value.offer ?: return - if (mutable.value.stage != InstallStage.IDLE) return - mutable.update { it.copy(stage = InstallStage.DOWNLOADING, progress = 0f, problem = null) } - scope.launch { - // Follows whichever download is running, not only one this call - // starts: when the Wi-Fi fetch is already bringing the build - // down, this waits behind it and its bar should move with it. - val following = launch { - updates.downloadProgress.collect { done -> mutable.update { it.copy(progress = done) } } + is Offer.Newer -> fetching.fetchAhead() + Offer.Current -> updates.tidy() + is Offer.Problem -> Unit } - val download = try { - updates.download(offer) {} - } finally { - following.cancel() + } + + /** Home is up: what is on offer now is told, if it is due. */ + fun tellHere() { + tells = true + tellIfDue() + } + + private fun tellIfDue() { + val now = mutable.value + val offer = now.offer + if (!tells || offer == null || now.stage != InstallStage.IDLE) return + val key = buildKey(offer.code, offer.version) + val at = System.currentTimeMillis() + if (dueToSay(key, told.build(), told.at(), at)) { + told.told(key, at) + telling.trySend(UpdateNews(offer, now.ready)) } - when (download) { - is Download.Problem -> mutable.update { - it.copy(stage = InstallStage.IDLE, problem = download.message) - } - is Download.Ready -> { - mutable.update { it.copy(ready = true) } - install(download.apk) + } + + /** Whether the offer has been downloaded meanwhile, perhaps in the background. */ + fun lookForReady() { + mutable.update { it.copy(ready = it.offer?.let(updates::ready) != null) } + } + + fun mayInstall(): Boolean = installer.canInstall() + + /** Sends the listener to allow installs; the update carries on when they come back. */ + fun askToInstall() { + mutable.update { it.copy(problem = ALLOW) } + installer.requestInstallPermission() + } + + /** Came back from allowing installs without allowing them. */ + fun refused() { + mutable.update { it.copy(problem = REFUSED) } + } + + /** + * Downloads the offer (or takes the one already here) and installs it. + * Runs in the app's scope, so leaving the screen does not stop it. + */ + fun fetchAndInstall() { + val offer = mutable.value.offer ?: return + if (mutable.value.stage != InstallStage.IDLE) return + mutable.update { it.copy(stage = InstallStage.DOWNLOADING, progress = 0f, problem = null) } + scope.launch { + // Follows whichever download is running, not only one this call + // starts: when the Wi-Fi fetch is already bringing the build + // down, this waits behind it and its bar should move with it. + val following = + launch { + updates.downloadProgress.collect { done -> mutable.update { it.copy(progress = done) } } + } + val download = + try { + updates.download(offer) {} + } finally { + following.cancel() + } + when (download) { + is Download.Problem -> + mutable.update { + it.copy(stage = InstallStage.IDLE, problem = download.message) + } + is Download.Ready -> { + mutable.update { it.copy(ready = true) } + install(download.apk) + } } } } - } - private suspend fun install(apk: File) { - mutable.update { it.copy(stage = InstallStage.INSTALLING) } - // On a successful silent install this never returns: the process is replaced. - val outcome = installer.install(apk) - mutable.update { it.copy(stage = InstallStage.IDLE, problem = outcome.message()) } - } + private suspend fun install(apk: File) { + mutable.update { it.copy(stage = InstallStage.INSTALLING) } + // On a successful silent install this never returns: the process is replaced. + val outcome = installer.install(apk) + mutable.update { it.copy(stage = InstallStage.IDLE, problem = outcome.message()) } + } - private companion object { - const val ALLOW = "Allow Minstrel to install apps. The update carries on when you come back." - const val REFUSED = - "Minstrel is still not allowed to install apps, so nothing was installed. Tap Update to try again." + private companion object { + const val ALLOW = "Allow Minstrel to install apps. The update carries on when you come back." + const val REFUSED = + "Minstrel is still not allowed to install apps, so nothing was installed. Tap Update to try again." + } } -} /** * What coming back to the app does to an update the listener asked for and @@ -198,7 +206,12 @@ internal enum class AfterAsking { WAIT, } -internal fun afterAsking(asked: Boolean, mayInstall: Boolean, offered: Boolean, busy: Boolean): AfterAsking = +internal fun afterAsking( + asked: Boolean, + mayInstall: Boolean, + offered: Boolean, + busy: Boolean, +): AfterAsking = when { !asked || busy || !offered -> AfterAsking.WAIT mayInstall -> AfterAsking.FETCH diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/InstallOutcome.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/InstallOutcome.kt index 12718958..2a147d95 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/InstallOutcome.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/InstallOutcome.kt @@ -22,7 +22,9 @@ sealed interface InstallOutcome { data object Cancelled : InstallOutcome /** The platform refused. [reason] is its own message, where it gave one. */ - data class Failed(val reason: String?) : InstallOutcome + data class Failed( + val reason: String?, + ) : InstallOutcome } /** @@ -43,9 +45,11 @@ enum class InstallStage { IDLE, DOWNLOADING, INSTALLING } * that puts [ErrorCopy][com.fabledsword.minstrel.api.ErrorCopy] outside the * UI layer. */ -fun InstallOutcome.message(): String? = when (this) { - InstallOutcome.Installed -> null - InstallOutcome.Cancelled -> "Update cancelled." - is InstallOutcome.Failed -> reason?.let { "Couldn't install update: $it" } - ?: "Couldn't install update." -} +fun InstallOutcome.message(): String? = + when (this) { + InstallOutcome.Installed -> null + InstallOutcome.Cancelled -> "Update cancelled." + is InstallOutcome.Failed -> + reason?.let { "Couldn't install update: $it" } + ?: "Couldn't install update." + } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/SelfUpdateSession.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/SelfUpdateSession.kt index 90442929..f0d50f41 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/SelfUpdateSession.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/SelfUpdateSession.kt @@ -63,158 +63,173 @@ private const val RESULT_ACTION = "com.fabledsword.minstrel.INSTALL_RESULT" * stores claiming the apps they install, not for an app updating itself. */ @Singleton -class SelfUpdateSession @Inject constructor( - @ApplicationContext private val context: Context, -) { - /** - * Stage [apk] and hand it to the platform, suspending until a terminal - * verdict arrives. - * - * Never returns on the happy path when the install is silent: the platform - * replaces this process the moment the new APK lands, so the coroutine dies - * rather than resuming. Callers must treat that as success, not a hang. - */ - suspend fun run(apk: File): InstallOutcome { - val staged = withContext(Dispatchers.IO) { runCatching { stage(apk) } } - return staged.fold( - onSuccess = { sessionId -> awaitCommit(sessionId) }, - onFailure = { InstallOutcome.Failed(it.message) }, - ) - } - - /** Open a session, stream the APK in, return the session id. */ - private fun stage(apk: File): Int { - val installer = context.packageManager.packageInstaller - val sessionId = installer.createSession(newParams()) - installer.openSession(sessionId).use { session -> - session.openWrite(STAGED_APK_NAME, WRITE_FROM_START, apk.length()).use { sink -> - apk.inputStream().use { source -> source.copyTo(sink) } - // fsync before the session closes: the platform validates the - // staged bytes at commit, and buffered tail bytes read as a - // truncated APK. - session.fsync(sink) - } +class SelfUpdateSession + @Inject + constructor( + @ApplicationContext private val context: Context, + ) { + /** + * Stage [apk] and hand it to the platform, suspending until a terminal + * verdict arrives. + * + * Never returns on the happy path when the install is silent: the platform + * replaces this process the moment the new APK lands, so the coroutine dies + * rather than resuming. Callers must treat that as success, not a hang. + */ + suspend fun run(apk: File): InstallOutcome { + val staged = withContext(Dispatchers.IO) { runCatching { stage(apk) } } + return staged.fold( + onSuccess = { sessionId -> awaitCommit(sessionId) }, + onFailure = { InstallOutcome.Failed(it.message) }, + ) } - return sessionId - } - // Explicit `params.` receivers rather than an apply {} block: lintVitalRelease - // runs on assembleRelease, and NewApi is easier for it to reason about when - // the guarded call has a named receiver instead of an implicit one. - private fun newParams(): PackageInstaller.SessionParams { - val params = PackageInstaller.SessionParams( - PackageInstaller.SessionParams.MODE_FULL_INSTALL, - ) - params.setAppPackageName(context.packageName) - params.setInstallReason(PackageManager.INSTALL_REASON_USER) - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - // The whole point of this class. Pre-S there is no such API, so the - // confirm dialog is unavoidable there — degrade, don't fail. - params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) - } - return params - } - - /** - * Commit the session and wait for the platform to report back. - * - * A pending-user-action status is *not* terminal — the platform is asking us - * to show its dialog, and the real verdict arrives in a second broadcast - * once the user decides. So the receiver stays registered across it. - */ - private suspend fun awaitCommit(sessionId: Int): InstallOutcome = - suspendCancellableCoroutine { continuation -> + /** Open a session, stream the APK in, return the session id. */ + private fun stage(apk: File): Int { val installer = context.packageManager.packageInstaller - val receiver = object : BroadcastReceiver() { - override fun onReceive(unused: Context, intent: Intent) { - val status = intent.getIntExtra( - PackageInstaller.EXTRA_STATUS, - PackageInstaller.STATUS_FAILURE, - ) - if (status == PackageInstaller.STATUS_PENDING_USER_ACTION) { - confirmWithUser(intent) - } else { - context.unregisterReceiver(this) - val why = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE) - if (continuation.isActive) continuation.resume(outcomeOf(status, why)) + val sessionId = installer.createSession(newParams()) + installer.openSession(sessionId).use { session -> + session.openWrite(STAGED_APK_NAME, WRITE_FROM_START, apk.length()).use { sink -> + apk.inputStream().use { source -> source.copyTo(sink) } + // fsync before the session closes: the platform validates the + // staged bytes at commit, and buffered tail bytes read as a + // truncated APK. + session.fsync(sink) + } + } + return sessionId + } + + // Explicit `params.` receivers rather than an apply {} block: lintVitalRelease + // runs on assembleRelease, and NewApi is easier for it to reason about when + // the guarded call has a named receiver instead of an implicit one. + private fun newParams(): PackageInstaller.SessionParams { + val params = + PackageInstaller.SessionParams( + PackageInstaller.SessionParams.MODE_FULL_INSTALL, + ) + params.setAppPackageName(context.packageName) + params.setInstallReason(PackageManager.INSTALL_REASON_USER) + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + // The whole point of this class. Pre-S there is no such API, so the + // confirm dialog is unavoidable there — degrade, don't fail. + params.setRequireUserAction(PackageInstaller.SessionParams.USER_ACTION_NOT_REQUIRED) + } + return params + } + + /** + * Commit the session and wait for the platform to report back. + * + * A pending-user-action status is *not* terminal — the platform is asking us + * to show its dialog, and the real verdict arrives in a second broadcast + * once the user decides. So the receiver stays registered across it. + */ + private suspend fun awaitCommit(sessionId: Int): InstallOutcome = + suspendCancellableCoroutine { continuation -> + val installer = context.packageManager.packageInstaller + val receiver = + object : BroadcastReceiver() { + override fun onReceive( + unused: Context, + intent: Intent, + ) { + val status = + intent.getIntExtra( + PackageInstaller.EXTRA_STATUS, + PackageInstaller.STATUS_FAILURE, + ) + if (status == PackageInstaller.STATUS_PENDING_USER_ACTION) { + confirmWithUser(intent) + } else { + context.unregisterReceiver(this) + val why = intent.getStringExtra(PackageInstaller.EXTRA_STATUS_MESSAGE) + if (continuation.isActive) continuation.resume(outcomeOf(status, why)) + } + } + } + ContextCompat.registerReceiver( + context, + receiver, + IntentFilter(RESULT_ACTION), + ContextCompat.RECEIVER_NOT_EXPORTED, + ) + continuation.invokeOnCancellation { + // Stop listening, but deliberately do NOT abandon the session. + // Cancellation here means our caller's scope died — the user + // navigated away, or the VM cleared — and by this point the + // session is already committed. The user asked for this install; + // killing it because nobody is watching the banner any more + // would be the wrong reading of their intent. + runCatching { context.unregisterReceiver(receiver) } + } + runCatching { + installer.openSession(sessionId).use { it.commit(resultSender(sessionId)) } + }.onFailure { error -> + // Resuming normally means invokeOnCancellation never fires, so + // clean up the staged session here or it sits until it expires. + runCatching { context.unregisterReceiver(receiver) } + runCatching { installer.abandonSession(sessionId) } + if (continuation.isActive) { + continuation.resume(InstallOutcome.Failed(error.message)) } } } - ContextCompat.registerReceiver( - context, - receiver, - IntentFilter(RESULT_ACTION), - ContextCompat.RECEIVER_NOT_EXPORTED, - ) - continuation.invokeOnCancellation { - // Stop listening, but deliberately do NOT abandon the session. - // Cancellation here means our caller's scope died — the user - // navigated away, or the VM cleared — and by this point the - // session is already committed. The user asked for this install; - // killing it because nobody is watching the banner any more - // would be the wrong reading of their intent. - runCatching { context.unregisterReceiver(receiver) } + + private fun resultSender(sessionId: Int): IntentSender { + // Scoped to our own package so the broadcast can't be answered elsewhere. + val intent = Intent(RESULT_ACTION).setPackage(context.packageName) + var flags = PendingIntent.FLAG_UPDATE_CURRENT + if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { + // The platform writes its status extras into this intent, so it has + // to stay mutable — FLAG_IMMUTABLE would arrive with none of them. + flags = flags or PendingIntent.FLAG_MUTABLE } - runCatching { - installer.openSession(sessionId).use { it.commit(resultSender(sessionId)) } - }.onFailure { error -> - // Resuming normally means invokeOnCancellation never fires, so - // clean up the staged session here or it sits until it expires. - runCatching { context.unregisterReceiver(receiver) } - runCatching { installer.abandonSession(sessionId) } - if (continuation.isActive) { - continuation.resume(InstallOutcome.Failed(error.message)) - } + // Session id as the request code keeps concurrent sessions from + // colliding on FLAG_UPDATE_CURRENT. + return PendingIntent.getBroadcast(context, sessionId, intent, flags).intentSender + } + + /** + * Show the platform's own confirm dialog, which arrives as an extra. + * + * The system-app check is not ceremony. Below API 34 a dynamically + * registered receiver cannot declare itself unexported, so another app on + * the device can broadcast [RESULT_ACTION] at us — and calling + * `startActivity` on an attacker-supplied extra would hand it whatever we + * can reach. The genuine confirm activity belongs to the platform + * installer, so demanding a system component costs the real path nothing. + */ + private fun confirmWithUser(result: Intent) { + val pending = + IntentCompat.getParcelableExtra( + result, + Intent.EXTRA_INTENT, + Intent::class.java, + ) ?: return + if (isPlatformActivity(pending)) { + context.startActivity(pending.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) } } - private fun resultSender(sessionId: Int): IntentSender { - // Scoped to our own package so the broadcast can't be answered elsewhere. - val intent = Intent(RESULT_ACTION).setPackage(context.packageName) - var flags = PendingIntent.FLAG_UPDATE_CURRENT - if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) { - // The platform writes its status extras into this intent, so it has - // to stay mutable — FLAG_IMMUTABLE would arrive with none of them. - flags = flags or PendingIntent.FLAG_MUTABLE + private fun isPlatformActivity(intent: Intent): Boolean { + val flags = + intent + .resolveActivityInfo(context.packageManager, 0) + ?.applicationInfo + ?.flags + ?: 0 + val systemFlags = ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP + return (flags and systemFlags) != 0 } - // Session id as the request code keeps concurrent sessions from - // colliding on FLAG_UPDATE_CURRENT. - return PendingIntent.getBroadcast(context, sessionId, intent, flags).intentSender - } - /** - * Show the platform's own confirm dialog, which arrives as an extra. - * - * The system-app check is not ceremony. Below API 34 a dynamically - * registered receiver cannot declare itself unexported, so another app on - * the device can broadcast [RESULT_ACTION] at us — and calling - * `startActivity` on an attacker-supplied extra would hand it whatever we - * can reach. The genuine confirm activity belongs to the platform - * installer, so demanding a system component costs the real path nothing. - */ - private fun confirmWithUser(result: Intent) { - val pending = IntentCompat.getParcelableExtra( - result, - Intent.EXTRA_INTENT, - Intent::class.java, - ) ?: return - if (isPlatformActivity(pending)) { - context.startActivity(pending.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)) - } + private fun outcomeOf( + status: Int, + message: String?, + ): InstallOutcome = + when (status) { + PackageInstaller.STATUS_SUCCESS -> InstallOutcome.Installed + PackageInstaller.STATUS_FAILURE_ABORTED -> InstallOutcome.Cancelled + else -> InstallOutcome.Failed(message) + } } - - private fun isPlatformActivity(intent: Intent): Boolean { - val flags = intent.resolveActivityInfo(context.packageManager, 0) - ?.applicationInfo - ?.flags - ?: 0 - val systemFlags = ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP - return (flags and systemFlags) != 0 - } - - private fun outcomeOf(status: Int, message: String?): InstallOutcome = when (status) { - PackageInstaller.STATUS_SUCCESS -> InstallOutcome.Installed - PackageInstaller.STATUS_FAILURE_ABORTED -> InstallOutcome.Cancelled - else -> InstallOutcome.Failed(message) - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateFetchWorker.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateFetchWorker.kt index c43d90c5..a55e4274 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateFetchWorker.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateFetchWorker.kt @@ -25,31 +25,35 @@ import javax.inject.Singleton * server may offer another build. */ @HiltWorker -class UpdateFetchWorker @AssistedInject constructor( - @Assisted context: Context, - @Assisted params: WorkerParameters, - private val updates: UpdateRepository, -) : CoroutineWorker(context, params) { - override suspend fun doWork(): Result = when (val offer = updates.check()) { - // A server out of reach is a phone away from home; the next check asks for this again. - is Offer.Problem -> Result.success() - Offer.Current -> { - updates.tidy() - Result.success() - } - is Offer.Newer -> when (updates.download(offer.info) {}) { - is Download.Ready -> Result.success() - // A dropped connection is worth another go after WorkManager's - // backoff, which also outlasts the server's one-download-a-minute - // limit; a few, not forever. - is Download.Problem -> if (runAttemptCount < TRIES) Result.retry() else Result.success() - } - } +class UpdateFetchWorker + @AssistedInject + constructor( + @Assisted context: Context, + @Assisted params: WorkerParameters, + private val updates: UpdateRepository, + ) : CoroutineWorker(context, params) { + override suspend fun doWork(): Result = + when (val offer = updates.check()) { + // A server out of reach is a phone away from home; the next check asks for this again. + is Offer.Problem -> Result.success() + Offer.Current -> { + updates.tidy() + Result.success() + } + is Offer.Newer -> + when (updates.download(offer.info) {}) { + is Download.Ready -> Result.success() + // A dropped connection is worth another go after WorkManager's + // backoff, which also outlasts the server's one-download-a-minute + // limit; a few, not forever. + is Download.Problem -> if (runAttemptCount < TRIES) Result.retry() else Result.success() + } + } - private companion object { - const val TRIES = 3 + private companion object { + const val TRIES = 3 + } } -} /** * Asks the platform to fetch the newer app when it is free to: on an @@ -61,24 +65,28 @@ class UpdateFetchWorker @AssistedInject constructor( * download already under way. */ @Singleton -class UpdateScheduler @Inject constructor(@ApplicationContext private val context: Context) { - fun fetchAhead() { - WorkManager.getInstance(context).enqueueUniqueWork( - FETCHING, - ExistingWorkPolicy.KEEP, - OneTimeWorkRequestBuilder() - .setConstraints( - Constraints.Builder() - .setRequiredNetworkType(NetworkType.UNMETERED) - .setRequiresBatteryNotLow(true) - .setRequiresStorageNotLow(true) - .build(), - ) - .build(), - ) - } +class UpdateScheduler + @Inject + constructor( + @ApplicationContext private val context: Context, + ) { + fun fetchAhead() { + WorkManager.getInstance(context).enqueueUniqueWork( + FETCHING, + ExistingWorkPolicy.KEEP, + OneTimeWorkRequestBuilder() + .setConstraints( + Constraints + .Builder() + .setRequiredNetworkType(NetworkType.UNMETERED) + .setRequiresBatteryNotLow(true) + .setRequiresStorageNotLow(true) + .build(), + ).build(), + ) + } - private companion object { - const val FETCHING = "update-fetch" + private companion object { + const val FETCHING = "update-fetch" + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateModule.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateModule.kt index cb2455a8..efe4b217 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateModule.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateModule.kt @@ -33,23 +33,25 @@ object UpdateModule { @ApplicationContext context: Context, retrofit: Retrofit, okHttpClient: OkHttpClient, - ): UpdateRepository = UpdateRepository( - api = retrofit.create(ClientVersionApi::class.java), - apk = ApkSource { apkUrl -> - withContext(Dispatchers.IO) { - val request = Request.Builder().url("http://placeholder.invalid$apkUrl").build() - val response = okHttpClient.newCall(request).execute() - if (!response.isSuccessful) { - response.close() - throw IOException("Download failed: HTTP ${response.code}") - } - response.body ?: throw IOException("Empty download body") - } - }, - dir = File(context.cacheDir, "update"), - installedCode = BuildConfig.VERSION_CODE.toLong(), - installedName = BuildConfig.VERSION_NAME, - offers = !BuildConfig.DEBUG, - legacyApk = File(context.cacheDir, "minstrel-update.apk"), - ) + ): UpdateRepository = + UpdateRepository( + api = retrofit.create(ClientVersionApi::class.java), + apk = + ApkSource { apkUrl -> + withContext(Dispatchers.IO) { + val request = Request.Builder().url("http://placeholder.invalid$apkUrl").build() + val response = okHttpClient.newCall(request).execute() + if (!response.isSuccessful) { + response.close() + throw IOException("Download failed: HTTP ${response.code}") + } + response.body ?: throw IOException("Empty download body") + } + }, + dir = File(context.cacheDir, "update"), + installedCode = BuildConfig.VERSION_CODE.toLong(), + installedName = BuildConfig.VERSION_NAME, + offers = !BuildConfig.DEBUG, + legacyApk = File(context.cacheDir, "minstrel-update.apk"), + ) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateRepository.kt index 175e5fba..51f2f335 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateRepository.kt @@ -25,19 +25,28 @@ import kotlin.coroutines.cancellation.CancellationException /** What asking the server for its app came to. */ sealed interface Offer { /** The server's app is another build than this one, and installs over it. */ - data class Newer(val info: UpdateInfo) : Offer + data class Newer( + val info: UpdateInfo, + ) : Offer /** This is the server's app, or the same app built again, or the server has none to offer. */ data object Current : Offer /** The server could not be asked. [message] says why, for the About card. */ - data class Problem(val message: String) : Offer + data class Problem( + val message: String, + ) : Offer } /** What a download came to. */ sealed interface Download { - data class Ready(val apk: File) : Download - data class Problem(val message: String) : Download + data class Ready( + val apk: File, + ) : Download + + data class Problem( + val message: String, + ) : Download } /** Opens the server's APK for reading. The caller closes the body. */ @@ -102,16 +111,17 @@ class UpdateRepository( } /** The package for [info], when it is already here and whole. */ - fun ready(info: UpdateInfo): File? = - waiting(info).takeIf { it.isFile && it.length() == info.sizeBytes } + fun ready(info: UpdateInfo): File? = waiting(info).takeIf { it.isFile && it.length() == info.sizeBytes } /** * The server's app, checked against the size and digest the server gave, * so what is handed to the installer is the build that was offered, all * of it. [progress] is called with 0 to 1 as it arrives. */ - suspend fun download(info: UpdateInfo, progress: (Float) -> Unit): Download = - turns.withLock { ready(info)?.let { Download.Ready(it) } ?: fetch(info, progress) } + suspend fun download( + info: UpdateInfo, + progress: (Float) -> Unit, + ): Download = turns.withLock { ready(info)?.let { Download.Ready(it) } ?: fetch(info, progress) } /** Drops every package kept here: none is on offer any more. */ suspend fun tidy() { @@ -128,17 +138,21 @@ class UpdateRepository( * checks out, so a download cut off partway is never taken for one that * finished. Any package for another build goes then. */ - private suspend fun fetch(info: UpdateInfo, progress: (Float) -> Unit): Download { + private suspend fun fetch( + info: UpdateInfo, + progress: (Float) -> Unit, + ): Download { val target = waiting(info) val part = File(dir, target.name + PART) fetched.value = 0f return try { - val digest = withContext(Dispatchers.IO) { - save(apk.open(info.apkUrl), part, info.sizeBytes) { done -> - fetched.value = done - progress(done) + val digest = + withContext(Dispatchers.IO) { + save(apk.open(info.apkUrl), part, info.sizeBytes) { done -> + fetched.value = done + progress(done) + } } - } withContext(Dispatchers.IO) { settle(info, part, target, digest) } } catch (e: CancellationException) { part.delete() @@ -151,10 +165,16 @@ class UpdateRepository( } } - private fun settle(info: UpdateInfo, part: File, target: File, digest: String): Download { + private fun settle( + info: UpdateInfo, + part: File, + target: File, + digest: String, + ): Download { // A server that predates the digest leaves the size as the only check. - val whole = part.length() == info.sizeBytes && - (info.sha256.isEmpty() || digest.equals(info.sha256, ignoreCase = true)) + val whole = + part.length() == info.sizeBytes && + (info.sha256.isEmpty() || digest.equals(info.sha256, ignoreCase = true)) return if (whole && part.renameTo(target)) { dir.listFiles()?.filter { it != target }?.forEach { it.delete() } Download.Ready(target) @@ -165,8 +185,7 @@ class UpdateRepository( } /** Where the package for [info] waits: named for its build. */ - private fun waiting(info: UpdateInfo): File = - File(dir, "minstrel-${info.code ?: info.version.replace(UNSAFE, "_")}.apk") + private fun waiting(info: UpdateInfo): File = File(dir, "minstrel-${info.code ?: info.version.replace(UNSAFE, "_")}.apk") private companion object { const val PART = ".part" @@ -174,17 +193,23 @@ class UpdateRepository( } } -private fun UpdateInfoWire.toDomain(): UpdateInfo = UpdateInfo( - version = version, - code = code, - channel = channel, - apkUrl = apkUrl, - sizeBytes = sizeBytes, - sha256 = sha256, -) +private fun UpdateInfoWire.toDomain(): UpdateInfo = + UpdateInfo( + version = version, + code = code, + channel = channel, + apkUrl = apkUrl, + sizeBytes = sizeBytes, + sha256 = sha256, + ) /** Writes [body] to [file], reporting progress against [size], and returns the SHA-256 written, in hex. */ -internal fun save(body: ResponseBody, file: File, size: Long, progress: (Float) -> Unit): String { +internal fun save( + body: ResponseBody, + file: File, + size: Long, + progress: (Float) -> Unit, +): String { file.parentFile?.mkdirs() val digest = MessageDigest.getInstance("SHA-256") // Closing the stream closes the body. @@ -194,7 +219,12 @@ internal fun save(body: ResponseBody, file: File, size: Long, progress: (Float) return digest.digest().joinToString("") { "%02x".format(it) } } -private fun copy(input: InputStream, output: OutputStream, digest: MessageDigest, written: (Long) -> Unit) { +private fun copy( + input: InputStream, + output: OutputStream, + digest: MessageDigest, + written: (Long) -> Unit, +) { val buffer = ByteArray(BUFFER_BYTES) var total = 0L var read = input.read(buffer) @@ -207,7 +237,11 @@ private fun copy(input: InputStream, output: OutputStream, digest: MessageDigest } } -private fun report(written: Long, size: Long, progress: (Float) -> Unit) { +private fun report( + written: Long, + size: Long, + progress: (Float) -> Unit, +) { if (size > 0) progress((written.toFloat() / size).coerceAtMost(1f)) } @@ -256,7 +290,10 @@ fun isUpdateAvailable( * non-zero component (branch-name builds like "main" vs "dev") so * a dev build still gets the banner. */ -fun isVersionNewer(server: String, installed: String): Boolean { +fun isVersionNewer( + server: String, + installed: String, +): Boolean { val svr = parseVersion(server) val ins = parseVersion(installed) if (svr.all { it == 0 } && ins.all { it == 0 }) { @@ -268,11 +305,14 @@ fun isVersionNewer(server: String, installed: String): Boolean { return compareComponentWise(svrPadded, insPadded) } -private fun parseVersion(v: String): List = - v.removePrefix("v").split('.').map { it.toIntOrNull() ?: 0 } +private fun parseVersion(v: String): List = v.removePrefix("v").split('.').map { it.toIntOrNull() ?: 0 } -private fun compareComponentWise(svr: List, ins: List): Boolean = - svr.zip(ins) +private fun compareComponentWise( + svr: List, + ins: List, +): Boolean = + svr + .zip(ins) .firstOrNull { (a, b) -> a != b } ?.let { (a, b) -> a > b } ?: false diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateTold.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateTold.kt index a03990b7..1a01f70c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateTold.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/data/UpdateTold.kt @@ -10,42 +10,64 @@ import javax.inject.Singleton * Android reopened does not say the same news again. */ @Singleton -class UpdateTold @Inject constructor(@ApplicationContext context: Context) { - private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) +class UpdateTold + @Inject + constructor( + @ApplicationContext context: Context, + ) { + private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE) - fun build(): String = prefs.getString(BUILD, "").orEmpty() + fun build(): String = prefs.getString(BUILD, "").orEmpty() - fun at(): Long = prefs.getLong(AT, 0L) + fun at(): Long = prefs.getLong(AT, 0L) - fun told(build: String, at: Long) { - prefs.edit().putString(BUILD, build).putLong(AT, at).apply() + fun told( + build: String, + at: Long, + ) { + prefs + .edit() + .putString(BUILD, build) + .putLong(AT, at) + .apply() + } + + private companion object { + const val PREFS_NAME = "update_told" + const val BUILD = "build" + const val AT = "at" + } } - private companion object { - const val PREFS_NAME = "update_told" - const val BUILD = "build" - const val AT = "at" - } -} - /** * The key a build is told under: its code, or its name from a server that * sends no code. */ -internal fun buildKey(code: Long?, version: String): String = code?.toString() ?: version +internal fun buildKey( + code: Long?, + version: String, +): String = code?.toString() ?: version /** * Whether a build on offer is said again: a build not yet told of is news at * once; the same one again a day later, until it is installed. A clock that * went backwards says it rather than hiding an update for a day. */ -internal fun dueToSay(build: String, toldBuild: String, toldAt: Long, now: Long): Boolean { +internal fun dueToSay( + build: String, + toldBuild: String, + toldAt: Long, + now: Long, +): Boolean { val since = now - toldAt return build != toldBuild || since < 0 || since >= SAY_AGAIN_AFTER_MS } /** What Home's snackbar says of an offer; its button opens the sheet. */ -internal fun toldWords(version: String, ready: Boolean): String = +internal fun toldWords( + version: String, + ready: Boolean, +): String = if (ready) { "Version $version of the app is downloaded and ready." } else { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/AppVersionCard.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/AppVersionCard.kt index 5f1e28b6..85cca008 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/AppVersionCard.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/AppVersionCard.kt @@ -29,7 +29,10 @@ import com.fabledsword.minstrel.update.data.UpdateUiState * listener asked for carries on. */ @Composable -fun AppVersionCard(model: UpdateViewModel, modifier: Modifier = Modifier) { +fun AppVersionCard( + model: UpdateViewModel, + modifier: Modifier = Modifier, +) { LifecycleResumeEffect(model) { model.resumed() onPauseOrDispose {} @@ -57,7 +60,11 @@ fun AppVersionCard(model: UpdateViewModel, modifier: Modifier = Modifier) { /** The newer build, and the one button that fetches and installs it. */ @Composable -private fun Offered(offer: UpdateInfo, state: UpdateUiState, update: () -> Unit) { +private fun Offered( + offer: UpdateInfo, + state: UpdateUiState, + update: () -> Unit, +) { SettingRow( title = if (state.ready) "Ready to install" else "New version on your server", summary = describe(offer), @@ -74,13 +81,17 @@ private fun Offered(offer: UpdateInfo, state: UpdateUiState, update: () -> Unit) } /** Whether this app is the newest, as far as the server has said. */ -internal fun versionWords(state: UpdateUiState, selfUpdates: Boolean = true): String = when { - // Its own package and the debug key: the server's app would install beside it, never over it. - !selfUpdates -> "Debug build: updates install from Android Studio." - state.checking -> "Checking for a newer version…" - state.unchecked != null -> "Couldn't check for a newer version: ${state.unchecked}" - else -> "This is the newest version." -} +internal fun versionWords( + state: UpdateUiState, + selfUpdates: Boolean = true, +): String = + when { + // Its own package and the debug key: the server's app would install beside it, never over it. + !selfUpdates -> "Debug build: updates install from Android Studio." + state.checking -> "Checking for a newer version…" + state.unchecked != null -> "Couldn't check for a newer version: ${state.unchecked}" + else -> "This is the newest version." + } /** The name, the channel when it is the test line, and the size. */ internal fun describe(offer: UpdateInfo): String { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/UpdateNotices.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/UpdateNotices.kt index 7d5867c9..b5482664 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/UpdateNotices.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/UpdateNotices.kt @@ -1,7 +1,6 @@ package com.fabledsword.minstrel.update.ui import androidx.compose.foundation.layout.BoxScope -import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.navigationBarsPadding import androidx.compose.foundation.layout.padding import androidx.compose.material3.ExperimentalMaterial3Api @@ -45,12 +44,13 @@ fun BoxScope.UpdateNotices(model: UpdateViewModel) { LaunchedEffect(model) { model.tellHere() model.news.collect { news -> - val tapped = notices.showSnackbar( - message = toldWords(news.offer.version, news.ready), - actionLabel = toldAction(news.ready), - withDismissAction = true, - duration = SnackbarDuration.Long, - ) + val tapped = + notices.showSnackbar( + message = toldWords(news.offer.version, news.ready), + actionLabel = toldAction(news.ready), + withDismissAction = true, + duration = SnackbarDuration.Long, + ) if (tapped == SnackbarResult.ActionPerformed) updating = true } } @@ -60,7 +60,10 @@ fun BoxScope.UpdateNotices(model: UpdateViewModel) { @OptIn(ExperimentalMaterial3Api::class) @Composable -private fun UpdateSheet(model: UpdateViewModel, dismiss: () -> Unit) { +private fun UpdateSheet( + model: UpdateViewModel, + dismiss: () -> Unit, +) { ModalBottomSheet(onDismissRequest = dismiss) { AppVersionCard( model, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/UpdateViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/UpdateViewModel.kt index 5fceef0a..ade405f5 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/UpdateViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/UpdateViewModel.kt @@ -23,64 +23,67 @@ import javax.inject.Inject * when they come back ([resumed]) instead of asking them to tap again. */ @HiltViewModel -class UpdateViewModel @Inject constructor( - private val updates: AppUpdates, - private val saved: SavedStateHandle, -) : ViewModel() { - val state: StateFlow = updates.state - val news: Flow = updates.news +class UpdateViewModel + @Inject + constructor( + private val updates: AppUpdates, + private val saved: SavedStateHandle, + ) : ViewModel() { + val state: StateFlow = updates.state + val news: Flow = updates.news - /** Asks the server again; once the answer is in, an update asked for before a restart carries on. */ - fun check() { - viewModelScope.launch { - updates.check().join() + /** Asks the server again; once the answer is in, an update asked for before a restart carries on. */ + fun check() { + viewModelScope.launch { + updates.check().join() + carryOn() + } + } + + fun tellHere() = updates.tellHere() + + /** The app is in front again, perhaps back from allowing installs. */ + fun resumed() { + updates.lookForReady() carryOn() } - } - fun tellHere() = updates.tellHere() - - /** The app is in front again, perhaps back from allowing installs. */ - fun resumed() { - updates.lookForReady() - carryOn() - } - - fun update() { - val now = state.value - when { - now.offer == null || now.stage != InstallStage.IDLE -> Unit - !updates.mayInstall() -> { - saved[ASKED] = true - updates.askToInstall() - } - else -> updates.fetchAndInstall() - } - } - - private fun carryOn() { - val now = state.value - val next = afterAsking( - asked = saved.get(ASKED) == true, - mayInstall = updates.mayInstall(), - offered = now.offer != null, - busy = now.stage != InstallStage.IDLE, - ) - when (next) { - AfterAsking.WAIT -> Unit - AfterAsking.REFUSED -> { - saved[ASKED] = false - updates.refused() - } - AfterAsking.FETCH -> { - saved[ASKED] = false - updates.fetchAndInstall() + fun update() { + val now = state.value + when { + now.offer == null || now.stage != InstallStage.IDLE -> Unit + !updates.mayInstall() -> { + saved[ASKED] = true + updates.askToInstall() + } + else -> updates.fetchAndInstall() } } - } - private companion object { - /** The listener asked for the update and was sent to allow installs. */ - const val ASKED = "update.asked_to_allow" + private fun carryOn() { + val now = state.value + val next = + afterAsking( + asked = saved.get(ASKED) == true, + mayInstall = updates.mayInstall(), + offered = now.offer != null, + busy = now.stage != InstallStage.IDLE, + ) + when (next) { + AfterAsking.WAIT -> Unit + AfterAsking.REFUSED -> { + saved[ASKED] = false + updates.refused() + } + AfterAsking.FETCH -> { + saved[ASKED] = false + updates.fetchAndInstall() + } + } + } + + private companion object { + /** The listener asked for the update and was sent to allow installs. */ + const val ASKED = "update.asked_to_allow" + } } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/VersionTooOldBanner.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/VersionTooOldBanner.kt index ab1814f7..c9d37a1c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/VersionTooOldBanner.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/VersionTooOldBanner.kt @@ -40,10 +40,11 @@ fun VersionTooOldBanner(viewModel: VersionTooOldViewModel = hiltViewModel()) { exit = shrinkVertically() + fadeOut(), ) { Row( - modifier = Modifier - .fillMaxWidth() - .background(MaterialTheme.colorScheme.errorContainer) - .padding(horizontal = 16.dp, vertical = 10.dp), + modifier = + Modifier + .fillMaxWidth() + .background(MaterialTheme.colorScheme.errorContainer) + .padding(horizontal = 16.dp, vertical = 10.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp), ) { @@ -53,8 +54,9 @@ fun VersionTooOldBanner(viewModel: VersionTooOldViewModel = hiltViewModel()) { tint = MaterialTheme.colorScheme.onErrorContainer, ) Text( - text = "This app is older than the server requires. " + - "Cached content still works; install an update when ready.", + text = + "This app is older than the server requires. " + + "Cached content still works; install an update when ready.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onErrorContainer, modifier = Modifier.weight(1f), diff --git a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/VersionTooOldViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/VersionTooOldViewModel.kt index 52874561..5adba185 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/update/ui/VersionTooOldViewModel.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/update/ui/VersionTooOldViewModel.kt @@ -13,10 +13,13 @@ import javax.inject.Inject * [VersionResult] plus its recheck trigger for the banner button. */ @HiltViewModel -class VersionTooOldViewModel @Inject constructor( - private val controller: NetworkStatusController, - @Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle, -) : ViewModel() { - val result: StateFlow = controller.versionResult - fun recheck() = controller.recheck() -} +class VersionTooOldViewModel + @Inject + constructor( + private val controller: NetworkStatusController, + @Suppress("UnusedPrivateProperty") savedStateHandle: SavedStateHandle, + ) : ViewModel() { + val result: StateFlow = controller.versionResult + + fun recheck() = controller.recheck() + } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModelTest.kt index ee9da1f0..e06a3ee8 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModelTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/admin/ui/AdminQuarantineViewModelTest.kt @@ -21,23 +21,27 @@ import kotlin.test.assertEquals /** Reports' two removals each reach their own endpoint, and either takes the row off the queue. */ @ExtendWith(MainDispatcherExtension::class) class AdminQuarantineViewModelTest { - private val row = AdminQuarantineItemRef( - trackId = "t1", - trackTitle = "Prismatic", - artistName = "Fields of Ontario", - albumTitle = "Geomantic", - albumId = "al1", - reportCount = 1, - ) - private val repository: AdminQuarantineRepository = mockk(relaxed = true) { - coEvery { list() } returns listOf(row) - } - private val eventsStream: EventsStream = mockk { - every { events } returns MutableSharedFlow() - } - private val network: NetworkStatusController = mockk { - every { state } returns MutableStateFlow(ServerHealth.Healthy) - } + private val row = + AdminQuarantineItemRef( + trackId = "t1", + trackTitle = "Prismatic", + artistName = "Fields of Ontario", + albumTitle = "Geomantic", + albumId = "al1", + reportCount = 1, + ) + private val repository: AdminQuarantineRepository = + mockk(relaxed = true) { + coEvery { list() } returns listOf(row) + } + private val eventsStream: EventsStream = + mockk { + every { events } returns MutableSharedFlow() + } + private val network: NetworkStatusController = + mockk { + every { state } returns MutableStateFlow(ServerHealth.Healthy) + } // Lazy: built inside each test, after the extension has swapped in the test Main dispatcher. private val viewModel by lazy { AdminQuarantineViewModel(repository, eventsStream, network) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/api/AuthCookieInterceptorTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/api/AuthCookieInterceptorTest.kt index 7f1455e8..cde7c5e6 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/api/AuthCookieInterceptorTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/api/AuthCookieInterceptorTest.kt @@ -66,14 +66,14 @@ class AuthCookieInterceptorTest { // before transport. authStore.setBaseUrl(server.url("/").toString()) client = - OkHttpClient.Builder() + OkHttpClient + .Builder() .addInterceptor(AuthCookieInterceptor(authStore)) .addInterceptor(BaseUrlInterceptor(authStore)) .build() } - private fun placeholderUrl(path: String): String = - "http://${BaseUrlInterceptor.PLACEHOLDER_HOST}$path" + private fun placeholderUrl(path: String): String = "http://${BaseUrlInterceptor.PLACEHOLDER_HOST}$path" @AfterEach fun teardown() { @@ -170,7 +170,8 @@ class AuthCookieInterceptorTest { } val loading = AuthStore(dao, slowVault, CoroutineScope(SupervisorJob() + Dispatchers.Default)) val launchClient = - OkHttpClient.Builder() + OkHttpClient + .Builder() .addInterceptor(AuthCookieInterceptor(loading)) .addInterceptor(BaseUrlInterceptor(loading)) .build() diff --git a/android/app/src/test/java/com/fabledsword/minstrel/api/BaseUrlInterceptorTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/api/BaseUrlInterceptorTest.kt index c341da5b..3ec416a9 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/api/BaseUrlInterceptorTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/api/BaseUrlInterceptorTest.kt @@ -55,9 +55,10 @@ class BaseUrlInterceptorTest { server.enqueue(MockResponse().setResponseCode(200)) val client = OkHttpClient.Builder().addInterceptor(BaseUrlInterceptor(authStore)).build() - client.newCall( - Request.Builder().url("http://placeholder.invalid/api/test").build(), - ).execute() + client + .newCall( + Request.Builder().url("http://placeholder.invalid/api/test").build(), + ).execute() val recorded = server.takeRequest() assertEquals("/api/test", recorded.path) @@ -74,25 +75,28 @@ class BaseUrlInterceptorTest { authStore.setBaseUrl(server.url("/").toString()) var seen: HttpUrl? = null val client = - OkHttpClient.Builder() + OkHttpClient + .Builder() .addInterceptor(BaseUrlInterceptor(authStore)) .addInterceptor { chain -> seen = chain.request().url - Response.Builder() + Response + .Builder() .request(chain.request()) .protocol(Protocol.HTTP_1_1) .code(200) .message("OK") .body("".toResponseBody()) .build() - } - .build() + }.build() - client.newCall( - Request.Builder() - .url("https://artwork.musicbrainz.org/release-group/abc/front-250.jpg") - .build(), - ).execute() + client + .newCall( + Request + .Builder() + .url("https://artwork.musicbrainz.org/release-group/abc/front-250.jpg") + .build(), + ).execute() assertEquals("artwork.musicbrainz.org", seen?.host) assertEquals("https", seen?.scheme) @@ -107,23 +111,25 @@ class BaseUrlInterceptorTest { authStore.setBaseUrl("not a url") var seen: HttpUrl? = null val client = - OkHttpClient.Builder() + OkHttpClient + .Builder() .addInterceptor(BaseUrlInterceptor(authStore)) .addInterceptor { chain -> seen = chain.request().url - Response.Builder() + Response + .Builder() .request(chain.request()) .protocol(Protocol.HTTP_1_1) .code(200) .message("OK") .body("".toResponseBody()) .build() - } - .build() + }.build() - client.newCall( - Request.Builder().url("http://placeholder.invalid/api/test").build(), - ).execute() + client + .newCall( + Request.Builder().url("http://placeholder.invalid/api/test").build(), + ).execute() assertEquals("placeholder.invalid", seen?.host) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/api/CleartextGuardTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/api/CleartextGuardTest.kt index b911bede..047611ed 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/api/CleartextGuardTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/api/CleartextGuardTest.kt @@ -32,8 +32,17 @@ class CleartextGuardTest { @Test fun `home network and overlay addresses may use plain http`() { for (a in listOf( - "127.0.0.1", "10.1.2.3", "172.16.0.9", "172.31.255.1", "192.168.1.20", - "169.254.3.4", "100.64.0.1", "100.127.255.254", "::1", "fd12:3456::1", "fe80::1", + "127.0.0.1", + "10.1.2.3", + "172.16.0.9", + "172.31.255.1", + "192.168.1.20", + "169.254.3.4", + "100.64.0.1", + "100.127.255.254", + "::1", + "fd12:3456::1", + "fe80::1", )) { assertTrue(CleartextPolicy.allows(ip(a)), "$a should be allowed") } @@ -42,21 +51,30 @@ class CleartextGuardTest { @Test fun `public addresses may not`() { for (a in listOf( - "8.8.8.8", "172.32.0.1", "100.128.0.1", "100.63.255.255", "203.0.113.5", - "2001:db8::1", "2606:4700::1111", + "8.8.8.8", + "172.32.0.1", + "100.128.0.1", + "100.63.255.255", + "203.0.113.5", + "2001:db8::1", + "2606:4700::1111", )) { assertFalse(CleartextPolicy.allows(ip(a)), "$a should be refused") } } - private fun client(allows: Boolean) = OkHttpClient.Builder() - .addNetworkInterceptor(CleartextGuardInterceptor { allows }) - .build() + private fun client(allows: Boolean) = + OkHttpClient + .Builder() + .addNetworkInterceptor(CleartextGuardInterceptor { allows }) + .build() - private fun serverRequest() = Request.Builder() - .url(server.url("/api/auth/login")) - .tag(MinstrelServerRequest::class.java, MinstrelServerRequest) - .build() + private fun serverRequest() = + Request + .Builder() + .url(server.url("/api/auth/login")) + .tag(MinstrelServerRequest::class.java, MinstrelServerRequest) + .build() @Test fun `a refused server request sends nothing`() { @@ -77,8 +95,10 @@ class CleartextGuardTest { @Test fun `requests not bound for the Minstrel server are left alone`() { server.enqueue(MockResponse().setResponseCode(200)) - client(allows = false).newCall(Request.Builder().url(server.url("/art.jpg")).build()) - .execute().use { assertEquals(200, it.code) } + client(allows = false) + .newCall(Request.Builder().url(server.url("/art.jpg")).build()) + .execute() + .use { assertEquals(200, it.code) } } @Test diff --git a/android/app/src/test/java/com/fabledsword/minstrel/api/ErrorCopyTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/api/ErrorCopyTest.kt index 6c47e211..dfcaba43 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/api/ErrorCopyTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/api/ErrorCopyTest.kt @@ -9,16 +9,20 @@ import retrofit2.Response import java.io.IOException class ErrorCopyTest { - private fun httpError(status: Int, body: String): HttpException = + private fun httpError( + status: Int, + body: String, + ): HttpException = HttpException( Response.error(status, body.toResponseBody("application/json".toMediaType())), ) @Test fun libraryNotWritableAppendsTheServerDetail() { - val detail = "Minstrel runs as uid 1000, gid 1000 and cannot delete from /music/A " + - "(read-only file system). The library mount must be writable by that user. " + - "Nothing was deleted." + val detail = + "Minstrel runs as uid 1000, gid 1000 and cannot delete from /music/A " + + "(read-only file system). The library mount must be writable by that user. " + + "Nothing was deleted." val e = httpError(409, """{"error":{"code":"library_not_writable","message":"$detail"}}""") assertEquals( diff --git a/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthControllerTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthControllerTest.kt index 9ce9015d..7e00c8ea 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthControllerTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthControllerTest.kt @@ -68,7 +68,8 @@ class AuthControllerTest { } val store = AuthStore(dao, slowVault, scope) val retrofit = - Retrofit.Builder() + Retrofit + .Builder() .baseUrl(server.url("/")) .client(OkHttpClient.Builder().build()) .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) @@ -100,22 +101,25 @@ class AuthControllerTest { } val store = AuthStore(dao, vault, scope) val retrofit = - Retrofit.Builder() + Retrofit + .Builder() .baseUrl(server.url("/")) .client( - OkHttpClient.Builder() + OkHttpClient + .Builder() // Attaches the stored cookie, as AuthCookieInterceptor does. .addInterceptor { chain -> val cookie = store.sessionCookieForRequest() chain.proceed( - chain.request().newBuilder().apply { - if (!cookie.isNullOrEmpty()) header("Cookie", cookie) - }.build(), + chain + .request() + .newBuilder() + .apply { + if (!cookie.isNullOrEmpty()) header("Cookie", cookie) + }.build(), ) - } - .build(), - ) - .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) + }.build(), + ).addConverterFactory(json.asConverterFactory("application/json".toMediaType())) .build() server.enqueue(MockResponse().setResponseCode(200).setBody("""{"id":"u1","username":"listener"}""")) server.enqueue(MockResponse().setResponseCode(204)) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthStoreSessionVaultTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthStoreSessionVaultTest.kt index 9dcce27d..e173b89f 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthStoreSessionVaultTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/auth/AuthStoreSessionVaultTest.kt @@ -27,85 +27,93 @@ import kotlin.test.assertNull @OptIn(ExperimentalCoroutinesApi::class) class AuthStoreSessionVaultTest { /** A DAO whose single row holds [legacyCookie] in its sessionCookie column. */ - private class RowDao(var legacyCookie: String?) { - val dao: AuthSessionDao = mockk { - every { observe() } returns flowOf(null) - coEvery { get() } answers { - AuthSessionEntity(baseUrl = "http://music.local", sessionCookie = legacyCookie) + private class RowDao( + var legacyCookie: String?, + ) { + val dao: AuthSessionDao = + mockk { + every { observe() } returns flowOf(null) + coEvery { get() } answers { + AuthSessionEntity(baseUrl = "http://music.local", sessionCookie = legacyCookie) + } + coEvery { upsert(any()) } answers { legacyCookie = firstArg().sessionCookie } + coEvery { setSessionCookie(any()) } answers { legacyCookie = firstArg() } } - coEvery { upsert(any()) } answers { legacyCookie = firstArg().sessionCookie } - coEvery { setSessionCookie(any()) } answers { legacyCookie = firstArg() } + } + + @Test + fun `an upgrading install keeps its session, moved out of the row into the vault`() = + runTest { + val row = RowDao(legacyCookie = "session=abc") + val vault = FakeSessionVault() + + val store = AuthStore(row.dao, vault, TestScope(UnconfinedTestDispatcher(testScheduler))) + store.awaitSessionHydrated() + + assertEquals("session=abc", store.sessionCookie.value) + assertEquals("session=abc", vault.stored) + assertNull(row.legacyCookie, "the plain-text copy must be cleared from the row") } - } @Test - fun `an upgrading install keeps its session, moved out of the row into the vault`() = runTest { - val row = RowDao(legacyCookie = "session=abc") - val vault = FakeSessionVault() + fun `a cookie already in the vault is loaded without touching the row`() = + runTest { + val row = RowDao(legacyCookie = null) + val vault = FakeSessionVault(stored = "session=xyz") - val store = AuthStore(row.dao, vault, TestScope(UnconfinedTestDispatcher(testScheduler))) - store.awaitSessionHydrated() + val store = AuthStore(row.dao, vault, TestScope(UnconfinedTestDispatcher(testScheduler))) + store.awaitSessionHydrated() - assertEquals("session=abc", store.sessionCookie.value) - assertEquals("session=abc", vault.stored) - assertNull(row.legacyCookie, "the plain-text copy must be cleared from the row") - } + assertEquals("session=xyz", store.sessionCookie.value) + assertEquals(0, vault.writes) + coVerify(exactly = 0) { row.dao.setSessionCookie(any()) } + } @Test - fun `a cookie already in the vault is loaded without touching the row`() = runTest { - val row = RowDao(legacyCookie = null) - val vault = FakeSessionVault(stored = "session=xyz") + fun `when the Keystore will not work the cookie stays in the row instead of being lost`() = + runTest { + val row = RowDao(legacyCookie = "session=abc") + val vault = FakeSessionVault(available = false) - val store = AuthStore(row.dao, vault, TestScope(UnconfinedTestDispatcher(testScheduler))) - store.awaitSessionHydrated() + val store = AuthStore(row.dao, vault, TestScope(UnconfinedTestDispatcher(testScheduler))) + store.awaitSessionHydrated() + assertEquals("session=abc", store.sessionCookie.value) + assertEquals("session=abc", row.legacyCookie) - assertEquals("session=xyz", store.sessionCookie.value) - assertEquals(0, vault.writes) - coVerify(exactly = 0) { row.dao.setSessionCookie(any()) } - } + store.setSessionCookie("session=new") + assertEquals("session=new", row.legacyCookie, "fallback writes go to the row") + } @Test - fun `when the Keystore will not work the cookie stays in the row instead of being lost`() = runTest { - val row = RowDao(legacyCookie = "session=abc") - val vault = FakeSessionVault(available = false) + fun `sign-in and sign-out write the vault, and never the row`() = + runTest { + val row = RowDao(legacyCookie = null) + val vault = FakeSessionVault() + val store = AuthStore(row.dao, vault, TestScope(UnconfinedTestDispatcher(testScheduler))) + store.awaitSessionHydrated() - val store = AuthStore(row.dao, vault, TestScope(UnconfinedTestDispatcher(testScheduler))) - store.awaitSessionHydrated() - assertEquals("session=abc", store.sessionCookie.value) - assertEquals("session=abc", row.legacyCookie) + store.setSessionCookie("session=new") + assertEquals("session=new", vault.stored) + assertNull(row.legacyCookie) - store.setSessionCookie("session=new") - assertEquals("session=new", row.legacyCookie, "fallback writes go to the row") - } + store.setSessionCookie(null) + assertNull(vault.stored) + assertNull(store.sessionCookie.value) + } @Test - fun `sign-in and sign-out write the vault, and never the row`() = runTest { - val row = RowDao(legacyCookie = null) - val vault = FakeSessionVault() - val store = AuthStore(row.dao, vault, TestScope(UnconfinedTestDispatcher(testScheduler))) - store.awaitSessionHydrated() + fun `a sign-out that lands before hydration finishes is not undone by it`() = + runTest { + val row = RowDao(legacyCookie = "session=stale") + val vault = FakeSessionVault() + val scope = TestScope(StandardTestDispatcher(testScheduler)) - store.setSessionCookie("session=new") - assertEquals("session=new", vault.stored) - assertNull(row.legacyCookie) + // Hydration is queued but has not run; a 401 clears the session first. + val store = AuthStore(row.dao, vault, scope) + store.setSessionCookie(null) + scope.advanceUntilIdle() - store.setSessionCookie(null) - assertNull(vault.stored) - assertNull(store.sessionCookie.value) - } - - @Test - fun `a sign-out that lands before hydration finishes is not undone by it`() = runTest { - val row = RowDao(legacyCookie = "session=stale") - val vault = FakeSessionVault() - val scope = TestScope(StandardTestDispatcher(testScheduler)) - - // Hydration is queued but has not run; a 401 clears the session first. - val store = AuthStore(row.dao, vault, scope) - store.setSessionCookie(null) - scope.advanceUntilIdle() - - assertNull(store.sessionCookie.value, "hydration must not resurrect the stale cookie") - assertNull(vault.stored) - } + assertNull(store.sessionCookie.value, "hydration must not resurrect the stale cookie") + assertNull(vault.stored) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt index 5911cc2e..495afcb1 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/auth/ServerProbeTest.kt @@ -28,21 +28,27 @@ class ServerProbeTest { private val ca = HeldCertificate.Builder().certificateAuthority(0).build() private val strangerCa = HeldCertificate.Builder().certificateAuthority(0).build() - private val serverCertificate = HeldCertificate.Builder() - .signedBy(ca) - .addSubjectAlternativeName("localhost") - .build() + private val serverCertificate = + HeldCertificate + .Builder() + .signedBy(ca) + .addSubjectAlternativeName("localhost") + .build() @AfterEach fun teardown() { servers.forEach { it.shutdown() } } - private fun server(tls: Boolean, body: String = SETUP_STATUS): String { + private fun server( + tls: Boolean, + body: String = SETUP_STATUS, + ): String { val server = MockWebServer() - server.dispatcher = object : Dispatcher() { - override fun dispatch(request: RecordedRequest) = MockResponse().setBody(body) - } + server.dispatcher = + object : Dispatcher() { + override fun dispatch(request: RecordedRequest) = MockResponse().setBody(body) + } if (tls) { val certificates = HandshakeCertificates.Builder().heldCertificate(serverCertificate).build() server.useHttps(certificates.sslSocketFactory(), false) @@ -52,25 +58,30 @@ class ServerProbeTest { return "localhost:${server.port}" } - private fun probe(trusts: HeldCertificate = ca, cleartextAllowed: Boolean = true): ServerProbe { - val certificates = HandshakeCertificates.Builder() - .addTrustedCertificate(trusts.certificate) - .build() - val client = OkHttpClient.Builder() - .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager) - .addInterceptor { chain -> - schemes += chain.request().url.scheme - chain.proceed(chain.request()) - } - .addNetworkInterceptor(CleartextGuardInterceptor { cleartextAllowed }) - .build() + private fun probe( + trusts: HeldCertificate = ca, + cleartextAllowed: Boolean = true, + ): ServerProbe { + val certificates = + HandshakeCertificates + .Builder() + .addTrustedCertificate(trusts.certificate) + .build() + val client = + OkHttpClient + .Builder() + .sslSocketFactory(certificates.sslSocketFactory(), certificates.trustManager) + .addInterceptor { chain -> + schemes += chain.request().url.scheme + chain.proceed(chain.request()) + }.addNetworkInterceptor(CleartextGuardInterceptor { cleartextAllowed }) + .build() // https aimed at a plain-http port can stall until the call times // out; a short timeout keeps those cases quick. return ServerProbe(client, callTimeoutMillis = 2_000) } - private fun failure(result: ServerProbe.Result): String = - assertIs(result).message + private fun failure(result: ServerProbe.Result): String = assertIs(result).message @Test fun `an address without a scheme is saved as https when Minstrel answers there`() { diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt index aef748af..c3075902 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/account/AccountCacheTest.kt @@ -40,74 +40,84 @@ class AccountCacheTest { private val user = MutableStateFlow(null) private val owner = MutableStateFlow(null) - private val authStore = mockk { - every { settingsLoaded } returns loaded - every { cacheOwnerUserId } returns owner - coEvery { setCacheOwnerUserId(any()) } coAnswers { owner.value = firstArg() } - coEvery { clearNotifiedUpTo() } returns Unit - } + private val authStore = + mockk { + every { settingsLoaded } returns loaded + every { cacheOwnerUserId } returns owner + coEvery { setCacheOwnerUserId(any()) } coAnswers { owner.value = firstArg() } + coEvery { clearNotifiedUpTo() } returns Unit + } private val authController = mockk { every { currentUser } returns user } private val tables = mockk(relaxed = true) private val player = mockk(relaxed = true) - private fun TestScope.accountCache() = AccountCache( - authStore, authController, tables, { player }, TestScope(UnconfinedTestDispatcher(testScheduler)), - ) + 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") + 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") - } + 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") + 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) - } + 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") + 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) - } + 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()) } + 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) - } + // 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) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/audiocache/BucketLedgerTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/audiocache/BucketLedgerTest.kt index 5790abb0..4f90392d 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/cache/audiocache/BucketLedgerTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/audiocache/BucketLedgerTest.kt @@ -10,9 +10,17 @@ import kotlin.test.assertNull * drops its own least-recently-used audio first. */ class BucketLedgerTest { - private data class Span(val key: String, val position: Long, val length: Long, val touched: Long) + private data class Span( + val key: String, + val position: Long, + val length: Long, + val touched: Long, + ) - private fun ledger(likedCap: Long = 0L, recentCap: Long = 0L) = BucketLedger( + private fun ledger( + likedCap: Long = 0L, + recentCap: Long = 0L, + ) = BucketLedger( keyOf = { it.key }, lengthOf = { it.length }, lruOrder = compareBy { it.touched }.thenBy { it.key }.thenBy { it.position }, diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt index 301d0692..8ef89c19 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SendOrQueueTest.kt @@ -19,33 +19,38 @@ class SendOrQueueTest { private fun httpError(status: Int) = HttpException(Response.error(status, "".toResponseBody())) - private suspend fun attempt(failure: Throwable?, onRefused: ((HttpException) -> WriteOutcome)? = null) = - if (onRefused == null) { - sendOrQueue(send = { failure?.let { throw it } }, queue = { queued++ }) - } else { - sendOrQueue(send = { failure?.let { throw it } }, queue = { queued++ }, onRefused = onRefused) + private suspend fun attempt( + failure: Throwable?, + onRefused: ((HttpException) -> WriteOutcome)? = null, + ) = if (onRefused == null) { + sendOrQueue(send = { failure?.let { throw it } }, queue = { queued++ }) + } else { + sendOrQueue(send = { failure?.let { throw it } }, queue = { queued++ }, onRefused = onRefused) + } + + @Test + fun `a write the server takes is synced and not queued`() = + runTest { + assertEquals(WriteOutcome.Synced, attempt(null)) + assertEquals(0, queued) } @Test - fun `a write the server takes is synced and not queued`() = runTest { - assertEquals(WriteOutcome.Synced, attempt(null)) - assertEquals(0, queued) - } - - @Test - fun `no answer, a server error, a timeout and too-many-requests are queued`() = runTest { - for (failure in listOf(IOException("offline"), httpError(503), httpError(408), httpError(429))) { - assertEquals(WriteOutcome.Queued, attempt(failure), "for $failure") + fun `no answer, a server error, a timeout and too-many-requests are queued`() = + runTest { + for (failure in listOf(IOException("offline"), httpError(503), httpError(408), httpError(429))) { + assertEquals(WriteOutcome.Queued, attempt(failure), "for $failure") + } + assertEquals(4, queued) } - assertEquals(4, queued) - } @Test - fun `a refusal is not queued, and is thrown by default so the caller can say why`() = runTest { - assertFailsWith { attempt(httpError(403)) } - assertEquals(WriteOutcome.Refused, attempt(httpError(404)) { WriteOutcome.Refused }) - assertEquals(0, queued) - } + fun `a refusal is not queued, and is thrown by default so the caller can say why`() = + runTest { + assertFailsWith { attempt(httpError(403)) } + assertEquals(WriteOutcome.Refused, attempt(httpError(404)) { WriteOutcome.Refused }) + assertEquals(0, queued) + } @Test fun `the replayer and the live write agree on what is worth retrying`() { diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt index 2480cf56..177dcda0 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/mutations/SupersededToggleIdsTest.kt @@ -17,44 +17,51 @@ import kotlin.test.assertTrue * and nothing surfaces the contradiction. */ class SupersededToggleIdsTest { - private val json = Json { ignoreUnknownKeys = true } - private fun likeRow(id: Long, entityId: String, desired: Boolean) = CachedMutationEntity( + private fun likeRow( + id: Long, + entityId: String, + desired: Boolean, + ) = CachedMutationEntity( id = id, kind = MutationKind.LIKE_TOGGLE, - payload = json.encodeToString( - LikeTogglePayload.serializer(), - LikeTogglePayload("artist", entityId, desired), - ), + payload = + json.encodeToString( + LikeTogglePayload.serializer(), + LikeTogglePayload("artist", entityId, desired), + ), ) @Test fun `a like followed by its undo drops the like`() { - val rows = listOf( - likeRow(1, "artist-1", desired = true), - likeRow(2, "artist-1", desired = false), - ) + val rows = + listOf( + likeRow(1, "artist-1", desired = true), + likeRow(2, "artist-1", desired = false), + ) // Only the later intent (the undo) survives to be replayed. assertEquals(setOf(1L), supersededToggleIds(rows, json)) } @Test fun `toggles for different entities never collapse into each other`() { - val rows = listOf( - likeRow(1, "artist-1", desired = true), - likeRow(2, "artist-2", desired = true), - ) + val rows = + listOf( + likeRow(1, "artist-1", desired = true), + likeRow(2, "artist-2", desired = true), + ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } @Test fun `only the newest of several toggles for one entity survives`() { - val rows = listOf( - likeRow(1, "artist-1", desired = true), - likeRow(2, "artist-1", desired = false), - likeRow(3, "artist-1", desired = true), - ) + val rows = + listOf( + likeRow(1, "artist-1", desired = true), + likeRow(2, "artist-1", desired = false), + likeRow(3, "artist-1", desired = true), + ) assertEquals(setOf(1L, 2L), supersededToggleIds(rows, json)) } @@ -63,10 +70,11 @@ class SupersededToggleIdsTest { // one another. @Test fun `a like and a setting with the same strings do not collide`() { - val rows = listOf( - likeRow(1, "same-id", desired = true), - settingRow(2, "artist", "same-id", value = true), - ) + val rows = + listOf( + likeRow(1, "same-id", desired = true), + settingRow(2, "artist", "same-id", value = true), + ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } @@ -74,24 +82,27 @@ class SupersededToggleIdsTest { fun `non-toggle kinds are never collapsed, even repeated for one entity`() { // Two appends to the same playlist are two real actions, not one // desired state — collapsing them would lose a write. - val rows = listOf( - CachedMutationEntity( - id = 1, - kind = MutationKind.PLAYLIST_APPEND, - payload = json.encodeToString( - PlaylistAppendPayload.serializer(), - PlaylistAppendPayload("pl-1", listOf("t1")), + val rows = + listOf( + CachedMutationEntity( + id = 1, + kind = MutationKind.PLAYLIST_APPEND, + payload = + json.encodeToString( + PlaylistAppendPayload.serializer(), + PlaylistAppendPayload("pl-1", listOf("t1")), + ), ), - ), - CachedMutationEntity( - id = 2, - kind = MutationKind.PLAYLIST_APPEND, - payload = json.encodeToString( - PlaylistAppendPayload.serializer(), - PlaylistAppendPayload("pl-1", listOf("t2")), + CachedMutationEntity( + id = 2, + kind = MutationKind.PLAYLIST_APPEND, + payload = + json.encodeToString( + PlaylistAppendPayload.serializer(), + PlaylistAppendPayload("pl-1", listOf("t2")), + ), ), - ), - ) + ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } @@ -100,14 +111,15 @@ class SupersededToggleIdsTest { // behind it. The dispatcher DROPs the bad row on its own. @Test fun `an undecodable payload does not suppress a valid later row`() { - val rows = listOf( - CachedMutationEntity( - id = 1, - kind = MutationKind.LIKE_TOGGLE, - payload = "{ not json", - ), - likeRow(2, "artist-1", desired = true), - ) + val rows = + listOf( + CachedMutationEntity( + id = 1, + kind = MutationKind.LIKE_TOGGLE, + payload = "{ not json", + ), + likeRow(2, "artist-1", desired = true), + ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } @@ -116,45 +128,57 @@ class SupersededToggleIdsTest { assertTrue(supersededToggleIds(emptyList(), json).isEmpty()) } - private fun normalizationRow(id: Long, mode: NormalizationMode) = CachedMutationEntity( + private fun normalizationRow( + id: Long, + mode: NormalizationMode, + ) = CachedMutationEntity( id = id, kind = MutationKind.NORMALIZATION_SET, - payload = json.encodeToString( - NormalizationPrefs.serializer(), - NormalizationPrefs.DEFAULT.copy(mode = mode), - ), + payload = + json.encodeToString( + NormalizationPrefs.serializer(), + NormalizationPrefs.DEFAULT.copy(mode = mode), + ), ) // There is one preference per user, so any two queued changes to it // collapse, and only the newest is sent. @Test fun `only the newest queued normalization change survives`() { - val rows = listOf( - normalizationRow(1, NormalizationMode.TRACK), - likeRow(2, "artist-1", desired = true), - normalizationRow(3, NormalizationMode.OFF), - normalizationRow(4, NormalizationMode.ALBUM), - ) + val rows = + listOf( + normalizationRow(1, NormalizationMode.TRACK), + likeRow(2, "artist-1", desired = true), + normalizationRow(3, NormalizationMode.OFF), + normalizationRow(4, NormalizationMode.ALBUM), + ) assertEquals(setOf(1L, 3L), supersededToggleIds(rows, json)) } - private fun settingRow(id: Long, kind: String, channel: String, value: Boolean) = CachedMutationEntity( + private fun settingRow( + id: Long, + kind: String, + channel: String, + value: Boolean, + ) = CachedMutationEntity( id = id, kind = MutationKind.NOTIFICATION_SETTING_SET, - payload = json.encodeToString( - NotificationSettingPayload.serializer(), - NotificationSettingPayload(kind, channel, value), - ), + payload = + json.encodeToString( + NotificationSettingPayload.serializer(), + NotificationSettingPayload(kind, channel, value), + ), ) @Test fun `notification settings collapse per kind and channel, never across them`() { - val rows = listOf( - settingRow(1, "tracks_missing", "email", false), - settingRow(2, "tracks_missing", "phone", false), - settingRow(3, "tracks_missing", "email", true), - settingRow(4, "quarantine_flagged", "email", false), - ) + val rows = + listOf( + settingRow(1, "tracks_missing", "email", false), + settingRow(2, "tracks_missing", "phone", false), + settingRow(3, "tracks_missing", "email", true), + settingRow(4, "quarantine_flagged", "email", false), + ) // Only the older email toggle for tracks_missing is superseded. assertEquals(setOf(1L), supersededToggleIds(rows, json)) } @@ -168,43 +192,53 @@ class SupersededToggleIdsTest { assertEquals(null, notificationSettingChange(NotificationSettingPayload("k", "pager", true))) } - private fun reorderRow(id: Long, playlistId: String, order: List) = CachedMutationEntity( + private fun reorderRow( + id: Long, + playlistId: String, + order: List, + ) = CachedMutationEntity( id = id, kind = MutationKind.PLAYLIST_REORDER, - payload = json.encodeToString( - PlaylistReorderPayload.serializer(), - PlaylistReorderPayload(playlistId, order), - ), + payload = + json.encodeToString( + PlaylistReorderPayload.serializer(), + PlaylistReorderPayload(playlistId, order), + ), ) @Test fun `only a playlist's last queued reorder is sent`() { - val rows = listOf( - reorderRow(1, "p1", listOf("a", "b")), - reorderRow(2, "p2", listOf("x", "y")), - reorderRow(3, "p1", listOf("b", "a")), - ) + val rows = + listOf( + reorderRow(1, "p1", listOf("a", "b")), + reorderRow(2, "p2", listOf("x", "y")), + reorderRow(3, "p1", listOf("b", "a")), + ) assertEquals(setOf(1L), supersededToggleIds(rows, json)) } @Test fun `every playlist change names its playlist, so one list's changes wait in order`() { - val create = CachedMutationEntity( - id = 1, - kind = MutationKind.PLAYLIST_CREATE, - payload = json.encodeToString( - PlaylistCreatePayload.serializer(), - PlaylistCreatePayload("p1", "Road Songs"), - ), - ) - val append = CachedMutationEntity( - id = 2, - kind = MutationKind.PLAYLIST_APPEND, - payload = json.encodeToString( - PlaylistAppendPayload.serializer(), - PlaylistAppendPayload("p1", listOf("t1")), - ), - ) + val create = + CachedMutationEntity( + id = 1, + kind = MutationKind.PLAYLIST_CREATE, + payload = + json.encodeToString( + PlaylistCreatePayload.serializer(), + PlaylistCreatePayload("p1", "Road Songs"), + ), + ) + val append = + CachedMutationEntity( + id = 2, + kind = MutationKind.PLAYLIST_APPEND, + payload = + json.encodeToString( + PlaylistAppendPayload.serializer(), + PlaylistAppendPayload("p1", listOf("t1")), + ), + ) val like = likeRow(3, "artist-1", desired = true) assertEquals(listOf("p1", "p1", null), listOf(create, append, like).map { playlistIdOf(it, json) }) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/cache/sync/SyncControllerTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/cache/sync/SyncControllerTest.kt index 5cd31ff4..5677a840 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/cache/sync/SyncControllerTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/cache/sync/SyncControllerTest.kt @@ -33,80 +33,110 @@ import kotlin.test.assertNull class SyncControllerTest { private val api: SyncApi = mockk() private val trackDao: CachedTrackDao = mockk(relaxed = true) - private val retrofit: Retrofit = mockk { - every { create(SyncApi::class.java) } returns api - } - private val authStore: AuthStore = mockk { - every { sessionCookie } returns MutableStateFlow(null) - } - private val networkStatus: NetworkStatusController = mockk { - // Offline, so construction starts no pass; each test runs one itself. - every { state } returns MutableStateFlow(ServerHealth.Offline) - } + private val retrofit: Retrofit = + mockk { + every { create(SyncApi::class.java) } returns api + } + private val authStore: AuthStore = + mockk { + every { sessionCookie } returns MutableStateFlow(null) + } + private val networkStatus: NetworkStatusController = + mockk { + // Offline, so construction starts no pass; each test runs one itself. + every { state } returns MutableStateFlow(ServerHealth.Offline) + } // The cursor round-trips through the DAO, so it is held for real. private var stored: SyncMetadataEntity? = null - private val metadataDao: SyncMetadataDao = mockk { - coEvery { get() } answers { stored } - coEvery { upsert(any()) } answers { stored = firstArg() } - } + private val metadataDao: SyncMetadataDao = + mockk { + coEvery { get() } answers { stored } + coEvery { upsert(any()) } answers { stored = firstArg() } + } - private fun page(cursor: Long, deletedTracks: List = emptyList()) = - Response.success(SyncResponseWire(cursor = cursor, deletes = SyncDeletesWire(track = deletedTracks))) + private fun page( + cursor: Long, + deletedTracks: List = emptyList(), + ) = Response.success(SyncResponseWire(cursor = cursor, deletes = SyncDeletesWire(track = deletedTracks))) private fun noContent(): Response = Response.success(204, null as SyncResponseWire?) @Test - fun `pages are pulled until the server has nothing newer`() = runTest { - coEvery { api.sync(0) } returns page(1000) - coEvery { api.sync(1000) } returns page(2000, deletedTracks = listOf("merged-away")) - coEvery { api.sync(2000) } returns noContent() + fun `pages are pulled until the server has nothing newer`() = + runTest { + coEvery { api.sync(0) } returns page(1000) + coEvery { api.sync(1000) } returns page(2000, deletedTracks = listOf("merged-away")) + coEvery { api.sync(2000) } returns noContent() - val controller = SyncController( - metadataDao, mockk(relaxed = true), mockk(relaxed = true), - trackDao, authStore, backgroundScope, networkStatus, retrofit, - ) - controller.syncSafe() + val controller = + SyncController( + metadataDao, + mockk(relaxed = true), + mockk(relaxed = true), + trackDao, + authStore, + backgroundScope, + networkStatus, + retrofit, + ) + controller.syncSafe() - assertNull(controller.lastSyncError.value) + assertNull(controller.lastSyncError.value) - coVerify(exactly = 1) { api.sync(2000) } - coVerify { trackDao.deleteByIds(listOf("merged-away")) } - assertEquals(2000L, stored?.cursor) - } + coVerify(exactly = 1) { api.sync(2000) } + coVerify { trackDao.deleteByIds(listOf("merged-away")) } + assertEquals(2000L, stored?.cursor) + } @Test - fun `a cursor that does not advance stops the pass`() = runTest { - stored = SyncMetadataEntity(cursor = 500) - coEvery { api.sync(500) } returns page(500) + fun `a cursor that does not advance stops the pass`() = + runTest { + stored = SyncMetadataEntity(cursor = 500) + coEvery { api.sync(500) } returns page(500) - val controller = SyncController( - metadataDao, mockk(relaxed = true), mockk(relaxed = true), - trackDao, authStore, backgroundScope, networkStatus, retrofit, - ) - controller.syncSafe() + val controller = + SyncController( + metadataDao, + mockk(relaxed = true), + mockk(relaxed = true), + trackDao, + authStore, + backgroundScope, + networkStatus, + retrofit, + ) + controller.syncSafe() - assertNull(controller.lastSyncError.value) + assertNull(controller.lastSyncError.value) - coVerify(exactly = 1) { api.sync(500) } - } + coVerify(exactly = 1) { api.sync(500) } + } @Test - fun `a stale cursor resets to zero and keeps pulling`() = runTest { - stored = SyncMetadataEntity(cursor = 7) - coEvery { api.sync(7) } returns Response.error(410, "".toResponseBody()) - coEvery { api.sync(0) } returns page(1000) - coEvery { api.sync(1000) } returns noContent() + fun `a stale cursor resets to zero and keeps pulling`() = + runTest { + stored = SyncMetadataEntity(cursor = 7) + coEvery { api.sync(7) } returns Response.error(410, "".toResponseBody()) + coEvery { api.sync(0) } returns page(1000) + coEvery { api.sync(1000) } returns noContent() - val controller = SyncController( - metadataDao, mockk(relaxed = true), mockk(relaxed = true), - trackDao, authStore, backgroundScope, networkStatus, retrofit, - ) - controller.syncSafe() + val controller = + SyncController( + metadataDao, + mockk(relaxed = true), + mockk(relaxed = true), + trackDao, + authStore, + backgroundScope, + networkStatus, + retrofit, + ) + controller.syncSafe() - assertNull(controller.lastSyncError.value) + assertNull(controller.lastSyncError.value) - coVerify(exactly = 1) { api.sync(1000) } - assertEquals(1000L, stored?.cursor) - } + coVerify(exactly = 1) { api.sync(1000) } + assertEquals(1000L, stored?.cursor) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/connectivity/ReachabilityMachineTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/connectivity/ReachabilityMachineTest.kt index 953fb028..0a264167 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/connectivity/ReachabilityMachineTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/connectivity/ReachabilityMachineTest.kt @@ -5,7 +5,6 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class ReachabilityMachineTest { - private fun machine() = ReachabilityMachine() @Test diff --git a/android/app/src/test/java/com/fabledsword/minstrel/diagnostics/TransportFlapDetectorTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/diagnostics/TransportFlapDetectorTest.kt index b066b1d2..a7c58d75 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/diagnostics/TransportFlapDetectorTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/diagnostics/TransportFlapDetectorTest.kt @@ -13,16 +13,19 @@ import kotlin.test.assertNull * shy and a real stutter goes unmeasured. */ class TransportFlapDetectorTest { - - private fun obs(state: String, atMs: Long, track: Int = 1, posMs: Long = 0L) = - TransportObservation( - state = state, - statusOk = true, - trackNumber = track, - positionMs = posMs, - playIntent = true, - atElapsedMs = atMs, - ) + private fun obs( + state: String, + atMs: Long, + track: Int = 1, + posMs: Long = 0L, + ) = TransportObservation( + state = state, + statusOk = true, + trackNumber = track, + positionMs = posMs, + playIntent = true, + atElapsedMs = atMs, + ) /** * PLAYING -> TRANSITIONING -> PLAYING is what a queue advance looks like. diff --git a/android/app/src/test/java/com/fabledsword/minstrel/home/data/HomeRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/home/data/HomeRepositoryTest.kt index 2ce0ecce..1da58cd9 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/home/data/HomeRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/home/data/HomeRepositoryTest.kt @@ -33,11 +33,13 @@ class HomeRepositoryTest { @BeforeEach fun setup() { server = MockWebServer().apply { start() } - retrofit = Retrofit.Builder() - .baseUrl(server.url("/")) - .client(OkHttpClient.Builder().build()) - .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) - .build() + retrofit = + Retrofit + .Builder() + .baseUrl(server.url("/")) + .client(OkHttpClient.Builder().build()) + .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) + .build() } @AfterEach @@ -52,42 +54,45 @@ class HomeRepositoryTest { private fun repo() = HomeRepository(homeIndexDao, metadataProvider, prewarmer, retrofit) @Test - fun `rediscover albums emit skeleton tiles then reveal as rows land`() = runTest { - val indexRow = CachedHomeIndexEntity( - section = HomeRepository.SECTION_REDISCOVER_ALBUMS, - position = 0, - entityType = "album", - entityId = "al1", - ) - every { - homeIndexDao.observeBySection(HomeRepository.SECTION_REDISCOVER_ALBUMS) - } returns flowOf(listOf(indexRow)) - val albumFlow = MutableStateFlow(null) - every { metadataProvider.observeAlbum("al1") } returns albumFlow + fun `rediscover albums emit skeleton tiles then reveal as rows land`() = + runTest { + val indexRow = + CachedHomeIndexEntity( + section = HomeRepository.SECTION_REDISCOVER_ALBUMS, + position = 0, + entityType = "album", + entityId = "al1", + ) + every { + homeIndexDao.observeBySection(HomeRepository.SECTION_REDISCOVER_ALBUMS) + } returns flowOf(listOf(indexRow)) + val albumFlow = MutableStateFlow(null) + every { metadataProvider.observeAlbum("al1") } returns albumFlow - repo().observeRediscoverAlbums().test { - val skeleton = awaitItem() - assertEquals(1, skeleton.size) - assertEquals("al1", skeleton[0].id) - assertNull(skeleton[0].value) // skeleton in position + repo().observeRediscoverAlbums().test { + val skeleton = awaitItem() + assertEquals(1, skeleton.size) + assertEquals("al1", skeleton[0].id) + assertNull(skeleton[0].value) // skeleton in position - albumFlow.value = AlbumRef(id = "al1", title = "Geomantic", artistId = "a1") - val revealed = awaitItem() - assertEquals("al1", revealed[0].id) - assertEquals("Geomantic", revealed[0].value?.title) // tile reveals - cancelAndIgnoreRemainingEvents() + albumFlow.value = AlbumRef(id = "al1", title = "Geomantic", artistId = "a1") + val revealed = awaitItem() + assertEquals("al1", revealed[0].id) + assertEquals("Geomantic", revealed[0].value?.title) // tile reveals + cancelAndIgnoreRemainingEvents() + } } - } @Test - fun `empty section emits empty list`() = runTest { - every { - homeIndexDao.observeBySection(HomeRepository.SECTION_REDISCOVER_ALBUMS) - } returns flowOf(emptyList()) + fun `empty section emits empty list`() = + runTest { + every { + homeIndexDao.observeBySection(HomeRepository.SECTION_REDISCOVER_ALBUMS) + } returns flowOf(emptyList()) - repo().observeRediscoverAlbums().test { - assertEquals(0, awaitItem().size) - awaitComplete() + repo().observeRediscoverAlbums().test { + assertEquals(0, awaitItem().size) + awaitComplete() + } } - } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt index aacbda94..5ea87f53 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/home/ui/BuildPlaylistsRowTest.kt @@ -8,9 +8,10 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue class BuildPlaylistsRowTest { - - private fun user(id: String, cached: Boolean) = - PlaylistRef(id = id, userId = "u", name = id, trackCount = 1, fullyCached = cached) + private fun user( + id: String, + cached: Boolean, + ) = PlaylistRef(id = id, userId = "u", name = id, trackCount = 1, fullyCached = cached) @Test fun `offline row leads with pools then available before greyed`() { @@ -26,19 +27,21 @@ class BuildPlaylistsRowTest { @Test fun `offline greys a refreshable system playlist even when fully cached`() { - val forYou = PlaylistRef( - id = "fy", - userId = "u", - name = "For You", - systemVariant = "for_you", - trackCount = 1, - fullyCached = true, - ) - val row = buildPlaylistsRow( - listOf(forYou, user("u1", cached = true)), - SystemPlaylistsStatus(), - offline = true, - ) + val forYou = + PlaylistRef( + id = "fy", + userId = "u", + name = "For You", + systemVariant = "for_you", + trackCount = 1, + fullyCached = true, + ) + val row = + buildPlaylistsRow( + listOf(forYou, user("u1", cached = true)), + SystemPlaylistsStatus(), + offline = true, + ) // The fully-cached user playlist is available; the refreshable system // mix needs the server, so it greys out and sorts after. val reals = row.filterIsInstance().map { it.playlist.id } @@ -58,7 +61,10 @@ class BuildPlaylistsRowTest { assertTrue(row.any { it is PlaylistRowItem.Placeholder }) } - private fun songsLike(id: String, cached: Boolean) = PlaylistRef( + private fun songsLike( + id: String, + cached: Boolean, + ) = PlaylistRef( id = id, userId = "u", name = "Songs like $id", @@ -105,7 +111,11 @@ class BuildPlaylistsRowTest { assertTrue(buildSongsLikeRow(emptyList(), SystemPlaylistsStatus(), offline = true).isEmpty()) } - private fun genreMix(name: String, cached: Boolean, rank: Int = 0) = PlaylistRef( + private fun genreMix( + name: String, + cached: Boolean, + rank: Int = 0, + ) = PlaylistRef( id = name, userId = "u", name = name, @@ -117,32 +127,38 @@ class BuildPlaylistsRowTest { @Test fun `genre mixes get their own row in name order and stay out of the carousel`() { - val owned = listOf( - genreMix("Shoegaze mix", cached = true), - genreMix("dub mix", cached = true), - genreMix("Jazz mix", cached = true), - user("u1", cached = true), - ) + val owned = + listOf( + genreMix("Shoegaze mix", cached = true), + genreMix("dub mix", cached = true), + genreMix("Jazz mix", cached = true), + user("u1", cached = true), + ) val row = buildGenreMixRow(owned, offline = false) val names = row.filterIsInstance().map { it.playlist.name } assertEquals(listOf("dub mix", "Jazz mix", "Shoegaze mix"), names) - val carousel = buildPlaylistsRow(owned, SystemPlaylistsStatus(), offline = false) - .filterIsInstance().map { it.playlist.id } + val carousel = + buildPlaylistsRow(owned, SystemPlaylistsStatus(), offline = false) + .filterIsInstance() + .map { it.playlist.id } assertEquals(listOf("u1"), carousel) } @Test fun `ranked genre mixes lead with the genre played most, the unranked follow by name`() { - val owned = listOf( - genreMix("Ambient mix", cached = true, rank = 3), - genreMix("Zydeco mix", cached = true), - genreMix("Pop mix", cached = true, rank = 1), - genreMix("Blues mix", cached = true), - genreMix("Jazz mix", cached = true, rank = 2), - ) - val names = buildGenreMixRow(owned, offline = false) - .filterIsInstance().map { it.playlist.name } + val owned = + listOf( + genreMix("Ambient mix", cached = true, rank = 3), + genreMix("Zydeco mix", cached = true), + genreMix("Pop mix", cached = true, rank = 1), + genreMix("Blues mix", cached = true), + genreMix("Jazz mix", cached = true, rank = 2), + ) + val names = + buildGenreMixRow(owned, offline = false) + .filterIsInstance() + .map { it.playlist.name } assertEquals(listOf("Pop mix", "Jazz mix", "Ambient mix", "Blues mix", "Zydeco mix"), names) } @@ -150,8 +166,10 @@ class BuildPlaylistsRowTest { fun `genre mixes are not refreshable, so a cached one plays offline`() { assertFalse(genreMix("Jazz mix", cached = true).refreshable) val owned = listOf(genreMix("A mix", cached = false), genreMix("B mix", cached = true)) - val names = buildGenreMixRow(owned, offline = true) - .filterIsInstance().map { it.playlist.name } + val names = + buildGenreMixRow(owned, offline = true) + .filterIsInstance() + .map { it.playlist.name } assertEquals(listOf("B mix", "A mix"), names) assertTrue(buildGenreMixRow(emptyList(), offline = false).isEmpty()) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt index 7f91c122..ca734a58 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryMappersTest.kt @@ -7,19 +7,21 @@ import kotlin.test.assertEquals class LibraryMappersTest { @Test fun `a cached artist with a fetched picture shows the artist image`() { - val artist = CachedArtistEntity( - id = "r1", - name = "Tin Orchard", - sortName = "Tin Orchard", - artistThumbPath = "/data/artist-art/r1/thumb.jpg", - ).toDomain(coverAlbumId = "a1") + val artist = + CachedArtistEntity( + id = "r1", + name = "Tin Orchard", + sortName = "Tin Orchard", + artistThumbPath = "/data/artist-art/r1/thumb.jpg", + ).toDomain(coverAlbumId = "a1") assertEquals("http://placeholder.invalid/api/artists/r1/image", artist.displayCoverUrl) } @Test fun `a cached artist without a picture falls back to an album cover`() { - val artist = CachedArtistEntity(id = "r1", name = "Tin Orchard", sortName = "Tin Orchard") - .toDomain(coverAlbumId = "a1") + val artist = + CachedArtistEntity(id = "r1", name = "Tin Orchard", sortName = "Tin Orchard") + .toDomain(coverAlbumId = "a1") assertEquals("http://placeholder.invalid/api/albums/a1/cover", artist.displayCoverUrl) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryRepositoryTest.kt index 93f64a93..0c3467b4 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/library/data/LibraryRepositoryTest.kt @@ -5,12 +5,15 @@ import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao import com.fabledsword.minstrel.cache.db.entities.CachedArtistEntity +import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory import io.mockk.coEvery import io.mockk.coVerify import io.mockk.every import io.mockk.mockk import kotlinx.coroutines.flow.flowOf import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.Json +import okhttp3.MediaType.Companion.toMediaType import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer @@ -18,9 +21,6 @@ import org.junit.jupiter.api.AfterEach import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import retrofit2.Retrofit -import kotlinx.serialization.json.Json -import com.jakewharton.retrofit2.converter.kotlinx.serialization.asConverterFactory -import okhttp3.MediaType.Companion.toMediaType import kotlin.test.assertEquals class LibraryRepositoryTest { @@ -34,7 +34,8 @@ class LibraryRepositoryTest { fun setup() { server = MockWebServer().apply { start() } retrofit = - Retrofit.Builder() + Retrofit + .Builder() .baseUrl(server.url("/")) .client(OkHttpClient.Builder().build()) .addConverterFactory(json.asConverterFactory("application/json".toMediaType())) @@ -51,56 +52,58 @@ class LibraryRepositoryTest { } @Test - fun `observeArtists maps DAO rows to domain ArtistRefs`() = runTest { - every { artistDao.observeAll() } returns - flowOf( - listOf( - CachedArtistEntity(id = "a1", name = "Fields of Ontario", sortName = "Fields of Ontario"), - ), - ) - // observeArtists now combines with albums (to derive the tile - // cover from the first album); stub it so combine can emit. - every { albumDao.observeAll() } returns flowOf(emptyList()) - val repo = LibraryRepository(artistDao, albumDao, trackDao, retrofit) + fun `observeArtists maps DAO rows to domain ArtistRefs`() = + runTest { + every { artistDao.observeAll() } returns + flowOf( + listOf( + CachedArtistEntity(id = "a1", name = "Fields of Ontario", sortName = "Fields of Ontario"), + ), + ) + // observeArtists now combines with albums (to derive the tile + // cover from the first album); stub it so combine can emit. + every { albumDao.observeAll() } returns flowOf(emptyList()) + val repo = LibraryRepository(artistDao, albumDao, trackDao, retrofit) - repo.observeArtists().test { - val first = awaitItem() - assertEquals(1, first.size) - assertEquals("a1", first[0].id) - assertEquals("Fields of Ontario", first[0].name) - awaitComplete() + repo.observeArtists().test { + val first = awaitItem() + assertEquals(1, first.size) + assertEquals("a1", first[0].id) + assertEquals("Fields of Ontario", first[0].name) + awaitComplete() + } } - } @Test - fun `refreshArtistDetail upserts the artist + the embedded albums`() = runTest { - server.enqueue( - MockResponse() - .setResponseCode(200) - .setHeader("Content-Type", "application/json") - .setBody( - """ - { - "id": "a1", - "name": "Fields of Ontario", - "sort_name": "Fields of Ontario", - "album_count": 2, - "cover_url": "", - "albums": [ - {"id": "al1", "title": "Music Has the Right to Wander", "artist_id": "a1", "sort_title": "Music Has the Right to Wander"}, - {"id": "al2", "title": "Geomantic", "artist_id": "a1", "sort_title": "Geomantic"} - ] - } - """.trimIndent(), - ), - ) - coEvery { artistDao.upsertAll(any()) } returns Unit - coEvery { albumDao.upsertAll(any()) } returns Unit - val repo = LibraryRepository(artistDao, albumDao, trackDao, retrofit) + fun `refreshArtistDetail upserts the artist + the embedded albums`() = + runTest { + server.enqueue( + MockResponse() + .setResponseCode(200) + .setHeader("Content-Type", "application/json") + .setBody( + """ + { + "id": "a1", + "name": "Fields of Ontario", + "sort_name": "Fields of Ontario", + "album_count": 2, + "cover_url": "", + "albums": [ + {"id": "al1", "title": "Music Has the Right to Wander", "artist_id": "a1", "sort_title": "Music Has the Right to Wander"}, + {"id": "al2", "title": "Geomantic", "artist_id": "a1", "sort_title": "Geomantic"} + ] + } + """.trimIndent(), + ), + ) + coEvery { artistDao.upsertAll(any()) } returns Unit + coEvery { albumDao.upsertAll(any()) } returns Unit + val repo = LibraryRepository(artistDao, albumDao, trackDao, retrofit) - repo.refreshArtistDetail("a1") + repo.refreshArtistDetail("a1") - coVerify { artistDao.upsertAll(match { it.size == 1 && it[0].id == "a1" }) } - coVerify { albumDao.upsertAll(match { it.size == 2 && it[0].id == "al1" && it[1].id == "al2" }) } - } + coVerify { artistDao.upsertAll(match { it.size == 1 && it[0].id == "a1" }) } + coVerify { albumDao.upsertAll(match { it.size == 2 && it[0].id == "al1" && it[1].id == "al2" }) } + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/library/ui/BrowseIndexTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/library/ui/BrowseIndexTest.kt index 6b3ac788..566ab758 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/library/ui/BrowseIndexTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/library/ui/BrowseIndexTest.kt @@ -7,15 +7,15 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class VisibleGenresTest { - // Server order: track count descending, name breaking ties. - private val index = listOf( - GenreCount("Rock", 420), - GenreCount("Electronic", 260), - GenreCount("rock", 12), - GenreCount("Alt. Rock", 7), - GenreCount("Rock/Pop", 3), - ) + private val index = + listOf( + GenreCount("Rock", 420), + GenreCount("Electronic", 260), + GenreCount("rock", 12), + GenreCount("Alt. Rock", 7), + GenreCount("Rock/Pop", 3), + ) @Test fun `count sort leaves the server's order alone`() { @@ -79,26 +79,27 @@ class VisibleGenresTest { } class GroupByDecadeTest { - @Test fun `groups by decade, newest decade first`() { - val out = groupByDecade( - listOf( - YearCount(2003, 4), - YearCount(1999, 2), - YearCount(2007, 1), - YearCount(1994, 3), - YearCount(2021, 5), - ), - ) + val out = + groupByDecade( + listOf( + YearCount(2003, 4), + YearCount(1999, 2), + YearCount(2007, 1), + YearCount(1994, 3), + YearCount(2021, 5), + ), + ) assertEquals(listOf(2020, 2000, 1990), out.map { it.decade }) } @Test fun `years within a decade are newest first`() { - val out = groupByDecade( - listOf(YearCount(2003, 1), YearCount(2007, 1), YearCount(2001, 1)), - ) + val out = + groupByDecade( + listOf(YearCount(2003, 1), YearCount(2007, 1), YearCount(2001, 1)), + ) assertEquals(listOf(2007, 2003, 2001), out.single().years.map { it.year }) } @@ -121,7 +122,6 @@ class GroupByDecadeTest { } class AlbumCountLabelTest { - /** * A count that appears as "0 albums" and then corrects itself reads as a * bug, so the first page's flight shows nothing at all. diff --git a/android/app/src/test/java/com/fabledsword/minstrel/library/ui/LibraryViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/library/ui/LibraryViewModelTest.kt index 434f1d4c..1d9f9a02 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/library/ui/LibraryViewModelTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/library/ui/LibraryViewModelTest.kt @@ -21,7 +21,6 @@ import kotlin.test.assertEquals @ExtendWith(MainDispatcherExtension::class) class LibraryViewModelTest { - // lastSyncError needs a real StateFlow: the VM combines it into uiState, // and a relaxed-mock flow never emits, so the combine would never fire. private fun syncControllerMock(): SyncController = @@ -30,19 +29,21 @@ class LibraryViewModelTest { } @Test - fun `initial state is Loading before any DAO emission`() = runTest { - val repo = mockk() - every { repo.observeArtists() } returns MutableSharedFlow() - every { repo.observeAlbums() } returns MutableSharedFlow() + fun `initial state is Loading before any DAO emission`() = + runTest { + val repo = mockk() + every { repo.observeArtists() } returns MutableSharedFlow() + every { repo.observeAlbums() } returns MutableSharedFlow() - val vm = LibraryViewModel( - repo, - syncControllerMock(), - mockk(relaxed = true), - ) + val vm = + LibraryViewModel( + repo, + syncControllerMock(), + mockk(relaxed = true), + ) - assertEquals(UiState.Loading, vm.uiState.value) - } + assertEquals(UiState.Loading, vm.uiState.value) + } // Note: tests below collect the resolved state directly. With // UnconfinedTestDispatcher, stateIn's upstream Flow runs synchronously @@ -52,66 +53,72 @@ class LibraryViewModelTest { // intermediate Loading. @Test - fun `Empty when DAOs emit empty lists`() = runTest { - val repo = mockk() - every { repo.observeArtists() } returns flowOf(emptyList()) - every { repo.observeAlbums() } returns flowOf(emptyList()) + fun `Empty when DAOs emit empty lists`() = + runTest { + val repo = mockk() + every { repo.observeArtists() } returns flowOf(emptyList()) + every { repo.observeAlbums() } returns flowOf(emptyList()) - val vm = LibraryViewModel( - repo, - syncControllerMock(), - mockk(relaxed = true), - ) + val vm = + LibraryViewModel( + repo, + syncControllerMock(), + mockk(relaxed = true), + ) - vm.uiState.test { - assertEquals(UiState.Empty, awaitItem()) - cancelAndConsumeRemainingEvents() + vm.uiState.test { + assertEquals(UiState.Empty, awaitItem()) + cancelAndConsumeRemainingEvents() + } } - } @Test - fun `Success when DAOs emit content`() = runTest { - val repo = mockk() - every { repo.observeArtists() } returns - flowOf(listOf(ArtistRef(id = "a1", name = "Fields of Ontario", sortName = "Fields"))) - every { repo.observeAlbums() } returns - flowOf(listOf(AlbumRef(id = "al1", title = "Geomantic", artistId = "a1"))) + fun `Success when DAOs emit content`() = + runTest { + val repo = mockk() + every { repo.observeArtists() } returns + flowOf(listOf(ArtistRef(id = "a1", name = "Fields of Ontario", sortName = "Fields"))) + every { repo.observeAlbums() } returns + flowOf(listOf(AlbumRef(id = "al1", title = "Geomantic", artistId = "a1"))) - val vm = LibraryViewModel( - repo, - syncControllerMock(), - mockk(relaxed = true), - ) + val vm = + LibraryViewModel( + repo, + syncControllerMock(), + mockk(relaxed = true), + ) - vm.uiState.test { - val success = awaitItem() as UiState.Success - assertEquals(1, success.data.artists.size) - assertEquals(1, success.data.albums.size) - assertEquals("a1", success.data.artists[0].id) - assertEquals("al1", success.data.albums[0].id) - cancelAndConsumeRemainingEvents() + vm.uiState.test { + val success = awaitItem() as UiState.Success + assertEquals(1, success.data.artists.size) + assertEquals(1, success.data.albums.size) + assertEquals("a1", success.data.artists[0].id) + assertEquals("al1", success.data.albums[0].id) + cancelAndConsumeRemainingEvents() + } } - } @Test - fun `Error when an upstream Flow throws`() = runTest { - val repo = mockk() - every { repo.observeArtists() } returns - flow { throw IllegalStateException("DAO blew up") } - every { repo.observeAlbums() } returns flowOf(emptyList()) + fun `Error when an upstream Flow throws`() = + runTest { + val repo = mockk() + every { repo.observeArtists() } returns + flow { throw IllegalStateException("DAO blew up") } + every { repo.observeAlbums() } returns flowOf(emptyList()) - val vm = LibraryViewModel( - repo, - syncControllerMock(), - mockk(relaxed = true), - ) + val vm = + LibraryViewModel( + repo, + syncControllerMock(), + mockk(relaxed = true), + ) - vm.uiState.test { - val error = awaitItem() as UiState.Error - // ErrorCopy maps a non-HTTP/non-IO throwable to the generic - // fallback rather than leaking the raw exception text. - assertEquals("Something went wrong.", error.message) - cancelAndConsumeRemainingEvents() + vm.uiState.test { + val error = awaitItem() as UiState.Error + // ErrorCopy maps a non-HTTP/non-IO throwable to the generic + // fallback rather than leaking the raw exception text. + assertEquals("Something went wrong.", error.message) + cancelAndConsumeRemainingEvents() + } } - } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt index 1a4eb83a..0c11b240 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt @@ -39,63 +39,77 @@ class LikesRepositoryTest { private val api: LikesApi = mockk(relaxed = true) private val likeDao: CachedLikeDao = mockk(relaxed = true) private val queue: MutationQueue = mockk(relaxed = true) - private val auth: AuthController = mockk { - every { currentUser } returns MutableStateFlow(UserRef(id = "u1", username = "listener")) - } - private val retrofit: Retrofit = mockk { - every { create(LikesApi::class.java) } returns api - } - private val repo = LikesRepository( - likeDao, mockk(), mockk(), mockk(), - queue, auth, scope, retrofit, - ) + private val auth: AuthController = + mockk { + every { currentUser } returns MutableStateFlow(UserRef(id = "u1", username = "listener")) + } + private val retrofit: Retrofit = + mockk { + every { create(LikesApi::class.java) } returns api + } + private val repo = + LikesRepository( + likeDao, + mockk(), + mockk(), + mockk(), + queue, + auth, + scope, + retrofit, + ) @AfterEach fun teardown() = scope.cancel() @Test - fun `a toggle with nothing queued goes live`() = runTest { - coEvery { queue.pendingLikeStates() } returns emptyMap() + fun `a toggle with nothing queued goes live`() = + runTest { + coEvery { queue.pendingLikeStates() } returns emptyMap() - repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = false) + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = false) - coVerify { api.unlike("tracks", "t1") } - coVerify(exactly = 0) { queue.enqueueLikeToggle(any(), any(), any()) } - } + coVerify { api.unlike("tracks", "t1") } + coVerify(exactly = 0) { queue.enqueueLikeToggle(any(), any(), any()) } + } @Test - fun `a toggle behind a queued one queues too, so the older one cannot land last`() = runTest { - coEvery { queue.pendingLikeStates() } returns - mapOf(likeToggleKey(LikesRepository.ENTITY_TRACK, "t1") to true) + fun `a toggle behind a queued one queues too, so the older one cannot land last`() = + runTest { + coEvery { queue.pendingLikeStates() } returns + mapOf(likeToggleKey(LikesRepository.ENTITY_TRACK, "t1") to true) - repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = false) + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = false) - coVerify(exactly = 0) { api.unlike(any(), any()) } - coVerify { queue.enqueueLikeToggle(LikesRepository.ENTITY_TRACK, "t1", false) } - } + coVerify(exactly = 0) { api.unlike(any(), any()) } + coVerify { queue.enqueueLikeToggle(LikesRepository.ENTITY_TRACK, "t1", false) } + } @Test - fun `a toggle that cannot reach the server is queued`() = runTest { - coEvery { queue.pendingLikeStates() } returns emptyMap() - coEvery { api.like(any(), any()) } throws IOException("offline") + fun `a toggle that cannot reach the server is queued`() = + runTest { + coEvery { queue.pendingLikeStates() } returns emptyMap() + coEvery { api.like(any(), any()) } throws IOException("offline") - repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = true) + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = true) - coVerify { queue.enqueueLikeToggle(LikesRepository.ENTITY_TRACK, "t1", true) } - } + coVerify { queue.enqueueLikeToggle(LikesRepository.ENTITY_TRACK, "t1", true) } + } @Test - fun `refresh keeps the likes and unlikes still queued over the server's list`() = runTest { - coEvery { api.ids() } returns LikedIdsWire(trackIds = listOf("kept", "unliked-here")) - coEvery { queue.pendingLikeStates() } returns mapOf( - likeToggleKey(LikesRepository.ENTITY_TRACK, "unliked-here") to false, - likeToggleKey(LikesRepository.ENTITY_TRACK, "liked-here") to true, - ) - val rows = slot>() - coEvery { likeDao.replaceAllForUser("u1", capture(rows)) } returns Unit + fun `refresh keeps the likes and unlikes still queued over the server's list`() = + runTest { + coEvery { api.ids() } returns LikedIdsWire(trackIds = listOf("kept", "unliked-here")) + coEvery { queue.pendingLikeStates() } returns + mapOf( + likeToggleKey(LikesRepository.ENTITY_TRACK, "unliked-here") to false, + likeToggleKey(LikesRepository.ENTITY_TRACK, "liked-here") to true, + ) + val rows = slot>() + coEvery { likeDao.replaceAllForUser("u1", capture(rows)) } returns Unit - repo.refreshIds() + repo.refreshIds() - assertEquals(setOf("kept", "liked-here"), rows.captured.map { it.entityId }.toSet()) - } + assertEquals(setOf("kept", "liked-here"), rows.captured.map { it.entityId }.toSet()) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/metadata/HomeArtistPrewarmerTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/metadata/HomeArtistPrewarmerTest.kt index 4aaf8bbb..a38d0c0b 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/metadata/HomeArtistPrewarmerTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/metadata/HomeArtistPrewarmerTest.kt @@ -19,7 +19,7 @@ class HomeArtistPrewarmerTest { prewarmer.warm(listOf("a1", "a2")) (1..8).forEach { i -> verify(exactly = 1) { provider.refreshArtist("a$i") } } - verify(exactly = 0) { provider.refreshArtist("a9") } // past the top-8 cap - verify(exactly = 0) { provider.refreshArtist("") } // blank skipped + verify(exactly = 0) { provider.refreshArtist("a9") } // past the top-8 cap + verify(exactly = 0) { provider.refreshArtist("") } // blank skipped } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/metadata/MetadataProviderTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/metadata/MetadataProviderTest.kt index 8894b089..c8576c93 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/metadata/MetadataProviderTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/metadata/MetadataProviderTest.kt @@ -27,67 +27,71 @@ class MetadataProviderTest { private val library = mockk(relaxed = true) @Test - fun `same missing id fetched once (dedup)`() = runTest { - val scope = this - coEvery { albumDao.observeById("a1") } returns flowOf(null) - val provider = MetadataProvider(albumDao, artistDao, trackDao, library, scope) + fun `same missing id fetched once (dedup)`() = + runTest { + val scope = this + coEvery { albumDao.observeById("a1") } returns flowOf(null) + val provider = MetadataProvider(albumDao, artistDao, trackDao, library, scope) - provider.observeAlbum("a1").first() - provider.observeAlbum("a1").first() - testScheduler.advanceUntilIdle() + provider.observeAlbum("a1").first() + provider.observeAlbum("a1").first() + testScheduler.advanceUntilIdle() - coVerify(exactly = 1) { library.refreshAlbumDetail("a1") } - } + coVerify(exactly = 1) { library.refreshAlbumDetail("a1") } + } // A row the server no longer has (a duplicate merge) is dropped, or the // freshness sweep asks for it every 30 minutes forever. @Test - fun `a 404 drops the cached row`() = runTest { - coEvery { library.refreshTrack("t1") } throws httpError(404) - val provider = MetadataProvider(albumDao, artistDao, trackDao, library, this) + fun `a 404 drops the cached row`() = + runTest { + coEvery { library.refreshTrack("t1") } throws httpError(404) + val provider = MetadataProvider(albumDao, artistDao, trackDao, library, this) - provider.refreshTrack("t1").join() + provider.refreshTrack("t1").join() - coVerify(exactly = 1) { trackDao.deleteByIds(listOf("t1")) } - } + coVerify(exactly = 1) { trackDao.deleteByIds(listOf("t1")) } + } @Test - fun `any other failure keeps the cached row`() = runTest { - coEvery { library.refreshAlbumDetail("a1") } throws httpError(500) - val provider = MetadataProvider(albumDao, artistDao, trackDao, library, this) + fun `any other failure keeps the cached row`() = + runTest { + coEvery { library.refreshAlbumDetail("a1") } throws httpError(500) + val provider = MetadataProvider(albumDao, artistDao, trackDao, library, this) - provider.refreshAlbum("a1").join() + provider.refreshAlbum("a1").join() - coVerify(exactly = 0) { albumDao.deleteByIds(any()) } - } + coVerify(exactly = 0) { albumDao.deleteByIds(any()) } + } private fun httpError(status: Int) = HttpException(Response.error(status, "".toResponseBody())) @Test - fun `at most four fetches run concurrently`() = runTest { - val scope = this - val live = AtomicInteger(0) - val peak = AtomicInteger(0) - val gate = CompletableDeferred() - coEvery { library.refreshAlbumDetail(any()) } coAnswers { - val now = live.incrementAndGet() - peak.updateAndGet { p -> maxOf(p, now) } - gate.await() - live.decrementAndGet() - mockk(relaxed = true) - } - (1..10).forEach { i -> coEvery { albumDao.observeById("a$i") } returns flowOf(null) } - val provider = MetadataProvider(albumDao, artistDao, trackDao, library, scope) - - (1..10).forEach { i -> - launch(UnconfinedTestDispatcher(testScheduler)) { - provider.observeAlbum("a$i").first() + fun `at most four fetches run concurrently`() = + runTest { + val scope = this + val live = AtomicInteger(0) + val peak = AtomicInteger(0) + val gate = CompletableDeferred() + coEvery { library.refreshAlbumDetail(any()) } coAnswers { + val now = live.incrementAndGet() + peak.updateAndGet { p -> maxOf(p, now) } + gate.await() + live.decrementAndGet() + mockk(relaxed = true) } - } - testScheduler.advanceUntilIdle() + (1..10).forEach { i -> coEvery { albumDao.observeById("a$i") } returns flowOf(null) } + val provider = MetadataProvider(albumDao, artistDao, trackDao, library, scope) - assertTrue(peak.get() <= 4, "peak concurrency was ${peak.get()}, expected <= 4") - gate.complete(Unit) - testScheduler.advanceUntilIdle() - } + (1..10).forEach { i -> + launch(UnconfinedTestDispatcher(testScheduler)) { + provider.observeAlbum("a$i").first() + } + } + testScheduler.advanceUntilIdle() + + assertTrue(peak.get() <= 4, "peak concurrency was ${peak.get()}, expected <= 4") + gate.complete(Unit) + testScheduler.advanceUntilIdle() + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepositoryTest.kt index 93ade546..adb92343 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationSettingsRepositoryTest.kt @@ -31,77 +31,85 @@ class NotificationSettingsRepositoryTest { private val dao: CachedNotificationDao = mockk(relaxed = true) private val mutationDao: CachedMutationDao = mockk() private val queue: MutationQueue = mockk(relaxed = true) - private val retrofit: Retrofit = mockk { - every { create(NotificationsApi::class.java) } returns api - } + private val retrofit: Retrofit = + mockk { + every { create(NotificationsApi::class.java) } returns api + } private val repo = NotificationSettingsRepository(retrofit, dao, mutationDao, queue, json) - private val settings = NotificationSettingsWire( - kinds = listOf( - NotificationKindSettingWire("new_music", false, inbox = true, phone = true, email = true), - ), - emailAvailable = true, - ) + private val settings = + NotificationSettingsWire( + kinds = + listOf( + NotificationKindSettingWire("new_music", false, inbox = true, phone = true, email = true), + ), + emailAvailable = true, + ) private fun cached() { - coEvery { dao.getSettings() } returns CachedNotificationSettingsEntity( - json = json.encodeToString(NotificationSettingsWire.serializer(), settings), - ) + coEvery { dao.getSettings() } returns + CachedNotificationSettingsEntity( + json = json.encodeToString(NotificationSettingsWire.serializer(), settings), + ) } @Test - fun `a toggle is shown at once and sends only that channel`() = runTest { - cached() - coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns false - val saved = mutableListOf() - coEvery { dao.upsertSettings(capture(saved)) } returns Unit - val body = slot() - coEvery { api.putSettings(capture(body)) } returns settings + fun `a toggle is shown at once and sends only that channel`() = + runTest { + cached() + coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns false + val saved = mutableListOf() + coEvery { dao.upsertSettings(capture(saved)) } returns Unit + val body = slot() + coEvery { api.putSettings(capture(body)) } returns settings - repo.set("new_music", NotificationChannel.EMAIL, false) + repo.set("new_music", NotificationChannel.EMAIL, false) - val optimistic = json.decodeFromString(NotificationSettingsWire.serializer(), saved.first().json) - assertFalse(optimistic.kinds.single().email) - assertEquals( - listOf(NotificationSettingChangeWire(kind = "new_music", email = false)), - body.captured.kinds, - ) - coVerify(exactly = 0) { queue.enqueueNotificationSettingSet(any()) } - } - - @Test - fun `a toggle that cannot reach the server is queued`() = runTest { - cached() - coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns false - coEvery { api.putSettings(any()) } throws IOException("offline") - - repo.set("new_music", NotificationChannel.PHONE, false) - - coVerify { - queue.enqueueNotificationSettingSet(NotificationSettingPayload("new_music", "phone", false)) + val optimistic = json.decodeFromString(NotificationSettingsWire.serializer(), saved.first().json) + assertFalse(optimistic.kinds.single().email) + assertEquals( + listOf(NotificationSettingChangeWire(kind = "new_music", email = false)), + body.captured.kinds, + ) + coVerify(exactly = 0) { queue.enqueueNotificationSettingSet(any()) } } - } @Test - fun `a toggle behind a queued one queues too`() = runTest { - cached() - coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns true + fun `a toggle that cannot reach the server is queued`() = + runTest { + cached() + coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns false + coEvery { api.putSettings(any()) } throws IOException("offline") - repo.set("new_music", NotificationChannel.INBOX, false) + repo.set("new_music", NotificationChannel.PHONE, false) - coVerify(exactly = 0) { api.putSettings(any()) } - coVerify { - queue.enqueueNotificationSettingSet(NotificationSettingPayload("new_music", "inbox", false)) + coVerify { + queue.enqueueNotificationSettingSet(NotificationSettingPayload("new_music", "phone", false)) + } } - } @Test - fun `refresh leaves a queued change on screen`() = runTest { - coEvery { api.getSettings() } returns settings - coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns true + fun `a toggle behind a queued one queues too`() = + runTest { + cached() + coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns true - repo.refresh() + repo.set("new_music", NotificationChannel.INBOX, false) - coVerify(exactly = 0) { dao.upsertSettings(any()) } - } + coVerify(exactly = 0) { api.putSettings(any()) } + coVerify { + queue.enqueueNotificationSettingSet(NotificationSettingPayload("new_music", "inbox", false)) + } + } + + @Test + fun `refresh leaves a queued change on screen`() = + runTest { + coEvery { api.getSettings() } returns settings + coEvery { mutationDao.hasPending(MutationKind.NOTIFICATION_SETTING_SET) } returns true + + repo.refresh() + + coVerify(exactly = 0) { dao.upsertSettings(any()) } + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationsRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationsRepositoryTest.kt index c394d782..7198f0f7 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationsRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/data/NotificationsRepositoryTest.kt @@ -32,14 +32,19 @@ class NotificationsRepositoryTest { private val api: NotificationsApi = mockk(relaxed = true) private val dao: CachedNotificationDao = mockk(relaxed = true) private val queue: MutationQueue = mockk(relaxed = true) - private val retrofit: Retrofit = mockk { - every { create(NotificationsApi::class.java) } returns api - } + private val retrofit: Retrofit = + mockk { + every { create(NotificationsApi::class.java) } returns api + } private val repo = NotificationsRepository(retrofit, dao, queue) private fun httpError(status: Int) = HttpException(Response.error(status, "".toResponseBody())) - private fun row(id: String, created: String, readAt: Instant? = null) = CachedNotificationEntity( + private fun row( + id: String, + created: String, + readAt: Instant? = null, + ) = CachedNotificationEntity( id = id, kind = "new_music", title = "t", @@ -50,78 +55,87 @@ class NotificationsRepositoryTest { ) @Test - fun `a read is shown at once and sent`() = runTest { - repo.markRead("n1") + fun `a read is shown at once and sent`() = + runTest { + repo.markRead("n1") - coVerify { dao.markRead("n1", any()) } - coVerify { api.markRead("n1") } - coVerify(exactly = 0) { queue.enqueueNotificationRead(any()) } - } + coVerify { dao.markRead("n1", any()) } + coVerify { api.markRead("n1") } + coVerify(exactly = 0) { queue.enqueueNotificationRead(any()) } + } @Test - fun `a read that cannot reach the server is queued`() = runTest { - coEvery { api.markRead("n1") } throws IOException("offline") + fun `a read that cannot reach the server is queued`() = + runTest { + coEvery { api.markRead("n1") } throws IOException("offline") - repo.markRead("n1") + repo.markRead("n1") - coVerify { dao.markRead("n1", any()) } - coVerify { queue.enqueueNotificationRead("n1") } - } + coVerify { dao.markRead("n1", any()) } + coVerify { queue.enqueueNotificationRead("n1") } + } @Test - fun `a notice the server no longer has is not queued`() = runTest { - coEvery { api.markRead("n1") } throws httpError(404) + fun `a notice the server no longer has is not queued`() = + runTest { + coEvery { api.markRead("n1") } throws httpError(404) - repo.markRead("n1") + repo.markRead("n1") - coVerify(exactly = 0) { queue.enqueueNotificationRead(any()) } - } + coVerify(exactly = 0) { queue.enqueueNotificationRead(any()) } + } @Test - fun `a server error queues the read for later`() = runTest { - coEvery { api.markRead("n1") } throws httpError(503) + fun `a server error queues the read for later`() = + runTest { + coEvery { api.markRead("n1") } throws httpError(503) - repo.markRead("n1") + repo.markRead("n1") - coVerify { queue.enqueueNotificationRead("n1") } - } + coVerify { queue.enqueueNotificationRead("n1") } + } @Test - fun `mark all read sends the newest notice shown, rounded up, and queues it offline`() = runTest { - coEvery { dao.getAll() } returns listOf( - row("a", "2026-10-08T10:00:00.123Z"), - row("b", "2026-10-08T11:00:00.456Z"), - ) - val body = slot() - coEvery { api.readAll(capture(body)) } throws IOException("offline") + fun `mark all read sends the newest notice shown, rounded up, and queues it offline`() = + runTest { + coEvery { dao.getAll() } returns + listOf( + row("a", "2026-10-08T10:00:00.123Z"), + row("b", "2026-10-08T11:00:00.456Z"), + ) + val body = slot() + coEvery { api.readAll(capture(body)) } throws IOException("offline") - repo.markAllRead() + repo.markAllRead() - coVerify { dao.markAllRead(any()) } - assertEquals("2026-10-08T11:00:00.457Z", body.captured.upTo) - coVerify { queue.enqueueNotificationsReadAll("2026-10-08T11:00:00.457Z") } - } + coVerify { dao.markAllRead(any()) } + assertEquals("2026-10-08T11:00:00.457Z", body.captured.upTo) + coVerify { queue.enqueueNotificationsReadAll("2026-10-08T11:00:00.457Z") } + } @Test - fun `refresh keeps a read made here that the server has not seen yet`() = runTest { - val readHere = Instant.parse("2026-10-08T12:00:00Z") - coEvery { dao.getAll() } returns listOf(row("a", "2026-10-08T10:00:00Z", readAt = readHere)) - coEvery { api.list(any()) } returns NotificationsPageWire( - items = listOf( - NotificationWire("a", "new_music", "t", "b", "/", "2026-10-08T10:00:00Z", null), - NotificationWire("b", "new_music", "t", "b", "/", "2026-10-08T11:00:00Z", null), - ), - unreadCount = 2, - ) - val saved = slot>() - coEvery { dao.replaceAll(capture(saved)) } returns Unit + fun `refresh keeps a read made here that the server has not seen yet`() = + runTest { + val readHere = Instant.parse("2026-10-08T12:00:00Z") + coEvery { dao.getAll() } returns listOf(row("a", "2026-10-08T10:00:00Z", readAt = readHere)) + coEvery { api.list(any()) } returns + NotificationsPageWire( + items = + listOf( + NotificationWire("a", "new_music", "t", "b", "/", "2026-10-08T10:00:00Z", null), + NotificationWire("b", "new_music", "t", "b", "/", "2026-10-08T11:00:00Z", null), + ), + unreadCount = 2, + ) + val saved = slot>() + coEvery { dao.replaceAll(capture(saved)) } returns Unit - repo.refresh() + repo.refresh() - val byId = saved.captured.associateBy { it.id } - assertEquals(readHere, byId.getValue("a").readAt) - assertNull(byId.getValue("b").readAt) - } + val byId = saved.captured.associateBy { it.id } + assertEquals(readHere, byId.getValue("a").readAt) + assertNull(byId.getValue("b").readAt) + } @Test fun `a notice with an unreadable timestamp is skipped, not the whole page`() { diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlanTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlanTest.kt index 9e37ba20..da11f3d0 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlanTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/delivery/DeliveryPlanTest.kt @@ -73,14 +73,16 @@ class DeliveryPlanTest { @Test fun `phone prefs come from the cached settings, with every kind on when none are cached`() { - val settings = NotificationSettingsWire( - kinds = listOf( - NotificationKindSettingWire("new_music", false, inbox = true, phone = false, email = true), - NotificationKindSettingWire("tracks_missing", true, inbox = false, phone = true, email = true), - NotificationKindSettingWire("quarantine_flagged", true, inbox = true, phone = true, email = true), - ), - emailAvailable = true, - ) + val settings = + NotificationSettingsWire( + kinds = + listOf( + NotificationKindSettingWire("new_music", false, inbox = true, phone = false, email = true), + NotificationKindSettingWire("tracks_missing", true, inbox = false, phone = true, email = true), + NotificationKindSettingWire("quarantine_flagged", true, inbox = true, phone = true, email = true), + ), + emailAvailable = true, + ) val phoneOn = phoneOnFor(settings) assertFalse(phoneOn("new_music")) assertFalse(phoneOn("tracks_missing"), "phone rides on the inbox") diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModelTest.kt index 865e39ff..90bb1fa2 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModelTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationsViewModelTest.kt @@ -18,16 +18,22 @@ import kotlin.test.assertEquals /** Showing the inbox reads it: unread notices are marked read once, and keep looking new until the screen goes. */ @ExtendWith(MainDispatcherExtension::class) class NotificationsViewModelTest { - private val repository: NotificationsRepository = mockk(relaxed = true) { - every { notifications } returns emptyFlow() - } - private val network: NetworkStatusController = mockk { - every { state } returns MutableStateFlow(ServerHealth.Healthy) - } + private val repository: NotificationsRepository = + mockk(relaxed = true) { + every { notifications } returns emptyFlow() + } + private val network: NetworkStatusController = + mockk { + every { state } returns MutableStateFlow(ServerHealth.Healthy) + } + // Lazy: built inside each test, after the extension has swapped in the test Main dispatcher. private val viewModel by lazy { NotificationsViewModel(repository, network) } - private fun row(id: String, read: Boolean) = CachedNotificationEntity( + private fun row( + id: String, + read: Boolean, + ) = CachedNotificationEntity( id = id, kind = "new_music", title = "t", diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/DropUnavailableTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/DropUnavailableTest.kt index fa27cb36..a32b8aca 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/DropUnavailableTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/DropUnavailableTest.kt @@ -11,18 +11,18 @@ import kotlin.test.assertTrue * more annoying bug than the one being fixed. */ class DropUnavailableTest { + private fun track( + id: String, + unavailable: Boolean = false, + ) = TrackRef( + id = id, + title = id, + albumId = "al-1", + artistId = "ar-1", + unavailable = unavailable, + ) - private fun track(id: String, unavailable: Boolean = false) = - TrackRef( - id = id, - title = id, - albumId = "al-1", - artistId = "ar-1", - unavailable = unavailable, - ) - - private fun queue(vararg spec: Pair) = - spec.map { (id, missing) -> track(id, missing) } + private fun queue(vararg spec: Pair) = spec.map { (id, missing) -> track(id, missing) } @Test fun `a queue with nothing missing is returned untouched`() { @@ -44,10 +44,11 @@ class DropUnavailableTest { */ @Test fun `the starting index follows its track past earlier removals`() { - val out = dropUnavailable( - queue("a" to true, "b" to true, "c" to false, "d" to false), - initialIndex = 2, - ) + val out = + dropUnavailable( + queue("a" to true, "b" to true, "c" to false, "d" to false), + initialIndex = 2, + ) assertEquals(listOf("c", "d"), out.tracks.map { it.id }) assertEquals(0, out.initialIndex) assertEquals("c", out.tracks[out.initialIndex].id) @@ -55,29 +56,32 @@ class DropUnavailableTest { @Test fun `removals after the starting index leave it alone`() { - val out = dropUnavailable( - queue("a" to false, "b" to false, "c" to true), - initialIndex = 1, - ) + val out = + dropUnavailable( + queue("a" to false, "b" to false, "c" to true), + initialIndex = 1, + ) assertEquals("b", out.tracks[out.initialIndex].id) } /** Tapping a missing track starts the next playable one — it gets skipped. */ @Test fun `asking to start on a missing track starts on the next playable one`() { - val out = dropUnavailable( - queue("a" to false, "b" to true, "c" to false), - initialIndex = 1, - ) + val out = + dropUnavailable( + queue("a" to false, "b" to true, "c" to false), + initialIndex = 1, + ) assertEquals("c", out.tracks[out.initialIndex].id) } @Test fun `a missing track at the end cannot push the index out of bounds`() { - val out = dropUnavailable( - queue("a" to false, "b" to false, "c" to true), - initialIndex = 2, - ) + val out = + dropUnavailable( + queue("a" to false, "b" to false, "c" to true), + initialIndex = 2, + ) assertTrue(out.initialIndex in out.tracks.indices) assertEquals("b", out.tracks[out.initialIndex].id) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/RemotePlayerStateTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/RemotePlayerStateTest.kt index e3ff5e38..2442043d 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/RemotePlayerStateTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/RemotePlayerStateTest.kt @@ -6,7 +6,6 @@ import kotlin.test.assertFalse import kotlin.test.assertTrue class RemotePlayerStateTest { - // A renderer error stops playback and is kept to report, but what the // listener asked for survives it, so a failed play can resume locally. @Test diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/RemoteStallWatchdogTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/RemoteStallWatchdogTest.kt index c3da481f..09752706 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/RemoteStallWatchdogTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/RemoteStallWatchdogTest.kt @@ -7,7 +7,6 @@ import kotlin.test.assertIs import kotlin.test.assertTrue class RemoteStallWatchdogTest { - private val uri = "http://server/api/tracks/t-1/stream.flac" private val other = "http://server/api/tracks/t-2/stream.flac" @@ -41,12 +40,13 @@ class RemoteStallWatchdogTest { ): RemoteStallWatchdog.Decision { var last: RemoteStallWatchdog.Decision = RemoteStallWatchdog.Decision.None repeat(n) { - last = poll( - trackUri = trackUri, - state = TransportState.STOPPED, - nowMs = nowMs, - queue = queue, - ) + last = + poll( + trackUri = trackUri, + state = TransportState.STOPPED, + nowMs = nowMs, + queue = queue, + ) } return last } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/RetryTransientIoTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/RetryTransientIoTest.kt index 77e2194a..3475d14b 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/RetryTransientIoTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/RetryTransientIoTest.kt @@ -15,51 +15,56 @@ import kotlin.test.assertFailsWith * single failed command falsely reverted Sonos playback to the phone. */ class RetryTransientIoTest { - @Test - fun `returns immediately on first success`() = runTest { - var calls = 0 - val result = retryTransientIo(attempts = 3, backoffMs = 0L) { - calls += 1 - "ok" + fun `returns immediately on first success`() = + runTest { + var calls = 0 + val result = + retryTransientIo(attempts = 3, backoffMs = 0L) { + calls += 1 + "ok" + } + assertEquals("ok", result) + assertEquals(1, calls) } - assertEquals("ok", result) - assertEquals(1, calls) - } @Test - fun `retries transient IO failure then succeeds`() = runTest { - var calls = 0 - val result = retryTransientIo(attempts = 3, backoffMs = 0L) { - calls += 1 - if (calls < 2) throw IOException("connect timeout") - "ok" + fun `retries transient IO failure then succeeds`() = + runTest { + var calls = 0 + val result = + retryTransientIo(attempts = 3, backoffMs = 0L) { + calls += 1 + if (calls < 2) throw IOException("connect timeout") + "ok" + } + assertEquals("ok", result) + assertEquals(2, calls) } - assertEquals("ok", result) - assertEquals(2, calls) - } @Test - fun `rethrows IO failure after exhausting attempts`() = runTest { - var calls = 0 - assertFailsWith { - retryTransientIo(attempts = 3, backoffMs = 0L) { - calls += 1 - throw IOException("still asleep") + fun `rethrows IO failure after exhausting attempts`() = + runTest { + var calls = 0 + assertFailsWith { + retryTransientIo(attempts = 3, backoffMs = 0L) { + calls += 1 + throw IOException("still asleep") + } } + assertEquals(3, calls) } - assertEquals(3, calls) - } @Test - fun `does not retry a SOAP fault from a responding renderer`() = runTest { - var calls = 0 - assertFailsWith { - retryTransientIo(attempts = 3, backoffMs = 0L) { - calls += 1 - throw SoapFaultException("718", "Invalid InstanceID") + fun `does not retry a SOAP fault from a responding renderer`() = + runTest { + var calls = 0 + assertFailsWith { + retryTransientIo(attempts = 3, backoffMs = 0L) { + calls += 1 + throw SoapFaultException("718", "Invalid InstanceID") + } } + assertEquals(1, calls) } - assertEquals(1, calls) - } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/gain/GainMathTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/gain/GainMathTest.kt index 2b6bc744..fbbec077 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/gain/GainMathTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/gain/GainMathTest.kt @@ -11,7 +11,6 @@ import kotlin.test.assertTrue /** Mirrors web/src/lib/player/gain.test.ts: both players must level alike. */ class GainMathTest { - private fun prefs( mode: NormalizationMode = NormalizationMode.AUTO, target: Int = -18, @@ -51,22 +50,24 @@ class GainMathTest { val quiet = ReplayGain(trackGain = 8f, trackPeak = 0.5f, albumGain = null, albumPeak = null) val headroom = GainMath.gainDb(prefs(mode = NormalizationMode.TRACK), quiet, false) assertEquals(-1f - 20f * log10(0.5f), headroom, 1e-4f) - val limited = GainMath.gainDb( - prefs(mode = NormalizationMode.TRACK, boost = NormalizationBoost.LIMITER), - quiet, - false, - ) + val limited = + GainMath.gainDb( + prefs(mode = NormalizationMode.TRACK, boost = NormalizationBoost.LIMITER), + quiet, + false, + ) assertEquals(8f, limited) } @Test fun `no boost passes the cap`() { val silent = ReplayGain(trackGain = 30f, trackPeak = 0.001f, albumGain = null, albumPeak = null) - val db = GainMath.gainDb( - prefs(mode = NormalizationMode.TRACK, boost = NormalizationBoost.LIMITER), - silent, - false, - ) + val db = + GainMath.gainDb( + prefs(mode = NormalizationMode.TRACK, boost = NormalizationBoost.LIMITER), + silent, + false, + ) assertEquals(GainMath.MAX_BOOST_DB, db) } @@ -76,7 +77,11 @@ class GainMathTest { assertEquals(-9f, GainMath.gainDb(prefs(mode = NormalizationMode.TRACK), hot, false)) } - private fun pos(album: String, track: Int?, disc: Int? = 1) = AlbumPosition(album, disc, track) + private fun pos( + album: String, + track: Int?, + disc: Int? = 1, + ) = AlbumPosition(album, disc, track) @Test fun `in-order neighbours from the same album are album play`() { diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/gain/GainStageTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/gain/GainStageTest.kt index 6995c2b1..2b6dd7b5 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/gain/GainStageTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/gain/GainStageTest.kt @@ -8,7 +8,6 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class GainStageTest { - private fun floats(vararg v: Float): ByteBuffer = ByteBuffer.allocateDirect(v.size * 4).order(ByteOrder.nativeOrder()).apply { v.forEach { putFloat(it) } @@ -21,7 +20,12 @@ class GainStageTest { flip() } - private fun runFloat(stage: GainStage, input: ByteBuffer, target: Float, limiting: Boolean): FloatArray { + private fun runFloat( + stage: GainStage, + input: ByteBuffer, + target: Float, + limiting: Boolean, + ): FloatArray { val out = ByteBuffer.allocateDirect(input.remaining()).order(ByteOrder.nativeOrder()) stage.process(input, out, channels = 2, isFloat = true, target = target, limiting = limiting) out.flip() diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/gain/ReplayGainStoreTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/gain/ReplayGainStoreTest.kt index 5fccb71c..02b53a9c 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/gain/ReplayGainStoreTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/gain/ReplayGainStoreTest.kt @@ -22,53 +22,59 @@ class ReplayGainStoreTest { private val api: ReplayGainApi = mockk() private var health = ServerHealth.Healthy - private fun store() = ReplayGainStore( - scope = TestScope(), - trackDao = dao, - api = api, - serverHealth = { health }, - clock = { 0L }, - ) - - @Test - fun `cached gains are used and only the rest are asked of the server`() = runTest { - coEvery { dao.replayGains(listOf("a", "b", "c")) } returns listOf( - CachedReplayGain("a", trackGain = -6f, trackPeak = 1f, albumGain = -4f, albumPeak = 1f), - // Cached but unmeasured at the last sync: the server may know more. - CachedReplayGain("b", trackGain = null, trackPeak = null, albumGain = null, albumPeak = null), + private fun store() = + ReplayGainStore( + scope = TestScope(), + trackDao = dao, + api = api, + serverHealth = { health }, + clock = { 0L }, ) - coEvery { api.getReplayGain("b,c") } returns ReplayGainResponseWire( - items = mapOf("b" to ReplayGainWire(trackGain = -3f, trackPeak = 0.9f)), - ) - val s = store() - - s.load(listOf("a", "b", "c")) - - assertEquals(-4f, s.get("a")?.albumGain) - assertEquals(-3f, s.get("b")?.trackGain) - assertNull(s.get("c"), "a track the server has not measured stays unknown") - } @Test - fun `offline, the cache is all there is`() = runTest { - health = ServerHealth.Offline - coEvery { dao.replayGains(any()) } returns emptyList() - val s = store() + fun `cached gains are used and only the rest are asked of the server`() = + runTest { + coEvery { dao.replayGains(listOf("a", "b", "c")) } returns + listOf( + CachedReplayGain("a", trackGain = -6f, trackPeak = 1f, albumGain = -4f, albumPeak = 1f), + // Cached but unmeasured at the last sync: the server may know more. + CachedReplayGain("b", trackGain = null, trackPeak = null, albumGain = null, albumPeak = null), + ) + coEvery { api.getReplayGain("b,c") } returns + ReplayGainResponseWire( + items = mapOf("b" to ReplayGainWire(trackGain = -3f, trackPeak = 0.9f)), + ) + val s = store() - s.load(listOf("a")) + s.load(listOf("a", "b", "c")) - assertNull(s.get("a")) - coVerify(exactly = 0) { api.getReplayGain(any()) } - } + assertEquals(-4f, s.get("a")?.albumGain) + assertEquals(-3f, s.get("b")?.trackGain) + assertNull(s.get("c"), "a track the server has not measured stays unknown") + } @Test - fun `a failed lookup leaves the track unknown, to be asked again`() = runTest { - coEvery { dao.replayGains(any()) } returns emptyList() - coEvery { api.getReplayGain(any()) } throws IOException("reset") - val s = store() + fun `offline, the cache is all there is`() = + runTest { + health = ServerHealth.Offline + coEvery { dao.replayGains(any()) } returns emptyList() + val s = store() - s.load(listOf("a")) + s.load(listOf("a")) - assertNull(s.get("a")) - } + assertNull(s.get("a")) + coVerify(exactly = 0) { api.getReplayGain(any()) } + } + + @Test + fun `a failed lookup leaves the track unknown, to be asked again`() = + runTest { + coEvery { dao.replayGains(any()) } returns emptyList() + coEvery { api.getReplayGain(any()) } throws IOException("reset") + val s = store() + + s.load(listOf("a")) + + assertNull(s.get("a")) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/IdleRevertDecisionTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/IdleRevertDecisionTest.kt index 960f86b6..004056e2 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/IdleRevertDecisionTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/IdleRevertDecisionTest.kt @@ -9,7 +9,6 @@ import kotlin.test.assertEquals * playing again or leaving the speaker; anything else leaves it as it is. */ class IdleRevertDecisionTest { - @ParameterizedTest(name = "engaged={0} playing={1} armed={2} -> {3}") @CsvSource( "true, false, false, ARM", @@ -19,7 +18,12 @@ class IdleRevertDecisionTest { "false, false, true, CANCEL", "false, true, false, IGNORE", ) - fun `the idle timer`(engaged: Boolean, playing: Boolean, armed: Boolean, want: String) { + fun `the idle timer`( + engaged: Boolean, + playing: Boolean, + armed: Boolean, + want: String, + ) { assertEquals(want, idleRevertAction(upnpEngaged = engaged, isPlaying = playing, armed = armed).name) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/SingleTrackQueueTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/SingleTrackQueueTest.kt index 3261bb80..5847c86f 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/SingleTrackQueueTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/SingleTrackQueueTest.kt @@ -13,10 +13,12 @@ import kotlin.test.assertNull * position. */ class SingleTrackQueueTest { - private fun t(id: String) = TrackRef(id = id, title = "", albumId = "", artistId = "") - private fun route(manufacturer: String, zgt: Boolean = false) = UpnpRoute( + private fun route( + manufacturer: String, + zgt: Boolean = false, + ) = UpnpRoute( id = "uuid:x", name = "Room", manufacturer = manufacturer, diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/SonosAlbumPlayTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/SonosAlbumPlayTest.kt index 7a1892e7..cb3a8d5e 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/SonosAlbumPlayTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/SonosAlbumPlayTest.kt @@ -11,9 +11,10 @@ import kotlin.test.assertEquals * that a track with no album counts as none. */ class SonosAlbumPlayTest { - - private fun t(album: String, n: Int?) = - TrackRef(id = "$album-$n", title = "", albumId = album, artistId = "", trackNumber = n) + private fun t( + album: String, + n: Int?, + ) = TrackRef(id = "$album-$n", title = "", albumId = album, artistId = "", trackNumber = n) private fun asAlbum(queue: List) = queue.indices.map { SonosQueueLoader.playingAsAlbum(queue, it) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/TrackEndDetectorTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/TrackEndDetectorTest.kt index a14b73f1..d79cddaf 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/TrackEndDetectorTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/TrackEndDetectorTest.kt @@ -10,11 +10,14 @@ import kotlin.test.assertTrue * stops partway; only the first should start the next track. */ class TrackEndDetectorTest { - private val d = TrackEndDetector() - private fun poll(state: TransportState, positionMs: Long, durationMs: Long = 200_000L, known: Long = 0L) = - d.onPoll(state, positionMs, durationMs, known) + private fun poll( + state: TransportState, + positionMs: Long, + durationMs: Long = 200_000L, + known: Long = 0L, + ) = d.onPoll(state, positionMs, durationMs, known) @Test fun `a stop just after the last playing reading near the end is an ending`() { diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClientTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClientTest.kt index 7996035e..f535844c 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClientTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/AVTransportClientTest.kt @@ -5,14 +5,13 @@ import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.jupiter.api.AfterEach -import org.junit.jupiter.api.BeforeEach -import org.junit.jupiter.api.Test import org.junit.jupiter.api.Assertions.assertEquals import org.junit.jupiter.api.Assertions.assertFalse import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.BeforeEach +import org.junit.jupiter.api.Test class AVTransportClientTest { - private lateinit var server: MockWebServer private lateinit var client: AVTransportClient @@ -30,148 +29,164 @@ class AVTransportClientTest { } @Test - fun `seek sends Target in HH MM SS format`() = runTest { - server.enqueue(emptyResponse("Seek")) - client.seek(positionMs = 65_000L) - val body = server.takeRequest().body.readUtf8() - assertTrue(body.contains("0:01:05")) { "body was $body" } - } - - @Test - fun `getPositionInfo parses Track, RelTime and TrackDuration`() = runTest { - server.enqueue( - MockResponse().setBody( - """ - - - - 3 - 0:03:30 - http://x/y.mp3 - 0:01:05 - - - """.trimIndent(), - ), - ) - val info = client.getPositionInfo() - assertEquals(3, info.track) - assertEquals(65_000L, info.relTimeMs) - assertEquals(210_000L, info.trackDurationMs) - assertEquals("http://x/y.mp3", info.trackUri) - } - - @Test - fun `getTransportInfo maps PAUSED_PLAYBACK to PAUSED`() = runTest { - server.enqueue( - MockResponse().setBody( - """ - - - - PAUSED_PLAYBACK - OK - 1 - - - """.trimIndent(), - ), - ) - val info = client.getTransportInfo() - assertEquals(TransportState.PAUSED, info.state) - } - - @Test - fun `getTransportInfo maps unknown state to UNKNOWN`() = runTest { - server.enqueue( - MockResponse().setBody( - """ - - - - BUFFERING_PLAYBACK - OK - 1 - - - """.trimIndent(), - ), - ) - val info = client.getTransportInfo() - assertEquals(TransportState.UNKNOWN, info.state) - } - - @Test - fun `addURIToQueue sends EnqueuedURI and DIDL-Lite metadata`() = runTest { - server.enqueue(emptyResponse("AddURIToQueue")) - client.addURIToQueue( - uri = "http://x/y.mp3", - mime = "audio/mpeg", - title = "Song", - enqueuedURIPosition = 2, - ) - val body = server.takeRequest().body.readUtf8() - assertTrue(body.contains("http://x/y.mp3")) { - "body missing EnqueuedURI: $body" + fun `seek sends Target in HH MM SS format`() = + runTest { + server.enqueue(emptyResponse("Seek")) + client.seek(positionMs = 65_000L) + val body = server.takeRequest().body.readUtf8() + assertTrue(body.contains("0:01:05")) { "body was $body" } } - val positionTag = "2" - assertTrue(body.contains(positionTag)) { "body missing position: $body" } - assertTrue(body.contains("<dc:title>Song</dc:title>")) { - "title missing in DIDL: $body" - } - assertTrue(body.contains("audio/mpeg")) { "mime missing: $body" } - } @Test - fun `seekToTrack sends TRACK_NR unit with 1-based target`() = runTest { - server.enqueue(emptyResponse("Seek")) - client.seekToTrack(trackNumber = 4) - val body = server.takeRequest().body.readUtf8() - assertTrue(body.contains("TRACK_NR")) { "body: $body" } - assertTrue(body.contains("4")) { "body: $body" } - } + fun `getPositionInfo parses Track, RelTime and TrackDuration`() = + runTest { + server.enqueue( + MockResponse().setBody( + """ + + + + + 3 + 0:03:30 + http://x/y.mp3 + 0:01:05 + + + + """.trimIndent(), + ), + ) + val info = client.getPositionInfo() + assertEquals(3, info.track) + assertEquals(65_000L, info.relTimeMs) + assertEquals(210_000L, info.trackDurationMs) + assertEquals("http://x/y.mp3", info.trackUri) + } @Test - fun `setAVTransportURIWithMetadata sends plain https URI for music track`() = runTest { - server.enqueue(emptyResponse("SetAVTransportURI")) - client.setAVTransportURIWithMetadata( - uri = "https://example.com/track.mp3", - mime = "audio/mpeg", - title = "Song", - ) - val body = server.takeRequest().body.readUtf8() - assertTrue(body.contains("https://example.com/track.mp3")) { - "CurrentURI should be sent as plain https: $body" + fun `getTransportInfo maps PAUSED_PLAYBACK to PAUSED`() = + runTest { + server.enqueue( + MockResponse().setBody( + """ + + + + + PAUSED_PLAYBACK + OK + 1 + + + + """.trimIndent(), + ), + ) + val info = client.getTransportInfo() + assertEquals(TransportState.PAUSED, info.state) } - assertFalse(body.contains("x-rincon-mp3radio")) { - "x-rincon-mp3radio scheme should not appear: $body" - } - } @Test - fun `getMediaInfo parses NrTracks and CurrentURI`() = runTest { - server.enqueue( - MockResponse().setBody( - """ - - - - 42 - 0:00:00 - x-rincon-queue:RINCON_ABC#0 - - - """.trimIndent(), - ), - ) - val info = client.getMediaInfo() - assertEquals(42, info.nrTracks) - assertEquals("x-rincon-queue:RINCON_ABC#0", info.currentUri) - } + fun `getTransportInfo maps unknown state to UNKNOWN`() = + runTest { + server.enqueue( + MockResponse().setBody( + """ + + + + + BUFFERING_PLAYBACK + OK + 1 + + + + """.trimIndent(), + ), + ) + val info = client.getTransportInfo() + assertEquals(TransportState.UNKNOWN, info.state) + } + + @Test + fun `addURIToQueue sends EnqueuedURI and DIDL-Lite metadata`() = + runTest { + server.enqueue(emptyResponse("AddURIToQueue")) + client.addURIToQueue( + uri = "http://x/y.mp3", + mime = "audio/mpeg", + title = "Song", + enqueuedURIPosition = 2, + ) + val body = server.takeRequest().body.readUtf8() + assertTrue(body.contains("http://x/y.mp3")) { + "body missing EnqueuedURI: $body" + } + val positionTag = "2" + assertTrue(body.contains(positionTag)) { "body missing position: $body" } + assertTrue(body.contains("<dc:title>Song</dc:title>")) { + "title missing in DIDL: $body" + } + assertTrue(body.contains("audio/mpeg")) { "mime missing: $body" } + } + + @Test + fun `seekToTrack sends TRACK_NR unit with 1-based target`() = + runTest { + server.enqueue(emptyResponse("Seek")) + client.seekToTrack(trackNumber = 4) + val body = server.takeRequest().body.readUtf8() + assertTrue(body.contains("TRACK_NR")) { "body: $body" } + assertTrue(body.contains("4")) { "body: $body" } + } + + @Test + fun `setAVTransportURIWithMetadata sends plain https URI for music track`() = + runTest { + server.enqueue(emptyResponse("SetAVTransportURI")) + client.setAVTransportURIWithMetadata( + uri = "https://example.com/track.mp3", + mime = "audio/mpeg", + title = "Song", + ) + val body = server.takeRequest().body.readUtf8() + assertTrue(body.contains("https://example.com/track.mp3")) { + "CurrentURI should be sent as plain https: $body" + } + assertFalse(body.contains("x-rincon-mp3radio")) { + "x-rincon-mp3radio scheme should not appear: $body" + } + } + + @Test + fun `getMediaInfo parses NrTracks and CurrentURI`() = + runTest { + server.enqueue( + MockResponse().setBody( + """ + + + + + 42 + 0:00:00 + x-rincon-queue:RINCON_ABC#0 + + + + """.trimIndent(), + ), + ) + val info = client.getMediaInfo() + assertEquals(42, info.nrTracks) + assertEquals("x-rincon-queue:RINCON_ABC#0", info.currentUri) + } /** * A renderer that omits NrTracks reads as 0, which callers must treat as @@ -180,68 +195,78 @@ class AVTransportClientTest { * then re-send the whole queue to a device playing it perfectly well. */ @Test - fun `getMediaInfo reports zero when the renderer omits NrTracks`() = runTest { - server.enqueue( - MockResponse().setBody( - """ - - - - http://x/y.mp3 - - - """.trimIndent(), - ), - ) - assertEquals(0, client.getMediaInfo().nrTracks) - } - - @Test - fun `setNextAVTransportURI sends NextURI with its metadata`() = runTest { - server.enqueue(emptyResponse("SetNextAVTransportURI")) - client.setNextAVTransportURI( - uri = "http://example.com/api/tracks/t2/stream.flac", - mime = "audio/flac", - title = "Next", - ) - val body = server.takeRequest().body.readUtf8() - assertTrue(body.contains("SetNextAVTransportURI")) { "body: $body" } - assertTrue(body.contains("http://example.com/api/tracks/t2/stream.flac")) { - "body: $body" + fun `getMediaInfo reports zero when the renderer omits NrTracks`() = + runTest { + server.enqueue( + MockResponse().setBody( + """ + + + + + http://x/y.mp3 + + + + """.trimIndent(), + ), + ) + assertEquals(0, client.getMediaInfo().nrTracks) } - assertTrue(body.contains("")) { "body: $body" } - } @Test - fun `a Sonos gets the Rincon metadata it requires`() = runTest { - server.enqueue(emptyResponse("SetAVTransportURI")) - client.setAVTransportURIWithMetadata("http://x/a.flac", "audio/flac", "Song") - val body = server.takeRequest().body.readUtf8() - assertTrue(body.contains("RINCON_AssociatedZPUDN")) { "body: $body" } - } + fun `setNextAVTransportURI sends NextURI with its metadata`() = + runTest { + server.enqueue(emptyResponse("SetNextAVTransportURI")) + client.setNextAVTransportURI( + uri = "http://example.com/api/tracks/t2/stream.flac", + mime = "audio/flac", + title = "Next", + ) + val body = server.takeRequest().body.readUtf8() + assertTrue(body.contains("SetNextAVTransportURI")) { "body: $body" } + assertTrue(body.contains("http://example.com/api/tracks/t2/stream.flac")) { + "body: $body" + } + assertTrue(body.contains("")) { "body: $body" } + } @Test - fun `a generic renderer gets plain DIDL that declares the stream seekable`() = runTest { - val generic = AVTransportClient( - SoapClient(OkHttpClient()), - server.url("/MediaRenderer/AVTransport/Control"), - sonos = false, + fun `a Sonos gets the Rincon metadata it requires`() = + runTest { + server.enqueue(emptyResponse("SetAVTransportURI")) + client.setAVTransportURIWithMetadata("http://x/a.flac", "audio/flac", "Song") + val body = server.takeRequest().body.readUtf8() + assertTrue(body.contains("RINCON_AssociatedZPUDN")) { "body: $body" } + } + + @Test + fun `a generic renderer gets plain DIDL that declares the stream seekable`() = + runTest { + val generic = + AVTransportClient( + SoapClient(OkHttpClient()), + server.url("/MediaRenderer/AVTransport/Control"), + sonos = false, + ) + server.enqueue(emptyResponse("SetAVTransportURI")) + generic.setAVTransportURIWithMetadata("http://x/a.flac", "audio/flac", "Song") + val body = server.takeRequest().body.readUtf8() + assertFalse(body.contains("RINCON")) { "body: $body" } + assertFalse(body.contains("rinconnetworks")) { "body: $body" } + assertTrue(body.contains("audio/flac:DLNA.ORG_OP=01")) { "body: $body" } + } + + private fun emptyResponse(action: String): MockResponse = + MockResponse().setBody( + """ + + + + + + + """.trimIndent(), ) - server.enqueue(emptyResponse("SetAVTransportURI")) - generic.setAVTransportURIWithMetadata("http://x/a.flac", "audio/flac", "Song") - val body = server.takeRequest().body.readUtf8() - assertFalse(body.contains("RINCON")) { "body: $body" } - assertFalse(body.contains("rinconnetworks")) { "body: $body" } - assertTrue(body.contains("audio/flac:DLNA.ORG_OP=01")) { "body: $body" } - } - - private fun emptyResponse(action: String): MockResponse = MockResponse().setBody( - """ - - - - - """.trimIndent(), - ) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/BareUdnTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/BareUdnTest.kt index 8de7e22b..8b748ed0 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/BareUdnTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/BareUdnTest.kt @@ -10,7 +10,6 @@ import kotlin.test.assertEquals * topology neither. Bare, they compare equal. */ class BareUdnTest { - @ParameterizedTest(name = "{0}") @CsvSource( "uuid:RINCON_ABC", diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescriptionTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescriptionTest.kt index 130be113..d69e454a 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescriptionTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/DeviceDescriptionTest.kt @@ -16,12 +16,12 @@ import kotlin.test.assertNull * lookup on the test classpath; the tests run unconditionally. */ class DeviceDescriptionTest { - private val base = "http://198.51.100.50:1400/xml/device_description.xml".toHttpUrl() @Test fun `parses Sonos-shaped description`() { - val xml = """ + val xml = + """ @@ -42,7 +42,7 @@ class DeviceDescriptionTest { - """.trimIndent() + """.trimIndent() val desc = DeviceDescription.parse(xml, base) assertNotNull(desc) @@ -63,7 +63,8 @@ class DeviceDescriptionTest { @Test fun `drops device with no AVTransport service`() { - val xml = """ + val xml = + """ @@ -77,14 +78,15 @@ class DeviceDescriptionTest { - """.trimIndent() + """.trimIndent() assertNull(DeviceDescription.parse(xml, base)) } @Test fun `parses ZoneGroupTopology control URL when present`() { - val xml = """ + val xml = + """ @@ -104,7 +106,7 @@ class DeviceDescriptionTest { - """.trimIndent() + """.trimIndent() val desc = DeviceDescription.parse(xml, base) assertNotNull(desc) assertEquals( @@ -115,7 +117,8 @@ class DeviceDescriptionTest { @Test fun `handles missing optional fields`() { - val xml = """ + val xml = + """ @@ -128,7 +131,7 @@ class DeviceDescriptionTest { - """.trimIndent() + """.trimIndent() val desc = DeviceDescription.parse(xml, base) assertNotNull(desc) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClientTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClientTest.kt index 4f65f5ef..a9b2ed3e 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClientTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/RenderingControlClientTest.kt @@ -5,15 +5,14 @@ import okhttp3.OkHttpClient import okhttp3.mockwebserver.MockResponse import okhttp3.mockwebserver.MockWebServer import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertTrue import org.junit.jupiter.api.BeforeEach import org.junit.jupiter.api.Test import org.junit.jupiter.params.ParameterizedTest import org.junit.jupiter.params.provider.CsvSource -import org.junit.jupiter.api.Assertions.assertEquals -import org.junit.jupiter.api.Assertions.assertTrue class RenderingControlClientTest { - private lateinit var server: MockWebServer private lateinit var client: RenderingControlClient @@ -25,40 +24,56 @@ class RenderingControlClientTest { } @AfterEach - fun tearDown() { server.shutdown() } + fun tearDown() { + server.shutdown() + } @Test - fun `getVolume parses CurrentVolume`() = runTest { - server.enqueue(MockResponse().setBody( - """ - - - - 42 - - - """.trimIndent())) - assertEquals(42, client.getVolume()) - val request = server.takeRequest() - val body = request.body.readUtf8() - assertTrue(body.contains("Master")) { body } - assertEquals( - "\"urn:schemas-upnp-org:service:RenderingControl:1#GetVolume\"", - request.getHeader("SOAPACTION"), - ) - } + fun `getVolume parses CurrentVolume`() = + runTest { + server.enqueue( + MockResponse().setBody( + """ + + + + + 42 + + + + """.trimIndent(), + ), + ) + assertEquals(42, client.getVolume()) + val request = server.takeRequest() + val body = request.body.readUtf8() + assertTrue(body.contains("Master")) { body } + assertEquals( + "\"urn:schemas-upnp-org:service:RenderingControl:1#GetVolume\"", + request.getHeader("SOAPACTION"), + ) + } @ParameterizedTest(name = "{0} -> {1}") @CsvSource("150, 100", "-5, 0", "40, 40") - fun `setVolume clamps to the renderer's range and sends DesiredVolume`(asked: Int, sent: Int) = runTest { - server.enqueue(MockResponse().setBody( - """ - - - - - """.trimIndent())) + fun `setVolume clamps to the renderer's range and sends DesiredVolume`( + asked: Int, + sent: Int, + ) = runTest { + server.enqueue( + MockResponse().setBody( + """ + + + + + + + """.trimIndent(), + ), + ) client.setVolume(asked) val body = server.takeRequest().body.readUtf8() assertTrue(body.contains("$sent")) { body } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/SoapClientTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/SoapClientTest.kt index d0decd5e..27e4be51 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/SoapClientTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/SoapClientTest.kt @@ -35,86 +35,92 @@ class SoapClientTest { } @Test - fun `SetAVTransportURI envelope sent with correct SOAPACTION header`() = runTest { - server.enqueue( - MockResponse() - .setBody(setUriResponseBody()) - .setHeader("Content-Type", "text/xml"), - ) + fun `SetAVTransportURI envelope sent with correct SOAPACTION header`() = + runTest { + server.enqueue( + MockResponse() + .setBody(setUriResponseBody()) + .setHeader("Content-Type", "text/xml"), + ) - client.call( - controlUrl = server.url("/avt/Control"), - serviceType = "urn:schemas-upnp-org:service:AVTransport:1", - action = "SetAVTransportURI", - args = mapOf( - "InstanceID" to "0", - "CurrentURI" to "http://server/api/tracks/x/stream?token=t&exp=1", - "CurrentURIMetaData" to "", - ), - ) - - val recorded = server.takeRequest() - assertEquals( - "\"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI\"", - recorded.getHeader("SOAPACTION"), - ) - val body = recorded.body.readUtf8() - assertTrue( - body.contains("http://server/api/tracks/x/stream?token=t&exp=1", - ), - "envelope missing escaped CurrentURI: $body", - ) - } - - @Test - fun `XML special chars in args are escaped`() = runTest { - server.enqueue( - MockResponse() - .setBody(setUriResponseBody()) - .setHeader("Content-Type", "text/xml"), - ) - - client.call( - controlUrl = server.url("/avt/Control"), - serviceType = "urn:schemas-upnp-org:service:AVTransport:1", - action = "SetAVTransportURI", - args = mapOf("CurrentURI" to "a&b\"d'e"), - ) - - val recorded = server.takeRequest() - val body = recorded.body.readUtf8() - assertTrue( - body.contains("a&b<c>"d'e"), - "expected all five XML escapes in body, got: $body", - ) - } - - @Test - fun `SOAP fault becomes SoapFaultException`() = runTest { - server.enqueue( - MockResponse() - .setResponseCode(500) - .setBody(faultResponseBody()) - .setHeader("Content-Type", "text/xml"), - ) - - val ex = assertFailsWith { client.call( controlUrl = server.url("/avt/Control"), serviceType = "urn:schemas-upnp-org:service:AVTransport:1", - action = "Play", - args = mapOf("InstanceID" to "0", "Speed" to "1"), + action = "SetAVTransportURI", + args = + mapOf( + "InstanceID" to "0", + "CurrentURI" to "http://server/api/tracks/x/stream?token=t&exp=1", + "CurrentURIMetaData" to "", + ), + ) + + val recorded = server.takeRequest() + assertEquals( + "\"urn:schemas-upnp-org:service:AVTransport:1#SetAVTransportURI\"", + recorded.getHeader("SOAPACTION"), + ) + val body = recorded.body.readUtf8() + assertTrue( + body.contains("http://server/api/tracks/x/stream?token=t&exp=1", + ), + "envelope missing escaped CurrentURI: $body", ) } - assertEquals("402", ex.code) - } - private fun setUriResponseBody(): String = """ + @Test + fun `XML special chars in args are escaped`() = + runTest { + server.enqueue( + MockResponse() + .setBody(setUriResponseBody()) + .setHeader("Content-Type", "text/xml"), + ) + + client.call( + controlUrl = server.url("/avt/Control"), + serviceType = "urn:schemas-upnp-org:service:AVTransport:1", + action = "SetAVTransportURI", + args = mapOf("CurrentURI" to "a&b\"d'e"), + ) + + val recorded = server.takeRequest() + val body = recorded.body.readUtf8() + assertTrue( + body.contains("a&b<c>"d'e"), + "expected all five XML escapes in body, got: $body", + ) + } + + @Test + fun `SOAP fault becomes SoapFaultException`() = + runTest { + server.enqueue( + MockResponse() + .setResponseCode(500) + .setBody(faultResponseBody()) + .setHeader("Content-Type", "text/xml"), + ) + + val ex = + assertFailsWith { + client.call( + controlUrl = server.url("/avt/Control"), + serviceType = "urn:schemas-upnp-org:service:AVTransport:1", + action = "Play", + args = mapOf("InstanceID" to "0", "Speed" to "1"), + ) + } + assertEquals("402", ex.code) + } + + private fun setUriResponseBody(): String = + """ @@ -123,9 +129,10 @@ class SoapClientTest { xmlns:u="urn:schemas-upnp-org:service:AVTransport:1"/> - """.trimIndent() + """.trimIndent() - private fun faultResponseBody(): String = """ + private fun faultResponseBody(): String = + """ @@ -142,5 +149,5 @@ class SoapClientTest { - """.trimIndent() + """.trimIndent() } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopologyTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopologyTest.kt index ef05ea95..53c253ed 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopologyTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/player/output/upnp/sonos/SonosTopologyTest.kt @@ -5,10 +5,10 @@ import kotlin.test.assertEquals import kotlin.test.assertNotNull class SonosTopologyTest { - @Test fun `single zone group with one member`() { - val xml = """ + val xml = + """ @@ -17,7 +17,7 @@ class SonosTopologyTest { - """.trimIndent() + """.trimIndent() val groups = SonosTopology.parse(xml) assertEquals(1, groups.size) val g = groups.first() @@ -28,7 +28,8 @@ class SonosTopologyTest { @Test fun `stereo pair collapses to one group with two members`() { - val xml = """ + val xml = + """ @@ -41,7 +42,7 @@ class SonosTopologyTest { - """.trimIndent() + """.trimIndent() val groups = SonosTopology.parse(xml) assertEquals(1, groups.size) val g = groups.first() @@ -53,7 +54,8 @@ class SonosTopologyTest { @Test fun `multi-speaker group lists coordinator name`() { - val xml = """ + val xml = + """ @@ -62,7 +64,7 @@ class SonosTopologyTest { - """.trimIndent() + """.trimIndent() val groups = SonosTopology.parse(xml) assertEquals("Office", groups.first().name) } @@ -77,7 +79,8 @@ class SonosTopologyTest { // Some Sonos firmware sends the topology as nested elements with // no escaping. After SoapClient.readUntilEndTag rebuilds a flat // string, parse should still find the groups. - val xml = """ + val xml = + """ @@ -86,14 +89,15 @@ class SonosTopologyTest { - """.trimIndent() + """.trimIndent() val groups = SonosTopology.parse(xml) assertEquals(1, groups.size) } @Test fun `parses escaped ZoneGroupState wrapped in entities`() { - val xml = """ + val xml = + """ <ZoneGroupState> <ZoneGroups> <ZoneGroup Coordinator="RINCON_A" ID="RINCON_A:1"> @@ -102,7 +106,7 @@ class SonosTopologyTest { </ZoneGroup> </ZoneGroups> </ZoneGroupState> - """.trimIndent() + """.trimIndent() val groups = SonosTopology.parse(xml) assertEquals(1, groups.size) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/ShelfTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/ShelfTest.kt index f9a0cada..74ad7176 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/playlists/ShelfTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/ShelfTest.kt @@ -11,7 +11,6 @@ import kotlin.test.assertEquals import kotlin.test.assertTrue class ShelfTest { - private val utc = ZoneOffset.UTC private val now = Instant.parse("2026-11-23T15:00:00Z") @@ -33,19 +32,21 @@ class ShelfTest { @Test fun `each tile takes the first album no earlier tile shows`() { - val got = assignShelfCovers( - listOf(mix(listOf("a", "b", "c")), mix(listOf("a", "d")), mix(listOf("a", "d", "e"))), - perTile = 1, - ) + val got = + assignShelfCovers( + listOf(mix(listOf("a", "b", "c")), mix(listOf("a", "d")), mix(listOf("a", "d", "e"))), + perTile = 1, + ) assertEquals(listOf(listOf("a"), listOf("d"), listOf("e")), got) } @Test fun `a band takes three unused albums`() { - val got = assignShelfCovers( - listOf(mix(listOf("a", "b", "c", "d")), mix(listOf("b", "c", "e", "f", "g"))), - perTile = 3, - ) + val got = + assignShelfCovers( + listOf(mix(listOf("a", "b", "c", "d")), mix(listOf("b", "c", "e", "f", "g"))), + perTile = 3, + ) assertEquals(listOf(listOf("a", "b", "c"), listOf("e", "f", "g")), got) } @@ -108,7 +109,10 @@ class ShelfTest { // the web client's tiles also hold to. @ParameterizedTest(name = "{0} cover") @MethodSource("lightCovers") - fun `a light or loud cover still leaves the faintest text at 4_5 to 1`(name: String, cover: Rgb) { + fun `a light or loud cover still leaves the faintest text at 4_5 to 1`( + name: String, + cover: Rgb, + ) { val ground = blend(washTone(cover).toD(), 0.62, Triple(14.0, 16.0, 19.0)) val text = blend(Triple(232.0, 228.0, 216.0), 0.8, ground) val ratio = (lum(text) + 0.05) / (lum(ground) + 0.05) @@ -117,7 +121,11 @@ class ShelfTest { private fun Rgb.toD() = Triple(r.toDouble(), g.toDouble(), b.toDouble()) - private fun blend(a: Triple, t: Double, b: Triple) = Triple( + private fun blend( + a: Triple, + t: Double, + b: Triple, + ) = Triple( a.first * t + b.first * (1 - t), a.second * t + b.second * (1 - t), a.third * t + b.third * (1 - t), @@ -133,11 +141,12 @@ class ShelfTest { companion object { @JvmStatic - fun lightCovers() = listOf( - arrayOf("beige", Rgb(200, 190, 160)), - arrayOf("near white", Rgb(245, 245, 245)), - arrayOf("acid yellow", Rgb(240, 240, 20)), - arrayOf("light grey", Rgb(170, 175, 180)), - ) + fun lightCovers() = + listOf( + arrayOf("beige", Rgb(200, 190, 160)), + arrayOf("near white", Rgb(245, 245, 245)), + arrayOf("acid yellow", Rgb(240, 240, 20)), + arrayOf("light grey", Rgb(170, 175, 180)), + ) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt index 6a091be4..a55a83f3 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistEditsTest.kt @@ -8,8 +8,10 @@ import kotlin.test.assertSame /** How the playlist screen shows a change before the server's copy comes back. */ class PlaylistEditsTest { - - private fun row(position: Int, trackId: String?) = PlaylistTrackRef( + private fun row( + position: Int, + trackId: String?, + ) = PlaylistTrackRef( position = position, trackId = trackId, title = trackId ?: "gone", @@ -17,10 +19,11 @@ class PlaylistEditsTest { artistId = null, ) - private fun detail(vararg ids: String?) = PlaylistDetailRef( - playlist = PlaylistRef(id = "p", userId = "me", name = "Road Songs", trackCount = ids.size), - tracks = ids.mapIndexed { i, id -> row(i, id) }, - ) + private fun detail(vararg ids: String?) = + PlaylistDetailRef( + playlist = PlaylistRef(id = "p", userId = "me", name = "Road Songs", trackCount = ids.size), + tracks = ids.mapIndexed { i, id -> row(i, id) }, + ) private fun PlaylistDetailRef.ids() = tracks.map { it.trackId } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistTrackAvailabilityTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistTrackAvailabilityTest.kt index ae19726f..bcfe1f6e 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistTrackAvailabilityTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistTrackAvailabilityTest.kt @@ -13,7 +13,6 @@ import kotlin.test.assertTrue * from the list the user curated. */ class PlaylistTrackAvailabilityTest { - private fun row( position: Int = 0, trackId: String? = "t-$position", @@ -59,12 +58,13 @@ class PlaylistTrackAvailabilityTest { @Test fun `queue building drops both kinds of dead row and keeps the rest`() { - val queue = listOf( - row(position = 0), - row(position = 1, trackId = null, streamUrl = null), - row(position = 2, unavailable = true, streamUrl = null), - row(position = 3), - ).toPlayableTrackRefs() + val queue = + listOf( + row(position = 0), + row(position = 1, trackId = null, streamUrl = null), + row(position = 2, unavailable = true, streamUrl = null), + row(position = 3), + ).toPlayableTrackRefs() assertEquals(listOf("t-0", "t-3"), queue.map { it.id }) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt index c30a3d65..60909447 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryCacheMergeTest.kt @@ -8,9 +8,10 @@ import org.junit.jupiter.params.provider.CsvSource import kotlin.test.assertEquals class PlaylistsRepositoryCacheMergeTest { - - private fun playlist(id: String, trackCount: Int) = - CachedPlaylistEntity(id = id, userId = "u", name = id, trackCount = trackCount) + private fun playlist( + id: String, + trackCount: Int, + ) = CachedPlaylistEntity(id = id, userId = "u", name = id, trackCount = trackCount) // Fully cached means every member track is resident; an empty playlist // never is, and no count row means nothing is resident. @@ -21,23 +22,30 @@ class PlaylistsRepositoryCacheMergeTest { ", 3, false", "0, 0, false", ) - fun `fully cached only when every track is resident`(cached: Int?, tracks: Int, want: Boolean) { - val out = mergePlaylistsWithCache( - rows = listOf(playlist("p", trackCount = tracks)), - counts = listOfNotNull(cached?.let { PlaylistCachedCount("p", cachedCount = it) }), - ) + fun `fully cached only when every track is resident`( + cached: Int?, + tracks: Int, + want: Boolean, + ) { + val out = + mergePlaylistsWithCache( + rows = listOf(playlist("p", trackCount = tracks)), + counts = listOfNotNull(cached?.let { PlaylistCachedCount("p", cachedCount = it) }), + ) assertEquals(want, out.single().fullyCached) } @Test fun `each playlist gets its own cache verdict`() { - val out = mergePlaylistsWithCache( - rows = listOf(playlist("full", 2), playlist("partial", 2)), - counts = listOf( - PlaylistCachedCount("full", cachedCount = 2), - PlaylistCachedCount("partial", cachedCount = 1), - ), - ) + val out = + mergePlaylistsWithCache( + rows = listOf(playlist("full", 2), playlist("partial", 2)), + counts = + listOf( + PlaylistCachedCount("full", cachedCount = 2), + PlaylistCachedCount("partial", cachedCount = 1), + ), + ) val byId = out.associateBy { it.id } assertEquals(true, byId.getValue("full").fullyCached) assertEquals(false, byId.getValue("partial").fullyCached) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt index 4abc740c..4211410e 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/playlists/data/PlaylistsRepositoryWritesTest.kt @@ -42,101 +42,111 @@ class PlaylistsRepositoryWritesTest { private val playlistDao: CachedPlaylistDao = mockk(relaxed = true) private val trackDao: CachedPlaylistTrackDao = mockk(relaxed = true) private val queue: MutationQueue = mockk(relaxed = true) - private val auth: AuthController = mockk { - every { currentUser } returns MutableStateFlow(UserRef(id = "me", username = "me")) - } - private val retrofit: Retrofit = mockk { - every { create(PlaylistsApi::class.java) } returns api - } + private val auth: AuthController = + mockk { + every { currentUser } returns MutableStateFlow(UserRef(id = "me", username = "me")) + } + private val retrofit: Retrofit = + mockk { + every { create(PlaylistsApi::class.java) } returns api + } private val repo = PlaylistsRepository(playlistDao, trackDao, queue, auth, retrofit) @Test - fun `a new playlist is shown at once and sent under the id the device made`() = runTest { - val sent = slot() - coEvery { api.create(capture(sent)) } returns Unit - val shown = slot>() - coEvery { playlistDao.upsertAll(capture(shown)) } returns Unit + fun `a new playlist is shown at once and sent under the id the device made`() = + runTest { + val sent = slot() + coEvery { api.create(capture(sent)) } returns Unit + val shown = slot>() + coEvery { playlistDao.upsertAll(capture(shown)) } returns Unit - val (id, outcome) = repo.createPlaylist("Road Songs") + val (id, outcome) = repo.createPlaylist("Road Songs") - assertEquals(WriteOutcome.Synced, outcome) - assertEquals(id, sent.captured.id) - assertEquals(listOf(id), shown.captured.map { it.id }) - assertEquals("me", shown.captured.single().userId) - coVerify(exactly = 0) { queue.enqueuePlaylistCreate(any()) } - } + assertEquals(WriteOutcome.Synced, outcome) + assertEquals(id, sent.captured.id) + assertEquals(listOf(id), shown.captured.map { it.id }) + assertEquals("me", shown.captured.single().userId) + coVerify(exactly = 0) { queue.enqueuePlaylistCreate(any()) } + } @Test - fun `a new playlist made offline is queued under the same id`() = runTest { - coEvery { api.create(any()) } throws IOException("offline") - val queued = slot() - coEvery { queue.enqueuePlaylistCreate(capture(queued)) } returns 1L + fun `a new playlist made offline is queued under the same id`() = + runTest { + coEvery { api.create(any()) } throws IOException("offline") + val queued = slot() + coEvery { queue.enqueuePlaylistCreate(capture(queued)) } returns 1L - val (id, outcome) = repo.createPlaylist("Road Songs") + val (id, outcome) = repo.createPlaylist("Road Songs") - assertEquals(WriteOutcome.Queued, outcome) - assertEquals(PlaylistCreatePayload(id = id, name = "Road Songs"), queued.captured) - } + assertEquals(WriteOutcome.Queued, outcome) + assertEquals(PlaylistCreatePayload(id = id, name = "Road Songs"), queued.captured) + } @Test - fun `an append whose reply is lost is queued under the request id it was sent with`() = runTest { - val sent = slot() - coEvery { api.appendTracks("p1", capture(sent)) } throws IOException("reply lost") - val queued = slot() - coEvery { queue.enqueuePlaylistAppend(capture(queued)) } returns 1L + fun `an append whose reply is lost is queued under the request id it was sent with`() = + runTest { + val sent = slot() + coEvery { api.appendTracks("p1", capture(sent)) } throws IOException("reply lost") + val queued = slot() + coEvery { queue.enqueuePlaylistAppend(capture(queued)) } returns 1L - val outcome = repo.appendTrack("p1", "t1") + val outcome = repo.appendTrack("p1", "t1") - assertEquals(WriteOutcome.Queued, outcome) - assertNotNull(sent.captured.requestId) - assertEquals(PlaylistAppendPayload("p1", listOf("t1"), sent.captured.requestId), queued.captured) - } + assertEquals(WriteOutcome.Queued, outcome) + assertNotNull(sent.captured.requestId) + assertEquals(PlaylistAppendPayload("p1", listOf("t1"), sent.captured.requestId), queued.captured) + } @Test - fun `a removal made offline is queued with the song expected at that place`() = runTest { - coEvery { api.removeTrack(any(), any(), any()) } throws IOException("offline") + fun `a removal made offline is queued with the song expected at that place`() = + runTest { + coEvery { api.removeTrack(any(), any(), any()) } throws IOException("offline") - repo.removeTrack("p1", position = 2, trackId = "t3") + repo.removeTrack("p1", position = 2, trackId = "t3") - coVerify { trackDao.deleteTracksFromPlaylist("p1", listOf("t3")) } - coVerify { queue.enqueuePlaylistRemoveTrack(PlaylistRemoveTrackPayload("p1", 2, "t3")) } - } + coVerify { trackDao.deleteTracksFromPlaylist("p1", listOf("t3")) } + coVerify { queue.enqueuePlaylistRemoveTrack(PlaylistRemoveTrackPayload("p1", 2, "t3")) } + } @Test - fun `a reorder sends the songs in their new order`() = runTest { - repo.reorderTracks("p1", listOf("t2", "t1")) + fun `a reorder sends the songs in their new order`() = + runTest { + repo.reorderTracks("p1", listOf("t2", "t1")) - coVerify { api.reorder("p1", ReorderTracksRequest(trackIds = listOf("t2", "t1"))) } - coVerify(exactly = 0) { queue.enqueuePlaylistReorder(any()) } - } + coVerify { api.reorder("p1", ReorderTracksRequest(trackIds = listOf("t2", "t1"))) } + coVerify(exactly = 0) { queue.enqueuePlaylistReorder(any()) } + } @Test - fun `a reorder made offline is queued`() = runTest { - coEvery { api.reorder(any(), any()) } throws IOException("offline") + fun `a reorder made offline is queued`() = + runTest { + coEvery { api.reorder(any(), any()) } throws IOException("offline") - repo.reorderTracks("p1", listOf("t2", "t1")) + repo.reorderTracks("p1", listOf("t2", "t1")) - coVerify { queue.enqueuePlaylistReorder(PlaylistReorderPayload("p1", listOf("t2", "t1"))) } - } + coVerify { queue.enqueuePlaylistReorder(PlaylistReorderPayload("p1", listOf("t2", "t1"))) } + } @Test - fun `a change the server refuses is not queued`() = runTest { - coEvery { api.delete("p1") } throws HttpException(Response.error(403, "".toResponseBody())) + fun `a change the server refuses is not queued`() = + runTest { + coEvery { api.delete("p1") } throws HttpException(Response.error(403, "".toResponseBody())) - val result = runCatching { repo.deletePlaylist("p1") } + val result = runCatching { repo.deletePlaylist("p1") } - assertTrue(result.exceptionOrNull() is HttpException) + assertTrue(result.exceptionOrNull() is HttpException) - coVerify(exactly = 0) { queue.enqueuePlaylistDelete(any()) } - } + coVerify(exactly = 0) { queue.enqueuePlaylistDelete(any()) } + } @Test - fun `a list refresh keeps a playlist whose create hasn't been sent`() = runTest { - coEvery { api.list(any()) } returns PlaylistsListWire() - coEvery { queue.pendingPlaylistCreateIds() } returns setOf("made-offline") + fun `a list refresh keeps a playlist whose create hasn't been sent`() = + runTest { + coEvery { api.list(any()) } returns PlaylistsListWire() + coEvery { queue.pendingPlaylistCreateIds() } returns setOf("made-offline") - repo.refreshList() + repo.refreshList() - coVerify { playlistDao.replaceList("me", listOf("made-offline"), emptyList()) } - } + coVerify { playlistDao.replaceList("me", listOf("made-offline"), emptyList()) } + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/settings/data/NormalizationRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/settings/data/NormalizationRepositoryTest.kt index f47f0160..d379ef3e 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/settings/data/NormalizationRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/settings/data/NormalizationRepositoryTest.kt @@ -23,68 +23,75 @@ import java.io.IOException */ class NormalizationRepositoryTest { private val api: MeApi = mockk() - private val authStore: AuthStore = mockk(relaxed = true) { - every { normalization } returns MutableStateFlow(NormalizationPrefs.DEFAULT) - } + private val authStore: AuthStore = + mockk(relaxed = true) { + every { normalization } returns MutableStateFlow(NormalizationPrefs.DEFAULT) + } private val queue: MutationQueue = mockk(relaxed = true) private val dao: CachedMutationDao = mockk() - private val retrofit: Retrofit = mockk { - every { create(MeApi::class.java) } returns api - } + private val retrofit: Retrofit = + mockk { + every { create(MeApi::class.java) } returns api + } private val repo = NormalizationRepository(retrofit, authStore, queue, dao) private val album = NormalizationPrefs.DEFAULT.copy(mode = NormalizationMode.ALBUM) @Test - fun `a change is shown at once and sent`() = runTest { - coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns false - coEvery { api.putNormalization(album) } returns album + fun `a change is shown at once and sent`() = + runTest { + coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns false + coEvery { api.putNormalization(album) } returns album - repo.set(album) + repo.set(album) - verify { authStore.setNormalization(album) } - coVerify { api.putNormalization(album) } - coVerify(exactly = 0) { queue.enqueueNormalizationSet(any()) } - } + verify { authStore.setNormalization(album) } + coVerify { api.putNormalization(album) } + coVerify(exactly = 0) { queue.enqueueNormalizationSet(any()) } + } @Test - fun `a change that cannot reach the server is queued`() = runTest { - coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns false - coEvery { api.putNormalization(album) } throws IOException("offline") + fun `a change that cannot reach the server is queued`() = + runTest { + coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns false + coEvery { api.putNormalization(album) } throws IOException("offline") - repo.set(album) + repo.set(album) - verify { authStore.setNormalization(album) } - coVerify { queue.enqueueNormalizationSet(album) } - } + verify { authStore.setNormalization(album) } + coVerify { queue.enqueueNormalizationSet(album) } + } @Test - fun `a change behind a queued one queues too, so the older one cannot land last`() = runTest { - coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns true + fun `a change behind a queued one queues too, so the older one cannot land last`() = + runTest { + coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns true - repo.set(album) + repo.set(album) - coVerify(exactly = 0) { api.putNormalization(any()) } - coVerify { queue.enqueueNormalizationSet(album) } - } + coVerify(exactly = 0) { api.putNormalization(any()) } + coVerify { queue.enqueueNormalizationSet(album) } + } @Test - fun `refresh takes the server value`() = runTest { - coEvery { api.getNormalization() } returns album - coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns false + fun `refresh takes the server value`() = + runTest { + coEvery { api.getNormalization() } returns album + coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns false - repo.refresh() + repo.refresh() - verify { authStore.setNormalization(album) } - } + verify { authStore.setNormalization(album) } + } @Test - fun `refresh leaves a queued change on screen`() = runTest { - coEvery { api.getNormalization() } returns NormalizationPrefs.DEFAULT - coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns true + fun `refresh leaves a queued change on screen`() = + runTest { + coEvery { api.getNormalization() } returns NormalizationPrefs.DEFAULT + coEvery { dao.hasPending(MutationKind.NORMALIZATION_SET) } returns true - repo.refresh() + repo.refresh() - verify(exactly = 0) { authStore.setNormalization(any()) } - } + verify(exactly = 0) { authStore.setNormalization(any()) } + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/PasswordViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/PasswordViewModelTest.kt index f169f638..12e875eb 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/PasswordViewModelTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/PasswordViewModelTest.kt @@ -17,7 +17,10 @@ import kotlin.test.assertEquals class PasswordViewModelTest { private val repository: MeRepository = mockk(relaxed = true) - private fun attempt(next: String, confirm: String): PasswordViewModel = + private fun attempt( + next: String, + confirm: String, + ): PasswordViewModel = PasswordViewModel(repository).apply { setCurrent("old-password") setNext(next) diff --git a/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/ProfileViewModelTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/ProfileViewModelTest.kt index 7af1912b..00be34a8 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/ProfileViewModelTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/settings/ui/ProfileViewModelTest.kt @@ -20,19 +20,21 @@ import kotlin.test.assertNull */ @ExtendWith(MainDispatcherExtension::class) class ProfileViewModelTest { - private val profile = MyProfile( - id = "u1", - username = "listener", - displayName = "A Listener", - email = "listener@example.com", - isAdmin = false, - ) + private val profile = + MyProfile( + id = "u1", + username = "listener", + displayName = "A Listener", + email = "listener@example.com", + isAdmin = false, + ) @Test fun `a failed load is a load error, not a form message`() { - val repository: MeRepository = mockk { - coEvery { getProfile() } throws IOException("unreachable") - } + val repository: MeRepository = + mockk { + coEvery { getProfile() } throws IOException("unreachable") + } val state = ProfileViewModel(repository).state.value diff --git a/android/app/src/test/java/com/fabledsword/minstrel/shared/PluralTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/shared/PluralTest.kt index c502fade..56ae0e67 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/shared/PluralTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/shared/PluralTest.kt @@ -26,12 +26,13 @@ class PluralTest { // - the number beside a choice of noun: `"${n} ${if (n == 1) ...}"`; // - a choice of noun alone: `if (n == 1) "track" else "tracks"`; // - a count with a fixed plural, which reads "1 tracks": `"${x.trackCount} tracks"`. - private val handRolled = listOf( - Regex("""== 1\) "1 """), - Regex("""\$\{?([\w.]+)\}? \$\{if \(\1 == 1\)"""), - Regex("""== 1\) "[a-z]+" else "[a-z]+s""""), - Regex("""\$\{[\w.]+(?:Count|\.size)\} (?:tracks|albums|songs|artists|playlists|files|users)\b"""), - ) + private val handRolled = + listOf( + Regex("""== 1\) "1 """), + Regex("""\$\{?([\w.]+)\}? \$\{if \(\1 == 1\)"""), + Regex("""== 1\) "[a-z]+" else "[a-z]+s""""), + Regex("""\$\{[\w.]+(?:Count|\.size)\} (?:tracks|albums|songs|artists|playlists|files|users)\b"""), + ) /** Comments describe the forbidden shape; strip them before asserting its absence. */ private fun stripComments(s: String) = s.replace(Regex("""^\s*(//|\*|/\*).*$""", RegexOption.MULTILINE), "") @@ -41,10 +42,12 @@ class PluralTest { val root = File("src/main/java") val sources = root.walkTopDown().filter { it.extension == "kt" }.toList() assertTrue(sources.size > 100, "expected the app's sources under ${root.absolutePath}") - val offenders = sources.filter { f -> - val text = stripComments(f.readText()) - handRolled.any { it.containsMatchIn(text) } - }.map { it.relativeTo(root).path } + val offenders = + sources + .filter { f -> + val text = stripComments(f.readText()) + handRolled.any { it.containsMatchIn(text) } + }.map { it.relativeTo(root).path } assertEquals(emptyList(), offenders) } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/shared/UpdateVeilControllerTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/shared/UpdateVeilControllerTest.kt index 733fc8e4..a8d6b9f6 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/shared/UpdateVeilControllerTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/shared/UpdateVeilControllerTest.kt @@ -45,22 +45,25 @@ private const val DRAIN_MS = 3_000L */ @OptIn(ExperimentalCoroutinesApi::class) class UpdateVeilControllerTest { - - private val timings = VeilTimings( - minHoldMs = 900, - quietMs = 700, - maxHoldMs = 12_000, - attempts = 3, - retryBackoffMs = 600, - ) + private val timings = + VeilTimings( + minHoldMs = 900, + quietMs = 700, + maxHoldMs = 12_000, + attempts = 3, + retryBackoffMs = 600, + ) /** Drives the settle signal by hand: content key, presence, art count. */ - private class FakeScreen(hasContent: Boolean = true) { + private class FakeScreen( + hasContent: Boolean = true, + ) { val state = MutableStateFlow(Triple(0, hasContent, 0)) - val signal = state.map { (key, hasContent, art) -> - VeilSettleState(contentKey = key, hasContent = hasContent, quiescent = art == 0) - } + val signal = + state.map { (key, hasContent, art) -> + VeilSettleState(contentKey = key, hasContent = hasContent, quiescent = art == 0) + } /** Content visibly changed — what the veil exists to cover. */ fun churn() { @@ -98,176 +101,188 @@ class UpdateVeilControllerTest { } @Test - fun `veil outlasts content that keeps churning after the pull returns`() = runTest { - val screen = FakeScreen() - val controller = controllerOn(screen) { true } + fun `veil outlasts content that keeps churning after the pull returns`() = + runTest { + val screen = FakeScreen() + val controller = controllerOn(screen) { true } - controller.request() - runCurrent() - // The pull's write lands: content changed, so the veil goes up. - screen.churn() - runCurrent() - assertTrue(controller.visible.value, "veil is up while the screen is still moving") - - // Tiles hydrating one after another, each inside the quiet window. - // The old implementation had already wiped off after a flat 500ms. - repeat(CHURN_ROUNDS) { - advanceTimeBy(timings.quietMs / 2) + controller.request() + runCurrent() + // The pull's write lands: content changed, so the veil goes up. screen.churn() runCurrent() - assertTrue(controller.visible.value, "veil must hold across staged churn") + assertTrue(controller.visible.value, "veil is up while the screen is still moving") + + // Tiles hydrating one after another, each inside the quiet window. + // The old implementation had already wiped off after a flat 500ms. + repeat(CHURN_ROUNDS) { + advanceTimeBy(timings.quietMs / 2) + screen.churn() + runCurrent() + assertTrue(controller.visible.value, "veil must hold across staged churn") + } + + advanceTimeBy(DRAIN_MS) + assertFalse(controller.visible.value, "veil lowers once the screen goes quiet") } - advanceTimeBy(DRAIN_MS) - assertFalse(controller.visible.value, "veil lowers once the screen goes quiet") - } - @Test - fun `veil waits for artwork to finish loading`() = runTest { - val screen = FakeScreen() - val controller = controllerOn(screen) { true } + fun `veil waits for artwork to finish loading`() = + runTest { + val screen = FakeScreen() + val controller = controllerOn(screen) { true } - screen.artLoading(ART_IN_FLIGHT) - controller.request() - runCurrent() - screen.churn() - runCurrent() - // Well past the quiet window and the floor — but art is still in - // flight, so lowering now would show the covers popping in. - advanceTimeBy(timings.minHoldMs + timings.quietMs * QUIET_WINDOWS_TO_OUTLAST) - assertTrue(controller.visible.value, "veil must wait on in-flight art") - - screen.artLoading(0) - advanceTimeBy(DRAIN_MS) - assertFalse(controller.visible.value, "veil lowers once art has landed") - } - - @Test - fun `retries quietly, then veils the churn the successful attempt produces`() = runTest { - val screen = FakeScreen() - var attempts = 0 - val controller = controllerOn(screen) { - attempts++ - val succeeded = attempts >= SUCCEED_ON_ATTEMPT // fail twice - // Only a pull that worked writes anything. - if (succeeded) screen.churn() - succeeded - } - val seen = recordVisibility(controller) - - controller.request() - runCurrent() - // A failed pull changes nothing, so there is nothing to hide yet — - // the retries happen with no veil at all. - assertFalse(controller.visible.value, "no veil over a pull that changed nothing") - - advanceTimeBy(DRAIN_MS) - assertEquals(SUCCEED_ON_ATTEMPT, attempts, "retries until the pull succeeds") - assertEquals( - listOf(false, true, false), - seen, - "the veil went up once, over the churn the retry finally produced", - ) - } - - @Test - fun `giving up is silent, reports FAILED, and does not block later requests`() = runTest { - val screen = FakeScreen() - val results = mutableListOf() - var attempts = 0 - var succeed = false - val controller = controllerOn(screen, onSessionEnd = { results += it }) { - attempts++ - succeed - } - - controller.request(userInitiated = true) - advanceTimeBy(DRAIN_MS) - assertEquals(timings.attempts, attempts, "exhausts its attempts") - assertFalse(controller.visible.value, "no veil — a failed pull changed nothing") - assertEquals(VeilOutcome.FAILED, results.single().outcome) - assertTrue(results.single().userInitiated, "the user asked, so they're owed an answer") - - // Giving up must not latch anything off — the reconnect-driven - // recovery still gets to try again later. - succeed = true - controller.request() - advanceTimeBy(DRAIN_MS) - assertEquals(timings.attempts + 1, attempts, "a later request still runs") - } - - @Test - fun `overlapping requests extend one veil instead of racing it`() = runTest { - val screen = FakeScreen() - var started = 0 - val controller = controllerOn(screen) { - started++ - delay(WORK_MS) + screen.artLoading(ART_IN_FLIGHT) + controller.request() + runCurrent() screen.churn() - true - } - val seen = recordVisibility(controller) + runCurrent() + // Well past the quiet window and the floor — but art is still in + // flight, so lowering now would show the covers popping in. + advanceTimeBy(timings.minHoldMs + timings.quietMs * QUIET_WINDOWS_TO_OUTLAST) + assertTrue(controller.visible.value, "veil must wait on in-flight art") - // Reconnect and the rebuild event arriving together is what made the - // old Boolean flag clear mid-update: whichever pull finished first - // wiped the veil off while the other was still running. - controller.request() - runCurrent() - controller.request() - advanceTimeBy(WORK_MS + 1) - assertTrue(controller.visible.value, "second trigger extends the same veil") - - advanceTimeBy(DRAIN_MS) - assertEquals(2, started, "the mid-session trigger still did its pull") - assertEquals(listOf(false, true, false), seen, "one veil session, not two") - } - - @Test - fun `a never-settling screen still releases the veil at the ceiling`() = runTest { - val screen = FakeScreen() - val controller = controllerOn(screen) { - screen.churn() - true + screen.artLoading(0) + advanceTimeBy(DRAIN_MS) + assertFalse(controller.visible.value, "veil lowers once art has landed") } - screen.artLoading(1) // an image that never completes - controller.request() - advanceTimeBy(timings.maxHoldMs + 1) - assertFalse(controller.visible.value, "the hard ceiling must never strand the user") - } + @Test + fun `retries quietly, then veils the churn the successful attempt produces`() = + runTest { + val screen = FakeScreen() + var attempts = 0 + val controller = + controllerOn(screen) { + attempts++ + val succeeded = attempts >= SUCCEED_ON_ATTEMPT // fail twice + // Only a pull that worked writes anything. + if (succeeded) screen.churn() + succeeded + } + val seen = recordVisibility(controller) + + controller.request() + runCurrent() + // A failed pull changes nothing, so there is nothing to hide yet — + // the retries happen with no veil at all. + assertFalse(controller.visible.value, "no veil over a pull that changed nothing") + + advanceTimeBy(DRAIN_MS) + assertEquals(SUCCEED_ON_ATTEMPT, attempts, "retries until the pull succeeds") + assertEquals( + listOf(false, true, false), + seen, + "the veil went up once, over the churn the retry finally produced", + ) + } @Test - fun `an unchanged refresh never raises the veil and reports UNCHANGED`() = runTest { - val screen = FakeScreen() - val results = mutableListOf() - // Succeeds without writing anything — the common case on a launch - // over a warm cache, where the server returns what's already cached. - val controller = controllerOn(screen, onSessionEnd = { results += it }) { true } - val seen = recordVisibility(controller) + fun `giving up is silent, reports FAILED, and does not block later requests`() = + runTest { + val screen = FakeScreen() + val results = mutableListOf() + var attempts = 0 + var succeed = false + val controller = + controllerOn(screen, onSessionEnd = { results += it }) { + attempts++ + succeed + } - controller.request(userInitiated = true) - advanceTimeBy(DRAIN_MS) + controller.request(userInitiated = true) + advanceTimeBy(DRAIN_MS) + assertEquals(timings.attempts, attempts, "exhausts its attempts") + assertFalse(controller.visible.value, "no veil — a failed pull changed nothing") + assertEquals(VeilOutcome.FAILED, results.single().outcome) + assertTrue(results.single().userInitiated, "the user asked, so they're owed an answer") - assertEquals(listOf(false), seen, "a veil over an unchanged screen would hide nothing") - assertEquals(VeilOutcome.UNCHANGED, results.single().outcome) - assertTrue(results.single().userInitiated, "so the caller can say 'already up to date'") - } + // Giving up must not latch anything off — the reconnect-driven + // recovery still gets to try again later. + succeed = true + controller.request() + advanceTimeBy(DRAIN_MS) + assertEquals(timings.attempts + 1, attempts, "a later request still runs") + } @Test - fun `cached content painting is not mistaken for a change`() = runTest { - // Warm cache that hasn't painted yet: the rows arrive a moment after - // the session starts. Treating that first paint as churn would veil - // every single launch. - val screen = FakeScreen(hasContent = false) - val controller = controllerOn(screen) { true } + fun `overlapping requests extend one veil instead of racing it`() = + runTest { + val screen = FakeScreen() + var started = 0 + val controller = + controllerOn(screen) { + started++ + delay(WORK_MS) + screen.churn() + true + } + val seen = recordVisibility(controller) - controller.request() - runCurrent() - screen.contentAppears() - advanceTimeBy(DRAIN_MS) + // Reconnect and the rebuild event arriving together is what made the + // old Boolean flag clear mid-update: whichever pull finished first + // wiped the veil off while the other was still running. + controller.request() + runCurrent() + controller.request() + advanceTimeBy(WORK_MS + 1) + assertTrue(controller.visible.value, "second trigger extends the same veil") - assertFalse(controller.visible.value, "first paint is not churn") - } + advanceTimeBy(DRAIN_MS) + assertEquals(2, started, "the mid-session trigger still did its pull") + assertEquals(listOf(false, true, false), seen, "one veil session, not two") + } + + @Test + fun `a never-settling screen still releases the veil at the ceiling`() = + runTest { + val screen = FakeScreen() + val controller = + controllerOn(screen) { + screen.churn() + true + } + + screen.artLoading(1) // an image that never completes + controller.request() + advanceTimeBy(timings.maxHoldMs + 1) + assertFalse(controller.visible.value, "the hard ceiling must never strand the user") + } + + @Test + fun `an unchanged refresh never raises the veil and reports UNCHANGED`() = + runTest { + val screen = FakeScreen() + val results = mutableListOf() + // Succeeds without writing anything — the common case on a launch + // over a warm cache, where the server returns what's already cached. + val controller = controllerOn(screen, onSessionEnd = { results += it }) { true } + val seen = recordVisibility(controller) + + controller.request(userInitiated = true) + advanceTimeBy(DRAIN_MS) + + assertEquals(listOf(false), seen, "a veil over an unchanged screen would hide nothing") + assertEquals(VeilOutcome.UNCHANGED, results.single().outcome) + assertTrue(results.single().userInitiated, "so the caller can say 'already up to date'") + } + + @Test + fun `cached content painting is not mistaken for a change`() = + runTest { + // Warm cache that hasn't painted yet: the rows arrive a moment after + // the session starts. Treating that first paint as churn would veil + // every single launch. + val screen = FakeScreen(hasContent = false) + val controller = controllerOn(screen) { true } + + controller.request() + runCurrent() + screen.contentAppears() + advanceTimeBy(DRAIN_MS) + + assertFalse(controller.visible.value, "first paint is not churn") + } @Test fun `a background trigger coalescing with the user's does not swallow their answer`() = @@ -289,25 +304,27 @@ class UpdateVeilControllerTest { } @Test - fun `a cold load runs unveiled and is never reported as already up to date`() = runTest { - val screen = FakeScreen() - val results = mutableListOf() - var ran = false - val controller = controllerOn( - screen, - shouldVeil = { false }, // empty cache: the skeleton owns this - onSessionEnd = { results += it }, - ) { - ran = true - true + fun `a cold load runs unveiled and is never reported as already up to date`() = + runTest { + val screen = FakeScreen() + val results = mutableListOf() + var ran = false + val controller = + controllerOn( + screen, + shouldVeil = { false }, // empty cache: the skeleton owns this + onSessionEnd = { results += it }, + ) { + ran = true + true + } + + controller.request(userInitiated = true) + advanceTimeBy(DRAIN_MS) + + assertTrue(ran, "the refresh still happens") + assertFalse(controller.visible.value, "but no veil over a skeleton") + // It went from nothing to something — that IS a change. + assertEquals(VeilOutcome.CHANGED, results.single().outcome) } - - controller.request(userInitiated = true) - advanceTimeBy(DRAIN_MS) - - assertTrue(ran, "the refresh still happens") - assertFalse(controller.visible.value, "but no veil over a skeleton") - // It went from nothing to something — that IS a change. - assertEquals(VeilOutcome.CHANGED, results.single().outcome) - } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt index 53561202..cc32f70e 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/shared/widgets/ReorderDragMathTest.kt @@ -12,7 +12,6 @@ import kotlin.test.assertEquals * one row off on one platform only. */ class ReorderDragMathTest { - @ParameterizedTest(name = "{0}px on {1}px rows -> {2}") @CsvSource( "0, 64, 0", diff --git a/android/app/src/test/java/com/fabledsword/minstrel/testutil/MainDispatcherExtension.kt b/android/app/src/test/java/com/fabledsword/minstrel/testutil/MainDispatcherExtension.kt index 803d2c17..540226bb 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/testutil/MainDispatcherExtension.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/testutil/MainDispatcherExtension.kt @@ -28,8 +28,8 @@ import org.junit.jupiter.api.extension.ExtensionContext @OptIn(ExperimentalCoroutinesApi::class) class MainDispatcherExtension( private val testDispatcher: TestDispatcher = UnconfinedTestDispatcher(), -) : BeforeEachCallback, AfterEachCallback { - +) : BeforeEachCallback, + AfterEachCallback { override fun beforeEach(context: ExtensionContext) { Dispatchers.setMain(testDispatcher) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/theme/BundledFontsTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/theme/BundledFontsTest.kt index 20ad44d3..c898644b 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/theme/BundledFontsTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/theme/BundledFontsTest.kt @@ -98,11 +98,15 @@ class BundledFontsTest { error("no OS/2 table in the font") } - private fun readU16(bytes: ByteArray, at: Int): Int = - ((bytes[at].toInt() and BYTE_MASK) shl Byte.SIZE_BITS) or (bytes[at + 1].toInt() and BYTE_MASK) + private fun readU16( + bytes: ByteArray, + at: Int, + ): Int = ((bytes[at].toInt() and BYTE_MASK) shl Byte.SIZE_BITS) or (bytes[at + 1].toInt() and BYTE_MASK) - private fun readU32(bytes: ByteArray, at: Int): Int = - (readU16(bytes, at) shl Short.SIZE_BITS) or readU16(bytes, at + 2) + private fun readU32( + bytes: ByteArray, + at: Int, + ): Int = (readU16(bytes, at) shl Short.SIZE_BITS) or readU16(bytes, at + 2) private companion object { const val TYPOGRAPHY = "src/main/java/com/fabledsword/minstrel/theme/Typography.kt" diff --git a/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateRepositoryTest.kt index 5b783995..0cb656b4 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateRepositoryTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateRepositoryTest.kt @@ -28,7 +28,11 @@ class UpdateRepositoryTest { private val apkBytes = "the newer app".toByteArray() private val sha = MessageDigest.getInstance("SHA-256").digest(apkBytes).joinToString("") { "%02x".format(it) } - private fun wire(code: Long? = 200L, version: String = "2026.10.26.1200", sha256: String = sha) = UpdateInfoWire( + private fun wire( + code: Long? = 200L, + version: String = "2026.10.26.1200", + sha256: String = sha, + ) = UpdateInfoWire( version = version, code = code, sizeBytes = apkBytes.size.toLong(), @@ -42,13 +46,15 @@ class UpdateRepositoryTest { body: () -> ByteArray = { apkBytes }, offers: Boolean = true, ) = UpdateRepository( - api = object : ClientVersionApi { - override suspend fun getVersion(): UpdateInfoWire = version() - }, - apk = ApkSource { - downloads += 1 - body().toResponseBody() - }, + api = + object : ClientVersionApi { + override suspend fun getVersion(): UpdateInfoWire = version() + }, + apk = + ApkSource { + downloads += 1 + body().toResponseBody() + }, dir = dir, installedCode = 100L, installedName = "2026.10.20.0900", @@ -56,70 +62,79 @@ class UpdateRepositoryTest { ) @Test - fun `a newer build is offered`() = runTest { - assertIs(repo().check()) - } + fun `a newer build is offered`() = + runTest { + assertIs(repo().check()) + } @Test - fun `a server with no app to offer is not a problem`() = runTest { - val none = repo(version = { throw HttpException(Response.error(404, "".toResponseBody())) }) - assertEquals(Offer.Current, none.check()) - } + fun `a server with no app to offer is not a problem`() = + runTest { + val none = repo(version = { throw HttpException(Response.error(404, "".toResponseBody())) }) + assertEquals(Offer.Current, none.check()) + } @Test - fun `a server out of reach is a problem, not an all-clear`() = runTest { - assertIs(repo(version = { throw IOException("unreachable") }).check()) - } + fun `a server out of reach is a problem, not an all-clear`() = + runTest { + assertIs(repo(version = { throw IOException("unreachable") }).check()) + } @Test - fun `a debug build is never offered one`() = runTest { - assertEquals(Offer.Current, repo(offers = false).check()) - } + fun `a debug build is never offered one`() = + runTest { + assertEquals(Offer.Current, repo(offers = false).check()) + } @Test - fun `a build already fetched is installed from disk without a second download`() = runTest { - val r = repo() - val info = (r.check() as Offer.Newer).info - assertIs(r.download(info) {}) - assertNotNull(r.ready(info)) - val again = r.download(info) {} - assertIs(again) - assertEquals(1, downloads) - } + fun `a build already fetched is installed from disk without a second download`() = + runTest { + val r = repo() + val info = (r.check() as Offer.Newer).info + assertIs(r.download(info) {}) + assertNotNull(r.ready(info)) + val again = r.download(info) {} + assertIs(again) + assertEquals(1, downloads) + } @Test - fun `the download under way is visible to anyone waiting on it, and settles back to zero`() = runTest { - val r = repo() - val info = (r.check() as Offer.Newer).info - val seen = mutableListOf() - r.download(info) { done -> seen += r.downloadProgress.value.also { assertEquals(done, it) } } - assertEquals(1f, seen.last()) - assertEquals(0f, r.downloadProgress.value) - } + fun `the download under way is visible to anyone waiting on it, and settles back to zero`() = + runTest { + val r = repo() + val info = (r.check() as Offer.Newer).info + val seen = mutableListOf() + r.download(info) { done -> seen += r.downloadProgress.value.also { assertEquals(done, it) } } + assertEquals(1f, seen.last()) + assertEquals(0f, r.downloadProgress.value) + } @Test - fun `a download cut off partway is not taken for the build`() = runTest { - val r = repo(body = { apkBytes.copyOf(5) }) - val info = (r.check() as Offer.Newer).info - assertIs(r.download(info) {}) - assertNull(r.ready(info)) - assertTrue(dir.listFiles().orEmpty().isEmpty(), "the part file is removed") - } + fun `a download cut off partway is not taken for the build`() = + runTest { + val r = repo(body = { apkBytes.copyOf(5) }) + val info = (r.check() as Offer.Newer).info + assertIs(r.download(info) {}) + assertNull(r.ready(info)) + assertTrue(dir.listFiles().orEmpty().isEmpty(), "the part file is removed") + } @Test - fun `a download that does not match the digest is not taken for the build`() = runTest { - val r = repo(body = { "the other app".toByteArray() }) // same length, other bytes - val info = (r.check() as Offer.Newer).info - assertIs(r.download(info) {}) - assertNull(r.ready(info)) - } + fun `a download that does not match the digest is not taken for the build`() = + runTest { + val r = repo(body = { "the other app".toByteArray() }) // same length, other bytes + val info = (r.check() as Offer.Newer).info + assertIs(r.download(info) {}) + assertNull(r.ready(info)) + } @Test - fun `tidy drops a package kept for a build no longer offered`() = runTest { - val r = repo() - val info = (r.check() as Offer.Newer).info - r.download(info) {} - r.tidy() - assertNull(r.ready(info)) - } + fun `tidy drops a package kept for a build no longer offered`() = + runTest { + val r = repo() + val info = (r.check() as Offer.Newer).info + r.download(info) {} + r.tidy() + assertNull(r.ready(info)) + } } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateVersioningTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateVersioningTest.kt index 442222d2..5edad699 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateVersioningTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/update/data/UpdateVersioningTest.kt @@ -16,14 +16,18 @@ class UpdateVersioningTest { fun `decides on the ordering key when the server reports one`() { assertTrue( isUpdateAvailable( - serverCode = 3523847, serverName = "2026.09.10.1432", - installedCode = 3519456, installedName = "2026.09.09.1828", + serverCode = 3523847, + serverName = "2026.09.10.1432", + installedCode = 3519456, + installedName = "2026.09.09.1828", ), ) assertFalse( isUpdateAvailable( - serverCode = 3519456, serverName = "2026.09.09.1828", - installedCode = 3523847, installedName = "2026.09.10.1432", + serverCode = 3519456, + serverName = "2026.09.09.1828", + installedCode = 3523847, + installedName = "2026.09.10.1432", ), ) } @@ -32,8 +36,10 @@ class UpdateVersioningTest { fun `an equal ordering key is not an update`() { assertFalse( isUpdateAvailable( - serverCode = 3523847, serverName = "2026.09.10.1432", - installedCode = 3523847, installedName = "2026.09.10.1432", + serverCode = 3523847, + serverName = "2026.09.10.1432", + installedCode = 3523847, + installedName = "2026.09.10.1432", ), ) } @@ -48,16 +54,20 @@ class UpdateVersioningTest { // Name looks older, key is newer — e.g. an older commit rebuilt later. assertTrue( isUpdateAvailable( - serverCode = 9_000_000, serverName = "2020.01.01.0000", - installedCode = 1, installedName = "2099.12.31.2359", + serverCode = 9_000_000, + serverName = "2020.01.01.0000", + installedCode = 1, + installedName = "2099.12.31.2359", ), ) // Name looks newer, key is not. Offering this would be offering an // install the platform then refuses as a downgrade. assertFalse( isUpdateAvailable( - serverCode = 1, serverName = "2099.12.31.2359", - installedCode = 9_000_000, installedName = "2020.01.01.0000", + serverCode = 1, + serverName = "2099.12.31.2359", + installedCode = 9_000_000, + installedName = "2020.01.01.0000", ), ) } @@ -71,8 +81,10 @@ class UpdateVersioningTest { fun `the same app built again at a later minute is not offered`() { assertFalse( isUpdateAvailable( - serverCode = 3523900, serverName = "2026.09.10.1432", - installedCode = 3523847, installedName = "2026.09.10.1432", + serverCode = 3523900, + serverName = "2026.09.10.1432", + installedCode = 3523847, + installedName = "2026.09.10.1432", ), ) } @@ -81,14 +93,18 @@ class UpdateVersioningTest { fun `falls back to the name when the server reports no ordering key`() { assertTrue( isUpdateAvailable( - serverCode = null, serverName = "2026.09.10.1432", - installedCode = 3519456, installedName = "2026.09.09.1828", + serverCode = null, + serverName = "2026.09.10.1432", + installedCode = 3519456, + installedName = "2026.09.09.1828", ), ) assertFalse( isUpdateAvailable( - serverCode = null, serverName = "2026.09.09.1828", - installedCode = 3519456, installedName = "2026.09.10.1432", + serverCode = null, + serverName = "2026.09.09.1828", + installedCode = 3519456, + installedName = "2026.09.10.1432", ), ) } @@ -105,8 +121,10 @@ class UpdateVersioningTest { // false and this would wrongly report no update despite a newer name. assertTrue( isUpdateAvailable( - serverCode = null, serverName = "2026.09.10.1432", - installedCode = 0, installedName = "2026.09.09.1828", + serverCode = null, + serverName = "2026.09.10.1432", + installedCode = 0, + installedName = "2026.09.09.1828", ), ) } diff --git a/android/gradle/libs.versions.toml b/android/gradle/libs.versions.toml index c1bd4681..ad64385e 100644 --- a/android/gradle/libs.versions.toml +++ b/android/gradle/libs.versions.toml @@ -3,42 +3,37 @@ # there is no kotlin-android plugin to apply, and KSP 2.3+ supports that # path. AGP 9.5 needs Gradle 9.x (gradle-wrapper.properties), and both run # on the JDK 25 in the ci-android image. -# Held below their newest versions until the CI image compiles against -# Android 37: compose-bom, androidx.hilt, navigation, lifecycle, core-ktx, -# mediarouter, coil and OkHttp 5 all require compileSdk 37 or later, and -# ci-android:36 carries SDK 36. ktlint-gradle stays on 12 until the test -# sources are reformatted for its newer ktlint rules. agp = "9.5.3" kotlin = "2.4.21" ksp = "2.3.14" hilt = "2.60.1" -hilt-androidx = "1.2.0" -compose-bom = "2026.05.01" -nav-compose = "2.8.3" +hilt-androidx = "1.4.0" +compose-bom = "2026.11.01" +nav-compose = "2.10.2" room = "2.8.5" retrofit = "3.0.0" -okhttp = "4.12.1" +okhttp = "5.5.1" kotlinx-serialization = "1.13.0" kotlinx-coroutines = "1.11.0" kotlinx-datetime = "0.8.0-0.6.x-compat" kotlinx-serialization-converter = "1.0.0" media3 = "1.11.1" -mediarouter = "1.7.0" -coil = "3.0.0-rc02" +mediarouter = "1.9.0" +coil = "3.6.3" palette = "1.1.0" timber = "5.0.1" work = "2.12.0" -lifecycle = "2.8.7" +lifecycle = "2.11.1" junit-jupiter = "6.1.3" turbine = "1.2.1" mockk = "1.14.12" compose-test = "1.7.5" -ktlint-gradle = "12.1.1" +ktlint-gradle = "14.2.0" detekt = "2.0.0-alpha.6" kxml2 = "2.3.0" [libraries] -androidx-core-ktx = { module = "androidx.core:core-ktx", version = "1.13.1" } +androidx-core-ktx = { module = "androidx.core:core-ktx", version = "1.19.1" } androidx-lifecycle-viewmodel-compose = { module = "androidx.lifecycle:lifecycle-viewmodel-compose", version.ref = "lifecycle" } androidx-lifecycle-runtime-compose = { module = "androidx.lifecycle:lifecycle-runtime-compose", version.ref = "lifecycle" } androidx-lifecycle-process = { module = "androidx.lifecycle:lifecycle-process", version.ref = "lifecycle" } diff --git a/ci-requirements.md b/ci-requirements.md index 51402d4e..17716687 100644 --- a/ci-requirements.md +++ b/ci-requirements.md @@ -9,16 +9,16 @@ Minstrel's one workflow, `.gitea/workflows/release.yml`, consumes two CI images: ``` git.fabledsword.com/bvandeusen/ci-go:1.26 -git.fabledsword.com/bvandeusen/ci-android:36 +git.fabledsword.com/bvandeusen/ci-android:37 ``` - `ci-go:1.26` — the `go`, `integration` and `web` lanes, and the container build and public release (`image-release`). All CI lives in that one workflow so every publishing job can depend on every lane. - `golang:1.26-trixie` (Docker Hub) — the `govulncheck` lane. Deliberately the same image as the Dockerfile's builder stage rather than `ci-go`, so the standard library it checks is the one in the shipped binary. Keep the two in step. -- `ci-android:36` — native Kotlin/Compose client: ktlint + detekt + unit tests (the `android` lane), and the signed release APK (`android-release`). +- `ci-android:37` — native Kotlin/Compose client: ktlint + detekt + unit tests (the `android` lane), and the signed release APK (`android-release`). **No job uses `ci-flutter`**; nothing in this repo needs a Flutter toolchain. The `flutter-ci` runner *label* is still used: the Android jobs schedule on it -while pulling `ci-android:36`, per the label/image split below. +while pulling `ci-android:37`, per the label/image split below. ## Image deps used @@ -30,12 +30,12 @@ while pulling `ci-android:36`, per the label/image split below. - **docker buildx** — release container build + push in `release.yml`. - **git, perl, node** — the public release in `image-release`: `git archive` for the export, `ci/leakgate.sh` (perl joins comment lines), `ci/releases.mjs` (node's fetch) for the release pages on GitHub and this forge. -### From `ci-android:36` +### From `ci-android:37` - **JDK 25** — Gradle launcher + Android build. Requires Gradle 9.1.0+ in `android/gradle/wrapper`; older Gradle rejects JDK 25 with an opaque `"25.0.3"` error. The workflows also set `JAVA_TOOL_OPTIONS=--enable-native-access=ALL-UNNAMED` to silence Gradle's launcher-JVM restricted-method warning. -- **Android SDK + cmdline-tools + build-tools 36.0.0** — APK assembly + signing. +- **Android SDK 37 (platform 37.0) + cmdline-tools + build-tools 37.0.0** — APK assembly + signing. No NDK: the app has no C/C++ sources. - **ktlint + detekt** — `./gradlew ktlintCheck` and `./gradlew detekt` in the `android` lane. Image pins track `android/gradle/libs.versions.toml` so local @@ -49,7 +49,7 @@ None. ## Notes -- **Label/image split.** Workflows keep `runs-on: go-ci` / `runs-on: flutter-ci` as the scheduling label per the [`ci-runners.md`](https://…/FabledRulebook/ci-runners.md) "label = scheduling handle, image = `container.image`" pattern. The labels are intentional handles, not toolchain assertions — which is why the Android jobs still schedule on `flutter-ci` while pulling `ci-android:36`. Switch them to `android-ci` if that runner label is ever registered; nothing breaks either way. +- **Label/image split.** Workflows keep `runs-on: go-ci` / `runs-on: flutter-ci` as the scheduling label per the [`ci-runners.md`](https://…/FabledRulebook/ci-runners.md) "label = scheduling handle, image = `container.image`" pattern. The labels are intentional handles, not toolchain assertions — which is why the Android jobs still schedule on `flutter-ci` while pulling `ci-android:37`. Switch them to `android-ci` if that runner label is ever registered; nothing breaks either way. - **Integration-job docker-socket dependency.** The `integration` lane uses the runner's shared docker socket (`/var/run/docker.sock`) to bridge-IP-discover the per-job Postgres service container by name + network intersection — the dev compose's `minstrel-postgres-*` containers are explicitly skipped as belt-and-suspenders. Depends on `act_runner.valid_volumes` whitelisting the socket; if that ever stops auto-mounting, integration tests fail at the `docker inspect` step. - **Go toolchain pin.** `go.mod` is on `go 1.25.0` because `golang.org/x/crypto v0.51.0` declares 1.25 as its minimum. `ci-go:1.26` satisfies this with headroom. Future `x/crypto` bumps that move the Go floor should be paired with an image-tag bump in this file + the workflows. - **In-app update channel — `needs:`, not polling.** `release.yml`'s `image-release` job declares `needs: [android-release]`, so on dev and main pushes the signed APK built from the same commit is guaranteed present before the image build starts — no polling window, no race. No APK is attached to any release page; phones get the app from the server image.