From 61a7b3390d68d844510c1182f96da26e8f540f20 Mon Sep 17 00:00:00 2001 From: Rhainland Date: Wed, 21 Oct 2026 22:06:55 +0200 Subject: [PATCH 1/6] fix(home): save Home row order and visibility to the profile on the server The phone and TV Home Sections editors kept row order and hidden rows in device-local storage, so the choices never followed the profile to other devices and the admin's per-profile Home sections card could not see or set them. Both editors now read the profile's Home rows from /api/v2/profile/sections/settings and save each change with a full PUT /api/v2/profile/sections that keeps every other saved customization (renames, rows the profile added or removed). Home renders /api/v2/home/sections in server order and re-reads after a save. The device-local stores are gone; their old preference files are left unread. The phone editor adds Move up and Move down accessibility actions beside drag, and both editors say the layout applies to this profile on every device. --- .../silo/android/di/AndroidModule.kt | 9 +- .../android/ui/screens/home/HomeScreen.kt | 32 +-- .../home/HomeSectionPreferencesStore.kt | 99 ------- .../ui/screens/home/HomeSectionsEditor.kt | 131 +++++----- .../ui/screens/settings/SettingsPages.kt | 2 +- .../preferences/TvHomeSectionPreferences.kt | 242 ------------------ .../siloserver/silo/tv/di/AndroidTvModule.kt | 5 +- .../silo/tv/ui/screens/home/TvHomeScreen.kt | 87 +++---- .../screens/settings/TvHomeSectionsEditor.kt | 117 ++++----- .../ui/screens/settings/TvSettingsScreen.kt | 19 +- .../silo/tv/ui/shell/TvMainShell.kt | 9 - .../tv/ui/screens/home/TvHomeSectionsTest.kt | 36 --- .../org/siloserver/silo/di/NetworkModule.kt | 1 + .../siloserver/silo/di/RepositoryModule.kt | 2 + .../model/section/ProfileSectionModels.kt | 53 ++++ .../network/apiv2/ProfileSectionsV2Api.kt | 70 +++++ .../silo/repository/HomeSectionOverrides.kt | 64 +++++ .../repository/ProfileHomeLayoutRepository.kt | 71 +++++ .../viewmodel/HomeSectionsEditorViewModel.kt | 109 ++++++++ .../silo/viewmodel/HomeViewModel.kt | 10 + .../network/apiv2/ProfileSectionsV2Test.kt | 133 ++++++++++ .../repository/HomeSectionOverridesTest.kt | 66 +++++ .../silo/viewmodel/HomeScreenV2Test.kt | 15 +- .../HomeSectionsEditorViewModelTest.kt | 117 +++++++++ 24 files changed, 871 insertions(+), 628 deletions(-) delete mode 100644 androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionPreferencesStore.kt delete mode 100644 androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/data/preferences/TvHomeSectionPreferences.kt create mode 100644 shared/src/commonMain/kotlin/org/siloserver/silo/model/section/ProfileSectionModels.kt create mode 100644 shared/src/commonMain/kotlin/org/siloserver/silo/network/apiv2/ProfileSectionsV2Api.kt create mode 100644 shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionOverrides.kt create mode 100644 shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt create mode 100644 shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt create mode 100644 shared/src/commonTest/kotlin/org/siloserver/silo/network/apiv2/ProfileSectionsV2Test.kt create mode 100644 shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionOverridesTest.kt create mode 100644 shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt index 3e2f317b1d..08c843071a 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/di/AndroidModule.kt @@ -507,7 +507,7 @@ val androidModule = module { networkEvidenceProvider = get(), ) } - viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull(), get(), get(), catalogLanguage = get()) } + viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull(), get(), get(), catalogLanguage = get(), homeLayoutChanges = get()) } viewModel { MainHeaderViewModel(get()) } viewModel { LibrariesViewModel( @@ -526,12 +526,7 @@ val androidModule = module { serverRegistry = get(), ) } - single { - org.siloserver.silo.android.ui.screens.home.HomeSectionPreferencesStore( - context = get(), - serverRegistry = get(), - ) - } + viewModel { org.siloserver.silo.viewmodel.HomeSectionsEditorViewModel(get()) } viewModel { params -> BrowseViewModel( get(), diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeScreen.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeScreen.kt index 8a09506956..8e18d44153 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeScreen.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeScreen.kt @@ -140,24 +140,15 @@ fun HomeScreen( modifier: Modifier = Modifier, ) { val state by viewModel.uiState.collectAsState() - val sectionPreferences: HomeSectionPreferencesStore = koinInject() - val preferenceRevision by sectionPreferences.revision.collectAsState() val serverRegistry: ServerRegistry = koinInject() val activeServerId by serverRegistry.activeServerId.collectAsState() val activeEntry by serverRegistry.activeEntry.collectAsState() val sections = state.sections val profileScopeId = activeEntry?.profileId ?: activeProfile?.id - val populatedServerSections = remember(sections) { sections.filter { it.items.isNotEmpty() } } // No hero billboard on phone (matches iOS): a `featured` section is just - // another row, rendered in the order the server configured it. - val regularSections = remember( - sections, - preferenceRevision, - activeServerId, - profileScopeId, - ) { - sectionPreferences.arrangedSections(sections, profileId = profileScopeId) - } + // another row. The server already orders and hides rows for this + // profile, so Home shows its populated rows exactly in that order. + val regularSections = remember(sections) { sections.filter { it.items.isNotEmpty() } } val context = LocalContext.current val catalogRepository: CatalogRepository = koinInject() val catalogLanguage: CatalogLanguageRevision = koinInject() @@ -334,19 +325,10 @@ fun HomeScreen( message = state.error ?: "Something went wrong", onRetry = { viewModel.loadSections() }, ) - regularSections.isEmpty() -> { - if (populatedServerSections.isNotEmpty()) { - EmptyStateView( - title = "Home sections are hidden", - subtitle = "Choose which rows appear in Settings → Interface → Home Sections.", - ) - } else { - EmptyStateView( - title = "Nothing to watch yet", - subtitle = "Add media to your libraries or start watching to see it here.", - ) - } - } + regularSections.isEmpty() -> EmptyStateView( + title = "Nothing to watch yet", + subtitle = "Add media to your libraries or start watching to see it here.", + ) else -> PullToRefreshBox( isRefreshing = state.isRefreshing, onRefresh = { viewModel.refresh() }, diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionPreferencesStore.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionPreferencesStore.kt deleted file mode 100644 index 623865fa51..0000000000 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionPreferencesStore.kt +++ /dev/null @@ -1,99 +0,0 @@ -package org.siloserver.silo.android.ui.screens.home - -import android.content.Context -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.serialization.Serializable -import kotlinx.serialization.json.Json -import org.siloserver.silo.model.section.ResolvedSection -import org.siloserver.silo.network.ServerRegistry - -/** - * Device-local Home row order and visibility, scoped to the active server and - * profile. The server remains authoritative for row membership and content; - * unknown rows append in server order and start visible. - */ -class HomeSectionPreferencesStore( - context: Context, - private val serverRegistry: ServerRegistry, -) { - @Serializable - private data class StoredLayout( - val orderedSectionIds: List = emptyList(), - val hiddenSectionIds: Set = emptySet(), - ) - - private val preferences = context.getSharedPreferences("home_section_preferences", Context.MODE_PRIVATE) - private val json = Json { ignoreUnknownKeys = true } - private val _revision = MutableStateFlow(0L) - val revision: StateFlow = _revision.asStateFlow() - - fun isVisible(sectionId: String, profileId: String? = null): Boolean = - sectionId !in load(profileId).hiddenSectionIds - - fun setVisible(sectionId: String, visible: Boolean, profileId: String? = null) { - val current = load(profileId) - val hidden = current.hiddenSectionIds.toMutableSet() - if (visible) hidden.remove(sectionId) else hidden.add(sectionId) - save(current.copy(hiddenSectionIds = hidden), profileId) - } - - /** - * Replaces the order of currently-known rows while retaining remembered - * identities that are temporarily empty or unavailable. - */ - fun setOrder(sectionIds: List, profileId: String? = null) { - val current = load(profileId) - val visibleOrder = sectionIds.distinct() - val visibleSet = visibleOrder.toSet() - save( - current.copy( - orderedSectionIds = visibleOrder + current.orderedSectionIds.filterNot(visibleSet::contains), - ), - profileId, - ) - } - - fun arrangedSections( - sections: List, - includingHidden: Boolean = false, - profileId: String? = null, - ): List { - val layout = load(profileId) - val rank = layout.orderedSectionIds.withIndex().associate { it.value to it.index } - val arranged = sections - .filter { it.items.isNotEmpty() } - .withIndex() - .sortedWith( - compareBy>( - { rank[it.value.id] ?: Int.MAX_VALUE }, - { it.index }, - ), - ) - .map { it.value } - return if (includingHidden) arranged else arranged.filterNot { it.id in layout.hiddenSectionIds } - } - - private fun storageKey(profileIdOverride: String? = null): String? { - val serverId = serverRegistry.activeServerId.value ?: "default" - val profileId = profileIdOverride - ?.takeIf { it.isNotBlank() } - ?: serverRegistry.activeEntry.value?.profileId - ?.takeIf { it.isNotBlank() } - ?: return null - return "android.homeSections.v1.$serverId.$profileId" - } - - private fun load(profileId: String? = null): StoredLayout { - val key = storageKey(profileId) ?: return StoredLayout() - val raw = preferences.getString(key, null) ?: return StoredLayout() - return runCatching { json.decodeFromString(raw) }.getOrDefault(StoredLayout()) - } - - private fun save(layout: StoredLayout, profileId: String? = null) { - val key = storageKey(profileId) ?: return - preferences.edit().putString(key, json.encodeToString(layout)).apply() - _revision.value += 1 - } -} diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionsEditor.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionsEditor.kt index af8916eaf8..4210086c12 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionsEditor.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/home/HomeSectionsEditor.kt @@ -24,6 +24,8 @@ import androidx.compose.material3.Icon import androidx.compose.material3.IconButton import androidx.compose.material3.MaterialTheme import androidx.compose.material3.Scaffold +import androidx.compose.material3.SnackbarHost +import androidx.compose.material3.SnackbarHostState import androidx.compose.material3.Text import androidx.compose.material3.pulltorefresh.PullToRefreshBox import androidx.compose.runtime.Composable @@ -33,60 +35,54 @@ import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableFloatStateOf import androidx.compose.runtime.mutableStateListOf import androidx.compose.runtime.mutableStateOf -import androidx.compose.runtime.produceState import androidx.compose.runtime.remember import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier import androidx.compose.ui.graphics.graphicsLayer import androidx.compose.ui.input.pointer.pointerInput +import androidx.compose.ui.semantics.CustomAccessibilityAction +import androidx.compose.ui.semantics.customActions +import androidx.compose.ui.semantics.semantics import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties -import org.koin.compose.koinInject import org.koin.compose.viewmodel.koinViewModel import org.siloserver.silo.android.ui.components.EmptyStateView import org.siloserver.silo.android.ui.components.ErrorView import org.siloserver.silo.android.ui.components.SiloTopBar -import org.siloserver.silo.model.section.ResolvedSection -import org.siloserver.silo.network.ServerRegistry -import org.siloserver.silo.repository.ProfileRepository -import org.siloserver.silo.viewmodel.HomeViewModel +import org.siloserver.silo.model.section.ProfileSectionSetting +import org.siloserver.silo.viewmodel.HomeSectionsEditorViewModel -/** Profile-scoped editor for the populated rows returned by Home. */ +/** + * Editor for the active profile's Home rows. The order and visibility live + * on the server, so they apply to this profile on every device and show in + * the admin's Home sections card; each change saves at once. + */ @OptIn(ExperimentalMaterial3Api::class) @Composable -fun HomeSectionsEditor(onDismiss: () -> Unit) { - val viewModel: HomeViewModel = koinViewModel(key = "home-sections-editor") - val state by viewModel.uiState.collectAsState() - val preferences: HomeSectionPreferencesStore = koinInject() - val preferenceRevision by preferences.revision.collectAsState() - val registry: ServerRegistry = koinInject() - val serverId by registry.activeServerId.collectAsState() - val entry by registry.activeEntry.collectAsState() - val profileRepository: ProfileRepository = koinInject() - val profileId by produceState( - initialValue = entry?.profileId, - key1 = entry?.id, - key2 = entry?.profileId, - ) { - value = entry?.profileId ?: profileRepository.getActiveProfileId() - } - val arranged = remember(state.sections, preferenceRevision, serverId, profileId) { - preferences.arrangedSections( - state.sections, - includingHidden = true, - profileId = profileId, - ) - } - val rows = remember { mutableStateListOf() } +fun HomeSectionsEditor( + onDismiss: () -> Unit, + viewModel: HomeSectionsEditorViewModel = koinViewModel(), +) { + val state by viewModel.state.collectAsState() + // Re-read on every open: another device or the admin may have changed + // the layout since this editor was last shown. + LaunchedEffect(viewModel) { viewModel.load() } + val rows = remember { mutableStateListOf() } var draggingId by remember { mutableStateOf(null) } - LaunchedEffect(arranged, draggingId) { + LaunchedEffect(state.rows, draggingId) { if (draggingId == null) { rows.clear() - rows.addAll(arranged) + rows.addAll(state.rows) } } + val snackbarHostState = remember { SnackbarHostState() } + LaunchedEffect(state.saveError) { + val message = state.saveError ?: return@LaunchedEffect + snackbarHostState.showSnackbar(message) + viewModel.dismissSaveError() + } Dialog( onDismissRequest = onDismiss, @@ -95,6 +91,7 @@ fun HomeSectionsEditor(onDismiss: () -> Unit) { Scaffold( modifier = Modifier.fillMaxSize(), containerColor = MaterialTheme.colorScheme.background, + snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { SiloTopBar( title = "Home Sections", @@ -104,8 +101,8 @@ fun HomeSectionsEditor(onDismiss: () -> Unit) { }, ) { padding -> PullToRefreshBox( - isRefreshing = state.isRefreshing, - onRefresh = viewModel::refresh, + isRefreshing = state.isLoading && rows.isNotEmpty(), + onRefresh = viewModel::load, modifier = Modifier.fillMaxSize().padding(padding), ) { when { @@ -113,21 +110,21 @@ fun HomeSectionsEditor(onDismiss: () -> Unit) { modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center, ) { CircularProgressIndicator() } - state.error != null && rows.isEmpty() -> ErrorView( - message = state.error ?: "Could not load Home sections", - onRetry = viewModel::loadSections, + state.loadError != null && rows.isEmpty() -> ErrorView( + message = state.loadError ?: "Could not load Home sections.", + onRetry = viewModel::load, ) rows.isEmpty() -> EmptyStateView( title = "No Home sections", - subtitle = "Home has no populated rows to arrange yet.", + subtitle = "This profile's Home has no rows to arrange yet.", ) else -> HomeSectionReorderList( rows = rows, - preferences = preferences, - profileId = profileId, - preferenceRevision = preferenceRevision, draggingId = draggingId, onDraggingIdChange = { draggingId = it }, + onDragFinished = { viewModel.setOrder(rows.map { it.id }) }, + onMove = viewModel::move, + onToggleHidden = { row -> viewModel.setHidden(row.id, !row.hidden) }, ) } } @@ -137,12 +134,12 @@ fun HomeSectionsEditor(onDismiss: () -> Unit) { @Composable private fun HomeSectionReorderList( - rows: MutableList, - preferences: HomeSectionPreferencesStore, - profileId: String?, - preferenceRevision: Long, + rows: MutableList, draggingId: String?, onDraggingIdChange: (String?) -> Unit, + onDragFinished: () -> Unit, + onMove: (id: String, offset: Int) -> Unit, + onToggleHidden: (ProfileSectionSetting) -> Unit, ) { val listState = rememberLazyListState() var dragOffset by remember { mutableFloatStateOf(0f) } @@ -154,34 +151,39 @@ private fun HomeSectionReorderList( ) { item(key = "instructions") { Text( - text = "Open eye: shown on Home. Closed eye: hidden. Drag the handle to reorder. Changes save automatically for this profile on this device.", + text = "Open eye: shown on Home. Closed eye: hidden. Drag the handle to reorder. " + + "Changes save to this profile and apply on every device.", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, modifier = Modifier.padding(16.dp), ) } items(rows, key = { it.id }) { section -> - // SharedPreferences itself is not observable. Reading the store's - // revision here makes each row recompose immediately after an eye - // toggle instead of showing stale state until the dialog reopens. - val isVisible = remember(section.id, profileId, preferenceRevision) { - preferences.isVisible(section.id, profileId) - } + val isVisible = !section.hidden val isDragging = draggingId == section.id + val index = rows.indexOfFirst { it.id == section.id } Row( modifier = Modifier .fillMaxWidth() .graphicsLayer { translationY = if (isDragging) dragOffset else 0f } .background(if (isDragging) MaterialTheme.colorScheme.surfaceVariant else MaterialTheme.colorScheme.surface) .padding(horizontal = 8.dp, vertical = 6.dp) - .graphicsLayer { alpha = if (isVisible) 1f else 0.42f }, + .graphicsLayer { alpha = if (isVisible) 1f else 0.42f } + // Dragging is touch-only; TalkBack and switch users move + // rows with these actions instead. + .semantics { + customActions = buildList { + if (index > 0) { + add(CustomAccessibilityAction("Move up") { onMove(section.id, -1); true }) + } + if (index in 0 until rows.lastIndex) { + add(CustomAccessibilityAction("Move down") { onMove(section.id, 1); true }) + } + } + }, verticalAlignment = Alignment.CenterVertically, ) { - IconButton( - onClick = { - preferences.setVisible(section.id, !isVisible, profileId) - }, - ) { + IconButton(onClick = { onToggleHidden(section) }) { Icon( imageVector = if (isVisible) Icons.Filled.Visibility else Icons.Filled.VisibilityOff, contentDescription = if (isVisible) "Hide ${section.title}" else "Show ${section.title}", @@ -190,7 +192,7 @@ private fun HomeSectionReorderList( Column(modifier = Modifier.weight(1f)) { Text(text = section.title, style = MaterialTheme.typography.bodyLarge, maxLines = 1) Text( - text = if (section.items.size == 1) "1 item" else "${section.items.size} items", + text = if (isVisible) "Shown on Home" else "Hidden from Home", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) @@ -204,13 +206,16 @@ private fun HomeSectionReorderList( onDraggingIdChange(section.id) dragOffset = 0f }, + // A cancelled drag still keeps the moves it + // made, so it saves like a finished one. onDragCancel = { dragOffset = 0f + onDragFinished() onDraggingIdChange(null) }, onDragEnd = { - preferences.setOrder(rows.map { it.id }, profileId) dragOffset = 0f + onDragFinished() onDraggingIdChange(null) }, onDrag = { change, amount -> @@ -228,10 +233,6 @@ private fun HomeSectionReorderList( if (toIndex >= 0 && toIndex != fromIndex) { val moved = rows.removeAt(fromIndex) rows.add(toIndex, moved) - // Persist each accepted move. If the - // system cancels the pointer gesture, - // the rows never snap back on exit. - preferences.setOrder(rows.map { it.id }, profileId) dragOffset = 0f } }, diff --git a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsPages.kt b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsPages.kt index 4b1182a40e..4850bb7f72 100644 --- a/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsPages.kt +++ b/androidApp/src/androidMain/kotlin/org/siloserver/silo/android/ui/screens/settings/SettingsPages.kt @@ -100,7 +100,7 @@ fun SettingsInterfaceScreen(viewModel: SettingsViewModel, onBackClick: () -> Uni item(key = "home") { SettingsSection( title = "Home", - footer = "Choose which Home rows are visible and the order they appear in.", + footer = "Choose which Home rows are visible and the order they appear in. This applies to this profile on every device.", ) { SettingsNavigationRow( label = "Home Sections", diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/data/preferences/TvHomeSectionPreferences.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/data/preferences/TvHomeSectionPreferences.kt deleted file mode 100644 index b3ce822a60..0000000000 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/data/preferences/TvHomeSectionPreferences.kt +++ /dev/null @@ -1,242 +0,0 @@ -package org.siloserver.silo.tv.data.preferences - -import android.content.Context -import androidx.datastore.core.DataStore -import androidx.datastore.preferences.core.PreferenceDataStoreFactory -import androidx.datastore.preferences.core.Preferences -import androidx.datastore.preferences.core.edit -import androidx.datastore.preferences.core.stringPreferencesKey -import androidx.datastore.preferences.core.stringSetPreferencesKey -import androidx.datastore.preferences.preferencesDataStoreFile -import kotlinx.coroutines.flow.MutableStateFlow -import kotlinx.coroutines.flow.StateFlow -import kotlinx.coroutines.flow.asStateFlow -import kotlinx.coroutines.flow.first -import kotlinx.coroutines.sync.Mutex -import kotlinx.coroutines.sync.withLock -import org.siloserver.silo.model.section.ResolvedSection -import org.siloserver.silo.network.TokenManager - -/** Device-local Home row order and visibility for one server/profile. */ -data class TvHomeSectionLayout( - val orderedSectionIds: List = emptyList(), - val hiddenSectionIds: Set = emptySet(), -) - -data class TvHomeSectionPreferenceState( - val authority: String? = null, - val layout: TvHomeSectionLayout = TvHomeSectionLayout(), - /** Changes only when the active authority or its saved layout changes. */ - val layoutRevision: Long = 0, -) - -/** - * Android TV counterpart to tvOS `HomeSectionPreferences`. - * - * The server remains authoritative for which populated rows exist. This store - * only projects those rows into a device-local order/visibility layout, scoped - * to the active server and profile. Newly-added server rows therefore append - * in server order and remain visible until explicitly hidden. - */ -class TvHomeSectionPreferences( - private val context: Context, - private val tokenManager: TokenManager, - private val dataStoreFactory: (profileId: String) -> DataStore = { profileId -> - PreferenceDataStoreFactory.create( - produceFile = { context.preferencesDataStoreFile(fileNameFor(profileId)) }, - ) - }, -) { - private data class Authority(val profileId: String, val serverId: String) { - val identity: String = "$serverId\u001f$profileId" - } - - private val mutex = Mutex() - private val storeCache = mutableMapOf>() - private val _state = MutableStateFlow(TvHomeSectionPreferenceState()) - val state: StateFlow = _state.asStateFlow() - - private fun storeFor(profileId: String): DataStore = - synchronized(storeCache) { - storeCache.getOrPut(profileId) { dataStoreFactory(profileId) } - } - - /** Load the active server/profile layout, if it is not already current. */ - suspend fun refresh() { - val authority = activeAuthority() - mutex.withLock { - if (authority == null) { - publishIfChanged(authority = null, layout = TvHomeSectionLayout()) - return - } - if (_state.value.authority == authority.identity) return - publishIfChanged(authority.identity, readLayout(authority)) - } - } - - suspend fun setVisible(sectionId: String, visible: Boolean) { - val authority = activeAuthority() ?: return - mutex.withLock { - val current = currentLayout(authority) - val wasVisible = sectionId !in current.hiddenSectionIds - if (wasVisible == visible) return - - val hidden = current.hiddenSectionIds.toMutableSet().apply { - if (visible) remove(sectionId) else add(sectionId) - } - val updated = current.copy(hiddenSectionIds = hidden) - persist(authority, updated) - publish(authority.identity, updated) - } - } - - /** - * Replace the order of currently-known rows while retaining remembered - * rows that are temporarily absent (for example empty Continue Watching). - */ - suspend fun setOrder(sectionIds: List) { - val authority = activeAuthority() ?: return - mutex.withLock { - val current = currentLayout(authority) - val updatedOrder = retainedOrder(sectionIds, current.orderedSectionIds) - if (updatedOrder == current.orderedSectionIds) return - - val updated = current.copy(orderedSectionIds = updatedOrder) - persist(authority, updated) - publish(authority.identity, updated) - } - } - - private suspend fun activeAuthority(): Authority? { - val scope = tokenManager.snapshotCurrentScope() - val profileId = (if (scope != null) scope.profileId else tokenManager.getProfileId()) - ?.takeIf(String::isNotBlank) - ?: return null - val serverId = (if (scope != null) scope.serverId else tokenManager.getCurrentServerId()) - ?.takeIf(String::isNotBlank) - ?: DEFAULT_SERVER_ID - return Authority(profileId = profileId, serverId = serverId) - } - - private suspend fun currentLayout(authority: Authority): TvHomeSectionLayout = - if (_state.value.authority == authority.identity) { - _state.value.layout - } else { - readLayout(authority) - } - - private suspend fun readLayout(authority: Authority): TvHomeSectionLayout { - val preferences = storeFor(authority.profileId).data.first() - return TvHomeSectionLayout( - orderedSectionIds = unique(decodeIds(preferences[orderKey(authority.serverId)])), - hiddenSectionIds = preferences[hiddenKey(authority.serverId)].orEmpty(), - ) - } - - private suspend fun persist(authority: Authority, layout: TvHomeSectionLayout) { - storeFor(authority.profileId).edit { preferences -> - preferences[orderKey(authority.serverId)] = encodeIds(layout.orderedSectionIds) - preferences[hiddenKey(authority.serverId)] = layout.hiddenSectionIds - } - } - - private fun publishIfChanged(authority: String?, layout: TvHomeSectionLayout) { - val current = _state.value - if (current.authority == authority && current.layout == layout) return - publish(authority, layout) - } - - private fun publish(authority: String?, layout: TvHomeSectionLayout) { - _state.value = TvHomeSectionPreferenceState( - authority = authority, - layout = layout, - layoutRevision = _state.value.layoutRevision + 1, - ) - } - - companion object { - private const val DEFAULT_SERVER_ID = "default" - - /** Apply saved order, then visibility, without introducing row gaps. */ - fun arrange( - sections: List, - layout: TvHomeSectionLayout, - includingHidden: Boolean = false, - ): List { - val rank = layout.orderedSectionIds.withIndex().associate { it.value to it.index } - val arranged = sections - .filter { it.items.isNotEmpty() } - .withIndex() - .sortedWith { left, right -> - val leftRank = rank[left.value.id] - val rightRank = rank[right.value.id] - when { - leftRank != null && rightRank != null -> leftRank.compareTo(rightRank) - leftRank != null -> -1 - rightRank != null -> 1 - else -> left.index.compareTo(right.index) - } - } - .map { it.value } - - return if (includingHidden) { - arranged - } else { - arranged.filterNot { it.id in layout.hiddenSectionIds } - } - } - - internal fun retainedOrder( - sectionIds: List, - rememberedSectionIds: List, - ): List { - val knownOrder = unique(sectionIds) - val knownIds = knownOrder.toSet() - return knownOrder + unique(rememberedSectionIds).filterNot(knownIds::contains) - } - - private fun orderKey(serverId: String) = - stringPreferencesKey("home_section_order_${serverHash(serverId)}") - - private fun hiddenKey(serverId: String) = - stringSetPreferencesKey("home_section_hidden_${serverHash(serverId)}") - - /** Length-prefixing keeps arbitrary server section ids reversible. */ - private fun encodeIds(ids: List): String = - unique(ids).joinToString(separator = "") { "${it.length}:$it" } - - private fun decodeIds(encoded: String?): List { - if (encoded.isNullOrEmpty()) return emptyList() - val result = mutableListOf() - var cursor = 0 - while (cursor < encoded.length) { - val separator = encoded.indexOf(':', startIndex = cursor) - if (separator < 0) return emptyList() - val length = encoded.substring(cursor, separator).toIntOrNull() ?: return emptyList() - val start = separator + 1 - val end = start + length - if (length < 0 || end > encoded.length) return emptyList() - result += encoded.substring(start, end) - cursor = end - } - return result - } - - private fun unique(ids: List): List { - val seen = mutableSetOf() - return ids.filter { it.isNotBlank() && seen.add(it) } - } - - private fun fileNameFor(profileId: String): String = - "tv_home_sections_${profileHash(profileId)}" - - private fun profileHash(profileId: String): String = hash(profileId).take(16) - - private fun serverHash(serverId: String): String = hash(serverId).take(16) - - private fun hash(value: String): String = - java.security.MessageDigest.getInstance("SHA-256") - .digest(value.toByteArray(Charsets.UTF_8)) - .joinToString(separator = "") { "%02x".format(it) } - } -} diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt index 99fcae031c..b20d01fd6c 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt @@ -6,7 +6,6 @@ import org.siloserver.silo.network.ApiResult import org.siloserver.silo.repository.SettingsRepository import org.siloserver.silo.tv.BuildConfig import org.siloserver.silo.tv.data.preferences.LegacyTvPrefsMigration -import org.siloserver.silo.tv.data.preferences.TvHomeSectionPreferences import org.siloserver.silo.tv.data.preferences.TvLibrarySelectionStore import org.siloserver.silo.common.network.AndroidDeviceMetadataProvider import org.siloserver.silo.common.network.SiloClientBuildIdentity @@ -318,7 +317,7 @@ val androidTvModule = module { // tvOS-parity Home row visibility/order, local to this TV and partitioned // by active server + profile. - single { TvHomeSectionPreferences(androidContext(), get()) } + viewModel { org.siloserver.silo.viewmodel.HomeSectionsEditorViewModel(get()) } // One-shot legacy `tv_prefs` import (playback settings → server device // overrides; selected-library id → active profile's selection store). @@ -495,7 +494,7 @@ val androidTvModule = module { // Content ViewModels // Starts hidden: the screens that show its rows report when they are on screen. - viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull(), get(), get(), catalogLanguage = get(), startShown = false) } + viewModel { HomeViewModel(get(), get(), get(), get(), getOrNull(), get(), get(), catalogLanguage = get(), startShown = false, homeLayoutChanges = get()) } viewModel { org.siloserver.silo.tv.ui.screens.home.TvUpcomingViewModel(get()) } viewModel { RecommendationsViewModel(get(), catalogLanguage = get()) } // The Requests page loads its view models when it composes. diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt index 31e32339dd..aab34b0ad3 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeScreen.kt @@ -13,7 +13,6 @@ import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue -import androidx.compose.runtime.key import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import androidx.compose.runtime.setValue @@ -27,11 +26,9 @@ import androidx.compose.ui.unit.dp import androidx.tv.material3.Button import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Text -import org.koin.compose.koinInject import org.koin.compose.viewmodel.koinViewModel import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.model.section.SectionItem -import org.siloserver.silo.tv.data.preferences.TvHomeSectionPreferences import org.siloserver.silo.tv.ui.components.TvErrorScreen import org.siloserver.silo.tv.ui.components.TvLoadingScreen import org.siloserver.silo.tv.ui.components.TvMediaCardActions @@ -67,7 +64,6 @@ fun TvHomeScreen( onPlayItem: (contentId: String, type: String?, resumePositionSeconds: Double?) -> Unit = { _, _, _ -> }, onSeeAll: () -> Unit = {}, onOpenForYou: () -> Unit = {}, - onOpenSettings: () -> Unit = {}, onInitialContentFocus: () -> Unit = {}, focusRequest: Int = 0, detailReturnFocusRequest: Int = 0, @@ -79,20 +75,11 @@ fun TvHomeScreen( viewModel: HomeViewModel = koinViewModel(), ) { val state by viewModel.uiState.collectAsState() - val homeSectionPreferences: TvHomeSectionPreferences = koinInject() - val homeSectionPreferenceState by homeSectionPreferences.state.collectAsState() - val normalizedSections = remember(state.sections) { state.sections.normalizeTvHomeSections() } - val visibleSections = remember(normalizedSections, homeSectionPreferenceState.layout) { - TvHomeSectionPreferences.arrange( - sections = normalizedSections, - layout = homeSectionPreferenceState.layout, - ) - } - val sectionsHiddenByPreference = - normalizedSections.isNotEmpty() && visibleSections.isEmpty() - - LaunchedEffect(homeSectionPreferences) { - homeSectionPreferences.refresh() + // The server already orders and hides rows for this profile, so Home + // shows its populated rows in that order. A split-off Continue Listening + // row sits right after the row it came from. + val visibleSections = remember(state.sections) { + state.sections.normalizeTvHomeSections().filter { it.items.isNotEmpty() } } // TV has no pull-to-refresh, so ON_RESUME is the only manual freshness @@ -129,43 +116,37 @@ fun TvHomeScreen( shouldShowHomeEmptyState(state.isLoading, state.error, visibleSections.size) -> TvHomeEmptyState( onRefresh = viewModel::loadSections, - onOpenSettings = onOpenSettings, - sectionsHiddenByPreference = sectionsHiddenByPreference, focusRequester = firstRowFocusRequester, focusRequest = focusRequest, onInitialContentFocus = onInitialContentFocus, ) - else -> key(homeSectionPreferenceState.layoutRevision) { - TvHomeContent( - sections = visibleSections, - sectionsFullyResolved = state.sectionsFullyResolved, - onItemClick = onItemClick, - onItemDetailSelection = onItemDetailSelection, - onPlayItem = onPlayItem, - onSeeAll = onSeeAll, - onOpenForYou = onOpenForYou, - onInitialContentFocus = onInitialContentFocus, - focusRequest = focusRequest, - detailReturnFocusRequest = detailReturnFocusRequest, - detailReturnCardFocusRequester = detailReturnCardFocusRequester, - firstRowFocusRequester = firstRowFocusRequester, - firstRowContainerFocusRequester = firstRowContainerFocusRequester, - onContentUpFallbackChanged = onContentUpFallbackChanged, - onSetWatched = viewModel::setWatched, - onMarqueeTranslated = viewModel::refreshFromRealtime, - onToggleFavorite = viewModel::toggleFavorite, - onToggleWatchlist = viewModel::toggleWatchlist, - onRemoveFromHome = viewModel::dismissFromHome, - ) - } + else -> TvHomeContent( + sections = visibleSections, + sectionsFullyResolved = state.sectionsFullyResolved, + onItemClick = onItemClick, + onItemDetailSelection = onItemDetailSelection, + onPlayItem = onPlayItem, + onSeeAll = onSeeAll, + onOpenForYou = onOpenForYou, + onInitialContentFocus = onInitialContentFocus, + focusRequest = focusRequest, + detailReturnFocusRequest = detailReturnFocusRequest, + detailReturnCardFocusRequester = detailReturnCardFocusRequester, + firstRowFocusRequester = firstRowFocusRequester, + firstRowContainerFocusRequester = firstRowContainerFocusRequester, + onContentUpFallbackChanged = onContentUpFallbackChanged, + onSetWatched = viewModel::setWatched, + onMarqueeTranslated = viewModel::refreshFromRealtime, + onToggleFavorite = viewModel::toggleFavorite, + onToggleWatchlist = viewModel::toggleWatchlist, + onRemoveFromHome = viewModel::dismissFromHome, + ) } } @Composable private fun TvHomeEmptyState( onRefresh: () -> Unit, - onOpenSettings: () -> Unit, - sectionsHiddenByPreference: Boolean, focusRequester: FocusRequester?, focusRequest: Int, onInitialContentFocus: () -> Unit, @@ -194,30 +175,22 @@ private fun TvHomeEmptyState( verticalArrangement = Arrangement.spacedBy(16.dp), ) { Text( - text = if (sectionsHiddenByPreference) { - "Home sections are hidden" - } else { - "Nothing to watch yet" - }, + text = "Nothing to watch yet", style = MaterialTheme.typography.headlineSmall, color = MaterialTheme.colorScheme.onBackground, ) Text( - text = if (sectionsHiddenByPreference) { - "Choose which rows appear in Settings → General → Home Sections." - } else { - "Add media to your libraries or start watching to see it here." - }, + text = "Add media to your libraries or start watching to see it here.", style = MaterialTheme.typography.bodyLarge, color = MaterialTheme.colorScheme.onSurfaceVariant, ) Button( - onClick = if (sectionsHiddenByPreference) onOpenSettings else onRefresh, + onClick = onRefresh, modifier = Modifier.focusRequester(refreshFocusRequester), contentPadding = PaddingValues(horizontal = 32.dp, vertical = 12.dp), ) { Text( - text = if (sectionsHiddenByPreference) "Open Settings" else "Refresh", + text = "Refresh", style = MaterialTheme.typography.labelLarge, ) } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvHomeSectionsEditor.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvHomeSectionsEditor.kt index 898e07586c..4d70caebb7 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvHomeSectionsEditor.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvHomeSectionsEditor.kt @@ -56,41 +56,33 @@ import androidx.tv.material3.MaterialTheme import androidx.tv.material3.Surface import androidx.tv.material3.Text import kotlinx.coroutines.launch -import org.koin.compose.koinInject import org.koin.compose.viewmodel.koinViewModel -import org.siloserver.silo.model.section.ResolvedSection -import org.siloserver.silo.tv.data.preferences.TvHomeSectionPreferences +import org.siloserver.silo.model.section.ProfileSectionSetting import org.siloserver.silo.tv.ui.focus.TvContentInitialFocusMaxAttempts import org.siloserver.silo.tv.ui.focus.TvFrameRelocationMaxAttempts import org.siloserver.silo.tv.ui.focus.requestFocusUntilObserved -import org.siloserver.silo.tv.ui.screens.home.normalizeTvHomeSections import org.siloserver.silo.tv.ui.theme.FocusedContainer import org.siloserver.silo.tv.ui.theme.FocusedContent -import org.siloserver.silo.viewmodel.HomeViewModel +import org.siloserver.silo.viewmodel.HomeSectionsEditorViewModel -/** Full-screen, remote-first Home row editor matching the tvOS settings flow. */ +/** + * Full-screen, remote-first Home row editor matching the tvOS settings flow. + * The rows are the active profile's server layout, so a change applies to + * this profile on every device and shows in the admin's Home sections card. + */ @OptIn(ExperimentalTvMaterial3Api::class) @Composable internal fun TvHomeSectionsEditor( onDismiss: () -> Unit, - viewModel: HomeViewModel = koinViewModel(), - preferences: TvHomeSectionPreferences = koinInject(), + viewModel: HomeSectionsEditorViewModel = koinViewModel(), ) { - val homeState by viewModel.uiState.collectAsState() - val preferenceState by preferences.state.collectAsState() - val sections = remember(homeState.sections) { - homeState.sections.normalizeTvHomeSections() - } - val arrangedSections = remember(sections, preferenceState.layout) { - TvHomeSectionPreferences.arrange( - sections = sections, - layout = preferenceState.layout, - includingHidden = true, - ) - } - val rowFocusRequesters = remember(sections.map { it.id }) { - sections.associate { section -> - section.id to HomeSectionRowFocusRequesters( + val state by viewModel.state.collectAsState() + val rows = state.rows + // Keyed by the set of rows, not their order, so a move keeps the + // requesters the focus restoration below is aiming at. + val rowFocusRequesters = remember(rows.map { it.id }.sorted()) { + rows.associate { row -> + row.id to HomeSectionRowFocusRequesters( moveUp = FocusRequester(), moveDown = FocusRequester(), ) @@ -109,48 +101,34 @@ internal fun TvHomeSectionsEditor( onDismiss() } - fun move(section: ResolvedSection, offset: Int) { - val ids = arrangedSections.map { it.id }.toMutableList() - val index = ids.indexOf(section.id) + fun move(row: ProfileSectionSetting, offset: Int) { + val index = rows.indexOfFirst { it.id == row.id } val target = index + offset - if (index < 0 || target !in ids.indices) return - ids[index] = ids[target] - ids[target] = section.id + if (index < 0 || target !in rows.indices) return + val lastIndex = rows.lastIndex + viewModel.move(row.id, offset) scope.launch { - preferences.setOrder(ids) - val requesters = rowFocusRequesters[section.id] ?: return@launch + val requesters = rowFocusRequesters[row.id] ?: return@launch val (requester, direction) = when (target) { 0 -> requesters.moveDown to 1 - ids.lastIndex -> requesters.moveUp to -1 + lastIndex -> requesters.moveUp to -1 else -> if (offset < 0) requesters.moveUp to -1 else requesters.moveDown to 1 } requestFocusUntilObserved( maxAttempts = TvFrameRelocationMaxAttempts, awaitAttempt = { withFrameNanos { } }, requestFocus = requester::requestFocus, - isFocused = { focusedMoveControl == (section.id to direction) }, + isFocused = { focusedMoveControl == (row.id to direction) }, ) } } BackHandler(onBack = ::close) - // The editor lists Home's rows, so realtime and language updates reach - // them while it is open, as they do on Home itself. - androidx.lifecycle.compose.LifecycleResumeEffect(viewModel) { - viewModel.onShown() - viewModel.runPendingRealtimeRefresh() - onPauseOrDispose { viewModel.onHidden() } - } - - LaunchedEffect(preferences, viewModel) { - preferences.refresh() - // The shell normally already owns populated Home state. A direct - // Settings entry can still arrive before that first load completes, - // so explicitly retry only while there is nothing useful to edit. - if (homeState.sections.isEmpty()) viewModel.loadSections() - } + // Re-read on every open: another device or the admin may have changed + // the layout since the editor was last shown. + LaunchedEffect(viewModel) { viewModel.load() } LaunchedEffect(Unit) { requestFocusUntilObserved( @@ -237,7 +215,7 @@ internal fun TvHomeSectionsEditor( HomeSectionsControlButton( label = if (isEditing) "Done Editing" else "Edit", onClick = { isEditing = !isEditing }, - enabled = arrangedSections.size >= 2, + enabled = rows.size >= 2, ) HomeSectionsControlButton( label = "Done", @@ -248,16 +226,16 @@ internal fun TvHomeSectionsEditor( } when { - arrangedSections.isEmpty() && homeState.isLoading -> { + rows.isEmpty() && state.isLoading -> { HomeSectionsMessage("Loading Home sections…") } - arrangedSections.isEmpty() && homeState.error != null -> { + rows.isEmpty() && state.loadError != null -> { HomeSectionsMessage( - "Silo couldn’t refresh the Home rows. Try again when the server is reachable.", + "Silo couldn’t load the Home rows. Try again when the server is reachable.", ) } - arrangedSections.isEmpty() -> { - HomeSectionsMessage("Home has no populated rows to arrange yet.") + rows.isEmpty() -> { + HomeSectionsMessage("This profile's Home has no rows to arrange yet.") } else -> { LazyColumn( @@ -265,15 +243,15 @@ internal fun TvHomeSectionsEditor( contentPadding = PaddingValues(bottom = 4.dp), verticalArrangement = Arrangement.spacedBy(5.dp), ) { - items(arrangedSections, key = { it.id }) { section -> - val visible = section.id !in preferenceState.layout.hiddenSectionIds - val index = arrangedSections.indexOfFirst { it.id == section.id } + items(rows, key = { it.id }) { section -> + val visible = !section.hidden + val index = rows.indexOfFirst { it.id == section.id } HomeSectionEditorRow( section = section, visible = visible, editing = isEditing, canMoveUp = index > 0, - canMoveDown = index in 0 until arrangedSections.lastIndex, + canMoveDown = index in 0 until rows.lastIndex, focusRequesters = rowFocusRequesters.getValue(section.id), onMoveFocusChanged = { direction, focused -> val control = section.id to direction @@ -285,24 +263,27 @@ internal fun TvHomeSectionsEditor( onMoveUp = { move(section, -1) }, onMoveDown = { move(section, 1) }, onToggleVisibility = { - scope.launch { - preferences.setVisible(section.id, visible = !visible) - } + viewModel.setHidden(section.id, hidden = visible) }, ) } } + val saveError = state.saveError Text( - text = if (isEditing) { - "Use the arrow buttons to move rows. The new order saves immediately." - } else { - "Open eye: visible on Home. Closed eye: hidden. Hidden rows leave no gap." + text = when { + saveError != null -> "$saveError The previous layout is back." + isEditing -> "Use the arrow buttons to move rows. The new order saves to this profile on every device." + else -> "Open eye: visible on Home. Closed eye: hidden. Hidden rows leave no gap." }, style = MaterialTheme.typography.bodySmall.copy( fontSize = 14.sp, lineHeight = 18.sp, ), - color = MaterialTheme.colorScheme.onSurfaceVariant, + color = if (saveError != null) { + MaterialTheme.colorScheme.error + } else { + MaterialTheme.colorScheme.onSurfaceVariant + }, ) } } @@ -347,7 +328,7 @@ private fun HomeSectionsMessage(message: String) { @Composable private fun HomeSectionEditorRow( - section: ResolvedSection, + section: ProfileSectionSetting, visible: Boolean, editing: Boolean, canMoveUp: Boolean, @@ -384,7 +365,7 @@ private fun HomeSectionEditorRow( overflow = TextOverflow.Ellipsis, ) Text( - text = "${section.items.size} item${if (section.items.size == 1) "" else "s"}", + text = if (visible) "Shown on Home" else "Hidden from Home", style = MaterialTheme.typography.bodySmall.copy(fontSize = 14.sp, lineHeight = 18.sp), color = MaterialTheme.colorScheme.onSurfaceVariant, ) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt index 90d9efac1d..8c42759734 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/screens/settings/TvSettingsScreen.kt @@ -139,7 +139,6 @@ import org.siloserver.silo.tv.ui.theme.Spacing import org.koin.compose.koinInject import org.koin.compose.viewmodel.koinViewModel import org.siloserver.silo.common.watchparty.WatchPartyExperiment -import org.siloserver.silo.viewmodel.HomeViewModel import kotlinx.coroutines.delay /** @@ -162,7 +161,6 @@ fun TvSettingsScreen( onManageServersReturnFocusConsumed: () -> Unit = {}, viewModel: TvSettingsViewModel = koinViewModel(), diagnosticsViewModel: TvDiagnosticsViewModel = koinViewModel(), - homeSectionsViewModel: HomeViewModel = koinViewModel(key = "settings-home-sections"), ) { val state by viewModel.uiState.collectAsState() val diagnosticsState by diagnosticsViewModel.state.collectAsState() @@ -275,7 +273,6 @@ fun TvSettingsScreen( state = state, diagnosticsState = diagnosticsState, diagnosticsViewModel = diagnosticsViewModel, - homeSectionsViewModel = homeSectionsViewModel, selectedCategory = selectedCategory, categoryFocusRequesters = categoryFocusRequesters, detailFocusRequester = detailFocusRequester, @@ -427,7 +424,6 @@ private fun SettingsSplitLayout( state: TvSettingsViewModel.UiState, diagnosticsState: org.siloserver.silo.common.diagnostics.DiagnosticsUiState, diagnosticsViewModel: TvDiagnosticsViewModel, - homeSectionsViewModel: HomeViewModel, selectedCategory: TvSettingsCategory, categoryFocusRequesters: Map, detailFocusRequester: FocusRequester, @@ -522,7 +518,6 @@ private fun SettingsSplitLayout( state = state, diagnosticsState = diagnosticsState, diagnosticsViewModel = diagnosticsViewModel, - homeSectionsViewModel = homeSectionsViewModel, selectedCategory = selectedCategory, detailFocusRequester = detailFocusRequester, onDetailFocusChanged = onDetailFocusChanged, @@ -808,7 +803,6 @@ private fun SettingsDetailPane( state: TvSettingsViewModel.UiState, diagnosticsState: org.siloserver.silo.common.diagnostics.DiagnosticsUiState, diagnosticsViewModel: TvDiagnosticsViewModel, - homeSectionsViewModel: HomeViewModel, selectedCategory: TvSettingsCategory, detailFocusRequester: FocusRequester, onDetailFocusChanged: (Boolean) -> Unit, @@ -867,7 +861,6 @@ private fun SettingsDetailPane( when (selectedCategory) { TvSettingsCategory.General -> TvGeneralSettingsPane( state = state, - homeSectionsViewModel = homeSectionsViewModel, firstFocusRequester = detailFocusRequester, onShowAudiobooksTabChanged = onShowAudiobooksTabChanged, onProfileLaunchBehaviorChanged = onProfileLaunchBehaviorChanged, @@ -989,7 +982,6 @@ private fun SettingsPaneHeader(category: TvSettingsCategory) { @Composable private fun TvGeneralSettingsPane( state: TvSettingsViewModel.UiState, - homeSectionsViewModel: HomeViewModel, firstFocusRequester: FocusRequester, onShowAudiobooksTabChanged: (Boolean) -> Unit, onProfileLaunchBehaviorChanged: (ProfileLaunchBehavior) -> Unit, @@ -1025,8 +1017,8 @@ private fun TvGeneralSettingsPane( } } item { - // Device-local, server/profile-specific visibility and order for - // the populated rows returned by Home, matching tvOS General. + // The active profile's Home row order and visibility, saved on the + // server so they follow the profile to every device. SettingsGroup(title = "Home Sections") { SettingsValueRow( label = "Home Sections", @@ -1034,7 +1026,7 @@ private fun TvGeneralSettingsPane( onClick = { showHomeSectionsEditor = true }, ) SettingsFooterText( - text = "Choose which Home rows are visible and edit the order in which they appear on this Android TV.", + text = "Choose which Home rows are visible and the order they appear in. This applies to this profile on every device.", ) } } @@ -1178,10 +1170,7 @@ private fun TvGeneralSettingsPane( } if (showHomeSectionsEditor) { - TvHomeSectionsEditor( - onDismiss = { showHomeSectionsEditor = false }, - viewModel = homeSectionsViewModel, - ) + TvHomeSectionsEditor(onDismiss = { showHomeSectionsEditor = false }) } } diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt index ef373e6346..6d505a3a14 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/ui/shell/TvMainShell.kt @@ -1226,10 +1226,6 @@ fun TvMainShell( onOpenForYou = { openForYou(null) }, - onOpenSettings = { - navigateToRoute(TvMainRoute.Settings.route) - moveFocusToContent(TvMainRoute.Settings.route) - }, onInitialContentFocus = { focusState.closeProfileMenuForContent() }, focusRequest = contentFocusRequest, detailReturnFocusRequest = homeDetailReturnFocusState.requestId, @@ -1253,10 +1249,6 @@ fun TvMainShell( onOpenForYou = { openForYou(null) }, - onOpenSettings = { - navigateToRoute(TvMainRoute.Settings.route) - moveFocusToContent(TvMainRoute.Settings.route) - }, onInitialContentFocus = { focusState.closeProfileMenuForContent() }, focusRequest = contentFocusRequest, detailReturnFocusRequest = homeDetailReturnFocusState.requestId, @@ -1460,7 +1452,6 @@ fun TvMainShell( } shellComposable(TvMainRoute.Settings.route) { TvSettingsScreen( - homeSectionsViewModel = homeViewModel, onManageServers = onManageServers, onOpenDiagnosticsReport = onOpenDiagnosticsReport, initialManageServersFocus = returnToManageServers, diff --git a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeSectionsTest.kt b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeSectionsTest.kt index f4426187c5..2cacae173c 100644 --- a/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeSectionsTest.kt +++ b/androidTvApp/src/androidUnitTest/kotlin/org/siloserver/silo/tv/ui/screens/home/TvHomeSectionsTest.kt @@ -3,8 +3,6 @@ package org.siloserver.silo.tv.ui.screens.home import java.io.File import org.siloserver.silo.model.section.ResolvedSection import org.siloserver.silo.model.section.SectionItem -import org.siloserver.silo.tv.data.preferences.TvHomeSectionLayout -import org.siloserver.silo.tv.data.preferences.TvHomeSectionPreferences import org.siloserver.silo.tv.ui.components.isTvContinueWatchingRow import org.siloserver.silo.tv.ui.components.TvRowStyle import kotlin.test.Test @@ -125,40 +123,6 @@ class TvHomeSectionsTest { assertEquals(TvRowStyle.Poster, normalized.single().tvHomeRowStyle()) } - @Test - fun savedOrderAndVisibilityProjectPopulatedRowsWithoutAGap() { - val sections = listOf( - homeSection("continue", "Continue Watching"), - homeSection("recent", "Recently Added"), - homeSection("because", "Because You Watched"), - ) - val layout = TvHomeSectionLayout( - orderedSectionIds = listOf("recent", "continue"), - hiddenSectionIds = setOf("recent"), - ) - - val visible = TvHomeSectionPreferences.arrange(sections, layout) - val editor = TvHomeSectionPreferences.arrange( - sections, - layout, - includingHidden = true, - ) - - assertEquals(listOf("continue", "because"), visible.map { it.id }) - assertEquals(listOf("recent", "continue", "because"), editor.map { it.id }) - } - - @Test - fun reorderedKnownRowsRetainTemporarilyAbsentRememberedRows() { - assertEquals( - listOf("recent", "continue", "temporarily-empty"), - TvHomeSectionPreferences.retainedOrder( - sectionIds = listOf("recent", "continue", "recent"), - rememberedSectionIds = listOf("continue", "temporarily-empty"), - ), - ) - } - @Test fun editorButtonsCenterTheirContentWithoutExpandingOverTheSectionRows() { val source = File( diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/di/NetworkModule.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/di/NetworkModule.kt index 1656daa91b..88ceeda55d 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/di/NetworkModule.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/di/NetworkModule.kt @@ -47,6 +47,7 @@ val networkModule = module { single { ProfileApi(get(), get(), get()) } single { LibrarySectionItemsV2Api(get(), get(), get()) } single { HomeSectionsV2Api(get(), get(), get()) } + single { org.siloserver.silo.network.apiv2.ProfileSectionsV2Api(get(), get(), get()) } single { SectionApi(get(), get(), get(), get()) } single { SimilarCardsV2Api(get(), get(), get()) } single { TasteProfileV2Api(get(), get(), get()) } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt index 32d067862e..bd3a02ecf2 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/di/RepositoryModule.kt @@ -116,6 +116,8 @@ val repositoryModule = module { ) } single { RecommendationRepository(get(), get()) } + single { org.siloserver.silo.repository.HomeLayoutChanges() } + single { org.siloserver.silo.repository.ProfileHomeLayoutRepository(get(), get()) } single { RequestsRepository( api = get(), diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/model/section/ProfileSectionModels.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/model/section/ProfileSectionModels.kt new file mode 100644 index 0000000000..503da07259 --- /dev/null +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/model/section/ProfileSectionModels.kt @@ -0,0 +1,53 @@ +package org.siloserver.silo.model.section + +import kotlinx.serialization.SerialName +import kotlinx.serialization.Serializable +import kotlinx.serialization.json.JsonObject + +/** + * One row of a page as the acting profile sees it in the customization screen + * (`GET /api/v2/profile/sections/settings`): the admin definition with the + * profile's overrides applied, hidden rows included. [id] is the admin + * section id, or the override's own id for a row the profile built + * ([isCustom]). + */ +@Serializable +data class ProfileSectionSetting( + val id: String, + @SerialName("section_type") val sectionType: String = "", + val title: String = "", + @SerialName("default_title") val defaultTitle: String = "", + val featured: Boolean = false, + @SerialName("item_limit") val itemLimit: Int = 0, + val hidden: Boolean = false, + @SerialName("is_custom") val isCustom: Boolean = false, + val customized: Boolean = false, + val position: Int = 0, + val config: JsonObject? = null, +) + +/** + * One saved profile override (`GET /api/v2/profile/sections`), also the shape + * written back by `PUT /api/v2/profile/sections`. Only the members the write + * accepts are modelled, so a read row re-encodes as a valid write: the + * server rejects unknown members such as `created_at`. Null members are + * omitted on the wire, which the server reads as "no override" ([position], + * [featured], [itemLimit]) or "none saved" ([config], [userConfig]). + */ +@Serializable +data class SectionOverride( + val id: String = "", + @SerialName("section_id") val sectionId: String = "", + val position: Int? = null, + val hidden: Boolean = false, + val removed: Boolean = false, + @SerialName("section_type") val sectionType: String = "", + val title: String = "", + val featured: Boolean? = null, + @SerialName("item_limit") val itemLimit: Int? = null, + val config: JsonObject? = null, + @SerialName("is_user_added") val isUserAdded: Boolean = false, + @SerialName("user_section_type") val userSectionType: String = "", + @SerialName("user_title") val userTitle: String = "", + @SerialName("user_config") val userConfig: JsonObject? = null, +) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/network/apiv2/ProfileSectionsV2Api.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/network/apiv2/ProfileSectionsV2Api.kt new file mode 100644 index 0000000000..aad42befc2 --- /dev/null +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/network/apiv2/ProfileSectionsV2Api.kt @@ -0,0 +1,70 @@ +package org.siloserver.silo.network.apiv2 + +import io.ktor.client.HttpClient +import io.ktor.client.request.* +import io.ktor.client.statement.HttpResponse +import io.ktor.http.content.TextContent +import io.ktor.http.* +import kotlinx.serialization.Serializable +import kotlinx.serialization.builtins.ListSerializer +import kotlinx.serialization.json.* +import org.siloserver.silo.model.section.ProfileSectionSetting +import org.siloserver.silo.model.section.SectionOverride +import org.siloserver.silo.network.* + +/** + * The acting profile's Home layout on API v2 (`/api/v2/profile/sections`, + * `scope=home`): the rows as the profile sees them, its saved overrides, and + * the whole-set replace. The same overrides drive Home on every + * device and the admin's per-profile Home sections card. Every call is pinned + * to the profile captured before it and refused when that profile changed. + */ +class ProfileSectionsV2Api( + private val client: HttpClient, + private val tokens: TokenManager, + private val gate: ApiV2Gate, +) { + @Serializable + private data class OverrideSet(val overrides: List) + + suspend fun capture(): AuthScopeSnapshot? = tokens.captureProfileScope() + + /** GET /api/v2/profile/sections/settings?scope=home: Home rows in profile order, hidden rows included. */ + suspend fun homeSettings(owner: AuthScopeSnapshot): ApiResult> = + exchange>(owner, HttpStatusCode.OK, { + client.get("/api/v2/profile/sections/settings") { scoped(owner) } + }) { body -> items(body, ProfileSectionSetting.serializer()).also { rows -> require(rows.all { it.id.isNotBlank() }) } } + + /** GET /api/v2/profile/sections?scope=home: the profile's saved Home overrides. */ + suspend fun homeOverrides(owner: AuthScopeSnapshot): ApiResult> = + exchange>(owner, HttpStatusCode.OK, { + client.get("/api/v2/profile/sections") { scoped(owner) } + }) { body -> items(body, SectionOverride.serializer()) } + + /** PUT /api/v2/profile/sections?scope=home: replaces the whole Home override set. */ + suspend fun replaceHome(owner: AuthScopeSnapshot, overrides: List): ApiResult = + exchange(owner, HttpStatusCode.NoContent, { + client.put("/api/v2/profile/sections") { + scoped(owner) + setBody(TextContent(SiloJson.encodeToString(OverrideSet.serializer(), OverrideSet(overrides)), ContentType.Application.Json)) + } + }) { } + + private suspend inline fun exchange( + owner: AuthScopeSnapshot, + status: HttpStatusCode, + crossinline block: suspend () -> HttpResponse, + crossinline project: (T) -> R, + ): ApiResult = ownedV2Call(gate, tokens, owner, OwnerPolicy.PROFILE, status, { block() }, project) + + private fun HttpRequestBuilder.scoped(owner: AuthScopeSnapshot) { + authScope(owner) + requireSiloAuth() + url { parameters.append("scope", "home") } + } + + private fun items(body: JsonObject, serializer: kotlinx.serialization.KSerializer): List { + val rows = requireNotNull(body["items"] as? JsonArray) { "Missing items." } + return SiloJson.decodeFromJsonElement(ListSerializer(serializer), rows) + } +} diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionOverrides.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionOverrides.kt new file mode 100644 index 0000000000..08918aabbf --- /dev/null +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionOverrides.kt @@ -0,0 +1,64 @@ +package org.siloserver.silo.repository + +import org.siloserver.silo.model.section.ProfileSectionSetting +import org.siloserver.silo.model.section.SectionOverride + +/** + * The override set a profile saves for its Home page + * (`PUT /api/v2/profile/sections?scope=home`), which replaces every override + * the profile saved for Home. + * + * [rows] is the Home settings list (`/profile/sections/settings`) in the new + * display order, with each row's chosen visibility. Every row stores its + * list index as its position. A row the profile already saved an override + * for keeps that override, its id and every other field (a rename, a + * featured or item-limit change, a profile-built row's recipe and config), + * with only position and hidden replaced. An admin row with no override + * gets a new one from [newId]. A saved override whose row is not in [rows] + * (a row the profile removed, or one it cannot currently see) is kept + * unchanged, so a reorder never loses it. + */ +fun buildHomeSectionOverrides( + rows: List, + saved: List, + newId: () -> String, +): List { + // The server resolves the last saved override for a section, so that is + // the one a row keeps. + val savedByRow = LinkedHashMap() + for (override in saved) { + val key = override.rowKey() ?: continue + savedByRow[key] = override + } + val matched = mutableSetOf() + val rowOverrides = rows.mapIndexedNotNull { index, row -> + val existing = savedByRow[row.rowKey()] + if (existing != null) { + matched += existing + existing.copy( + id = existing.id.ifBlank { newId() }, + position = index, + hidden = row.hidden, + ) + } else if (row.isCustom) { + // A profile-built row only exists as its saved override; without + // it there is no recipe to write back. + null + } else { + SectionOverride(id = newId(), sectionId = row.id, position = index, hidden = row.hidden) + } + } + // Unlisted overrides go first: should one duplicate a listed row's + // section, the listed row's override is still the last and wins. + val unlisted = saved.filter { it !in matched } + return unlisted + rowOverrides +} + +/** Admin rows are matched by section id, profile-built rows by override id. */ +private fun ProfileSectionSetting.rowKey(): String = if (isCustom) "custom:$id" else "admin:$id" + +private fun SectionOverride.rowKey(): String? = when { + sectionId.isNotBlank() -> "admin:$sectionId" + id.isNotBlank() -> "custom:$id" + else -> null +} diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt new file mode 100644 index 0000000000..1937450544 --- /dev/null +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt @@ -0,0 +1,71 @@ +package org.siloserver.silo.repository + +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.flow.StateFlow +import kotlinx.coroutines.flow.asStateFlow +import kotlinx.coroutines.flow.update +import org.siloserver.silo.model.section.ProfileSectionSetting +import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.AuthScopeSnapshot +import org.siloserver.silo.network.apiv2.ProfileSectionsV2Api + +/** + * Bumped after the acting profile's Home layout changed on the server, so + * every Home on this device re-reads its rows in the new order. + */ +class HomeLayoutChanges { + private val _revision = MutableStateFlow(0L) + val revision: StateFlow = _revision.asStateFlow() + + fun changed() { + _revision.update { it + 1 } + } +} + +/** The acting profile's Home rows as it sees them, pinned to the profile they were read for. */ +data class ProfileHomeLayout( + val owner: AuthScopeSnapshot, + val rows: List, +) + +/** + * Reads and writes the acting profile's Home row order and visibility on the + * server. The server applies them to `/api/v2/home/sections` for that profile + * on every device, and the admin sees and sets them in the profile's Home + * sections card, so there is no device-local copy. + */ +class ProfileHomeLayoutRepository( + private val api: ProfileSectionsV2Api, + private val changes: HomeLayoutChanges, + private val newId: () -> String = ::newOverrideId, +) { + suspend fun load(): ApiResult { + val owner = api.capture() ?: return noProfile() + return when (val rows = api.homeSettings(owner)) { + is ApiResult.Success -> ApiResult.Success(ProfileHomeLayout(owner, rows.data)) + is ApiResult.Error -> rows + is ApiResult.NetworkError -> rows + } + } + + /** + * Saves [rows] (the whole Home list in its new order, with each row's + * visibility) as the profile's layout, keeping every other saved + * customization; see [buildHomeSectionOverrides]. + */ + suspend fun save(owner: AuthScopeSnapshot, rows: List): ApiResult { + val saved = when (val read = api.homeOverrides(owner)) { + is ApiResult.Success -> read.data + is ApiResult.Error -> return read + is ApiResult.NetworkError -> return read + } + val result = api.replaceHome(owner, buildHomeSectionOverrides(rows, saved, newId)) + if (result is ApiResult.Success) changes.changed() + return result + } + + private fun noProfile() = ApiResult.Error(0, "identity_changed", "Choose a profile to arrange its Home rows.") +} + +@OptIn(kotlin.uuid.ExperimentalUuidApi::class) +private fun newOverrideId(): String = kotlin.uuid.Uuid.random().toString() diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt new file mode 100644 index 0000000000..f39ca3a73e --- /dev/null +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt @@ -0,0 +1,109 @@ +package org.siloserver.silo.viewmodel + +import androidx.lifecycle.ViewModel +import androidx.lifecycle.viewModelScope +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 kotlinx.coroutines.sync.Mutex +import kotlinx.coroutines.sync.withLock +import org.siloserver.silo.model.section.ProfileSectionSetting +import org.siloserver.silo.network.ApiResult +import org.siloserver.silo.network.AuthScopeSnapshot +import org.siloserver.silo.network.errorMessage +import org.siloserver.silo.repository.ProfileHomeLayoutRepository + +data class HomeSectionsEditorState( + val isLoading: Boolean = true, + /** The profile's Home rows in display order, hidden rows included. */ + val rows: List = emptyList(), + val loadError: String? = null, + /** The last change that could not be saved; the rows are back as they were before it. */ + val saveError: String? = null, +) + +/** + * State holder for the phone and TV Home Sections editors. The rows come + * from the acting profile's server layout, and every change is saved there + * at once, so the order and visibility follow the profile to every device + * and show in the admin's Home sections card. Saves run one at a time, in + * the order they were made, each carrying the whole list. + */ +class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepository) : ViewModel() { + private val _state = MutableStateFlow(HomeSectionsEditorState()) + val state: StateFlow = _state.asStateFlow() + + /** The profile the rows were read for; every save is pinned to it. */ + private var owner: AuthScopeSnapshot? = null + private val saves = Mutex() + private var loadJob: Job? = null + + /** (Re)reads the profile's rows; the editors call it each time they open. */ + fun load() { + loadJob?.cancel() + loadJob = viewModelScope.launch { + _state.update { it.copy(isLoading = true, loadError = null, saveError = null) } + when (val result = repository.load()) { + is ApiResult.Success -> { + owner = result.data.owner + _state.update { it.copy(isLoading = false, rows = result.data.rows, loadError = null) } + } + else -> _state.update { + it.copy(isLoading = false, loadError = result.errorMessage("Could not load Home sections.")) + } + } + } + } + + /** Moves row [id] by [offset] places (−1 earlier, +1 later) and saves. */ + fun move(id: String, offset: Int) { + val rows = _state.value.rows.toMutableList() + val from = rows.indexOfFirst { it.id == id } + val to = from + offset + if (from < 0 || to !in rows.indices) return + rows.add(to, rows.removeAt(from)) + commit(rows) + } + + /** Saves the rows in the order of [ids], for a drag that ended; unknown ids are ignored. */ + fun setOrder(ids: List) { + val current = _state.value.rows + val byId = current.associateBy { it.id } + val ordered = ids.distinct().mapNotNull(byId::get) + commit(ordered + current.filterNot { row -> ordered.any { it.id == row.id } }) + } + + fun setHidden(id: String, hidden: Boolean) { + commit(_state.value.rows.map { if (it.id == id) it.copy(hidden = hidden) else it }) + } + + fun dismissSaveError() { + _state.update { it.copy(saveError = null) } + } + + private fun commit(next: List) { + val previous = _state.value.rows + val owner = owner + if (next == previous || owner == null) return + _state.update { it.copy(rows = next, saveError = null) } + viewModelScope.launch { + saves.withLock { + val result = repository.save(owner, next) + if (result !is ApiResult.Success) { + _state.update { state -> + state.copy( + // A later change already carries this one and + // saves the whole list itself, so only an + // untouched list goes back. + rows = if (state.rows == next) previous else state.rows, + saveError = result.errorMessage("Could not save Home sections."), + ) + } + } + } + } + } +} diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt index 23f9031f81..66a17fddb1 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeViewModel.kt @@ -80,6 +80,8 @@ class HomeViewModel( * never reports and stays shown. */ startShown: Boolean = true, + /** Home layout saves from the Home Sections editor; each one re-reads Home in the new order. */ + private val homeLayoutChanges: org.siloserver.silo.repository.HomeLayoutChanges? = null, ) : ViewModel() { private var displayedOwner: AuthScopeSnapshot? = null @@ -141,6 +143,14 @@ class HomeViewModel( coordinator.refreshSignals.collect { refreshFromRealtime() } } } + homeLayoutChanges?.let { changes -> + viewModelScope.launch { + // A saved row order or visibility re-reads Home quietly, as a + // realtime update does: at once while Home is shown, else when + // it is shown again. + changes.revision.drop(1).collect { refreshFromRealtime() } + } + } } /** diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/network/apiv2/ProfileSectionsV2Test.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/network/apiv2/ProfileSectionsV2Test.kt new file mode 100644 index 0000000000..c4319c7527 --- /dev/null +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/network/apiv2/ProfileSectionsV2Test.kt @@ -0,0 +1,133 @@ +package org.siloserver.silo.network.apiv2 + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.* +import io.ktor.http.* +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.* +import org.siloserver.silo.model.section.ProfileSectionSetting +import org.siloserver.silo.model.section.SectionOverride +import org.siloserver.silo.network.* +import kotlin.test.* + +class ProfileSectionsV2Test { + private var owner = AuthScopeSnapshot("s", "p", "https://example.invalid", "pin", identityGeneration = 1) + private val tokens = object : TokenManager by TokenManagerImpl() { + override suspend fun snapshotCurrentScope(): AuthScopeSnapshot = owner + } + private val json = headersOf(HttpHeaders.ContentType, "application/json") + + private val settingsBody = """{"items":[ + {"id":"recent","section_type":"recently_added","title":"New this week","default_title":"Recently Added","featured":true,"item_limit":20,"hidden":true,"is_custom":false,"customized":true,"position":0,"config":{"days":7}}, + {"id":"ov-custom","section_type":"hidden_gems","title":"Gems","default_title":"","featured":false,"item_limit":12,"hidden":false,"is_custom":true,"customized":false,"position":1} + ]}""" + private val overridesBody = """{"items":[ + {"id":"ov-recent","section_id":"recent","position":0,"hidden":true,"removed":false,"section_type":"","title":"New this week","featured":null,"item_limit":null,"is_user_added":false,"user_section_type":"","user_title":"","config":{},"created_at":"2026-01-02T03:04:05.000Z","updated_at":null}, + {"id":"ov-custom","section_id":"","position":1,"hidden":false,"removed":false,"section_type":"hidden_gems","title":"","featured":false,"item_limit":12,"is_user_added":true,"user_section_type":"hidden_gems","user_title":"Gems","user_config":{"min":7},"created_at":null,"updated_at":null} + ]}""" + + private fun api(handler: MockRequestHandler): Pair { + val client = HttpClient(MockEngine(handler)) + return ProfileSectionsV2Api(client, tokens, ApiV2Gate.Unrestricted) to client + } + + @Test + fun readsHomeSettingsAndSavedOverridesForTheOwningProfile() = runTest { + val (api, client) = api { request -> + assertEquals(HttpMethod.Get, request.method) + assertEquals("home", request.url.parameters["scope"]) + assertEquals(owner, request.attributes[AuthScopeAttributeKey]) + assertTrue(request.attributes[RequireSiloAuthAttributeKey]) + when (request.url.encodedPath) { + "/api/v2/profile/sections/settings" -> respond(settingsBody, HttpStatusCode.OK, json) + "/api/v2/profile/sections" -> respond(overridesBody, HttpStatusCode.OK, json) + else -> error("unexpected ${request.url}") + } + } + try { + val settings = api.homeSettings(owner).getOrThrow() + assertEquals( + listOf( + ProfileSectionSetting( + id = "recent", sectionType = "recently_added", title = "New this week", + defaultTitle = "Recently Added", featured = true, itemLimit = 20, hidden = true, + customized = true, position = 0, + config = buildJsonObject { put("days", 7) }, + ), + ProfileSectionSetting( + id = "ov-custom", sectionType = "hidden_gems", title = "Gems", itemLimit = 12, + isCustom = true, position = 1, + ), + ), + settings, + ) + val saved = api.homeOverrides(owner).getOrThrow() + assertEquals( + listOf( + SectionOverride( + id = "ov-recent", sectionId = "recent", position = 0, hidden = true, + title = "New this week", config = JsonObject(emptyMap()), + ), + SectionOverride( + id = "ov-custom", position = 1, sectionType = "hidden_gems", featured = false, + itemLimit = 12, isUserAdded = true, userSectionType = "hidden_gems", + userTitle = "Gems", userConfig = buildJsonObject { put("min", 7) }, + ), + ), + saved, + ) + } finally { + client.close() + } + } + + @Test + fun replaceSendsOnlyWritableMembersAndOmitsNoOverrideNulls() = runTest { + var sent: JsonObject? = null + val (api, client) = api { request -> + assertEquals(HttpMethod.Put, request.method) + assertEquals("/api/v2/profile/sections", request.url.encodedPath) + assertEquals("home", request.url.parameters["scope"]) + assertEquals(owner, request.attributes[AuthScopeAttributeKey]) + sent = Json.parseToJsonElement((request.body as io.ktor.http.content.TextContent).text).jsonObject + respond("", HttpStatusCode.NoContent) + } + try { + val result = api.replaceHome( + owner, + listOf( + SectionOverride(id = "a", sectionId = "recent", position = 0, hidden = true, config = JsonObject(emptyMap())), + ), + ) + assertIs>(result) + assertEquals( + Json.parseToJsonElement( + """{"overrides":[{"id":"a","section_id":"recent","position":0,"hidden":true,"removed":false, + "section_type":"","title":"","config":{},"is_user_added":false,"user_section_type":"","user_title":""}]}""", + ), + sent, + ) + } finally { + client.close() + } + } + + @Test + fun aProfileSwitchRefusesTheWriteBeforeItIsSent() = runTest { + var sends = 0 + val (api, client) = api { _ -> + sends++ + respond("", HttpStatusCode.NoContent) + } + try { + val stale = owner + owner = owner.copy(profileId = "other") + val refused = api.replaceHome(stale, emptyList()) + assertIs(refused) + assertEquals("identity_changed", refused.error) + assertEquals(0, sends) + } finally { + client.close() + } + } +} diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionOverridesTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionOverridesTest.kt new file mode 100644 index 0000000000..851a6aec3b --- /dev/null +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionOverridesTest.kt @@ -0,0 +1,66 @@ +package org.siloserver.silo.repository + +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import org.siloserver.silo.model.section.ProfileSectionSetting +import org.siloserver.silo.model.section.SectionOverride +import kotlin.test.Test +import kotlin.test.assertEquals + +class HomeSectionOverridesTest { + private val config = JsonObject(mapOf("genre" to JsonPrimitive("drama"))) + private val renamed = SectionOverride( + id = "ov-recent", sectionId = "recent", position = 0, hidden = false, + title = "New this week", featured = true, itemLimit = 12, config = config, + ) + private val custom = SectionOverride( + id = "ov-custom", position = 1, isUserAdded = true, + userSectionType = "hidden_gems", userTitle = "Gems", userConfig = JsonObject(emptyMap()), + ) + private val removed = SectionOverride(id = "ov-gone", sectionId = "gone", position = 4, removed = true) + + private fun row(id: String, hidden: Boolean = false, isCustom: Boolean = false) = + ProfileSectionSetting(id = id, title = id, hidden = hidden, isCustom = isCustom) + + @Test + fun reorderKeepsRenamesAddedAndRemovedRowsAndWritesEveryPosition() { + val ids = ArrayDeque(listOf("new-1")) + val built = buildHomeSectionOverrides( + rows = listOf(row("continue", hidden = true), row("ov-custom", isCustom = true), row("recent")), + saved = listOf(renamed, custom, removed), + newId = { ids.removeFirst() }, + ) + + assertEquals( + listOf( + removed, + SectionOverride(id = "new-1", sectionId = "continue", position = 0, hidden = true), + custom.copy(position = 1, hidden = false), + renamed.copy(position = 2, hidden = false), + ), + built, + ) + } + + @Test + fun hidingARowWithASavedOverrideKeepsItsOtherFields() { + val built = buildHomeSectionOverrides( + rows = listOf(row("recent", hidden = true)), + saved = listOf(renamed), + newId = { error("no new id expected") }, + ) + + assertEquals(listOf(renamed.copy(position = 0, hidden = true)), built) + } + + @Test + fun aSavedOverrideWithoutAnIdGetsANewOne() { + val built = buildHomeSectionOverrides( + rows = listOf(row("recent")), + saved = listOf(renamed.copy(id = "")), + newId = { "fresh" }, + ) + + assertEquals(listOf(renamed.copy(id = "fresh", position = 0)), built) + } +} diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeScreenV2Test.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeScreenV2Test.kt index f4feeb3b80..1f65c7f15d 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeScreenV2Test.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeScreenV2Test.kt @@ -22,6 +22,7 @@ class HomeScreenV2Test { private var owner = AuthScopeSnapshot("s", "p", "https://example.invalid", "pin", identityGeneration = 1) private val tokens = object : TokenManager by TokenManagerImpl() { override suspend fun snapshotCurrentScope() = owner } private val language = org.siloserver.silo.domain.settings.CatalogLanguageRevision() + private val layoutChanges = HomeLayoutChanges() private var title = "Old" private var unresolved = false private var failFallback = false @@ -71,7 +72,7 @@ class HomeScreenV2Test { try { val repository = SectionRepository(SectionApi(client, home = HomeSectionsV2Api(client, tokens, ApiV2Gate.Unrestricted, decodeDispatcher = dispatcher))) val vm = HomeViewModel(repository, MediaActionsCoordinator(PersonalDataRepository(PersonalDataApi(client))), cache, local, - homeRealtime = realtime, catalogLanguage = language, startShown = startShown) + homeRealtime = realtime, catalogLanguage = language, startShown = startShown, homeLayoutChanges = layoutChanges) store.put("home", vm); block(vm) } finally { store.clear(); client.close(); Dispatchers.resetMain() } } @@ -145,6 +146,18 @@ class HomeScreenV2Test { assertEquals(2, listReads, "the deferred refresh runs once") } + // A Home layout saved from the editor shows on Home at once, and a hidden + // Home (TV while Settings is open) re-reads when it is shown again. + @Test fun savedHomeLayoutRereadsHome() = scenario(startShown = false) { vm -> + runCurrent(); assertEquals(1, listReads) + layoutChanges.changed(); runCurrent() + assertEquals(1, listReads, "a hidden Home must not re-read") + vm.onShown(); vm.runPendingRealtimeRefresh(); runCurrent() + assertEquals(2, listReads) + layoutChanges.changed(); runCurrent() + assertEquals(3, listReads) + } + @Test fun shownHomeRefreshesLiveAndStopsWhenHidden() = scenario { vm -> runCurrent(); assertEquals(1, listReads) reportAccessChange(); advanceTimeBy(5_000); runCurrent() diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt new file mode 100644 index 0000000000..63958b9dac --- /dev/null +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt @@ -0,0 +1,117 @@ +package org.siloserver.silo.viewmodel + +import androidx.lifecycle.ViewModelStore +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.* +import io.ktor.http.* +import io.ktor.http.content.TextContent +import kotlinx.coroutines.* +import kotlinx.coroutines.test.* +import kotlinx.serialization.json.* +import org.siloserver.silo.network.* +import org.siloserver.silo.network.apiv2.ApiV2Gate +import org.siloserver.silo.network.apiv2.ProfileSectionsV2Api +import org.siloserver.silo.repository.HomeLayoutChanges +import org.siloserver.silo.repository.ProfileHomeLayoutRepository +import kotlin.test.* + +@OptIn(ExperimentalCoroutinesApi::class) +class HomeSectionsEditorViewModelTest { + private val owner = AuthScopeSnapshot("s", "p", "https://example.invalid", "pin", identityGeneration = 1) + private val tokens = object : TokenManager by TokenManagerImpl() { + override suspend fun snapshotCurrentScope(): AuthScopeSnapshot = owner + } + private val json = headersOf(HttpHeaders.ContentType, "application/json") + private val settings = """{"items":[ + {"id":"recent","section_type":"recently_added","title":"New this week","default_title":"Recently Added","hidden":false,"is_custom":false,"position":0}, + {"id":"continue","section_type":"continue_watching","title":"Continue Watching","default_title":"Continue Watching","hidden":false,"is_custom":false,"position":1} + ]}""" + private val overrides = """{"items":[ + {"id":"ov-recent","section_id":"recent","position":null,"hidden":false,"removed":false,"section_type":"","title":"New this week","featured":null,"item_limit":null,"is_user_added":false,"user_section_type":"","user_title":"","created_at":null,"updated_at":null}, + {"id":"ov-gone","section_id":"gone","position":null,"hidden":false,"removed":true,"section_type":"","title":"","featured":null,"item_limit":null,"is_user_added":false,"user_section_type":"","user_title":"","created_at":null,"updated_at":null} + ]}""" + private var putStatus = HttpStatusCode.NoContent + private val puts = mutableListOf() + private val changes = HomeLayoutChanges() + + private fun scenario(block: suspend TestScope.(HomeSectionsEditorViewModel) -> Unit) = runTest { + val dispatcher = StandardTestDispatcher(testScheduler) + Dispatchers.setMain(dispatcher) + val client = HttpClient(MockEngine(MockEngineConfig().apply { + this.dispatcher = dispatcher + addHandler { request -> + when { + request.method == HttpMethod.Put -> { + puts += Json.parseToJsonElement((request.body as TextContent).text) + respond("", putStatus) + } + request.url.encodedPath.endsWith("/settings") -> respond(settings, HttpStatusCode.OK, json) + else -> respond(overrides, HttpStatusCode.OK, json) + } + } + })) + val store = ViewModelStore() + try { + val repository = ProfileHomeLayoutRepository( + ProfileSectionsV2Api(client, tokens, ApiV2Gate.Unrestricted), + changes, + newId = { "new-continue" }, + ) + val vm = HomeSectionsEditorViewModel(repository) + store.put("editor", vm) + vm.load() + block(vm) + } finally { + store.clear(); client.close(); Dispatchers.resetMain() + } + } + + @Test + fun movingARowSavesTheWholeLayoutToTheProfileAndRefreshesHome() = scenario { vm -> + runCurrent() + assertEquals(listOf("recent", "continue"), vm.state.value.rows.map { it.id }) + assertFalse(vm.state.value.isLoading) + + vm.move("continue", -1) + assertEquals(listOf("continue", "recent"), vm.state.value.rows.map { it.id }) + runCurrent() + + assertEquals( + Json.parseToJsonElement( + """{"overrides":[ + {"id":"ov-gone","section_id":"gone","hidden":false,"removed":true,"section_type":"","title":"","is_user_added":false,"user_section_type":"","user_title":""}, + {"id":"new-continue","section_id":"continue","position":0,"hidden":false,"removed":false,"section_type":"","title":"","is_user_added":false,"user_section_type":"","user_title":""}, + {"id":"ov-recent","section_id":"recent","position":1,"hidden":false,"removed":false,"section_type":"","title":"New this week","is_user_added":false,"user_section_type":"","user_title":""} + ]}""", + ), + puts.single(), + ) + assertEquals(1L, changes.revision.value) + assertNull(vm.state.value.saveError) + } + + @Test + fun hidingARowSavesItHidden() = scenario { vm -> + runCurrent() + vm.setHidden("recent", true) + runCurrent() + + val rows = puts.single().jsonObject.getValue("overrides").jsonArray.map { it.jsonObject } + val recent = rows.single { it["section_id"]?.jsonPrimitive?.content == "recent" } + assertEquals(JsonPrimitive(true), recent["hidden"]) + assertTrue(vm.state.value.rows.single { it.id == "recent" }.hidden) + } + + @Test + fun aFailedSaveRestoresThePreviousOrderAndSaysSo() = scenario { vm -> + runCurrent() + putStatus = HttpStatusCode.InternalServerError + + vm.move("continue", -1) + runCurrent() + + assertEquals(listOf("recent", "continue"), vm.state.value.rows.map { it.id }) + assertNotNull(vm.state.value.saveError) + assertEquals(0L, changes.revision.value) + } +} From a4b1154db4ac0dbf022794a97c26dfe7546711f0 Mon Sep 17 00:00:00 2001 From: Rhainland Date: Wed, 21 Oct 2026 23:43:36 +0200 Subject: [PATCH 2/6] fix(home): keep following the admin's row order until the profile reorders A hide-only change no longer writes a position for every Home row, so a profile that has never reordered its Home still follows the admin's later reorders, as the web editor does. Positions are written once the profile reorders rows or already has a saved position. The Home Sections editor also reads the layout only after pending saves finish, rolls a failed save back to the layout the server last confirmed, and shows its loading or error state instead of old rows while it reloads. --- .../siloserver/silo/tv/di/AndroidTvModule.kt | 4 +- .../silo/repository/HomeSectionOverrides.kt | 58 +++++++++------ .../repository/ProfileHomeLayoutRepository.kt | 11 ++- .../viewmodel/HomeSectionsEditorViewModel.kt | 53 +++++++++----- .../repository/HomeSectionOverridesTest.kt | 70 +++++++++++++++++++ .../HomeSectionsEditorViewModelTest.kt | 56 ++++++++++++++- 6 files changed, 209 insertions(+), 43 deletions(-) diff --git a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt index b20d01fd6c..d21f80d1d2 100644 --- a/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt +++ b/androidTvApp/src/androidMain/kotlin/org/siloserver/silo/tv/di/AndroidTvModule.kt @@ -315,8 +315,8 @@ val androidTvModule = module { org.siloserver.silo.common.settings.BrowsePrefsStore(androidContext(), get(), keyPrefix = "androidtv") } - // tvOS-parity Home row visibility/order, local to this TV and partitioned - // by active server + profile. + // Home Sections editor: the active profile's Home row order and + // visibility, read from and saved to the server. viewModel { org.siloserver.silo.viewmodel.HomeSectionsEditorViewModel(get()) } // One-shot legacy `tv_prefs` import (playback settings → server device diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionOverrides.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionOverrides.kt index 08918aabbf..2dfe0ff23f 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionOverrides.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/HomeSectionOverrides.kt @@ -6,21 +6,28 @@ import org.siloserver.silo.model.section.SectionOverride /** * The override set a profile saves for its Home page * (`PUT /api/v2/profile/sections?scope=home`), which replaces every override - * the profile saved for Home. + * the profile saved for Home. Mirrors the web editor's `buildSectionOverrides`. * * [rows] is the Home settings list (`/profile/sections/settings`) in the new - * display order, with each row's chosen visibility. Every row stores its - * list index as its position. A row the profile already saved an override - * for keeps that override, its id and every other field (a rename, a - * featured or item-limit change, a profile-built row's recipe and config), - * with only position and hidden replaced. An admin row with no override - * gets a new one from [newId]. A saved override whose row is not in [rows] - * (a row the profile removed, or one it cannot currently see) is kept - * unchanged, so a reorder never loses it. + * display order, with each row's chosen visibility; [baseline] is the same + * list as the server last confirmed it. + * + * The server uses a saved position whenever one is present, so positions are + * written only once the profile has ordered its Home: when [rows] reorders + * [baseline], or an earlier save already stored a position for an admin row. + * Then every row stores its list index. Until then admin rows keep following + * the admin's order: only a hidden admin row gets a new override, and a + * saved override keeps the position it has. + * + * A row with a saved override keeps that override, its id and every other + * field (a rename, a featured or item-limit change, a profile-built row's + * recipe and config). A saved override whose row is not in [rows] (a row the + * profile removed, or one it cannot currently see) is kept unchanged. */ fun buildHomeSectionOverrides( rows: List, saved: List, + baseline: List, newId: () -> String, ): List { // The server resolves the last saved override for a section, so that is @@ -30,22 +37,27 @@ fun buildHomeSectionOverrides( val key = override.rowKey() ?: continue savedByRow[key] = override } + val ordered = saved.any { it.sectionId.isNotBlank() && it.position != null } || + sharedOrder(rows, baseline) != sharedOrder(baseline, rows) val matched = mutableSetOf() val rowOverrides = rows.mapIndexedNotNull { index, row -> val existing = savedByRow[row.rowKey()] - if (existing != null) { - matched += existing - existing.copy( - id = existing.id.ifBlank { newId() }, - position = index, - hidden = row.hidden, - ) - } else if (row.isCustom) { + when { + existing != null -> { + matched += existing + existing.copy( + id = existing.id.ifBlank { newId() }, + position = if (ordered) index else existing.position, + hidden = row.hidden, + ) + } // A profile-built row only exists as its saved override; without // it there is no recipe to write back. - null - } else { - SectionOverride(id = newId(), sectionId = row.id, position = index, hidden = row.hidden) + row.isCustom -> null + ordered -> SectionOverride(id = newId(), sectionId = row.id, position = index, hidden = row.hidden) + row.hidden -> SectionOverride(id = newId(), sectionId = row.id, hidden = true) + // An untouched visible admin row needs no override. + else -> null } } // Unlisted overrides go first: should one duplicate a listed row's @@ -54,6 +66,12 @@ fun buildHomeSectionOverrides( return unlisted + rowOverrides } +/** The row keys of [a] in order, keeping only rows [b] also has. */ +private fun sharedOrder(a: List, b: List): List { + val keys = b.mapTo(mutableSetOf()) { it.rowKey() } + return a.map { it.rowKey() }.filter { it in keys } +} + /** Admin rows are matched by section id, profile-built rows by override id. */ private fun ProfileSectionSetting.rowKey(): String = if (isCustom) "custom:$id" else "admin:$id" diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt index 1937450544..388602c258 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt @@ -51,15 +51,20 @@ class ProfileHomeLayoutRepository( /** * Saves [rows] (the whole Home list in its new order, with each row's * visibility) as the profile's layout, keeping every other saved - * customization; see [buildHomeSectionOverrides]. + * customization. [baseline] is the list as the server last confirmed it; + * see [buildHomeSectionOverrides]. */ - suspend fun save(owner: AuthScopeSnapshot, rows: List): ApiResult { + suspend fun save( + owner: AuthScopeSnapshot, + rows: List, + baseline: List, + ): ApiResult { val saved = when (val read = api.homeOverrides(owner)) { is ApiResult.Success -> read.data is ApiResult.Error -> return read is ApiResult.NetworkError -> return read } - val result = api.replaceHome(owner, buildHomeSectionOverrides(rows, saved, newId)) + val result = api.replaceHome(owner, buildHomeSectionOverrides(rows, saved, baseline, newId)) if (result is ApiResult.Success) changes.changed() return result } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt index f39ca3a73e..703d6a165f 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt @@ -38,21 +38,39 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos /** The profile the rows were read for; every save is pinned to it. */ private var owner: AuthScopeSnapshot? = null + + /** The rows as the server last confirmed them: read, or saved. A failed save goes back to these. */ + private var confirmed: List = emptyList() + + /** Held by each save, and by each read so it never runs beside a save and shows the layout before it. */ private val saves = Mutex() private var loadJob: Job? = null - /** (Re)reads the profile's rows; the editors call it each time they open. */ + /** + * (Re)reads the profile's rows; the editors call it each time they open. + * Until the read lands the editor shows its loading state and takes no + * edits, so neither another profile's old rows nor an edit made before + * the read can be saved over the layout it returns. + */ fun load() { loadJob?.cancel() + owner = null + _state.update { it.copy(isLoading = true, rows = emptyList(), loadError = null, saveError = null) } loadJob = viewModelScope.launch { - _state.update { it.copy(isLoading = true, loadError = null, saveError = null) } - when (val result = repository.load()) { - is ApiResult.Success -> { - owner = result.data.owner - _state.update { it.copy(isLoading = false, rows = result.data.rows, loadError = null) } - } - else -> _state.update { - it.copy(isLoading = false, loadError = result.errorMessage("Could not load Home sections.")) + saves.withLock { + when (val result = repository.load()) { + is ApiResult.Success -> { + owner = result.data.owner + confirmed = result.data.rows + _state.update { it.copy(isLoading = false, rows = result.data.rows, loadError = null) } + } + else -> _state.update { + it.copy( + isLoading = false, + rows = emptyList(), + loadError = result.errorMessage("Could not load Home sections."), + ) + } } } } @@ -85,20 +103,21 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos } private fun commit(next: List) { - val previous = _state.value.rows val owner = owner - if (next == previous || owner == null) return + if (next == _state.value.rows || owner == null) return _state.update { it.copy(rows = next, saveError = null) } viewModelScope.launch { saves.withLock { - val result = repository.save(owner, next) - if (result !is ApiResult.Success) { + val result = repository.save(owner, next, baseline = confirmed) + if (result is ApiResult.Success) { + confirmed = next + } else { _state.update { state -> state.copy( - // A later change already carries this one and - // saves the whole list itself, so only an - // untouched list goes back. - rows = if (state.rows == next) previous else state.rows, + // A later change carries this one and saves the + // whole list itself; only the list this save + // failed to store goes back, to what the server has. + rows = if (state.rows == next) confirmed else state.rows, saveError = result.errorMessage("Could not save Home sections."), ) } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionOverridesTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionOverridesTest.kt index 851a6aec3b..5462cae2f4 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionOverridesTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/repository/HomeSectionOverridesTest.kt @@ -28,6 +28,7 @@ class HomeSectionOverridesTest { val built = buildHomeSectionOverrides( rows = listOf(row("continue", hidden = true), row("ov-custom", isCustom = true), row("recent")), saved = listOf(renamed, custom, removed), + baseline = listOf(row("recent"), row("ov-custom", isCustom = true), row("continue")), newId = { ids.removeFirst() }, ) @@ -47,6 +48,7 @@ class HomeSectionOverridesTest { val built = buildHomeSectionOverrides( rows = listOf(row("recent", hidden = true)), saved = listOf(renamed), + baseline = listOf(row("recent")), newId = { error("no new id expected") }, ) @@ -58,9 +60,77 @@ class HomeSectionOverridesTest { val built = buildHomeSectionOverrides( rows = listOf(row("recent")), saved = listOf(renamed.copy(id = "")), + baseline = listOf(row("recent")), newId = { "fresh" }, ) assertEquals(listOf(renamed.copy(id = "fresh", position = 0)), built) } + + // Until the profile orders its Home itself, rows keep following the + // admin's order, so a visibility change must not pin any position. + @Test + fun hidingARowOnAFreshProfileWritesNoPositionsAndOnlyThatRow() { + val built = buildHomeSectionOverrides( + rows = listOf(row("recent"), row("continue", hidden = true), row("trending")), + saved = emptyList(), + baseline = listOf(row("recent"), row("continue"), row("trending")), + newId = { "new" }, + ) + + assertEquals(listOf(SectionOverride(id = "new", sectionId = "continue", hidden = true)), built) + } + + @Test + fun showingARowAgainKeepsItsUnpositionedOverride() { + val hiddenOnly = SectionOverride(id = "ov-continue", sectionId = "continue", hidden = true) + val built = buildHomeSectionOverrides( + rows = listOf(row("recent"), row("continue")), + saved = listOf(hiddenOnly), + baseline = listOf(row("recent"), row("continue", hidden = true)), + newId = { error("no new id expected") }, + ) + + assertEquals(listOf(hiddenOnly.copy(hidden = false)), built) + } + + @Test + fun reorderingAFreshProfileWritesAPositionForEveryRow() { + val ids = ArrayDeque(listOf("n1", "n2")) + val built = buildHomeSectionOverrides( + rows = listOf(row("continue"), row("recent")), + saved = emptyList(), + baseline = listOf(row("recent"), row("continue")), + newId = { ids.removeFirst() }, + ) + + assertEquals( + listOf( + SectionOverride(id = "n1", sectionId = "continue", position = 0), + SectionOverride(id = "n2", sectionId = "recent", position = 1), + ), + built, + ) + } + + @Test + fun hidingARowAfterAnEarlierReorderKeepsWritingPositions() { + val built = buildHomeSectionOverrides( + rows = listOf(row("continue"), row("recent", hidden = true)), + saved = listOf( + SectionOverride(id = "ov-continue", sectionId = "continue", position = 0), + SectionOverride(id = "ov-recent", sectionId = "recent", position = 1), + ), + baseline = listOf(row("continue"), row("recent")), + newId = { error("no new id expected") }, + ) + + assertEquals( + listOf( + SectionOverride(id = "ov-continue", sectionId = "continue", position = 0), + SectionOverride(id = "ov-recent", sectionId = "recent", position = 1, hidden = true), + ), + built, + ) + } } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt index 63958b9dac..d66afc1a52 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt @@ -31,6 +31,9 @@ class HomeSectionsEditorViewModelTest { {"id":"ov-gone","section_id":"gone","position":null,"hidden":false,"removed":true,"section_type":"","title":"","featured":null,"item_limit":null,"is_user_added":false,"user_section_type":"","user_title":"","created_at":null,"updated_at":null} ]}""" private var putStatus = HttpStatusCode.NoContent + private var putGate: CompletableDeferred? = null + private var settingsReads = 0 + private var settingsStatus = HttpStatusCode.OK private val puts = mutableListOf() private val changes = HomeLayoutChanges() @@ -43,9 +46,14 @@ class HomeSectionsEditorViewModelTest { when { request.method == HttpMethod.Put -> { puts += Json.parseToJsonElement((request.body as TextContent).text) + putGate?.await() respond("", putStatus) } - request.url.encodedPath.endsWith("/settings") -> respond(settings, HttpStatusCode.OK, json) + request.url.encodedPath.endsWith("/settings") -> { + settingsReads++ + if (settingsStatus == HttpStatusCode.OK) respond(settings, HttpStatusCode.OK, json) + else respond("", settingsStatus) + } else -> respond(overrides, HttpStatusCode.OK, json) } } @@ -114,4 +122,50 @@ class HomeSectionsEditorViewModelTest { assertNotNull(vm.state.value.saveError) assertEquals(0L, changes.revision.value) } + + @Test + fun aSecondFailedSaveRestoresTheLastSavedLayoutNotTheFirstUnsavedChange() = scenario { vm -> + runCurrent() + putStatus = HttpStatusCode.InternalServerError + + vm.move("continue", -1) + vm.setHidden("recent", true) + runCurrent() + + assertEquals(listOf("recent", "continue"), vm.state.value.rows.map { it.id }) + assertFalse(vm.state.value.rows.single { it.id == "recent" }.hidden) + assertNotNull(vm.state.value.saveError) + } + + @Test + fun reopeningTheEditorWaitsForAPendingSaveBeforeReadingTheLayout() = scenario { vm -> + runCurrent() + val readsAfterOpen = settingsReads + putGate = CompletableDeferred() + + vm.move("continue", -1) + runCurrent() + vm.load() + runCurrent() + assertEquals(readsAfterOpen, settingsReads, "the layout was read while the save was still running") + + putGate!!.complete(Unit) + runCurrent() + assertEquals(readsAfterOpen + 1, settingsReads) + } + + @Test + fun aFailedReloadShowsTheErrorInsteadOfTheOldRowsAndCannotSave() = scenario { vm -> + runCurrent() + settingsStatus = HttpStatusCode.InternalServerError + + vm.load() + runCurrent() + + assertTrue(vm.state.value.rows.isEmpty()) + assertNotNull(vm.state.value.loadError) + vm.setHidden("recent", true) + runCurrent() + assertTrue(puts.isEmpty()) + } } From 20d7958c9288caa5d61d890baf7823a05a493aee Mon Sep 17 00:00:00 2001 From: Rhainland Date: Thu, 22 Oct 2026 09:51:44 +0200 Subject: [PATCH 3/6] fix(home): roll back a failed save only when nothing later owns the rows The rollback compared the rows on screen with the list the failed save sent, so a later edit that returned to the same list was rolled back with it. Each edit and reload now takes a generation, and a failed save rolls back only if it is still the latest. A successful save or reload clears the save error. --- .../viewmodel/HomeSectionsEditorViewModel.kt | 18 ++++++---- .../HomeSectionsEditorViewModelTest.kt | 35 ++++++++++++++++++- 2 files changed, 46 insertions(+), 7 deletions(-) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt index 703d6a165f..43a8e76f4a 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt @@ -21,7 +21,7 @@ data class HomeSectionsEditorState( /** The profile's Home rows in display order, hidden rows included. */ val rows: List = emptyList(), val loadError: String? = null, - /** The last change that could not be saved; the rows are back as they were before it. */ + /** The last change that could not be saved; unless a later change carries it, the rows are back as the server has them. */ val saveError: String? = null, ) @@ -39,13 +39,16 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos /** The profile the rows were read for; every save is pinned to it. */ private var owner: AuthScopeSnapshot? = null - /** The rows as the server last confirmed them: read, or saved. A failed save goes back to these. */ + /** The rows as the server last confirmed them: read, or saved. A failed save goes back to these unless a later change carries it. */ private var confirmed: List = emptyList() /** Held by each save, and by each read so it never runs beside a save and shows the layout before it. */ private val saves = Mutex() private var loadJob: Job? = null + /** Counts edits and reloads, so a failed save can tell whether something later owns the rows on screen. */ + private var rowsGeneration = 0L + /** * (Re)reads the profile's rows; the editors call it each time they open. * Until the read lands the editor shows its loading state and takes no @@ -55,6 +58,7 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos fun load() { loadJob?.cancel() owner = null + rowsGeneration++ _state.update { it.copy(isLoading = true, rows = emptyList(), loadError = null, saveError = null) } loadJob = viewModelScope.launch { saves.withLock { @@ -62,7 +66,7 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos is ApiResult.Success -> { owner = result.data.owner confirmed = result.data.rows - _state.update { it.copy(isLoading = false, rows = result.data.rows, loadError = null) } + _state.update { it.copy(isLoading = false, rows = result.data.rows, loadError = null, saveError = null) } } else -> _state.update { it.copy( @@ -106,18 +110,20 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos val owner = owner if (next == _state.value.rows || owner == null) return _state.update { it.copy(rows = next, saveError = null) } + val edit = ++rowsGeneration viewModelScope.launch { saves.withLock { val result = repository.save(owner, next, baseline = confirmed) if (result is ApiResult.Success) { confirmed = next + _state.update { it.copy(saveError = null) } } else { _state.update { state -> state.copy( // A later change carries this one and saves the - // whole list itself; only the list this save - // failed to store goes back, to what the server has. - rows = if (state.rows == next) confirmed else state.rows, + // whole list itself; only the last change's list + // goes back, to what the server has. + rows = if (edit == rowsGeneration) confirmed else state.rows, saveError = result.errorMessage("Could not save Home sections."), ) } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt index d66afc1a52..f977dc84ff 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt @@ -31,6 +31,8 @@ class HomeSectionsEditorViewModelTest { {"id":"ov-gone","section_id":"gone","position":null,"hidden":false,"removed":true,"section_type":"","title":"","featured":null,"item_limit":null,"is_user_added":false,"user_section_type":"","user_title":"","created_at":null,"updated_at":null} ]}""" private var putStatus = HttpStatusCode.NoContent + /** Statuses for the next PUTs in turn; [putStatus] once they run out. */ + private val putStatuses = ArrayDeque() private var putGate: CompletableDeferred? = null private var settingsReads = 0 private var settingsStatus = HttpStatusCode.OK @@ -47,7 +49,7 @@ class HomeSectionsEditorViewModelTest { request.method == HttpMethod.Put -> { puts += Json.parseToJsonElement((request.body as TextContent).text) putGate?.await() - respond("", putStatus) + respond("", putStatuses.removeFirstOrNull() ?: putStatus) } request.url.encodedPath.endsWith("/settings") -> { settingsReads++ @@ -137,6 +139,37 @@ class HomeSectionsEditorViewModelTest { assertNotNull(vm.state.value.saveError) } + @Test + fun aFailedSaveKeepsALaterEditThatReturnsToTheSameRows() = scenario { vm -> + runCurrent() + putStatuses += HttpStatusCode.InternalServerError + + vm.move("continue", -1) + vm.setHidden("recent", true) + vm.setHidden("recent", false) + runCurrent() + + assertEquals(3, puts.size) + assertEquals(listOf("continue", "recent"), vm.state.value.rows.map { it.id }) + assertNull(vm.state.value.saveError, "a later save stored the change the failed one carried") + } + + @Test + fun aReloadDropsTheErrorOfASaveThatFailedBeforeIt() = scenario { vm -> + runCurrent() + putStatus = HttpStatusCode.InternalServerError + putGate = CompletableDeferred() + + vm.move("continue", -1) + runCurrent() + vm.load() + putGate!!.complete(Unit) + runCurrent() + + assertEquals(listOf("recent", "continue"), vm.state.value.rows.map { it.id }) + assertNull(vm.state.value.saveError) + } + @Test fun reopeningTheEditorWaitsForAPendingSaveBeforeReadingTheLayout() = scenario { vm -> runCurrent() From 30c456968b326720d0f17006d9dc78664aa58df8 Mon Sep 17 00:00:00 2001 From: Quick <31828688+Quick104@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:37:12 +0000 Subject: [PATCH 4/6] fix(home): show the translated load error when no profile is chosen The editor's no-profile refusal carried an English message, which the editor shows as is. Without one, the editor falls back to its translated load error. Co-Authored-By: Claude Opus 5.5 --- .../siloserver/silo/repository/ProfileHomeLayoutRepository.kt | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt index 388602c258..7e0834a6fc 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt @@ -69,7 +69,8 @@ class ProfileHomeLayoutRepository( return result } - private fun noProfile() = ApiResult.Error(0, "identity_changed", "Choose a profile to arrange its Home rows.") + // No message, so the editor shows its own translated load error. + private fun noProfile() = ApiResult.Error(0, "identity_changed", "") } @OptIn(kotlin.uuid.ExperimentalUuidApi::class) From a35615fc2554163aca88d5a9ef5453b84a359171 Mon Sep 17 00:00:00 2001 From: Quick <31828688+Quick104@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:53:51 +0000 Subject: [PATCH 5/6] fix(home): read back the layout after a Home Sections save fails A save's reply can be lost after the server stored the change. The editor rolled back to its cached rows and said the save failed, while the server and the profile's other devices had the new layout; the next edit then wrote the old order back. A failed save now reads the layout back: when the change landed it keeps the new rows, clears the error and refreshes Home, otherwise it shows the server's rows. Saves also finish when leaving Settings clears the editor, and only the latest change reports a failure; a later change or reload carries an earlier one. Co-Authored-By: Claude Opus 5.5 --- .../silo/common/store/AccountLocalData.kt | 5 ++- .../repository/ProfileHomeLayoutRepository.kt | 18 +++++++++ .../viewmodel/HomeSectionsEditorViewModel.kt | 40 ++++++++++++++----- .../HomeSectionsEditorViewModelTest.kt | 25 +++++++++++- 4 files changed, 75 insertions(+), 13 deletions(-) diff --git a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/store/AccountLocalData.kt b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/store/AccountLocalData.kt index 7899a6107d..ceaa65b308 100644 --- a/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/store/AccountLocalData.kt +++ b/android-shared/src/androidMain/kotlin/org/siloserver/silo/common/store/AccountLocalData.kt @@ -231,6 +231,7 @@ class AccountLocalData( const val DATASTORE_SUFFIX = ".preferences_pb" const val BROWSE_PREFS = "browse_prefs" + /** No longer written (Home row order moved to the server); kept so older installs are cleaned up. */ const val HOME_SECTIONS_PREFS = "home_section_preferences" const val ONBOARDING_PREFS = "onboarding_tour" const val SERIES_AUTO_RESET_PREFS = "series_track_auto_resets" @@ -254,7 +255,9 @@ class AccountLocalData( /** * Per-(account, profile) DataStore files: `FILE_BASE` of * AndroidPlayerSettingsStore, AudiobookSettingsStore and the TV app's - * TvHomeSectionPreferences, TvLibraryScopeStore, TvLibrarySelectionStore. + * TvLibraryScopeStore, TvLibrarySelectionStore. `tv_home_sections` is + * no longer written (Home row order moved to the server); it stays + * listed so older installs' files are still cleaned up. */ val DATASTORE_BASES = listOf( "silo_player_settings", diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt index 7e0834a6fc..4eedf25a3a 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt @@ -69,9 +69,27 @@ class ProfileHomeLayoutRepository( return result } + /** + * After a failed [save] for [owner]: the rows the server now has, or null + * when they can't be read. A save whose reply was lost may still have + * landed; when the rows match [expected], Home re-reads as after a save. + */ + suspend fun readBack( + owner: AuthScopeSnapshot, + expected: List, + ): List? { + val rows = (api.homeSettings(owner) as? ApiResult.Success)?.data ?: return null + if (rows.sameLayoutAs(expected)) changes.changed() + return rows + } + // No message, so the editor shows its own translated load error. private fun noProfile() = ApiResult.Error(0, "identity_changed", "") } @OptIn(kotlin.uuid.ExperimentalUuidApi::class) private fun newOverrideId(): String = kotlin.uuid.Uuid.random().toString() + +/** The same rows in the same order, each shown or hidden alike. */ +fun List.sameLayoutAs(other: List): Boolean = + map { it.id to it.hidden } == other.map { it.id to it.hidden } diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt index cb80348bd5..39b95c46f1 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt @@ -3,11 +3,13 @@ package org.siloserver.silo.viewmodel import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import kotlinx.coroutines.Job +import kotlinx.coroutines.NonCancellable 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 kotlinx.coroutines.withContext import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.siloserver.silo.common.i18n.SharedString @@ -17,6 +19,7 @@ import org.siloserver.silo.model.section.ProfileSectionSetting import org.siloserver.silo.network.ApiResult import org.siloserver.silo.network.AuthScopeSnapshot import org.siloserver.silo.repository.ProfileHomeLayoutRepository +import org.siloserver.silo.repository.sameLayoutAs data class HomeSectionsEditorState( val isLoading: Boolean = true, @@ -114,19 +117,34 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos _state.update { it.copy(rows = next, saveError = null) } val edit = ++rowsGeneration viewModelScope.launch { - saves.withLock { - val result = repository.save(owner, next, baseline = confirmed) - if (result is ApiResult.Success) { - confirmed = next - _state.update { it.copy(saveError = null) } - } else { + // Leaving Settings clears this ViewModel; a change the user + // already sees saved must still reach the server. + withContext(NonCancellable) { + saves.withLock { + val result = repository.save(owner, next, baseline = confirmed) + if (result is ApiResult.Success) { + confirmed = next + _state.update { it.copy(saveError = null) } + return@withLock + } + // The reply can be lost after the server stored the + // change, so read back what it has instead of assuming + // the old rows. + val serverRows = repository.readBack(owner, next) + if (serverRows != null) confirmed = serverRows + val landed = serverRows?.sameLayoutAs(next) == true + // A later change or reload carries this one and reports + // its own outcome; only the latest change goes back to + // what the server has and says it failed. + val latest = edit == rowsGeneration _state.update { state -> state.copy( - // A later change carries this one and saves the - // whole list itself; only the last change's list - // goes back, to what the server has. - rows = if (edit == rowsGeneration) confirmed else state.rows, - saveError = result.errorText(SharedString.HomeEditorSaveFailed), + rows = if (latest) confirmed else state.rows, + saveError = when { + !latest -> state.saveError + landed -> null + else -> result.errorText(SharedString.HomeEditorSaveFailed) + }, ) } } diff --git a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt index f977dc84ff..fa8f6cdba3 100644 --- a/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt +++ b/shared/src/commonTest/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModelTest.kt @@ -30,12 +30,15 @@ class HomeSectionsEditorViewModelTest { {"id":"ov-recent","section_id":"recent","position":null,"hidden":false,"removed":false,"section_type":"","title":"New this week","featured":null,"item_limit":null,"is_user_added":false,"user_section_type":"","user_title":"","created_at":null,"updated_at":null}, {"id":"ov-gone","section_id":"gone","position":null,"hidden":false,"removed":true,"section_type":"","title":"","featured":null,"item_limit":null,"is_user_added":false,"user_section_type":"","user_title":"","created_at":null,"updated_at":null} ]}""" + private var settingsBody = settings private var putStatus = HttpStatusCode.NoContent /** Statuses for the next PUTs in turn; [putStatus] once they run out. */ private val putStatuses = ArrayDeque() private var putGate: CompletableDeferred? = null private var settingsReads = 0 private var settingsStatus = HttpStatusCode.OK + /** Settings the server returns after the next PUT, stored even when the PUT's reply is an error. */ + private var settingsAfterPut: String? = null private val puts = mutableListOf() private val changes = HomeLayoutChanges() @@ -48,12 +51,13 @@ class HomeSectionsEditorViewModelTest { when { request.method == HttpMethod.Put -> { puts += Json.parseToJsonElement((request.body as TextContent).text) + settingsAfterPut?.let { settingsBody = it } putGate?.await() respond("", putStatuses.removeFirstOrNull() ?: putStatus) } request.url.encodedPath.endsWith("/settings") -> { settingsReads++ - if (settingsStatus == HttpStatusCode.OK) respond(settings, HttpStatusCode.OK, json) + if (settingsStatus == HttpStatusCode.OK) respond(settingsBody, HttpStatusCode.OK, json) else respond("", settingsStatus) } else -> respond(overrides, HttpStatusCode.OK, json) @@ -125,6 +129,25 @@ class HomeSectionsEditorViewModelTest { assertEquals(0L, changes.revision.value) } + // The PUT is not retried, so an error can arrive after the server stored + // the change. The editor shows what the server has, not the old rows. + @Test + fun aSaveTheServerStoredDespiteAnErrorReplyKeepsTheNewRows() = scenario { vm -> + runCurrent() + putStatus = HttpStatusCode.GatewayTimeout + settingsAfterPut = """{"items":[ + {"id":"continue","section_type":"continue_watching","title":"Continue Watching","default_title":"Continue Watching","hidden":false,"is_custom":false,"position":0}, + {"id":"recent","section_type":"recently_added","title":"New this week","default_title":"Recently Added","hidden":false,"is_custom":false,"position":1} + ]}""" + + vm.move("continue", -1) + runCurrent() + + assertEquals(listOf("continue", "recent"), vm.state.value.rows.map { it.id }) + assertNull(vm.state.value.saveError) + assertEquals(1L, changes.revision.value, "Home re-reads the layout that landed") + } + @Test fun aSecondFailedSaveRestoresTheLastSavedLayoutNotTheFirstUnsavedChange() = scenario { vm -> runCurrent() From 293c73ff49e3bd8bdb684bf36b22f3b9c03bd5f5 Mon Sep 17 00:00:00 2001 From: Quick <31828688+Quick104@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:35:23 +0000 Subject: [PATCH 6/6] fix(home): share the Home Sections save lock across editors An editor reopened while an earlier one was still saving read the layout before that save landed, and its next edit wrote the older list back. The lock now lives in the shared repository, so every editor's reads wait for any save in flight. The read-back after a failed save compared the whole row list, so a row the admin added meanwhile made a landed save look failed. It now compares the rows both lists have, and Home re-reads whenever the read-back differs from the last confirmed rows. Co-Authored-By: Claude Opus 5.5 --- .../repository/ProfileHomeLayoutRepository.kt | 27 ++++++++++++++----- .../viewmodel/HomeSectionsEditorViewModel.kt | 7 +++-- 2 files changed, 24 insertions(+), 10 deletions(-) diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt index 4eedf25a3a..18c50d7f39 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/repository/ProfileHomeLayoutRepository.kt @@ -4,6 +4,7 @@ import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update +import kotlinx.coroutines.sync.Mutex import org.siloserver.silo.model.section.ProfileSectionSetting import org.siloserver.silo.network.ApiResult import org.siloserver.silo.network.AuthScopeSnapshot @@ -39,6 +40,13 @@ class ProfileHomeLayoutRepository( private val changes: HomeLayoutChanges, private val newId: () -> String = ::newOverrideId, ) { + /** + * Held by every editor's saves and reads. The repository outlives each + * editor, so an editor reopened while an earlier one still saves reads + * the layout after that save, not before it. + */ + internal val editorLock = Mutex() + suspend fun load(): ApiResult { val owner = api.capture() ?: return noProfile() return when (val rows = api.homeSettings(owner)) { @@ -72,14 +80,15 @@ class ProfileHomeLayoutRepository( /** * After a failed [save] for [owner]: the rows the server now has, or null * when they can't be read. A save whose reply was lost may still have - * landed; when the rows match [expected], Home re-reads as after a save. + * landed, or the layout changed elsewhere; when the rows differ from + * [previous] (the rows last confirmed), Home re-reads as after a save. */ suspend fun readBack( owner: AuthScopeSnapshot, - expected: List, + previous: List, ): List? { val rows = (api.homeSettings(owner) as? ApiResult.Success)?.data ?: return null - if (rows.sameLayoutAs(expected)) changes.changed() + if (rows.map { it.id to it.hidden } != previous.map { it.id to it.hidden }) changes.changed() return rows } @@ -90,6 +99,12 @@ class ProfileHomeLayoutRepository( @OptIn(kotlin.uuid.ExperimentalUuidApi::class) private fun newOverrideId(): String = kotlin.uuid.Uuid.random().toString() -/** The same rows in the same order, each shown or hidden alike. */ -fun List.sameLayoutAs(other: List): Boolean = - map { it.id to it.hidden } == other.map { it.id to it.hidden } +/** + * The rows both lists have are in the same order and shown or hidden alike. + * A row the admin added or removed in the meantime doesn't count against it. + */ +fun List.sameLayoutAs(other: List): Boolean { + val shared = map { it.id }.toSet().intersect(other.map { it.id }.toSet()) + fun List.layout() = filter { it.id in shared }.map { it.id to it.hidden } + return layout() == other.layout() +} diff --git a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt index 39b95c46f1..033212bd26 100644 --- a/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt +++ b/shared/src/commonMain/kotlin/org/siloserver/silo/viewmodel/HomeSectionsEditorViewModel.kt @@ -10,7 +10,6 @@ import kotlinx.coroutines.flow.asStateFlow import kotlinx.coroutines.flow.update import kotlinx.coroutines.launch import kotlinx.coroutines.withContext -import kotlinx.coroutines.sync.Mutex import kotlinx.coroutines.sync.withLock import org.siloserver.silo.common.i18n.SharedString import org.siloserver.silo.common.i18n.UiText @@ -47,8 +46,8 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos /** The rows as the server last confirmed them: read, or saved. A failed save goes back to these unless a later change carries it. */ private var confirmed: List = emptyList() - /** Held by each save, and by each read so it never runs beside a save and shows the layout before it. */ - private val saves = Mutex() + /** Held by each save, and by each read so it never runs beside a save and shows the layout before it. Shared by every editor instance. */ + private val saves get() = repository.editorLock private var loadJob: Job? = null /** Counts edits and reloads, so a failed save can tell whether something later owns the rows on screen. */ @@ -130,7 +129,7 @@ class HomeSectionsEditorViewModel(private val repository: ProfileHomeLayoutRepos // The reply can be lost after the server stored the // change, so read back what it has instead of assuming // the old rows. - val serverRows = repository.readBack(owner, next) + val serverRows = repository.readBack(owner, previous = confirmed) if (serverRows != null) confirmed = serverRows val landed = serverRows?.sameLayoutAs(next) == true // A later change or reload carries this one and reports