Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -472,6 +472,7 @@ val androidTvModule = module {
libraryId = params.get(),
libraryTitle = params.get(),
libraryType = params.get(),
mediaScope = params.values.getOrNull(3) as? String,
)
}
viewModel { params ->
Expand All @@ -481,6 +482,8 @@ val androidTvModule = module {
libraryId = params.get(),
collectionId = params.get(),
title = params.get(),
mediaScope = params.values.getOrNull(3) as? String,
collectionSource = params.values.getOrNull(4) as? String ?: "library_collection",
)
}
viewModel { TvSearchViewModel(get(), get(), get()) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -908,9 +908,9 @@ fun TvAppNavigation(
onOpenWatchParty = {
navController.navigateToWatchParty(null, watchPartyRepository, lastPlaybackNavigation)
},
onOpenLibraryCollectionDetail = { libraryId, collectionId, title, libraryType ->
onOpenLibraryCollectionDetail = { libraryId, collectionId, title, libraryType, source, scope ->
navController.navigate(
TvRoute.LibraryCollectionDetail(libraryId, collectionId, title, libraryType).route,
TvRoute.LibraryCollectionDetail(libraryId, collectionId, title, libraryType, source, scope).route,
)
},
onOpenCollectionDetail = { collectionId, title ->
Expand Down Expand Up @@ -1512,6 +1512,14 @@ fun TvAppNavigation(
type = NavType.StringType
defaultValue = ""
},
navArgument(TvRoute.LibraryCollectionDetail.ARG_MEDIA_SCOPE) {
type = NavType.StringType
defaultValue = ""
},
navArgument(TvRoute.LibraryCollectionDetail.ARG_SOURCE) {
type = NavType.StringType
defaultValue = "library_collection"
},
navArgument(TvRoute.LibraryCollectionDetail.ARG_LIBRARY_TYPE) {
type = NavType.StringType
defaultValue = ""
Expand All @@ -1531,6 +1539,8 @@ fun TvAppNavigation(
?.getString(TvRoute.LibraryCollectionDetail.ARG_LIBRARY_TYPE)
.orEmpty()
TvLibraryCollectionDetailScreen(
mediaScope = backStack.arguments?.getString(TvRoute.LibraryCollectionDetail.ARG_MEDIA_SCOPE)?.takeIf { it in setOf("movie", "series") },
collectionSource = backStack.arguments?.getString(TvRoute.LibraryCollectionDetail.ARG_SOURCE) ?: "library_collection",
libraryId = libraryId,
collectionId = collectionId,
title = title,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -248,17 +248,21 @@ sealed class TvRoute(val route: String) {
val title: String,
/** Drives which sort keys and filter facets the page offers. */
val libraryType: String = "",
val collectionSource: String = "library_collection",
val mediaScope: String? = null,
) : TvRoute(
"library/$libraryId/collection/${collectionId.routeEncode()}" +
"?title=${title.routeEncode()}&libraryType=${libraryType.routeEncode()}"
"?title=${title.routeEncode()}&libraryType=${libraryType.routeEncode()}&source=${collectionSource.routeEncode()}&mediaScope=${mediaScope.orEmpty().routeEncode()}"
) {
companion object {
const val ROUTE =
"library/{libraryId}/collection/{collectionId}?title={title}&libraryType={libraryType}"
"library/{libraryId}/collection/{collectionId}?title={title}&libraryType={libraryType}&source={collectionSource}&mediaScope={mediaScope}"
const val ARG_LIBRARY_ID = "libraryId"
const val ARG_COLLECTION_ID = "collectionId"
const val ARG_TITLE = "title"
const val ARG_LIBRARY_TYPE = "libraryType"
const val ARG_SOURCE = "collectionSource"
const val ARG_MEDIA_SCOPE = "mediaScope"
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,22 @@ import org.siloserver.silo.tv.ui.theme.tvPresetGridColumns
import org.koin.compose.viewmodel.koinViewModel
import org.koin.core.parameter.parametersOf

/**
* A mixed library opens personal collections here too, so the shuffle scope
* follows the collection's source: a personal collection id means nothing to
* the library-collection namespace. A Movies- or Series-scoped view offers no
* shuffle, since a shuffle request carries no media type or library and would
* draw from the whole collection.
*/
internal fun collectionShuffleKind(
collectionSource: String,
mediaScope: String?,
): org.siloserver.silo.model.shuffle.ShuffleScopeKind? = when {
mediaScope != null -> null
collectionSource == "user_collection" -> org.siloserver.silo.model.shuffle.ShuffleScopeKind.USER_COLLECTION
else -> org.siloserver.silo.model.shuffle.ShuffleScopeKind.LIBRARY_COLLECTION
}

/** Which overlay panel is open over the collection grid (mirrors Browse). */
private enum class TvCollectionPanel { Sort, Filter }

Expand All @@ -44,29 +60,30 @@ fun TvLibraryCollectionDetailScreen(
collectionId: String,
title: String,
libraryType: String,
collectionSource: String = "library_collection",
mediaScope: String? = null,
onItemClick: (contentId: String) -> Unit,
onBack: () -> Unit,
// Plays the first pick of a shuffle started from the header.
onShuffleStarted: (org.siloserver.silo.model.shuffle.Shuffle) -> Unit = {},
viewModel: TvLibraryCollectionDetailViewModel = koinViewModel(
key = "library-collection-$libraryId-$collectionId",
parameters = { parametersOf(libraryId, collectionId, title) },
key = "library-collection-$libraryId-$collectionId-$libraryType-$collectionSource-${mediaScope.orEmpty()}",
parameters = { parametersOf(libraryId, collectionId, title, mediaScope, collectionSource) },
),
) {
val state by viewModel.uiState.collectAsState()
val shuffleLauncher = org.siloserver.silo.common.ui.rememberShuffleLauncher(
org.koin.compose.koinInject(),
onShuffleStarted,
)
val shuffleKind = collectionShuffleKind(collectionSource, mediaScope)
val onShuffle = if (
shuffleKind != null &&
state.items.isNotEmpty() &&
shuffleLauncher.supports(org.siloserver.silo.model.shuffle.ShuffleScopeKind.LIBRARY_COLLECTION)
shuffleLauncher.supports(shuffleKind)
) {
{
shuffleLauncher.start(
org.siloserver.silo.model.shuffle.ShuffleScopeKind.LIBRARY_COLLECTION,
collectionId,
)
shuffleLauncher.start(shuffleKind, collectionId)
Comment thread
RXWatcher marked this conversation as resolved.
Resolved
}
} else {
null
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ class TvLibraryCollectionDetailViewModel(
private val libraryId: Int,
private val collectionId: String,
val title: String,
private val mediaScope: String? = null,
private val collectionSource: String = "library_collection",
) : ViewModel() {

data class UiState(
Expand Down Expand Up @@ -99,7 +101,7 @@ class TvLibraryCollectionDetailViewModel(
viewModelScope.launch {
val result = catalogRepository.getFilters(
includeTechnical = true,
source = "library_collection",
source = collectionSource,
collectionId = collectionId,
)
if (result is ApiResult.Success) {
Expand Down Expand Up @@ -177,6 +179,9 @@ class TvLibraryCollectionDetailViewModel(
collectionId,
continuation = cursor,
limit = PAGE_SIZE,
mediaType = mediaScope,
libraryId = libraryId.takeIf { mediaScope != null },
source = collectionSource,
sort = state.sort.ifBlank { null },
order = state.order,
queryGroups = facetGroups,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ import org.siloserver.silo.tv.ui.focus.requestFocusUntilObserved
import org.siloserver.silo.tv.ui.focus.TvObservedFocusResult
import org.siloserver.silo.tv.ui.focus.TvContentInitialFocusMaxAttempts
import androidx.tv.material3.Card
import androidx.tv.material3.Button
import androidx.tv.material3.CardDefaults
import androidx.tv.material3.ExperimentalTvMaterial3Api
import androidx.tv.material3.Icon
Expand Down Expand Up @@ -101,6 +102,7 @@ fun TvLibraryDetailScreen(
libraryId: Int,
libraryTitle: String,
libraryType: String,
mediaScope: String? = null,
onItemClick: (contentId: String) -> Unit,
onCollectionClick: (collectionId: String, title: String, isUserCollection: Boolean) -> Unit,
onInitialContentFocus: () -> Unit = {},
Expand All @@ -117,17 +119,20 @@ fun TvLibraryDetailScreen(
// Plays the first pick of a shuffle started from the Library tab.
onShuffleStarted: (org.siloserver.silo.model.shuffle.Shuffle) -> Unit = {},
viewModel: TvLibraryDetailViewModel = koinViewModel(
key = "library-$libraryId",
parameters = { parametersOf(libraryId, libraryTitle, libraryType) },
key = "library-$libraryId-${mediaScope.orEmpty()}",
parameters = { parametersOf(libraryId, libraryTitle, libraryType, mediaScope) },
),
) {
val state by viewModel.uiState.collectAsState()
val shuffleLauncher = org.siloserver.silo.common.ui.rememberShuffleLauncher(
org.koin.compose.koinInject(),
onShuffleStarted,
)
// Movie, TV, and mixed libraries shuffle when the server offers it.
// Movie, TV, and mixed libraries shuffle when the server offers it. A
// Movies- or Series-scoped view of a mixed library does not: a shuffle
// request carries no media type, so it would draw from both.
val onShuffleLibrary = if (
mediaScope == null &&
org.siloserver.silo.model.shuffle.isShuffleLibraryType(libraryType) &&
shuffleLauncher.supports(org.siloserver.silo.model.shuffle.ShuffleScopeKind.LIBRARY)
) {
Expand All @@ -153,7 +158,7 @@ fun TvLibraryDetailScreen(
) {
when (state.selectedTab) {
TvLibraryTab.Recommended -> RecommendedTab(
surfaceKey = "library-$libraryId",
surfaceKey = "library-$libraryId-${mediaScope.orEmpty()}",
state = state,
onItemClick = onItemClick,
onRetry = viewModel::retryRecommended,
Expand Down Expand Up @@ -268,6 +273,7 @@ fun TvLibraryDetailScreen(
// Tab content
// ============================================================================

@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
private fun RecommendedTab(
/** Distinguishes this feed's saveable slots from other surfaces'. */
Expand Down Expand Up @@ -307,14 +313,28 @@ private fun RecommendedTab(
)
}
else -> {
TvSkylineSectionFeed(
surfaceKey = surfaceKey,
sections = rows,
onItemClick = onItemClick,
focusRequest = focusRequest,
onInitialContentFocus = onInitialContentFocus,
onContentUpFallbackChanged = onContentUpFallbackChanged,
)
Box {
TvSkylineSectionFeed(
surfaceKey = surfaceKey,
sections = rows,
onItemClick = onItemClick,
focusRequest = focusRequest,
onInitialContentFocus = onInitialContentFocus,
onContentUpFallbackChanged = onContentUpFallbackChanged,
)
state.recommendedError?.let { message ->
Row(
modifier = Modifier.align(Alignment.BottomCenter).fillMaxWidth()
.background(MaterialTheme.colorScheme.surface)
.padding(horizontal = Spacing.safeArea, vertical = 16.dp),
horizontalArrangement = Arrangement.spacedBy(16.dp),
verticalAlignment = Alignment.CenterVertically,
) {
Text(message, modifier = Modifier.weight(1f))
Button(onClick = onRetry) { Text("Retry") }
}
}
}
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,13 +16,17 @@ import org.siloserver.silo.repository.SectionRepository
import org.siloserver.silo.tv.ui.util.tvCatalogMediaTypeFor
import org.siloserver.silo.tv.ui.util.visibleOnTv
import kotlinx.coroutines.async
import kotlinx.coroutines.Job
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.ensureActive
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.isActive
import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withPermit

/**
* Library content sections committed by the Skyline cascade. The extra browse
Expand Down Expand Up @@ -158,6 +162,7 @@ class TvLibraryDetailViewModel(
private val libraryId: Int,
private val libraryTitle: String,
private val libraryType: String,
private val mediaScope: String? = null,
) : ViewModel() {

data class UiState(
Expand Down Expand Up @@ -399,11 +404,15 @@ class TvLibraryDetailViewModel(
}

private var recommendedGeneration = 0L
private var recommendedJob: Job? = null

private fun loadRecommended() {
val run = ++recommendedGeneration
loadedRecommended = true
viewModelScope.launch {
// A retry supersedes the running load; cancel it so its refill
// cursor chains stop instead of paging until the final publish check.
recommendedJob?.cancel()
recommendedJob = viewModelScope.launch {
_uiState.update { it.copy(recommendedLoading = true, recommendedError = null) }

val owner = sectionRepository.captureLibrarySectionAuthority()
Expand Down Expand Up @@ -479,12 +488,26 @@ class TvLibraryDetailViewModel(
sections.map { section -> resolvedById[section.id] ?: section }
}

// Independent shelves can overlap, but keep each cursor chain sequential.
val refillPermits = Semaphore(3)
val scoped = resolved.filterNot { it.featured }.map { section ->
async {
refillPermits.withPermit {
scopeTvLibrarySection(section, mediaScope) { cursor ->
// Each page request also rechecks the auth identity.
kotlinx.coroutines.currentCoroutineContext().ensureActive()
sectionRepository.getLibrarySectionCatalogItems(libraryId, section.id, owner, cursor)
}
}
}
}.awaitAll()
if (!mayPublish()) return@launch
_uiState.update {
it.copy(
sections = resolved.visibleOnTv(),
sections = scoped.map { it.section }.visibleOnTv(),
recommendedLoading = false,
recommendedError = null,
recommendedError = if (scoped.any { it.incomplete })
"Some shelves could not be fully loaded for this media type. Retry or open Browse." else null,
)
}
}
Expand Down Expand Up @@ -547,7 +570,7 @@ class TvLibraryDetailViewModel(
val facetGroups = filter.facetSelection.toQueryGroups()
val result = catalogRepository.browse(
source = "query",
mediaType = mediaTypeFor(libraryType),
mediaType = mediaScope ?: mediaTypeFor(libraryType),
libraryId = libraryId,
genre = filter.genre,
sort = filter.sort,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
package org.siloserver.silo.tv.ui.screens.library

import kotlinx.serialization.encodeToString
import org.siloserver.silo.model.catalog.CatalogResponse
import org.siloserver.silo.model.section.ResolvedSection
import org.siloserver.silo.model.section.SectionItem
import org.siloserver.silo.network.ApiResult
import org.siloserver.silo.network.SiloJson
import org.siloserver.silo.network.apiv2.CatalogContinuationV2

internal fun matchesTvMediaScope(type: String, scope: String?): Boolean = when (scope) {
"movie" -> type.trim().lowercase() in setOf("movie", "movies", "film")
"series" -> type.trim().lowercase() in setOf("series", "show", "shows", "tv", "episode")
else -> true
}

internal data class ScopedTvSection(val section: ResolvedSection, val incomplete: Boolean = false)

/** Section sources reject type overlays. Page their original order and filter locally. */
internal suspend fun scopeTvLibrarySection(
section: ResolvedSection,
mediaScope: String?,
loadPage: suspend (CatalogContinuationV2?) -> ApiResult<CatalogResponse>,
): ScopedTvSection {
if (mediaScope == null) return ScopedTvSection(section)
val initial = section.items.filter { matchesTvMediaScope(it.type, mediaScope) }
val target = (section.itemLimit.takeIf { it > 0 } ?: section.items.size.coerceAtLeast(20)).coerceAtMost(100)
fun result(items: List<SectionItem>, incomplete: Boolean = false) =
ScopedTvSection(section.copy(items = items.take(target), totalCount = items.size.coerceAtMost(target)), incomplete)
// Inline total_count is not an exhaustion signal: several server shelves (e.g. recently added)
// report the bounded inline count. Only the catalog continuation can say nothing else remains.
if (initial.size >= target) return result(initial)
// The catalog section source pages the stored admin definition, not the profile-resolved one, so a
// customized or profile-added shelf cannot be refilled without dropping the profile's overrides.
if (section.customized || section.isCustom) return result(initial, incomplete = true)

val originals = section.items.associateBy { it.contentId }
val visible = linkedMapOf<String, SectionItem>()
var continuation: CatalogContinuationV2? = null
repeat(8) {
when (val page = loadPage(continuation)) {
is ApiResult.Success -> {
page.data.items.filter { matchesTvMediaScope(it.type, mediaScope) }.forEach { item ->
visible.putIfAbsent(item.contentId, originals[item.contentId]
?: SiloJson.decodeFromString<SectionItem>(SiloJson.encodeToString(item)))
}
if (visible.size >= target || !page.data.hasMore) return result(visible.values.toList())
val next = page.data.continuation
if (next == null || next === continuation || page.data.items.isEmpty())
return result((visible.values + initial).distinctBy { it.contentId }, true)
continuation = next
}
else -> return result((visible.values + initial).distinctBy { it.contentId }, true)
}
}
return result((visible.values + initial).distinctBy { it.contentId }, true)
}
Loading
Loading