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 b1bea272..1c99ff86 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 @@ -11,9 +11,9 @@ import javax.inject.Inject import javax.inject.Singleton /** - * Read-through accessor for the admin quarantine queue. No Room cache — - * same rationale as AdminRequests. Three resolution actions all delete - * the row from the queue once the server accepts them. + * Read-through accessor for the admin quarantine queue. No Room cache: + * it is an admin's live work list, read fresh each time. Three resolution + * actions all delete the row from the queue once the server accepts them. */ @Singleton class AdminQuarantineRepository @Inject constructor( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepository.kt deleted file mode 100644 index 9c4c94cc..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepository.kt +++ /dev/null @@ -1,50 +0,0 @@ -package com.fabledsword.minstrel.admin.data - -import com.fabledsword.minstrel.api.endpoints.AdminRequestsApi -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.models.RequestStatus -import com.fabledsword.minstrel.models.wire.RequestWire -import retrofit2.Retrofit -import retrofit2.create -import javax.inject.Inject -import javax.inject.Singleton - -/** - * Read-through accessor for the admin cross-user requests queue. - * - * No Room caching — admin actions are infrequent and don't benefit - * from offline scrollback. `approve` and `reject` fire direct REST - * (no mutation queue) because admin confirmation is point-and-shoot; - * if the request fails the UI surfaces the error and rolls back. - */ -@Singleton -class AdminRequestsRepository @Inject constructor( - retrofit: Retrofit, -) { - private val api: AdminRequestsApi = retrofit.create() - - suspend fun list(): List = api.list().map { it.toDomain() } - - suspend fun approve(id: String) = api.approve(id) - - suspend fun reject(id: String) = api.reject(id) -} - -private fun RequestWire.toDomain(): RequestRef = RequestRef( - id = id, - userId = userId, - username = username, - status = RequestStatus.fromWire(status), - kind = kind, - artistName = artistName, - albumTitle = albumTitle, - trackTitle = trackTitle, - requestedAt = requestedAt, - decidedAt = decidedAt, - notes = notes, - importedAlbumCount = importedAlbumCount, - importedTrackCount = importedTrackCount, - matchedTrackId = matchedTrackId, - matchedAlbumId = matchedAlbumId, - matchedArtistId = matchedArtistId, -) 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 b45a2dbe..505c54a7 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 @@ -3,7 +3,6 @@ package com.fabledsword.minstrel.admin.data import com.fabledsword.minstrel.api.endpoints.AdminUsersApi import com.fabledsword.minstrel.api.endpoints.ResetPasswordBody import com.fabledsword.minstrel.api.endpoints.SetAdminBody -import com.fabledsword.minstrel.api.endpoints.SetAutoApproveBody import com.fabledsword.minstrel.models.AdminUserRef import com.fabledsword.minstrel.models.wire.AdminUserWire import retrofit2.Retrofit @@ -27,9 +26,6 @@ class AdminUsersRepository @Inject constructor( suspend fun setAdmin(id: String, isAdmin: Boolean) = api.setAdmin(id, SetAdminBody(isAdmin)) - suspend fun setAutoApprove(id: String, autoApprove: Boolean) = - api.setAutoApprove(id, SetAutoApproveBody(autoApprove)) - suspend fun resetPassword(id: String, newPassword: String) = api.resetPassword(id, ResetPasswordBody(newPassword)) @@ -41,6 +37,5 @@ private fun AdminUserWire.toDomain(): AdminUserRef = AdminUserRef( username = username, displayName = displayName, isAdmin = isAdmin, - autoApproveRequests = autoApproveRequests, createdAt = createdAt, ) 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 9fd6b7dc..74589622 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 @@ -26,19 +26,16 @@ import androidx.lifecycle.ViewModel import androidx.lifecycle.compose.collectAsStateWithLifecycle import androidx.lifecycle.viewModelScope import androidx.navigation.NavHostController -import com.composables.icons.lucide.Inbox import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Music import com.composables.icons.lucide.TriangleAlert import com.composables.icons.lucide.Users import com.fabledsword.minstrel.admin.data.AdminQuarantineRepository -import com.fabledsword.minstrel.admin.data.AdminRequestsRepository import com.fabledsword.minstrel.admin.data.AdminTagSourcesRepository import com.fabledsword.minstrel.admin.data.AdminUsersRepository import com.fabledsword.minstrel.api.ErrorCopy import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.AdminQuarantine -import com.fabledsword.minstrel.nav.AdminRequests import com.fabledsword.minstrel.nav.AdminTagSources import com.fabledsword.minstrel.nav.AdminUsers import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets @@ -58,7 +55,7 @@ import javax.inject.Inject // ─── State ─────────────────────────────────────────────────────────── -data class AdminCounts(val requests: Int, val quarantine: Int, val users: Int, val tagSources: Int) +data class AdminCounts(val quarantine: Int, val users: Int, val tagSources: Int) sealed interface AdminLandingUiState { data object Loading : AdminLandingUiState @@ -70,7 +67,6 @@ sealed interface AdminLandingUiState { @HiltViewModel class AdminLandingViewModel @Inject constructor( - private val requestsRepo: AdminRequestsRepository, private val quarantineRepo: AdminQuarantineRepository, private val usersRepo: AdminUsersRepository, private val tagSourcesRepo: AdminTagSourcesRepository, @@ -87,11 +83,10 @@ class AdminLandingViewModel @Inject constructor( internal.value = AdminLandingUiState.Loading try { val counts = coroutineScope { - val req = async { requestsRepo.list().size } val qua = async { quarantineRepo.list().size } val usr = async { usersRepo.list().size } val tag = async { tagSourcesRepo.list().count { it.enabled } } - AdminCounts(req.await(), qua.await(), usr.await(), tag.await()) + AdminCounts(qua.await(), usr.await(), tag.await()) } internal.value = AdminLandingUiState.Success(counts) } catch ( @@ -150,15 +145,6 @@ private fun SectionList(counts: AdminCounts, navController: NavHostController) { contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp), ) { - item { - SectionCard( - icon = Lucide.Inbox, - title = "Requests", - subtitle = "Approve or reject requests for new music", - count = counts.requests, - onClick = { navController.navigate(AdminRequests) }, - ) - } item { SectionCard( icon = Lucide.TriangleAlert, diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsScreen.kt deleted file mode 100644 index f0269712..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsScreen.kt +++ /dev/null @@ -1,163 +0,0 @@ -package com.fabledsword.minstrel.admin.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.fillMaxWidth -import androidx.compose.foundation.layout.padding -import androidx.compose.foundation.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.material3.AssistChip -import androidx.compose.material3.Button -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -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.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.nav.AdminRequests -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 - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun AdminRequestsScreen( - navController: NavHostController, - viewModel: AdminRequestsViewModel = hiltViewModel(), -) { - val state by viewModel.uiState.collectAsStateWithLifecycle() - Scaffold( - contentWindowInsets = ShellContentWindowInsets, - modifier = Modifier.fillMaxSize(), - topBar = { - MinstrelTopAppBar( - title = "Admin · Requests", - navController = navController, - currentRouteName = AdminRequests::class.qualifiedName, - onBack = { navController.popBackStack() }, - ) - }, - ) { inner -> - PullToRefreshScaffold( - onRefresh = { viewModel.refresh().join() }, - modifier = Modifier.fillMaxSize().padding(inner), - ) { - when (val s = state) { - AdminRequestsUiState.Loading -> LoadingCentered() - AdminRequestsUiState.Empty -> EmptyState( - title = "No requests waiting", - body = "When users ask for new music, their pending " + - "requests show up here for approval.", - ) - is AdminRequestsUiState.Error -> ErrorRetry( - title = "Couldn't load requests", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is AdminRequestsUiState.Success -> RequestList( - rows = s.rows, - onApprove = viewModel::approve, - onReject = viewModel::reject, - ) - } - } - } -} - -@Composable -private fun RequestList( - rows: List, - onApprove: (String) -> Unit, - onReject: (String) -> Unit, -) { - LazyColumn(modifier = Modifier.fillMaxSize()) { - items(items = rows, key = { it.id }) { req -> - AdminRequestRow( - req = req, - requester = req.username.ifEmpty { - req.userId.take(USER_ID_PREFIX_LEN).ifEmpty { "unknown" } - }, - onApprove = { onApprove(req.id) }, - onReject = { onReject(req.id) }, - ) - HorizontalDivider() - } - } -} - -@Composable -private fun AdminRequestRow( - req: RequestRef, - requester: String, - onApprove: () -> Unit, - onReject: () -> Unit, -) { - Column( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalArrangement = Arrangement.spacedBy(8.dp), - ) { - Text( - text = req.displayName, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - text = "Requested by $requester", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) { - AssistChip( - onClick = {}, - enabled = false, - label = { Text(req.kind, style = MaterialTheme.typography.labelSmall) }, - ) - AssistChip( - onClick = {}, - enabled = false, - label = { Text(req.status.wire, style = MaterialTheme.typography.labelSmall) }, - ) - } - if (req.artistName.isNotEmpty() && req.artistName != req.displayName) { - Text( - text = "Artist: ${req.artistName}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - Row( - modifier = Modifier.fillMaxWidth(), - horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End), - ) { - OutlinedButton(onClick = onReject) { Text("Reject") } - Button(onClick = onApprove) { Text("Approve") } - } - } -} - -// UUID prefix length used as a friendlier-than-raw-UUID fallback when a -// row comes back without the requester's username. -private const val USER_ID_PREFIX_LEN = 8 diff --git a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsViewModel.kt deleted file mode 100644 index a01a9509..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/admin/ui/AdminRequestsViewModel.kt +++ /dev/null @@ -1,105 +0,0 @@ -package com.fabledsword.minstrel.admin.ui - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.fabledsword.minstrel.admin.data.AdminRequestsRepository -import com.fabledsword.minstrel.api.ErrorCopy -import com.fabledsword.minstrel.connectivity.NetworkStatusController -import com.fabledsword.minstrel.connectivity.recoveries -import com.fabledsword.minstrel.events.EventsStream -import com.fabledsword.minstrel.models.RequestRef -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.launch -import javax.inject.Inject - -private val RELEVANT_EVENT_KINDS = setOf("request.status_changed") - -sealed interface AdminRequestsUiState { - data object Loading : AdminRequestsUiState - data object Empty : AdminRequestsUiState - data class Success(val rows: List) : AdminRequestsUiState - data class Error(val message: String) : AdminRequestsUiState -} - -@HiltViewModel -class AdminRequestsViewModel @Inject constructor( - private val repository: AdminRequestsRepository, - private val eventsStream: EventsStream, - networkStatus: NetworkStatusController, -) : ViewModel() { - - private val internal = MutableStateFlow(AdminRequestsUiState.Loading) - val uiState: StateFlow = internal.asStateFlow() - - init { - refresh() - viewModelScope.launch { - eventsStream.events - .filter { it.kind in RELEVANT_EVENT_KINDS } - .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 AdminRequestsUiState.Error) refresh() - } - } - } - - fun refresh(): Job = viewModelScope.launch { - internal.value = AdminRequestsUiState.Loading - try { - val rows = repository.list() - internal.value = if (rows.isEmpty()) { - AdminRequestsUiState.Empty - } else { - AdminRequestsUiState.Success(rows = rows) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = AdminRequestsUiState.Error( - ErrorCopy.fromThrowable(e), - ) - } - } - - fun approve(id: String) = decide(id) { repository.approve(it) } - - fun reject(id: String) = decide(id) { repository.reject(it) } - - /** - * Optimistically removes the decided row from the visible list and - * fires the REST call. On failure, refetches so the UI matches the - * server's view rather than leaving a phantom hole. - */ - private fun decide(id: String, action: suspend (String) -> Unit) { - val before = internal.value - if (before is AdminRequestsUiState.Success) { - val filtered = before.rows.filterNot { it.id == id } - internal.value = if (filtered.isEmpty()) { - AdminRequestsUiState.Empty - } else { - AdminRequestsUiState.Success(rows = filtered) - } - } - viewModelScope.launch { - try { - action(id) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Refetch reconciles whatever the server now says about - // this request; the error is intentionally swallowed - // because the refresh result IS the user-facing signal. - refresh() - } - } - } -} 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 2b232a27..d85f7572 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 @@ -81,7 +81,6 @@ fun AdminUsersScreen( invitesViewModel.refresh() }, onSetAdmin = viewModel::setAdmin, - onSetAutoApprove = viewModel::setAutoApprove, onAskResetPassword = { resetPasswordFor = it }, onAskDelete = { deleteCandidate = it }, onAskGenerateInvite = { showGenerateInvite = true }, @@ -121,7 +120,6 @@ private fun AdminUsersScaffold( invitesState: AdminInvitesUiState, onRefresh: suspend () -> Unit, onSetAdmin: (String, Boolean) -> Unit, - onSetAutoApprove: (String, Boolean) -> Unit, onAskResetPassword: (AdminUserRef) -> Unit, onAskDelete: (AdminUserRef) -> Unit, onAskGenerateInvite: () -> Unit, @@ -148,7 +146,6 @@ private fun AdminUsersScaffold( usersSection( state = usersState, onSetAdmin = onSetAdmin, - onSetAutoApprove = onSetAutoApprove, onAskResetPassword = onAskResetPassword, onAskDelete = onAskDelete, ) @@ -195,7 +192,6 @@ private fun SectionHeader(label: String, trailing: (@Composable () -> Unit)? = n private fun androidx.compose.foundation.lazy.LazyListScope.usersSection( state: AdminUsersUiState, onSetAdmin: (String, Boolean) -> Unit, - onSetAutoApprove: (String, Boolean) -> Unit, onAskResetPassword: (AdminUserRef) -> Unit, onAskDelete: (AdminUserRef) -> Unit, ) { @@ -207,7 +203,6 @@ private fun androidx.compose.foundation.lazy.LazyListScope.usersSection( UserRow( user = user, onSetAdmin = { onSetAdmin(user.id, it) }, - onSetAutoApprove = { onSetAutoApprove(user.id, it) }, onResetPassword = { onAskResetPassword(user) }, onDelete = { onAskDelete(user) }, ) @@ -397,7 +392,6 @@ private fun PendingDialogs( private fun UserRow( user: AdminUserRef, onSetAdmin: (Boolean) -> Unit, - onSetAutoApprove: (Boolean) -> Unit, onResetPassword: () -> Unit, onDelete: () -> Unit, ) { @@ -420,11 +414,6 @@ private fun UserRow( color = MaterialTheme.colorScheme.onSurfaceVariant, ) ToggleRow(label = "Admin", checked = user.isAdmin, onChange = onSetAdmin) - ToggleRow( - label = "Auto-approve requests", - checked = user.autoApproveRequests, - onChange = onSetAutoApprove, - ) Row( modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(4.dp, Alignment.End), 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 000d86c7..33b0c8f5 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 @@ -62,11 +62,6 @@ class AdminUsersViewModel @Inject constructor( repository.setAdmin(it, isAdmin) } - fun setAutoApprove(id: String, autoApprove: Boolean) = - patch(id, { it.copy(autoApproveRequests = autoApprove) }) { - repository.setAutoApprove(it, autoApprove) - } - fun resetPassword(id: String, newPassword: String) { viewModelScope.launch { runCatching { repository.resetPassword(id, newPassword) } 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 1c4be42d..2a732f7a 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 @@ -24,7 +24,7 @@ import javax.inject.Singleton * rewritten. Absolute external URLs — artwork from * artwork.musicbrainz.org / coverartarchive.org, for example — must * reach their authored host unchanged: rewritten to the Minstrel host - * they 404, and Discover suggestions show no covers. + * they 404, and the art never shows. * * No-op when the stored base URL is unparseable (falls through to * whatever Retrofit had) — that case shows up as a transport-level diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminRequestsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminRequestsApi.kt deleted file mode 100644 index ef0db4d8..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/AdminRequestsApi.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.fabledsword.minstrel.api.endpoints - -import com.fabledsword.minstrel.models.wire.RequestWire -import retrofit2.http.GET -import retrofit2.http.POST -import retrofit2.http.Path - -/** - * Retrofit interface for `/api/admin/requests`. - * - * Server returns the same `requestView` shape as the user-side - * `/api/requests`, so RequestWire is reused. Different listing scope — - * admin sees all users' requests, not just the caller's. - */ -interface AdminRequestsApi { - @GET("api/admin/requests") - suspend fun list(): List - - @POST("api/admin/requests/{id}/approve") - suspend fun approve(@Path("id") id: String) - - @POST("api/admin/requests/{id}/reject") - suspend fun reject(@Path("id") id: String) -} 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 b6ef8172..0064f792 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 @@ -9,14 +9,7 @@ import retrofit2.http.POST import retrofit2.http.PUT import retrofit2.http.Path -/** - * Retrofit interface for `/api/admin/users`. - * - * Note: the PUT-auto-approve body field is `auto_approve`, NOT - * `auto_approve_requests` — the request shape differs from the - * response field name. Verified against `internal/api/admin_users.go - * adminAutoApproveReq` (May 2026). - */ +/** Retrofit interface for `/api/admin/users`. */ interface AdminUsersApi { @GET("api/admin/users") suspend fun list(): AdminUsersListWire @@ -24,9 +17,6 @@ interface AdminUsersApi { @PUT("api/admin/users/{id}/admin") suspend fun setAdmin(@Path("id") id: String, @Body body: SetAdminBody) - @PUT("api/admin/users/{id}/auto-approve") - suspend fun setAutoApprove(@Path("id") id: String, @Body body: SetAutoApproveBody) - @POST("api/admin/users/{id}/reset-password") suspend fun resetPassword(@Path("id") id: String, @Body body: ResetPasswordBody) @@ -39,10 +29,5 @@ data class SetAdminBody( @kotlinx.serialization.SerialName("is_admin") val isAdmin: Boolean, ) -@Serializable -data class SetAutoApproveBody( - @kotlinx.serialization.SerialName("auto_approve") val autoApprove: Boolean, -) - @Serializable data class ResetPasswordBody(val password: String) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiscoverApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiscoverApi.kt deleted file mode 100644 index 899b9bd0..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/DiscoverApi.kt +++ /dev/null @@ -1,62 +0,0 @@ -package com.fabledsword.minstrel.api.endpoints - -import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire -import com.fabledsword.minstrel.models.wire.CreateRequestBody -import com.fabledsword.minstrel.models.wire.CatalogueSearchResultWire -import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody -import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire -import retrofit2.http.Body -import retrofit2.http.DELETE -import retrofit2.http.GET -import retrofit2.http.POST -import retrofit2.http.Path -import retrofit2.http.Query - -/** - * Retrofit interface for Discover / catalogue search / request creation. - * - * `/api/catalogue/search` asks MusicBrainz, which allows one request a - * second, so the Discover screen searches when the query is submitted, - * not on every keystroke. - * - * Cancel + my-requests-list endpoints live on RequestsApi, not here. - */ -interface DiscoverApi { - @GET("api/discover/suggestions") - suspend fun listSuggestions(): List - - @GET("api/catalogue/search") - suspend fun search( - @Query("q") query: String, - @Query("kind") kind: String, - ): List - - @POST("api/requests") - suspend fun createRequest(@Body body: CreateRequestBody) - - /** - * Parks a suggestion — "not right now", NOT a dislike. Time-boxed - * server-side (90 days) and never fed into the taste profile. - * - * [body] must carry the artist's name: candidates are out-of-library, so - * the server has no local row to resolve a display name from and returns - * 400 without it. - */ - @POST("api/discover/suggestions/{mbid}/snooze") - suspend fun snoozeSuggestion( - @Path("mbid") mbid: String, - @Body body: SnoozeSuggestionBody, - ) - - /** Brings a parked suggestion back. 404 when it wasn't snoozed. */ - @DELETE("api/discover/suggestions/{mbid}/snooze") - suspend fun unsnoozeSuggestion(@Path("mbid") mbid: String) - - /** - * Currently-parked suggestions. Server filters expired rows, so every - * row returned is still snoozed. This is the only route back to an - * un-snooze once the card has left the deck. - */ - @GET("api/discover/snoozes") - suspend fun listSnoozes(): List -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/RequestsApi.kt b/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/RequestsApi.kt deleted file mode 100644 index 700b92a8..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/api/endpoints/RequestsApi.kt +++ /dev/null @@ -1,24 +0,0 @@ -package com.fabledsword.minstrel.api.endpoints - -import com.fabledsword.minstrel.models.wire.RequestWire -import retrofit2.http.DELETE -import retrofit2.http.GET -import retrofit2.http.Path - -/** - * Retrofit interface for the user-side `/api/requests`. - * - * Server scopes results to the caller — admins see only their own - * requests through this endpoint. The cross-user admin view lives on - * a separate `/api/admin/requests` route. - * - * The DELETE endpoint returns the cancelled row (not 204) so the UI - * can patch local state without a refetch. - */ -interface RequestsApi { - @GET("api/requests") - suspend fun listMine(): List - - @DELETE("api/requests/{id}") - suspend fun cancel(@Path("id") id: String): RequestWire -} 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 a78a61cc..eee08a39 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 @@ -19,16 +19,15 @@ private const val QUEUED_MESSAGE = "Saved — will sync when online" /** * Stable mutation kinds the queue knows how to replay. Strings are * persisted in `cached_mutations.kind` so renaming a variant breaks - * the on-disk queue — only ever add new kinds, never rename. + * the on-disk queue — never rename one. A kind can be removed: the + * replayer drops rows of a kind it doesn't know. */ object MutationKind { const val LIKE_TOGGLE: String = "like_toggle" - const val REQUEST_CREATE: String = "request_create" const val QUARANTINE_UNFLAG: String = "quarantine_unflag" const val PLAYLIST_APPEND: String = "playlist_append" const val QUARANTINE_FLAG: String = "quarantine_flag" const val PLAY_OFFLINE: String = "play_offline" - const val REQUEST_CANCEL: String = "request_cancel" const val PLAYBACK_ERROR_REPORT: String = "playback_error_report" // Durable close-by-id for a play whose server row is already open @@ -37,12 +36,6 @@ object MutationKind { // background would duplicate the open row and leave it orphaned. const val PLAY_ENDED: String = "play_ended" - // Suggestion snooze. ONE toggle kind rather than separate - // snooze/unsnooze kinds, mirroring LIKE_TOGGLE, so a snooze followed by - // an undo collapses to the latest intent instead of replaying as two - // opposed calls whose order decides the outcome. - const val SUGGESTION_SNOOZE_TOGGLE: String = "suggestion_snooze_toggle" - // Loudness-normalization preference. The payload is the whole // preference, a target state like the toggles above, so queued changes // collapse to the last one and an older one can never be replayed last. @@ -73,23 +66,6 @@ data class LikeTogglePayload( val desiredState: Boolean, ) -/** - * Persisted payload for `MutationKind.REQUEST_CREATE` (a Discover - * request that landed during a connectivity hiccup). Optional - * fields stay null when not applicable; the replayer rebuilds the - * `CreateRequestBody` from these. - */ -@Serializable -data class RequestCreatePayload( - val kind: String, - val artistMbid: String, - val artistName: String, - val albumMbid: String? = null, - val albumTitle: String? = null, - val trackMbid: String? = null, - val trackTitle: String? = null, -) - /** * Write side of the offline mutation queue; [MutationReplayer] drains it. * @@ -137,11 +113,6 @@ class MutationQueue @Inject constructor( ), ) - suspend fun enqueueRequestCreate(payload: RequestCreatePayload): Long = insertUserDriven( - MutationKind.REQUEST_CREATE, - json.encodeToString(RequestCreatePayload.serializer(), payload), - ) - suspend fun enqueueQuarantineUnflag(trackId: String): Long = insertUserDriven( MutationKind.QUARANTINE_UNFLAG, json.encodeToString( @@ -173,25 +144,6 @@ class MutationQueue @Inject constructor( ), ) - /** - * Queues a suggestion snooze (or its undo) for replay. [desiredSnoozed] - * is the TARGET state, so repeated taps collapse to one replay. - * - * [name] is carried even for an un-snooze, where the server ignores it, - * so a single payload shape serves both directions. - */ - suspend fun enqueueSuggestionSnoozeToggle( - mbid: String, - name: String, - desiredSnoozed: Boolean, - ): Long = insertUserDriven( - MutationKind.SUGGESTION_SNOOZE_TOGGLE, - json.encodeToString( - SuggestionSnoozeTogglePayload.serializer(), - SuggestionSnoozeTogglePayload(mbid, name, desiredSnoozed), - ), - ) - /** Queues the user's whole normalization preference for replay. */ suspend fun enqueueNormalizationSet(prefs: NormalizationPrefs): Long = insertUserDriven( MutationKind.NORMALIZATION_SET, @@ -217,14 +169,6 @@ class MutationQueue @Inject constructor( json.encodeToString(NotificationSettingPayload.serializer(), payload), ) - suspend fun enqueueRequestCancel(requestId: String): Long = insertUserDriven( - MutationKind.REQUEST_CANCEL, - json.encodeToString( - RequestCancelPayload.serializer(), - RequestCancelPayload(requestId), - ), - ) - suspend fun enqueuePlayOffline(payload: PlayOfflinePayload): Long = dao.insert( CachedMutationEntity( kind = MutationKind.PLAY_OFFLINE, @@ -257,21 +201,6 @@ class MutationQueue @Inject constructor( } } -/** - * Persisted payload for `MutationKind.SUGGESTION_SNOOZE_TOGGLE`. - * `desiredSnoozed` is the *target* state, matching [LikeTogglePayload], so - * the replayer can collapse repeated toggles for one candidate down to the - * last intent. Both directions are idempotent server-side: re-snoozing - * extends the window, and un-snoozing something already back is a 404 the - * replayer treats as permanent (nothing left to do). - */ -@Serializable -data class SuggestionSnoozeTogglePayload( - val mbid: String, - val name: String, - val desiredSnoozed: Boolean, -) - /** * Persisted payload for `MutationKind.QUARANTINE_UNFLAG` — the * `DELETE /api/quarantine/{trackId}` call lost during a connectivity @@ -337,15 +266,6 @@ data class PlayEndedPayload( val durationPlayedMs: Long, ) -/** - * Persisted payload for `MutationKind.REQUEST_CANCEL` — the - * `POST /api/requests/{id}/cancel` call lost during a connectivity - * hiccup. Server is idempotent on re-cancel (already-cancelled - * request stays cancelled). - */ -@Serializable -data class RequestCancelPayload(val requestId: String) - /** * Persisted payload for `MutationKind.PLAYBACK_ERROR_REPORT` — the * `POST /api/playback-errors` call lost during a connectivity hiccup. 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 5a28f9b7..7c11eba9 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 @@ -3,7 +3,6 @@ package com.fabledsword.minstrel.cache.mutations import com.fabledsword.minstrel.api.endpoints.AppendTracksRequest -import com.fabledsword.minstrel.api.endpoints.DiscoverApi import com.fabledsword.minstrel.api.endpoints.EventsApi import com.fabledsword.minstrel.api.endpoints.FlagRequest import com.fabledsword.minstrel.api.endpoints.LikesApi @@ -15,19 +14,16 @@ 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.QuarantineApi -import com.fabledsword.minstrel.api.endpoints.RequestsApi 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.models.wire.SnoozeSuggestionBody import com.fabledsword.minstrel.auth.AuthStore import com.fabledsword.minstrel.cache.db.dao.CachedMutationDao import com.fabledsword.minstrel.cache.db.entities.CachedMutationEntity import com.fabledsword.minstrel.di.ApplicationScope import com.fabledsword.minstrel.likes.data.LikesRepository import com.fabledsword.minstrel.settings.data.NormalizationPrefs -import com.fabledsword.minstrel.models.wire.CreateRequestBody import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.flow.distinctUntilChanged import kotlinx.coroutines.flow.filter @@ -78,11 +74,9 @@ class MutationReplayer @Inject constructor( retrofit: Retrofit, ) { private val likesApi: LikesApi = retrofit.create() - private val discoverApi: DiscoverApi = retrofit.create() private val quarantineApi: QuarantineApi = retrofit.create() private val playlistsApi: PlaylistsApi = retrofit.create() private val eventsApi: EventsApi = retrofit.create() - private val requestsApi: RequestsApi = retrofit.create() private val playbackErrorsApi: PlaybackErrorsApi = retrofit.create() private val meApi: MeApi = retrofit.create() private val notificationsApi: NotificationsApi = retrofit.create() @@ -122,11 +116,11 @@ class MutationReplayer @Inject constructor( private suspend fun drain() { val rows = dao.getAll() - // Collapse superseded toggles (likes, suggestion snoozes): only the - // latest desired state per entity is replayed; older toggles for the - // same entity are dropped unsent. Without this, partial-failure + + // 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 — a snooze the user already undid would come back. + // final state — an unlike the user already made would be undone. val superseded = supersededToggleIds(rows, json) for (row in rows) { if (row.id in superseded) { @@ -164,15 +158,12 @@ class MutationReplayer @Inject constructor( */ private suspend fun dispatch(row: CachedMutationEntity): Outcome = when (row.kind) { MutationKind.LIKE_TOGGLE -> dispatchLikeToggle(row.payload) - MutationKind.REQUEST_CREATE -> dispatchRequestCreate(row.payload) MutationKind.QUARANTINE_UNFLAG -> dispatchQuarantineUnflag(row.payload) MutationKind.PLAYLIST_APPEND -> dispatchPlaylistAppend(row.payload) MutationKind.QUARANTINE_FLAG -> dispatchQuarantineFlag(row.payload) MutationKind.PLAY_OFFLINE -> dispatchPlayOffline(row.payload) MutationKind.PLAY_ENDED -> dispatchPlayEnded(row.payload) - MutationKind.REQUEST_CANCEL -> dispatchRequestCancel(row.payload) MutationKind.PLAYBACK_ERROR_REPORT -> dispatchPlaybackErrorReport(row.payload) - MutationKind.SUGGESTION_SNOOZE_TOGGLE -> dispatchSuggestionSnoozeToggle(row.payload) MutationKind.NORMALIZATION_SET -> dispatchNormalizationSet(row.payload) MutationKind.NOTIFICATION_READ, MutationKind.NOTIFICATIONS_READ_ALL, @@ -206,22 +197,6 @@ class MutationReplayer @Inject constructor( return Outcome.SENT } - private suspend fun dispatchRequestCreate(payload: String): Outcome { - val decoded = json.decodeFromString(RequestCreatePayload.serializer(), payload) - discoverApi.createRequest( - CreateRequestBody( - kind = decoded.kind, - artistMbid = decoded.artistMbid, - artistName = decoded.artistName, - albumMbid = decoded.albumMbid, - albumTitle = decoded.albumTitle, - trackMbid = decoded.trackMbid, - trackTitle = decoded.trackTitle, - ), - ) - return Outcome.SENT - } - private suspend fun dispatchQuarantineUnflag(payload: String): Outcome { val decoded = json.decodeFromString(QuarantineUnflagPayload.serializer(), payload) quarantineApi.unflag(decoded.trackId) @@ -275,30 +250,6 @@ class MutationReplayer @Inject constructor( return Outcome.SENT } - private suspend fun dispatchRequestCancel(payload: String): Outcome { - val decoded = json.decodeFromString(RequestCancelPayload.serializer(), payload) - requestsApi.cancel(decoded.requestId) - return Outcome.SENT - } - - /** - * Replays a suggestion snooze in whichever direction the payload asks for. - * - * The un-snooze branch can legitimately 404 (the row already lapsed, or a - * previous attempt landed and the response was lost). [outcomeFor] classes - * 404 as permanent → DROP, which is right: the user's intended end state - * already holds, so there is nothing left to send. - */ - private suspend fun dispatchSuggestionSnoozeToggle(payload: String): Outcome { - val decoded = json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), payload) - if (decoded.desiredSnoozed) { - discoverApi.snoozeSuggestion(decoded.mbid, SnoozeSuggestionBody(name = decoded.name)) - } else { - discoverApi.unsnoozeSuggestion(decoded.mbid) - } - 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 @@ -354,7 +305,7 @@ class MutationReplayer @Inject constructor( /** * 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 - * than an action — like-toggles, suggestion snoozes and the + * than an action — like-toggles, notification settings and the * normalization preference — because * replaying a stale one last would invert the final state. * @@ -388,10 +339,6 @@ private fun toggleKeyOf(row: CachedMutationEntity, json: Json): String? = when ( json.decodeFromString(LikeTogglePayload.serializer(), row.payload) }.getOrNull()?.let { "${row.kind}:${it.entityType}:${it.entityId}" } - MutationKind.SUGGESTION_SNOOZE_TOGGLE -> runCatching { - json.decodeFromString(SuggestionSnoozeTogglePayload.serializer(), row.payload) - }.getOrNull()?.let { "${row.kind}:${it.mbid}" } - MutationKind.NOTIFICATION_SETTING_SET -> runCatching { json.decodeFromString(NotificationSettingPayload.serializer(), row.payload) }.getOrNull()?.let { "${row.kind}:${it.kind}:${it.channel}" } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/discover/data/DiscoverRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/discover/data/DiscoverRepository.kt deleted file mode 100644 index 96e08bec..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/discover/data/DiscoverRepository.kt +++ /dev/null @@ -1,199 +0,0 @@ -package com.fabledsword.minstrel.discover.data - -import com.fabledsword.minstrel.api.endpoints.DiscoverApi -import com.fabledsword.minstrel.cache.mutations.MutationQueue -import com.fabledsword.minstrel.cache.mutations.RequestCreatePayload -import com.fabledsword.minstrel.models.ArtistSuggestionRef -import com.fabledsword.minstrel.models.RequestKind -import com.fabledsword.minstrel.models.CatalogueResultRef -import com.fabledsword.minstrel.models.SeedContributionRef -import com.fabledsword.minstrel.models.SuggestionSnoozeRef -import com.fabledsword.minstrel.models.wire.ArtistSuggestionWire -import com.fabledsword.minstrel.models.wire.CreateRequestBody -import com.fabledsword.minstrel.models.wire.CatalogueSearchResultWire -import com.fabledsword.minstrel.models.wire.SeedContributionWire -import com.fabledsword.minstrel.models.wire.SnoozeSuggestionBody -import com.fabledsword.minstrel.models.wire.SuggestionSnoozeWire -import retrofit2.HttpException -import retrofit2.Retrofit -import retrofit2.create -import javax.inject.Inject -import javax.inject.Singleton - -/** - * Outcome of a `createRequest` call — discriminates "server accepted" - * from "network down, queued for later replay". The UI uses this to - * pick between "Requested" and "Queued" snackbars. - */ -enum class RequestOutcome { ACCEPTED, QUEUED } - -/** - * Read-through Discover surface: catalogue search, suggestion feed, and - * the request-creation write path. Writes never go fire-and-forget, so - * `createRequest` falls back to the MutationQueue on transport failure. - * - * Reads are not cached locally — discovery results are inherently - * transient (60s server-side LRU), so a local cache would win little. - */ -@Singleton -class DiscoverRepository @Inject constructor( - private val mutationQueue: MutationQueue, - retrofit: Retrofit, -) { - private val api: DiscoverApi = retrofit.create() - - suspend fun listSuggestions(): List = - api.listSuggestions().map { it.toDomain() } - - suspend fun listSnoozes(): List = - api.listSnoozes().map { it.toDomain() } - - /** - * Parks a suggestion ("not right now"). Offline-first: on - * transport failure the target state is queued for the replayer rather - * than dropped. - * - * Always reports success to the caller. Unlike a request, a snooze has no - * meaningful failed state to show — the user asked for a card to go away, - * and it will, either now or when the queue drains. - */ - suspend fun snoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze( - mbid = mbid, - name = name, - desiredSnoozed = true, - ) { api.snoozeSuggestion(mbid, SnoozeSuggestionBody(name = name)) } - - /** Brings a parked suggestion back. Same offline-first contract. */ - suspend fun unsnoozeSuggestion(mbid: String, name: String): Unit = toggleSnooze( - mbid = mbid, - name = name, - desiredSnoozed = false, - ) { api.unsnoozeSuggestion(mbid) } - - private suspend fun toggleSnooze( - mbid: String, - name: String, - desiredSnoozed: Boolean, - call: suspend () -> Unit, - ) { - try { - call() - } catch (e: HttpException) { - // A 4xx is the server's considered answer, not a lost call, so - // queueing it would be wrong twice over: the replay is guaranteed - // to fail again, and the enqueue would raise a "will sync when - // online" snackbar for something already settled. The common case - // is a 404 from un-snoozing a row that already lapsed — which is - // the end state the user wanted anyway. - if (!isPermanent(e.code())) { - mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed) - } - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Transport failure — intentional swallow, same offline-first - // rationale as createRequest above. The queue carries the desired - // STATE, so a later undo supersedes this rather than fighting it - // on replay. - mutationQueue.enqueueSuggestionSnoozeToggle(mbid, name, desiredSnoozed) - } - } - - /** - * Mirrors MutationReplayer's classification so the enqueue decision here - * and the drop decision there can't disagree: 4xx is permanent except the - * two "retry me" statuses. - */ - private fun isPermanent(code: Int): Boolean = - code in HTTP_CLIENT_ERR_MIN..HTTP_CLIENT_ERR_MAX && - code != HTTP_TIMEOUT && code != HTTP_TOO_MANY - - suspend fun search(query: String, kind: RequestKind): List = - api.search(query = query, kind = kind.wire).map { it.toDomain() } - - /** - * Fires `POST /api/requests`; on transport failure enqueues a - * `RequestCreatePayload` for the Phase-12.2 replayer to drain. - * Returns [RequestOutcome.ACCEPTED] when the server responded - * 2xx, [RequestOutcome.QUEUED] when the call was buffered. - */ - suspend fun createRequest( - kind: RequestKind, - artistMbid: String, - artistName: String, - albumMbid: String? = null, - albumTitle: String? = null, - trackMbid: String? = null, - trackTitle: String? = null, - ): RequestOutcome { - val payload = RequestCreatePayload( - kind = kind.wire, - artistMbid = artistMbid, - artistName = artistName, - albumMbid = albumMbid?.ifEmpty { null }, - albumTitle = albumTitle?.ifEmpty { null }, - trackMbid = trackMbid?.ifEmpty { null }, - trackTitle = trackTitle?.ifEmpty { null }, - ) - return try { - api.createRequest(payload.toBody()) - RequestOutcome.ACCEPTED - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Intentional swallow — see LikesRepository.toggleLike for - // the same offline-first rationale. - mutationQueue.enqueueRequestCreate(payload) - RequestOutcome.QUEUED - } - } - - private companion object { - const val HTTP_CLIENT_ERR_MIN = 400 - const val HTTP_CLIENT_ERR_MAX = 499 - const val HTTP_TIMEOUT = 408 - const val HTTP_TOO_MANY = 429 - } -} - -// ── Mappers (internal — wire types stay out of UI) ── - -private fun CatalogueSearchResultWire.toDomain(): CatalogueResultRef = CatalogueResultRef( - mbid = mbid, - name = name, - secondaryText = secondaryText, - imageUrl = imageUrl, - artistMbid = artistMbid, - albumMbid = albumMbid, - inLibrary = inLibrary, - requested = requested, -) - -private fun ArtistSuggestionWire.toDomain(): ArtistSuggestionRef = ArtistSuggestionRef( - mbid = mbid, - name = name, - imageUrl = imageUrl, - attribution = attribution.map { it.toDomain() }, - matchedTags = matchedTags, -) - -private fun SeedContributionWire.toDomain(): SeedContributionRef = SeedContributionRef( - name = name, - isLiked = isLiked, -) - -private fun SuggestionSnoozeWire.toDomain(): SuggestionSnoozeRef = SuggestionSnoozeRef( - mbid = mbid, - name = name, - snoozedUntil = snoozedUntil, -) - -private fun RequestCreatePayload.toBody(): CreateRequestBody = CreateRequestBody( - kind = kind, - artistMbid = artistMbid, - artistName = artistName, - albumMbid = albumMbid, - albumTitle = albumTitle, - trackMbid = trackMbid, - trackTitle = trackTitle, -) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverScreen.kt deleted file mode 100644 index ade53f2a..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverScreen.kt +++ /dev/null @@ -1,353 +0,0 @@ -package com.fabledsword.minstrel.discover.ui - -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -import androidx.compose.foundation.layout.Column -import androidx.compose.foundation.layout.PaddingValues -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.lazy.LazyColumn -import androidx.compose.foundation.lazy.items -import androidx.compose.foundation.text.KeyboardActions -import androidx.compose.foundation.text.KeyboardOptions -import androidx.compose.material3.ExperimentalMaterial3Api -import androidx.compose.material3.FilterChip -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedTextField -import androidx.compose.material3.Scaffold -import androidx.compose.material3.SnackbarHost -import androidx.compose.material3.SnackbarHostState -import androidx.compose.material3.Text -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.remember -import androidx.compose.runtime.rememberCoroutineScope -import androidx.lifecycle.compose.collectAsStateWithLifecycle -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.text.input.ImeAction -import androidx.compose.ui.unit.dp -import androidx.hilt.navigation.compose.hiltViewModel -import androidx.navigation.NavHostController -import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.Search as LucideSearch -import com.fabledsword.minstrel.discover.data.RequestOutcome -import com.fabledsword.minstrel.models.ArtistSuggestionRef -import com.fabledsword.minstrel.models.RequestKind -import com.fabledsword.minstrel.models.CatalogueResultRef -import com.fabledsword.minstrel.models.SuggestionSnoozeRef -import com.fabledsword.minstrel.nav.Discover -import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets -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 kotlinx.coroutines.launch - -// ─── Screen ────────────────────────────────────────────────────────── - -@OptIn(ExperimentalMaterial3Api::class) -@Composable -fun DiscoverScreen( - navController: NavHostController, - viewModel: DiscoverViewModel = hiltViewModel(), -) { - val state by viewModel.state.collectAsStateWithLifecycle() - val snackbar = remember { SnackbarHostState() } - val scope = rememberCoroutineScope() - - Scaffold( - contentWindowInsets = ShellContentWindowInsets, - modifier = Modifier.fillMaxSize(), - topBar = { - MinstrelTopAppBar( - title = "Discover", - navController = navController, - currentRouteName = Discover::class.qualifiedName, - onBack = { navController.popBackStack() }, - ) - }, - snackbarHost = { SnackbarHost(snackbar) }, - ) { inner -> - DiscoverBody( - inner = inner, - state = state, - viewModel = viewModel, - snackbar = snackbar, - scope = scope, - ) - } -} - -@Composable -private fun DiscoverBody( - inner: androidx.compose.foundation.layout.PaddingValues, - state: DiscoverState, - viewModel: DiscoverViewModel, - snackbar: SnackbarHostState, - scope: kotlinx.coroutines.CoroutineScope, -) { - Column(modifier = Modifier.fillMaxSize().padding(inner)) { - SearchBar( - query = state.query, - onQueryChange = viewModel::setQuery, - onSubmit = viewModel::runSearch, - ) - KindChips(kind = state.kind, onChange = viewModel::setKind) - PullToRefreshScaffold( - onRefresh = { viewModel.loadSuggestions().join() }, - modifier = Modifier.fillMaxSize(), - ) { - when (val r = state.results) { - ResultsState.Idle -> SuggestionsPane( - state = state.suggestions, - locallyRequestedMbids = state.locallyRequestedMbids, - snoozeUi = SnoozeUi( - locallySnoozedMbids = state.locallySnoozedMbids, - snoozes = state.snoozes, - // No snackbar on snooze: the row itself flips to "Not - // right now" with an Undo, so a snackbar would only - // repeat what the user can already see — and cover the - // next row while doing it. - onSnooze = { s -> scope.launch { viewModel.snoozeSuggestion(s) } }, - onUnsnooze = { mbid, name -> - scope.launch { viewModel.unsnoozeSuggestion(mbid, name) } - }, - ), - onRequest = { s -> - scope.launch { - val outcome = viewModel.requestSuggestion(s) - snackbar.showSnackbar(snackbarFor(outcome, s.name)) - } - }, - onRetry = { viewModel.loadSuggestions() }, - ) - ResultsState.Loading -> LoadingCentered() - is ResultsState.Loaded -> ResultsList( - rows = r.items, - locallyRequestedMbids = state.locallyRequestedMbids, - onRequest = { row -> - scope.launch { - val outcome = viewModel.requestRow(row) - snackbar.showSnackbar(snackbarFor(outcome, row.name)) - } - }, - ) - is ResultsState.Error -> ErrorRetry( - title = "Search failed", - message = r.message, - onRetry = viewModel::runSearch, - ) - } - } - } -} - -@Composable -private fun SearchBar( - query: String, - onQueryChange: (String) -> Unit, - onSubmit: () -> Unit, -) { - OutlinedTextField( - value = query, - onValueChange = onQueryChange, - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), - singleLine = true, - placeholder = { Text("Search MusicBrainz for new music") }, - keyboardOptions = KeyboardOptions(imeAction = ImeAction.Search), - keyboardActions = KeyboardActions(onSearch = { onSubmit() }), - trailingIcon = { - IconButton(onClick = onSubmit) { - Icon(Lucide.LucideSearch, contentDescription = "Search") - } - }, - ) -} - -@Composable -private fun KindChips(kind: RequestKind, onChange: (RequestKind) -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 4.dp), - horizontalArrangement = Arrangement.spacedBy(8.dp), - ) { - FilterChip( - selected = kind == RequestKind.ARTIST, - onClick = { onChange(RequestKind.ARTIST) }, - label = { Text("Artists") }, - ) - FilterChip( - selected = kind == RequestKind.ALBUM, - onClick = { onChange(RequestKind.ALBUM) }, - label = { Text("Albums") }, - ) - } -} - -/** - * The snooze surface's data and callbacks, bundled rather than threaded - * through as separate parameters: the pane carries three actions, and the - * signatures stop being readable otherwise. - */ -private data class SnoozeUi( - val locallySnoozedMbids: Set, - val snoozes: List, - val onSnooze: (ArtistSuggestionRef) -> Unit, - val onUnsnooze: (String, String) -> Unit, -) - -@Composable -private fun SuggestionsPane( - state: SuggestionState, - locallyRequestedMbids: Set, - snoozeUi: SnoozeUi, - onRequest: (ArtistSuggestionRef) -> Unit, - onRetry: () -> Unit, -) { - when (state) { - SuggestionState.Loading -> LoadingCentered() - is SuggestionState.Error -> ErrorRetry( - title = "Couldn't load suggestions", - message = state.message, - onRetry = onRetry, - ) - is SuggestionState.Loaded -> SuggestionsList( - items = state.items.filter { it.mbid !in locallyRequestedMbids }, - snoozeUi = snoozeUi, - onRequest = onRequest, - ) - } -} - -@Composable -private fun SuggestionsList( - items: List, - snoozeUi: SnoozeUi, - onRequest: (ArtistSuggestionRef) -> Unit, -) { - LazyColumn( - modifier = Modifier.fillMaxSize(), - contentPadding = PaddingValues(bottom = 16.dp), - ) { - item { SuggestionsHeader() } - if (items.isEmpty()) { - // An empty deck means one of two things — no listening signal yet, - // or "you parked them all" — and telling the second user to go - // listen to something would be wrong advice. - item { - CenteredMessage( - if (snoozeUi.snoozes.isEmpty()) { - "Listen to or like an artist to fill this in." - } else { - "Nothing new right now — the artists you've parked are below." - }, - ) - } - } else { - items(items = items, key = { it.mbid }) { s -> - SuggestionTile( - s = s, - snoozed = s.mbid in snoozeUi.locallySnoozedMbids, - onRequest = { onRequest(s) }, - onSnooze = { snoozeUi.onSnooze(s) }, - onUnsnooze = { snoozeUi.onUnsnooze(s.mbid, s.name) }, - ) - HorizontalDivider() - } - } - // Parked candidates live at the bottom of the same scroll, not behind a - // separate screen: it's a short list the user rarely needs, but it must - // be reachable — a snoozed candidate is gone from the deck above, so - // this is the only way back to it. - if (snoozeUi.snoozes.isNotEmpty()) { - item { SnoozedHeader() } - items(items = snoozeUi.snoozes, key = { "snoozed-${it.mbid}" }) { row -> - SnoozedTile( - row = row, - onUnsnooze = { snoozeUi.onUnsnooze(row.mbid, row.name) }, - ) - HorizontalDivider() - } - } - } -} - -@Composable -private fun SnoozedHeader() { - Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) { - HorizontalDivider(modifier = Modifier.padding(bottom = 12.dp)) - Text( - text = "Not right now", - style = MaterialTheme.typography.titleMedium, - color = MaterialTheme.colorScheme.onBackground, - ) - Text( - text = "These come back on their own. Nothing here counts against your taste profile.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -@Composable -private fun SuggestionsHeader() { - Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)) { - Text( - text = "Suggested for you", - style = MaterialTheme.typography.titleLarge, - color = MaterialTheme.colorScheme.onBackground, - ) - Text( - text = "Out-of-library artists drawn from what you've liked and played.", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -@Composable -private fun ResultsList( - rows: List, - locallyRequestedMbids: Set, - onRequest: (CatalogueResultRef) -> Unit, -) { - if (rows.isEmpty()) { - CenteredMessage("Nothing to add for that search yet.") - return - } - LazyColumn(modifier = Modifier.fillMaxSize()) { - items(items = rows, key = { it.mbid }) { row -> - ResultTile( - row = row, - locallyRequested = row.mbid in locallyRequestedMbids, - onRequest = { onRequest(row) }, - ) - HorizontalDivider() - } - } -} - -@Composable -private fun CenteredMessage(text: String) { - Box(modifier = Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.Center) { - Text( - text = text, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } -} - -private fun snackbarFor(outcome: RequestOutcome, name: String): String = when (outcome) { - RequestOutcome.ACCEPTED -> "Requested: $name" - RequestOutcome.QUEUED -> "Request queued: $name" -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverTiles.kt b/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverTiles.kt deleted file mode 100644 index 334d3427..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverTiles.kt +++ /dev/null @@ -1,191 +0,0 @@ -package com.fabledsword.minstrel.discover.ui - -import androidx.compose.foundation.background -import androidx.compose.foundation.layout.Arrangement -import androidx.compose.foundation.layout.Box -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.shape.CircleShape -import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.AssistChip -import androidx.compose.material3.Button -import androidx.compose.material3.Icon -import androidx.compose.material3.IconButton -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -import androidx.compose.ui.draw.clip -import androidx.compose.ui.graphics.vector.ImageVector -import androidx.compose.ui.text.style.TextOverflow -import androidx.compose.ui.unit.dp -import com.composables.icons.lucide.Clock -import com.composables.icons.lucide.Disc3 -import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.User -import com.fabledsword.minstrel.models.ArtistSuggestionRef -import com.fabledsword.minstrel.models.CatalogueResultRef -import com.fabledsword.minstrel.models.SuggestionSnoozeRef -import com.fabledsword.minstrel.shared.widgets.ServerImage - -@Composable -internal fun SuggestionTile( - s: ArtistSuggestionRef, - snoozed: Boolean, - onRequest: () -> Unit, - onSnooze: () -> Unit, - onUnsnooze: () -> Unit, -) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Avatar(imageUrl = s.imageUrl, fallback = Lucide.User, circular = true) - Column(modifier = Modifier.weight(1f)) { - Text( - text = s.name, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - // Once parked, the "because you liked X" line is no longer the - // useful thing to say — confirming what just happened is. - val secondary = - if (snoozed) "Not right now — hidden for a while" else s.reasonText - if (secondary.isNotEmpty()) { - Text( - text = secondary, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - } - } - if (snoozed) { - TextButton(onClick = onUnsnooze) { Text("Undo") } - } else { - Button(onClick = onRequest) { Text("Request") } - IconButton(onClick = onSnooze) { - Icon( - imageVector = Lucide.Clock, - // The label states what happens and passes no judgement on the - // music: never "not for me". - contentDescription = "Not right now — hide ${s.name} for a while", - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } - } -} - -/** - * One row of the parked list. This exists because a snoozed candidate is by - * definition absent from the deck above, so without it there is no route back - * to an un-snooze once the card has gone. - */ -@Composable -internal fun SnoozedTile(row: SuggestionSnoozeRef, onUnsnooze: () -> Unit) { - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 8.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Column(modifier = Modifier.weight(1f)) { - Text( - text = row.name, - style = MaterialTheme.typography.bodyMedium, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Text( - text = "Back ${row.returnsIn()}", - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - TextButton(onClick = onUnsnooze) { Text("Bring back") } - } -} - -@Composable -internal fun ResultTile( - row: CatalogueResultRef, - locallyRequested: Boolean, - onRequest: () -> Unit, -) { - val effectivelyRequested = row.requested || locallyRequested - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 10.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - Avatar(imageUrl = row.imageUrl, fallback = Lucide.Disc3, circular = false) - Column(modifier = Modifier.weight(1f)) { - Text( - text = row.name, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - if (row.secondaryText.isNotEmpty()) { - Text( - text = row.secondaryText, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - } - } - when { - row.inLibrary -> AssistChip(onClick = {}, enabled = false, label = { Text("In library") }) - effectivelyRequested -> - AssistChip(onClick = {}, enabled = false, label = { Text("Requested") }) - else -> Button(onClick = onRequest) { Text("Request") } - } - } -} - -@Composable -private fun Avatar(imageUrl: String, fallback: ImageVector, circular: Boolean) { - val clip = if (circular) CircleShape else RoundedCornerShape(6.dp) - Box( - modifier = Modifier - .size(56.dp) - .clip(clip) - .background(MaterialTheme.colorScheme.surfaceVariant), - contentAlignment = Alignment.Center, - ) { - // The server hands back its own art endpoint (relative), - // which answers 404 when no source has an image: ServerImage resolves - // the path and shows the icon while loading and on a miss. - ServerImage( - url = imageUrl, - contentDescription = null, - modifier = Modifier.fillMaxSize(), - ) { - Icon( - imageVector = fallback, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - ) - } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverViewModel.kt deleted file mode 100644 index bce9f3c9..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/discover/ui/DiscoverViewModel.kt +++ /dev/null @@ -1,206 +0,0 @@ -package com.fabledsword.minstrel.discover.ui - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.fabledsword.minstrel.api.ErrorCopy -import com.fabledsword.minstrel.connectivity.NetworkStatusController -import com.fabledsword.minstrel.connectivity.recoveries -import com.fabledsword.minstrel.discover.data.DiscoverRepository -import com.fabledsword.minstrel.discover.data.RequestOutcome -import com.fabledsword.minstrel.models.ArtistSuggestionRef -import com.fabledsword.minstrel.models.RequestKind -import com.fabledsword.minstrel.models.CatalogueResultRef -import com.fabledsword.minstrel.models.SuggestionSnoozeRef -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.Job -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import javax.inject.Inject - -// ─── State ─────────────────────────────────────────────────────────── - -data class DiscoverState( - val query: String = "", - val kind: RequestKind = RequestKind.ARTIST, - val suggestions: SuggestionState = SuggestionState.Loading, - val results: ResultsState = ResultsState.Idle, - val locallyRequestedMbids: Set = emptySet(), - /** - * Parked candidates, for the manage list under the feed. Empty is the - * normal case and hides the section entirely. - */ - val snoozes: List = emptyList(), - /** - * Just-snoozed MBIDs. These keep their row visible showing an Undo rather - * than yanking it out from under the user's finger; the row is gone on the - * next load, and [snoozes] is the way back after that. - */ - val locallySnoozedMbids: Set = emptySet(), -) - -sealed interface SuggestionState { - data object Loading : SuggestionState - data class Loaded(val items: List) : SuggestionState - data class Error(val message: String) : SuggestionState -} - -sealed interface ResultsState { - /** No active search — the screen shows the suggestion feed. */ - data object Idle : ResultsState - data object Loading : ResultsState - data class Loaded(val items: List) : ResultsState - data class Error(val message: String) : ResultsState -} - -// ─── ViewModel ─────────────────────────────────────────────────────── - -@HiltViewModel -class DiscoverViewModel @Inject constructor( - private val repository: DiscoverRepository, - networkStatus: NetworkStatusController, -) : ViewModel() { - - private val internal = MutableStateFlow(DiscoverState()) - val state: StateFlow = internal.asStateFlow() - - init { - loadSuggestions() - // Screen-level auto-recovery: re-run whichever pane - // failed while the server was unreachable once health returns. - viewModelScope.launch { - networkStatus.recoveries().collect { - val s = internal.value - if (s.suggestions is SuggestionState.Error) loadSuggestions() - if (s.results is ResultsState.Error) runSearch() - } - } - } - - fun setQuery(value: String) { - internal.update { - // Clearing the box returns to the suggestion feed. - val newResults = if (value.isBlank()) ResultsState.Idle else it.results - it.copy(query = value, results = newResults) - } - } - - fun setKind(kind: RequestKind) { - internal.update { it.copy(kind = kind) } - if (internal.value.query.isNotBlank()) runSearch() - } - - fun loadSuggestions(): Job = viewModelScope.launch { - internal.update { it.copy(suggestions = SuggestionState.Loading) } - try { - val items = repository.listSuggestions() - internal.update { it.copy(suggestions = SuggestionState.Loaded(items)) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy( - suggestions = SuggestionState.Error( - ErrorCopy.fromThrowable(e), - ), - ) - } - } - // Refresh the parked list alongside the deck: a snooze made on another - // client should show up here, and one whose window lapsed should drop - // off. Sequenced after the deck load rather than raced with it so the - // two panes can't disagree about a candidate mid-refresh. - loadSnoozes() - } - - /** - * Loads the parked list. Failure is deliberately silent: this is a - * secondary pane, and an error banner for it would sit above the suggestion - * feed the user actually came for. The list stays as-is and the next - * refresh retries. - */ - private suspend fun loadSnoozes() { - try { - val rows = repository.listSnoozes() - internal.update { it.copy(snoozes = rows) } - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Keep whatever we last showed rather than blanking the section. - } - } - - /** - * Parks a suggestion. Flips the row locally first so the tap registers - * immediately; the repository handles the offline case, so there is no - * failure branch to revert here — unlike the web client, where the fetch - * either lands or doesn't. - */ - suspend fun snoozeSuggestion(s: ArtistSuggestionRef) { - internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids + s.mbid) } - repository.snoozeSuggestion(s.mbid, s.name) - loadSnoozes() - } - - /** Brings a parked suggestion back, from either the card or the list. */ - suspend fun unsnoozeSuggestion(mbid: String, name: String) { - internal.update { it.copy(locallySnoozedMbids = it.locallySnoozedMbids - mbid) } - repository.unsnoozeSuggestion(mbid, name) - loadSnoozes() - } - - fun runSearch() { - val q = internal.value.query.trim() - if (q.isEmpty()) { - internal.update { it.copy(results = ResultsState.Idle) } - return - } - viewModelScope.launch { - internal.update { it.copy(results = ResultsState.Loading) } - try { - val rows = repository.search(q, internal.value.kind) - internal.update { it.copy(results = ResultsState.Loaded(rows)) } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.update { - it.copy(results = ResultsState.Error(ErrorCopy.fromThrowable(e))) - } - } - } - } - - /** - * Request a search-result row. Returns the outcome (ACCEPTED vs - * QUEUED) so the screen can pick the snackbar wording and update - * the local "requested" overlay. - */ - suspend fun requestRow(row: CatalogueResultRef): RequestOutcome { - val kind = internal.value.kind - val outcome = repository.createRequest( - kind = kind, - artistMbid = if (kind == RequestKind.ARTIST) row.mbid else row.artistMbid, - artistName = if (kind == RequestKind.ARTIST) row.name else row.secondaryText, - albumMbid = if (kind == RequestKind.ALBUM) row.mbid else null, - albumTitle = if (kind == RequestKind.ALBUM) row.name else null, - ) - markRequested(row.mbid) - return outcome - } - - suspend fun requestSuggestion(s: ArtistSuggestionRef): RequestOutcome { - val outcome = repository.createRequest( - kind = RequestKind.ARTIST, - artistMbid = s.mbid, - artistName = s.name, - ) - markRequested(s.mbid) - return outcome - } - - private fun markRequested(mbid: String) { - internal.update { it.copy(locallyRequestedMbids = it.locallyRequestedMbids + mbid) } - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/AdminUserRef.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/AdminUserRef.kt index 0d19b4ec..4e44a69c 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/AdminUserRef.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/AdminUserRef.kt @@ -1,8 +1,7 @@ package com.fabledsword.minstrel.models /** - * One admin-side user row. The - * admin-scoped variant exposes `autoApproveRequests` and the + * One admin-side user row. The admin-scoped variant carries the * canonical `createdAt` that the user-scoped /me response omits. */ data class AdminUserRef( @@ -10,6 +9,5 @@ data class AdminUserRef( val username: String, val displayName: String? = null, val isAdmin: Boolean = false, - val autoApproveRequests: Boolean = false, val createdAt: String = "", ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/Discover.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/Discover.kt deleted file mode 100644 index b320ee11..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/Discover.kt +++ /dev/null @@ -1,157 +0,0 @@ -package com.fabledsword.minstrel.models - -import kotlinx.datetime.Instant -import kotlin.math.roundToInt - -/** - * Kind of request being created. Wire form is the lowercase - * enum name; the helper [wire] keeps that mapping in one place. - */ -enum class RequestKind { - ARTIST, ALBUM, TRACK; - - val wire: String get() = name.lowercase() -} - -/** - * Catalogue search hit — `mbid` is the result's own MBID; `artistMbid` - * and `albumMbid` are filled when the row is an album/track and the - * UI needs the parent IDs to build the request. - * - * `inLibrary` and `requested` together cover the "already-handled" - * cases — UI greys the row + swaps the Request button for a pill. - */ -data class CatalogueResultRef( - val mbid: String, - val name: String, - val secondaryText: String = "", - val imageUrl: String = "", - val artistMbid: String = "", - val albumMbid: String = "", - val inLibrary: Boolean = false, - val requested: Boolean = false, -) - -/** - * Per-seed attribution string for a suggestion — "you liked X" / - * "you played Y". `isLiked = true` discriminates the verb. - */ -data class SeedContributionRef( - val name: String, - val isLiked: Boolean, -) - -/** - * Out-of-library artist suggestion from `GET /api/discover/suggestions`. - * `attributionText` names up to 3 seeds with an Oxford comma so the - * subtitle reads naturally. - */ -data class ArtistSuggestionRef( - val mbid: String, - val name: String, - val imageUrl: String = "", - val attribution: List = emptyList(), - /** Taste-profile tags this candidate matches, strongest first. */ - val matchedTags: List = emptyList(), -) { - val attributionText: String - get() { - if (attribution.isEmpty()) return "" - val phrases = attribution - .take(MAX_ATTRIBUTION_PHRASES) - .map { "${if (it.isLiked) "liked" else "played"} ${it.name}" } - return when (phrases.size) { - 1 -> "Because you ${phrases[0]}." - 2 -> "Because you ${phrases[0]} and ${phrases[1]}." - else -> "Because you ${phrases[0]}, ${phrases[1]}, and ${phrases[2]}." - } - } - - /** - * The subtitle line for the card. - * - * Prefers the taste-tag reason over seed attribution when we have one, - * because it describes the MUSIC ("sounds like what you like") rather than - * the graph ("adjacent to something you played"). Falls back to - * attribution, which is the common case: tag coverage for out-of-library - * artists is partial by nature, so most candidates have no matched tags. - * - * Kept in lockstep with the web client's reasonText() in - * SuggestionFeed.svelte — same wording, same Oxford comma. - */ - val reasonText: String - get() { - val tags = matchedTags.take(MAX_ATTRIBUTION_PHRASES) - return when (tags.size) { - 0 -> attributionText - 1 -> "Matches your taste in ${tags[0]}." - 2 -> "Matches your taste in ${tags[0]} and ${tags[1]}." - else -> "Matches your taste in ${tags[0]}, ${tags[1]}, and ${tags[2]}." - } - } - - companion object { - private const val MAX_ATTRIBUTION_PHRASES = 3 - } -} - -/** - * A suggestion the user parked with "not right now". - * - * Deliberately NOT a dislike: it carries no verdict on the artist, expires on - * its own, and never reaches the taste profile. Anything that treats this as - * negative preference signal is a bug. - * - * [snoozedUntil] is the raw RFC3339 string from the wire. Only the server - * decides whether a snooze is still in effect — every row the client receives - * already is — so this is read purely to phrase "back in about 3 months". - */ -data class SuggestionSnoozeRef( - val mbid: String, - val name: String, - val snoozedUntil: String, -) { - /** - * Relative return phrase for the manage list. Relative rather than a - * calendar date because the exact day a 90-day snooze lapses is noise the - * user never asked for. - * - * [nowMs] is injectable so this is testable without freezing the clock. - * Returns "shortly" for an unparseable or already-past timestamp: the row - * is on screen, so the server still considers it snoozed, and guessing is - * better than rendering an empty line. - */ - fun returnsIn(nowMs: Long = System.currentTimeMillis()): String { - val remainingMs = runCatching { Instant.parse(snoozedUntil).toEpochMilliseconds() } - .getOrNull()?.minus(nowMs) - // Two ways to have nothing to state: an unparseable timestamp, or one - // already lapsed by our clock though the server still returned the row - // (the two disagree). Neither is "today", which would read as a real - // prediction. - if (remainingMs == null || remainingMs <= 0) return "shortly" - val days = (remainingMs.toDouble() / MILLIS_PER_DAY).roundToInt() - return when { - days < 1 -> "today" - days == 1 -> "tomorrow" - days < DAYS_BEFORE_MONTHS -> "in $days days" - else -> { - val months = (days.toDouble() / DAYS_PER_MONTH).roundToInt() - if (months == 1) "in about a month" else "in about $months months" - } - } - } - - private companion object { - const val MILLIS_PER_DAY = 86_400_000.0 - - // Below this, days read more naturally than a rounded month count. - // - // Must be <= DAYS_PER_MONTH, or the singular "in about a month" is - // unreachable: a rounded month count of 1 needs 15..44 days, and any - // threshold above 30 sends all of those down the days branch instead. - // This was 45 and the singular branch was dead code — the unit test - // for it is what surfaced that. - const val DAYS_BEFORE_MONTHS = 30 - const val DAYS_PER_MONTH = 30.0 - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/Request.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/Request.kt deleted file mode 100644 index 29b59394..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/Request.kt +++ /dev/null @@ -1,64 +0,0 @@ -package com.fabledsword.minstrel.models - -/** - * Status of a request. Stored on the wire as a plain string; - * the typed enum keeps switch / when blocks exhaustive and lets the - * UI map directly to a status pill color without raw-string matches. - */ -enum class RequestStatus { - PENDING, APPROVED, REJECTED, COMPLETED, FAILED, UNKNOWN; - - companion object { - fun fromWire(s: String): RequestStatus = when (s) { - "pending" -> PENDING - "approved" -> APPROVED - "rejected" -> REJECTED - "completed" -> COMPLETED - "failed" -> FAILED - else -> UNKNOWN - } - } - - val wire: String get() = name.lowercase() -} - -/** - * One request the user has submitted, shared between the user-side - * `/api/requests` view and the admin cross-user view since the wire - * shape is identical. - * - * `displayName` picks the right field based on kind: - * - album → albumTitle (fallback artistName) - * - track → trackTitle (fallback artistName) - * - artist → artistName - * - * `listenHrefId` returns the most-specific matched library ID once the - * request completes (track → album → artist) so the "Listen" CTA can - * navigate to the right detail screen. Returns null until the - * server's ingest job populates the matched_* fields. - */ -data class RequestRef( - val id: String, - val userId: String, - val username: String = "", - val status: RequestStatus, - val kind: String, - val artistName: String, - val albumTitle: String? = null, - val trackTitle: String? = null, - val requestedAt: String, - val decidedAt: String? = null, - val notes: String? = null, - val importedAlbumCount: Int = 0, - val importedTrackCount: Int = 0, - val matchedTrackId: String? = null, - val matchedAlbumId: String? = null, - val matchedArtistId: String? = null, -) { - val displayName: String - get() = when (kind) { - "album" -> albumTitle ?: artistName - "track" -> trackTitle ?: artistName - else -> artistName - } -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/AdminUserWire.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/AdminUserWire.kt index 18fe9227..dc93d7ac 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/AdminUserWire.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/AdminUserWire.kt @@ -6,8 +6,8 @@ import kotlinx.serialization.Serializable /** * One admin-side user row. Mirrors `adminUserView` from * `internal/api/admin_users.go`. Distinct from the user-scoped /me - * profile shape because admin endpoints expose `auto_approve_requests` - * and the canonical `created_at`. + * profile shape because admin endpoints expose the canonical + * `created_at`. */ @Serializable data class AdminUserWire( @@ -15,7 +15,6 @@ data class AdminUserWire( val username: String = "", @SerialName("display_name") val displayName: String? = null, @SerialName("is_admin") val isAdmin: Boolean = false, - @SerialName("auto_approve_requests") val autoApproveRequests: Boolean = false, @SerialName("created_at") val createdAt: String = "", ) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/DiscoverWire.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/DiscoverWire.kt deleted file mode 100644 index 60de2119..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/DiscoverWire.kt +++ /dev/null @@ -1,100 +0,0 @@ -package com.fabledsword.minstrel.models.wire - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable - -/** - * One row of `GET /api/catalogue/search` (the MusicBrainz search). Mirrors - * `web/src/lib/api/types.ts` CatalogueSearchResult. `imageUrl` is the - * server's own art endpoint, relative, so it goes through ServerImage. - * - * `inLibrary` and `requested` let the UI greyout rows the user can't - * act on (already imported / already awaiting review). All defaults - * empty so missing keys don't throw on decode. - */ -@Serializable -data class CatalogueSearchResultWire( - val mbid: String = "", - val name: String = "", - @SerialName("secondary_text") val secondaryText: String = "", - @SerialName("image_url") val imageUrl: String = "", - @SerialName("artist_mbid") val artistMbid: String = "", - @SerialName("album_mbid") val albumMbid: String = "", - @SerialName("in_library") val inLibrary: Boolean = false, - val requested: Boolean = false, -) - -/** - * `GET /api/discover/suggestions` row — an out-of-library artist - * surfaced from ListenBrainz-derived seeds. `imageUrl` may be empty. - */ -@Serializable -data class ArtistSuggestionWire( - val mbid: String = "", - val name: String = "", - @SerialName("image_url") val imageUrl: String = "", - val attribution: List = emptyList(), - /** - * Tags this candidate shares with the user's taste profile, strongest - * first (max 3). Absent for most candidates — tag coverage for - * out-of-library artists is partial by nature — so the default - * empty list is the common case, not an error. - */ - @SerialName("matched_tags") val matchedTags: List = emptyList(), -) - -/** - * Per-seed attribution for an ArtistSuggestion — "because you liked X" - * / "because you played Y". `isLiked = true` means the seed came from - * the user's likes; false means a played-but-not-liked play. - */ -@Serializable -data class SeedContributionWire( - val name: String = "", - @SerialName("is_liked") val isLiked: Boolean = false, -) - -/** - * One row of `GET /api/discover/snoozes` — a suggestion the user parked - * with "not right now". The server only returns rows that are still in - * effect, so the client never compares [snoozedUntil] against the clock to - * decide whether to show it; it reads it only to say when the artist comes - * back. - */ -@Serializable -data class SuggestionSnoozeWire( - val mbid: String = "", - val name: String = "", - @SerialName("snoozed_until") val snoozedUntil: String = "", - @SerialName("created_at") val createdAt: String = "", -) - -/** - * Body for `POST /api/discover/suggestions/{mbid}/snooze`. - * - * [name] is required by the server, not decorative: suggestions are - * out-of-library, so there is no artists row to resolve a display name from - * and the snooze list would have nothing to render. Omitting it is a 400. - * - * No `days` field. The duration is the server's to own (90 days); pinning it - * client-side would freeze the default at whatever this build shipped. - */ -@Serializable -data class SnoozeSuggestionBody( - val name: String, -) - -/** - * Body posted to `POST /api/requests`. Optional fields are emitted only - * when non-null server-side; matching that here keeps the wire identical. - */ -@Serializable -data class CreateRequestBody( - val kind: String, - @SerialName("artist_mbid") val artistMbid: String, - @SerialName("artist_name") val artistName: String, - @SerialName("album_mbid") val albumMbid: String? = null, - @SerialName("album_title") val albumTitle: String? = null, - @SerialName("track_mbid") val trackMbid: String? = null, - @SerialName("track_title") val trackTitle: String? = null, -) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/RequestWire.kt b/android/app/src/main/java/com/fabledsword/minstrel/models/wire/RequestWire.kt deleted file mode 100644 index d78cd555..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/models/wire/RequestWire.kt +++ /dev/null @@ -1,37 +0,0 @@ -package com.fabledsword.minstrel.models.wire - -import kotlinx.serialization.SerialName -import kotlinx.serialization.Serializable - -/** - * Wire shape of `requestView` from `internal/api/requests.go` — the - * row returned by both `GET /api/requests` (caller's own requests) and - * `GET /api/admin/requests` (cross-user admin view). - * - * Status values: `pending` / `approved` / `rejected` / `completed` / - * `failed`. Kind values: `artist` / `album` / `track`. - * - * `matched_*_id` are set after a completed request ingests into the - * local library; the user-side "Listen" affordance picks the most - * specific one (track → album → artist). - */ -@Serializable -data class RequestWire( - val id: String, - @SerialName("user_id") val userId: String = "", - // The requester's username. Only `GET /api/admin/requests` sends it. - val username: String = "", - val status: String = "pending", - val kind: String = "artist", - @SerialName("artist_name") val artistName: String = "", - @SerialName("album_title") val albumTitle: String? = null, - @SerialName("track_title") val trackTitle: String? = null, - @SerialName("requested_at") val requestedAt: String = "", - @SerialName("decided_at") val decidedAt: String? = null, - val notes: String? = null, - @SerialName("imported_album_count") val importedAlbumCount: Int = 0, - @SerialName("imported_track_count") val importedTrackCount: Int = 0, - @SerialName("matched_track_id") val matchedTrackId: String? = null, - @SerialName("matched_album_id") val matchedAlbumId: String? = null, - @SerialName("matched_artist_id") val matchedArtistId: String? = null, -) 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 64decef0..0a5ec914 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 @@ -15,12 +15,10 @@ import androidx.navigation.compose.NavHost import androidx.navigation.compose.composable import com.fabledsword.minstrel.admin.ui.AdminLandingScreen import com.fabledsword.minstrel.admin.ui.AdminQuarantineScreen -import com.fabledsword.minstrel.admin.ui.AdminRequestsScreen import com.fabledsword.minstrel.admin.ui.AdminTagSourcesScreen import com.fabledsword.minstrel.admin.ui.AdminUsersScreen import com.fabledsword.minstrel.auth.ui.LoginScreen import com.fabledsword.minstrel.auth.ui.ServerUrlScreen -import com.fabledsword.minstrel.discover.ui.DiscoverScreen import com.fabledsword.minstrel.home.ui.HomeScreen import com.fabledsword.minstrel.library.ui.AlbumDetailScreen import com.fabledsword.minstrel.library.ui.ArtistDetailScreen @@ -31,7 +29,6 @@ import com.fabledsword.minstrel.player.ui.NowPlayingScreen import com.fabledsword.minstrel.player.ui.QueueScreen import com.fabledsword.minstrel.playlists.ui.PlaylistDetailScreen import com.fabledsword.minstrel.playlists.ui.PlaylistsListScreen -import com.fabledsword.minstrel.requests.ui.RequestsScreen import com.fabledsword.minstrel.search.ui.SearchScreen import com.fabledsword.minstrel.settings.ui.SettingsScreen import com.fabledsword.minstrel.shared.widgets.ShellScaffold @@ -92,13 +89,6 @@ private fun NavGraphBuilder.inShellTopLevel( } } } - composable { - WithAnimatedScope { - ShellScaffold(onExpandPlayer = expandPlayer) { - DiscoverScreen(navController = navController) - } - } - } composable { WithAnimatedScope { ShellScaffold(onExpandPlayer = expandPlayer) { @@ -120,13 +110,6 @@ private fun NavGraphBuilder.inShellTopLevel( } } } - composable { - WithAnimatedScope { - ShellScaffold(onExpandPlayer = expandPlayer) { - RequestsScreen(navController = navController) - } - } - } } /** @@ -172,13 +155,6 @@ private fun NavGraphBuilder.inShellDetail( } } } - composable { - WithAnimatedScope { - ShellScaffold(onExpandPlayer = expandPlayer) { - AdminRequestsScreen(navController = navController) - } - } - } composable { WithAnimatedScope { ShellScaffold(onExpandPlayer = expandPlayer) { 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 830a09f3..53d87db6 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 @@ -8,11 +8,9 @@ import kotlinx.serialization.Serializable @Serializable data object Home @Serializable data object Library @Serializable data object Search -@Serializable data object Discover @Serializable data object Playlists @Serializable data object Settings @Serializable data object Admin -@Serializable data object Requests @Serializable data object Notifications @Serializable data object NotificationSettings @@ -21,7 +19,6 @@ import kotlinx.serialization.Serializable @Serializable data class AlbumDetail(val id: String) @Serializable data class ArtistDetail(val id: String) @Serializable data class PlaylistDetail(val id: String) -@Serializable data object AdminRequests @Serializable data object AdminQuarantine @Serializable data object AdminUsers @Serializable data object AdminTagSources 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 bac2fce0..99f16329 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 @@ -2,10 +2,8 @@ package com.fabledsword.minstrel.notifications.ui import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.AdminQuarantine -import com.fabledsword.minstrel.nav.AdminRequests import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.Requests /** * The app screen for a notice's link. The server writes web paths, the same @@ -22,8 +20,6 @@ internal fun routeForLink(link: String): Any? { return when { parts.size == 2 && parts[0] == "albums" -> AlbumDetail(parts[1]) parts.size == 2 && parts[0] == "artists" -> ArtistDetail(parts[1]) - parts == listOf("requests") -> Requests - parts == listOf("admin", "requests") -> AdminRequests parts == listOf("collection", "reports") -> AdminQuarantine parts.firstOrNull() == "collection" && parts.getOrNull(1) in ADMIN_COLLECTION_PAGES -> Admin parts.firstOrNull() == "admin" -> Admin 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 c3add71a..82e34875 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 @@ -80,7 +80,7 @@ fun NotificationsScreen( list == null -> LoadingCentered() list.isEmpty() -> EmptyState( title = "Nothing waiting for you", - body = "Requests, new music and anything needing a look will gather here.", + body = "Library problems and anything needing a look will gather here.", icon = Lucide.Bell, ) else -> LazyColumn(modifier = Modifier.fillMaxSize()) { diff --git a/android/app/src/main/java/com/fabledsword/minstrel/requests/data/RequestsRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/requests/data/RequestsRepository.kt deleted file mode 100644 index 4814e651..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/requests/data/RequestsRepository.kt +++ /dev/null @@ -1,73 +0,0 @@ -package com.fabledsword.minstrel.requests.data - -import com.fabledsword.minstrel.api.endpoints.RequestsApi -import com.fabledsword.minstrel.cache.mutations.MutationQueue -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.models.RequestStatus -import com.fabledsword.minstrel.models.wire.RequestWire -import retrofit2.Retrofit -import retrofit2.create -import java.io.IOException -import javax.inject.Inject -import javax.inject.Singleton - -/** - * Outcome of a [RequestsRepository.cancel] call. Mirrors the - * [com.fabledsword.minstrel.likes.data.UnflagOutcome] / etc. shape. - */ -enum class CancelOutcome { Synced, Queued } - -/** - * Read-through accessor for the caller's own requests + - * cancel-while-pending write. No Room caching. Cancel is offline-first: - * direct REST on the happy - * path, MutationQueue fallback on transport failure so the user's - * intent persists across connectivity loss. - */ -@Singleton -class RequestsRepository @Inject constructor( - private val mutationQueue: MutationQueue, - retrofit: Retrofit, -) { - private val api: RequestsApi = retrofit.create() - - suspend fun listMine(): List = - api.listMine().map { it.toDomain() } - - /** - * Cancels a pending request. On 2xx, returns the canonical - * cancelled row from the server (status=rejected). On transport - * failure, enqueues a REQUEST_CANCEL mutation for later replay - * and returns null — the caller's optimistic UI removal already - * reflects the user's intent, and the next listMine() refetch - * (post-replay) will surface the canonical row. - */ - suspend fun cancel(id: String): Pair = try { - CancelOutcome.Synced to api.cancel(id).toDomain() - } catch ( - @Suppress("SwallowedException") _: IOException, - ) { - mutationQueue.enqueueRequestCancel(id) - CancelOutcome.Queued to null - } -} - -// ── Mappers (internal — wire stays out of UI) ── - -private fun RequestWire.toDomain(): RequestRef = RequestRef( - id = id, - userId = userId, - status = RequestStatus.fromWire(status), - kind = kind, - artistName = artistName, - albumTitle = albumTitle, - trackTitle = trackTitle, - requestedAt = requestedAt, - decidedAt = decidedAt, - notes = notes, - importedAlbumCount = importedAlbumCount, - importedTrackCount = importedTrackCount, - matchedTrackId = matchedTrackId, - matchedAlbumId = matchedAlbumId, - matchedArtistId = matchedArtistId, -) diff --git a/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsScreen.kt b/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsScreen.kt deleted file mode 100644 index 03d13202..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsScreen.kt +++ /dev/null @@ -1,313 +0,0 @@ -@file:Suppress("TooManyFunctions") // Compose screen + private helper composables - -package com.fabledsword.minstrel.requests.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.fillMaxWidth -import androidx.compose.foundation.layout.padding -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.AssistChip -import androidx.compose.material3.Button -import androidx.compose.material3.HorizontalDivider -import androidx.compose.material3.Icon -import androidx.compose.material3.MaterialTheme -import androidx.compose.material3.OutlinedButton -import androidx.compose.material3.Scaffold -import androidx.compose.material3.Text -import androidx.compose.material3.TextButton -import androidx.compose.runtime.Composable -import androidx.compose.runtime.getValue -import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.remember -import androidx.compose.runtime.setValue -import androidx.compose.ui.Alignment -import androidx.compose.ui.Modifier -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.Disc3 -import com.composables.icons.lucide.LibraryBig -import com.composables.icons.lucide.Lucide -import com.composables.icons.lucide.Music -import com.composables.icons.lucide.Play -import com.composables.icons.lucide.X -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.models.RequestStatus -import com.fabledsword.minstrel.nav.AlbumDetail -import com.fabledsword.minstrel.shared.UiState -import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.Requests -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 - -@Composable -fun RequestsScreen( - navController: NavHostController, - viewModel: RequestsViewModel = hiltViewModel(), -) { - val state by viewModel.uiState.collectAsStateWithLifecycle() - Scaffold( - contentWindowInsets = ShellContentWindowInsets, - modifier = Modifier.fillMaxSize(), - topBar = { - MinstrelTopAppBar( - title = "Your requests", - navController = navController, - currentRouteName = Requests::class.qualifiedName, - onBack = { navController.popBackStack() }, - ) - }, - ) { inner -> - PullToRefreshScaffold( - onRefresh = { viewModel.refresh().join() }, - modifier = Modifier.fillMaxSize().padding(inner), - ) { - when (val s = state) { - UiState.Loading -> LoadingCentered() - UiState.Empty -> EmptyState( - title = "Nothing requested yet", - body = "Use Discover to ask for new music; your " + - "requests show up here.", - ) - is UiState.Error -> ErrorRetry( - title = "Couldn't load requests", - message = s.message, - onRetry = { viewModel.refresh() }, - ) - is UiState.Success -> RequestList( - rows = s.data, - onCancel = viewModel::cancel, - onListen = { id -> navController.navigate(id) }, - ) - } - } - } -} - -@Composable -private fun RequestList( - rows: List, - onCancel: (String) -> Unit, - onListen: (Any) -> Unit, -) { - LazyColumn(modifier = Modifier.fillMaxSize()) { - items(items = rows, key = { it.id }) { req -> - RequestRow( - req = req, - onCancel = { onCancel(req.id) }, - onListen = req.listenRoute()?.let { route -> { onListen(route) } }, - ) - HorizontalDivider() - } - } -} - -@Composable -private fun RequestRow( - req: RequestRef, - onCancel: () -> Unit, - onListen: (() -> Unit)?, -) { - var showCancelConfirm by remember { mutableStateOf(false) } - Row( - modifier = Modifier - .fillMaxWidth() - .padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(12.dp), - ) { - KindAvatar(kind = req.kind) - RequestRowBody(req = req, modifier = Modifier.weight(1f)) - RequestRowAction( - req = req, - onListen = onListen, - onAskCancel = { showCancelConfirm = true }, - ) - } - if (showCancelConfirm) { - CancelConfirmDialog( - displayName = req.displayName, - onConfirm = { - showCancelConfirm = false - onCancel() - }, - onDismiss = { showCancelConfirm = false }, - ) - } -} - -@Composable -private fun RequestRowBody(req: RequestRef, modifier: Modifier = Modifier) { - Column(modifier = modifier) { - Text( - text = req.displayName, - style = MaterialTheme.typography.bodyLarge, - color = MaterialTheme.colorScheme.onSurface, - maxLines = 1, - overflow = TextOverflow.Ellipsis, - ) - Row( - modifier = Modifier.padding(top = 4.dp), - horizontalArrangement = Arrangement.spacedBy(6.dp), - ) { - StatusPill(status = req.status) - KindPill(label = req.kind) - } - val progress = req.ingestProgressText() - if (progress != null) { - Text( - text = progress, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 4.dp), - ) - } - if (req.status == RequestStatus.REJECTED && !req.notes.isNullOrEmpty()) { - Text( - text = req.notes, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.padding(top = 4.dp), - maxLines = 2, - overflow = TextOverflow.Ellipsis, - ) - } - } -} - -@Composable -private fun RequestRowAction( - req: RequestRef, - onListen: (() -> Unit)?, - onAskCancel: () -> Unit, -) { - when { - onListen != null -> OutlinedButton(onClick = onListen) { - Icon( - Lucide.Play, - contentDescription = null, - modifier = Modifier.size(16.dp).padding(end = 4.dp), - ) - Text("Listen") - } - req.status == RequestStatus.PENDING -> TextButton(onClick = onAskCancel) { - Icon(Lucide.X, contentDescription = null, modifier = Modifier.padding(end = 4.dp)) - Text("Cancel") - } - } -} - -@Composable -private fun CancelConfirmDialog( - displayName: String, - onConfirm: () -> Unit, - onDismiss: () -> Unit, -) { - AlertDialog( - onDismissRequest = onDismiss, - title = { Text("Cancel request?") }, - text = { Text("Cancel “$displayName”? Your request is withdrawn.") }, - confirmButton = { - Button(onClick = onConfirm) { Text("Cancel request") } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text("Keep") } - }, - ) -} - -@Composable -private fun KindAvatar(kind: String) { - // Icons: disc-3 for artist, library-big for album, music for track. - val icon = when (kind) { - "artist" -> Lucide.Disc3 - "album" -> Lucide.LibraryBig - "track" -> Lucide.Music - else -> Lucide.Music - } - Icon( - imageVector = icon, - contentDescription = null, - tint = MaterialTheme.colorScheme.onSurfaceVariant, - modifier = Modifier.size(28.dp), - ) -} - -/** - * Most-specific listenable detail-screen route for a completed - * request, or null when nothing's been matched / the status isn't - * completed. Track-level matches resolve to AlbumDetail since the - * client has no TrackDetail screen. - */ -private fun RequestRef.listenRoute(): Any? = when { - status != RequestStatus.COMPLETED -> null - !matchedAlbumId.isNullOrEmpty() -> AlbumDetail(matchedAlbumId) - !matchedArtistId.isNullOrEmpty() -> ArtistDetail(matchedArtistId) - else -> null -} - -/** - * "2 albums · 14 tracks ingested" — null when both counts are zero. - * Singular when the count is 1 ("1 album · 1 track ingested"). - */ -private fun RequestRef.ingestProgressText(): String? { - if (importedAlbumCount == 0 && importedTrackCount == 0) return null - val parts = buildList { - if (importedAlbumCount > 0) { - add( - "$importedAlbumCount ${if (importedAlbumCount == 1) "album" else "albums"}", - ) - } - if (importedTrackCount > 0) { - add( - "$importedTrackCount ${if (importedTrackCount == 1) "track" else "tracks"}", - ) - } - } - return "${parts.joinToString(" · ")} ingested" -} - -@Composable -private fun StatusPill(status: RequestStatus) { - val (label, isError) = when (status) { - RequestStatus.PENDING -> "pending" to false - RequestStatus.APPROVED -> "approved" to false - RequestStatus.COMPLETED -> "completed" to false - RequestStatus.REJECTED -> "rejected" to true - RequestStatus.FAILED -> "failed" to true - RequestStatus.UNKNOWN -> "unknown" to false - } - val color = if (isError) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.primary - AssistChip( - onClick = {}, - enabled = false, - label = { Text(label, color = color) }, - ) -} - -@Composable -private fun KindPill(label: String) { - AssistChip( - onClick = {}, - enabled = false, - label = { - Text( - label, - style = MaterialTheme.typography.labelSmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - }, - ) -} diff --git a/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsViewModel.kt b/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsViewModel.kt deleted file mode 100644 index d1c3a82d..00000000 --- a/android/app/src/main/java/com/fabledsword/minstrel/requests/ui/RequestsViewModel.kt +++ /dev/null @@ -1,177 +0,0 @@ -package com.fabledsword.minstrel.requests.ui - -import androidx.lifecycle.ViewModel -import androidx.lifecycle.viewModelScope -import com.fabledsword.minstrel.api.ErrorCopy -import com.fabledsword.minstrel.connectivity.NetworkStatusController -import com.fabledsword.minstrel.connectivity.recoveries -import com.fabledsword.minstrel.events.EventsStream -import com.fabledsword.minstrel.models.RequestRef -import com.fabledsword.minstrel.models.RequestStatus -import com.fabledsword.minstrel.requests.data.CancelOutcome -import com.fabledsword.minstrel.requests.data.RequestsRepository -import com.fabledsword.minstrel.shared.UiState -import dagger.hilt.android.lifecycle.HiltViewModel -import kotlinx.coroutines.Job -import kotlinx.coroutines.delay -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.filter -import kotlinx.coroutines.flow.update -import kotlinx.coroutines.launch -import javax.inject.Inject - -private val RELEVANT_EVENT_KINDS = setOf("request.status_changed") - -// Cadence for in-flight request polling — matches the web client: -// fast enough to feel live, slow enough not to hammer the server. -private const val POLL_INTERVAL_MS = 12_000L - -@HiltViewModel -class RequestsViewModel @Inject constructor( - private val repository: RequestsRepository, - private val eventsStream: EventsStream, - networkStatus: NetworkStatusController, -) : ViewModel() { - - private val internal = MutableStateFlow>>(UiState.Loading) - val uiState: StateFlow>> = internal.asStateFlow() - - init { - refresh() - // SSE push: reconciler completions arrive here; reload silently so the - // row updates in place rather than flashing the loading spinner. - viewModelScope.launch { - eventsStream.events - .filter { it.kind in RELEVANT_EVENT_KINDS } - .collect { silentReload() } - } - viewModelScope.launch { pollWhileInFlight() } - // Screen-level auto-recovery: a load that failed while - // the server was unreachable heals the moment health returns, without - // waiting for the next poll tick. - viewModelScope.launch { - networkStatus.recoveries().collect { - if (internal.value is UiState.Error) silentReload() - } - } - } - - fun refresh(): Job = viewModelScope.launch { - internal.value = UiState.Loading - try { - val rows = repository.listMine() - internal.value = if (rows.isEmpty()) { - UiState.Empty - } else { - UiState.Success(rows) - } - } catch ( - @Suppress("TooGenericExceptionCaught") e: Throwable, - ) { - internal.value = UiState.Error(ErrorCopy.fromThrowable(e)) - } - } - - /** - * Auto-poll while any request is mid-ingest (status APPROVED), matching the - * web client. Reloads silently every [POLL_INTERVAL_MS] and pauses - * when nothing is in-flight — complements the SSE push so progress stays - * live even if the event stream drops. - */ - private suspend fun pollWhileInFlight() { - while (true) { - // Also retry from a failed load: from UiState.Error - // the in-flight predicate can never become true, so without this - // the poll never self-heals the screen — e.g. after a transient - // 500 that health monitoring (transport-level) never saw. - if (hasInFlightRequest() || internal.value is UiState.Error) { - silentReload() - } - delay(POLL_INTERVAL_MS) - } - } - - private fun hasInFlightRequest(): Boolean { - val state = internal.value - return state is UiState.Success && - state.data.any { it.status == RequestStatus.APPROVED } - } - - /** - * Reload the list in place without flipping to Loading — used by the poll - * loop and the SSE collector so visible rows update without a spinner - * flash. A transient failure keeps the current view; the next reload wins. - */ - private suspend fun silentReload() { - try { - val rows = repository.listMine() - internal.value = if (rows.isEmpty()) UiState.Empty else UiState.Success(rows) - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Keep the current view; the next poll / SSE / pull reconciles. - } - } - - /** - * Optimistically removes [id] from the success list so the row - * disappears immediately; on server-side success the row is - * replaced by the canonical cancelled state from the return value. - * On error rolls back by refetching the list. - */ - fun cancel(id: String) { - val before = internal.value - if (before is UiState.Success) { - val filtered = before.data.filterNot { it.id == id } - internal.value = if (filtered.isEmpty()) { - UiState.Empty - } else { - UiState.Success(filtered) - } - } - viewModelScope.launch { - try { - val (outcome, updated) = repository.cancel(id) - if (updated != null) { - internal.update { state -> - if (state !is UiState.Success) { - // Mid-refresh — let the refresh result win, but - // splice the cancelled row in so it shows the new - // status if the user re-pulls. - UiState.Success(listOf(updated)) - } else { - // Re-insert the cancelled row in its old position - // would require remembering the prior ordering; - // simpler to refetch in the background. - state - } - } - } - // Only refetch on the Synced outcome. The - // Queued path is offline by definition — the optimistic - // removal at the top of cancel() is correct, and a - // refresh() call here would either (a) get the - // not-yet-delivered cancelled row back from the server - // and snap it into the list (confusing), or (b) fail - // with a transport error and flip the whole screen to - // UiState.Error, making the user think the cancel - // failed. The mutation queue will replay the cancel - // when connectivity returns; the next on-screen refresh - // (pull-to-refresh, navigation back) reconciles. - if (outcome == CancelOutcome.Synced) { - refresh() - } - } catch ( - @Suppress("TooGenericExceptionCaught", "SwallowedException") e: Throwable, - ) { - // Roll back by re-fetching; the failed cancel might - // already be visible to the server (eventual consistency) - // or not at all (transport drop). The refetch makes - // local state match either outcome. - refresh() - } - } - } -} 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 0565fc94..2fe65f65 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 @@ -27,13 +27,11 @@ 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.ListMusic import com.composables.icons.lucide.LogOut import com.composables.icons.lucide.Lucide import com.composables.icons.lucide.Shield import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.NotificationSettings -import com.fabledsword.minstrel.nav.Requests import com.fabledsword.minstrel.nav.ServerUrl import com.fabledsword.minstrel.nav.Settings as SettingsRoute import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar @@ -87,7 +85,6 @@ fun SettingsScreen( state = state, themeMode = themeMode, onPickTheme = themeVm::setThemeMode, - onNavToRequests = { navController.navigate(Requests) }, onNavToNotifications = { navController.navigate(NotificationSettings) }, onNavToAdmin = { navController.navigate(Admin) }, onToggleDiagnostics = viewModel::setDiagnosticsOptOut, @@ -111,7 +108,6 @@ private fun SettingsList( state: SettingsState, themeMode: ThemeMode, onPickTheme: (ThemeMode) -> Unit, - onNavToRequests: () -> Unit, onNavToNotifications: () -> Unit, onNavToAdmin: () -> Unit, onToggleDiagnostics: (Boolean) -> Unit, @@ -127,7 +123,6 @@ private fun SettingsList( ) { AccountSection( state = state, - onNavToRequests = onNavToRequests, onNavToNotifications = onNavToNotifications, onNavToAdmin = onNavToAdmin, onSignOutClick = onSignOutClick, @@ -175,7 +170,6 @@ private fun SignOutConfirmDialog(onConfirm: () -> Unit, onDismiss: () -> Unit) { @Composable private fun AccountSection( state: SettingsState, - onNavToRequests: () -> Unit, onNavToNotifications: () -> Unit, onNavToAdmin: () -> Unit, onSignOutClick: () -> Unit, @@ -186,12 +180,6 @@ private fun AccountSection( summary = if (state.isAdmin) "Signed in · admin" else "Signed in", ) SettingRow(title = "Server", summary = state.serverUrl) - SettingRow( - title = "My requests", - summary = "What you've asked Minstrel to add", - icon = Lucide.ListMusic, - onClick = onNavToRequests, - ) { RowChevron() } SettingRow( title = "Notifications", summary = "What reaches you, and where", @@ -201,7 +189,7 @@ private fun AccountSection( if (state.isAdmin) { SettingRow( title = "Admin", - summary = "Requests, quarantine and users", + summary = "Library health, users and metadata", icon = Lucide.Shield, onClick = onNavToAdmin, ) { RowChevron() } 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 634400b4..4c0f62ad 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 @@ -24,7 +24,6 @@ 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.Discover import com.fabledsword.minstrel.nav.Home import com.fabledsword.minstrel.nav.Library import com.fabledsword.minstrel.nav.Notifications @@ -37,7 +36,7 @@ import com.fabledsword.minstrel.nav.Settings as SettingsRoute * bottom nav, drawer, or rail; every * top-level AppBar carries this row, and the kebab covers the rest. * - * [Home] [Library] [Search] [ ⋮ Playlists / Discover / Settings / Admin ] + * [Home] [Library] [Search] [ ⋮ Playlists / Settings / Admin ] * * The icon for the screen the user is currently on is suppressed so * the action set looks contextual. The "Admin" overflow item is @@ -124,10 +123,6 @@ private fun OverflowMenu(navController: NavHostController, isAdmin: Boolean) { text = { Text("Playlists") }, onClick = { expanded = false; navController.navigate(Playlists) }, ) - DropdownMenuItem( - text = { Text("Discover") }, - onClick = { expanded = false; navController.navigate(Discover) }, - ) DropdownMenuItem( text = { Text("Settings") }, onClick = { expanded = false; navController.navigate(SettingsRoute) }, diff --git a/android/app/src/test/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepositoryTest.kt deleted file mode 100644 index 9aae6bb9..00000000 --- a/android/app/src/test/java/com/fabledsword/minstrel/admin/data/AdminRequestsRepositoryTest.kt +++ /dev/null @@ -1,39 +0,0 @@ -package com.fabledsword.minstrel.admin.data - -import com.fabledsword.minstrel.api.endpoints.AdminRequestsApi -import com.fabledsword.minstrel.models.wire.RequestWire -import io.mockk.coEvery -import io.mockk.every -import io.mockk.mockk -import kotlinx.coroutines.test.runTest -import org.junit.jupiter.api.Test -import retrofit2.Retrofit -import kotlin.test.assertEquals - -/** - * The admin queue names who asked from the row itself: the server - * sends the requester's username, so the screen needs no users-list fetch. - */ -class AdminRequestsRepositoryTest { - private val api: AdminRequestsApi = mockk(relaxed = true) - private val retrofit: Retrofit = mockk { - every { create(AdminRequestsApi::class.java) } returns api - } - private val repo = AdminRequestsRepository(retrofit) - - @Test - fun `a request carries the requester's username`() = runTest { - coEvery { api.list() } returns listOf( - RequestWire(id = "r1", userId = "f7e1ec86-0e76-4cad-8191-b0cc78492851", username = "alice"), - ) - - assertEquals("alice", repo.list().single().username) - } - - @Test - fun `a request without a username keeps it empty`() = runTest { - coEvery { api.list() } returns listOf(RequestWire(id = "r1", userId = "u1")) - - assertEquals("", repo.list().single().username) - } -} 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 0fc5e568..c341da5b 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 @@ -70,8 +70,7 @@ class BaseUrlInterceptorTest { // External artwork hosts (artwork.musicbrainz.org, // coverartarchive.org) are absolute external URLs. The // interceptor must NOT rewrite them to the Minstrel base — - // doing so produces 404s the user saw as missing Discover - // suggestion covers. + // doing so produces 404s, and the art never shows. authStore.setBaseUrl(server.url("/").toString()) var seen: HttpUrl? = null val client = 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 c055e4fb..425785ca 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 @@ -13,22 +13,13 @@ import kotlin.test.assertTrue * Collapse rules for desired-state toggles in the offline queue. * * The hazard this guards against is real and silent: without collapsing, a - * queued snooze that replays AFTER the user's undo re-hides an artist they - * asked to see again, and nothing surfaces the contradiction. + * queued like that replays AFTER the user's unlike likes the artist again, + * and nothing surfaces the contradiction. */ class SupersededToggleIdsTest { private val json = Json { ignoreUnknownKeys = true } - private fun snoozeRow(id: Long, mbid: String, desiredSnoozed: Boolean) = CachedMutationEntity( - id = id, - kind = MutationKind.SUGGESTION_SNOOZE_TOGGLE, - payload = json.encodeToString( - SuggestionSnoozeTogglePayload.serializer(), - SuggestionSnoozeTogglePayload(mbid, "Name", desiredSnoozed), - ), - ) - private fun likeRow(id: Long, entityId: String, desired: Boolean) = CachedMutationEntity( id = id, kind = MutationKind.LIKE_TOGGLE, @@ -39,54 +30,46 @@ class SupersededToggleIdsTest { ) @Test - fun `a snooze followed by its undo drops the snooze`() { + fun `a like followed by its undo drops the like`() { val rows = listOf( - snoozeRow(1, "mb-a", desiredSnoozed = true), - snoozeRow(2, "mb-a", desiredSnoozed = false), + 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 candidates never collapse into each other`() { + fun `toggles for different entities never collapse into each other`() { val rows = listOf( - snoozeRow(1, "mb-a", desiredSnoozed = true), - snoozeRow(2, "mb-b", desiredSnoozed = true), + 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 candidate survives`() { + fun `only the newest of several toggles for one entity survives`() { val rows = listOf( - snoozeRow(1, "mb-a", desiredSnoozed = true), - snoozeRow(2, "mb-a", desiredSnoozed = false), - snoozeRow(3, "mb-a", desiredSnoozed = true), + 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)) } - // The kind is part of the collapse key, so a snooze and a like that happen - // to share an id string must not shadow one another. + // The kind is part of the collapse key, so a like and a notification + // setting whose fields happen to spell the same strings must not shadow + // one another. @Test - fun `a like and a snooze on the same id string do not collide`() { + fun `a like and a setting with the same strings do not collide`() { val rows = listOf( likeRow(1, "same-id", desired = true), - snoozeRow(2, "same-id", desiredSnoozed = true), + settingRow(2, "artist", "same-id", value = true), ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } - @Test - fun `like toggles still collapse — the pre-existing behaviour is intact`() { - val rows = listOf( - likeRow(1, "artist-1", desired = true), - likeRow(2, "artist-1", desired = false), - ) - assertEquals(setOf(1L), supersededToggleIds(rows, json)) - } - @Test fun `non-toggle kinds are never collapsed, even repeated for one entity`() { // Two appends to the same playlist are two real actions, not one @@ -120,10 +103,10 @@ class SupersededToggleIdsTest { val rows = listOf( CachedMutationEntity( id = 1, - kind = MutationKind.SUGGESTION_SNOOZE_TOGGLE, + kind = MutationKind.LIKE_TOGGLE, payload = "{ not json", ), - snoozeRow(2, "mb-a", desiredSnoozed = true), + likeRow(2, "artist-1", desired = true), ) assertTrue(supersededToggleIds(rows, json).isEmpty()) } @@ -148,7 +131,7 @@ class SupersededToggleIdsTest { fun `only the newest queued normalization change survives`() { val rows = listOf( normalizationRow(1, NormalizationMode.TRACK), - snoozeRow(2, "mb-a", desiredSnoozed = true), + likeRow(2, "artist-1", desired = true), normalizationRow(3, NormalizationMode.OFF), normalizationRow(4, NormalizationMode.ALBUM), ) @@ -167,12 +150,12 @@ class SupersededToggleIdsTest { @Test fun `notification settings collapse per kind and channel, never across them`() { val rows = listOf( - settingRow(1, "request_completed", "email", false), - settingRow(2, "request_completed", "phone", false), - settingRow(3, "request_completed", "email", true), - settingRow(4, "request_approved", "email", false), + 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 request_completed is superseded. + // Only the older email toggle for tracks_missing is superseded. assertEquals(setOf(1L), supersededToggleIds(rows, json)) } diff --git a/android/app/src/test/java/com/fabledsword/minstrel/models/ArtistSuggestionReasonTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/models/ArtistSuggestionReasonTest.kt deleted file mode 100644 index e002c3e6..00000000 --- a/android/app/src/test/java/com/fabledsword/minstrel/models/ArtistSuggestionReasonTest.kt +++ /dev/null @@ -1,85 +0,0 @@ -package com.fabledsword.minstrel.models - -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -/** - * The card's subtitle line. Wording is kept in lockstep with the web - * client's reasonText() in SuggestionFeed.svelte — these assertions are the - * record of what that wording IS, so a change on one client without the other - * shows up as a failure rather than as silent divergence between the two - * surfaces. - */ -class ArtistSuggestionReasonTest { - - private val seeds = listOf( - SeedContributionRef(name = "Seed", isLiked = true), - ) - - private fun suggestion( - matched: List = emptyList(), - attribution: List = seeds, - ) = ArtistSuggestionRef( - mbid = "mb", - name = "Candidate", - attribution = attribution, - matchedTags = matched, - ) - - @Test - fun `one matched tag reads in the singular`() { - assertEquals( - "Matches your taste in shoegaze.", - suggestion(matched = listOf("shoegaze")).reasonText, - ) - } - - @Test - fun `two matched tags join with and`() { - assertEquals( - "Matches your taste in shoegaze and dream pop.", - suggestion(matched = listOf("shoegaze", "dream pop")).reasonText, - ) - } - - @Test - fun `three matched tags use an Oxford comma`() { - assertEquals( - "Matches your taste in a, b, and c.", - suggestion(matched = listOf("a", "b", "c")).reasonText, - ) - } - - // The server caps at 3, but the client must not render a run-on line if a - // future server sends more. - @Test - fun `more than three matched tags are capped at three`() { - assertEquals( - "Matches your taste in a, b, and c.", - suggestion(matched = listOf("a", "b", "c", "d", "e")).reasonText, - ) - } - - // The COMMON case: most candidates have no cached tags, so the card - // must fall back to seed attribution rather than going blank. - @Test - fun `no matched tags falls back to seed attribution`() { - assertEquals("Because you liked Seed.", suggestion().reasonText) - } - - // Nothing to say at all — a candidate with neither tags nor attribution - // yields an empty line, which the tile suppresses rather than rendering as - // a blank row. - @Test - fun `neither tags nor attribution yields an empty line`() { - assertEquals("", suggestion(attribution = emptyList()).reasonText) - } - - // The taste reason WINS over attribution when both exist: describing the - // music beats describing the similarity graph. - @Test - fun `a taste match supersedes seed attribution`() { - val got = suggestion(matched = listOf("shoegaze")).reasonText - assertEquals("Matches your taste in shoegaze.", got) - } -} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/models/SuggestionSnoozeRefTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/models/SuggestionSnoozeRefTest.kt deleted file mode 100644 index d777af99..00000000 --- a/android/app/src/test/java/com/fabledsword/minstrel/models/SuggestionSnoozeRefTest.kt +++ /dev/null @@ -1,83 +0,0 @@ -package com.fabledsword.minstrel.models - -import kotlinx.datetime.Instant -import org.junit.jupiter.api.Test -import kotlin.test.assertEquals - -/** - * `returnsIn` phrasing for the parked-suggestions list. The clock is - * injected rather than frozen, so these assertions are stable. - */ -class SuggestionSnoozeRefTest { - - private val now = 1_800_000_000_000L // fixed epoch ms; any value works - - private fun snoozeIn(days: Double) = SuggestionSnoozeRef( - mbid = "mb", - name = "Parked", - snoozedUntil = Instant - .fromEpochMilliseconds(now + (days * 86_400_000L).toLong()) - .toString(), - ) - - @Test - fun `the default 90-day snooze reads as about 3 months`() { - assertEquals("in about 3 months", snoozeIn(90.0).returnsIn(now)) - } - - @Test - fun `a month reads in the singular`() { - assertEquals("in about a month", snoozeIn(30.0).returnsIn(now)) - } - - @Test - fun `under the month threshold it counts days`() { - assertEquals("in 14 days", snoozeIn(14.0).returnsIn(now)) - } - - // Pins the days→months boundary. The singular branch was originally dead - // code because the threshold (45) sat above the divisor (30), so no day - // count could ever round to one month without being caught by the days - // branch first. Asserting both sides of the seam keeps that from - // regressing silently. - @Test - fun `the days-to-months boundary is exactly at 30 days`() { - assertEquals("in 29 days", snoozeIn(29.0).returnsIn(now)) - assertEquals("in about a month", snoozeIn(30.0).returnsIn(now)) - } - - @Test - fun `well past a month still reads in the singular rather than jumping to two`() { - assertEquals("in about a month", snoozeIn(40.0).returnsIn(now)) - } - - @Test - fun `tomorrow is named, not rendered as 1 days`() { - assertEquals("tomorrow", snoozeIn(1.0).returnsIn(now)) - } - - @Test - fun `later today rounds down to today rather than going negative`() { - assertEquals("today", snoozeIn(0.1).returnsIn(now)) - } - - // The server only ever returns unexpired rows, so a past timestamp means - // our clock and the server's disagree. The row is on screen either way, so - // say something plausible rather than leaving the line blank. - @Test - fun `an already-past expiry degrades to shortly`() { - assertEquals("shortly", snoozeIn(-5.0).returnsIn(now)) - } - - @Test - fun `an unparseable timestamp degrades to shortly`() { - val row = SuggestionSnoozeRef(mbid = "mb", name = "Parked", snoozedUntil = "not-a-date") - assertEquals("shortly", row.returnsIn(now)) - } - - @Test - fun `an empty timestamp degrades to shortly`() { - val row = SuggestionSnoozeRef(mbid = "mb", name = "Parked", snoozedUntil = "") - assertEquals("shortly", row.returnsIn(now)) - } -} diff --git a/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationUiTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationUiTest.kt index f988ac13..dc586c89 100644 --- a/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationUiTest.kt +++ b/android/app/src/test/java/com/fabledsword/minstrel/notifications/ui/NotificationUiTest.kt @@ -3,10 +3,8 @@ package com.fabledsword.minstrel.notifications.ui import com.fabledsword.minstrel.api.endpoints.NotificationKindSettingWire import com.fabledsword.minstrel.nav.Admin import com.fabledsword.minstrel.nav.AdminQuarantine -import com.fabledsword.minstrel.nav.AdminRequests import com.fabledsword.minstrel.nav.AlbumDetail import com.fabledsword.minstrel.nav.ArtistDetail -import com.fabledsword.minstrel.nav.Requests import com.fabledsword.minstrel.notifications.data.NotificationChannel import com.fabledsword.minstrel.shared.widgets.badgeLabel import kotlinx.datetime.Instant @@ -21,8 +19,6 @@ class NotificationUiTest { fun `server links open the matching screens`() { assertEquals(AlbumDetail("al-1"), routeForLink("/albums/al-1")) assertEquals(ArtistDetail("ar-1"), routeForLink("/artists/ar-1")) - assertEquals(Requests, routeForLink("/requests")) - assertEquals(AdminRequests, routeForLink("/admin/requests")) assertEquals(AdminQuarantine, routeForLink("/collection/reports")) // Library health pages the app has no screen for open the Admin landing. assertEquals(Admin, routeForLink("/collection/duplicates")) @@ -30,6 +26,9 @@ class NotificationUiTest { assertEquals(Admin, routeForLink("/collection/missing")) assertEquals(Admin, routeForLink("/admin")) assertNull(routeForLink("/somewhere-new")) + // A link to a page the app has no screen for and Admin does not hold + // opens nothing, rather than an empty screen. + assertNull(routeForLink("/requests")) } @Test