Skip to content

StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.

Complete premium Android TV upgrade roadmap

Davidonab576d3b05aa7
diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
index 06360b50..0f758f61 100644
--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
@@ -48,6 +48,9 @@ abstract class RepositoryModule {
@Binds @Singleton
abstract fun bindBackupManager(impl: com.streamvault.data.manager.BackupManagerImpl): com.streamvault.domain.manager.BackupManager
+ @Binds @Singleton
+ abstract fun bindRecordingManager(impl: com.streamvault.data.manager.RecordingManagerImpl): com.streamvault.domain.manager.RecordingManager
+
companion object {
@Provides
@Singleton
diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
index 5baa8aa9..53488d3f 100644
--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
@@ -6,6 +6,11 @@ import androidx.navigation.compose.NavHost
import androidx.navigation.compose.composable
import androidx.navigation.compose.rememberNavController
import androidx.navigation.navArgument
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.app.ui.screens.dashboard.DashboardScreen
import com.streamvault.app.ui.screens.favorites.FavoritesScreen
import com.streamvault.app.ui.screens.favorites.FavoriteUiModel
import com.streamvault.app.ui.screens.multiview.MultiViewScreen
@@ -21,12 +26,15 @@ import com.streamvault.app.ui.screens.welcome.WelcomeScreen
object Routes {
const val PROVIDER_SETUP = "provider_setup?providerId={providerId}"
const val HOME = "home"
+ const val LIVE_TV = "live_tv"
+ const val LIVE_TV_DESTINATION = "live_tv?categoryId={categoryId}"
const val MOVIES = "movies"
const val SERIES = "series"
const val FAVORITES = "favorites"
const val EPG = "epg"
+ const val EPG_DESTINATION = "epg?categoryId={categoryId}&anchorTime={anchorTime}&favoritesOnly={favoritesOnly}"
const val SETTINGS = "settings"
- const val PLAYER = "player/{streamUrl}?title={title}&channelId={channelId}&internalId={internalId}&categoryId={categoryId}&providerId={providerId}&isVirtual={isVirtual}&contentType={contentType}"
+ const val PLAYER = "player/{streamUrl}?title={title}&channelId={channelId}&internalId={internalId}&categoryId={categoryId}&providerId={providerId}&isVirtual={isVirtual}&contentType={contentType}&archiveStartMs={archiveStartMs}&archiveEndMs={archiveEndMs}&archiveTitle={archiveTitle}&returnRoute={returnRoute}"
const val SEARCH = "search"
const val SERIES_DETAIL = "series_detail/{seriesId}"
const val WELCOME = "welcome"
@@ -35,6 +43,55 @@ object Routes {
fun providerSetup(providerId: Long? = null) = "provider_setup?providerId=${providerId ?: -1L}"
+ fun liveTv(categoryId: Long? = null) = if (categoryId == null) LIVE_TV else "$LIVE_TV?categoryId=$categoryId"
+ fun epg(categoryId: Long? = null, anchorTime: Long? = null, favoritesOnly: Boolean? = null): String {
+ val resolvedCategoryId = categoryId ?: -1L
+ val resolvedAnchorTime = anchorTime ?: -1L
+ val resolvedFavoritesOnly = favoritesOnly ?: false
+ return "$EPG?categoryId=$resolvedCategoryId&anchorTime=$resolvedAnchorTime&favoritesOnly=$resolvedFavoritesOnly"
+ }
+
+ fun livePlayer(
+ channel: Channel,
+ categoryId: Long? = channel.categoryId,
+ providerId: Long? = channel.providerId,
+ isVirtual: Boolean = false,
+ returnRoute: String? = null
+ ): String {
+ val effectiveCategoryId = categoryId ?: ChannelRepository.ALL_CHANNELS_ID
+ return player(
+ streamUrl = channel.streamUrl,
+ title = channel.name,
+ channelId = channel.epgChannelId,
+ internalId = channel.id,
+ categoryId = effectiveCategoryId,
+ providerId = providerId,
+ isVirtual = isVirtual,
+ contentType = "LIVE",
+ returnRoute = returnRoute
+ )
+ }
+
+ fun moviePlayer(movie: Movie): String {
+ return player(
+ streamUrl = movie.streamUrl,
+ title = movie.name,
+ internalId = movie.id,
+ categoryId = movie.categoryId,
+ providerId = movie.providerId,
+ contentType = "MOVIE"
+ )
+ }
+
+ fun episodePlayer(episode: Episode): String {
+ return player(
+ streamUrl = episode.streamUrl,
+ title = "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}",
+ internalId = episode.id,
+ providerId = episode.providerId,
+ contentType = "SERIES_EPISODE"
+ )
+ }
fun player(
streamUrl: String,
@@ -44,11 +101,17 @@ object Routes {
categoryId: Long? = null,
providerId: Long? = null,
isVirtual: Boolean = false,
- contentType: String = "LIVE"
+ contentType: String = "LIVE",
+ archiveStartMs: Long? = null,
+ archiveEndMs: Long? = null,
+ archiveTitle: String? = null,
+ returnRoute: String? = null
): String {
val encodedUrl = java.net.URLEncoder.encode(streamUrl, "UTF-8")
val encodedTitle = java.net.URLEncoder.encode(title, "UTF-8")
- return "player/$encodedUrl?title=$encodedTitle&channelId=${channelId ?: ""}&internalId=$internalId&categoryId=${categoryId ?: -1L}&providerId=${providerId ?: -1L}&isVirtual=$isVirtual&contentType=$contentType"
+ val encodedArchiveTitle = java.net.URLEncoder.encode(archiveTitle ?: "", "UTF-8")
+ val encodedReturnRoute = java.net.URLEncoder.encode(returnRoute ?: "", "UTF-8")
+ return "player/$encodedUrl?title=$encodedTitle&channelId=${channelId ?: ""}&internalId=$internalId&categoryId=${categoryId ?: -1L}&providerId=${providerId ?: -1L}&isVirtual=$isVirtual&contentType=$contentType&archiveStartMs=${archiveStartMs ?: -1L}&archiveEndMs=${archiveEndMs ?: -1L}&archiveTitle=$encodedArchiveTitle&returnRoute=$encodedReturnRoute"
}
fun seriesDetail(seriesId: Long) = "series_detail/$seriesId"
@@ -98,18 +161,87 @@ fun AppNavigation() {
// ...
composable(Routes.HOME) {
+ DashboardScreen(
+ onNavigate = { route ->
+ navController.navigate(route) {
+ popUpTo(Routes.HOME) { saveState = true }
+ launchSingleTop = true
+ restoreState = true
+ }
+ },
+ onAddProvider = {
+ navController.navigate(Routes.providerSetup(null))
+ },
+ onChannelClick = { channel ->
+ navController.navigate(
+ Routes.livePlayer(
+ channel = channel,
+ categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,
+ providerId = channel.providerId,
+ isVirtual = false
+ )
+ )
+ },
+ onMovieClick = { movie ->
+ navController.navigate(Routes.moviePlayer(movie))
+ },
+ onSeriesClick = { series ->
+ navController.navigate(Routes.seriesDetail(series.id))
+ },
+ onPlaybackHistoryClick = { history ->
+ val route = when (history.contentType) {
+ com.streamvault.domain.model.ContentType.LIVE -> {
+ Routes.player(
+ streamUrl = history.streamUrl,
+ title = history.title,
+ internalId = history.contentId,
+ providerId = history.providerId,
+ contentType = history.contentType.name
+ )
+ }
+ com.streamvault.domain.model.ContentType.MOVIE -> {
+ Routes.player(
+ streamUrl = history.streamUrl,
+ title = history.title,
+ internalId = history.contentId,
+ providerId = history.providerId,
+ contentType = history.contentType.name
+ )
+ }
+ com.streamvault.domain.model.ContentType.SERIES -> {
+ Routes.seriesDetail(history.seriesId ?: history.contentId)
+ }
+ com.streamvault.domain.model.ContentType.SERIES_EPISODE -> {
+ Routes.player(
+ streamUrl = history.streamUrl,
+ title = history.title,
+ internalId = history.contentId,
+ providerId = history.providerId,
+ contentType = history.contentType.name
+ )
+ }
+ }
+ navController.navigate(route)
+ },
+ currentRoute = Routes.HOME
+ )
+ }
+
+ composable(
+ route = Routes.LIVE_TV_DESTINATION,
+ arguments = listOf(
+ navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L }
+ )
+ ) { backStackEntry ->
+ val initialCategoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }
HomeScreen(
onChannelClick = { channel, category, provider ->
navController.navigate(
- Routes.player(
- streamUrl = channel.streamUrl,
- title = channel.name,
- channelId = channel.epgChannelId,
- internalId = channel.id,
+ Routes.livePlayer(
+ channel = channel,
categoryId = category?.id,
providerId = provider?.id,
- isVirtual = category?.isVirtual == true,
- contentType = "LIVE"
+ isVirtual = category?.isVirtual == true
)
)
},
@@ -120,7 +252,8 @@ fun AppNavigation() {
restoreState = true
}
},
- currentRoute = Routes.HOME
+ currentRoute = Routes.LIVE_TV,
+ initialCategoryId = initialCategoryId
)
}
// ... (rest of file)
@@ -128,14 +261,7 @@ fun AppNavigation() {
composable(Routes.MOVIES) {
MoviesScreen(
onMovieClick = { movie ->
- navController.navigate(Routes.player(
- streamUrl = movie.streamUrl,
- title = movie.name,
- internalId = movie.id,
- categoryId = movie.categoryId,
- providerId = movie.providerId,
- contentType = "MOVIE"
- ))
+ navController.navigate(Routes.moviePlayer(movie))
},
onNavigate = { route ->
navController.navigate(route) {
@@ -167,17 +293,70 @@ fun AppNavigation() {
composable(Routes.FAVORITES) {
FavoritesScreen(
onItemClick = { item ->
- navController.navigate(
- Routes.player(
- streamUrl = item.streamUrl,
- title = item.title,
- internalId = item.favorite.contentId,
- categoryId = -999L, // Global favorites virtual category
- providerId = -1L,
- isVirtual = true,
- contentType = item.favorite.contentType.name
- )
- )
+ val route = when (item.favorite.contentType) {
+ com.streamvault.domain.model.ContentType.LIVE -> {
+ Routes.player(
+ streamUrl = item.streamUrl,
+ title = item.title,
+ channelId = item.epgChannelId,
+ internalId = item.favorite.contentId,
+ categoryId = item.launchCategoryId,
+ providerId = item.providerId,
+ isVirtual = item.launchIsVirtual,
+ contentType = item.favorite.contentType.name
+ )
+ }
+ com.streamvault.domain.model.ContentType.MOVIE -> {
+ Routes.player(
+ streamUrl = item.streamUrl,
+ title = item.title,
+ internalId = item.favorite.contentId,
+ categoryId = item.categoryId,
+ providerId = item.providerId,
+ contentType = item.favorite.contentType.name
+ )
+ }
+ else -> Routes.seriesDetail(item.favorite.contentId)
+ }
+ navController.navigate(route)
+ },
+ onHistoryClick = { item ->
+ val route = when (item.history.contentType) {
+ com.streamvault.domain.model.ContentType.LIVE -> {
+ Routes.player(
+ streamUrl = item.history.streamUrl,
+ title = item.title,
+ channelId = item.epgChannelId,
+ internalId = item.history.contentId,
+ categoryId = item.categoryId,
+ providerId = item.providerId,
+ isVirtual = item.launchIsVirtual,
+ contentType = item.history.contentType.name
+ )
+ }
+ com.streamvault.domain.model.ContentType.MOVIE -> {
+ Routes.player(
+ streamUrl = item.history.streamUrl,
+ title = item.title,
+ internalId = item.history.contentId,
+ providerId = item.providerId,
+ contentType = item.history.contentType.name
+ )
+ }
+ com.streamvault.domain.model.ContentType.SERIES -> {
+ Routes.seriesDetail(item.history.seriesId ?: item.history.contentId)
+ }
+ com.streamvault.domain.model.ContentType.SERIES_EPISODE -> {
+ Routes.player(
+ streamUrl = item.history.streamUrl,
+ title = item.title,
+ internalId = item.history.contentId,
+ providerId = item.providerId,
+ contentType = item.history.contentType.name
+ )
+ }
+ }
+ navController.navigate(route)
},
onNavigate = { route ->
navController.navigate(route) {
@@ -190,9 +369,51 @@ fun AppNavigation() {
)
}
- composable(Routes.EPG) {
+ composable(
+ route = Routes.EPG_DESTINATION,
+ arguments = listOf(
+ navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L },
+ navArgument("anchorTime") { type = NavType.LongType; defaultValue = -1L },
+ navArgument("favoritesOnly") { type = NavType.BoolType; defaultValue = false }
+ )
+ ) { backStackEntry ->
+ val epgCategoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }
+ val epgAnchorTime = backStackEntry.arguments?.getLong("anchorTime")?.takeIf { it != -1L }
+ val epgFavoritesOnly = backStackEntry.arguments?.getBoolean("favoritesOnly") ?: false
com.streamvault.app.ui.screens.epg.FullEpgScreen(
currentRoute = Routes.EPG,
+ initialCategoryId = epgCategoryId,
+ initialAnchorTime = epgAnchorTime,
+ initialFavoritesOnly = epgFavoritesOnly,
+ onPlayChannel = { channel, returnRoute ->
+ navController.navigate(
+ Routes.livePlayer(
+ channel = channel,
+ categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,
+ providerId = channel.providerId,
+ isVirtual = false,
+ returnRoute = returnRoute
+ )
+ )
+ },
+ onPlayArchive = { channel, program, returnRoute ->
+ navController.navigate(
+ Routes.player(
+ streamUrl = channel.streamUrl,
+ title = channel.name,
+ channelId = channel.epgChannelId,
+ internalId = channel.id,
+ categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,
+ providerId = channel.providerId,
+ isVirtual = false,
+ contentType = "LIVE",
+ archiveStartMs = program.startTime,
+ archiveEndMs = program.endTime,
+ archiveTitle = "${channel.name}: ${program.title}",
+ returnRoute = returnRoute
+ )
+ )
+ },
onNavigate = { route ->
navController.navigate(route) {
popUpTo(Routes.HOME) { saveState = true }
@@ -249,10 +470,17 @@ fun AppNavigation() {
composable(Routes.SEARCH) {
com.streamvault.app.ui.screens.search.SearchScreen(
onChannelClick = { channel ->
- navController.navigate(Routes.player(channel.streamUrl, channel.name, channel.epgChannelId))
+ navController.navigate(
+ Routes.livePlayer(
+ channel = channel,
+ categoryId = channel.categoryId ?: ChannelRepository.ALL_CHANNELS_ID,
+ providerId = channel.providerId,
+ isVirtual = false
+ )
+ )
},
onMovieClick = { movie ->
- navController.navigate(Routes.player(movie.streamUrl, movie.name))
+ navController.navigate(Routes.moviePlayer(movie))
},
onSeriesClick = { series ->
navController.navigate(Routes.seriesDetail(series.id))
@@ -270,7 +498,11 @@ fun AppNavigation() {
navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L },
navArgument("providerId") { type = NavType.LongType; defaultValue = -1L },
navArgument("isVirtual") { type = NavType.BoolType; defaultValue = false },
- navArgument("contentType") { type = NavType.StringType; defaultValue = "LIVE" }
+ navArgument("contentType") { type = NavType.StringType; defaultValue = "LIVE" },
+ navArgument("archiveStartMs") { type = NavType.LongType; defaultValue = -1L },
+ navArgument("archiveEndMs") { type = NavType.LongType; defaultValue = -1L },
+ navArgument("archiveTitle") { type = NavType.StringType; defaultValue = "" },
+ navArgument("returnRoute") { type = NavType.StringType; defaultValue = "" }
)
) { backStackEntry ->
val streamUrl = backStackEntry.arguments?.getString("streamUrl") ?: ""
@@ -281,6 +513,10 @@ fun AppNavigation() {
val providerId = backStackEntry.arguments?.getLong("providerId")?.takeIf { it != -1L }
val isVirtual = backStackEntry.arguments?.getBoolean("isVirtual") ?: false
val contentType = backStackEntry.arguments?.getString("contentType") ?: "LIVE"
+ val archiveStartMs = backStackEntry.arguments?.getLong("archiveStartMs")?.takeIf { it != -1L }
+ val archiveEndMs = backStackEntry.arguments?.getLong("archiveEndMs")?.takeIf { it != -1L }
+ val archiveTitle = backStackEntry.arguments?.getString("archiveTitle")?.takeIf { it.isNotBlank() }
+ val returnRoute = backStackEntry.arguments?.getString("returnRoute")?.takeIf { it.isNotBlank() }
PlayerScreen(
streamUrl = streamUrl,
@@ -291,6 +527,10 @@ fun AppNavigation() {
providerId = providerId,
isVirtual = isVirtual,
contentType = contentType,
+ archiveStartMs = archiveStartMs,
+ archiveEndMs = archiveEndMs,
+ archiveTitle = archiveTitle,
+ returnRoute = returnRoute,
onBack = { navController.popBackStack() },
onNavigate = { route -> navController.navigate(route) }
)
@@ -304,14 +544,7 @@ fun AppNavigation() {
) {
com.streamvault.app.ui.screens.series.SeriesDetailScreen(
onEpisodeClick = { episode ->
- // Navigate to player
- navController.navigate(Routes.player(
- streamUrl = episode.streamUrl,
- title = "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}",
- internalId = episode.id,
- providerId = episode.providerId,
- contentType = "SERIES_EPISODE"
- ))
+ navController.navigate(Routes.episodePlayer(episode))
},
onBack = { navController.popBackStack() }
)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
index fc1b215a..3f7b1187 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/CategoryRow.kt
@@ -7,9 +7,13 @@ import androidx.compose.runtime.Composable
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
+import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.Surface
import androidx.tv.material3.Text
import com.streamvault.app.ui.theme.LocalSpacing
+import com.streamvault.app.ui.theme.Primary
import com.streamvault.app.ui.theme.TextPrimary
import com.streamvault.app.ui.theme.TextTertiary
import androidx.compose.ui.res.stringResource
@@ -40,11 +44,21 @@ fun <T> CategoryRow(
color = TextPrimary
)
if (onSeeAll != null) {
- Text(
- text = stringResource(R.string.category_see_all),
- style = MaterialTheme.typography.labelLarge,
- color = TextTertiary
- )
+ Surface(
+ onClick = onSeeAll,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Primary.copy(alpha = 0.12f),
+ focusedContainerColor = Primary.copy(alpha = 0.22f),
+ contentColor = TextTertiary
+ )
+ ) {
+ Text(
+ text = stringResource(R.string.category_see_all),
+ style = MaterialTheme.typography.labelLarge,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)
+ )
+ }
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt
new file mode 100644
index 00000000..2ff8e448
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryContextCard.kt
@@ -0,0 +1,97 @@
+package com.streamvault.app.ui.components
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.res.stringResource
+import androidx.tv.material3.Button
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.SurfaceDefaults
+import androidx.tv.material3.Text
+import com.streamvault.app.R
+import com.streamvault.app.ui.theme.OnSurface
+import com.streamvault.app.ui.theme.OnSurfaceDim
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+
+@Composable
+fun SavedCategoryContextCard(
+ categoryName: String,
+ itemCount: Int,
+ onManageClick: () -> Unit,
+ onBrowseAllClick: () -> Unit,
+ modifier: Modifier = Modifier
+) {
+ Surface(
+ modifier = modifier.fillMaxWidth(),
+ shape = RoundedCornerShape(18.dp),
+ colors = SurfaceDefaults.colors(
+ containerColor = SurfaceElevated
+ )
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 20.dp, vertical = 18.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.library_saved_active_title),
+ style = MaterialTheme.typography.labelLarge,
+ color = Primary
+ )
+ Text(
+ text = categoryName,
+ style = MaterialTheme.typography.titleLarge,
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = stringResource(R.string.library_saved_active_summary, itemCount),
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim,
+ maxLines = 1
+ )
+ }
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Button(
+ onClick = onManageClick,
+ colors = ButtonDefaults.colors(
+ containerColor = Primary.copy(alpha = 0.92f)
+ )
+ ) {
+ Text(stringResource(R.string.library_saved_manage_action))
+ }
+ Button(
+ onClick = onBrowseAllClick,
+ colors = ButtonDefaults.colors(
+ containerColor = SurfaceElevated,
+ contentColor = OnSurface
+ )
+ ) {
+ Text(stringResource(R.string.library_browse_all))
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt
new file mode 100644
index 00000000..c46bd7be
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/SavedCategoryShortcutsRow.kt
@@ -0,0 +1,176 @@
+package com.streamvault.app.ui.components
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.res.stringResource
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.Text
+import com.streamvault.app.R
+import com.streamvault.app.ui.theme.OnSurface
+import com.streamvault.app.ui.theme.OnSurfaceDim
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+
+data class SavedCategoryShortcut(
+ val name: String,
+ val count: Int
+)
+
+@Composable
+fun SavedCategoryShortcutsRow(
+ title: String,
+ subtitle: String,
+ emptyHint: String,
+ shortcuts: List<SavedCategoryShortcut>,
+ managementHint: String? = null,
+ primaryShortcutLabel: String? = null,
+ isPrimaryShortcutSelected: Boolean = false,
+ onPrimaryShortcutClick: (() -> Unit)? = null,
+ selectedShortcutName: String? = null,
+ onShortcutLongClick: ((String) -> Unit)? = null,
+ onShortcutClick: (String) -> Unit,
+ modifier: Modifier = Modifier
+) {
+ Column(modifier = modifier.fillMaxWidth()) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(start = 48.dp, end = 48.dp, top = 16.dp, bottom = 8.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(2.dp)) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleMedium,
+ color = OnSurface
+ )
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ if (!managementHint.isNullOrBlank()) {
+ Text(
+ text = managementHint,
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary.copy(alpha = 0.85f)
+ )
+ }
+ }
+ }
+
+ if (shortcuts.isEmpty()) {
+ Surface(
+ enabled = false,
+ onClick = { },
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 48.dp),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceElevated
+ )
+ ) {
+ Text(
+ text = emptyHint,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 18.dp)
+ )
+ }
+ return
+ }
+
+ LazyRow(
+ contentPadding = PaddingValues(horizontal = 48.dp),
+ horizontalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ if (primaryShortcutLabel != null && onPrimaryShortcutClick != null) {
+ item(key = "primary_shortcut") {
+ Surface(
+ onClick = onPrimaryShortcutClick,
+ modifier = Modifier.width(220.dp),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (isPrimaryShortcutSelected) {
+ Primary.copy(alpha = 0.18f)
+ } else {
+ SurfaceElevated
+ },
+ focusedContainerColor = Primary.copy(alpha = 0.22f)
+ )
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = primaryShortcutLabel,
+ style = MaterialTheme.typography.titleSmall,
+ color = if (isPrimaryShortcutSelected) Primary else OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = stringResource(R.string.library_saved_primary_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ maxLines = 1
+ )
+ }
+ }
+ }
+ }
+ items(items = shortcuts, key = { it.name }) { shortcut ->
+ val isSelected = shortcut.name == selectedShortcutName
+ Surface(
+ onClick = { onShortcutClick(shortcut.name) },
+ onLongClick = onShortcutLongClick?.let { handler ->
+ { handler(shortcut.name) }
+ },
+ modifier = Modifier.width(220.dp),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
+ focusedContainerColor = Primary.copy(alpha = 0.22f)
+ )
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = shortcut.name,
+ style = MaterialTheme.typography.titleSmall,
+ color = if (isSelected) Primary else OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = stringResource(R.string.library_saved_items_count, shortcut.count),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ maxLines = 1
+ )
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
new file mode 100644
index 00000000..d939e66d
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/SelectionChipRow.kt
@@ -0,0 +1,107 @@
+package com.streamvault.app.ui.components
+
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import androidx.tv.material3.Border
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.Text
+import com.streamvault.app.ui.theme.FocusBorder
+import com.streamvault.app.ui.theme.OnSurface
+import com.streamvault.app.ui.theme.OnSurfaceDim
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.theme.SurfaceHighlight
+
+data class SelectionChip(
+ val key: String,
+ val label: String,
+ val supportingText: String? = null
+)
+
+@Composable
+fun SelectionChipRow(
+ title: String,
+ chips: List<SelectionChip>,
+ selectedKey: String?,
+ onChipSelected: (String) -> Unit,
+ modifier: Modifier = Modifier,
+ subtitle: String? = null,
+ contentPadding: PaddingValues = PaddingValues(horizontal = 24.dp)
+) {
+ if (chips.isEmpty()) return
+
+ Column(
+ modifier = modifier
+ .fillMaxWidth()
+ .padding(vertical = 6.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 24.dp)
+ )
+ if (!subtitle.isNullOrBlank()) {
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 24.dp, vertical = 2.dp)
+ )
+ }
+ LazyRow(
+ contentPadding = contentPadding,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ items(chips, key = { it.key }) { chip ->
+ val isSelected = chip.key == selectedKey
+ Surface(
+ onClick = { onChipSelected(chip.key) },
+ modifier = Modifier,
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
+ focusedContainerColor = SurfaceHighlight,
+ contentColor = if (isSelected) Primary else OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(999.dp)
+ )
+ )
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ Text(
+ text = chip.label,
+ style = MaterialTheme.typography.labelLarge
+ )
+ if (!chip.supportingText.isNullOrBlank()) {
+ Text(
+ text = chip.supportingText,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt b/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt
index ec50fe37..cc83391c 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt
@@ -52,12 +52,18 @@ fun TopNavBar(
modifier: Modifier = Modifier
) {
val tabs = listOf(
- NavTab(stringResource(id = R.string.nav_live_tv), Routes.HOME),
+ NavTab(stringResource(id = R.string.nav_home), Routes.HOME),
+ NavTab(stringResource(id = R.string.nav_live_tv), Routes.LIVE_TV),
NavTab(stringResource(id = R.string.nav_movies), Routes.MOVIES),
NavTab(stringResource(id = R.string.nav_series), Routes.SERIES),
NavTab(stringResource(id = R.string.nav_epg), Routes.EPG),
NavTab(stringResource(id = R.string.nav_settings), Routes.SETTINGS)
)
+ val subtitle = when (currentRoute) {
+ Routes.FAVORITES -> stringResource(id = R.string.favorites_title)
+ Routes.SEARCH -> stringResource(id = R.string.search_title)
+ else -> tabs.firstOrNull { it.route == currentRoute }?.label ?: stringResource(id = R.string.app_name)
+ }
val focusRequesters = remember { mutableMapOf<String, FocusRequester>() }
@@ -82,7 +88,7 @@ fun TopNavBar(
color = TextPrimary
)
Text(
- text = stringResource(id = R.string.nav_live_tv),
+ text = subtitle,
style = MaterialTheme.typography.labelSmall,
color = TextTertiary
)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/TvEmptyState.kt b/app/src/main/java/com/streamvault/app/ui/components/TvEmptyState.kt
new file mode 100644
index 00000000..e0d071d3
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/TvEmptyState.kt
@@ -0,0 +1,57 @@
+package com.streamvault.app.ui.components
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Text
+import com.streamvault.app.ui.theme.OnSurface
+import com.streamvault.app.ui.theme.OnSurfaceDim
+
+@Composable
+fun TvEmptyState(
+ title: String,
+ subtitle: String,
+ modifier: Modifier = Modifier
+) {
+ Box(
+ modifier = modifier.fillMaxSize(),
+ contentAlignment = Alignment.Center
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth(0.62f)
+ .background(Color.White.copy(alpha = 0.04f), RoundedCornerShape(20.dp))
+ ) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ modifier = Modifier.padding(horizontal = 28.dp, vertical = 24.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleLarge,
+ color = OnSurface,
+ textAlign = TextAlign.Center
+ )
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim,
+ textAlign = TextAlign.Center
+ )
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt
index a6dc4495..43c4cf7a 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/AddToGroupDialog.kt
@@ -18,6 +18,7 @@ import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
+import androidx.compose.ui.window.DialogProperties
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Category
import androidx.compose.ui.res.stringResource
@@ -25,9 +26,6 @@ import com.streamvault.app.R
import androidx.compose.ui.input.key.*
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.foundation.shape.CircleShape
-import androidx.compose.foundation.text.KeyboardActions
-import androidx.compose.foundation.text.KeyboardOptions
-import androidx.compose.ui.text.input.ImeAction
import kotlinx.coroutines.delay
import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialog
import com.streamvault.app.ui.screens.multiview.MultiViewViewModel
@@ -48,7 +46,6 @@ fun AddToGroupDialog(
onNavigateToSplitScreen: (() -> Unit)? = null // navigate to MultiViewScreen when launched
) {
var showCreateGroup by remember { mutableStateOf(false) }
- var newGroupName by remember { mutableStateOf("") }
val focusRequester = remember { FocusRequester() }
// Ghost-click debounce
@@ -81,70 +78,48 @@ fun AddToGroupDialog(
)
}
- Dialog(onDismissRequest = safeDismiss) {
- Surface(
- shape = RoundedCornerShape(16.dp),
- color = MaterialTheme.colorScheme.surface,
- modifier = Modifier
- .width(400.dp)
- .padding(16.dp)
- ) {
- Column(modifier = Modifier.padding(24.dp)) {
- // Header
- Row(
- modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp),
- horizontalArrangement = Arrangement.SpaceBetween,
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = stringResource(R.string.add_group_manage_title, contentTitle),
- style = MaterialTheme.typography.titleLarge,
- modifier = Modifier.weight(1f)
- )
- IconButton(
- onClick = safeDismiss,
- modifier = Modifier.focusRequester(focusRequester)
- ) {
- Icon(Icons.Default.Close, contentDescription = stringResource(R.string.add_group_close_cd))
- }
- }
+ if (showCreateGroup) {
+ CreateGroupDialog(
+ onDismissRequest = { showCreateGroup = false },
+ onConfirm = { name ->
+ onCreateGroup(name)
+ showCreateGroup = false
+ }
+ )
+ }
- if (showCreateGroup) {
- OutlinedTextField(
- value = newGroupName,
- onValueChange = { newGroupName = it },
- label = { Text(stringResource(R.string.add_group_name_hint)) },
- modifier = Modifier.fillMaxWidth(),
- singleLine = true,
- keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
- keyboardActions = KeyboardActions(
- onDone = {
- if (newGroupName.isNotBlank()) {
- onCreateGroup(newGroupName)
- showCreateGroup = false
- newGroupName = ""
- }
- }
- )
- )
+ if (!showCreateGroup && !showSlotPicker) {
+ Dialog(
+ onDismissRequest = safeDismiss,
+ properties = DialogProperties(usePlatformDefaultWidth = false)
+ ) {
+ Surface(
+ shape = RoundedCornerShape(16.dp),
+ color = MaterialTheme.colorScheme.surface,
+ modifier = Modifier
+ .width(400.dp)
+ .padding(16.dp)
+ ) {
+ Column(modifier = Modifier.padding(24.dp)) {
+ // Header
Row(
- modifier = Modifier.fillMaxWidth().padding(top = 16.dp),
- horizontalArrangement = Arrangement.End
+ modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
) {
- TextButton(onClick = { showCreateGroup = false }) {
- Text(stringResource(R.string.add_group_cancel))
- }
- Button(onClick = {
- if (newGroupName.isNotBlank()) {
- onCreateGroup(newGroupName)
- showCreateGroup = false
- newGroupName = ""
- }
- }) {
- Text(stringResource(R.string.add_group_create))
+ Text(
+ text = stringResource(R.string.add_group_manage_title, contentTitle),
+ style = MaterialTheme.typography.titleLarge,
+ modifier = Modifier.weight(1f)
+ )
+ IconButton(
+ onClick = safeDismiss,
+ modifier = Modifier.focusRequester(focusRequester)
+ ) {
+ Icon(Icons.Default.Close, contentDescription = stringResource(R.string.add_group_close_cd))
}
}
- } else {
+
LazyColumn(
modifier = Modifier.weight(1f, fill = false),
verticalArrangement = Arrangement.spacedBy(8.dp)
@@ -259,18 +234,18 @@ fun AddToGroupDialog(
}
}
- item {
- Spacer(modifier = Modifier.height(8.dp))
- OutlinedButton(
- onClick = { showCreateGroup = true },
- modifier = Modifier.fillMaxWidth()
- ) {
- Icon(Icons.Default.Add, contentDescription = null)
- Spacer(modifier = Modifier.width(8.dp))
- Text(stringResource(R.string.add_group_create_new_btn))
- }
+ item {
+ Spacer(modifier = Modifier.height(8.dp))
+ OutlinedButton(
+ onClick = { showCreateGroup = true },
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Icon(Icons.Default.Add, contentDescription = null)
+ Spacer(modifier = Modifier.width(8.dp))
+ Text(stringResource(R.string.add_group_create_new_btn))
}
}
+ }
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt
index 20c81250..f1a4e52d 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CategoryOptionsDialog.kt
@@ -1,31 +1,33 @@
package com.streamvault.app.ui.components.dialogs
-import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.TextButton
-import androidx.tv.material3.Text
-import androidx.tv.material3.MaterialTheme
import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
+import com.streamvault.app.R
import com.streamvault.domain.model.Category
-
-
-import androidx.compose.runtime.*
import kotlinx.coroutines.delay
-import androidx.compose.ui.res.stringResource
-import com.streamvault.app.R
@Composable
fun CategoryOptionsDialog(
category: Category,
onDismissRequest: () -> Unit,
onSetAsDefault: (() -> Unit)? = null,
+ onRename: (() -> Unit)? = null,
onToggleLock: (() -> Unit)? = null,
onDelete: (() -> Unit)? = null,
onReorderChannels: (() -> Unit)? = null
) {
- // Fix for ghost clicks: Debounce interaction for 500ms to ignore long-press release
var canInteract by remember { mutableStateOf(false) }
LaunchedEffect(Unit) {
delay(500)
@@ -38,21 +40,32 @@ fun CategoryOptionsDialog(
AlertDialog(
onDismissRequest = safeDismiss,
- title = { Text(text = category.name, style = MaterialTheme.typography.titleLarge) },
+ title = {
+ androidx.tv.material3.Text(
+ text = category.name,
+ style = androidx.tv.material3.MaterialTheme.typography.titleLarge
+ )
+ },
text = {
Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
-
- // Option 1: Set as Default
if (onSetAsDefault != null) {
androidx.tv.material3.Button(
onClick = { if (canInteract) onSetAsDefault() },
modifier = Modifier.fillMaxWidth()
) {
- Text(stringResource(R.string.category_options_set_default))
+ androidx.tv.material3.Text(stringResource(R.string.category_options_set_default))
+ }
+ }
+
+ if (onRename != null) {
+ androidx.tv.material3.Button(
+ onClick = { if (canInteract) onRename() },
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ androidx.tv.material3.Text(stringResource(R.string.category_options_rename))
}
}
- // Option 2: Reorder Channels (only for virtual/custom categories)
if (onReorderChannels != null) {
androidx.tv.material3.Button(
onClick = {
@@ -63,32 +76,34 @@ fun CategoryOptionsDialog(
},
modifier = Modifier.fillMaxWidth()
) {
- Text("↕ Reorder Channels")
+ androidx.tv.material3.Text(stringResource(R.string.category_options_reorder))
}
}
- // Option 3: Lock/Unlock
if (onToggleLock != null) {
- val lockText = if (category.isUserProtected) stringResource(R.string.category_options_unlock) else stringResource(R.string.category_options_lock)
+ val lockText = if (category.isUserProtected) {
+ stringResource(R.string.category_options_unlock)
+ } else {
+ stringResource(R.string.category_options_lock)
+ }
androidx.tv.material3.Button(
onClick = { if (canInteract) onToggleLock() },
modifier = Modifier.fillMaxWidth()
) {
- Text(lockText)
+ androidx.tv.material3.Text(lockText)
}
}
- // Option 4: Delete (Optional)
if (onDelete != null) {
androidx.tv.material3.Button(
onClick = { if (canInteract) onDelete() },
modifier = Modifier.fillMaxWidth(),
colors = androidx.tv.material3.ButtonDefaults.colors(
- containerColor = MaterialTheme.colorScheme.errorContainer,
- contentColor = MaterialTheme.colorScheme.onErrorContainer
+ containerColor = androidx.tv.material3.MaterialTheme.colorScheme.errorContainer,
+ contentColor = androidx.tv.material3.MaterialTheme.colorScheme.onErrorContainer
)
) {
- Text(stringResource(R.string.category_options_delete))
+ androidx.tv.material3.Text(stringResource(R.string.category_options_delete))
}
}
}
@@ -96,7 +111,7 @@ fun CategoryOptionsDialog(
confirmButton = {},
dismissButton = {
TextButton(onClick = safeDismiss) {
- Text(stringResource(R.string.category_options_cancel))
+ androidx.tv.material3.Text(stringResource(R.string.category_options_cancel))
}
}
)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt
new file mode 100644
index 00000000..0cef79a9
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/CreateGroupDialog.kt
@@ -0,0 +1,94 @@
+package com.streamvault.app.ui.components.dialogs
+
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.text.KeyboardActions
+import androidx.compose.foundation.text.KeyboardOptions
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.platform.LocalSoftwareKeyboardController
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.input.ImeAction
+import androidx.compose.ui.window.DialogProperties
+import com.streamvault.app.R
+
+@Composable
+fun CreateGroupDialog(
+ onDismissRequest: () -> Unit,
+ onConfirm: (String) -> Unit
+) {
+ var value by rememberSaveable { mutableStateOf("") }
+ val focusRequester = remember { FocusRequester() }
+ val keyboardController = LocalSoftwareKeyboardController.current
+
+ LaunchedEffect(Unit) {
+ runCatching { focusRequester.requestFocus() }
+ keyboardController?.show()
+ }
+
+ AlertDialog(
+ onDismissRequest = {
+ keyboardController?.hide()
+ onDismissRequest()
+ },
+ properties = DialogProperties(usePlatformDefaultWidth = false),
+ title = {
+ androidx.tv.material3.Text(stringResource(R.string.add_group_create_new_btn))
+ },
+ text = {
+ OutlinedTextField(
+ value = value,
+ onValueChange = { value = it },
+ modifier = Modifier
+ .fillMaxWidth()
+ .focusRequester(focusRequester),
+ singleLine = true,
+ label = {
+ androidx.tv.material3.Text(stringResource(R.string.add_group_name_hint))
+ },
+ keyboardOptions = KeyboardOptions(imeAction = ImeAction.Done),
+ keyboardActions = KeyboardActions(
+ onDone = {
+ val normalized = value.trim()
+ if (normalized.isNotEmpty()) {
+ keyboardController?.hide()
+ onConfirm(normalized)
+ }
+ }
+ )
+ )
+ },
+ confirmButton = {
+ TextButton(
+ onClick = {
+ val normalized = value.trim()
+ if (normalized.isNotEmpty()) {
+ keyboardController?.hide()
+ onConfirm(normalized)
+ }
+ },
+ enabled = value.trim().isNotEmpty()
+ ) {
+ androidx.tv.material3.Text(stringResource(R.string.add_group_create))
+ }
+ },
+ dismissButton = {
+ TextButton(onClick = {
+ keyboardController?.hide()
+ onDismissRequest()
+ }) {
+ androidx.tv.material3.Text(stringResource(R.string.add_group_cancel))
+ }
+ }
+ )
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
index b54a932d..1ac53456 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PinDialog.kt
@@ -15,6 +15,7 @@ import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.unit.dp
@@ -36,22 +37,28 @@ fun PinDialog(
) {
var pin by remember { mutableStateOf("") }
val focusRequester = remember { FocusRequester() }
+ val keyboardController = LocalSoftwareKeyboardController.current
LaunchedEffect(Unit) {
focusRequester.requestFocus()
+ keyboardController?.show()
}
// Auto-submit when length reaches 4
LaunchedEffect(pin) {
if (pin.length == 4) {
delay(300) // Small delay for visual feedback
+ keyboardController?.hide()
onPinEntered(pin)
pin = "" // Reset logic usually handled by parent state (error or dismiss)
}
}
Dialog(
- onDismissRequest = onDismissRequest,
+ onDismissRequest = {
+ keyboardController?.hide()
+ onDismissRequest()
+ },
properties = DialogProperties(usePlatformDefaultWidth = false)
) {
Box(
@@ -120,7 +127,10 @@ fun PinDialog(
)
// Cancel Button
- TextButton(onClick = onDismissRequest) {
+ TextButton(onClick = {
+ keyboardController?.hide()
+ onDismissRequest()
+ }) {
Text(stringResource(R.string.pin_dialog_cancel), color = Color.White.copy(alpha = 0.7f))
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt
new file mode 100644
index 00000000..f658cfa3
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/RenameGroupDialog.kt
@@ -0,0 +1,58 @@
+package com.streamvault.app.ui.components.dialogs
+
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.material3.AlertDialog
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import com.streamvault.app.R
+
+@Composable
+fun RenameGroupDialog(
+ initialName: String,
+ errorMessage: String?,
+ onDismissRequest: () -> Unit,
+ onConfirm: (String) -> Unit
+) {
+ var value by rememberSaveable(initialName) { mutableStateOf(initialName) }
+
+ AlertDialog(
+ onDismissRequest = onDismissRequest,
+ title = {
+ androidx.tv.material3.Text(stringResource(R.string.category_options_rename))
+ },
+ text = {
+ OutlinedTextField(
+ value = value,
+ onValueChange = { value = it },
+ modifier = Modifier.fillMaxWidth(),
+ singleLine = true,
+ label = {
+ androidx.tv.material3.Text(stringResource(R.string.add_group_name_hint))
+ },
+ supportingText = errorMessage?.let { message ->
+ {
+ androidx.tv.material3.Text(message)
+ }
+ }
+ )
+ },
+ confirmButton = {
+ TextButton(onClick = { onConfirm(value) }) {
+ androidx.tv.material3.Text(stringResource(R.string.add_group_rename))
+ }
+ },
+ dismissButton = {
+ TextButton(onClick = onDismissRequest) {
+ androidx.tv.material3.Text(stringResource(R.string.add_group_cancel))
+ }
+ }
+ )
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
new file mode 100644
index 00000000..bf77f431
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardScreen.kt
@@ -0,0 +1,780 @@
+package com.streamvault.app.ui.screens.dashboard
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.hilt.navigation.compose.hiltViewModel
+import androidx.tv.material3.Border
+import androidx.tv.material3.Button
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.SurfaceDefaults
+import androidx.tv.material3.Text
+import coil3.compose.AsyncImage
+import com.streamvault.app.R
+import com.streamvault.app.navigation.Routes
+import com.streamvault.app.ui.components.CategoryRow
+import com.streamvault.app.ui.components.ChannelCard
+import com.streamvault.app.ui.components.ContinueWatchingRow
+import com.streamvault.app.ui.components.MovieCard
+import com.streamvault.app.ui.components.SeriesCard
+import com.streamvault.app.ui.components.TopNavBar
+import com.streamvault.app.ui.theme.FocusBorder
+import com.streamvault.app.ui.theme.OnBackground
+import com.streamvault.app.ui.theme.OnSurfaceDim
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.theme.SurfaceHighlight
+import com.streamvault.app.ui.theme.TextPrimary
+import com.streamvault.app.ui.theme.TextTertiary
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.Series
+import androidx.compose.ui.res.stringResource
+import androidx.compose.foundation.BorderStroke
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
+
+@Composable
+fun DashboardScreen(
+ onNavigate: (String) -> Unit,
+ onAddProvider: () -> Unit,
+ onChannelClick: (Channel) -> Unit,
+ onMovieClick: (Movie) -> Unit,
+ onSeriesClick: (Series) -> Unit,
+ onPlaybackHistoryClick: (PlaybackHistory) -> Unit,
+ currentRoute: String,
+ viewModel: DashboardViewModel = hiltViewModel()
+) {
+ val uiState by viewModel.uiState.collectAsState()
+
+ Column(modifier = Modifier.fillMaxSize()) {
+ TopNavBar(
+ currentRoute = currentRoute,
+ onNavigate = onNavigate,
+ modifier = Modifier.fillMaxWidth()
+ )
+
+ val provider = uiState.provider
+ if (provider == null) {
+ EmptyDashboard(
+ onAddProvider = onAddProvider,
+ onOpenSettings = { onNavigate(Routes.SETTINGS) }
+ )
+ return@Column
+ }
+ val orderedSections = rememberDashboardSections(uiState)
+
+ androidx.compose.foundation.lazy.LazyColumn(
+ modifier = Modifier.fillMaxSize(),
+ contentPadding = PaddingValues(bottom = 40.dp)
+ ) {
+ item {
+ DashboardHero(
+ providerName = provider.name,
+ feature = uiState.feature,
+ stats = uiState.stats,
+ onOpenLiveTv = { onNavigate(Routes.LIVE_TV) },
+ onOpenGuide = { onNavigate(Routes.EPG) },
+ onOpenSearch = { onNavigate(Routes.SEARCH) },
+ onOpenSavedLibrary = { onNavigate(Routes.FAVORITES) },
+ onFeatureAction = {
+ when (uiState.feature.actionType) {
+ DashboardFeatureAction.LIVE -> onNavigate(Routes.LIVE_TV)
+ DashboardFeatureAction.CONTINUE_WATCHING -> uiState.continueWatching.firstOrNull()?.let(onPlaybackHistoryClick)
+ DashboardFeatureAction.MOVIES -> onNavigate(Routes.MOVIES)
+ DashboardFeatureAction.SERIES -> onNavigate(Routes.SERIES)
+ }
+ }
+ )
+ }
+
+ item {
+ DashboardProviderHealthCard(
+ providerName = provider.name,
+ health = uiState.providerHealth,
+ onOpenDiagnostics = { onNavigate(Routes.SETTINGS) }
+ )
+ }
+
+ if (uiState.providerWarnings.isNotEmpty()) {
+ item {
+ DashboardProviderWarningCard(
+ warnings = uiState.providerWarnings,
+ onOpenSettings = { onNavigate(Routes.SETTINGS) }
+ )
+ }
+ }
+
+ items(orderedSections, key = { it.name }) { section ->
+ when (section) {
+ DashboardHomeSection.LIVE_SHORTCUTS -> DashboardShortcutRow(
+ title = stringResource(R.string.dashboard_live_shortcuts),
+ subtitle = stringResource(R.string.dashboard_live_shortcuts_subtitle),
+ shortcuts = uiState.liveShortcuts,
+ onShortcutClick = { shortcut ->
+ shortcut.categoryId?.let { categoryId ->
+ onNavigate(Routes.liveTv(categoryId))
+ } ?: onNavigate(Routes.LIVE_TV)
+ }
+ )
+
+ DashboardHomeSection.FAVORITE_CHANNELS -> CategoryRow(
+ title = stringResource(R.string.dashboard_favorite_channels),
+ items = uiState.favoriteChannels,
+ onSeeAll = { onNavigate(Routes.liveTv(com.streamvault.domain.model.VirtualCategoryIds.FAVORITES)) }
+ ) { channel ->
+ ChannelCard(
+ channel = channel,
+ onClick = { onChannelClick(channel) }
+ )
+ }
+
+ DashboardHomeSection.RECENT_CHANNELS -> CategoryRow(
+ title = stringResource(R.string.dashboard_recent_channels),
+ items = uiState.recentChannels,
+ onSeeAll = { onNavigate(Routes.liveTv(com.streamvault.domain.model.VirtualCategoryIds.RECENT)) }
+ ) { channel ->
+ ChannelCard(
+ channel = channel,
+ onClick = { onChannelClick(channel) }
+ )
+ }
+
+ DashboardHomeSection.CONTINUE_WATCHING -> ContinueWatchingRow(
+ items = uiState.continueWatching,
+ onItemClick = onPlaybackHistoryClick
+ )
+
+ DashboardHomeSection.RECENT_MOVIES -> CategoryRow(
+ title = stringResource(R.string.dashboard_recent_movies),
+ items = uiState.recentMovies,
+ onSeeAll = { onNavigate(Routes.MOVIES) }
+ ) { movie ->
+ MovieCard(
+ movie = movie,
+ onClick = { onMovieClick(movie) }
+ )
+ }
+
+ DashboardHomeSection.RECENT_SERIES -> CategoryRow(
+ title = stringResource(R.string.dashboard_recent_series),
+ items = uiState.recentSeries,
+ onSeeAll = { onNavigate(Routes.SERIES) }
+ ) { series ->
+ SeriesCard(
+ series = series,
+ subtitle = series.releaseDate ?: stringResource(R.string.dashboard_updated_series_badge),
+ onClick = { onSeriesClick(series) }
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun DashboardHero(
+ providerName: String,
+ feature: DashboardFeature,
+ stats: DashboardStats,
+ onOpenLiveTv: () -> Unit,
+ onOpenGuide: () -> Unit,
+ onOpenSearch: () -> Unit,
+ onOpenSavedLibrary: () -> Unit,
+ onFeatureAction: () -> Unit
+) {
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 48.dp, vertical = 24.dp),
+ shape = RoundedCornerShape(28.dp),
+ colors = SurfaceDefaults.colors(
+ containerColor = SurfaceElevated
+ )
+ ) {
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(380.dp)
+ .background(
+ Brush.linearGradient(
+ colors = listOf(
+ Color(0xFF07111F),
+ Color(0xFF0B2240),
+ Color(0xFF111827)
+ )
+ )
+ )
+ ) {
+ if (!feature.artworkUrl.isNullOrBlank()) {
+ AsyncImage(
+ model = feature.artworkUrl,
+ contentDescription = null,
+ contentScale = ContentScale.Crop,
+ modifier = Modifier
+ .fillMaxSize()
+ .clip(RoundedCornerShape(28.dp))
+ )
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(
+ Brush.horizontalGradient(
+ colors = listOf(
+ Color.Black.copy(alpha = 0.84f),
+ Color.Black.copy(alpha = 0.68f),
+ Color.Black.copy(alpha = 0.28f)
+ )
+ )
+ )
+ )
+ }
+
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 32.dp, vertical = 28.dp),
+ verticalArrangement = Arrangement.SpaceBetween
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(
+ text = stringResource(R.string.dashboard_title),
+ style = MaterialTheme.typography.displaySmall,
+ color = TextPrimary
+ )
+ Text(
+ text = stringResource(R.string.dashboard_subtitle, providerName),
+ style = MaterialTheme.typography.titleMedium,
+ color = OnSurfaceDim
+ )
+ }
+
+ DashboardStatRow(stats = stats)
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(16.dp)) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(
+ text = feature.title,
+ style = MaterialTheme.typography.headlineLarge,
+ color = TextPrimary,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = feature.summary,
+ style = MaterialTheme.typography.titleMedium,
+ color = TextTertiary,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ DashboardActionButton(
+ label = stringResource(R.string.nav_live_tv),
+ onClick = onOpenLiveTv
+ )
+ DashboardActionButton(
+ label = stringResource(R.string.nav_epg),
+ onClick = onOpenGuide
+ )
+ DashboardActionButton(
+ label = stringResource(R.string.dashboard_search_library),
+ onClick = onOpenSearch
+ )
+ DashboardActionButton(
+ label = stringResource(R.string.favorites_title),
+ onClick = onOpenSavedLibrary
+ )
+ if (feature.actionLabel.isNotBlank()) {
+ DashboardActionButton(
+ label = feature.actionLabel,
+ onClick = onFeatureAction
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun DashboardStatRow(
+ stats: DashboardStats
+) {
+ val statItems = listOf(
+ stringResource(R.string.dashboard_stat_live, stats.liveChannelCount),
+ stringResource(R.string.dashboard_stat_favorites, stats.favoriteChannelCount),
+ stringResource(R.string.dashboard_stat_recent, stats.recentChannelCount),
+ stringResource(R.string.dashboard_stat_resume, stats.continueWatchingCount),
+ stringResource(R.string.dashboard_stat_movies, stats.movieLibraryCount),
+ stringResource(R.string.dashboard_stat_series, stats.seriesLibraryCount)
+ )
+
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ items(statItems) { statLabel ->
+ Surface(
+ shape = RoundedCornerShape(999.dp),
+ colors = SurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.08f)
+ )
+ ) {
+ Text(
+ text = statLabel,
+ style = MaterialTheme.typography.labelLarge,
+ color = TextPrimary,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun DashboardShortcutRow(
+ title: String,
+ subtitle: String,
+ shortcuts: List<DashboardLiveShortcut>,
+ onShortcutClick: (DashboardLiveShortcut) -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(top = 8.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 48.dp, vertical = 8.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleMedium,
+ color = TextPrimary
+ )
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ }
+
+ LazyRow(
+ contentPadding = PaddingValues(horizontal = 48.dp),
+ horizontalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ items(shortcuts, key = { "${it.type}:${it.categoryId}:${it.label}" }) { shortcut ->
+ DashboardShortcutCard(
+ shortcut = shortcut,
+ onClick = { onShortcutClick(shortcut) }
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun DashboardShortcutCard(
+ shortcut: DashboardLiveShortcut,
+ onClick: () -> Unit
+) {
+ val accentColor = when (shortcut.type) {
+ DashboardShortcutType.FAVORITES -> Color(0xFFFFC857)
+ DashboardShortcutType.RECENT -> Color(0xFF4FD1C5)
+ DashboardShortcutType.LAST_GROUP -> Color(0xFF60A5FA)
+ DashboardShortcutType.CUSTOM_GROUP -> Primary
+ }
+
+ Surface(
+ onClick = onClick,
+ modifier = Modifier
+ .width(220.dp)
+ .height(108.dp),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(18.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceElevated,
+ focusedContainerColor = SurfaceHighlight
+ ),
+ border = ClickableSurfaceDefaults.border(
+ border = Border(
+ border = BorderStroke(1.dp, accentColor.copy(alpha = 0.28f)),
+ shape = RoundedCornerShape(18.dp)
+ ),
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(18.dp)
+ )
+ )
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 16.dp, vertical = 14.dp),
+ verticalArrangement = Arrangement.SpaceBetween
+ ) {
+ Row(
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Box(
+ modifier = Modifier
+ .size(12.dp)
+ .clip(RoundedCornerShape(999.dp))
+ .background(accentColor)
+ )
+ Text(
+ text = shortcut.label,
+ style = MaterialTheme.typography.titleSmall,
+ color = TextPrimary,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ Text(
+ text = shortcut.detail,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+}
+
+@Composable
+private fun DashboardActionButton(
+ label: String,
+ onClick: () -> Unit
+) {
+ Button(
+ onClick = onClick,
+ colors = ButtonDefaults.colors(
+ containerColor = Primary.copy(alpha = 0.18f),
+ focusedContainerColor = Primary.copy(alpha = 0.32f),
+ contentColor = TextPrimary
+ )
+ ) {
+ Text(text = label)
+ }
+}
+
+@Composable
+private fun DashboardProviderHealthCard(
+ providerName: String,
+ health: DashboardProviderHealth,
+ onOpenDiagnostics: () -> Unit
+) {
+ val syncLabel = remember(health.lastSyncedAt) {
+ if (health.lastSyncedAt <= 0L) {
+ "No recent sync"
+ } else {
+ val format = SimpleDateFormat("MMM d, HH:mm", Locale.getDefault())
+ "Synced ${format.format(Date(health.lastSyncedAt))}"
+ }
+ }
+ val expiryLabel = remember(health.expirationDate) {
+ health.expirationDate?.let {
+ val format = SimpleDateFormat("MMM d, yyyy", Locale.getDefault())
+ "Expires ${format.format(Date(it))}"
+ } ?: "No expiry reported"
+ }
+ val statusLabel = when (health.status) {
+ com.streamvault.domain.model.ProviderStatus.ACTIVE -> stringResource(R.string.settings_status_active)
+ com.streamvault.domain.model.ProviderStatus.PARTIAL -> stringResource(R.string.settings_status_partial)
+ com.streamvault.domain.model.ProviderStatus.ERROR -> stringResource(R.string.settings_status_error)
+ com.streamvault.domain.model.ProviderStatus.EXPIRED -> stringResource(R.string.settings_status_expired)
+ com.streamvault.domain.model.ProviderStatus.DISABLED -> stringResource(R.string.settings_status_disabled)
+ com.streamvault.domain.model.ProviderStatus.UNKNOWN -> stringResource(R.string.settings_status_unknown)
+ }
+ val sourceLabel = when (health.type) {
+ com.streamvault.domain.model.ProviderType.XTREAM_CODES -> stringResource(R.string.dashboard_provider_xtream)
+ com.streamvault.domain.model.ProviderType.M3U -> stringResource(R.string.dashboard_provider_m3u)
+ }
+
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 48.dp, vertical = 4.dp),
+ shape = RoundedCornerShape(22.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceHighlight)
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 22.dp, vertical = 18.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.dashboard_provider_health_title),
+ style = MaterialTheme.typography.titleMedium,
+ color = TextPrimary
+ )
+ Text(
+ text = providerName,
+ style = MaterialTheme.typography.bodyLarge,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = "$syncLabel • $expiryLabel",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ item {
+ DashboardHealthPill(
+ label = statusLabel,
+ value = stringResource(R.string.dashboard_provider_status)
+ )
+ }
+ item {
+ DashboardHealthPill(
+ label = sourceLabel,
+ value = stringResource(R.string.dashboard_provider_source)
+ )
+ }
+ item {
+ DashboardHealthPill(
+ label = health.maxConnections.toString(),
+ value = stringResource(R.string.dashboard_provider_connections)
+ )
+ }
+ }
+ }
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 22.dp, vertical = 0.dp),
+ horizontalArrangement = Arrangement.End
+ ) {
+ DashboardActionButton(
+ label = stringResource(R.string.dashboard_warning_review),
+ onClick = onOpenDiagnostics
+ )
+ }
+ }
+}
+
+@Composable
+private fun DashboardHealthPill(
+ label: String,
+ value: String
+) {
+ Surface(
+ shape = RoundedCornerShape(18.dp),
+ colors = SurfaceDefaults.colors(containerColor = Color.White.copy(alpha = 0.08f))
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ Text(
+ text = value,
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelLarge,
+ color = TextPrimary
+ )
+ }
+ }
+}
+
+@Composable
+private fun DashboardProviderWarningCard(
+ warnings: List<String>,
+ onOpenSettings: () -> Unit
+) {
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 48.dp, vertical = 6.dp),
+ shape = RoundedCornerShape(20.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 22.dp, vertical = 18.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.dashboard_warning_title),
+ style = MaterialTheme.typography.titleMedium,
+ color = Primary
+ )
+ Text(
+ text = warnings.take(3).joinToString(" | "),
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ DashboardActionButton(
+ label = stringResource(R.string.dashboard_warning_review),
+ onClick = onOpenSettings
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun EmptyDashboard(
+ onAddProvider: () -> Unit,
+ onOpenSettings: () -> Unit
+) {
+ Box(
+ modifier = Modifier.fillMaxSize(),
+ contentAlignment = Alignment.Center
+ ) {
+ Surface(
+ shape = RoundedCornerShape(28.dp),
+ colors = SurfaceDefaults.colors(
+ containerColor = SurfaceHighlight
+ )
+ ) {
+ Column(
+ modifier = Modifier
+ .width(720.dp)
+ .padding(horizontal = 32.dp, vertical = 28.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ horizontalAlignment = Alignment.Start
+ ) {
+ Text(
+ text = stringResource(R.string.dashboard_empty_title),
+ style = MaterialTheme.typography.headlineMedium,
+ color = OnBackground
+ )
+ Text(
+ text = stringResource(R.string.dashboard_empty_body),
+ style = MaterialTheme.typography.titleMedium,
+ color = OnSurfaceDim
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ Button(onClick = onAddProvider) {
+ Text(stringResource(R.string.settings_add_provider))
+ }
+ Button(
+ onClick = onOpenSettings,
+ colors = ButtonDefaults.colors(
+ containerColor = SurfaceElevated,
+ focusedContainerColor = Primary.copy(alpha = 0.24f),
+ contentColor = TextPrimary
+ )
+ ) {
+ Text(stringResource(R.string.nav_settings))
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun rememberDashboardSections(
+ uiState: DashboardUiState
+): List<DashboardHomeSection> {
+ return remember(
+ uiState.feature.actionType,
+ uiState.liveShortcuts,
+ uiState.favoriteChannels,
+ uiState.recentChannels,
+ uiState.continueWatching,
+ uiState.recentMovies,
+ uiState.recentSeries
+ ) {
+ val preferred = when (uiState.feature.actionType) {
+ DashboardFeatureAction.CONTINUE_WATCHING -> listOf(
+ DashboardHomeSection.CONTINUE_WATCHING,
+ DashboardHomeSection.RECENT_CHANNELS,
+ DashboardHomeSection.FAVORITE_CHANNELS,
+ DashboardHomeSection.RECENT_MOVIES,
+ DashboardHomeSection.RECENT_SERIES,
+ DashboardHomeSection.LIVE_SHORTCUTS
+ )
+ DashboardFeatureAction.MOVIES -> listOf(
+ DashboardHomeSection.RECENT_MOVIES,
+ DashboardHomeSection.CONTINUE_WATCHING,
+ DashboardHomeSection.RECENT_SERIES,
+ DashboardHomeSection.RECENT_CHANNELS,
+ DashboardHomeSection.FAVORITE_CHANNELS,
+ DashboardHomeSection.LIVE_SHORTCUTS
+ )
+ DashboardFeatureAction.SERIES -> listOf(
+ DashboardHomeSection.RECENT_SERIES,
+ DashboardHomeSection.CONTINUE_WATCHING,
+ DashboardHomeSection.RECENT_MOVIES,
+ DashboardHomeSection.RECENT_CHANNELS,
+ DashboardHomeSection.FAVORITE_CHANNELS,
+ DashboardHomeSection.LIVE_SHORTCUTS
+ )
+ DashboardFeatureAction.LIVE -> listOf(
+ DashboardHomeSection.RECENT_CHANNELS,
+ DashboardHomeSection.FAVORITE_CHANNELS,
+ DashboardHomeSection.LIVE_SHORTCUTS,
+ DashboardHomeSection.CONTINUE_WATCHING,
+ DashboardHomeSection.RECENT_MOVIES,
+ DashboardHomeSection.RECENT_SERIES
+ )
+ }
+
+ preferred.filter { section ->
+ when (section) {
+ DashboardHomeSection.LIVE_SHORTCUTS -> uiState.liveShortcuts.isNotEmpty()
+ DashboardHomeSection.FAVORITE_CHANNELS -> uiState.favoriteChannels.isNotEmpty()
+ DashboardHomeSection.RECENT_CHANNELS -> uiState.recentChannels.isNotEmpty()
+ DashboardHomeSection.CONTINUE_WATCHING -> uiState.continueWatching.isNotEmpty()
+ DashboardHomeSection.RECENT_MOVIES -> uiState.recentMovies.isNotEmpty()
+ DashboardHomeSection.RECENT_SERIES -> uiState.recentSeries.isNotEmpty()
+ }
+ }
+ }
+}
+
+private enum class DashboardHomeSection {
+ LIVE_SHORTCUTS,
+ FAVORITE_CHANNELS,
+ RECENT_CHANNELS,
+ CONTINUE_WATCHING,
+ RECENT_MOVIES,
+ RECENT_SERIES
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt
new file mode 100644
index 00000000..02d3edc4
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/dashboard/DashboardViewModel.kt
@@ -0,0 +1,464 @@
+package com.streamvault.app.ui.screens.dashboard
+
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.data.sync.SyncManager
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Series
+import com.streamvault.domain.model.SyncState
+import com.streamvault.domain.model.VirtualCategoryIds
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.FavoriteRepository
+import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.PlaybackHistoryRepository
+import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.repository.SeriesRepository
+import com.streamvault.domain.usecase.GetCustomCategories
+import dagger.hilt.android.lifecycle.HiltViewModel
+import java.time.LocalDate
+import java.time.Year
+import java.time.format.DateTimeFormatter
+import javax.inject.Inject
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.launch
+
+@HiltViewModel
+@OptIn(ExperimentalCoroutinesApi::class)
+class DashboardViewModel @Inject constructor(
+ private val providerRepository: ProviderRepository,
+ private val favoriteRepository: FavoriteRepository,
+ private val channelRepository: ChannelRepository,
+ private val playbackHistoryRepository: PlaybackHistoryRepository,
+ private val movieRepository: MovieRepository,
+ private val seriesRepository: SeriesRepository,
+ private val preferencesRepository: PreferencesRepository,
+ private val getCustomCategories: GetCustomCategories,
+ private val syncManager: SyncManager
+) : ViewModel() {
+ private companion object {
+ const val FAVORITE_CHANNEL_LIMIT = 12
+ const val RECENT_CHANNEL_LIMIT = 12
+ const val CONTINUE_WATCHING_LIMIT = 12
+ const val MOVIE_SHELF_LIMIT = 12
+ const val SERIES_SHELF_LIMIT = 12
+ const val HOME_SHORTCUT_LIMIT = 4
+ }
+
+ private val _uiState = MutableStateFlow(DashboardUiState())
+ val uiState: StateFlow<DashboardUiState> = _uiState.asStateFlow()
+
+ init {
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .flatMapLatest { provider ->
+ if (provider == null) {
+ flowOf(DashboardUiState(isLoading = false))
+ } else {
+ val contentShelves = combine(
+ observeFavoriteChannels(provider.id),
+ observeRecentChannels(provider.id),
+ observeContinueWatching(provider.id),
+ movieRepository.getMovies(provider.id).map { movies ->
+ movies
+ .sortedByDescending(::movieFreshnessScore)
+ .take(MOVIE_SHELF_LIMIT)
+ },
+ seriesRepository.getSeries(provider.id).map { series ->
+ series
+ .sortedByDescending(::seriesFreshnessScore)
+ .take(SERIES_SHELF_LIMIT)
+ }
+ ) { favoriteChannels, recentChannels, continueWatching, recentMovies, recentSeries ->
+ DashboardContentShelves(
+ favoriteChannels = favoriteChannels,
+ recentChannels = recentChannels,
+ continueWatching = continueWatching,
+ recentMovies = recentMovies,
+ recentSeries = recentSeries
+ )
+ }
+
+ combine(
+ contentShelves,
+ buildLiveContext(provider.id),
+ channelRepository.getChannels(provider.id).map { it.size },
+ movieRepository.getLibraryCount(provider.id),
+ seriesRepository.getLibraryCount(provider.id)
+ ) { shelves, liveContext, liveChannelCount, movieCount, seriesCount ->
+ DashboardSnapshot(
+ shelves = shelves,
+ liveContext = liveContext,
+ liveChannelCount = liveChannelCount,
+ movieCount = movieCount,
+ seriesCount = seriesCount
+ )
+ }.combine(syncManager.syncState) { snapshot, syncState ->
+ DashboardUiState(
+ provider = provider,
+ favoriteChannels = snapshot.shelves.favoriteChannels,
+ recentChannels = snapshot.shelves.recentChannels,
+ continueWatching = snapshot.shelves.continueWatching,
+ recentMovies = snapshot.shelves.recentMovies,
+ recentSeries = snapshot.shelves.recentSeries,
+ lastLiveCategory = snapshot.liveContext.lastVisitedCategory,
+ liveShortcuts = snapshot.liveContext.shortcuts,
+ stats = DashboardStats(
+ liveChannelCount = snapshot.liveChannelCount,
+ favoriteChannelCount = snapshot.shelves.favoriteChannels.size,
+ recentChannelCount = snapshot.shelves.recentChannels.size,
+ continueWatchingCount = snapshot.shelves.continueWatching.size,
+ movieLibraryCount = snapshot.movieCount,
+ seriesLibraryCount = snapshot.seriesCount
+ ),
+ feature = buildFeature(
+ providerName = provider.name,
+ recentChannels = snapshot.shelves.recentChannels,
+ continueWatching = snapshot.shelves.continueWatching,
+ recentMovies = snapshot.shelves.recentMovies,
+ recentSeries = snapshot.shelves.recentSeries
+ ),
+ providerHealth = DashboardProviderHealth(
+ status = provider.status,
+ type = provider.type,
+ lastSyncedAt = provider.lastSyncedAt,
+ expirationDate = provider.expirationDate,
+ maxConnections = provider.maxConnections
+ ),
+ providerWarnings = when (syncState) {
+ is SyncState.Partial -> syncState.warnings
+ is SyncState.Error -> listOf(syncState.message)
+ else -> emptyList()
+ },
+ isLoading = false
+ )
+ }
+ }
+ }
+ .collect { state ->
+ _uiState.value = state
+ }
+ }
+ }
+
+ private fun observeFavoriteChannels(providerId: Long): Flow<List<Channel>> =
+ favoriteRepository.getFavorites(ContentType.LIVE)
+ .map { favorites ->
+ favorites
+ .filter { it.groupId == null }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .take(FAVORITE_CHANNEL_LIMIT)
+ }
+ .flatMapLatest(::loadChannelsByOrderedIds)
+
+ private fun observeRecentChannels(providerId: Long): Flow<List<Channel>> =
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, RECENT_CHANNEL_LIMIT)
+ .map { history ->
+ history
+ .filter { it.contentType == ContentType.LIVE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.contentId }
+ .map { it.contentId }
+ .take(RECENT_CHANNEL_LIMIT)
+ }
+ .flatMapLatest(::loadChannelsByOrderedIds)
+
+ private fun observeContinueWatching(providerId: Long): Flow<List<PlaybackHistory>> =
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, CONTINUE_WATCHING_LIMIT)
+ .map { history ->
+ history
+ .filter { it.contentType != ContentType.LIVE }
+ .distinctBy { "${it.contentType}:${it.contentId}:${it.seriesId}" }
+ .sortedByDescending { it.lastWatchedAt }
+ .take(CONTINUE_WATCHING_LIMIT)
+ }
+
+ private fun buildLiveContext(providerId: Long): Flow<DashboardLiveContext> =
+ combine(
+ getCustomCategories(ContentType.LIVE),
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, RECENT_CHANNEL_LIMIT)
+ .map { history ->
+ history
+ .filter { it.contentType == ContentType.LIVE }
+ .distinctBy { it.contentId }
+ .count()
+ },
+ preferencesRepository.getLastLiveCategoryId(providerId),
+ preferencesRepository.promotedLiveGroupIds
+ ) { customCategories, recentCount, lastVisitedCategoryId, promotedGroupIds ->
+ val lastVisitedCategory = customCategories.firstOrNull { it.id == lastVisitedCategoryId }
+ val shortcuts = buildList {
+ customCategories
+ .firstOrNull { it.id == VirtualCategoryIds.FAVORITES && it.count > 0 }
+ ?.let {
+ add(
+ DashboardLiveShortcut(
+ label = it.name,
+ detail = "${it.count} saved",
+ categoryId = it.id,
+ type = DashboardShortcutType.FAVORITES
+ )
+ )
+ }
+
+ if (recentCount > 0) {
+ add(
+ DashboardLiveShortcut(
+ label = "Recent",
+ detail = "$recentCount channels",
+ categoryId = VirtualCategoryIds.RECENT,
+ type = DashboardShortcutType.RECENT
+ )
+ )
+ }
+
+ lastVisitedCategory?.let {
+ add(
+ DashboardLiveShortcut(
+ label = "Last Group",
+ detail = it.name,
+ categoryId = it.id,
+ type = DashboardShortcutType.LAST_GROUP
+ )
+ )
+ }
+
+ customCategories
+ .asSequence()
+ .filter { it.id != VirtualCategoryIds.FAVORITES }
+ .filter { it.count > 0 }
+ .sortedWith(
+ compareByDescending<Category> { category ->
+ val groupId = if (category.id < 0) -category.id else category.id
+ groupId in promotedGroupIds
+ }.thenByDescending { it.count }
+ )
+ .take(HOME_SHORTCUT_LIMIT)
+ .forEach { category ->
+ val groupId = if (category.id < 0) -category.id else category.id
+ add(
+ DashboardLiveShortcut(
+ label = category.name,
+ detail = if (groupId in promotedGroupIds) {
+ "Pinned • ${category.count} channels"
+ } else {
+ "${category.count} channels"
+ },
+ categoryId = category.id,
+ type = DashboardShortcutType.CUSTOM_GROUP
+ )
+ )
+ }
+ }
+ .distinctBy { it.categoryId ?: it.label }
+ .take(HOME_SHORTCUT_LIMIT)
+
+ DashboardLiveContext(
+ lastVisitedCategory = lastVisitedCategory,
+ shortcuts = shortcuts
+ )
+ }
+
+ private fun loadChannelsByOrderedIds(ids: List<Long>): Flow<List<Channel>> {
+ if (ids.isEmpty()) return flowOf(emptyList())
+
+ return channelRepository.getChannelsByIds(ids).map { channels ->
+ val channelMap = channels.associateBy { it.id }
+ ids.mapNotNull { id ->
+ channelMap[id]
+ }
+ }
+ }
+
+ private fun buildFeature(
+ providerName: String,
+ recentChannels: List<Channel>,
+ continueWatching: List<PlaybackHistory>,
+ recentMovies: List<Movie>,
+ recentSeries: List<Series>
+ ): DashboardFeature {
+ val resumeItem = continueWatching.firstOrNull()
+ if (resumeItem != null) {
+ val detail = when (resumeItem.contentType) {
+ ContentType.MOVIE -> "Resume movie"
+ ContentType.SERIES -> "Resume series"
+ ContentType.SERIES_EPISODE -> {
+ if (resumeItem.seasonNumber != null && resumeItem.episodeNumber != null) {
+ "Resume S${resumeItem.seasonNumber} E${resumeItem.episodeNumber}"
+ } else {
+ "Resume episode"
+ }
+ }
+ ContentType.LIVE -> "Resume"
+ }
+ return DashboardFeature(
+ title = resumeItem.title,
+ summary = detail,
+ artworkUrl = resumeItem.posterUrl,
+ actionLabel = "Continue Watching",
+ actionType = DashboardFeatureAction.CONTINUE_WATCHING
+ )
+ }
+
+ recentChannels.firstOrNull()?.let { channel ->
+ return DashboardFeature(
+ title = channel.name,
+ summary = "Jump back into live TV",
+ artworkUrl = channel.logoUrl,
+ actionLabel = "Watch Live",
+ actionType = DashboardFeatureAction.LIVE
+ )
+ }
+
+ recentMovies.firstOrNull()?.let { movie ->
+ return DashboardFeature(
+ title = movie.name,
+ summary = movie.year ?: "Fresh movie pick",
+ artworkUrl = movie.backdropUrl ?: movie.posterUrl,
+ actionLabel = "Open Movies",
+ actionType = DashboardFeatureAction.MOVIES
+ )
+ }
+
+ recentSeries.firstOrNull()?.let { series ->
+ return DashboardFeature(
+ title = series.name,
+ summary = "Updated series shelf",
+ artworkUrl = series.backdropUrl ?: series.posterUrl,
+ actionLabel = "Open Series",
+ actionType = DashboardFeatureAction.SERIES
+ )
+ }
+
+ return DashboardFeature(
+ title = providerName,
+ summary = "Your IPTV library is ready",
+ artworkUrl = null,
+ actionLabel = "Open Live TV",
+ actionType = DashboardFeatureAction.LIVE
+ )
+ }
+
+ private fun movieFreshnessScore(movie: Movie): Long {
+ return parseDateScore(movie.releaseDate)
+ ?: movie.year?.toIntOrNull()?.toLong()
+ ?: movie.id
+ }
+
+ private fun seriesFreshnessScore(series: Series): Long {
+ return series.lastModified
+ .takeIf { it > 0L }
+ ?: parseDateScore(series.releaseDate)
+ ?: series.id
+ }
+
+ private fun parseDateScore(raw: String?): Long? {
+ if (raw.isNullOrBlank()) return null
+
+ return runCatching {
+ LocalDate.parse(raw, DateTimeFormatter.ISO_LOCAL_DATE).toEpochDay()
+ }.getOrNull()
+ ?: runCatching {
+ Year.parse(raw, DateTimeFormatter.ofPattern("yyyy")).atDay(1).toEpochDay()
+ }.getOrNull()
+ }
+}
+
+private data class DashboardLiveContext(
+ val lastVisitedCategory: Category?,
+ val shortcuts: List<DashboardLiveShortcut>
+)
+
+private data class DashboardContentShelves(
+ val favoriteChannels: List<Channel>,
+ val recentChannels: List<Channel>,
+ val continueWatching: List<PlaybackHistory>,
+ val recentMovies: List<Movie>,
+ val recentSeries: List<Series>
+)
+
+private data class DashboardSnapshot(
+ val shelves: DashboardContentShelves,
+ val liveContext: DashboardLiveContext,
+ val liveChannelCount: Int,
+ val movieCount: Int,
+ val seriesCount: Int
+)
+
+data class DashboardUiState(
+ val provider: Provider? = null,
+ val favoriteChannels: List<Channel> = emptyList(),
+ val recentChannels: List<Channel> = emptyList(),
+ val continueWatching: List<PlaybackHistory> = emptyList(),
+ val recentMovies: List<Movie> = emptyList(),
+ val recentSeries: List<Series> = emptyList(),
+ val lastLiveCategory: Category? = null,
+ val liveShortcuts: List<DashboardLiveShortcut> = emptyList(),
+ val feature: DashboardFeature = DashboardFeature(),
+ val providerHealth: DashboardProviderHealth = DashboardProviderHealth(),
+ val providerWarnings: List<String> = emptyList(),
+ val stats: DashboardStats = DashboardStats(),
+ val isLoading: Boolean = true
+)
+
+data class DashboardProviderHealth(
+ val status: ProviderStatus = ProviderStatus.UNKNOWN,
+ val type: ProviderType = ProviderType.M3U,
+ val lastSyncedAt: Long = 0L,
+ val expirationDate: Long? = null,
+ val maxConnections: Int = 1
+)
+
+data class DashboardStats(
+ val liveChannelCount: Int = 0,
+ val favoriteChannelCount: Int = 0,
+ val recentChannelCount: Int = 0,
+ val continueWatchingCount: Int = 0,
+ val movieLibraryCount: Int = 0,
+ val seriesLibraryCount: Int = 0
+)
+
+data class DashboardFeature(
+ val title: String = "",
+ val summary: String = "",
+ val artworkUrl: String? = null,
+ val actionLabel: String = "",
+ val actionType: DashboardFeatureAction = DashboardFeatureAction.LIVE
+)
+
+enum class DashboardFeatureAction {
+ LIVE,
+ CONTINUE_WATCHING,
+ MOVIES,
+ SERIES
+}
+
+data class DashboardLiveShortcut(
+ val label: String,
+ val detail: String,
+ val categoryId: Long?,
+ val type: DashboardShortcutType
+)
+
+enum class DashboardShortcutType {
+ FAVORITES,
+ RECENT,
+ LAST_GROUP,
+ CUSTOM_GROUP
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt
index 1a8519b6..26f017ee 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgScreen.kt
@@ -2,85 +2,1288 @@ package com.streamvault.app.ui.screens.epg
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.BoxWithConstraints
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxHeight
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.runtime.*
+import androidx.compose.foundation.verticalScroll
+import androidx.compose.material3.LinearProgressIndicator
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+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.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
+import androidx.compose.ui.unit.Dp
import androidx.hilt.navigation.compose.hiltViewModel
-import androidx.tv.material3.*
+import androidx.tv.material3.Border
+import androidx.tv.material3.Button
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.SurfaceDefaults
+import androidx.tv.material3.Text
+import com.streamvault.app.R
+import com.streamvault.app.navigation.Routes
+import com.streamvault.app.ui.components.SelectionChip
+import com.streamvault.app.ui.components.SelectionChipRow
import com.streamvault.app.ui.components.TopNavBar
-import com.streamvault.app.ui.theme.*
+import com.streamvault.app.ui.theme.FocusBorder
+import com.streamvault.app.ui.theme.OnBackground
+import com.streamvault.app.ui.theme.OnSurface
+import com.streamvault.app.ui.theme.OnSurfaceDim
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.theme.SurfaceHighlight
+import com.streamvault.app.ui.theme.TextPrimary
+import com.streamvault.app.ui.theme.TextSecondary
+import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Program
+import com.streamvault.domain.repository.ChannelRepository
import java.text.SimpleDateFormat
-import java.util.*
+import java.util.Calendar
+import java.util.Date
+import java.util.Locale
+import kotlinx.coroutines.delay
+import kotlin.math.max
+import kotlin.math.roundToInt
@Composable
fun FullEpgScreen(
currentRoute: String,
+ initialCategoryId: Long? = null,
+ initialAnchorTime: Long? = null,
+ initialFavoritesOnly: Boolean = false,
+ onPlayChannel: (Channel, String) -> Unit,
+ onPlayArchive: (Channel, Program, String) -> Unit,
onNavigate: (String) -> Unit,
viewModel: EpgViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsState()
+ var selectedProgram by remember { mutableStateOf<Pair<Channel, Program>?>(null) }
+ val now = rememberGuideNow()
+ val returnRoute = remember(uiState.selectedCategoryId, uiState.guideAnchorTime, uiState.showFavoritesOnly) {
+ Routes.epg(
+ categoryId = uiState.selectedCategoryId.takeIf { it != ChannelRepository.ALL_CHANNELS_ID },
+ anchorTime = uiState.guideAnchorTime,
+ favoritesOnly = uiState.showFavoritesOnly
+ )
+ }
+
+ LaunchedEffect(initialCategoryId, initialAnchorTime, initialFavoritesOnly) {
+ viewModel.applyNavigationContext(
+ categoryId = initialCategoryId,
+ anchorTime = initialAnchorTime,
+ favoritesOnly = initialFavoritesOnly
+ )
+ }
- Column(modifier = Modifier.fillMaxSize().background(MaterialTheme.colorScheme.background)) {
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(MaterialTheme.colorScheme.background)
+ ) {
TopNavBar(
currentRoute = currentRoute,
onNavigate = onNavigate,
- modifier = Modifier.fillMaxWidth().padding(top = 16.dp, bottom = 16.dp)
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(top = 16.dp, bottom = 12.dp)
)
- if (uiState.isLoading) {
- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- Text("Loading EPG...", color = OnBackground)
+ if (uiState.error == null) {
+ GuideFilterRow(
+ categories = uiState.categories,
+ selectedCategoryId = uiState.selectedCategoryId,
+ onCategorySelected = viewModel::selectCategory
+ )
+
+ GuideTimeControlsRow(
+ onJumpToPreviousDay = viewModel::jumpToPreviousDay,
+ onPageBackward = viewModel::pageBackward,
+ onJumpBackwardHalfHour = viewModel::jumpBackwardHalfHour,
+ onJumpBackward = viewModel::jumpBackward,
+ onJumpToNow = viewModel::jumpToNow,
+ onJumpForwardHalfHour = viewModel::jumpForwardHalfHour,
+ onJumpForward = viewModel::jumpForward,
+ onPageForward = viewModel::pageForward,
+ onJumpToPrimeTime = viewModel::jumpToPrimeTime,
+ onJumpToTomorrow = viewModel::jumpToTomorrow,
+ onJumpToNextDay = viewModel::jumpToNextDay
+ )
+
+ GuideDayRow(
+ selectedDayStart = startOfDay(uiState.guideWindowStart + EpgViewModel.LOOKBACK_MS),
+ onDaySelected = viewModel::jumpToDay
+ )
+
+ GuideModeRow(
+ selectedMode = uiState.selectedChannelMode,
+ onModeSelected = viewModel::selectChannelMode
+ )
+
+ GuideDensityRow(
+ selectedDensity = uiState.selectedDensity,
+ onDensitySelected = viewModel::selectDensity
+ )
+
+ GuideViewOptionsRow(
+ showScheduledOnly = uiState.showScheduledOnly,
+ onToggleScheduledOnly = viewModel::toggleScheduledOnly
+ )
+
+ GuideFavoritesRow(
+ showFavoritesOnly = uiState.showFavoritesOnly,
+ onToggleFavoritesOnly = viewModel::toggleFavoritesOnly
+ )
+
+ GuideSummaryCard(uiState = uiState)
+ }
+
+ when {
+ uiState.isLoading -> {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Text(stringResource(R.string.epg_loading), color = OnBackground)
+ }
+ }
+
+ uiState.error != null -> {
+ GuideMessageState(
+ title = when (uiState.error) {
+ EpgViewModel.NO_ACTIVE_PROVIDER -> stringResource(R.string.epg_no_provider)
+ else -> stringResource(R.string.epg_error)
+ },
+ subtitle = when (uiState.error) {
+ EpgViewModel.NO_ACTIVE_PROVIDER -> null
+ else -> stringResource(R.string.epg_retry_hint)
+ },
+ actionLabel = if (uiState.error == EpgViewModel.NO_ACTIVE_PROVIDER) null else stringResource(R.string.epg_retry),
+ onAction = if (uiState.error == EpgViewModel.NO_ACTIVE_PROVIDER) null else viewModel::refresh
+ )
+ }
+
+ uiState.channels.isEmpty() -> {
+ GuideMessageState(
+ title = if (uiState.selectedCategoryId == ChannelRepository.ALL_CHANNELS_ID) {
+ if (uiState.showScheduledOnly) {
+ stringResource(R.string.epg_no_scheduled_channels)
+ } else {
+ stringResource(R.string.epg_no_data)
+ }
+ } else {
+ if (uiState.showScheduledOnly) {
+ stringResource(R.string.epg_no_scheduled_channels)
+ } else {
+ stringResource(R.string.epg_no_channels_in_category)
+ }
+ },
+ subtitle = if (uiState.showScheduledOnly) {
+ stringResource(R.string.epg_scheduled_only_hint)
+ } else {
+ stringResource(R.string.epg_filter_hint)
+ },
+ actionLabel = stringResource(R.string.epg_retry),
+ onAction = viewModel::refresh
+ )
+ }
+
+ else -> {
+ EpgGrid(
+ channels = uiState.channels,
+ favoriteChannelIds = uiState.favoriteChannelIds,
+ programsByChannel = uiState.programsByChannel,
+ guideWindowStart = uiState.guideWindowStart,
+ guideWindowEnd = uiState.guideWindowEnd,
+ density = uiState.selectedDensity,
+ now = now,
+ onChannelClick = { channel -> onPlayChannel(channel, returnRoute) },
+ onProgramClick = { channel, program -> selectedProgram = channel to program }
+ )
}
- } else if (uiState.error != null) {
- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- Text("Error: ${uiState.error}", color = MaterialTheme.colorScheme.error)
+ }
+ }
+
+ val dialogState = selectedProgram
+ if (dialogState != null) {
+ val (channel, program) = dialogState
+ val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
+ val channelPrograms = channel.epgChannelId?.let { uiState.programsByChannel[it].orEmpty() }.orEmpty()
+ val surroundingPrograms = remember(channelPrograms, program) {
+ val index = channelPrograms.indexOfFirst { it.startTime == program.startTime && it.endTime == program.endTime && it.title == program.title }
+ if (index == -1) {
+ channelPrograms.take(4)
+ } else {
+ channelPrograms.subList(max(0, index - 1), minOf(channelPrograms.size, index + 3))
}
+ }
+
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.55f))
+ .clickable(onClick = { selectedProgram = null }, indication = null, interactionSource = remember { androidx.compose.foundation.interaction.MutableInteractionSource() }),
+ contentAlignment = Alignment.CenterEnd
+ ) {
+ Surface(
+ modifier = Modifier
+ .width(520.dp)
+ .fillMaxHeight()
+ .padding(vertical = 24.dp, horizontal = 24.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(20.dp)
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxSize()
+ .verticalScroll(rememberScrollState())
+ .padding(24.dp),
+ verticalArrangement = Arrangement.spacedBy(18.dp)
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(
+ text = program.title,
+ style = MaterialTheme.typography.headlineSmall,
+ color = OnSurface
+ )
+ Text(
+ text = stringResource(
+ R.string.player_time_range_minutes,
+ format.format(Date(program.startTime)),
+ format.format(Date(program.endTime)),
+ program.durationMinutes
+ ),
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ if (program.description.isNotBlank()) {
+ Text(
+ text = program.description,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurface
+ )
+ }
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ GuideProgramMetadataRow(
+ label = stringResource(R.string.epg_program_channel_label),
+ value = channel.name
+ )
+ uiState.currentProviderName?.let { providerName ->
+ GuideProgramMetadataRow(
+ label = stringResource(R.string.epg_program_provider_label),
+ value = providerName
+ )
+ }
+ if (uiState.providerSourceLabel.isNotBlank()) {
+ GuideProgramMetadataRow(
+ label = stringResource(R.string.epg_program_provider_type_label),
+ value = uiState.providerSourceLabel
+ )
+ }
+ GuideProgramMetadataRow(
+ label = stringResource(R.string.epg_program_language_label),
+ value = program.lang.ifBlank { stringResource(R.string.epg_program_unknown_value) }
+ )
+ GuideProgramMetadataRow(
+ label = stringResource(R.string.epg_program_replay_label),
+ value = when {
+ program.hasArchive -> stringResource(R.string.epg_program_replay_ready)
+ channel.catchUpSupported -> stringResource(R.string.epg_program_replay_partial)
+ else -> stringResource(R.string.epg_program_replay_unavailable)
+ }
+ )
+ if (program.isNowPlaying) {
+ GuideProgramMetadataRow(
+ label = stringResource(R.string.epg_program_progress_label),
+ value = stringResource(
+ R.string.epg_program_progress_value,
+ (program.progressPercent * 100f).roundToInt(),
+ stringResource(R.string.epg_minutes_remaining, ((program.endTime - now) / 60_000L).coerceAtLeast(0L))
+ )
+ )
+ }
+ }
+
+ GuideStatusCard(
+ isArchiveReady = program.hasArchive,
+ providerCatchUpSupported = channel.catchUpSupported,
+ isGuideStale = uiState.isGuideStale
+ )
+
+ if (uiState.providerArchiveSummary.isNotBlank()) {
+ GuideProviderTroubleshootingCard(
+ summary = uiState.providerArchiveSummary,
+ channel = channel,
+ program = program,
+ isGuideStale = uiState.isGuideStale
+ )
+ }
+
+ if (surroundingPrograms.isNotEmpty()) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(
+ text = stringResource(R.string.epg_upcoming_schedule),
+ style = MaterialTheme.typography.titleMedium,
+ color = OnSurface
+ )
+ surroundingPrograms.forEach { scheduleProgram ->
+ val isSelectedProgram = scheduleProgram === program ||
+ (scheduleProgram.startTime == program.startTime &&
+ scheduleProgram.endTime == program.endTime &&
+ scheduleProgram.title == program.title)
+ Surface(
+ onClick = { selectedProgram = channel to scheduleProgram },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (isSelectedProgram) Primary.copy(alpha = 0.18f) else SurfaceHighlight,
+ focusedContainerColor = SurfaceHighlight
+ )
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 14.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = scheduleProgram.title,
+ style = MaterialTheme.typography.titleSmall,
+ color = if (isSelectedProgram) Primary else OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = "${format.format(Date(scheduleProgram.startTime))} - ${format.format(Date(scheduleProgram.endTime))}",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+ }
+ }
+
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ if (program.hasArchive || channel.catchUpSupported) {
+ Button(
+ onClick = {
+ selectedProgram = null
+ onPlayArchive(channel, program, returnRoute)
+ },
+ colors = ButtonDefaults.colors(
+ containerColor = Primary,
+ contentColor = Color.White
+ ),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(stringResource(R.string.epg_watch_archive))
+ }
+ }
+ Button(
+ onClick = {
+ selectedProgram = null
+ onPlayChannel(channel, returnRoute)
+ },
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(stringResource(R.string.epg_watch_live))
+ }
+ if (uiState.isGuideStale) {
+ Button(
+ onClick = viewModel::refresh,
+ modifier = Modifier.fillMaxWidth(),
+ colors = ButtonDefaults.colors(
+ containerColor = SurfaceHighlight,
+ contentColor = OnSurface
+ )
+ ) {
+ Text(stringResource(R.string.epg_refresh_guide))
+ }
+ }
+ TextButton(onClick = { selectedProgram = null }) {
+ Text(stringResource(R.string.settings_cancel))
+ }
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideProgramMetadataRow(
+ label: String,
+ value: String
+) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = value,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+}
+
+@Composable
+private fun GuideStatusCard(
+ isArchiveReady: Boolean,
+ providerCatchUpSupported: Boolean,
+ isGuideStale: Boolean
+) {
+ Surface(
+ shape = RoundedCornerShape(16.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceHighlight)
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.epg_program_status_title),
+ style = MaterialTheme.typography.titleSmall,
+ color = OnSurface
+ )
+ Text(
+ text = when {
+ isArchiveReady -> stringResource(R.string.epg_archive_ready_hint)
+ providerCatchUpSupported -> stringResource(R.string.epg_archive_provider_hint)
+ else -> stringResource(R.string.epg_archive_unavailable_hint)
+ },
+ style = MaterialTheme.typography.bodyMedium,
+ color = if (isArchiveReady) Primary else OnSurfaceDim
+ )
+ if (isGuideStale) {
+ Text(
+ text = stringResource(R.string.epg_archive_stale_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideProviderTroubleshootingCard(
+ summary: String,
+ channel: Channel,
+ program: Program,
+ isGuideStale: Boolean
+) {
+ Surface(
+ shape = RoundedCornerShape(16.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceHighlight.copy(alpha = 0.85f))
+ ) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.epg_provider_troubleshooting_title),
+ style = MaterialTheme.typography.titleSmall,
+ color = OnSurface
+ )
+ Text(
+ text = summary,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurface
+ )
+ val channelReason = when {
+ !channel.catchUpSupported && !program.hasArchive ->
+ stringResource(R.string.epg_provider_troubleshooting_no_archive)
+ channel.catchUpSupported && channel.catchUpSource.isNullOrBlank() ->
+ stringResource(R.string.epg_provider_troubleshooting_missing_template)
+ channel.streamId <= 0L ->
+ stringResource(R.string.epg_provider_troubleshooting_missing_stream_id)
+ else ->
+ stringResource(R.string.epg_provider_troubleshooting_ready)
+ }
+ Text(
+ text = channelReason,
+ style = MaterialTheme.typography.bodySmall,
+ color = if (program.hasArchive) Primary else OnSurfaceDim
+ )
+ if (isGuideStale) {
+ Text(
+ text = stringResource(R.string.epg_provider_troubleshooting_stale),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun rememberGuideNow(): Long {
+ val currentTime by produceState(initialValue = System.currentTimeMillis()) {
+ while (true) {
+ value = System.currentTimeMillis()
+ delay(30_000L)
+ }
+ }
+ return currentTime
+}
+
+@Composable
+private fun GuideDensityRow(
+ selectedDensity: GuideDensity,
+ onDensitySelected: (GuideDensity) -> Unit
+) {
+ SelectionChipRow(
+ title = stringResource(R.string.epg_density_label),
+ subtitle = stringResource(R.string.epg_density_subtitle),
+ chips = listOf(
+ SelectionChip(
+ key = GuideDensity.COMPACT.name,
+ label = stringResource(R.string.epg_density_compact),
+ supportingText = stringResource(R.string.epg_density_compact_hint)
+ ),
+ SelectionChip(
+ key = GuideDensity.COMFORTABLE.name,
+ label = stringResource(R.string.epg_density_comfortable),
+ supportingText = stringResource(R.string.epg_density_comfortable_hint)
+ ),
+ SelectionChip(
+ key = GuideDensity.CINEMATIC.name,
+ label = stringResource(R.string.epg_density_cinematic),
+ supportingText = stringResource(R.string.epg_density_cinematic_hint)
+ )
+ ),
+ selectedKey = selectedDensity.name,
+ onChipSelected = { key ->
+ GuideDensity.entries.firstOrNull { it.name == key }?.let(onDensitySelected)
+ }
+ )
+}
+
+@Composable
+private fun GuideModeRow(
+ selectedMode: GuideChannelMode,
+ onModeSelected: (GuideChannelMode) -> Unit
+) {
+ SelectionChipRow(
+ title = stringResource(R.string.epg_mode_label),
+ subtitle = stringResource(R.string.epg_mode_subtitle),
+ chips = listOf(
+ SelectionChip(
+ key = GuideChannelMode.ALL.name,
+ label = stringResource(R.string.epg_mode_all),
+ supportingText = stringResource(R.string.epg_mode_all_hint)
+ ),
+ SelectionChip(
+ key = GuideChannelMode.ANCHORED.name,
+ label = stringResource(R.string.epg_mode_anchored),
+ supportingText = stringResource(R.string.epg_mode_anchored_hint)
+ ),
+ SelectionChip(
+ key = GuideChannelMode.ARCHIVE_READY.name,
+ label = stringResource(R.string.epg_mode_archive),
+ supportingText = stringResource(R.string.epg_mode_archive_hint)
+ )
+ ),
+ selectedKey = selectedMode.name,
+ onChipSelected = { key ->
+ GuideChannelMode.entries
+ .firstOrNull { it.name == key }
+ ?.let(onModeSelected)
+ }
+ )
+}
+
+@Composable
+private fun GuideFilterRow(
+ categories: List<Category>,
+ selectedCategoryId: Long,
+ onCategorySelected: (Long) -> Unit
+) {
+ if (categories.isEmpty()) return
+
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.epg_filter_label),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ items(categories, key = { it.id }) { category ->
+ Surface(
+ onClick = { onCategorySelected(category.id) },
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (category.id == selectedCategoryId) Primary.copy(alpha = 0.18f) else SurfaceElevated,
+ focusedContainerColor = SurfaceHighlight,
+ contentColor = if (category.id == selectedCategoryId) Primary else OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(999.dp)
+ )
+ )
+ ) {
+ Text(
+ text = category.name,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideTimeControlsRow(
+ onJumpToPreviousDay: () -> Unit,
+ onPageBackward: () -> Unit,
+ onJumpBackwardHalfHour: () -> Unit,
+ onJumpBackward: () -> Unit,
+ onJumpToNow: () -> Unit,
+ onJumpForwardHalfHour: () -> Unit,
+ onJumpForward: () -> Unit,
+ onPageForward: () -> Unit,
+ onJumpToPrimeTime: () -> Unit,
+ onJumpToTomorrow: () -> Unit,
+ onJumpToNextDay: () -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp, vertical = 12.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.epg_time_controls),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_previous_day),
+ onClick = onJumpToPreviousDay
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_page_back),
+ onClick = onPageBackward
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_jump_back_half_hour),
+ onClick = onJumpBackwardHalfHour
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_jump_back),
+ onClick = onJumpBackward
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_jump_now),
+ onClick = onJumpToNow
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_jump_forward_half_hour),
+ onClick = onJumpForwardHalfHour
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_jump_forward),
+ onClick = onJumpForward
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_page_forward),
+ onClick = onPageForward
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_jump_prime_time),
+ onClick = onJumpToPrimeTime
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_jump_tomorrow),
+ onClick = onJumpToTomorrow
+ )
+ }
+ item {
+ GuideShortcutChip(
+ label = stringResource(R.string.epg_next_day),
+ onClick = onJumpToNextDay
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideDayRow(
+ selectedDayStart: Long,
+ onDaySelected: (Long) -> Unit
+) {
+ val dayFormat = remember { SimpleDateFormat("EEE d MMM", Locale.getDefault()) }
+ val dayAnchors = remember(selectedDayStart) {
+ (-1L..3L).map { offset ->
+ selectedDayStart + (offset * EpgViewModel.DAY_SHIFT_MS)
+ }
+ }
+
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp, vertical = 4.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.epg_day_selector_label),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ items(dayAnchors, key = { it }) { dayStart ->
+ val isSelected = dayStart == selectedDayStart
+ Surface(
+ onClick = { onDaySelected(dayStart) },
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (isSelected) Primary.copy(alpha = 0.18f) else SurfaceElevated,
+ focusedContainerColor = SurfaceHighlight,
+ contentColor = if (isSelected) Primary else OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(999.dp)
+ )
+ )
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ Text(
+ text = dayRelativeLabel(dayStart),
+ style = MaterialTheme.typography.labelLarge
+ )
+ Text(
+ text = dayFormat.format(Date(dayStart)),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideViewOptionsRow(
+ showScheduledOnly: Boolean,
+ onToggleScheduledOnly: () -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp, vertical = 4.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.epg_view_options_label),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Spacer(modifier = Modifier.height(8.dp))
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ item {
+ Surface(
+ onClick = onToggleScheduledOnly,
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (showScheduledOnly) Primary.copy(alpha = 0.18f) else SurfaceElevated,
+ focusedContainerColor = SurfaceHighlight,
+ contentColor = if (showScheduledOnly) Primary else OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(999.dp)
+ )
+ )
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ Text(
+ text = stringResource(
+ if (showScheduledOnly) {
+ R.string.epg_view_scheduled_only_on
+ } else {
+ R.string.epg_view_scheduled_only_off
+ }
+ ),
+ style = MaterialTheme.typography.labelLarge
+ )
+ Text(
+ text = stringResource(R.string.epg_view_scheduled_only_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideFavoritesRow(
+ showFavoritesOnly: Boolean,
+ onToggleFavoritesOnly: () -> Unit
+) {
+ SelectionChipRow(
+ title = stringResource(R.string.epg_favorites_filter_title),
+ subtitle = stringResource(R.string.epg_favorites_filter_subtitle),
+ chips = listOf(
+ SelectionChip(
+ key = "all",
+ label = stringResource(R.string.epg_favorites_filter_all),
+ supportingText = stringResource(R.string.epg_favorites_filter_all_hint)
+ ),
+ SelectionChip(
+ key = "favorites",
+ label = stringResource(R.string.epg_favorites_filter_favorites),
+ supportingText = stringResource(R.string.epg_favorites_filter_favorites_hint)
+ )
+ ),
+ selectedKey = if (showFavoritesOnly) "favorites" else "all",
+ onChipSelected = { key ->
+ val shouldShowFavorites = key == "favorites"
+ if (shouldShowFavorites != showFavoritesOnly) {
+ onToggleFavoritesOnly()
+ }
+ },
+ contentPadding = PaddingValues(horizontal = 24.dp)
+ )
+}
+
+@Composable
+private fun GuideShortcutChip(
+ label: String,
+ onClick: () -> Unit
+) {
+ Surface(
+ onClick = onClick,
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceElevated,
+ focusedContainerColor = SurfaceHighlight,
+ contentColor = OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ border = ClickableSurfaceDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(2.dp, FocusBorder),
+ shape = RoundedCornerShape(999.dp)
+ )
+ )
+ ) {
+ Text(
+ text = label,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp),
+ style = MaterialTheme.typography.labelLarge
+ )
+ }
+}
+
+@Composable
+private fun GuideSummaryCard(uiState: EpgUiState) {
+ val lastUpdatedLabel = uiState.lastUpdatedAt?.let { timestamp ->
+ val minutes = ((System.currentTimeMillis() - timestamp) / 60_000L).coerceAtLeast(0L)
+ if (minutes <= 1) {
+ stringResource(R.string.epg_updated_now)
} else {
- EpgGrid(channels = uiState.channels, programsByChannel = uiState.programsByChannel)
+ stringResource(R.string.epg_updated_minutes_ago, minutes)
+ }
+ }
+ val windowFormat = remember { SimpleDateFormat("EEE HH:mm", Locale.getDefault()) }
+ val windowLabel = stringResource(
+ R.string.epg_window_label,
+ windowFormat.format(Date(uiState.guideWindowStart)),
+ windowFormat.format(Date(uiState.guideWindowEnd))
+ )
+
+ Surface(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp, vertical = 12.dp),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(14.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ Text(
+ text = stringResource(
+ R.string.epg_showing_channels,
+ uiState.channels.size,
+ uiState.totalChannelCount
+ ),
+ style = MaterialTheme.typography.titleSmall,
+ color = OnSurface
+ )
+ Text(
+ text = stringResource(
+ R.string.epg_schedule_summary,
+ uiState.channelsWithSchedule,
+ uiState.channels.size
+ ),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = windowLabel,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ if (lastUpdatedLabel != null) {
+ Text(
+ text = lastUpdatedLabel,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ if (uiState.isGuideStale) {
+ Text(
+ text = stringResource(R.string.epg_stale_warning),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun GuideMessageState(
+ title: String,
+ subtitle: String?,
+ actionLabel: String?,
+ onAction: (() -> Unit)?
+) {
+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(10.dp),
+ modifier = Modifier.padding(horizontal = 32.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleLarge,
+ color = OnSurface
+ )
+ if (!subtitle.isNullOrBlank()) {
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ }
+ if (actionLabel != null && onAction != null) {
+ Button(
+ onClick = onAction,
+ colors = ButtonDefaults.colors(
+ containerColor = Primary,
+ contentColor = Color.White
+ )
+ ) {
+ Text(actionLabel)
+ }
+ }
+ }
+ }
+}
+
+@Composable
+fun EpgGrid(
+ channels: List<Channel>,
+ favoriteChannelIds: Set<Long>,
+ programsByChannel: Map<String, List<Program>>,
+ guideWindowStart: Long,
+ guideWindowEnd: Long,
+ density: GuideDensity,
+ now: Long,
+ onChannelClick: (Channel) -> Unit,
+ onProgramClick: (Channel, Program) -> Unit
+) {
+ val (channelRailWidth, timelineGap, rowHeight) = when (density) {
+ GuideDensity.COMPACT -> Triple(180.dp, 12.dp, 76.dp)
+ GuideDensity.COMFORTABLE -> Triple(220.dp, 16.dp, 92.dp)
+ GuideDensity.CINEMATIC -> Triple(260.dp, 20.dp, 108.dp)
+ }
+
+ BoxWithConstraints(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 24.dp, vertical = 16.dp)
+ ) {
+ val timelineWidth = (maxWidth - channelRailWidth - timelineGap).coerceAtLeast(720.dp)
+ val markerStepMs = EpgViewModel.HALF_HOUR_SHIFT_MS
+
+ LazyColumn(
+ modifier = Modifier.fillMaxSize(),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ item(key = "timeline_header") {
+ GuideTimelineHeader(
+ windowStart = guideWindowStart,
+ windowEnd = guideWindowEnd,
+ now = now,
+ channelRailWidth = channelRailWidth,
+ timelineGap = timelineGap,
+ timelineWidth = timelineWidth,
+ markerStepMs = markerStepMs
+ )
+ }
+ items(channels, key = { it.id }) { channel ->
+ val programs = channel.epgChannelId?.let { programsByChannel[it] } ?: emptyList()
+ EpgRow(
+ channel = channel,
+ isFavorite = channel.id in favoriteChannelIds,
+ programs = programs,
+ now = now,
+ windowStart = guideWindowStart,
+ windowEnd = guideWindowEnd,
+ channelRailWidth = channelRailWidth,
+ timelineGap = timelineGap,
+ timelineWidth = timelineWidth,
+ rowHeight = rowHeight,
+ markerStepMs = markerStepMs,
+ onChannelClick = { onChannelClick(channel) },
+ onProgramClick = { program -> onProgramClick(channel, program) }
+ )
+ }
}
}
}
@Composable
-fun EpgGrid(channels: List<Channel>, programsByChannel: Map<String, List<Program>>) {
- // Current time to show line
- val now = System.currentTimeMillis()
+private fun GuideTimelineHeader(
+ windowStart: Long,
+ windowEnd: Long,
+ now: Long,
+ channelRailWidth: Dp,
+ timelineGap: Dp,
+ timelineWidth: Dp,
+ markerStepMs: Long
+) {
+ val hourFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
+ val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)
+ val clampedNow = now.coerceIn(windowStart, windowEnd)
+ val elapsedRatio = ((clampedNow - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
+ val markerLabel = if (now in windowStart..windowEnd) {
+ stringResource(R.string.epg_now_marker, hourFormat.format(Date(now)))
+ } else {
+ stringResource(R.string.epg_outside_window)
+ }
+ val hourMarkers = buildList {
+ var marker = windowStart
+ while (marker <= windowEnd) {
+ add(marker)
+ marker += markerStepMs
+ }
+ if (lastOrNull() != windowEnd) {
+ add(windowEnd)
+ }
+ }
- LazyColumn(
- modifier = Modifier.fillMaxSize(),
- contentPadding = PaddingValues(horizontal = 24.dp, vertical = 16.dp),
- verticalArrangement = Arrangement.spacedBy(16.dp)
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(bottom = 4.dp),
+ verticalAlignment = Alignment.Bottom
) {
- items(channels) { channel ->
- val programs = channel.epgChannelId?.let { programsByChannel[it] } ?: emptyList()
- EpgRow(channel = channel, programs = programs, now = now)
+ Spacer(modifier = Modifier.width(channelRailWidth + timelineGap))
+ Column(
+ modifier = Modifier.width(timelineWidth),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(R.string.epg_timeline_label),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = stringResource(
+ R.string.epg_timeline_range_label,
+ formatWindowDuration(totalDuration)
+ ),
+ style = MaterialTheme.typography.labelMedium,
+ color = OnSurfaceDim
+ )
+ }
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(44.dp)
+ ) {
+ hourMarkers.forEach { marker ->
+ val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
+ val markerOffset = timelineWidth * markerRatio
+ Column(
+ modifier = Modifier.padding(start = markerOffset),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ Text(
+ text = hourFormat.format(Date(marker)),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ Box(
+ modifier = Modifier
+ .width(1.dp)
+ .height(18.dp)
+ .background(Color.White.copy(alpha = 0.16f))
+ )
+ }
+ }
+ if (now in windowStart..windowEnd) {
+ Box(
+ modifier = Modifier
+ .padding(start = timelineWidth * elapsedRatio)
+ .width(2.dp)
+ .fillMaxHeight()
+ .background(Primary)
+ )
+ }
+ }
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = markerLabel,
+ style = MaterialTheme.typography.labelMedium,
+ color = if (now in windowStart..windowEnd) Primary else OnSurfaceDim
+ )
+ }
+ LinearProgressIndicator(
+ progress = { elapsedRatio },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(4.dp),
+ color = Primary,
+ trackColor = SurfaceElevated
+ )
}
}
}
@Composable
-fun EpgRow(channel: Channel, programs: List<Program>, now: Long) {
+fun EpgRow(
+ channel: Channel,
+ isFavorite: Boolean,
+ programs: List<Program>,
+ now: Long,
+ windowStart: Long,
+ windowEnd: Long,
+ channelRailWidth: Dp,
+ timelineGap: Dp,
+ timelineWidth: Dp,
+ rowHeight: Dp,
+ markerStepMs: Long,
+ onChannelClick: () -> Unit,
+ onProgramClick: (Program) -> Unit
+) {
var isFocused by remember { mutableStateOf(false) }
+ val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)
+ val currentProgram = programs.firstOrNull { now in it.startTime..it.endTime }
Row(
- modifier = Modifier.fillMaxWidth().height(84.dp),
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(rowHeight),
verticalAlignment = Alignment.CenterVertically
) {
- // Channel Info
Surface(
- onClick = { /* TODO: Play channel */ },
- modifier = Modifier.width(220.dp).fillMaxHeight().onFocusChanged { isFocused = it.isFocused },
+ onClick = onChannelClick,
+ modifier = Modifier
+ .width(channelRailWidth)
+ .fillMaxHeight()
+ .onFocusChanged { isFocused = it.isFocused },
colors = ClickableSurfaceDefaults.colors(
containerColor = SurfaceElevated,
focusedContainerColor = SurfaceHighlight
@@ -93,34 +1296,97 @@ fun EpgRow(channel: Channel, programs: List<Program>, now: Long) {
)
)
) {
- Row(modifier = Modifier.padding(12.dp).fillMaxSize(), verticalAlignment = Alignment.CenterVertically) {
- Text(
- text = "${channel.number}. ${channel.name}",
- style = MaterialTheme.typography.titleMedium,
- color = if (isFocused) TextPrimary else OnSurface,
- maxLines = 2,
- overflow = TextOverflow.Ellipsis
- )
+ Row(
+ modifier = Modifier
+ .padding(12.dp)
+ .fillMaxSize(),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ if (isFavorite) {
+ Text(
+ text = stringResource(R.string.epg_favorite_badge),
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary,
+ maxLines = 1
+ )
+ }
+ Text(
+ text = "${channel.number}. ${channel.name}",
+ style = MaterialTheme.typography.titleMedium,
+ color = if (isFocused) TextPrimary else OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = currentProgram?.title ?: stringResource(R.string.epg_no_schedule),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
}
}
- Spacer(modifier = Modifier.width(16.dp))
+ Spacer(modifier = Modifier.width(timelineGap))
- // Programs
if (programs.isEmpty()) {
Box(
- modifier = Modifier.weight(1f).fillMaxHeight().background(SurfaceElevated, RoundedCornerShape(8.dp)),
+ modifier = Modifier
+ .width(timelineWidth)
+ .fillMaxHeight()
+ .background(SurfaceElevated, RoundedCornerShape(8.dp)),
contentAlignment = Alignment.Center
) {
- Text("No EPG Data Available", color = OnSurfaceDim)
+ Text(stringResource(R.string.epg_no_schedule), color = OnSurfaceDim)
}
} else {
- LazyRow(
- modifier = Modifier.weight(1f).fillMaxHeight(),
- horizontalArrangement = Arrangement.spacedBy(8.dp)
+ Box(
+ modifier = Modifier
+ .width(timelineWidth)
+ .fillMaxHeight()
+ .background(SurfaceElevated, RoundedCornerShape(8.dp))
) {
- items(programs) { program ->
- ProgramItem(program = program, isCurrent = now in program.startTime..program.endTime)
+ val markers = remember(windowStart, windowEnd, markerStepMs) {
+ buildList {
+ var marker = windowStart
+ while (marker <= windowEnd) {
+ add(marker)
+ marker += markerStepMs
+ }
+ }
+ }
+ markers.forEach { marker ->
+ val markerRatio = ((marker - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
+ Box(
+ modifier = Modifier
+ .padding(start = timelineWidth * markerRatio)
+ .width(1.dp)
+ .fillMaxHeight()
+ .background(Color.White.copy(alpha = 0.08f))
+ )
+ }
+ if (now in windowStart..windowEnd) {
+ val nowRatio = ((now - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
+ Box(
+ modifier = Modifier
+ .padding(start = timelineWidth * nowRatio)
+ .width(2.dp)
+ .fillMaxHeight()
+ .background(Primary)
+ )
+ }
+ programs.forEach { program ->
+ ProgramItem(
+ program = program,
+ isCurrent = now in program.startTime..program.endTime,
+ now = now,
+ windowStart = windowStart,
+ windowEnd = windowEnd,
+ timelineWidth = timelineWidth,
+ onClick = { onProgramClick(program) }
+ )
}
}
}
@@ -128,21 +1394,41 @@ fun EpgRow(channel: Channel, programs: List<Program>, now: Long) {
}
@Composable
-fun ProgramItem(program: Program, isCurrent: Boolean) {
+fun ProgramItem(
+ program: Program,
+ isCurrent: Boolean,
+ now: Long,
+ windowStart: Long,
+ windowEnd: Long,
+ timelineWidth: Dp,
+ onClick: () -> Unit
+) {
var isFocused by remember { mutableStateOf(false) }
-
- // Format times
- val format = SimpleDateFormat("HH:mm", Locale.getDefault())
+
+ val format = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
val startStr = format.format(Date(program.startTime))
val endStr = format.format(Date(program.endTime))
-
- // Estimate width based on duration (1 min = 6dp)
- val durationMin = ((program.endTime - program.startTime) / 60000).coerceAtLeast(15)
- val itemWidth = (durationMin * 6).toInt().dp.coerceAtMost(600.dp) // Cap width to prevent ultra-wide items
+ val totalDuration = (windowEnd - windowStart).coerceAtLeast(1L)
+ val visibleStart = max(program.startTime, windowStart)
+ val visibleEnd = max(visibleStart + 1, minOf(program.endTime, windowEnd))
+ val startRatio = ((visibleStart - windowStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
+ val widthRatio = ((visibleEnd - visibleStart).toFloat() / totalDuration.toFloat()).coerceIn(0f, 1f)
+ val itemStart = timelineWidth * startRatio
+ val itemWidth = (timelineWidth * widthRatio).coerceAtLeast(96.dp)
+ val elapsedRatio = if (program.endTime > program.startTime) {
+ ((now - program.startTime).toFloat() / (program.endTime - program.startTime).toFloat()).coerceIn(0f, 1f)
+ } else {
+ 0f
+ }
+ val remainingMinutes = ((program.endTime - now) / 60_000L).coerceAtLeast(0L)
Surface(
- onClick = { /* TODO: Optional details dialog */ },
- modifier = Modifier.width(itemWidth).fillMaxHeight().onFocusChanged { isFocused = it.isFocused },
+ onClick = onClick,
+ modifier = Modifier
+ .padding(start = itemStart, top = 6.dp, bottom = 6.dp)
+ .width(itemWidth)
+ .fillMaxHeight()
+ .onFocusChanged { isFocused = it.isFocused },
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isCurrent) Primary.copy(alpha = 0.2f) else SurfaceElevated,
focusedContainerColor = SurfaceHighlight
@@ -156,13 +1442,24 @@ fun ProgramItem(program: Program, isCurrent: Boolean) {
)
) {
Column(
- modifier = Modifier.padding(12.dp).fillMaxSize(),
+ modifier = Modifier
+ .padding(12.dp)
+ .fillMaxSize(),
verticalArrangement = Arrangement.Center
) {
+ if (isCurrent) {
+ Text(
+ text = stringResource(R.string.epg_now_playing),
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary,
+ maxLines = 1
+ )
+ Spacer(modifier = Modifier.height(4.dp))
+ }
Text(
text = program.title,
style = MaterialTheme.typography.titleSmall,
- color = if (isFocused) TextPrimary else (if (isCurrent) Primary else OnSurface),
+ color = if (isFocused) TextPrimary else if (isCurrent) Primary else OnSurface,
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
@@ -172,6 +1469,68 @@ fun ProgramItem(program: Program, isCurrent: Boolean) {
style = MaterialTheme.typography.bodySmall,
color = if (isFocused) TextSecondary else OnSurfaceDim
)
+ if (program.hasArchive) {
+ Spacer(modifier = Modifier.height(4.dp))
+ Text(
+ text = stringResource(R.string.player_archive_badge),
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary,
+ maxLines = 1
+ )
+ }
+ if (isCurrent) {
+ Spacer(modifier = Modifier.height(8.dp))
+ LinearProgressIndicator(
+ progress = { elapsedRatio },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(4.dp),
+ color = Primary,
+ trackColor = SurfaceHighlight
+ )
+ Spacer(modifier = Modifier.height(4.dp))
+ Text(
+ text = stringResource(R.string.epg_minutes_remaining, remainingMinutes),
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim,
+ maxLines = 1
+ )
+ }
+ }
+ }
+}
+
+private fun formatWindowDuration(durationMs: Long): String {
+ val hours = durationMs / (60 * 60 * 1000L)
+ val minutes = (durationMs / (60 * 1000L)) % 60
+ return if (minutes == 0L) {
+ "${hours}h"
+ } else {
+ "${hours}h ${minutes}m"
+ }
+}
+
+private fun startOfDay(timestamp: Long): Long {
+ val calendar = Calendar.getInstance().apply {
+ timeInMillis = timestamp
+ set(Calendar.HOUR_OF_DAY, 0)
+ set(Calendar.MINUTE, 0)
+ set(Calendar.SECOND, 0)
+ set(Calendar.MILLISECOND, 0)
+ }
+ return calendar.timeInMillis
+}
+
+@Composable
+private fun dayRelativeLabel(dayStart: Long): String {
+ val todayStart = remember { startOfDay(System.currentTimeMillis()) }
+ return when (dayStart) {
+ todayStart - EpgViewModel.DAY_SHIFT_MS -> stringResource(R.string.epg_day_yesterday)
+ todayStart -> stringResource(R.string.epg_day_today)
+ todayStart + EpgViewModel.DAY_SHIFT_MS -> stringResource(R.string.epg_day_tomorrow)
+ else -> {
+ val format = remember { SimpleDateFormat("EEE", Locale.getDefault()) }
+ format.format(Date(dayStart))
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
index a7e77e6a..21659d2f 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/epg/EpgViewModel.kt
@@ -2,70 +2,478 @@ package com.streamvault.app.ui.screens.epg
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Program
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.data.preferences.PreferencesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
-import kotlinx.coroutines.flow.*
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
data class EpgUiState(
+ val currentProviderName: String? = null,
+ val providerSourceLabel: String = "",
+ val providerArchiveSummary: String = "",
+ val categories: List<Category> = emptyList(),
+ val selectedCategoryId: Long = ChannelRepository.ALL_CHANNELS_ID,
+ val showScheduledOnly: Boolean = false,
+ val selectedChannelMode: GuideChannelMode = GuideChannelMode.ALL,
+ val selectedDensity: GuideDensity = GuideDensity.COMFORTABLE,
+ val showFavoritesOnly: Boolean = false,
+ val favoriteChannelIds: Set<Long> = emptySet(),
val channels: List<Channel> = emptyList(),
val programsByChannel: Map<String, List<Program>> = emptyMap(),
val isLoading: Boolean = true,
- val error: String? = null
+ val error: String? = null,
+ val totalChannelCount: Int = 0,
+ val channelsWithSchedule: Int = 0,
+ val failedScheduleCount: Int = 0,
+ val lastUpdatedAt: Long? = null,
+ val isGuideStale: Boolean = false,
+ val guideAnchorTime: Long = System.currentTimeMillis(),
+ val guideWindowStart: Long = System.currentTimeMillis() - EpgViewModel.LOOKBACK_MS,
+ val guideWindowEnd: Long = System.currentTimeMillis() + EpgViewModel.LOOKAHEAD_MS
+)
+
+enum class GuideChannelMode {
+ ALL,
+ ANCHORED,
+ ARCHIVE_READY
+}
+
+enum class GuideDensity {
+ COMPACT,
+ COMFORTABLE,
+ CINEMATIC
+}
+
+private data class GuideProgramsResult(
+ val programsByChannel: Map<String, List<Program>>,
+ val failedCount: Int
+)
+
+private data class GuideChannelSelection(
+ val channels: List<Channel>,
+ val favoriteChannelIds: Set<Long>
)
@HiltViewModel
class EpgViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val channelRepository: ChannelRepository,
- private val epgRepository: EpgRepository
+ private val epgRepository: EpgRepository,
+ private val favoriteRepository: FavoriteRepository,
+ private val preferencesRepository: PreferencesRepository
) : ViewModel() {
+ companion object {
+ const val MAX_CHANNELS = 60
+ const val LOOKBACK_MS = 60 * 60 * 1000L
+ const val LOOKAHEAD_MS = 6 * 60 * 60 * 1000L
+ const val HALF_HOUR_SHIFT_MS = 30 * 60 * 1000L
+ const val WINDOW_SHIFT_MS = 3 * 60 * 60 * 1000L
+ const val PAGE_SHIFT_MS = LOOKBACK_MS + LOOKAHEAD_MS
+ const val DAY_SHIFT_MS = 24 * 60 * 60 * 1000L
+ const val PRIME_TIME_HOUR = 20
+ const val NO_ACTIVE_PROVIDER = "NO_ACTIVE_PROVIDER"
+ }
+
private val _uiState = MutableStateFlow(EpgUiState())
val uiState: StateFlow<EpgUiState> = _uiState.asStateFlow()
+ private val selectedCategoryId = MutableStateFlow(ChannelRepository.ALL_CHANNELS_ID)
+ private val guideAnchorTime = MutableStateFlow(System.currentTimeMillis())
+ private val showScheduledOnly = MutableStateFlow(false)
+ private val selectedChannelMode = MutableStateFlow(GuideChannelMode.ALL)
+ private val selectedDensity = MutableStateFlow(GuideDensity.COMFORTABLE)
+ private val showFavoritesOnly = MutableStateFlow(false)
+ private val refreshNonce = MutableStateFlow(0)
+
init {
- loadData()
+ restoreGuidePreferences()
+ observeGuide()
+ }
+
+ fun selectCategory(categoryId: Long) {
+ if (selectedCategoryId.value == categoryId) return
+ selectedCategoryId.value = categoryId
+ }
+
+ fun refresh() {
+ refreshNonce.update { it + 1 }
+ }
+
+ fun jumpToNow() {
+ updateGuideAnchorTime(System.currentTimeMillis())
+ }
+
+ fun jumpForwardHalfHour() {
+ updateGuideAnchorTime(guideAnchorTime.value + HALF_HOUR_SHIFT_MS)
+ }
+
+ fun jumpBackwardHalfHour() {
+ updateGuideAnchorTime((guideAnchorTime.value - HALF_HOUR_SHIFT_MS).coerceAtLeast(0L))
+ }
+
+ fun jumpForward() {
+ updateGuideAnchorTime(guideAnchorTime.value + WINDOW_SHIFT_MS)
+ }
+
+ fun jumpBackward() {
+ updateGuideAnchorTime((guideAnchorTime.value - WINDOW_SHIFT_MS).coerceAtLeast(0L))
+ }
+
+ fun pageBackward() {
+ updateGuideAnchorTime((guideAnchorTime.value - PAGE_SHIFT_MS).coerceAtLeast(0L))
+ }
+
+ fun pageForward() {
+ updateGuideAnchorTime(guideAnchorTime.value + PAGE_SHIFT_MS)
+ }
+
+ fun jumpToTomorrow() {
+ updateGuideAnchorTime(System.currentTimeMillis() + DAY_SHIFT_MS)
+ }
+
+ fun jumpToPrimeTime() {
+ val selectedDayStart = (guideAnchorTime.value / DAY_SHIFT_MS) * DAY_SHIFT_MS
+ updateGuideAnchorTime(selectedDayStart + (PRIME_TIME_HOUR * 60 * 60 * 1000L))
+ }
+
+ fun jumpToPreviousDay() {
+ updateGuideAnchorTime((guideAnchorTime.value - DAY_SHIFT_MS).coerceAtLeast(0L))
+ }
+
+ fun jumpToNextDay() {
+ updateGuideAnchorTime(guideAnchorTime.value + DAY_SHIFT_MS)
+ }
+
+ fun jumpToDay(dayStartMillis: Long) {
+ val currentTimeOfDay = guideAnchorTime.value
+ .mod(DAY_SHIFT_MS)
+ .let { if (it < 0L) it + DAY_SHIFT_MS else it }
+ updateGuideAnchorTime(dayStartMillis + currentTimeOfDay)
+ }
+
+ fun toggleScheduledOnly() {
+ showScheduledOnly.update { !it }
+ }
+
+ fun selectChannelMode(mode: GuideChannelMode) {
+ selectedChannelMode.value = mode
+ viewModelScope.launch {
+ preferencesRepository.setGuideChannelMode(mode.name)
+ }
+ }
+
+ fun selectDensity(density: GuideDensity) {
+ selectedDensity.value = density
+ viewModelScope.launch {
+ preferencesRepository.setGuideDensity(density.name)
+ }
+ }
+
+ fun toggleFavoritesOnly() {
+ val enabled = !showFavoritesOnly.value
+ showFavoritesOnly.value = enabled
+ viewModelScope.launch {
+ preferencesRepository.setGuideFavoritesOnly(enabled)
+ }
+ }
+
+ fun applyNavigationContext(
+ categoryId: Long?,
+ anchorTime: Long?,
+ favoritesOnly: Boolean?
+ ) {
+ categoryId?.let { requested ->
+ selectedCategoryId.value = requested
+ }
+ anchorTime?.takeIf { it > 0L }?.let { requested ->
+ guideAnchorTime.value = requested
+ }
+ favoritesOnly?.let { requested ->
+ showFavoritesOnly.value = requested
+ }
}
- private fun loadData() {
+ private fun observeGuide() {
viewModelScope.launch {
- try {
- providerRepository.getActiveProvider().firstOrNull()?.let { provider ->
- channelRepository.getChannels(provider.id).collect { channels ->
- if (channels.isNotEmpty()) {
- val epgIds = channels.mapNotNull { it.epgChannelId }.distinct()
-
- // Listen for EPG updates for all these channels
- epgRepository.getNowPlayingForChannels(provider.id, epgIds).collect { programsDict ->
- _uiState.update {
- it.copy(
- channels = channels.take(100), // Limit to 100 for now to avoid grid overload
- programsByChannel = programsDict,
- isLoading = false
- )
+ providerRepository.getActiveProvider().collectLatest { provider ->
+ if (provider == null) {
+ _uiState.update {
+ it.copy(
+ currentProviderName = null,
+ providerSourceLabel = "",
+ providerArchiveSummary = "",
+ categories = emptyList(),
+ channels = emptyList(),
+ programsByChannel = emptyMap(),
+ isLoading = false,
+ error = NO_ACTIVE_PROVIDER,
+ totalChannelCount = 0,
+ channelsWithSchedule = 0,
+ failedScheduleCount = 0,
+ lastUpdatedAt = null,
+ isGuideStale = false,
+ guideAnchorTime = System.currentTimeMillis(),
+ guideWindowStart = System.currentTimeMillis() - LOOKBACK_MS,
+ guideWindowEnd = System.currentTimeMillis() + LOOKAHEAD_MS
+ )
+ }
+ return@collectLatest
+ }
+
+ channelRepository.getCategories(provider.id).combine(
+ combine(
+ combine(
+ selectedCategoryId,
+ guideAnchorTime,
+ showScheduledOnly,
+ selectedChannelMode,
+ selectedDensity
+ ) { requestedCategoryId, anchorTime, scheduledOnly, channelMode, density ->
+ GuideSelectionState(
+ requestedCategoryId = requestedCategoryId,
+ anchorTime = anchorTime,
+ scheduledOnly = scheduledOnly,
+ channelMode = channelMode,
+ density = density,
+ favoritesOnly = false
+ )
+ },
+ showFavoritesOnly
+ ) { selection, favoritesOnly ->
+ selection.copy(favoritesOnly = favoritesOnly)
+ }
+ ) { categories, selection ->
+ GuideRequest(
+ categories = categories,
+ requestedCategoryId = selection.requestedCategoryId,
+ anchorTime = selection.anchorTime,
+ scheduledOnly = selection.scheduledOnly,
+ channelMode = selection.channelMode,
+ density = selection.density,
+ favoritesOnly = selection.favoritesOnly
+ )
+ }.combine(refreshNonce) { request, _ ->
+ request
+ }.collectLatest { request ->
+ val providerCategories = request.categories
+ val requestedCategoryId = request.requestedCategoryId
+ val anchorTime = request.anchorTime
+ val categories = buildList {
+ add(Category(id = ChannelRepository.ALL_CHANNELS_ID, name = "All Channels"))
+ addAll(providerCategories.sortedBy { it.name.lowercase() })
+ }
+
+ val resolvedCategoryId = requestedCategoryId.takeIf { categoryId ->
+ categoryId == ChannelRepository.ALL_CHANNELS_ID || providerCategories.any { it.id == categoryId }
+ } ?: ChannelRepository.ALL_CHANNELS_ID
+
+ _uiState.update {
+ it.copy(
+ currentProviderName = provider.name,
+ providerSourceLabel = when (provider.type) {
+ com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"
+ com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"
+ },
+ providerArchiveSummary = buildProviderArchiveSummary(provider),
+ categories = categories,
+ selectedCategoryId = resolvedCategoryId,
+ showScheduledOnly = request.scheduledOnly,
+ selectedChannelMode = request.channelMode,
+ selectedDensity = request.density,
+ showFavoritesOnly = request.favoritesOnly,
+ guideAnchorTime = anchorTime,
+ guideWindowStart = anchorTime - LOOKBACK_MS,
+ guideWindowEnd = anchorTime + LOOKAHEAD_MS,
+ isLoading = true,
+ error = null
+ )
+ }
+
+ val channelsFlow = if (resolvedCategoryId == ChannelRepository.ALL_CHANNELS_ID) {
+ channelRepository.getChannels(provider.id)
+ } else {
+ channelRepository.getChannelsByCategory(provider.id, resolvedCategoryId)
+ }
+
+ combine(
+ channelsFlow,
+ favoriteRepository.getFavorites(ContentType.LIVE)
+ ) { channels, favorites ->
+ val favoriteIds = favorites.map { it.contentId }.toSet()
+ if (!request.favoritesOnly) {
+ GuideChannelSelection(
+ channels = channels,
+ favoriteChannelIds = favoriteIds
+ )
+ } else {
+ GuideChannelSelection(
+ channels = channels.filter { it.id in favoriteIds },
+ favoriteChannelIds = favoriteIds
+ )
+ }
+ }.collectLatest { channelSelection ->
+ val visibleChannels = channelSelection.channels.take(MAX_CHANNELS)
+ val windowStart = anchorTime - LOOKBACK_MS
+ val windowEnd = anchorTime + LOOKAHEAD_MS
+ val guideResult = loadGuidePrograms(provider.id, visibleChannels, windowStart, windowEnd)
+ val now = System.currentTimeMillis()
+ val channelsWithSchedule = guideResult.programsByChannel.count { it.value.isNotEmpty() }
+ val hasUpcomingData = guideResult.programsByChannel.values.flatten().any { program ->
+ program.endTime > windowStart
+ }
+ val displayChannels = visibleChannels.filter { channel ->
+ val programs = channel.epgChannelId?.let { epgId ->
+ guideResult.programsByChannel[epgId].orEmpty()
+ }.orEmpty()
+ val matchesScheduled = !request.scheduledOnly || programs.isNotEmpty()
+ val matchesMode = when (request.channelMode) {
+ GuideChannelMode.ALL -> true
+ GuideChannelMode.ANCHORED -> programs.any { program ->
+ request.anchorTime in program.startTime until program.endTime
+ }
+ GuideChannelMode.ARCHIVE_READY -> {
+ channel.catchUpSupported || programs.any { it.hasArchive }
}
}
- } else {
- _uiState.update { it.copy(isLoading = false, channels = emptyList()) }
+ matchesScheduled && matchesMode
+ }
+
+ _uiState.update {
+ it.copy(
+ favoriteChannelIds = channelSelection.favoriteChannelIds,
+ channels = displayChannels,
+ programsByChannel = guideResult.programsByChannel,
+ isLoading = false,
+ error = null,
+ totalChannelCount = channelSelection.channels.size,
+ channelsWithSchedule = channelsWithSchedule,
+ failedScheduleCount = guideResult.failedCount,
+ lastUpdatedAt = now,
+ isGuideStale = visibleChannels.isNotEmpty() && (channelsWithSchedule == 0 || !hasUpcomingData),
+ guideAnchorTime = request.anchorTime,
+ guideWindowStart = windowStart,
+ guideWindowEnd = windowEnd
+ )
}
}
- } ?: run {
- _uiState.update { it.copy(isLoading = false, error = "No active provider") }
- }
- } catch (e: Exception) {
- _uiState.update {
- it.copy(
- isLoading = false,
- error = e.message ?: "Failed to load EPG data"
- )
}
}
}
}
+
+ private fun restoreGuidePreferences() {
+ viewModelScope.launch {
+ preferencesRepository.guideDensity.first()
+ ?.let { saved ->
+ GuideDensity.entries.firstOrNull { it.name == saved }?.let { density ->
+ selectedDensity.value = density
+ }
+ }
+ preferencesRepository.guideChannelMode.first()
+ ?.let { saved ->
+ GuideChannelMode.entries.firstOrNull { it.name == saved }?.let { mode ->
+ selectedChannelMode.value = mode
+ }
+ }
+ showFavoritesOnly.value = preferencesRepository.guideFavoritesOnly.first()
+ preferencesRepository.guideAnchorTime.first()
+ ?.takeIf { it > 0L }
+ ?.let { guideAnchorTime.value = it }
+ }
+ }
+
+ private fun buildProviderArchiveSummary(provider: com.streamvault.domain.model.Provider): String {
+ return when (provider.type) {
+ com.streamvault.domain.model.ProviderType.XTREAM_CODES ->
+ "Xtream replay depends on archive-enabled channels and valid replay stream ids from the provider."
+ com.streamvault.domain.model.ProviderType.M3U ->
+ if (provider.epgUrl.isBlank()) {
+ "M3U replay is limited: archive depends on provider templates and guide coverage is weaker without XMLTV."
+ } else {
+ "M3U replay depends on the provider catch-up template and matching guide data."
+ }
+ }
+ }
+
+ private fun updateGuideAnchorTime(anchorTimeMs: Long) {
+ guideAnchorTime.value = anchorTimeMs
+ viewModelScope.launch {
+ preferencesRepository.setGuideAnchorTime(anchorTimeMs)
+ }
+ }
+
+ private suspend fun loadGuidePrograms(
+ providerId: Long,
+ channels: List<Channel>,
+ windowStart: Long,
+ windowEnd: Long
+ ): GuideProgramsResult {
+ if (channels.isEmpty()) {
+ return GuideProgramsResult(emptyMap(), failedCount = 0)
+ }
+
+ val deferredResults = coroutineScope {
+ channels
+ .mapNotNull { channel ->
+ channel.epgChannelId?.let { epgId -> epgId }
+ }
+ .map { epgId ->
+ async {
+ val programs = runCatching {
+ epgRepository
+ .getProgramsForChannel(providerId, epgId, windowStart, windowEnd)
+ .first()
+ }.getOrElse { emptyList() }
+
+ val failed = programs.isEmpty()
+ Triple(epgId, programs, failed)
+ }
+ }
+ .awaitAll()
+ }
+
+ return GuideProgramsResult(
+ programsByChannel = deferredResults.associate { (epgId, programs, _) -> epgId to programs },
+ failedCount = deferredResults.count { (_, _, failed) -> failed }
+ )
+ }
+
}
+
+private data class GuideRequest(
+ val categories: List<Category>,
+ val requestedCategoryId: Long,
+ val anchorTime: Long,
+ val scheduledOnly: Boolean,
+ val channelMode: GuideChannelMode,
+ val density: GuideDensity,
+ val favoritesOnly: Boolean
+)
+
+private data class GuideSelectionState(
+ val requestedCategoryId: Long,
+ val anchorTime: Long,
+ val scheduledOnly: Boolean,
+ val channelMode: GuideChannelMode,
+ val density: GuideDensity,
+ val favoritesOnly: Boolean
+)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt
index 902ddf32..ed8f1b1d 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt
@@ -7,259 +7,1206 @@ import androidx.compose.animation.fadeIn
import androidx.compose.animation.fadeOut
import androidx.compose.animation.slideInHorizontally
import androidx.compose.animation.slideOutHorizontally
-import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
-import androidx.compose.foundation.layout.*
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
-import androidx.compose.runtime.*
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.collectAsState
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.rememberCoroutineScope
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.SnackbarHostState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.input.key.*
+import androidx.compose.ui.input.key.KeyEventType
+import androidx.compose.ui.input.key.onKeyEvent
+import androidx.compose.ui.input.key.type
+import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
-import androidx.tv.material3.*
+import androidx.tv.material3.Border
+import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Surface
+import androidx.tv.material3.SurfaceDefaults
+import androidx.tv.material3.Text
+import com.streamvault.app.R
+import com.streamvault.app.ui.components.SelectionChip
+import com.streamvault.app.ui.components.SelectionChipRow
import com.streamvault.app.ui.components.TopNavBar
-import com.streamvault.app.ui.theme.*
+import com.streamvault.app.ui.theme.CardBackground
+import com.streamvault.app.ui.theme.OnBackground
+import com.streamvault.app.ui.theme.OnPrimary
+import com.streamvault.app.ui.theme.OnSurface
+import com.streamvault.app.ui.theme.OnSurfaceDim
+import com.streamvault.app.ui.theme.Primary
+import com.streamvault.app.ui.theme.SurfaceElevated
+import com.streamvault.app.ui.theme.SurfaceHighlight
import com.streamvault.domain.model.ContentType
-import androidx.compose.ui.res.stringResource
-import com.streamvault.app.R
+import kotlinx.coroutines.launch
+
@Composable
fun FavoritesScreen(
onItemClick: (FavoriteUiModel) -> Unit,
+ onHistoryClick: (SavedHistoryUiModel) -> Unit,
onNavigate: (String) -> Unit,
currentRoute: String,
viewModel: FavoritesViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsState()
+ val activeReorderSection = uiState.sections.firstOrNull { it.key == uiState.reorderSectionKey }
+ val listState = rememberLazyListState()
+ val scope = rememberCoroutineScope()
+ val snackbarHostState = remember { SnackbarHostState() }
+ val homeShelfGlobalTitle = stringResource(R.string.saved_preset_home_shelf_global_title)
+ val homeShelfGlobalSubtitle = stringResource(R.string.saved_preset_home_shelf_global_subtitle)
+ val providerScopedSections = remember(
+ uiState.sections,
+ uiState.selectedPreset,
+ uiState.selectedProviderScope,
+ uiState.activeProviderId,
+ uiState.managedGroups,
+ homeShelfGlobalTitle,
+ homeShelfGlobalSubtitle
+ ) {
+ val presetSections = when (uiState.selectedPreset) {
+ SavedLibraryPreset.ALL_SAVED,
+ SavedLibraryPreset.WATCH_NEXT -> uiState.sections
+ SavedLibraryPreset.HOME_SHELF -> uiState.sections.mapNotNull { section ->
+ if (section.key == "global") {
+ val liveFavorites = section.items.filter { it.favorite.contentType == ContentType.LIVE }
+ if (liveFavorites.isEmpty()) null else section.copy(
+ title = homeShelfGlobalTitle,
+ subtitle = homeShelfGlobalSubtitle,
+ items = liveFavorites,
+ reorderable = liveFavorites.size > 1
+ )
+ } else {
+ val groupId = section.key.removePrefix("group:").toLongOrNull()
+ val managedGroup = uiState.managedGroups.firstOrNull { it.group.id == groupId }
+ if (managedGroup?.isPromotedOnHome == true) section else null
+ }
+ }
+ SavedLibraryPreset.LIVE_RECALL -> uiState.sections.filter { section ->
+ section.items.any { it.favorite.contentType == ContentType.LIVE }
+ }
+ SavedLibraryPreset.MOVIES -> uiState.sections.filter { section ->
+ section.items.any { it.favorite.contentType == ContentType.MOVIE }
+ }
+ SavedLibraryPreset.SERIES -> uiState.sections.filter { section ->
+ section.items.any { it.favorite.contentType == ContentType.SERIES }
+ }
+ SavedLibraryPreset.CUSTOM_GROUPS -> uiState.sections.filterNot { it.key == "global" }
+ }
+ if (uiState.selectedProviderScope != SavedLibraryProviderScope.CURRENT_PROVIDER || uiState.activeProviderId == null) {
+ presetSections
+ } else {
+ presetSections.mapNotNull { section ->
+ val scopedItems = section.items.filter { it.providerId == uiState.activeProviderId }
+ if (scopedItems.isEmpty()) {
+ null
+ } else {
+ section.copy(
+ subtitle = "${scopedItems.size} saved items",
+ items = scopedItems,
+ reorderable = section.reorderable && scopedItems.size > 1
+ )
+ }
+ }
+ }
+ }
+ val visibleContinueWatching = remember(uiState.continueWatching, uiState.selectedPreset, uiState.selectedProviderScope, uiState.activeProviderId) {
+ when (uiState.selectedPreset) {
+ SavedLibraryPreset.ALL_SAVED,
+ SavedLibraryPreset.WATCH_NEXT -> uiState.continueWatching
+ SavedLibraryPreset.MOVIES -> uiState.continueWatching.filter { it.history.contentType == ContentType.MOVIE }
+ SavedLibraryPreset.SERIES -> uiState.continueWatching.filter {
+ it.history.contentType == ContentType.SERIES || it.history.contentType == ContentType.SERIES_EPISODE
+ }
+ else -> emptyList()
+ }.let { items ->
+ if (uiState.selectedProviderScope == SavedLibraryProviderScope.CURRENT_PROVIDER && uiState.activeProviderId != null) {
+ items.filter { it.providerId == uiState.activeProviderId }
+ } else {
+ items
+ }
+ }
+ }
+ val visibleRecentLive = remember(uiState.recentLive, uiState.selectedPreset, uiState.selectedProviderScope, uiState.activeProviderId) {
+ when (uiState.selectedPreset) {
+ SavedLibraryPreset.ALL_SAVED,
+ SavedLibraryPreset.LIVE_RECALL,
+ SavedLibraryPreset.HOME_SHELF -> uiState.recentLive
+ else -> emptyList()
+ }.let { items ->
+ if (uiState.selectedProviderScope == SavedLibraryProviderScope.CURRENT_PROVIDER && uiState.activeProviderId != null) {
+ items.filter { it.providerId == uiState.activeProviderId }
+ } else {
+ items
+ }
+ }
+ }
+ val filteredSections = remember(providerScopedSections, uiState.selectedFilter, uiState.selectedSort, uiState.isReorderMode) {
+ providerScopedSections
+ .mapNotNull { section ->
+ val filteredItems = when (uiState.selectedFilter) {
+ SavedLibraryFilter.ALL -> section.items
+ SavedLibraryFilter.LIVE -> section.items.filter { it.favorite.contentType == ContentType.LIVE }
+ SavedLibraryFilter.MOVIE -> section.items.filter { it.favorite.contentType == ContentType.MOVIE }
+ SavedLibraryFilter.SERIES -> section.items.filter { it.favorite.contentType == ContentType.SERIES }
+ }
+ if (filteredItems.isEmpty()) {
+ null
+ } else {
+ val sortedItems = if (uiState.isReorderMode) {
+ filteredItems
+ } else {
+ when (uiState.selectedSort) {
+ SavedLibrarySort.DEFAULT -> filteredItems
+ SavedLibrarySort.RECENT -> filteredItems.sortedByDescending { it.lastWatchedAt }
+ SavedLibrarySort.TITLE -> filteredItems.sortedBy { it.title.lowercase() }
+ }
+ }
+ section.copy(
+ subtitle = "${sortedItems.size} saved items",
+ items = sortedItems,
+ reorderable = section.reorderable && filteredItems.size > 1
+ )
+ }
+ }
+ .let { sections ->
+ if (uiState.isReorderMode || uiState.selectedSort == SavedLibrarySort.DEFAULT) {
+ sections
+ } else {
+ sections.sortedByDescending { section ->
+ when (uiState.selectedSort) {
+ SavedLibrarySort.RECENT -> section.items.maxOfOrNull { it.lastWatchedAt } ?: 0L
+ SavedLibrarySort.TITLE -> 0L
+ SavedLibrarySort.DEFAULT -> 0L
+ }
+ }.let { recentSorted ->
+ if (uiState.selectedSort == SavedLibrarySort.TITLE) {
+ sections.sortedBy { it.title.lowercase() }
+ } else {
+ recentSorted
+ }
+ }
+ }
+ }
+ }
+ val providerScopedSummary = remember(filteredSections, providerScopedSections, visibleContinueWatching, visibleRecentLive) {
+ val globalItems = providerScopedSections.firstOrNull { it.key == "global" }?.items.orEmpty()
+ SavedLibrarySummary(
+ totalItems = globalItems.size,
+ liveCount = globalItems.count { it.favorite.contentType == ContentType.LIVE },
+ movieCount = globalItems.count { it.favorite.contentType == ContentType.MOVIE },
+ seriesCount = globalItems.count { it.favorite.contentType == ContentType.SERIES },
+ customGroupCount = providerScopedSections.count { it.key != "global" },
+ continueWatchingCount = visibleContinueWatching.size,
+ recentLiveCount = visibleRecentLive.size
+ )
+ }
+ val providerScopedPresetSummary = remember(providerScopedSections, visibleContinueWatching, visibleRecentLive) {
+ val globalItems = providerScopedSections.firstOrNull { it.key == "global" }?.items.orEmpty()
+ SavedLibraryPresetSummary(
+ allSavedCount = globalItems.size,
+ watchNextCount = visibleContinueWatching.size,
+ liveRecallCount = visibleRecentLive.size,
+ movieCount = globalItems.count { it.favorite.contentType == ContentType.MOVIE },
+ seriesCount = globalItems.count { it.favorite.contentType == ContentType.SERIES },
+ customGroupCount = providerScopedSections.count { it.key != "global" }
+ )
+ }
+ val visibleManagedGroups = remember(uiState.managedGroups, providerScopedSections, uiState.selectedProviderScope, uiState.activeProviderId) {
+ val scopedSectionCounts = providerScopedSections
+ .filter { it.key.startsWith("group:") }
+ .associate { section ->
+ section.key.removePrefix("group:").toLongOrNull() to section.items.size
+ }
+ uiState.managedGroups.mapNotNull { group ->
+ val scopedCount = scopedSectionCounts[group.group.id]
+ if (uiState.selectedProviderScope == SavedLibraryProviderScope.CURRENT_PROVIDER && uiState.activeProviderId != null) {
+ if (scopedCount == null || scopedCount == 0) {
+ null
+ } else {
+ group.copy(itemCount = scopedCount)
+ }
+ } else {
+ group
+ }
+ }
+ }
+ val sectionBaseIndex = 5 +
+ (if (visibleContinueWatching.isNotEmpty()) 1 else 0) +
+ (if (visibleRecentLive.isNotEmpty()) 1 else 0)
+ val sectionChipIndex = remember(filteredSections, sectionBaseIndex) {
+ buildMap {
+ var currentIndex = sectionBaseIndex
+ filteredSections.forEach { section ->
+ put(section.key, currentIndex)
+ currentIndex += 1 + section.items.size
+ }
+ }
+ }
+ val presetChips = listOf(
+ SelectionChip(
+ key = SavedLibraryPreset.ALL_SAVED.name,
+ label = stringResource(R.string.saved_preset_all_saved),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedPresetSummary.allSavedCount)
+ ),
+ SelectionChip(
+ key = SavedLibraryPreset.HOME_SHELF.name,
+ label = stringResource(R.string.saved_preset_home_shelf),
+ supportingText = stringResource(
+ R.string.library_saved_items_count,
+ visibleManagedGroups.count { it.isPromotedOnHome } + visibleRecentLive.size
+ )
+ ),
+ SelectionChip(
+ key = SavedLibraryPreset.WATCH_NEXT.name,
+ label = stringResource(R.string.saved_preset_watch_next),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedPresetSummary.watchNextCount)
+ ),
+ SelectionChip(
+ key = SavedLibraryPreset.LIVE_RECALL.name,
+ label = stringResource(R.string.saved_preset_live_recall),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedPresetSummary.liveRecallCount)
+ ),
+ SelectionChip(
+ key = SavedLibraryPreset.MOVIES.name,
+ label = stringResource(R.string.search_movies),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedPresetSummary.movieCount)
+ ),
+ SelectionChip(
+ key = SavedLibraryPreset.SERIES.name,
+ label = stringResource(R.string.search_series),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedPresetSummary.seriesCount)
+ ),
+ SelectionChip(
+ key = SavedLibraryPreset.CUSTOM_GROUPS.name,
+ label = stringResource(R.string.saved_preset_custom_groups),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedPresetSummary.customGroupCount)
+ )
+ )
+ val providerScopeChips = listOf(
+ SelectionChip(
+ key = SavedLibraryProviderScope.CURRENT_PROVIDER.name,
+ label = uiState.activeProviderName ?: stringResource(R.string.saved_scope_current_provider),
+ supportingText = stringResource(R.string.saved_scope_current_provider_hint)
+ ),
+ SelectionChip(
+ key = SavedLibraryProviderScope.ALL_PROVIDERS.name,
+ label = stringResource(R.string.saved_scope_all_providers),
+ supportingText = stringResource(R.string.saved_scope_all_providers_hint)
+ )
+ )
+ val filterChips = listOf(
+ SelectionChip(
+ key = SavedLibraryFilter.ALL.name,
+ label = stringResource(R.string.search_all),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedSummary.totalItems)
+ ),
+ SelectionChip(
+ key = SavedLibraryFilter.LIVE.name,
+ label = stringResource(R.string.search_live_tv),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedSummary.liveCount)
+ ),
+ SelectionChip(
+ key = SavedLibraryFilter.MOVIE.name,
+ label = stringResource(R.string.search_movies),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedSummary.movieCount)
+ ),
+ SelectionChip(
+ key = SavedLibraryFilter.SERIES.name,
+ label = stringResource(R.string.search_series),
+ supportingText = stringResource(R.string.library_saved_items_count, providerScopedSummary.seriesCount)
+ )
+ )
Column(modifier = Modifier.fillMaxSize()) {
TopNavBar(currentRoute = currentRoute, onNavigate = onNavigate)
- if (uiState.isLoading) {
- Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- Text(stringResource(R.string.favorites_loading), style = MaterialTheme.typography.bodyLarge, color = OnSurface)
- }
- } else if (uiState.favorites.isEmpty()) {
- Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- Column(horizontalAlignment = Alignment.CenterHorizontally) {
- Text("⭐", style = MaterialTheme.typography.displayLarge)
- Spacer(Modifier.height(8.dp))
- Text(stringResource(R.string.favorites_no_favorites), style = MaterialTheme.typography.bodyLarge, color = OnSurface)
+ when {
+ uiState.isLoading -> {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
Text(
- stringResource(R.string.favorites_empty_hint),
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
+ text = stringResource(R.string.favorites_loading),
+ style = MaterialTheme.typography.bodyLarge,
+ color = OnSurface
)
}
}
- } else {
- Box(modifier = Modifier.fillMaxSize()) {
- // Main favorites list
- LazyColumn(
- modifier = Modifier.fillMaxSize(),
- contentPadding = PaddingValues(32.dp),
- verticalArrangement = Arrangement.spacedBy(8.dp)
- ) {
- // Virtual groups
- if (uiState.groups.isNotEmpty()) {
- items(uiState.groups, key = { it.id }) { group ->
- Text(
- text = "${group.iconEmoji ?: "📁"} ${group.name}",
- style = MaterialTheme.typography.titleMedium,
- color = OnBackground,
- modifier = Modifier.padding(vertical = 8.dp)
+
+ uiState.sections.isEmpty() -> {
+ Box(Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(
+ text = stringResource(R.string.favorites_no_favorites),
+ style = MaterialTheme.typography.titleLarge,
+ color = OnSurface
+ )
+ Spacer(Modifier.height(8.dp))
+ Text(
+ text = stringResource(R.string.favorites_empty_hint),
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+
+ else -> {
+ Box(modifier = Modifier.fillMaxSize()) {
+ LazyColumn(
+ state = listState,
+ modifier = Modifier.fillMaxSize(),
+ contentPadding = PaddingValues(32.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ item(key = "summary") {
+ SavedLibrarySummaryCard(
+ summary = providerScopedSummary,
+ currentFilter = uiState.selectedFilter
)
}
- }
- // All favorites
- items(uiState.favorites, key = { it.favorite.id }) { item ->
- val isReorderingThis = uiState.isReorderMode && uiState.reorderItem?.id == item.favorite.id
- val scale by animateFloatAsState(if (isReorderingThis) 1.05f else 1f)
-
- Surface(
- onClick = {
- if (uiState.isReorderMode) {
- if (isReorderingThis) viewModel.saveReorder()
- } else {
- if (item.favorite.contentType == ContentType.SERIES) {
- onNavigate("series_detail/${item.favorite.contentId}")
- } else {
- onItemClick(item)
- }
- }
- },
- onLongClick = {
- viewModel.enterReorderMode(item)
- },
- modifier = Modifier
- .fillMaxWidth()
- .height(56.dp)
- .scale(scale)
- .then(
- if (isReorderingThis) {
- Modifier.onKeyEvent { event ->
- if (event.type == KeyEventType.KeyDown) {
- when (event.nativeKeyEvent.keyCode) {
- android.view.KeyEvent.KEYCODE_DPAD_UP -> {
- viewModel.moveItem(-1)
- true
- }
- android.view.KeyEvent.KEYCODE_DPAD_DOWN -> {
- viewModel.moveItem(1)
- true
- }
- android.view.KeyEvent.KEYCODE_DPAD_CENTER, android.view.KeyEvent.KEYCODE_ENTER -> {
- viewModel.saveReorder()
- true
- }
- android.view.KeyEvent.KEYCODE_BACK -> {
- viewModel.exitReorderMode()
- true
- }
- else -> false
- }
- } else false
- }
- } else Modifier
+ item(key = "provider_scope") {
+ SelectionChipRow(
+ title = stringResource(R.string.saved_scope_title),
+ subtitle = stringResource(
+ R.string.saved_scope_subtitle,
+ uiState.activeProviderName ?: stringResource(R.string.settings_overview_no_provider)
),
- shape = ClickableSurfaceDefaults.shape(
- RoundedCornerShape(8.dp)
- ),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = if (isReorderingThis) Primary.copy(alpha = 0.2f) else SurfaceElevated,
- focusedContainerColor = if (isReorderingThis) Primary else SurfaceHighlight,
- contentColor = if (isReorderingThis) Primary else OnSurface,
- focusedContentColor = if (isReorderingThis) OnPrimary else OnSurface
- ),
- border = ClickableSurfaceDefaults.border(
- border = Border(
- border = BorderStroke(
- width = if (isReorderingThis) 2.dp else 0.dp,
- color = if (isReorderingThis) Primary else Color.Transparent
+ chips = providerScopeChips,
+ selectedKey = uiState.selectedProviderScope.name,
+ onChipSelected = { key ->
+ SavedLibraryProviderScope.entries.firstOrNull { it.name == key }?.let(viewModel::selectProviderScope)
+ },
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ }
+
+ item(key = "filters") {
+ SelectionChipRow(
+ title = stringResource(R.string.saved_preset_title),
+ subtitle = stringResource(R.string.saved_preset_subtitle),
+ chips = presetChips,
+ selectedKey = uiState.selectedPreset.name,
+ onChipSelected = { key ->
+ SavedLibraryPreset.entries
+ .firstOrNull { it.name == key }
+ ?.let(viewModel::selectPreset)
+ },
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ }
+
+ item(key = "filter_types") {
+ SelectionChipRow(
+ title = stringResource(R.string.favorites_filters_title),
+ subtitle = stringResource(R.string.favorites_filters_subtitle),
+ chips = filterChips,
+ selectedKey = uiState.selectedFilter.name,
+ onChipSelected = { key ->
+ SavedLibraryFilter.entries
+ .firstOrNull { it.name == key }
+ ?.let(viewModel::selectFilter)
+ },
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ }
+
+ item(key = "sorts") {
+ SelectionChipRow(
+ title = stringResource(R.string.favorites_sort_title),
+ subtitle = stringResource(R.string.favorites_sort_subtitle),
+ chips = listOf(
+ SelectionChip(
+ key = SavedLibrarySort.DEFAULT.name,
+ label = stringResource(R.string.favorites_sort_default),
+ supportingText = stringResource(R.string.favorites_sort_default_hint)
+ ),
+ SelectionChip(
+ key = SavedLibrarySort.RECENT.name,
+ label = stringResource(R.string.favorites_sort_recent),
+ supportingText = stringResource(R.string.favorites_sort_recent_hint)
+ ),
+ SelectionChip(
+ key = SavedLibrarySort.TITLE.name,
+ label = stringResource(R.string.favorites_sort_title_alpha),
+ supportingText = stringResource(R.string.favorites_sort_title_hint)
)
- )
+ ),
+ selectedKey = uiState.selectedSort.name,
+ onChipSelected = { key ->
+ SavedLibrarySort.entries.firstOrNull { it.name == key }?.let(viewModel::selectSort)
+ },
+ contentPadding = PaddingValues(horizontal = 0.dp)
)
- ) {
- Row(
- modifier = Modifier
- .fillMaxSize()
- .padding(horizontal = 16.dp),
- verticalAlignment = Alignment.CenterVertically
- ) {
+ }
+
+ if (visibleManagedGroups.isNotEmpty()) {
+ item(key = "group_management") {
+ SavedGroupManagementRow(
+ groups = visibleManagedGroups,
+ onGroupClick = { group ->
+ scope.launch {
+ val itemIndex = sectionChipIndex["group:${group.group.id}"]
+ if (itemIndex != null) {
+ listState.animateScrollToItem(itemIndex)
+ } else {
+ when (group.group.contentType) {
+ ContentType.LIVE -> viewModel.selectPreset(SavedLibraryPreset.LIVE_RECALL)
+ ContentType.MOVIE -> viewModel.selectPreset(SavedLibraryPreset.MOVIES)
+ ContentType.SERIES -> viewModel.selectPreset(SavedLibraryPreset.SERIES)
+ ContentType.SERIES_EPISODE -> Unit
+ }
+ }
+ }
+ },
+ onGroupLongClick = viewModel::showGroupOptions
+ )
+ }
+ }
+
+ if (visibleContinueWatching.isNotEmpty()) {
+ item(key = "continue_watching") {
+ SavedHistoryRow(
+ title = stringResource(R.string.favorites_continue_title),
+ subtitle = stringResource(R.string.favorites_continue_subtitle),
+ items = visibleContinueWatching,
+ onItemClick = onHistoryClick
+ )
+ }
+ }
+
+ if (visibleRecentLive.isNotEmpty()) {
+ item(key = "recent_live") {
+ SavedHistoryRow(
+ title = stringResource(R.string.favorites_recent_live_title),
+ subtitle = stringResource(R.string.favorites_recent_live_subtitle),
+ items = visibleRecentLive,
+ onItemClick = onHistoryClick
+ )
+ }
+ }
+
+ if (filteredSections.isNotEmpty()) {
+ item(key = "jumps") {
+ SelectionChipRow(
+ title = stringResource(R.string.favorites_jump_title),
+ subtitle = stringResource(R.string.favorites_jump_subtitle),
+ chips = filteredSections.map { section ->
+ SelectionChip(
+ key = section.key,
+ label = section.title,
+ supportingText = stringResource(
+ R.string.library_saved_items_count,
+ section.items.size
+ )
+ )
+ },
+ selectedKey = null,
+ onChipSelected = { key ->
+ val itemIndex = sectionChipIndex[key]
+ if (itemIndex != null) {
+ scope.launch {
+ listState.animateScrollToItem(itemIndex)
+ }
+ }
+ },
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ }
+ } else {
+ item(key = "filtered_empty") {
Text(
- text = item.title,
- style = MaterialTheme.typography.bodyMedium,
- color = if (isReorderingThis) Primary else OnSurface
+ text = stringResource(R.string.library_filter_empty),
+ style = MaterialTheme.typography.bodyLarge,
+ color = OnSurfaceDim
)
- Spacer(Modifier.weight(1f))
- if (isReorderingThis) {
- Text("↕ " + stringResource(R.string.favorites_reordering), style = MaterialTheme.typography.bodySmall, color = Primary)
- } else {
- Text(
- text = item.subtitle ?: "",
- style = MaterialTheme.typography.bodySmall,
- color = OnSurfaceDim
- )
- }
}
}
+
+ filteredSections.forEach { section ->
+ item(key = "header:${section.key}") {
+ FavoriteSectionHeader(section = section)
+ }
+
+ items(
+ items = section.items,
+ key = { item -> "${section.key}:${item.favorite.id}" }
+ ) { item ->
+ FavoriteRow(
+ item = item,
+ isReorderMode = uiState.isReorderMode,
+ isReorderingThis = uiState.isReorderMode && uiState.reorderItem?.id == item.favorite.id,
+ onClick = {
+ if (uiState.isReorderMode) {
+ if (uiState.reorderItem?.id == item.favorite.id) {
+ viewModel.saveReorder()
+ }
+ } else if (item.favorite.contentType == ContentType.SERIES) {
+ onNavigate("series_detail/${item.favorite.contentId}")
+ } else {
+ onItemClick(item)
+ }
+ },
+ onLongClick = { viewModel.showItemOptions(item) },
+ onMoveUp = { viewModel.moveItem(-1) },
+ onMoveDown = { viewModel.moveItem(1) },
+ onConfirm = { viewModel.saveReorder() },
+ onCancel = { viewModel.exitReorderMode() }
+ )
+ }
+ }
+ }
+
+ androidx.compose.animation.AnimatedVisibility(
+ visible = uiState.isReorderMode && activeReorderSection != null,
+ enter = slideInHorizontally(initialOffsetX = { it }) + fadeIn(),
+ exit = slideOutHorizontally(targetOffsetX = { it }) + fadeOut(),
+ modifier = Modifier
+ .align(Alignment.TopEnd)
+ .padding(top = 24.dp)
+ ) {
+ ReorderPanel(
+ section = activeReorderSection,
+ movingFavoriteId = uiState.reorderItem?.id
+ )
+ }
+
+ SnackbarHost(
+ hostState = snackbarHostState,
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .padding(bottom = 18.dp)
+ )
+ }
+ }
+ }
+ }
+
+ androidx.compose.runtime.LaunchedEffect(uiState.userMessage) {
+ uiState.userMessage?.let { message ->
+ snackbarHostState.showSnackbar(message)
+ viewModel.userMessageShown()
+ }
+ }
+
+ uiState.itemDialogItem?.let { item ->
+ SavedItemOptionsDialog(
+ item = item,
+ moveTargets = uiState.itemMoveTargets,
+ onDismiss = viewModel::dismissSavedDialog,
+ onRemove = { viewModel.removeFromSavedContext(item) },
+ onMoveToGroup = viewModel::moveItemToGroup
+ )
+ }
+
+ uiState.managedGroupDialog?.let { group ->
+ SavedGroupOptionsDialog(
+ group = group,
+ canMerge = visibleManagedGroups.any {
+ it.group.contentType == group.group.contentType && it.group.id != group.group.id
+ },
+ onDismiss = viewModel::dismissSavedDialog,
+ onReorder = {
+ val section = uiState.sections.firstOrNull { it.key == "group:${group.group.id}" }
+ val firstItem = section?.items?.firstOrNull()
+ if (section != null && firstItem != null) {
+ viewModel.enterReorderMode(section.key, firstItem)
+ }
+ viewModel.dismissSavedDialog()
+ },
+ onTogglePromotion = if (group.group.contentType == ContentType.LIVE) {
+ { viewModel.toggleHomePromotion(group) }
+ } else null,
+ onMerge = { viewModel.startMergeGroup(group) },
+ onDelete = { viewModel.deleteManagedGroup(group) }
+ )
+ }
+
+ uiState.mergeSourceGroup?.let { source ->
+ MergeSavedGroupDialog(
+ source = source,
+ targets = uiState.mergeTargetCandidates,
+ onDismiss = viewModel::dismissSavedDialog,
+ onTargetSelected = viewModel::mergeGroupInto
+ )
+ }
+
+ if (uiState.isReorderMode) {
+ BackHandler(onBack = viewModel::exitReorderMode)
+ }
+}
+
+@Composable
+private fun SavedLibrarySummaryCard(
+ summary: SavedLibrarySummary,
+ currentFilter: SavedLibraryFilter
+) {
+ Surface(
+ modifier = Modifier.fillMaxWidth(),
+ shape = RoundedCornerShape(18.dp),
+ colors = androidx.tv.material3.SurfaceDefaults.colors(containerColor = SurfaceElevated)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 24.dp, vertical = 20.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.favorites_overview_title),
+ style = MaterialTheme.typography.titleLarge,
+ color = OnSurface
+ )
+ Text(
+ text = stringResource(
+ R.string.favorites_overview_subtitle,
+ summary.totalItems,
+ summary.customGroupCount
+ ),
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ SavedLibraryStatPill(
+ label = stringResource(R.string.search_live_tv),
+ value = summary.liveCount,
+ highlighted = currentFilter == SavedLibraryFilter.LIVE
+ )
+ SavedLibraryStatPill(
+ label = stringResource(R.string.search_movies),
+ value = summary.movieCount,
+ highlighted = currentFilter == SavedLibraryFilter.MOVIE
+ )
+ SavedLibraryStatPill(
+ label = stringResource(R.string.search_series),
+ value = summary.seriesCount,
+ highlighted = currentFilter == SavedLibraryFilter.SERIES
+ )
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ SavedLibraryStatPill(
+ label = stringResource(R.string.favorites_continue_short),
+ value = summary.continueWatchingCount,
+ highlighted = false
+ )
+ SavedLibraryStatPill(
+ label = stringResource(R.string.favorites_recent_short),
+ value = summary.recentLiveCount,
+ highlighted = false
+ )
+ }
+ }
+ }
+}
+
+@Composable
+private fun SavedLibraryStatPill(
+ label: String,
+ value: Int,
+ highlighted: Boolean
+) {
+ Surface(
+ shape = RoundedCornerShape(999.dp),
+ colors = SurfaceDefaults.colors(
+ containerColor = if (highlighted) Primary.copy(alpha = 0.18f) else SurfaceHighlight
+ )
+ ) {
+ Text(
+ text = "$label $value",
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
+ style = MaterialTheme.typography.labelLarge,
+ color = if (highlighted) Primary else OnSurface
+ )
+ }
+}
+
+@Composable
+private fun FavoriteSectionHeader(section: FavoriteSectionUiModel) {
+ Column(modifier = Modifier.padding(top = 6.dp, bottom = 4.dp)) {
+ Text(
+ text = section.title,
+ style = MaterialTheme.typography.titleMedium,
+ color = OnBackground
+ )
+ Text(
+ text = section.subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+}
+
+@Composable
+private fun SavedHistoryRow(
+ title: String,
+ subtitle: String,
+ items: List<SavedHistoryUiModel>,
+ onItemClick: (SavedHistoryUiModel) -> Unit
+) {
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleMedium,
+ color = OnBackground
+ )
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ androidx.compose.foundation.lazy.LazyRow(
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ contentPadding = PaddingValues(vertical = 4.dp)
+ ) {
+ items(items, key = { "${it.history.contentType}:${it.history.contentId}" }) { item ->
+ Surface(
+ onClick = { onItemClick(item) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = CardBackground,
+ focusedContainerColor = SurfaceHighlight,
+ contentColor = OnSurface,
+ focusedContentColor = OnSurface
+ ),
+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1.04f),
+ modifier = Modifier.width(250.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
+ ) {
+ Text(
+ text = item.title,
+ style = MaterialTheme.typography.titleSmall,
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = item.subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
}
}
+ }
+ }
+ }
+}
- // Reorder mode hint — compact top-right corner overlay
- androidx.compose.animation.AnimatedVisibility(
- visible = uiState.isReorderMode,
- enter = slideInHorizontally(initialOffsetX = { it }) + fadeIn(),
- exit = slideOutHorizontally(targetOffsetX = { it }) + fadeOut(),
- modifier = Modifier.align(Alignment.TopEnd).padding(top = 24.dp)
+@Composable
+private fun SavedGroupManagementRow(
+ groups: List<SavedGroupManagementUiModel>,
+ onGroupClick: (SavedGroupManagementUiModel) -> Unit,
+ onGroupLongClick: (SavedGroupManagementUiModel) -> Unit
+) {
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.saved_group_manage_title),
+ style = MaterialTheme.typography.titleMedium,
+ color = OnBackground
+ )
+ Text(
+ text = stringResource(R.string.saved_group_manage_subtitle),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ androidx.compose.foundation.lazy.LazyRow(
+ horizontalArrangement = Arrangement.spacedBy(10.dp),
+ contentPadding = PaddingValues(vertical = 4.dp)
+ ) {
+ items(groups, key = { "group-manage:${it.group.id}" }) { group ->
+ Surface(
+ onClick = { onGroupClick(group) },
+ onLongClick = { onGroupLongClick(group) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(14.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = CardBackground,
+ focusedContainerColor = SurfaceHighlight
+ ),
+ modifier = Modifier.width(240.dp)
) {
Column(
- modifier = Modifier
- .width(220.dp)
- .heightIn(max = 280.dp)
- .background(CardBackground.copy(alpha = 0.97f), RoundedCornerShape(topStart = 12.dp, bottomStart = 12.dp))
- .padding(16.dp),
- verticalArrangement = Arrangement.spacedBy(10.dp)
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 14.dp),
+ verticalArrangement = Arrangement.spacedBy(6.dp)
) {
- // Header
Text(
- text = "↕ Reorder Mode",
+ text = group.group.name,
style = MaterialTheme.typography.titleSmall,
- color = Primary
+ color = OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
)
+ Text(
+ text = if (group.isPromotedOnHome) {
+ stringResource(R.string.saved_group_manage_promoted, group.itemCount)
+ } else {
+ stringResource(R.string.saved_group_manage_count, group.itemCount)
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+ }
+ }
+}
- // Button hints
- Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
- ReorderHintRow(icon = "▲", label = "Move Up")
- ReorderHintRow(icon = "▼", label = "Move Down")
- ReorderHintRow(icon = "●", label = "Confirm")
- ReorderHintRow(icon = "← Back", label = "Cancel")
+@Composable
+private fun SavedItemOptionsDialog(
+ item: FavoriteUiModel,
+ moveTargets: List<SavedGroupManagementUiModel>,
+ onDismiss: () -> Unit,
+ onRemove: () -> Unit,
+ onMoveToGroup: (FavoriteUiModel, Long) -> Unit
+) {
+ androidx.compose.material3.AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { androidx.compose.material3.Text(item.title) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ androidx.tv.material3.Button(
+ onClick = onRemove,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(
+ text = if (item.favorite.groupId == null) {
+ stringResource(R.string.saved_item_remove_saved)
+ } else {
+ stringResource(R.string.saved_item_remove_group)
}
+ )
+ }
+ moveTargets.forEach { target ->
+ androidx.tv.material3.Button(
+ onClick = { onMoveToGroup(item, target.group.id) },
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(
+ text = stringResource(R.string.saved_item_move_to, target.group.name)
+ )
+ }
+ }
+ }
+ },
+ confirmButton = {},
+ dismissButton = {
+ androidx.compose.material3.TextButton(onClick = onDismiss) {
+ androidx.compose.material3.Text(stringResource(R.string.settings_cancel))
+ }
+ }
+ )
+}
- // Mini-map — only show up to 8 items to keep panel compact
- val movingId = uiState.reorderItem?.id
- Column(
- modifier = Modifier
- .background(SurfaceElevated.copy(alpha = 0.5f), RoundedCornerShape(6.dp))
- .padding(8.dp),
- verticalArrangement = Arrangement.spacedBy(3.dp)
- ) {
- uiState.favorites.take(10).forEach { item ->
- val isMoving = movingId == item.favorite.id
- Row(
- modifier = Modifier.fillMaxWidth(),
- verticalAlignment = Alignment.CenterVertically
- ) {
- Text(
- text = if (isMoving) "▶ " else " ",
- style = MaterialTheme.typography.labelSmall,
- color = Primary
- )
- Text(
- text = item.title,
- style = MaterialTheme.typography.labelSmall,
- color = if (isMoving) Primary else OnSurfaceDim,
- maxLines = 1,
- overflow = TextOverflow.Ellipsis,
- modifier = Modifier.weight(1f)
- )
- }
+@Composable
+private fun SavedGroupOptionsDialog(
+ group: SavedGroupManagementUiModel,
+ canMerge: Boolean,
+ onDismiss: () -> Unit,
+ onReorder: () -> Unit,
+ onTogglePromotion: (() -> Unit)?,
+ onMerge: () -> Unit,
+ onDelete: () -> Unit
+) {
+ androidx.compose.material3.AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { androidx.compose.material3.Text(group.group.name) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (group.itemCount > 1) {
+ androidx.tv.material3.Button(
+ onClick = onReorder,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(stringResource(R.string.category_options_reorder))
+ }
+ }
+ onTogglePromotion?.let { toggle ->
+ androidx.tv.material3.Button(
+ onClick = toggle,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(
+ text = if (group.isPromotedOnHome) {
+ stringResource(R.string.saved_group_demote_home)
+ } else {
+ stringResource(R.string.saved_group_promote_home)
}
+ )
+ }
+ }
+ if (canMerge) {
+ androidx.tv.material3.Button(
+ onClick = onMerge,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(stringResource(R.string.saved_group_merge))
+ }
+ }
+ androidx.tv.material3.Button(
+ onClick = onDelete,
+ modifier = Modifier.fillMaxWidth(),
+ colors = androidx.tv.material3.ButtonDefaults.colors(
+ containerColor = Color(0x44D32F2F),
+ contentColor = Color.White
+ )
+ ) {
+ Text(
+ text = if (group.itemCount == 0) {
+ stringResource(R.string.saved_group_delete_empty)
+ } else {
+ stringResource(R.string.category_options_delete)
}
+ )
+ }
+ }
+ },
+ confirmButton = {},
+ dismissButton = {
+ androidx.compose.material3.TextButton(onClick = onDismiss) {
+ androidx.compose.material3.Text(stringResource(R.string.settings_cancel))
+ }
+ }
+ )
+}
+
+@Composable
+private fun MergeSavedGroupDialog(
+ source: SavedGroupManagementUiModel,
+ targets: List<SavedGroupManagementUiModel>,
+ onDismiss: () -> Unit,
+ onTargetSelected: (Long) -> Unit
+) {
+ androidx.compose.material3.AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { androidx.compose.material3.Text(stringResource(R.string.saved_group_merge_title, source.group.name)) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ targets.forEach { target ->
+ androidx.tv.material3.Button(
+ onClick = { onTargetSelected(target.group.id) },
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(text = target.group.name)
}
}
}
+ },
+ confirmButton = {},
+ dismissButton = {
+ androidx.compose.material3.TextButton(onClick = onDismiss) {
+ androidx.compose.material3.Text(stringResource(R.string.settings_cancel))
+ }
}
- }
-
- if (uiState.isReorderMode) {
- BackHandler {
- viewModel.exitReorderMode()
+ )
+}
+
+@Composable
+private fun FavoriteRow(
+ item: FavoriteUiModel,
+ isReorderMode: Boolean,
+ isReorderingThis: Boolean,
+ onClick: () -> Unit,
+ onLongClick: () -> Unit,
+ onMoveUp: () -> Unit,
+ onMoveDown: () -> Unit,
+ onConfirm: () -> Unit,
+ onCancel: () -> Unit
+) {
+ val scale by animateFloatAsState(if (isReorderingThis) 1.03f else 1f, label = "favoriteRowScale")
+
+ Surface(
+ onClick = onClick,
+ onLongClick = {
+ if (!isReorderMode) {
+ onLongClick()
+ }
+ },
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(64.dp)
+ .scale(scale)
+ .then(
+ if (isReorderingThis) {
+ Modifier.onKeyEvent { event ->
+ if (event.type != KeyEventType.KeyDown) return@onKeyEvent false
+
+ when (event.nativeKeyEvent.keyCode) {
+ android.view.KeyEvent.KEYCODE_DPAD_UP -> {
+ onMoveUp()
+ true
+ }
+
+ android.view.KeyEvent.KEYCODE_DPAD_DOWN -> {
+ onMoveDown()
+ true
+ }
+
+ android.view.KeyEvent.KEYCODE_DPAD_CENTER,
+ android.view.KeyEvent.KEYCODE_ENTER -> {
+ onConfirm()
+ true
+ }
+
+ android.view.KeyEvent.KEYCODE_BACK -> {
+ onCancel()
+ true
+ }
+
+ else -> false
+ }
+ }
+ } else {
+ Modifier
+ }
+ ),
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (isReorderingThis) Primary.copy(alpha = 0.18f) else SurfaceElevated,
+ focusedContainerColor = if (isReorderingThis) Primary else SurfaceHighlight,
+ contentColor = if (isReorderingThis) Primary else OnSurface,
+ focusedContentColor = if (isReorderingThis) OnPrimary else OnSurface
+ ),
+ border = ClickableSurfaceDefaults.border(
+ border = Border(
+ border = androidx.compose.foundation.BorderStroke(
+ width = if (isReorderingThis) 2.dp else 0.dp,
+ color = if (isReorderingThis) Primary else Color.Transparent
+ )
+ )
+ )
+ ) {
+ Row(
+ modifier = Modifier
+ .fillMaxSize()
+ .padding(horizontal = 18.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(2.dp)
+ ) {
+ Text(
+ text = item.title,
+ style = MaterialTheme.typography.bodyLarge,
+ color = if (isReorderingThis) Primary else OnSurface,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ if (!item.subtitle.isNullOrBlank()) {
+ Text(
+ text = item.subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = if (isReorderingThis) Primary else OnSurfaceDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+
+ if (isReorderingThis) {
+ Text(
+ text = stringResource(R.string.favorites_reordering),
+ style = MaterialTheme.typography.bodySmall,
+ color = Primary
+ )
+ }
}
}
}
@Composable
-private fun ReorderHintRow(icon: String, label: String) {
- Row(
- verticalAlignment = Alignment.CenterVertically,
- horizontalArrangement = Arrangement.spacedBy(8.dp)
+private fun ReorderPanel(
+ section: FavoriteSectionUiModel?,
+ movingFavoriteId: Long?
+) {
+ if (section == null) return
+
+ Column(
+ modifier = Modifier
+ .width(250.dp)
+ .heightIn(max = 300.dp)
+ .background(
+ color = CardBackground.copy(alpha = 0.97f),
+ shape = RoundedCornerShape(topStart = 12.dp, bottomStart = 12.dp)
+ )
+ .padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
) {
- Box(
+ Text(
+ text = stringResource(R.string.favorites_reorder_mode),
+ style = MaterialTheme.typography.titleSmall,
+ color = Primary
+ )
+ Text(
+ text = section.title,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ ReorderHintRow(label = stringResource(R.string.favorites_move_up))
+ ReorderHintRow(label = stringResource(R.string.favorites_move_down))
+ ReorderHintRow(label = stringResource(R.string.favorites_confirm))
+ ReorderHintRow(label = stringResource(R.string.favorites_cancel))
+ }
+
+ Column(
modifier = Modifier
- .background(SurfaceHighlight, RoundedCornerShape(4.dp))
- .padding(horizontal = 8.dp, vertical = 4.dp)
+ .background(SurfaceElevated.copy(alpha = 0.5f), RoundedCornerShape(6.dp))
+ .padding(8.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
) {
- Text(icon, style = MaterialTheme.typography.labelSmall, color = Primary)
+ section.items.take(10).forEach { item ->
+ val isMoving = movingFavoriteId == item.favorite.id
+ Text(
+ text = item.title,
+ style = MaterialTheme.typography.labelSmall,
+ color = if (isMoving) Primary else OnSurfaceDim,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
}
- Text(label, style = MaterialTheme.typography.labelSmall, color = OnSurfaceDim)
}
}
-
+@Composable
+private fun ReorderHintRow(label: String) {
+ Text(
+ text = label,
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(vertical = 1.dp)
+ )
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt
index de42b571..d2c89aa9 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt
@@ -4,14 +4,28 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Favorite
+import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.VirtualCategoryIds
import com.streamvault.domain.model.VirtualGroup
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.PlaybackHistoryRepository
+import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.repository.SeriesRepository
+import com.streamvault.data.preferences.PreferencesRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
-import kotlinx.coroutines.flow.*
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject
@@ -19,7 +33,84 @@ data class FavoriteUiModel(
val favorite: Favorite,
val title: String,
val subtitle: String? = null,
- val streamUrl: String = ""
+ val lastWatchedAt: Long = 0L,
+ val streamUrl: String = "",
+ val providerId: Long = -1L,
+ val categoryId: Long? = null,
+ val epgChannelId: String? = null,
+ val launchCategoryId: Long? = null,
+ val launchIsVirtual: Boolean = false
+)
+
+data class FavoriteSectionUiModel(
+ val key: String,
+ val title: String,
+ val subtitle: String,
+ val items: List<FavoriteUiModel>,
+ val reorderable: Boolean
+)
+
+enum class SavedLibraryFilter {
+ ALL,
+ LIVE,
+ MOVIE,
+ SERIES
+}
+
+enum class SavedLibrarySort {
+ DEFAULT,
+ RECENT,
+ TITLE
+}
+
+enum class SavedLibraryPreset {
+ ALL_SAVED,
+ HOME_SHELF,
+ WATCH_NEXT,
+ LIVE_RECALL,
+ MOVIES,
+ SERIES,
+ CUSTOM_GROUPS
+}
+
+enum class SavedLibraryProviderScope {
+ CURRENT_PROVIDER,
+ ALL_PROVIDERS
+}
+
+data class SavedLibrarySummary(
+ val totalItems: Int = 0,
+ val liveCount: Int = 0,
+ val movieCount: Int = 0,
+ val seriesCount: Int = 0,
+ val customGroupCount: Int = 0,
+ val continueWatchingCount: Int = 0,
+ val recentLiveCount: Int = 0
+)
+
+data class SavedLibraryPresetSummary(
+ val allSavedCount: Int = 0,
+ val watchNextCount: Int = 0,
+ val liveRecallCount: Int = 0,
+ val movieCount: Int = 0,
+ val seriesCount: Int = 0,
+ val customGroupCount: Int = 0
+)
+
+data class SavedHistoryUiModel(
+ val history: PlaybackHistory,
+ val title: String,
+ val subtitle: String,
+ val providerId: Long,
+ val categoryId: Long? = null,
+ val epgChannelId: String? = null,
+ val launchIsVirtual: Boolean = false
+)
+
+data class SavedGroupManagementUiModel(
+ val group: VirtualGroup,
+ val itemCount: Int,
+ val isPromotedOnHome: Boolean
)
@HiltViewModel
@@ -28,106 +119,609 @@ class FavoritesViewModel @Inject constructor(
private val favoriteRepository: FavoriteRepository,
private val channelRepository: ChannelRepository,
private val movieRepository: MovieRepository,
- private val seriesRepository: SeriesRepository
+ private val seriesRepository: SeriesRepository,
+ private val playbackHistoryRepository: PlaybackHistoryRepository,
+ private val providerRepository: ProviderRepository,
+ private val preferencesRepository: PreferencesRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(FavoritesUiState())
val uiState: StateFlow<FavoritesUiState> = _uiState.asStateFlow()
init {
- viewModelScope.launch {
- favoriteRepository.getFavorites(null)
- .flatMapLatest { favorites ->
- val channelIds = favorites.filter { it.contentType == ContentType.LIVE }.map { it.contentId }
- val movieIds = favorites.filter { it.contentType == ContentType.MOVIE }.map { it.contentId }
- val seriesIds = favorites.filter { it.contentType == ContentType.SERIES }.map { it.contentId }
-
- combine(
- if (channelIds.isEmpty()) flowOf(emptyList()) else channelRepository.getChannelsByIds(channelIds),
- if (movieIds.isEmpty()) flowOf(emptyList()) else movieRepository.getMoviesByIds(movieIds),
- if (seriesIds.isEmpty()) flowOf(emptyList()) else seriesRepository.getSeriesByIds(seriesIds)
- ) { channels, movies, series ->
- val channelsById = channels.associateBy { it.id }
- val moviesById = movies.associateBy { it.id }
- val seriesById = series.associateBy { it.id }
-
- favorites.mapNotNull { favorite ->
- when (favorite.contentType) {
- ContentType.LIVE -> channelsById[favorite.contentId]?.let { channel ->
- FavoriteUiModel(
- favorite = favorite,
- title = channel.name,
- subtitle = "Channel ${channel.number}",
- streamUrl = channel.streamUrl
- )
- }
- ContentType.MOVIE -> moviesById[favorite.contentId]?.let { movie ->
- FavoriteUiModel(
- favorite = favorite,
- title = movie.name,
- subtitle = "Movie",
- streamUrl = movie.streamUrl
+ val globalSectionFlow = observeFavoriteItems(favoriteRepository.getFavorites(null))
+ .map { items ->
+ FavoriteSectionUiModel(
+ key = GLOBAL_SECTION_KEY,
+ title = "All Favorites",
+ subtitle = "${items.size} saved items",
+ items = items,
+ reorderable = items.size > 1
+ )
+ }
+
+ val allGroupsFlow = combine(
+ favoriteRepository.getGroups(ContentType.LIVE),
+ favoriteRepository.getGroups(ContentType.MOVIE),
+ favoriteRepository.getGroups(ContentType.SERIES)
+ ) { liveGroups, movieGroups, seriesGroups ->
+ (liveGroups + movieGroups + seriesGroups)
+ .sortedWith(compareBy<VirtualGroup>({ it.contentType.ordinal }, { it.position }, { it.name.lowercase() }))
+ }
+
+ val liveGroupManagementFlow = combine(
+ favoriteRepository.getGroups(ContentType.LIVE),
+ favoriteRepository.getGroupFavoriteCounts(ContentType.LIVE),
+ preferencesRepository.promotedLiveGroupIds
+ ) { liveGroups, liveCounts, promotedLiveGroupIds ->
+ liveGroups.map { group ->
+ SavedGroupManagementUiModel(
+ group = group,
+ itemCount = liveCounts[group.id] ?: 0,
+ isPromotedOnHome = group.id in promotedLiveGroupIds
+ )
+ }
+ }
+
+ val movieGroupManagementFlow = combine(
+ favoriteRepository.getGroups(ContentType.MOVIE),
+ favoriteRepository.getGroupFavoriteCounts(ContentType.MOVIE)
+ ) { movieGroups, movieCounts ->
+ movieGroups.map { group ->
+ SavedGroupManagementUiModel(
+ group = group,
+ itemCount = movieCounts[group.id] ?: 0,
+ isPromotedOnHome = false
+ )
+ }
+ }
+
+ val seriesGroupManagementFlow = combine(
+ favoriteRepository.getGroups(ContentType.SERIES),
+ favoriteRepository.getGroupFavoriteCounts(ContentType.SERIES)
+ ) { seriesGroups, seriesCounts ->
+ seriesGroups.map { group ->
+ SavedGroupManagementUiModel(
+ group = group,
+ itemCount = seriesCounts[group.id] ?: 0,
+ isPromotedOnHome = false
+ )
+ }
+ }
+
+ val groupManagementFlow = combine(
+ liveGroupManagementFlow,
+ movieGroupManagementFlow,
+ seriesGroupManagementFlow
+ ) { liveGroups, movieGroups, seriesGroups ->
+ (liveGroups + movieGroups + seriesGroups)
+ .sortedWith(
+ compareBy<SavedGroupManagementUiModel>(
+ { it.group.contentType.ordinal },
+ { it.group.position },
+ { it.group.name.lowercase() }
+ )
+ )
+ }
+
+ val groupedSectionsFlow = allGroupsFlow.flatMapLatest { groups ->
+ if (groups.isEmpty()) {
+ flowOf(emptyList())
+ } else {
+ combine(
+ groups.map { group ->
+ observeFavoriteItems(favoriteRepository.getFavoritesByGroup(group.id))
+ .map { items ->
+ FavoriteSectionUiModel(
+ key = sectionKeyForGroup(group.id),
+ title = group.name,
+ subtitle = "${group.contentType.displayName} group",
+ items = items,
+ reorderable = items.size > 1
+ )
+ }
+ }
+ ) { sections ->
+ sections.toList().filter { it.items.isNotEmpty() }
+ }
+ }
+ }
+
+ val savedHistoryFlow = providerRepository.getActiveProvider().flatMapLatest { provider ->
+ if (provider == null) {
+ flowOf(SavedHistorySnapshot())
+ } else {
+ playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 18)
+ .flatMapLatest { history ->
+ val continueWatching = history
+ .asSequence()
+ .filter { it.contentType != ContentType.LIVE }
+ .filter { it.resumePositionMs > 0L || it.contentType == ContentType.SERIES }
+ .distinctBy { it.contentType to it.contentId }
+ .take(8)
+ .toList()
+
+ val recentLiveHistory = history
+ .asSequence()
+ .filter { it.contentType == ContentType.LIVE }
+ .distinctBy { it.contentId }
+ .take(10)
+ .toList()
+
+ val recentLiveIds = recentLiveHistory.map { it.contentId }
+ val recentLiveFlow = if (recentLiveIds.isEmpty()) {
+ flowOf(emptyList())
+ } else {
+ channelRepository.getChannelsByIds(recentLiveIds)
+ }
+
+ recentLiveFlow.map { liveChannels ->
+ val liveById = liveChannels.associateBy { it.id }
+ SavedHistorySnapshot(
+ continueWatching = continueWatching.map { entry ->
+ SavedHistoryUiModel(
+ history = entry,
+ title = entry.title,
+ subtitle = when (entry.contentType) {
+ ContentType.MOVIE -> "Movie"
+ ContentType.SERIES -> "Series"
+ ContentType.SERIES_EPISODE -> buildString {
+ append("Episode")
+ entry.seasonNumber?.let { append(" S$it") }
+ entry.episodeNumber?.let { append("E$it") }
+ }
+ ContentType.LIVE -> "Live"
+ },
+ providerId = entry.providerId
)
- }
- ContentType.SERIES -> seriesById[favorite.contentId]?.let { seriesItem ->
- FavoriteUiModel(
- favorite = favorite,
- title = seriesItem.name,
- subtitle = "Series",
- streamUrl = "" // Series doesn't have a single stream URL
+ },
+ recentLive = recentLiveHistory.mapNotNull { entry ->
+ val channel = liveById[entry.contentId] ?: return@mapNotNull null
+ SavedHistoryUiModel(
+ history = entry,
+ title = channel.name,
+ subtitle = if (channel.number > 0) {
+ "Channel ${channel.number}"
+ } else {
+ "Recent live channel"
+ },
+ providerId = channel.providerId,
+ categoryId = channel.categoryId,
+ epgChannelId = channel.epgChannelId,
+ launchIsVirtual = false
)
}
- else -> null
- }
+ )
}
}
+ }
+ }
+
+ val activeProviderFlow = providerRepository.getActiveProvider()
+
+ viewModelScope.launch {
+ combine(
+ combine(globalSectionFlow, groupedSectionsFlow) { globalSection, groupedSections ->
+ buildList {
+ if (globalSection.items.isNotEmpty()) {
+ add(globalSection)
+ }
+ addAll(groupedSections)
+ }
+ },
+ savedHistoryFlow,
+ groupManagementFlow,
+ activeProviderFlow
+ ) { sections, historySnapshot, managedGroups, activeProvider ->
+ SavedLibrarySnapshot(
+ sections = sections,
+ history = historySnapshot,
+ managedGroups = managedGroups,
+ activeProviderId = activeProvider?.id,
+ activeProviderName = activeProvider?.name
+ )
+ }.collect { snapshot ->
+ val sections = snapshot.sections
+ val historySnapshot = snapshot.history
+ val managedGroups = snapshot.managedGroups
+ val globalItems = sections
+ .firstOrNull { it.key == GLOBAL_SECTION_KEY }
+ ?.items
+ .orEmpty()
+ _uiState.update { state ->
+ state.copy(
+ sections = state.applyReorderPreview(sections),
+ continueWatching = historySnapshot.continueWatching,
+ recentLive = historySnapshot.recentLive,
+ managedGroups = managedGroups,
+ summary = SavedLibrarySummary(
+ totalItems = globalItems.size,
+ liveCount = globalItems.count { it.favorite.contentType == ContentType.LIVE },
+ movieCount = globalItems.count { it.favorite.contentType == ContentType.MOVIE },
+ seriesCount = globalItems.count { it.favorite.contentType == ContentType.SERIES },
+ customGroupCount = sections.count { it.key != GLOBAL_SECTION_KEY },
+ continueWatchingCount = historySnapshot.continueWatching.size,
+ recentLiveCount = historySnapshot.recentLive.size
+ ),
+ presetSummary = SavedLibraryPresetSummary(
+ allSavedCount = globalItems.size,
+ watchNextCount = historySnapshot.continueWatching.size,
+ liveRecallCount = historySnapshot.recentLive.size,
+ movieCount = globalItems.count { it.favorite.contentType == ContentType.MOVIE },
+ seriesCount = globalItems.count { it.favorite.contentType == ContentType.SERIES },
+ customGroupCount = sections.count { it.key != GLOBAL_SECTION_KEY }
+ ),
+ activeProviderId = snapshot.activeProviderId,
+ activeProviderName = snapshot.activeProviderName,
+ isLoading = false
+ )
}
- .collect { uiModels ->
- _uiState.update { it.copy(favorites = uiModels, isLoading = false) }
+ }
+ }
+ }
+
+ fun enterReorderMode(sectionKey: String, item: FavoriteUiModel) {
+ _uiState.update {
+ it.copy(
+ isReorderMode = true,
+ reorderSectionKey = sectionKey,
+ reorderItem = item.favorite
+ )
+ }
+ }
+
+ fun exitReorderMode() {
+ _uiState.update { it.copy(isReorderMode = false, reorderSectionKey = null, reorderItem = null) }
+ }
+
+ fun selectFilter(filter: SavedLibraryFilter) {
+ _uiState.update { it.copy(selectedFilter = filter) }
+ }
+
+ fun selectSort(sort: SavedLibrarySort) {
+ _uiState.update { it.copy(selectedSort = sort) }
+ }
+
+ fun selectPreset(preset: SavedLibraryPreset) {
+ _uiState.update { state ->
+ state.copy(
+ selectedPreset = preset,
+ selectedFilter = when (preset) {
+ SavedLibraryPreset.MOVIES -> SavedLibraryFilter.MOVIE
+ SavedLibraryPreset.SERIES -> SavedLibraryFilter.SERIES
+ SavedLibraryPreset.LIVE_RECALL -> SavedLibraryFilter.LIVE
+ else -> state.selectedFilter
}
+ )
+ }
+ }
+
+ fun selectProviderScope(scope: SavedLibraryProviderScope) {
+ _uiState.update { it.copy(selectedProviderScope = scope) }
+ }
+
+ fun dismissSavedDialog() {
+ _uiState.update {
+ it.copy(
+ itemDialogItem = null,
+ itemMoveTargets = emptyList(),
+ managedGroupDialog = null,
+ mergeSourceGroup = null,
+ mergeTargetCandidates = emptyList()
+ )
}
+ }
+
+ fun showItemOptions(item: FavoriteUiModel) {
viewModelScope.launch {
- favoriteRepository.getGroups(ContentType.LIVE).collect { groups ->
- _uiState.update { it.copy(groups = groups) }
+ val targetGroups = _uiState.value.managedGroups
+ .filter { it.group.contentType == item.favorite.contentType }
+ .filter { it.group.id != item.favorite.groupId }
+ _uiState.update {
+ it.copy(
+ itemDialogItem = item,
+ itemMoveTargets = targetGroups
+ )
}
}
}
- fun enterReorderMode(item: FavoriteUiModel) {
- _uiState.update { it.copy(isReorderMode = true, reorderItem = item.favorite) }
+ fun removeFromSavedContext(item: FavoriteUiModel) {
+ viewModelScope.launch {
+ favoriteRepository.removeFavorite(
+ contentId = item.favorite.contentId,
+ contentType = item.favorite.contentType,
+ groupId = item.favorite.groupId
+ )
+ _uiState.update {
+ it.copy(
+ itemDialogItem = null,
+ itemMoveTargets = emptyList(),
+ userMessage = "Removed ${item.title} from this saved view."
+ )
+ }
+ }
}
- fun exitReorderMode() {
- _uiState.update { it.copy(isReorderMode = false, reorderItem = null) }
+ fun moveItemToGroup(item: FavoriteUiModel, targetGroupId: Long) {
+ viewModelScope.launch {
+ favoriteRepository.addFavorite(
+ contentId = item.favorite.contentId,
+ contentType = item.favorite.contentType,
+ groupId = targetGroupId
+ )
+ favoriteRepository.removeFavorite(
+ contentId = item.favorite.contentId,
+ contentType = item.favorite.contentType,
+ groupId = item.favorite.groupId
+ )
+ _uiState.update {
+ it.copy(
+ itemDialogItem = null,
+ itemMoveTargets = emptyList(),
+ userMessage = "Moved ${item.title} to the selected group."
+ )
+ }
+ }
}
- fun moveItem(direction: Int) {
- val currentList = _uiState.value.favorites.toMutableList()
- val reorderItem = _uiState.value.reorderItem ?: return
- val index = currentList.indexOfFirst { it.favorite.id == reorderItem.id }
- if (index == -1) return
+ fun showGroupOptions(group: SavedGroupManagementUiModel) {
+ _uiState.update {
+ it.copy(
+ managedGroupDialog = group,
+ mergeSourceGroup = null,
+ mergeTargetCandidates = emptyList()
+ )
+ }
+ }
+
+ fun deleteManagedGroup(group: SavedGroupManagementUiModel) {
+ viewModelScope.launch {
+ favoriteRepository.deleteGroup(group.group.id)
+ if (group.group.contentType == ContentType.LIVE) {
+ val currentPromoted = preferencesRepository.promotedLiveGroupIds.first()
+ preferencesRepository.setPromotedLiveGroupIds(currentPromoted - group.group.id)
+ }
+ _uiState.update {
+ it.copy(
+ managedGroupDialog = null,
+ userMessage = "Deleted group ${group.group.name}."
+ )
+ }
+ }
+ }
+
+ fun toggleHomePromotion(group: SavedGroupManagementUiModel) {
+ if (group.group.contentType != ContentType.LIVE) return
+ viewModelScope.launch {
+ val currentPromoted = preferencesRepository.promotedLiveGroupIds.first()
+ val updated = if (group.group.id in currentPromoted) {
+ currentPromoted - group.group.id
+ } else {
+ currentPromoted + group.group.id
+ }
+ preferencesRepository.setPromotedLiveGroupIds(updated)
+ _uiState.update {
+ it.copy(
+ managedGroupDialog = null,
+ userMessage = if (group.group.id in currentPromoted) {
+ "Removed ${group.group.name} from Home priority."
+ } else {
+ "Pinned ${group.group.name} to Home."
+ }
+ )
+ }
+ }
+ }
+
+ fun startMergeGroup(group: SavedGroupManagementUiModel) {
+ val candidates = _uiState.value.managedGroups
+ .filter { it.group.contentType == group.group.contentType && it.group.id != group.group.id }
+ _uiState.update {
+ it.copy(
+ mergeSourceGroup = group,
+ mergeTargetCandidates = candidates
+ )
+ }
+ }
+
+ fun mergeGroupInto(targetGroupId: Long) {
+ val source = _uiState.value.mergeSourceGroup ?: return
+ viewModelScope.launch {
+ val items = favoriteRepository.getFavoritesByGroup(source.group.id).first()
+ items.forEach { favorite ->
+ favoriteRepository.addFavorite(
+ contentId = favorite.contentId,
+ contentType = favorite.contentType,
+ groupId = targetGroupId
+ )
+ favoriteRepository.removeFavorite(
+ contentId = favorite.contentId,
+ contentType = favorite.contentType,
+ groupId = source.group.id
+ )
+ }
+ favoriteRepository.deleteGroup(source.group.id)
+ if (source.group.contentType == ContentType.LIVE) {
+ val currentPromoted = preferencesRepository.promotedLiveGroupIds.first()
+ preferencesRepository.setPromotedLiveGroupIds(currentPromoted - source.group.id)
+ }
+ _uiState.update {
+ it.copy(
+ managedGroupDialog = null,
+ mergeSourceGroup = null,
+ mergeTargetCandidates = emptyList(),
+ userMessage = "Merged ${source.group.name} into the selected group."
+ )
+ }
+ }
+ }
- val newIndex = index + direction
- if (newIndex in 0 until currentList.size) {
- java.util.Collections.swap(currentList, index, newIndex)
- _uiState.update { it.copy(favorites = currentList) }
+ fun userMessageShown() {
+ _uiState.update { it.copy(userMessage = null) }
+ }
+
+ fun moveItem(direction: Int) {
+ val state = _uiState.value
+ val reorderSectionKey = state.reorderSectionKey ?: return
+ val reorderItem = state.reorderItem ?: return
+ val updatedSections = state.sections.map { section ->
+ if (section.key != reorderSectionKey) {
+ section
+ } else {
+ val currentItems = section.items.toMutableList()
+ val index = currentItems.indexOfFirst { it.favorite.id == reorderItem.id }
+ val newIndex = index + direction
+ if (index == -1 || newIndex !in currentItems.indices) {
+ section
+ } else {
+ java.util.Collections.swap(currentItems, index, newIndex)
+ section.copy(items = currentItems)
+ }
+ }
}
+
+ _uiState.update { it.copy(sections = updatedSections) }
}
fun saveReorder() {
- val currentModels = _uiState.value.favorites
- val updatedFavorites = currentModels.map { it.favorite }
+ val state = _uiState.value
+ val sectionKey = state.reorderSectionKey ?: return
+ val section = state.sections.firstOrNull { it.key == sectionKey } ?: return
+
viewModelScope.launch {
- favoriteRepository.reorderFavorites(updatedFavorites)
+ favoriteRepository.reorderFavorites(section.items.map { it.favorite })
exitReorderMode()
}
}
+
+ private fun observeFavoriteItems(favoritesFlow: Flow<List<Favorite>>): Flow<List<FavoriteUiModel>> {
+ return favoritesFlow.flatMapLatest { favorites ->
+ val orderedFavorites = favorites.sortedBy { it.position }
+ val channelIds = orderedFavorites.filter { it.contentType == ContentType.LIVE }.map { it.contentId }
+ val movieIds = orderedFavorites.filter { it.contentType == ContentType.MOVIE }.map { it.contentId }
+ val seriesIds = orderedFavorites.filter { it.contentType == ContentType.SERIES }.map { it.contentId }
+
+ combine(
+ playbackHistoryRepository.getRecentlyWatched(limit = 500),
+ if (channelIds.isEmpty()) flowOf(emptyList()) else channelRepository.getChannelsByIds(channelIds),
+ if (movieIds.isEmpty()) flowOf(emptyList()) else movieRepository.getMoviesByIds(movieIds),
+ if (seriesIds.isEmpty()) flowOf(emptyList()) else seriesRepository.getSeriesByIds(seriesIds)
+ ) { history, channels, movies, series ->
+ val historyMap = history.associateBy { Triple(it.contentType, it.contentId, it.providerId) }
+ val channelsById = channels.associateBy { it.id }
+ val moviesById = movies.associateBy { it.id }
+ val seriesById = series.associateBy { it.id }
+
+ orderedFavorites.mapNotNull { favorite ->
+ when (favorite.contentType) {
+ ContentType.LIVE -> channelsById[favorite.contentId]?.let { channel ->
+ FavoriteUiModel(
+ favorite = favorite,
+ title = channel.name,
+ subtitle = if (channel.number > 0) "Channel ${channel.number}" else "Live channel",
+ lastWatchedAt = historyMap[Triple(favorite.contentType, favorite.contentId, channel.providerId)]?.lastWatchedAt ?: 0L,
+ streamUrl = channel.streamUrl,
+ providerId = channel.providerId,
+ categoryId = channel.categoryId,
+ epgChannelId = channel.epgChannelId,
+ launchCategoryId = favorite.groupId?.let { -it } ?: VirtualCategoryIds.FAVORITES,
+ launchIsVirtual = true
+ )
+ }
+
+ ContentType.MOVIE -> moviesById[favorite.contentId]?.let { movie ->
+ FavoriteUiModel(
+ favorite = favorite,
+ title = movie.name,
+ subtitle = "Movie",
+ lastWatchedAt = historyMap[Triple(favorite.contentType, favorite.contentId, movie.providerId)]?.lastWatchedAt ?: 0L,
+ streamUrl = movie.streamUrl,
+ providerId = movie.providerId,
+ categoryId = movie.categoryId
+ )
+ }
+
+ ContentType.SERIES -> seriesById[favorite.contentId]?.let { seriesItem ->
+ FavoriteUiModel(
+ favorite = favorite,
+ title = seriesItem.name,
+ subtitle = "Series",
+ lastWatchedAt = historyMap[Triple(favorite.contentType, favorite.contentId, seriesItem.providerId)]?.lastWatchedAt ?: 0L,
+ streamUrl = "",
+ providerId = seriesItem.providerId
+ )
+ }
+
+ ContentType.SERIES_EPISODE -> null
+ }
+ }
+ }
+ }
+ }
+
+ private fun FavoritesUiState.applyReorderPreview(
+ incomingSections: List<FavoriteSectionUiModel>
+ ): List<FavoriteSectionUiModel> {
+ if (!isReorderMode || reorderSectionKey == null) {
+ return incomingSections
+ }
+
+ val previewSection = sections.firstOrNull { it.key == reorderSectionKey } ?: return incomingSections
+ return incomingSections.map { section ->
+ if (section.key == reorderSectionKey) previewSection else section
+ }
+ }
+
+ private val ContentType.displayName: String
+ get() = when (this) {
+ ContentType.LIVE -> "Live"
+ ContentType.MOVIE -> "Movie"
+ ContentType.SERIES -> "Series"
+ ContentType.SERIES_EPISODE -> "Episode"
+ }
+
+ companion object {
+ private const val GLOBAL_SECTION_KEY = "global"
+
+ private fun sectionKeyForGroup(groupId: Long): String = "group:$groupId"
+ }
}
data class FavoritesUiState(
- val favorites: List<FavoriteUiModel> = emptyList(),
- val groups: List<VirtualGroup> = emptyList(),
+ val sections: List<FavoriteSectionUiModel> = emptyList(),
+ val continueWatching: List<SavedHistoryUiModel> = emptyList(),
+ val recentLive: List<SavedHistoryUiModel> = emptyList(),
+ val managedGroups: List<SavedGroupManagementUiModel> = emptyList(),
+ val summary: SavedLibrarySummary = SavedLibrarySummary(),
+ val presetSummary: SavedLibraryPresetSummary = SavedLibraryPresetSummary(),
+ val activeProviderId: Long? = null,
+ val activeProviderName: String? = null,
+ val selectedProviderScope: SavedLibraryProviderScope = SavedLibraryProviderScope.CURRENT_PROVIDER,
+ val selectedPreset: SavedLibraryPreset = SavedLibraryPreset.ALL_SAVED,
+ val selectedFilter: SavedLibraryFilter = SavedLibraryFilter.ALL,
+ val selectedSort: SavedLibrarySort = SavedLibrarySort.DEFAULT,
+ val itemDialogItem: FavoriteUiModel? = null,
+ val itemMoveTargets: List<SavedGroupManagementUiModel> = emptyList(),
+ val managedGroupDialog: SavedGroupManagementUiModel? = null,
+ val mergeSourceGroup: SavedGroupManagementUiModel? = null,
+ val mergeTargetCandidates: List<SavedGroupManagementUiModel> = emptyList(),
+ val userMessage: String? = null,
val isLoading: Boolean = true,
val isReorderMode: Boolean = false,
+ val reorderSectionKey: String? = null,
val reorderItem: Favorite? = null
)
+
+private data class SavedHistorySnapshot(
+ val continueWatching: List<SavedHistoryUiModel> = emptyList(),
+ val recentLive: List<SavedHistoryUiModel> = emptyList()
+)
+
+private data class SavedLibrarySnapshot(
+ val sections: List<FavoriteSectionUiModel>,
+ val history: SavedHistorySnapshot,
+ val managedGroups: List<SavedGroupManagementUiModel>,
+ val activeProviderId: Long?,
+ val activeProviderName: String?
+)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
index d90b9445..1e1b8237 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt
@@ -39,6 +39,7 @@ import com.streamvault.app.ui.components.CategoryRow
import com.streamvault.app.ui.components.ChannelCard
import com.streamvault.app.ui.components.dialogs.CategoryOptionsDialog
import com.streamvault.app.ui.components.dialogs.PinDialog
+import com.streamvault.app.ui.components.dialogs.RenameGroupDialog
import com.streamvault.app.ui.components.TopNavBar
import com.streamvault.app.ui.components.SkeletonCard
import com.streamvault.app.ui.components.shimmerEffect
@@ -52,6 +53,12 @@ import com.streamvault.app.R
import com.streamvault.app.ui.screens.multiview.MultiViewViewModel
import com.streamvault.app.ui.screens.multiview.MultiViewPlannerDialog
import com.streamvault.app.navigation.Routes
+import com.streamvault.domain.model.VirtualCategoryIds
+
+private enum class FocusRestoreTarget {
+ CATEGORY,
+ CHANNEL
+}
// ── Screen ─────────────────────────────────────────────────────────
@@ -66,6 +73,7 @@ fun HomeScreen(
onChannelClick: (Channel, Category?, Provider?) -> Unit,
onNavigate: (String) -> Unit,
currentRoute: String,
+ initialCategoryId: Long? = null,
viewModel: HomeViewModel = hiltViewModel(),
multiViewViewModel: MultiViewViewModel = hiltViewModel()
) {
@@ -86,6 +94,10 @@ fun HomeScreen(
val scope = rememberCoroutineScope()
val context = androidx.compose.ui.platform.LocalContext.current
+ LaunchedEffect(initialCategoryId) {
+ viewModel.setPreferredInitialCategory(initialCategoryId)
+ }
+
LaunchedEffect(uiState.userMessage) {
uiState.userMessage?.let { message ->
snackbarHostState.showSnackbar(message)
@@ -141,18 +153,20 @@ fun HomeScreen(
viewModel.setDefaultCategory(category)
viewModel.dismissCategoryOptions()
},
+ onRename = if (category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {
+ { viewModel.requestRenameGroup(category) }
+ } else null,
onToggleLock = {
viewModel.dismissCategoryOptions()
pendingLockToggleCategory = category
showPinDialog = true
},
- onDelete = if (category.isVirtual && category.id != -999L) {
+ onDelete = if (category.isVirtual && category.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) {
{
- viewModel.dismissCategoryOptions()
viewModel.requestDeleteGroup(category)
}
} else null,
- onReorderChannels = if (category.isVirtual) {
+ onReorderChannels = if (category.isVirtual && category.id != VirtualCategoryIds.RECENT) {
{ viewModel.enterChannelReorderMode(category) }
} else null
)
@@ -178,7 +192,7 @@ fun HomeScreen(
verticalAlignment = Alignment.CenterVertically
) {
Text(
- "Reordering '${uiState.selectedCategory?.name ?: "Channels"}'",
+ "Reordering '${uiState.reorderCategory?.name ?: uiState.selectedCategory?.name ?: "Channels"}'",
style = MaterialTheme.typography.titleLarge,
color = Primary
)
@@ -266,6 +280,7 @@ fun HomeScreen(
val channelFocusRequesters = remember { mutableMapOf<Long, FocusRequester>() }
var lastFocusedCategoryId by rememberSaveable { mutableStateOf<Long?>(null) }
var lastFocusedChannelId by rememberSaveable { mutableStateOf<Long?>(null) }
+ var preferredRestoreTarget by rememberSaveable { mutableStateOf(FocusRestoreTarget.CHANNEL.name) }
var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }
var shouldRestoreChannelFocus by remember { mutableStateOf(false) }
@@ -287,9 +302,20 @@ fun HomeScreen(
uiState.filteredChannels.any { it.id == lastFocusedChannelId }
val canRestoreCategory = lastFocusedCategoryId != null &&
uiState.categories.any { it.id == lastFocusedCategoryId }
+ val restoreTarget = runCatching {
+ FocusRestoreTarget.valueOf(preferredRestoreTarget)
+ }.getOrDefault(FocusRestoreTarget.CHANNEL)
+
+ shouldRestoreCategoryFocus = restoreTarget == FocusRestoreTarget.CATEGORY && canRestoreCategory
+ shouldRestoreChannelFocus = when {
+ restoreTarget == FocusRestoreTarget.CATEGORY -> false
+ canRestoreChannel -> true
+ else -> false
+ }
- shouldRestoreChannelFocus = canRestoreChannel
- shouldRestoreCategoryFocus = !canRestoreChannel && canRestoreCategory
+ if (!shouldRestoreChannelFocus && !shouldRestoreCategoryFocus && canRestoreCategory) {
+ shouldRestoreCategoryFocus = true
+ }
}
LaunchedEffect(shouldRestoreChannelFocus, uiState.filteredChannels) {
@@ -429,7 +455,10 @@ fun HomeScreen(
viewModel.selectCategory(category)
}
},
- onLongClick = { viewModel.showCategoryOptions(category) },
+ onLongClick = {
+ preferredRestoreTarget = FocusRestoreTarget.CATEGORY.name
+ viewModel.showCategoryOptions(category)
+ },
onJumpToSearch = { categorySearchFocusRequester.requestFocus() },
onJumpToContent = {
if (uiState.filteredChannels.isNotEmpty()) {
@@ -466,14 +495,19 @@ fun HomeScreen(
style = MaterialTheme.typography.headlineSmall,
color = OnBackground
)
- SearchInput(
- value = uiState.channelSearchQuery,
- onValueChange = { viewModel.updateChannelSearchQuery(it) },
- placeholder = stringResource(R.string.home_search_channels),
- onSearch = { focusManager.clearFocus() },
- focusRequester = channelSearchFocusRequester,
- modifier = Modifier.width(300.dp)
- )
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ SearchInput(
+ value = uiState.channelSearchQuery,
+ onValueChange = { viewModel.updateChannelSearchQuery(it) },
+ placeholder = stringResource(R.string.home_search_channels),
+ onSearch = { focusManager.clearFocus() },
+ focusRequester = channelSearchFocusRequester,
+ modifier = Modifier.width(300.dp)
+ )
+ }
}
if (uiState.isLoading) {
@@ -511,13 +545,20 @@ fun HomeScreen(
color = OnSurface
)
val selectedCategory = uiState.selectedCategory
- if (selectedCategory?.isVirtual == true && selectedCategory.id == -999L) {
+ if (selectedCategory?.isVirtual == true && selectedCategory.id == VirtualCategoryIds.FAVORITES) {
Text(
text = stringResource(R.string.home_add_favorites_hint),
style = MaterialTheme.typography.bodySmall,
color = OnSurfaceDim,
modifier = Modifier.padding(top = 4.dp)
)
+ } else if (selectedCategory?.isVirtual == true && selectedCategory.id == VirtualCategoryIds.RECENT) {
+ Text(
+ text = stringResource(R.string.home_recent_channels_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(top = 4.dp)
+ )
}
}
}
@@ -600,6 +641,7 @@ fun HomeScreen(
onLongClick = {
if (!uiState.isChannelReorderMode) {
ignoreNextClick = true
+ preferredRestoreTarget = FocusRestoreTarget.CHANNEL.name
viewModel.onShowDialog(channel)
}
},
@@ -645,7 +687,7 @@ fun HomeScreen(
com.streamvault.app.ui.components.dialogs.AddToGroupDialog(
contentTitle = channel.name,
channel = channel,
- groups = uiState.categories.filter { it.isVirtual && it.id != -999L },
+ groups = uiState.categories.filter { it.isVirtual && it.id !in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT) },
isFavorite = channel.isFavorite,
memberOfGroups = uiState.dialogGroupMemberships,
onDismiss = { viewModel.onDismissDialog() },
@@ -659,6 +701,15 @@ fun HomeScreen(
)
}
+ if (uiState.showRenameGroupDialog && uiState.groupToRename != null) {
+ RenameGroupDialog(
+ initialName = uiState.groupToRename!!.name,
+ errorMessage = uiState.renameGroupError,
+ onDismissRequest = { viewModel.cancelRenameGroup() },
+ onConfirm = { name -> viewModel.confirmRenameGroup(name) }
+ )
+ }
+
// Split Screen manager dialog (opened from the header button)
if (showSplitManagerDialog) {
MultiViewPlannerDialog(
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
index 7b077641..d8b5cc22 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt
@@ -7,40 +7,50 @@ import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.VirtualCategoryIds
import com.streamvault.domain.repository.CategoryRepository
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.EpgRepository
import com.streamvault.domain.repository.FavoriteRepository
+import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.usecase.GetCustomCategories
import dagger.hilt.android.lifecycle.HiltViewModel
+import com.streamvault.app.R
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
+import android.app.Application
@HiltViewModel
@OptIn(ExperimentalCoroutinesApi::class)
class HomeViewModel @Inject constructor(
+ application: Application,
private val providerRepository: ProviderRepository,
private val channelRepository: ChannelRepository,
private val categoryRepository: CategoryRepository,
private val favoriteRepository: FavoriteRepository,
private val preferencesRepository: PreferencesRepository,
private val epgRepository: EpgRepository,
+ private val playbackHistoryRepository: PlaybackHistoryRepository,
private val getCustomCategories: GetCustomCategories,
private val parentalControlManager: ParentalControlManager
) : ViewModel() {
+ private val appContext = application
private val _uiState = MutableStateFlow(HomeUiState())
val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()
private val _localChannels = MutableStateFlow<List<Channel>>(emptyList())
+ private val _preferredInitialCategoryId = MutableStateFlow<Long?>(null)
private var epgJob: Job? = null
private var loadChannelsJob: Job? = null
private var categoriesJob: Job? = null
+ private var recentChannelsJob: Job? = null
init {
loadAllProviders()
@@ -50,6 +60,7 @@ class HomeViewModel @Inject constructor(
.collectLatest { provider ->
_uiState.update { it.copy(provider = provider) }
loadCategoriesAndChannels(provider.id)
+ observeRecentChannels(provider.id)
preferencesRepository.setLastActiveProviderId(provider.id)
}
}
@@ -105,17 +116,58 @@ class HomeViewModel @Inject constructor(
combine(
channelRepository.getCategories(providerId),
getCustomCategories(),
- preferencesRepository.defaultCategoryId
- ) { providerCats, customCats, defaultId ->
- Triple(customCats + providerCats, defaultId, Unit)
- }.collect { (categories, defaultId, _) ->
- _uiState.update { it.copy(categories = categories) }
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24),
+ preferencesRepository.defaultCategoryId,
+ preferencesRepository.getLastLiveCategoryId(providerId)
+ ) { providerCats, customCats, history, defaultId, lastVisitedCategoryId ->
+ val recentCategory = Category(
+ id = VirtualCategoryIds.RECENT,
+ name = "Recent",
+ type = ContentType.LIVE,
+ isVirtual = true,
+ count = history.toRecentLiveContentIds().size
+ )
+
+ val orderedCategories = buildList {
+ val favoritesCategory = customCats.find { it.id == VirtualCategoryIds.FAVORITES }
+ if (favoritesCategory != null) {
+ add(favoritesCategory)
+ }
+ add(recentCategory)
+ addAll(
+ customCats.filter { it.id != VirtualCategoryIds.FAVORITES }
+ )
+ addAll(providerCats)
+ }
+
+ CategorySelectionContext(
+ categories = orderedCategories,
+ defaultCategoryId = defaultId,
+ lastVisitedCategoryId = lastVisitedCategoryId
+ )
+ }.collect { selectionContext ->
+ val categories = selectionContext.categories
+ val defaultId = selectionContext.defaultCategoryId
+ val preferredCategoryId = _preferredInitialCategoryId.value
+ val lastVisitedCategory = selectionContext.lastVisitedCategoryId?.let { lastVisitedId ->
+ categories.find { it.id == lastVisitedId && it.id != VirtualCategoryIds.RECENT }
+ }
+ _uiState.update { it.copy(categories = categories, lastVisitedCategory = lastVisitedCategory) }
val currentSelected = _uiState.value.selectedCategory
+ val preferredCategory = preferredCategoryId?.let { categoryId ->
+ categories.find { it.id == categoryId }
+ }
+
+ if (preferredCategory != null && currentSelected?.id != preferredCategory.id) {
+ _preferredInitialCategoryId.value = null
+ selectCategory(preferredCategory)
+ return@collect
+ }
if (currentSelected == null && categories.isNotEmpty()) {
val defaultCat = defaultId?.let { id -> categories.find { it.id == id } }
- val favoritesCat = categories.find { it.id == -999L }
+ val favoritesCat = categories.find { it.id == VirtualCategoryIds.FAVORITES }
if (defaultCat != null) selectCategory(defaultCat)
else if (favoritesCat != null) selectCategory(favoritesCat)
@@ -130,7 +182,7 @@ class HomeViewModel @Inject constructor(
loadChannelsForCategory(reselectedCat)
} else {
val defaultCat = defaultId?.let { id -> categories.find { it.id == id } }
- val favoritesCat = categories.find { it.id == -999L }
+ val favoritesCat = categories.find { it.id == VirtualCategoryIds.FAVORITES }
if (defaultCat != null) selectCategory(defaultCat)
else if (favoritesCat != null) selectCategory(favoritesCat)
@@ -145,35 +197,50 @@ class HomeViewModel @Inject constructor(
if (_uiState.value.selectedCategory?.id == category.id) return
parentalControlManager.clearUnlockedCategories(_uiState.value.provider?.id)
_uiState.update { it.copy(selectedCategory = category, isLoading = true) }
+ _preferredInitialCategoryId.value = null
+ if (category.id != VirtualCategoryIds.RECENT) {
+ val providerId = _uiState.value.provider?.id
+ if (providerId != null) {
+ viewModelScope.launch {
+ preferencesRepository.setLastLiveCategoryId(providerId, category.id)
+ }
+ }
+ }
loadChannelsForCategory(category)
}
+ fun setPreferredInitialCategory(categoryId: Long?) {
+ if (categoryId == null) return
+
+ val matchingCategory = _uiState.value.categories.firstOrNull { it.id == categoryId }
+ if (matchingCategory != null) {
+ if (_uiState.value.selectedCategory?.id != matchingCategory.id) {
+ selectCategory(matchingCategory)
+ }
+ return
+ }
+
+ _preferredInitialCategoryId.value = categoryId
+ }
+
private fun loadChannelsForCategory(category: Category) {
val providerId = _uiState.value.provider?.id ?: return
loadChannelsJob?.cancel()
loadChannelsJob = viewModelScope.launch {
val channelsFlow = if (category.isVirtual) {
- if (category.id == -999L) {
+ if (category.id == VirtualCategoryIds.RECENT) {
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24)
+ .map { it.toRecentLiveContentIds() }
+ .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }
+ } else if (category.id == VirtualCategoryIds.FAVORITES) {
favoriteRepository.getFavorites(ContentType.LIVE)
.map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
- .flatMapLatest { ids ->
- if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids).map { unsorted ->
- val map = unsorted.associateBy { it.id }
- ids.mapNotNull { map[it] }
- }
- }
+ .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }
} else {
val groupId = -category.id
favoriteRepository.getFavoritesByGroup(groupId)
.map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }
- .flatMapLatest { ids ->
- if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids).map { unsorted ->
- val map = unsorted.associateBy { it.id }
- ids.mapNotNull { map[it] }
- }
- }
+ .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }
}
} else {
channelRepository.getChannelsByCategory(providerId, category.id)
@@ -242,24 +309,101 @@ class HomeViewModel @Inject constructor(
fun createCustomGroup(name: String) {
val trimmed = name.trim()
+ if (trimmed.isBlank()) {
+ _uiState.update { it.copy(userMessage = appContext.getString(R.string.home_group_name_invalid)) }
+ return
+ }
if (trimmed.equals("Favorites", ignoreCase = true)) {
- _uiState.update { it.copy(userMessage = "Cannot create group named 'Favorites'") }
+ _uiState.update { it.copy(userMessage = appContext.getString(R.string.home_group_name_reserved)) }
return
}
if (_uiState.value.categories.any { it.name.equals(trimmed, ignoreCase = true) }) {
- _uiState.update { it.copy(userMessage = "Group '$trimmed' already exists") }
+ _uiState.update { it.copy(userMessage = appContext.getString(R.string.home_group_name_duplicate, trimmed)) }
return
}
viewModelScope.launch {
favoriteRepository.createGroup(trimmed, contentType = ContentType.LIVE)
- _uiState.update { it.copy(userMessage = "Group '$trimmed' created") }
+ _uiState.update { it.copy(userMessage = appContext.getString(R.string.home_group_created, trimmed)) }
+ }
+ }
+
+ private fun observeRecentChannels(providerId: Long) {
+ recentChannelsJob?.cancel()
+ recentChannelsJob = viewModelScope.launch {
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 12)
+ .map { it.toRecentLiveContentIds() }
+ .flatMapLatest { ids -> loadChannelsByOrderedIds(ids) }
+ .collect { channels ->
+ _uiState.update { it.copy(recentChannels = channels) }
+ }
+ }
+ }
+
+ fun requestRenameGroup(category: Category) {
+ if (!category.isVirtual || category.id in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) return
+ _uiState.update {
+ it.copy(
+ selectedCategoryForOptions = null,
+ showRenameGroupDialog = true,
+ groupToRename = category,
+ renameGroupError = null
+ )
+ }
+ }
+
+ fun cancelRenameGroup() {
+ _uiState.update {
+ it.copy(
+ showRenameGroupDialog = false,
+ groupToRename = null,
+ renameGroupError = null
+ )
+ }
+ }
+
+ fun confirmRenameGroup(name: String) {
+ val category = _uiState.value.groupToRename ?: return
+ val trimmed = name.trim()
+ when {
+ trimmed.isBlank() -> {
+ _uiState.update { it.copy(renameGroupError = appContext.getString(R.string.home_group_name_invalid)) }
+ return
+ }
+ trimmed.equals("Favorites", ignoreCase = true) -> {
+ _uiState.update { it.copy(renameGroupError = appContext.getString(R.string.home_group_name_reserved)) }
+ return
+ }
+ _uiState.value.categories.any { existing ->
+ existing.id != category.id && existing.name.equals(trimmed, ignoreCase = true)
+ } -> {
+ _uiState.update { it.copy(renameGroupError = appContext.getString(R.string.home_group_name_duplicate, trimmed)) }
+ return
+ }
+ }
+
+ viewModelScope.launch {
+ favoriteRepository.renameGroup(-category.id, trimmed)
+ _uiState.update {
+ it.copy(
+ showRenameGroupDialog = false,
+ groupToRename = null,
+ renameGroupError = null,
+ userMessage = appContext.getString(R.string.home_group_renamed, trimmed)
+ )
+ }
}
}
fun requestDeleteGroup(category: Category) {
- if (!category.isVirtual || category.id == -999L) return
- _uiState.update { it.copy(showDeleteGroupDialog = true, groupToDelete = category) }
+ if (!category.isVirtual || category.id in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) return
+ _uiState.update {
+ it.copy(
+ selectedCategoryForOptions = null,
+ showDeleteGroupDialog = true,
+ groupToDelete = category
+ )
+ }
}
fun cancelDeleteGroup() {
@@ -274,14 +418,14 @@ class HomeViewModel @Inject constructor(
it.copy(
showDeleteGroupDialog = false,
groupToDelete = null,
- userMessage = "Group '${category.name}' deleted"
+ userMessage = appContext.getString(R.string.home_group_deleted, category.name)
)
}
}
}
fun addToGroup(channel: Channel, category: Category) {
- if (!category.isVirtual || category.id == -999L) return
+ if (!category.isVirtual || category.id in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) return
viewModelScope.launch {
val groupId = -category.id
favoriteRepository.addFavorite(
@@ -295,7 +439,7 @@ class HomeViewModel @Inject constructor(
}
fun removeFromGroup(channel: Channel, category: Category) {
- if (!category.isVirtual || category.id == -999L) return
+ if (!category.isVirtual || category.id in setOf(VirtualCategoryIds.FAVORITES, VirtualCategoryIds.RECENT)) return
viewModelScope.launch {
val groupId = -category.id
favoriteRepository.removeFavorite(
@@ -310,7 +454,7 @@ class HomeViewModel @Inject constructor(
fun moveChannel(channel: Channel, direction: Int) {
val currentCategory = _uiState.value.selectedCategory ?: return
- if (!currentCategory.isVirtual) return
+ if (!currentCategory.isVirtual || currentCategory.id == VirtualCategoryIds.RECENT) return
val currentList = _localChannels.value.toMutableList()
val index = currentList.indexOfFirst { it.id == channel.id }
@@ -323,7 +467,7 @@ class HomeViewModel @Inject constructor(
_localChannels.value = currentList
viewModelScope.launch {
- val groupId = if (currentCategory.id == -999L) null else -currentCategory.id
+ val groupId = if (currentCategory.id == VirtualCategoryIds.FAVORITES) null else -currentCategory.id
val favoritesFlow = if (groupId == null) {
favoriteRepository.getFavorites(ContentType.LIVE)
@@ -405,7 +549,16 @@ class HomeViewModel @Inject constructor(
fun enterChannelReorderMode(category: Category) {
dismissCategoryOptions()
- _uiState.update { it.copy(isChannelReorderMode = true, reorderCategory = category) }
+ viewModelScope.launch {
+ val reorderChannels = loadReorderChannels(category)
+ _uiState.update {
+ it.copy(
+ isChannelReorderMode = true,
+ reorderCategory = category,
+ filteredChannels = reorderChannels
+ )
+ }
+ }
}
fun exitChannelReorderMode() {
@@ -442,6 +595,7 @@ class HomeViewModel @Inject constructor(
fun saveChannelReorder() {
val state = _uiState.value
val category = state.reorderCategory ?: return
+ if (category.id == VirtualCategoryIds.RECENT) return
val currentList = state.filteredChannels
// Exit reorder mode immediately for responsive UI
@@ -453,7 +607,7 @@ class HomeViewModel @Inject constructor(
viewModelScope.launch {
try {
// Map the virtual category ID back to the Favorite Group ID
- val groupId = if (category.id == -999L) null else -category.id
+ val groupId = if (category.id == VirtualCategoryIds.FAVORITES) null else -category.id
val favoritesFlow = if (groupId == null) {
favoriteRepository.getFavorites(ContentType.LIVE)
@@ -481,12 +635,48 @@ class HomeViewModel @Inject constructor(
}
}
}
+
+ private fun loadChannelsByOrderedIds(ids: List<Long>): Flow<List<Channel>> {
+ if (ids.isEmpty()) return flowOf(emptyList())
+
+ return channelRepository.getChannelsByIds(ids).map { unsorted ->
+ val channelsById = unsorted.associateBy { it.id }
+ ids.mapNotNull { channelsById[it] }
+ }
+ }
+
+ private suspend fun loadReorderChannels(category: Category): List<Channel> {
+ if (!category.isVirtual || category.id == VirtualCategoryIds.RECENT) return emptyList()
+
+ val groupId = if (category.id == VirtualCategoryIds.FAVORITES) null else -category.id
+ val favorites = if (groupId == null) {
+ favoriteRepository.getFavorites(ContentType.LIVE).first()
+ } else {
+ favoriteRepository.getFavoritesByGroup(groupId).first()
+ }
+
+ val orderedIds = favorites
+ .sortedBy { it.position }
+ .map { it.contentId }
+
+ return loadChannelsByOrderedIds(orderedIds).first()
+ }
+
+ private fun List<PlaybackHistory>.toRecentLiveContentIds(): List<Long> =
+ asSequence()
+ .filter { it.contentType == ContentType.LIVE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.contentId }
+ .map { it.contentId }
+ .toList()
}
data class HomeUiState(
val provider: Provider? = null,
val allProviders: List<Provider> = emptyList(),
val categories: List<Category> = emptyList(),
+ val recentChannels: List<Channel> = emptyList(),
+ val lastVisitedCategory: Category? = null,
val selectedCategory: Category? = null,
val filteredChannels: List<Channel> = emptyList(),
val hasChannels: Boolean = false,
@@ -497,6 +687,9 @@ data class HomeUiState(
val selectedChannelForDialog: Channel? = null,
val dialogGroupMemberships: List<Long> = emptyList(),
val userMessage: String? = null,
+ val showRenameGroupDialog: Boolean = false,
+ val groupToRename: Category? = null,
+ val renameGroupError: String? = null,
val showDeleteGroupDialog: Boolean = false,
val groupToDelete: Category? = null,
val parentalControlLevel: Int = 0,
@@ -504,3 +697,9 @@ data class HomeUiState(
val isChannelReorderMode: Boolean = false,
val reorderCategory: Category? = null
)
+
+private data class CategorySelectionContext(
+ val categories: List<Category>,
+ val defaultCategoryId: Long?,
+ val lastVisitedCategoryId: Long?
+)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
index 938c31c3..875fa774 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
@@ -36,6 +36,11 @@ import com.streamvault.app.navigation.Routes
import com.streamvault.app.ui.components.CategoryRow
import com.streamvault.app.ui.components.ContinueWatchingRow
import com.streamvault.app.ui.components.MovieCard
+import com.streamvault.app.ui.components.SelectionChip
+import com.streamvault.app.ui.components.SelectionChipRow
+import com.streamvault.app.ui.components.SavedCategoryContextCard
+import com.streamvault.app.ui.components.SavedCategoryShortcut
+import com.streamvault.app.ui.components.SavedCategoryShortcutsRow
import com.streamvault.app.ui.components.SkeletonRow
import com.streamvault.app.ui.components.TopNavBar
import com.streamvault.app.ui.theme.*
@@ -45,10 +50,14 @@ import androidx.compose.ui.res.stringResource
import com.streamvault.app.R
import androidx.compose.ui.text.input.TextFieldValue
import androidx.compose.foundation.border
+import androidx.compose.runtime.saveable.rememberSaveable
import com.streamvault.app.ui.components.ReorderTopBar
import com.streamvault.app.ui.components.dialogs.DeleteGroupDialog
import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.SnackbarHostState
import androidx.tv.material3.Border
+import com.streamvault.app.ui.components.dialogs.RenameGroupDialog
@OptIn(ExperimentalFoundationApi::class)
@Composable
@@ -59,12 +68,23 @@ fun MoviesScreen(
viewModel: MoviesViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsState()
+ val snackbarHostState = remember { SnackbarHostState() }
var showPinDialog by remember { mutableStateOf(false) }
var pinError by remember { mutableStateOf<String?>(null) }
var pendingMovie by remember { mutableStateOf<Movie?>(null) }
+ var selectedLibraryLens by rememberSaveable { mutableStateOf(MovieLibraryLens.FAVORITES.name) }
+ var selectedFacet by rememberSaveable { mutableStateOf(MovieLibraryFacet.ALL.name) }
+ var selectedSort by rememberSaveable { mutableStateOf(MovieLibrarySort.LIBRARY.name) }
val scope = rememberCoroutineScope()
val context = androidx.compose.ui.platform.LocalContext.current
+ LaunchedEffect(uiState.userMessage) {
+ uiState.userMessage?.let { message ->
+ snackbarHostState.showSnackbar(message)
+ viewModel.userMessageShown()
+ }
+ }
+
if (showPinDialog) {
com.streamvault.app.ui.components.dialogs.PinDialog(
onDismissRequest = {
@@ -88,7 +108,8 @@ fun MoviesScreen(
)
}
- Column(modifier = Modifier.fillMaxSize()) {
+ Box(modifier = Modifier.fillMaxSize()) {
+ Column(modifier = Modifier.fillMaxSize()) {
if (uiState.isReorderMode && uiState.reorderCategory != null) {
ReorderTopBar(
categoryName = uiState.reorderCategory!!.name,
@@ -122,6 +143,43 @@ fun MoviesScreen(
Row(modifier = Modifier.fillMaxSize()) {
val focusManager = LocalFocusManager.current
val categorySearchFocusRequester = remember { FocusRequester() }
+ val categoryFocusRequesters = remember { mutableMapOf<String, FocusRequester>() }
+ var lastFocusedCategoryName by rememberSaveable { mutableStateOf<String?>(null) }
+ var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }
+ var preferCategoryRestore by rememberSaveable { mutableStateOf(false) }
+ val heroMovie = remember(uiState.categoryNames, uiState.moviesByCategory) {
+ uiState.categoryNames
+ .asSequence()
+ .mapNotNull { categoryName -> uiState.moviesByCategory[categoryName]?.firstOrNull() }
+ .firstOrNull()
+ }
+
+ LaunchedEffect(
+ uiState.selectedCategoryForOptions,
+ uiState.showRenameGroupDialog,
+ uiState.showDeleteGroupDialog
+ ) {
+ val modalClosed =
+ uiState.selectedCategoryForOptions == null &&
+ !uiState.showRenameGroupDialog &&
+ !uiState.showDeleteGroupDialog
+ if (modalClosed && preferCategoryRestore && lastFocusedCategoryName != null) {
+ shouldRestoreCategoryFocus = true
+ preferCategoryRestore = false
+ }
+ }
+
+ LaunchedEffect(shouldRestoreCategoryFocus, uiState.categoryNames) {
+ if (!shouldRestoreCategoryFocus) return@LaunchedEffect
+ kotlinx.coroutines.delay(80)
+ val categoryName = lastFocusedCategoryName
+ if (categoryName != null) {
+ runCatching {
+ categoryFocusRequesters[categoryName]?.requestFocus()
+ }
+ }
+ shouldRestoreCategoryFocus = false
+ }
Column(
modifier = Modifier
@@ -133,7 +191,7 @@ fun MoviesScreen(
// Sticky Header
Column(modifier = Modifier.padding(horizontal = 16.dp)) {
Text(
- text = "Categories",
+ text = stringResource(R.string.movies_categories_title),
style = MaterialTheme.typography.titleMedium,
color = Primary,
modifier = Modifier.padding(vertical = 8.dp)
@@ -142,7 +200,7 @@ fun MoviesScreen(
SearchInput(
value = uiState.searchQuery,
onValueChange = { viewModel.setSearchQuery(it) },
- placeholder = "Search movies...",
+ placeholder = stringResource(R.string.movies_search_placeholder),
focusRequester = categorySearchFocusRequester,
modifier = Modifier.padding(bottom = 8.dp)
)
@@ -153,7 +211,7 @@ fun MoviesScreen(
contentPadding = PaddingValues(bottom = 8.dp)
) {
item {
- val isAllSelected = uiState.selectedCategory == null
+ val isAllSelected = uiState.selectedCategory == null || uiState.selectedCategory == uiState.fullLibraryCategoryName
Surface(
onClick = { viewModel.selectCategory(null) },
shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(8.dp)),
@@ -178,13 +236,13 @@ fun MoviesScreen(
verticalAlignment = Alignment.CenterVertically
) {
Text(
- text = "All Categories",
+ text = stringResource(R.string.movies_all_categories),
style = MaterialTheme.typography.bodyMedium,
color = if (isAllSelected) Primary else OnSurface,
modifier = Modifier.weight(1f)
)
Text(
- text = "${uiState.moviesByCategory.values.sumOf { it.size }}",
+ text = "${uiState.libraryCount}",
style = MaterialTheme.typography.labelSmall,
color = OnSurfaceDim
)
@@ -194,10 +252,13 @@ fun MoviesScreen(
items(uiState.categoryNames.size) { index ->
val categoryName = uiState.categoryNames[index]
val isSelected = uiState.selectedCategory == categoryName
- val count = uiState.moviesByCategory[categoryName]?.size ?: 0
+ val count = uiState.categoryCounts[categoryName] ?: 0
Surface(
onClick = { viewModel.selectCategory(categoryName) },
- onLongClick = { viewModel.showCategoryOptions(categoryName) },
+ onLongClick = {
+ preferCategoryRestore = true
+ viewModel.showCategoryOptions(categoryName)
+ },
shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(8.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isSelected) Primary.copy(alpha = 0.15f) else Color.Transparent,
@@ -206,6 +267,12 @@ fun MoviesScreen(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 2.dp)
+ .focusRequester(categoryFocusRequesters.getOrPut(categoryName) { FocusRequester() })
+ .onFocusChanged { focusState ->
+ if (focusState.isFocused) {
+ lastFocusedCategoryName = categoryName
+ }
+ }
.onPreviewKeyEvent { event ->
if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT) {
@@ -238,8 +305,58 @@ fun MoviesScreen(
}
}
+ val savedShortcuts = remember(
+ uiState.favoriteCategoryName,
+ uiState.categories,
+ uiState.moviesByCategory
+ ) {
+ buildList {
+ val favoriteCount = uiState.categoryCounts[uiState.favoriteCategoryName] ?: 0
+ if (favoriteCount > 0) {
+ add(
+ SavedCategoryShortcut(
+ name = uiState.favoriteCategoryName,
+ count = favoriteCount
+ )
+ )
+ }
+ uiState.categories
+ .asSequence()
+ .filterNot { it.name == uiState.favoriteCategoryName }
+ .map { category ->
+ SavedCategoryShortcut(
+ name = category.name,
+ count = uiState.categoryCounts[category.name] ?: 0
+ )
+ }
+ .filter { it.count > 0 }
+ .sortedByDescending { it.count }
+ .forEach(::add)
+ }
+ }
+ val selectedSavedCategory = remember(
+ uiState.selectedCategory,
+ uiState.favoriteCategoryName,
+ uiState.categories
+ ) {
+ when (uiState.selectedCategory) {
+ null -> null
+ uiState.favoriteCategoryName -> com.streamvault.domain.model.Category(
+ id = -999L,
+ name = uiState.favoriteCategoryName,
+ type = com.streamvault.domain.model.ContentType.MOVIE,
+ isVirtual = true
+ )
+ else -> uiState.categories.firstOrNull { it.name == uiState.selectedCategory }
+ }
+ }
+
// Main content
if (uiState.selectedCategory == null) {
+ val activeLibraryLens = remember(selectedLibraryLens, uiState.libraryLensRows) {
+ MovieLibraryLens.entries.firstOrNull { it.name == selectedLibraryLens && uiState.libraryLensRows.containsKey(it) }
+ ?: uiState.libraryLensRows.keys.firstOrNull()
+ }
// Netflix-style rows (All categories view)
LazyColumn(
modifier = Modifier.fillMaxSize().weight(1f),
@@ -272,7 +389,6 @@ fun MoviesScreen(
}
}
- val heroMovie = uiState.moviesByCategory.values.flatten().firstOrNull()
if (heroMovie != null) {
item {
HeroBanner(
@@ -290,6 +406,97 @@ fun MoviesScreen(
}
}
+ item(key = "saved_shortcuts") {
+ SavedCategoryShortcutsRow(
+ title = stringResource(R.string.library_saved_title),
+ subtitle = stringResource(R.string.library_saved_subtitle),
+ emptyHint = stringResource(R.string.movies_saved_empty_hint),
+ shortcuts = savedShortcuts,
+ managementHint = stringResource(R.string.library_saved_manage_hint),
+ primaryShortcutLabel = stringResource(R.string.library_browse_all),
+ isPrimaryShortcutSelected = uiState.selectedCategory == null,
+ onPrimaryShortcutClick = { viewModel.selectCategory(null) },
+ selectedShortcutName = uiState.selectedCategory,
+ onShortcutLongClick = viewModel::showCategoryOptions,
+ onShortcutClick = viewModel::selectCategory
+ )
+ }
+
+ if (activeLibraryLens != null) {
+ item(key = "library_lens_chips") {
+ SelectionChipRow(
+ title = stringResource(R.string.library_lens_title),
+ subtitle = stringResource(R.string.movies_library_lens_subtitle),
+ chips = uiState.libraryLensRows.keys.map { lens ->
+ SelectionChip(
+ key = lens.name,
+ label = movieLibraryLensLabel(lens),
+ supportingText = stringResource(
+ R.string.library_saved_items_count,
+ uiState.libraryLensRows[lens]?.size ?: 0
+ )
+ )
+ },
+ selectedKey = activeLibraryLens.name,
+ onChipSelected = { selectedLibraryLens = it },
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ }
+
+ item(key = "library_lens_row") {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Surface(
+ onClick = viewModel::selectFullLibraryBrowse,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.06f),
+ focusedContainerColor = Primary
+ ),
+ modifier = Modifier.padding(horizontal = 16.dp)
+ ) {
+ Column(modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp)) {
+ Text(
+ text = stringResource(R.string.library_full_browse_title_movies),
+ style = MaterialTheme.typography.titleSmall,
+ color = Color.White
+ )
+ Spacer(Modifier.height(4.dp))
+ Text(
+ text = stringResource(R.string.library_full_browse_subtitle, uiState.libraryCount),
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.8f)
+ )
+ }
+ }
+
+ CategoryRow(
+ title = movieLibraryLensLabel(activeLibraryLens),
+ items = uiState.libraryLensRows[activeLibraryLens].orEmpty(),
+ onSeeAll = if (activeLibraryLens == MovieLibraryLens.FAVORITES) {
+ { viewModel.selectCategory(uiState.favoriteCategoryName) }
+ } else {
+ null
+ }
+ ) { movie ->
+ val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ MovieCard(
+ movie = movie,
+ isLocked = isLocked,
+ onClick = {
+ if (isLocked) {
+ pendingMovie = movie
+ showPinDialog = true
+ } else {
+ onMovieClick(movie)
+ }
+ },
+ onLongClick = { viewModel.onShowDialog(movie) }
+ )
+ }
+ }
+ }
+ }
+
// Continue Watching row (shown first, only if non-empty)
item(key = "continue_watching") {
ContinueWatchingRow(
@@ -309,7 +516,11 @@ fun MoviesScreen(
items = uiState.moviesByCategory.entries.toList(),
key = { it.key }
) { (categoryName, movies) ->
- CategoryRow(title = categoryName, items = movies) { movie ->
+ CategoryRow(
+ title = categoryName,
+ items = movies,
+ onSeeAll = { viewModel.selectCategory(categoryName) }
+ ) { movie ->
val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
MovieCard(
movie = movie,
@@ -331,8 +542,35 @@ fun MoviesScreen(
}
} else {
// Filtered grid for selected category
- val filteredMovies = uiState.moviesByCategory[uiState.selectedCategory] ?: emptyList()
- val activeMovies = if (uiState.isReorderMode) uiState.filteredMovies else filteredMovies
+ val baseMovies = if (uiState.searchQuery.isBlank()) {
+ uiState.selectedCategoryItems
+ } else {
+ uiState.moviesByCategory[uiState.selectedCategory] ?: emptyList()
+ }
+ val activeMovies = if (uiState.isReorderMode) uiState.filteredMovies else baseMovies
+ val resumeMovieIds = remember(uiState.continueWatching) {
+ uiState.continueWatching.map { it.contentId }.toSet()
+ }
+ val activeFacet = remember(selectedFacet) {
+ MovieLibraryFacet.entries.firstOrNull { it.name == selectedFacet } ?: MovieLibraryFacet.ALL
+ }
+ val activeSort = remember(selectedSort) {
+ MovieLibrarySort.entries.firstOrNull { it.name == selectedSort } ?: MovieLibrarySort.LIBRARY
+ }
+ val filteredGridMovies = remember(activeMovies, activeFacet, activeSort, resumeMovieIds, uiState.isReorderMode) {
+ if (uiState.isReorderMode) {
+ activeMovies
+ } else {
+ applyMovieFacetAndSort(
+ items = activeMovies,
+ facet = activeFacet,
+ sort = activeSort,
+ resumeMovieIds = resumeMovieIds
+ )
+ }
+ }
+ val showSelectedCategoryControls = !uiState.isReorderMode &&
+ (selectedSavedCategory != null || activeMovies.size > 8)
var draggingMovie by remember { mutableStateOf<Movie?>(null) }
@@ -342,88 +580,209 @@ fun MoviesScreen(
}
}
- LazyVerticalGrid(
- columns = GridCells.Adaptive(minSize = 160.dp),
+ Column(
modifier = Modifier
.fillMaxSize()
.weight(1f)
- .onPreviewKeyEvent { event ->
- if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
- if (draggingMovie != null) {
- draggingMovie = null
- true
- } else {
- viewModel.exitCategoryReorderMode()
- true
- }
- } else false
- } else false
- },
- contentPadding = PaddingValues(16.dp),
- horizontalArrangement = Arrangement.spacedBy(16.dp),
- verticalArrangement = Arrangement.spacedBy(16.dp)
) {
- item(span = { GridItemSpan(maxLineSpan) }) {
- Text(
- text = uiState.selectedCategory ?: "",
- style = MaterialTheme.typography.headlineSmall,
- color = Primary,
- fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,
- modifier = Modifier.padding(bottom = 16.dp)
+ if (selectedSavedCategory != null) {
+ SavedCategoryShortcutsRow(
+ title = stringResource(R.string.library_saved_title),
+ subtitle = stringResource(R.string.library_saved_subtitle),
+ emptyHint = stringResource(R.string.movies_saved_empty_hint),
+ shortcuts = savedShortcuts,
+ managementHint = stringResource(R.string.library_saved_manage_hint),
+ primaryShortcutLabel = stringResource(R.string.library_browse_all),
+ isPrimaryShortcutSelected = uiState.selectedCategory == null,
+ onPrimaryShortcutClick = { viewModel.selectCategory(null) },
+ selectedShortcutName = uiState.selectedCategory,
+ onShortcutLongClick = viewModel::showCategoryOptions,
+ onShortcutClick = viewModel::selectCategory
+ )
+
+ SavedCategoryContextCard(
+ categoryName = selectedSavedCategory.name,
+ itemCount = uiState.categoryCounts[selectedSavedCategory.name] ?: filteredGridMovies.size,
+ onManageClick = { viewModel.showCategoryOptions(selectedSavedCategory.name) },
+ onBrowseAllClick = { viewModel.selectCategory(null) },
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)
)
}
-
- gridItems(
- items = activeMovies,
- key = { it.id }
- ) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
- val isDraggingThis = draggingMovie == movie
-
- MovieCard(
- movie = movie,
- isLocked = isLocked,
- isReorderMode = uiState.isReorderMode,
- isDragging = isDraggingThis,
- onClick = {
- if (uiState.isReorderMode) {
- draggingMovie = if (isDraggingThis) null else movie
- } else if (isLocked) {
- pendingMovie = movie
- showPinDialog = true
- } else {
- onMovieClick(movie)
- }
- },
- onLongClick = {
- if (!uiState.isReorderMode) {
- viewModel.onShowDialog(movie)
- }
+
+ if (showSelectedCategoryControls) {
+ SelectionChipRow(
+ title = stringResource(R.string.library_filter_title),
+ chips = buildMovieFacetChips(
+ items = activeMovies,
+ resumeMovieIds = resumeMovieIds
+ ),
+ selectedKey = activeFacet.name,
+ onChipSelected = { selectedFacet = it },
+ modifier = Modifier.padding(horizontal = 16.dp),
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+
+ SelectionChipRow(
+ title = stringResource(R.string.library_sort_title),
+ chips = MovieLibrarySort.entries.map { sort ->
+ SelectionChip(
+ key = sort.name,
+ label = when (sort) {
+ MovieLibrarySort.LIBRARY -> stringResource(R.string.library_sort_library)
+ MovieLibrarySort.TITLE -> stringResource(R.string.library_sort_az)
+ MovieLibrarySort.RELEASE -> stringResource(R.string.library_sort_release)
+ MovieLibrarySort.RATING -> stringResource(R.string.library_sort_rating)
+ }
+ )
},
- modifier = Modifier.onPreviewKeyEvent { event ->
- if (uiState.isReorderMode && isDraggingThis && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
- when (event.nativeKeyEvent.keyCode) {
- android.view.KeyEvent.KEYCODE_DPAD_LEFT,
- android.view.KeyEvent.KEYCODE_DPAD_UP -> {
- viewModel.moveItemUp(movie)
+ selectedKey = activeSort.name,
+ onChipSelected = { selectedSort = it },
+ modifier = Modifier.padding(horizontal = 16.dp),
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ }
+
+ LazyVerticalGrid(
+ columns = GridCells.Adaptive(minSize = 160.dp),
+ modifier = Modifier
+ .fillMaxSize()
+ .onPreviewKeyEvent { event ->
+ if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
+ if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
+ if (draggingMovie != null) {
+ draggingMovie = null
true
- }
- android.view.KeyEvent.KEYCODE_DPAD_RIGHT,
- android.view.KeyEvent.KEYCODE_DPAD_DOWN -> {
- viewModel.moveItemDown(movie)
+ } else {
+ viewModel.exitCategoryReorderMode()
true
}
- else -> false
- }
+ } else false
} else false
+ },
+ contentPadding = PaddingValues(16.dp),
+ horizontalArrangement = Arrangement.spacedBy(16.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Column(modifier = Modifier.padding(bottom = 16.dp)) {
+ Text(
+ text = when (uiState.selectedCategory) {
+ uiState.fullLibraryCategoryName -> stringResource(R.string.library_full_browse_title_movies)
+ else -> uiState.selectedCategory ?: ""
+ },
+ style = MaterialTheme.typography.headlineSmall,
+ color = Primary,
+ fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
+ )
+ if (!uiState.isReorderMode && uiState.selectedCategoryTotalCount > 0) {
+ Spacer(Modifier.height(6.dp))
+ Text(
+ text = stringResource(
+ R.string.library_loaded_results,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
}
- )
+ }
+
+ if (filteredGridMovies.isEmpty()) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Text(
+ text = stringResource(R.string.library_filter_empty),
+ style = MaterialTheme.typography.bodyLarge,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(bottom = 12.dp)
+ )
+ }
+ }
+
+ gridItems(
+ items = filteredGridMovies,
+ key = { it.id }
+ ) { movie ->
+ val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ val isDraggingThis = draggingMovie == movie
+
+ MovieCard(
+ movie = movie,
+ isLocked = isLocked,
+ isReorderMode = uiState.isReorderMode,
+ isDragging = isDraggingThis,
+ onClick = {
+ if (uiState.isReorderMode) {
+ draggingMovie = if (isDraggingThis) null else movie
+ } else if (isLocked) {
+ pendingMovie = movie
+ showPinDialog = true
+ } else {
+ onMovieClick(movie)
+ }
+ },
+ onLongClick = {
+ if (!uiState.isReorderMode) {
+ viewModel.onShowDialog(movie)
+ }
+ },
+ modifier = Modifier.onPreviewKeyEvent { event ->
+ if (uiState.isReorderMode && isDraggingThis && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
+ when (event.nativeKeyEvent.keyCode) {
+ android.view.KeyEvent.KEYCODE_DPAD_LEFT,
+ android.view.KeyEvent.KEYCODE_DPAD_UP -> {
+ viewModel.moveItemUp(movie)
+ true
+ }
+ android.view.KeyEvent.KEYCODE_DPAD_RIGHT,
+ android.view.KeyEvent.KEYCODE_DPAD_DOWN -> {
+ viewModel.moveItemDown(movie)
+ true
+ }
+ else -> false
+ }
+ } else false
+ }
+ )
+ }
+
+ if (!uiState.isReorderMode && uiState.canLoadMoreSelectedCategory) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Surface(
+ onClick = viewModel::loadMoreSelectedCategory,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.06f),
+ focusedContainerColor = Primary
+ ),
+ modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)
+ ) {
+ Text(
+ text = stringResource(
+ R.string.library_load_more,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White,
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp)
+ )
+ }
+ }
+ }
}
}
}
}
}
+ }
+ SnackbarHost(
+ hostState = snackbarHostState,
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .padding(bottom = 16.dp)
+ )
}
if (uiState.showDialog && uiState.selectedMovieForDialog != null) {
@@ -448,9 +807,11 @@ fun MoviesScreen(
com.streamvault.app.ui.components.dialogs.CategoryOptionsDialog(
category = category,
onDismissRequest = { viewModel.dismissCategoryOptions() },
+ onRename = if (category.isVirtual && category.id != -999L) {
+ { viewModel.requestRenameGroup(category) }
+ } else null,
onDelete = if (category.isVirtual && category.id != -999L) {
{
- viewModel.dismissCategoryOptions()
viewModel.requestDeleteGroup(category)
}
} else null,
@@ -460,6 +821,15 @@ fun MoviesScreen(
)
}
+ if (uiState.showRenameGroupDialog && uiState.groupToRename != null) {
+ RenameGroupDialog(
+ initialName = uiState.groupToRename!!.name,
+ errorMessage = uiState.renameGroupError,
+ onDismissRequest = { viewModel.cancelRenameGroup() },
+ onConfirm = { name -> viewModel.confirmRenameGroup(name) }
+ )
+ }
+
if (uiState.showDeleteGroupDialog && uiState.groupToDelete != null) {
DeleteGroupDialog(
groupName = uiState.groupToDelete!!.name,
@@ -552,3 +922,75 @@ fun HeroBanner(
}
}
}
+
+private enum class MovieLibraryFacet {
+ ALL,
+ FAVORITES,
+ RESUME,
+ UNWATCHED,
+ TOP_RATED
+}
+
+private enum class MovieLibrarySort {
+ LIBRARY,
+ TITLE,
+ RELEASE,
+ RATING
+}
+
+@Composable
+private fun movieLibraryLensLabel(lens: MovieLibraryLens): String =
+ when (lens) {
+ MovieLibraryLens.FAVORITES -> stringResource(R.string.library_lens_favorites)
+ MovieLibraryLens.CONTINUE -> stringResource(R.string.library_lens_continue)
+ MovieLibraryLens.TOP_RATED -> stringResource(R.string.library_lens_top_rated)
+ MovieLibraryLens.FRESH -> stringResource(R.string.library_lens_fresh_movies)
+ }
+
+private fun buildMovieFacetChips(
+ items: List<Movie>,
+ resumeMovieIds: Set<Long>
+): List<SelectionChip> {
+ val favoriteCount = items.count { it.isFavorite }
+ val resumeCount = items.count { it.id in resumeMovieIds || it.watchProgress > 0L }
+ val unwatchedCount = items.count { it.watchProgress <= 0L && it.id !in resumeMovieIds }
+ val topRatedCount = items.count { it.rating > 0f }
+ return listOf(
+ SelectionChip(MovieLibraryFacet.ALL.name, "All", "${items.size} visible"),
+ SelectionChip(MovieLibraryFacet.FAVORITES.name, "Favorites", "$favoriteCount saved"),
+ SelectionChip(MovieLibraryFacet.RESUME.name, "Resume", "$resumeCount in progress"),
+ SelectionChip(MovieLibraryFacet.UNWATCHED.name, "Unwatched", "$unwatchedCount not started"),
+ SelectionChip(MovieLibraryFacet.TOP_RATED.name, "Top Rated", "$topRatedCount rated")
+ )
+}
+
+private fun applyMovieFacetAndSort(
+ items: List<Movie>,
+ facet: MovieLibraryFacet,
+ sort: MovieLibrarySort,
+ resumeMovieIds: Set<Long>
+): List<Movie> {
+ val filtered = when (facet) {
+ MovieLibraryFacet.ALL -> items
+ MovieLibraryFacet.FAVORITES -> items.filter { it.isFavorite }
+ MovieLibraryFacet.RESUME -> items.filter { it.id in resumeMovieIds || it.watchProgress > 0L }
+ MovieLibraryFacet.UNWATCHED -> items.filter { it.watchProgress <= 0L && it.id !in resumeMovieIds }
+ MovieLibraryFacet.TOP_RATED -> items.filter { it.rating > 0f }
+ }
+
+ return when (sort) {
+ MovieLibrarySort.LIBRARY -> filtered
+ MovieLibrarySort.TITLE -> filtered.sortedBy { it.name.lowercase() }
+ MovieLibrarySort.RELEASE -> filtered.sortedByDescending(::movieReleaseScore)
+ MovieLibrarySort.RATING -> filtered.sortedByDescending { it.rating }
+ }
+}
+
+private fun movieReleaseScore(movie: Movie): Long {
+ return movie.releaseDate
+ ?.filter { it.isDigit() }
+ ?.take(8)
+ ?.toLongOrNull()
+ ?: movie.year?.toLongOrNull()
+ ?: 0L
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
index 26dbf491..a66c2d3a 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
@@ -3,21 +3,45 @@ package com.streamvault.app.ui.screens.movies
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.usecase.GetCustomCategories
import dagger.hilt.android.lifecycle.HiltViewModel
-import kotlinx.coroutines.flow.*
-import kotlinx.coroutines.launch
import javax.inject.Inject
-import com.streamvault.domain.model.Category
-import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.repository.FavoriteRepository
-import com.streamvault.domain.usecase.GetCustomCategories
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.filterNotNull
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+enum class MovieLibraryLens {
+ FAVORITES,
+ CONTINUE,
+ TOP_RATED,
+ FRESH
+}
@HiltViewModel
+@OptIn(ExperimentalCoroutinesApi::class)
class MoviesViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val movieRepository: MovieRepository,
@@ -26,93 +50,254 @@ class MoviesViewModel @Inject constructor(
private val favoriteRepository: FavoriteRepository,
private val getCustomCategories: GetCustomCategories
) : ViewModel() {
+ private companion object {
+ const val UNCATEGORIZED = "Uncategorized"
+ const val FAVORITES_CATEGORY = "\u2605 Favorites"
+ const val FAVORITES_SENTINEL_ID = -999L
+ const val FULL_LIBRARY_CATEGORY = "__full_library__"
+ const val PREVIEW_ROW_LIMIT = 18
+ const val SELECTED_CATEGORY_PAGE_SIZE = 60
+ }
private val _uiState = MutableStateFlow(MoviesUiState())
val uiState: StateFlow<MoviesUiState> = _uiState.asStateFlow()
private val _searchQuery = MutableStateFlow("")
- private val _localMovies = MutableStateFlow<List<Movie>>(emptyList())
+ private val _selectedCategoryLoadLimit = MutableStateFlow(SELECTED_CATEGORY_PAGE_SIZE)
init {
viewModelScope.launch {
providerRepository.getActiveProvider()
.filterNotNull()
- .collectLatest { provider ->
- // Movies by category
- launch {
- combine(
- movieRepository.getMovies(provider.id),
- favoriteRepository.getAllFavorites(ContentType.MOVIE),
- getCustomCategories(ContentType.MOVIE),
- _searchQuery
- ) { movies, allFavorites, customCats, query ->
- // 1. Mark global favorites
- val globalFavoriteIds = allFavorites.filter { it.groupId == null }.map { it.contentId }.toSet()
- val enrichedMovies = movies.map { it.copy(isFavorite = globalFavoriteIds.contains(it.id)) }
-
- // 2. Filter by search query
- val filtered = if (query.isBlank()) enrichedMovies
- else enrichedMovies.filter { it.name.contains(query, ignoreCase = true) }
-
- // 3. Group by default category
- val grouped = filtered.groupBy { it.categoryName ?: "Uncategorized" }.toMutableMap()
-
- // 4. Always add "★ Favorites" even if empty
- grouped["★ Favorites"] = enrichedMovies.filter { it.isFavorite }
-
- // 5. Always add Custom Groups even if empty, and populate them
- customCats.filter { it.id != -999L }.forEach { customCategory ->
- val groupId = -customCategory.id // Restore actual group DB ID
- val movieIdsInGroup = allFavorites.filter { it.groupId == groupId }.map { it.contentId }.toSet()
- grouped[customCategory.name] = enrichedMovies.filter { movieIdsInGroup.contains(it.id) }
+ .flatMapLatest { provider ->
+ combine(
+ favoriteRepository.getAllFavorites(ContentType.MOVIE),
+ getCustomCategories(ContentType.MOVIE),
+ movieRepository.getCategories(provider.id),
+ movieRepository.getCategoryItemCounts(provider.id),
+ movieRepository.getLibraryCount(provider.id)
+ ) { allFavorites, customCategories, providerCategories, providerCategoryCounts, libraryCount ->
+ MovieCatalogDependencies(
+ allFavorites = allFavorites,
+ customCategories = customCategories,
+ providerCategories = providerCategories,
+ providerCategoryCounts = providerCategoryCounts,
+ libraryCount = libraryCount
+ )
+ }.combine(_searchQuery) { dependencies, query ->
+ MovieCatalogParams(
+ providerId = provider.id,
+ allFavorites = dependencies.allFavorites,
+ customCategories = dependencies.customCategories,
+ providerCategories = dependencies.providerCategories,
+ providerCategoryCounts = dependencies.providerCategoryCounts,
+ libraryCount = dependencies.libraryCount,
+ query = query.trim()
+ )
+ }
+ }
+ .flatMapLatest { params ->
+ flow {
+ emit(
+ if (params.query.isBlank()) {
+ buildPreviewCatalog(params)
+ } else {
+ val searchResults = movieRepository.searchMovies(params.providerId, params.query).first()
+ buildSearchCatalog(
+ movies = searchResults,
+ allFavorites = params.allFavorites,
+ customCategories = params.customCategories
+ ).copy(libraryCount = searchResults.size)
}
+ )
+ }
+ }
+ .collect { snapshot ->
+ val isReordering = _uiState.value.isReorderMode
+ _uiState.update {
+ it.copy(
+ moviesByCategory = snapshot.grouped,
+ categoryNames = snapshot.categoryNames,
+ categoryCounts = snapshot.categoryCounts,
+ libraryCount = snapshot.libraryCount,
+ filteredMovies = if (isReordering) it.filteredMovies else emptyList(),
+ isLoading = false
+ )
+ }
+ }
+ }
- // 6. Sort category names, ensuring "★ Favorites" is first, followed by custom groups
- val customNames = customCats.map { it.name }
- val categoryNames = grouped.keys.sortedWith(compareBy<String> {
- when (it) {
- "★ Favorites" -> 0
- in customNames -> 1
- else -> 2
- }
- }.thenBy { it })
-
- grouped to categoryNames
- }.collect { (grouped, categoryNames) ->
- val isReordering = _uiState.value.isReorderMode
- _uiState.update { it.copy(
- moviesByCategory = grouped,
- categoryNames = categoryNames,
- filteredMovies = if (isReordering) it.filteredMovies else emptyList(),
- isLoading = false
- ) }
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .flatMapLatest { provider ->
+ combine(
+ favoriteRepository.getAllFavorites(ContentType.MOVIE),
+ getCustomCategories(ContentType.MOVIE),
+ movieRepository.getCategories(provider.id),
+ movieRepository.getCategoryItemCounts(provider.id)
+ ) { allFavorites, customCategories, providerCategories, providerCategoryCounts ->
+ MovieCategorySelectionDependencies(
+ allFavorites = allFavorites,
+ customCategories = customCategories,
+ providerCategories = providerCategories,
+ providerCategoryCounts = providerCategoryCounts
+ )
+ }.combine(
+ combine(
+ _uiState.map { it.selectedCategory }.distinctUntilChanged(),
+ _selectedCategoryLoadLimit,
+ _searchQuery
+ ) { selectedCategory, loadLimit, query ->
+ Triple(selectedCategory, loadLimit, query.trim())
}
+ ) { dependencies, selection ->
+ SelectedMovieCategoryRequest(
+ providerId = provider.id,
+ selectedCategory = selection.first,
+ loadLimit = selection.second,
+ query = selection.third,
+ allFavorites = dependencies.allFavorites,
+ customCategories = dependencies.customCategories,
+ providerCategories = dependencies.providerCategories,
+ providerCategoryCounts = dependencies.providerCategoryCounts
+ )
}
- // Continue Watching — last 20 movie/series items for this provider
+ }
+ .flatMapLatest { request ->
+ flow {
+ emit(loadSelectedCategoryItems(request))
+ }
+ }
+ .collect { snapshot ->
+ _uiState.update {
+ it.copy(
+ selectedCategoryItems = snapshot.items,
+ selectedCategoryLoadedCount = snapshot.loadedCount,
+ selectedCategoryTotalCount = snapshot.totalCount,
+ canLoadMoreSelectedCategory = snapshot.canLoadMore
+ )
+ }
+ }
+ }
+
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .collectLatest { provider ->
launch {
playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 20)
.collect { history ->
- _uiState.update { it.copy(continueWatching = history) }
+ _uiState.update {
+ it.copy(
+ continueWatching = history.filter { entry ->
+ entry.contentType == ContentType.MOVIE
+ }
+ )
+ }
}
}
}
}
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .flatMapLatest { provider ->
+ combine(
+ favoriteRepository.getAllFavorites(ContentType.MOVIE),
+ playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 24),
+ movieRepository.getTopRatedPreview(provider.id, PREVIEW_ROW_LIMIT),
+ movieRepository.getFreshPreview(provider.id, PREVIEW_ROW_LIMIT)
+ ) { allFavorites, history, topRated, fresh ->
+ MovieLibraryLensDependencies(
+ providerId = provider.id,
+ allFavorites = allFavorites,
+ history = history,
+ topRated = topRated,
+ fresh = fresh
+ )
+ }
+ }
+ .collectLatest { dependencies ->
+ val globalFavoriteIds = dependencies.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val favoriteIds = dependencies.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .take(PREVIEW_ROW_LIMIT)
+ .toList()
+ val continueIds = dependencies.history
+ .asSequence()
+ .filter { it.contentType == ContentType.MOVIE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.contentId }
+ .map { it.contentId }
+ .take(PREVIEW_ROW_LIMIT)
+ .toList()
+
+ val favoritePreview = if (favoriteIds.isEmpty()) {
+ emptyList()
+ } else {
+ movieRepository.getMoviesByIds(favoriteIds).first().orderByIds(favoriteIds)
+ }.markFavorites(globalFavoriteIds)
+ val continuePreview = if (continueIds.isEmpty()) {
+ emptyList()
+ } else {
+ movieRepository.getMoviesByIds(continueIds).first().orderByIds(continueIds)
+ }.markFavorites(globalFavoriteIds)
+
+ _uiState.update {
+ it.copy(
+ libraryLensRows = mapOf(
+ MovieLibraryLens.FAVORITES to favoritePreview,
+ MovieLibraryLens.CONTINUE to continuePreview,
+ MovieLibraryLens.TOP_RATED to dependencies.topRated.markFavorites(globalFavoriteIds),
+ MovieLibraryLens.FRESH to dependencies.fresh.markFavorites(globalFavoriteIds)
+ ).filterValues { rows -> rows.isNotEmpty() }
+ )
+ }
+ }
+ }
+
viewModelScope.launch {
preferencesRepository.parentalControlLevel.collect { level ->
_uiState.update { it.copy(parentalControlLevel = level) }
}
}
-
+
viewModelScope.launch {
- getCustomCategories(ContentType.MOVIE).collect { cats ->
- _uiState.update { it.copy(categories = cats) }
+ getCustomCategories(ContentType.MOVIE).collect { categories ->
+ _uiState.update { it.copy(categories = categories) }
}
}
}
fun selectCategory(categoryName: String?) {
- _uiState.update { it.copy(selectedCategory = categoryName) }
+ _selectedCategoryLoadLimit.value = SELECTED_CATEGORY_PAGE_SIZE
+ _uiState.update {
+ it.copy(
+ selectedCategory = categoryName,
+ selectedCategoryItems = emptyList(),
+ selectedCategoryLoadedCount = 0,
+ selectedCategoryTotalCount = 0,
+ canLoadMoreSelectedCategory = false
+ )
+ }
+ }
+
+ fun selectFullLibraryBrowse() {
+ selectCategory(FULL_LIBRARY_CATEGORY)
+ }
+
+ fun loadMoreSelectedCategory() {
+ if (!_uiState.value.canLoadMoreSelectedCategory) return
+ _selectedCategoryLoadLimit.update { it + SELECTED_CATEGORY_PAGE_SIZE }
}
fun setSearchQuery(query: String) {
@@ -127,13 +312,14 @@ class MoviesViewModel @Inject constructor(
fun onShowDialog(movie: Movie) {
viewModelScope.launch {
val memberships = favoriteRepository.getGroupMemberships(movie.id, ContentType.MOVIE)
- val isFav = favoriteRepository.isFavorite(movie.id, ContentType.MOVIE)
- val updatedMovie = movie.copy(isFavorite = isFav)
- _uiState.update { it.copy(
- showDialog = true,
- selectedMovieForDialog = updatedMovie,
- dialogGroupMemberships = memberships
- ) }
+ val isFavorite = favoriteRepository.isFavorite(movie.id, ContentType.MOVIE)
+ _uiState.update {
+ it.copy(
+ showDialog = true,
+ selectedMovieForDialog = movie.copy(isFavorite = isFavorite),
+ dialogGroupMemberships = memberships
+ )
+ }
}
}
@@ -157,8 +343,7 @@ class MoviesViewModel @Inject constructor(
fun addToGroup(movie: Movie, group: Category) {
viewModelScope.launch {
- val groupId = -group.id
- favoriteRepository.addFavorite(movie.id, ContentType.MOVIE, groupId)
+ favoriteRepository.addFavorite(movie.id, ContentType.MOVIE, groupId = -group.id)
val memberships = favoriteRepository.getGroupMemberships(movie.id, ContentType.MOVIE)
_uiState.update { it.copy(dialogGroupMemberships = memberships) }
}
@@ -166,25 +351,39 @@ class MoviesViewModel @Inject constructor(
fun removeFromGroup(movie: Movie, group: Category) {
viewModelScope.launch {
- val groupId = -group.id
- favoriteRepository.removeFavorite(movie.id, ContentType.MOVIE, groupId)
+ favoriteRepository.removeFavorite(movie.id, ContentType.MOVIE, groupId = -group.id)
val memberships = favoriteRepository.getGroupMemberships(movie.id, ContentType.MOVIE)
_uiState.update { it.copy(dialogGroupMemberships = memberships) }
}
}
fun createCustomGroup(name: String) {
+ val normalizedName = name.trim()
+ val validationError = validateGroupName(normalizedName)
+ if (validationError != null) {
+ _uiState.update { it.copy(userMessage = validationError) }
+ return
+ }
+
viewModelScope.launch {
- favoriteRepository.createGroup(name, contentType = ContentType.MOVIE)
+ favoriteRepository.createGroup(normalizedName, contentType = ContentType.MOVIE)
+ _uiState.update { it.copy(userMessage = "Created group $normalizedName") }
}
}
- // ── Category Options (Long-Press) ──────────────────────────────────
fun showCategoryOptions(categoryName: String) {
- // Find matching Category object or construct a dummy Virtual mapping
val matchedCategory = _uiState.value.categories.find { it.name == categoryName }
- ?: if (categoryName == "★ Favorites") Category(id = -999L, name = "★ Favorites", type = ContentType.MOVIE, isVirtual = true) else null
-
+ ?: if (categoryName == FAVORITES_CATEGORY) {
+ Category(
+ id = FAVORITES_SENTINEL_ID,
+ name = FAVORITES_CATEGORY,
+ type = ContentType.MOVIE,
+ isVirtual = true
+ )
+ } else {
+ null
+ }
+
if (matchedCategory != null) {
_uiState.update { it.copy(selectedCategoryForOptions = matchedCategory) }
}
@@ -194,9 +393,59 @@ class MoviesViewModel @Inject constructor(
_uiState.update { it.copy(selectedCategoryForOptions = null) }
}
+ fun requestRenameGroup(category: Category) {
+ if (!category.isVirtual || category.id == FAVORITES_SENTINEL_ID) return
+ _uiState.update {
+ it.copy(
+ selectedCategoryForOptions = null,
+ showRenameGroupDialog = true,
+ groupToRename = category,
+ renameGroupError = null
+ )
+ }
+ }
+
+ fun cancelRenameGroup() {
+ _uiState.update {
+ it.copy(
+ showRenameGroupDialog = false,
+ groupToRename = null,
+ renameGroupError = null
+ )
+ }
+ }
+
+ fun confirmRenameGroup(name: String) {
+ val category = _uiState.value.groupToRename ?: return
+ val normalizedName = name.trim()
+ val validationError = validateGroupName(normalizedName, currentGroupId = category.id)
+ if (validationError != null) {
+ _uiState.update { it.copy(renameGroupError = validationError) }
+ return
+ }
+
+ viewModelScope.launch {
+ favoriteRepository.renameGroup(-category.id, normalizedName)
+ _uiState.update {
+ it.copy(
+ showRenameGroupDialog = false,
+ groupToRename = null,
+ renameGroupError = null,
+ userMessage = "Renamed group to $normalizedName"
+ )
+ }
+ }
+ }
+
fun requestDeleteGroup(category: Category) {
- if (!category.isVirtual || category.id == -999L) return
- _uiState.update { it.copy(showDeleteGroupDialog = true, groupToDelete = category) }
+ if (!category.isVirtual || category.id == FAVORITES_SENTINEL_ID) return
+ _uiState.update {
+ it.copy(
+ selectedCategoryForOptions = null,
+ showDeleteGroupDialog = true,
+ groupToDelete = category
+ )
+ }
}
fun cancelDeleteGroup() {
@@ -210,53 +459,57 @@ class MoviesViewModel @Inject constructor(
_uiState.update {
it.copy(
showDeleteGroupDialog = false,
- groupToDelete = null
+ groupToDelete = null,
+ userMessage = "Deleted group ${category.name}"
)
}
}
}
- // ── Reorder ────────────────────────────────────────────────────────
+ fun userMessageShown() {
+ _uiState.update { it.copy(userMessage = null) }
+ }
+
fun enterCategoryReorderMode(category: Category) {
dismissCategoryOptions()
- // Capture a local snapshot of the current view to allow instant drag-and-drop
- val currentCategoryName = category.name
- val moviesInView = _uiState.value.moviesByCategory[currentCategoryName] ?: emptyList()
- _localMovies.value = moviesInView
-
- _uiState.update { it.copy(
- isReorderMode = true,
- reorderCategory = category,
- filteredMovies = moviesInView
- ) }
+ viewModelScope.launch {
+ val moviesInView = loadReorderMovies(category)
+ _uiState.update {
+ it.copy(
+ isReorderMode = true,
+ reorderCategory = category,
+ filteredMovies = moviesInView
+ )
+ }
+ }
}
fun exitCategoryReorderMode() {
- _uiState.update { it.copy(
- isReorderMode = false,
- reorderCategory = null,
- filteredMovies = emptyList() // Clear local snapshot rendering
- ) }
+ _uiState.update {
+ it.copy(
+ isReorderMode = false,
+ reorderCategory = null,
+ filteredMovies = emptyList()
+ )
+ }
}
fun moveItemUp(movie: Movie) {
- val state = _uiState.value
- val list = state.filteredMovies.toMutableList()
- val idx = list.indexOf(movie)
- if (idx > 0) {
- list.removeAt(idx)
- list.add(idx - 1, movie)
+ val list = _uiState.value.filteredMovies.toMutableList()
+ val index = list.indexOf(movie)
+ if (index > 0) {
+ list.removeAt(index)
+ list.add(index - 1, movie)
_uiState.update { it.copy(filteredMovies = list) }
}
}
fun moveItemDown(movie: Movie) {
- val state = _uiState.value
- val list = state.filteredMovies.toMutableList()
- val idx = list.indexOf(movie)
- if (idx >= 0 && idx < list.size - 1) {
- list.removeAt(idx)
- list.add(idx + 1, movie)
+ val list = _uiState.value.filteredMovies.toMutableList()
+ val index = list.indexOf(movie)
+ if (index >= 0 && index < list.lastIndex) {
+ list.removeAt(index)
+ list.add(index + 1, movie)
_uiState.update { it.copy(filteredMovies = list) }
}
}
@@ -266,12 +519,11 @@ class MoviesViewModel @Inject constructor(
val category = state.reorderCategory ?: return
val currentList = state.filteredMovies
- // Provide an instant UI reversion out of reorder state
exitCategoryReorderMode()
viewModelScope.launch {
try {
- val groupId = if (category.id == -999L) null else -category.id
+ val groupId = if (category.id == FAVORITES_SENTINEL_ID) null else -category.id
val favoritesFlow = if (groupId == null) {
favoriteRepository.getFavorites(ContentType.MOVIE)
} else {
@@ -280,25 +532,338 @@ class MoviesViewModel @Inject constructor(
val favorites = favoritesFlow.first()
val favoriteMap = favorites.associateBy { it.contentId }
-
- val reorderedFavorites = currentList.mapNotNull { mov ->
- favoriteMap[mov.id]
- }.mapIndexed { i, fav ->
- fav.copy(position = i)
+ val reorderedFavorites = currentList.mapNotNull { movie ->
+ favoriteMap[movie.id]
+ }.mapIndexed { index, favorite ->
+ favorite.copy(position = index)
}
favoriteRepository.reorderFavorites(reorderedFavorites)
- } catch (e: Exception) {
- // Ignore silently for now
+ } catch (_: Exception) {
+ }
+ }
+ }
+
+ private suspend fun loadReorderMovies(category: Category): List<Movie> {
+ if (!category.isVirtual) return emptyList()
+
+ val groupId = if (category.id == FAVORITES_SENTINEL_ID) null else -category.id
+ val favorites = if (groupId == null) {
+ favoriteRepository.getFavorites(ContentType.MOVIE).first()
+ } else {
+ favoriteRepository.getFavoritesByGroup(groupId).first()
+ }
+
+ val orderedIds = favorites
+ .sortedBy { it.position }
+ .map { it.contentId }
+
+ if (orderedIds.isEmpty()) return emptyList()
+ return movieRepository.getMoviesByIds(orderedIds).first().orderByIds(orderedIds)
+ }
+
+ private suspend fun buildPreviewCatalog(
+ params: MovieCatalogParams
+ ): MovieCatalogSnapshot {
+ val globalFavoriteIds = params.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val previewRows = linkedMapOf<String, List<Movie>>()
+ val countMap = linkedMapOf<String, Int>()
+
+ val favoritesIds = params.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .toList()
+ if (favoritesIds.isNotEmpty()) {
+ val preview = movieRepository.getMoviesByIds(favoritesIds.take(PREVIEW_ROW_LIMIT)).first()
+ .markFavorites(globalFavoriteIds)
+ if (preview.isNotEmpty()) {
+ previewRows[FAVORITES_CATEGORY] = preview
+ countMap[FAVORITES_CATEGORY] = favoritesIds.size
+ }
+ }
+
+ params.customCategories
+ .filter { it.id != FAVORITES_SENTINEL_ID }
+ .forEach { category ->
+ val ids = params.allFavorites
+ .asSequence()
+ .filter { it.groupId == -category.id }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .toList()
+ if (ids.isNotEmpty()) {
+ val preview = movieRepository.getMoviesByIds(ids.take(PREVIEW_ROW_LIMIT)).first()
+ .markFavorites(globalFavoriteIds)
+ if (preview.isNotEmpty()) {
+ previewRows[category.name] = preview
+ countMap[category.name] = ids.size
+ }
+ }
+ }
+
+ val providerPreviews = coroutineScope {
+ params.providerCategories
+ .sortedBy { it.name.lowercase() }
+ .map { category ->
+ async {
+ val preview = movieRepository
+ .getMoviesByCategoryPreview(params.providerId, category.id, PREVIEW_ROW_LIMIT)
+ .first()
+ .markFavorites(globalFavoriteIds)
+ category to preview
+ }
+ }
+ .awaitAll()
+ }
+
+ providerPreviews.forEach { (category, preview) ->
+ if (preview.isNotEmpty()) {
+ previewRows[category.name] = preview
+ countMap[category.name] = params.providerCategoryCounts[category.id] ?: preview.size
+ }
+ }
+
+ return MovieCatalogSnapshot(
+ grouped = previewRows,
+ categoryNames = previewRows.keys.toList(),
+ categoryCounts = countMap,
+ libraryCount = params.libraryCount
+ )
+ }
+
+ private fun buildSearchCatalog(
+ movies: List<Movie>,
+ allFavorites: List<com.streamvault.domain.model.Favorite>,
+ customCategories: List<Category>
+ ): MovieCatalogSnapshot {
+ val globalFavoriteIds = allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val enrichedMovies = movies.map { it.copy(isFavorite = globalFavoriteIds.contains(it.id)) }
+ val grouped = enrichedMovies
+ .groupBy { it.categoryName ?: UNCATEGORIZED }
+ .toMutableMap()
+
+ grouped[FAVORITES_CATEGORY] = enrichedMovies.filter { it.isFavorite }
+
+ customCategories
+ .filter { it.id != FAVORITES_SENTINEL_ID }
+ .forEach { customCategory ->
+ val movieIdsInGroup = allFavorites
+ .asSequence()
+ .filter { it.groupId == -customCategory.id }
+ .map { it.contentId }
+ .toSet()
+ grouped[customCategory.name] = enrichedMovies.filter { it.id in movieIdsInGroup }
+ }
+
+ val customNames = customCategories.map { it.name }.toSet()
+ val categoryNames = grouped.keys.sortedWith(
+ compareBy<String> {
+ when (it) {
+ FAVORITES_CATEGORY -> 0
+ in customNames -> 1
+ else -> 2
+ }
+ }.thenBy { it }
+ )
+
+ val categoryCounts = categoryNames.associateWith { name -> grouped[name]?.size ?: 0 }
+
+ return MovieCatalogSnapshot(
+ grouped = grouped,
+ categoryNames = categoryNames,
+ categoryCounts = categoryCounts,
+ libraryCount = movies.size
+ )
+ }
+
+ private suspend fun loadSelectedCategoryItems(
+ request: SelectedMovieCategoryRequest
+ ): SelectedMovieCategorySnapshot {
+ if (request.selectedCategory.isNullOrBlank() || request.query.isNotBlank()) {
+ return SelectedMovieCategorySnapshot()
+ }
+
+ val globalFavoriteIds = request.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+
+ val (selectedItems, totalCount) = when (request.selectedCategory) {
+ FULL_LIBRARY_CATEGORY -> {
+ val result = movieRepository
+ .browseMovies(
+ LibraryBrowseQuery(
+ providerId = request.providerId,
+ categoryId = null,
+ limit = request.loadLimit,
+ offset = 0
+ )
+ )
+ .first()
+ result.items to result.totalCount
}
+ FAVORITES_CATEGORY -> {
+ val ids = request.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .toList()
+ val pagedIds = ids.take(request.loadLimit)
+ val items = if (pagedIds.isEmpty()) {
+ emptyList()
+ } else {
+ movieRepository.getMoviesByIds(pagedIds).first().orderByIds(pagedIds)
+ }
+ items to ids.size
+ }
+ else -> {
+ val customCategory = request.customCategories.firstOrNull { it.name == request.selectedCategory }
+ if (customCategory != null) {
+ val ids = request.allFavorites
+ .asSequence()
+ .filter { it.groupId == -customCategory.id }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .toList()
+ val pagedIds = ids.take(request.loadLimit)
+ val items = if (pagedIds.isEmpty()) {
+ emptyList()
+ } else {
+ movieRepository.getMoviesByIds(pagedIds).first().orderByIds(pagedIds)
+ }
+ items to ids.size
+ } else {
+ val providerCategory = request.providerCategories.firstOrNull { it.name == request.selectedCategory }
+ if (providerCategory != null) {
+ val result = movieRepository
+ .browseMovies(
+ LibraryBrowseQuery(
+ providerId = request.providerId,
+ categoryId = providerCategory.id,
+ limit = request.loadLimit,
+ offset = 0
+ )
+ )
+ .first()
+ result.items to result.totalCount
+ } else {
+ emptyList<Movie>() to 0
+ }
+ }
+ }
+ }
+
+ val enrichedItems = selectedItems.markFavorites(globalFavoriteIds)
+ return SelectedMovieCategorySnapshot(
+ items = enrichedItems,
+ loadedCount = enrichedItems.size,
+ totalCount = totalCount,
+ canLoadMore = totalCount > enrichedItems.size
+ )
+ }
+
+ private fun validateGroupName(name: String, currentGroupId: Long? = null): String? {
+ if (name.isBlank()) return "Enter a group name"
+ if (name.equals("favorites", ignoreCase = true)) return "Favorites is reserved"
+
+ val duplicate = _uiState.value.categories.any { category ->
+ category.id != currentGroupId && category.name.equals(name, ignoreCase = true)
}
+ return if (duplicate) "A movie group with that name already exists" else null
+ }
+
+ private fun List<Movie>.markFavorites(globalFavoriteIds: Set<Long>): List<Movie> =
+ map { movie -> movie.copy(isFavorite = movie.id in globalFavoriteIds) }
+
+ private fun List<Movie>.orderByIds(ids: List<Long>): List<Movie> {
+ val movieMap = associateBy { it.id }
+ return ids.mapNotNull { movieMap[it] }
}
}
+private data class MovieCatalogParams(
+ val providerId: Long,
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val customCategories: List<Category>,
+ val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>,
+ val libraryCount: Int,
+ val query: String
+)
+
+private data class MovieCatalogDependencies(
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val customCategories: List<Category>,
+ val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>,
+ val libraryCount: Int
+)
+
+private data class MovieCatalogSnapshot(
+ val grouped: Map<String, List<Movie>>,
+ val categoryNames: List<String>,
+ val categoryCounts: Map<String, Int>,
+ val libraryCount: Int
+)
+
+private data class MovieLibraryLensDependencies(
+ val providerId: Long,
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val history: List<PlaybackHistory>,
+ val topRated: List<Movie>,
+ val fresh: List<Movie>
+)
+
+private data class MovieCategorySelectionDependencies(
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val customCategories: List<Category>,
+ val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>
+)
+
+private data class SelectedMovieCategoryRequest(
+ val providerId: Long,
+ val selectedCategory: String?,
+ val loadLimit: Int,
+ val query: String,
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val customCategories: List<Category>,
+ val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>
+)
+
+private data class SelectedMovieCategorySnapshot(
+ val items: List<Movie> = emptyList(),
+ val loadedCount: Int = 0,
+ val totalCount: Int = 0,
+ val canLoadMore: Boolean = false
+)
+
data class MoviesUiState(
val moviesByCategory: Map<String, List<Movie>> = emptyMap(),
val categoryNames: List<String> = emptyList(),
+ val categoryCounts: Map<String, Int> = emptyMap(),
+ val libraryCount: Int = 0,
+ val favoriteCategoryName: String = "\u2605 Favorites",
+ val fullLibraryCategoryName: String = "__full_library__",
+ val libraryLensRows: Map<MovieLibraryLens, List<Movie>> = emptyMap(),
val selectedCategory: String? = null,
+ val selectedCategoryItems: List<Movie> = emptyList(),
+ val selectedCategoryLoadedCount: Int = 0,
+ val selectedCategoryTotalCount: Int = 0,
+ val canLoadMoreSelectedCategory: Boolean = false,
val searchQuery: String = "",
val continueWatching: List<PlaybackHistory> = emptyList(),
val isLoading: Boolean = true,
@@ -307,14 +872,14 @@ data class MoviesUiState(
val selectedMovieForDialog: Movie? = null,
val categories: List<Category> = emptyList(),
val dialogGroupMemberships: List<Long> = emptyList(),
-
- // Category Options & Deletion
+ val userMessage: String? = null,
val selectedCategoryForOptions: Category? = null,
+ val showRenameGroupDialog: Boolean = false,
+ val groupToRename: Category? = null,
+ val renameGroupError: String? = null,
val showDeleteGroupDialog: Boolean = false,
val groupToDelete: Category? = null,
-
- // Reorder State
val isReorderMode: Boolean = false,
val reorderCategory: Category? = null,
- val filteredMovies: List<Movie> = emptyList() // The active sortable list
+ val filteredMovies: List<Movie> = emptyList()
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
index 35fc55e4..a0706a55 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewScreen.kt
@@ -4,6 +4,7 @@ import android.view.View
import androidx.activity.compose.BackHandler
import androidx.annotation.OptIn
import androidx.compose.foundation.background
+import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
@@ -12,7 +13,9 @@ import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Text
@@ -20,7 +23,9 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.focusRequester
@@ -32,12 +37,15 @@ import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
+import androidx.compose.ui.res.stringResource
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.media3.common.util.UnstableApi
import androidx.media3.ui.AspectRatioFrameLayout
import androidx.media3.ui.PlayerView
import androidx.tv.material3.Border
import androidx.tv.material3.ClickableSurfaceDefaults
+import androidx.tv.material3.Button
+import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Surface
import com.streamvault.app.R
import com.streamvault.app.ui.theme.Primary
@@ -49,6 +57,7 @@ fun MultiViewScreen(
) {
val uiState by viewModel.uiState.collectAsState()
val firstSlotFocusRequester = remember { androidx.compose.ui.focus.FocusRequester() }
+ var showReplacementPicker by remember { mutableStateOf(false) }
BackHandler(onBack = onBack)
@@ -67,6 +76,17 @@ fun MultiViewScreen(
.fillMaxSize()
.background(Color.Black)
) {
+ if (showReplacementPicker) {
+ ReplaceSlotDialog(
+ candidates = uiState.replacementCandidates,
+ onDismiss = { showReplacementPicker = false },
+ onReplace = { channel ->
+ viewModel.replaceFocusedSlot(channel)
+ showReplacementPicker = false
+ }
+ )
+ }
+
Column(modifier = Modifier.fillMaxSize()) {
Row(modifier = Modifier.weight(1f)) {
PlayerCell(
@@ -106,18 +126,75 @@ fun MultiViewScreen(
}
val focused = uiState.slots.getOrNull(uiState.focusedSlotIndex)
- if (focused != null && focused.title.isNotBlank()) {
- Text(
- text = "Focused: ${focused.title}",
- color = Color(0xFF4CAF50),
- fontSize = 12.sp,
- fontWeight = FontWeight.Bold,
- modifier = Modifier
- .align(Alignment.BottomCenter)
- .padding(bottom = 8.dp)
- .background(Color.Black.copy(alpha = 0.7f), RoundedCornerShape(4.dp))
- .padding(horizontal = 12.dp, vertical = 4.dp)
+ Column(
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .padding(bottom = 8.dp),
+ horizontalAlignment = Alignment.CenterHorizontally
+ ) {
+ MultiViewPolicyCard(
+ policy = uiState.performancePolicy,
+ telemetry = uiState.telemetry,
+ onModeSelected = viewModel::setPerformanceMode
)
+ if (focused != null && focused.title.isNotBlank()) {
+ Text(
+ text = stringResource(R.string.multiview_focused_prefix, focused.title),
+ color = Color(0xFF4CAF50),
+ fontSize = 12.sp,
+ fontWeight = FontWeight.Bold,
+ modifier = Modifier
+ .background(Color.Black.copy(alpha = 0.7f), RoundedCornerShape(4.dp))
+ .padding(horizontal = 12.dp, vertical = 4.dp)
+ )
+ }
+ if (uiState.presets.isNotEmpty()) {
+ Spacer(modifier = Modifier.size(8.dp))
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ uiState.presets.forEach { preset ->
+ val presetLabel = stringResource(R.string.multiview_preset_label, preset.index + 1)
+ Button(onClick = { viewModel.loadPreset(preset.index) }) {
+ Text(
+ text = if (preset.isPopulated) {
+ "$presetLabel (${preset.channelCount})"
+ } else {
+ presetLabel
+ }
+ )
+ }
+ Button(onClick = { viewModel.saveCurrentAsPreset(preset.index) }) {
+ Text(text = stringResource(R.string.multiview_preset_save, preset.index + 1))
+ }
+ }
+ }
+ }
+ Spacer(modifier = Modifier.size(8.dp))
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Button(
+ onClick = { showReplacementPicker = true },
+ enabled = uiState.replacementCandidates.isNotEmpty()
+ ) {
+ Text(stringResource(R.string.multiview_replace_slot))
+ }
+ Button(
+ onClick = { viewModel.removeFocusedSlot() },
+ enabled = focused != null && !focused.isEmpty
+ ) {
+ Text(stringResource(R.string.multiview_remove_slot))
+ }
+ if (uiState.pinnedAudioSlotIndex == uiState.focusedSlotIndex) {
+ Button(onClick = { viewModel.clearPinnedAudio() }) {
+ Text(stringResource(R.string.multiview_audio_follow_focus))
+ }
+ } else {
+ Button(
+ onClick = { viewModel.pinAudioToFocusedSlot() },
+ enabled = focused != null && !focused.isEmpty
+ ) {
+ Text(stringResource(R.string.multiview_pin_audio))
+ }
+ }
+ }
}
}
}
@@ -191,6 +268,25 @@ private fun PlayerCell(
}
}
+ !slot.performanceBlockedReason.isNullOrBlank() -> {
+ Column(horizontalAlignment = Alignment.CenterHorizontally) {
+ Text(
+ text = stringResource(R.string.multiview_policy_blocked),
+ color = Color(0xFFFFC107),
+ fontSize = 13.sp,
+ fontWeight = FontWeight.Bold
+ )
+ Spacer(modifier = Modifier.size(6.dp))
+ Text(
+ text = slot.performanceBlockedReason.orEmpty(),
+ color = Color(0xFFFFE082),
+ fontSize = 11.sp,
+ textAlign = TextAlign.Center,
+ modifier = Modifier.padding(horizontal = 16.dp)
+ )
+ }
+ }
+
else -> {
val engine = slot.playerEngine
if (engine != null) {
@@ -226,7 +322,11 @@ private fun PlayerCell(
.padding(horizontal = 8.dp, vertical = 6.dp)
) {
Text(
- text = "AUDIO",
+ text = if (slot.isAudioPinned) {
+ stringResource(R.string.multiview_audio_pinned_badge)
+ } else {
+ stringResource(R.string.multiview_audio_badge)
+ },
color = Primary,
fontSize = 12.sp,
fontWeight = FontWeight.Bold
@@ -254,3 +354,181 @@ private fun PlayerCell(
}
}
}
+
+@Composable
+private fun MultiViewPolicyCard(
+ policy: MultiViewPerformancePolicyUiModel,
+ telemetry: MultiViewTelemetryUiModel,
+ onModeSelected: (MultiViewPerformanceMode) -> Unit
+) {
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(8.dp),
+ modifier = Modifier
+ .background(Color.Black.copy(alpha = 0.7f), RoundedCornerShape(12.dp))
+ .padding(horizontal = 16.dp, vertical = 12.dp)
+ ) {
+ Text(
+ text = stringResource(
+ R.string.multiview_policy_summary,
+ policy.tier.name.lowercase().replaceFirstChar { it.uppercase() },
+ policy.maxActiveSlots
+ ),
+ color = Color.White,
+ style = MaterialTheme.typography.labelLarge
+ )
+ Text(
+ text = policy.summary,
+ color = Color(0xFFB0BEC5),
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = TextAlign.Center
+ )
+ Column(
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = stringResource(
+ R.string.multiview_telemetry_snapshot,
+ telemetry.activeSlots,
+ telemetry.standbySlots,
+ telemetry.bufferingSlots,
+ telemetry.errorSlots
+ ),
+ color = Color.White,
+ style = MaterialTheme.typography.labelMedium
+ )
+ Text(
+ text = stringResource(
+ R.string.multiview_telemetry_detail,
+ telemetry.totalDroppedFrames,
+ telemetry.droppedFramesDelta,
+ telemetry.sustainedLoadScore,
+ when (telemetry.thermalStatus) {
+ MultiViewThermalStatus.NORMAL -> stringResource(R.string.multiview_thermal_normal)
+ MultiViewThermalStatus.LIGHT -> stringResource(R.string.multiview_thermal_light)
+ MultiViewThermalStatus.MODERATE -> stringResource(R.string.multiview_thermal_moderate)
+ MultiViewThermalStatus.SEVERE -> stringResource(R.string.multiview_thermal_severe)
+ MultiViewThermalStatus.CRITICAL -> stringResource(R.string.multiview_thermal_critical)
+ MultiViewThermalStatus.UNKNOWN -> stringResource(R.string.multiview_thermal_unknown)
+ }
+ ),
+ color = Color(0xFFB0BEC5),
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = TextAlign.Center
+ )
+ if (telemetry.isLowMemory) {
+ Text(
+ text = stringResource(R.string.multiview_low_memory_warning),
+ color = Color(0xFFFFC107),
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = TextAlign.Center
+ )
+ }
+ telemetry.throttledReason?.let { reason ->
+ Text(
+ text = reason,
+ color = Color(0xFFFFE082),
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = TextAlign.Center
+ )
+ }
+ Text(
+ text = telemetry.recommendation,
+ color = Color(0xFF90CAF9),
+ style = MaterialTheme.typography.bodySmall,
+ textAlign = TextAlign.Center
+ )
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ MultiViewPerformanceMode.entries.forEach { mode ->
+ Surface(
+ onClick = { onModeSelected(mode) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(20.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (policy.mode == mode) Color(0xFF1E3A5F) else Color(0xFF1A1A30),
+ focusedContainerColor = Color(0xFF294B75)
+ ),
+ border = ClickableSurfaceDefaults.border(
+ border = Border(
+ androidx.compose.foundation.BorderStroke(
+ width = 1.dp,
+ color = if (policy.mode == mode) Color.White else Color.Transparent
+ )
+ )
+ )
+ ) {
+ Text(
+ text = when (mode) {
+ MultiViewPerformanceMode.AUTO -> stringResource(R.string.multiview_policy_auto)
+ MultiViewPerformanceMode.CONSERVATIVE -> stringResource(R.string.multiview_policy_conservative)
+ MultiViewPerformanceMode.BALANCED -> stringResource(R.string.multiview_policy_balanced)
+ MultiViewPerformanceMode.MAXIMUM -> stringResource(R.string.multiview_policy_maximum)
+ },
+ color = Color.White,
+ style = MaterialTheme.typography.labelMedium,
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 8.dp)
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun ReplaceSlotDialog(
+ candidates: List<com.streamvault.domain.model.Channel>,
+ onDismiss: () -> Unit,
+ onReplace: (com.streamvault.domain.model.Channel) -> Unit
+) {
+ androidx.compose.ui.window.Dialog(onDismissRequest = onDismiss) {
+ androidx.compose.material3.Surface(
+ shape = RoundedCornerShape(16.dp),
+ color = Color(0xFF12121F),
+ modifier = Modifier
+ .fillMaxWidth(0.55f)
+ .padding(20.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.multiview_replace_title),
+ color = Color.White,
+ style = MaterialTheme.typography.titleMedium
+ )
+ if (candidates.isEmpty()) {
+ Text(
+ text = stringResource(R.string.multiview_replace_empty),
+ color = Color(0xFFAAAAAA),
+ style = MaterialTheme.typography.bodySmall
+ )
+ } else {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ candidates.forEach { channel ->
+ Surface(
+ onClick = { onReplace(channel) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color(0xFF1A1A30),
+ focusedContainerColor = Color(0xFF2C2C46)
+ )
+ ) {
+ Column(modifier = Modifier.padding(14.dp)) {
+ Text(channel.name, color = Color.White, style = MaterialTheme.typography.bodyLarge)
+ channel.categoryName?.takeIf { it.isNotBlank() }?.let {
+ Text(it, color = Color(0xFFAAAAAA), style = MaterialTheme.typography.bodySmall)
+ }
+ }
+ }
+ }
+ }
+ }
+ Button(onClick = onDismiss) {
+ Text(stringResource(R.string.settings_cancel))
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewState.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewState.kt
index bb9b4775..266d43af 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewState.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewState.kt
@@ -3,6 +3,51 @@ package com.streamvault.app.ui.screens.multiview
import com.streamvault.domain.model.Channel
import com.streamvault.player.PlayerEngine
+enum class DevicePerformanceTier {
+ LOW,
+ MID,
+ HIGH
+}
+
+enum class MultiViewPerformanceMode {
+ AUTO,
+ CONSERVATIVE,
+ BALANCED,
+ MAXIMUM
+}
+
+enum class MultiViewThermalStatus {
+ UNKNOWN,
+ NORMAL,
+ LIGHT,
+ MODERATE,
+ SEVERE,
+ CRITICAL
+}
+
+data class MultiViewPerformancePolicyUiModel(
+ val tier: DevicePerformanceTier = DevicePerformanceTier.MID,
+ val mode: MultiViewPerformanceMode = MultiViewPerformanceMode.AUTO,
+ val maxActiveSlots: Int = 3,
+ val startupDelayMs: Long = 300L,
+ val summary: String = ""
+)
+
+data class MultiViewTelemetryUiModel(
+ val activeSlotLimit: Int = 3,
+ val activeSlots: Int = 0,
+ val standbySlots: Int = 0,
+ val bufferingSlots: Int = 0,
+ val errorSlots: Int = 0,
+ val droppedFramesDelta: Int = 0,
+ val totalDroppedFrames: Int = 0,
+ val sustainedLoadScore: Int = 0,
+ val thermalStatus: MultiViewThermalStatus = MultiViewThermalStatus.UNKNOWN,
+ val isLowMemory: Boolean = false,
+ val throttledReason: String? = null,
+ val recommendation: String = ""
+)
+
/**
* Represents a single player slot in the 2x2 Multi-View grid.
*/
@@ -13,7 +58,9 @@ data class MultiViewSlot(
val title: String = "",
val playerEngine: PlayerEngine? = null,
val isLoading: Boolean = false,
- val hasError: Boolean = false
+ val hasError: Boolean = false,
+ val isAudioPinned: Boolean = false,
+ val performanceBlockedReason: String? = null
) {
val isEmpty: Boolean get() = channel == null
}
@@ -22,5 +69,17 @@ data class MultiViewUiState(
val slots: List<MultiViewSlot> = List(4) { MultiViewSlot(index = it) },
val focusedSlotIndex: Int = 0,
val isLaunching: Boolean = false,
- val showSelectionBorder: Boolean = true
+ val showSelectionBorder: Boolean = true,
+ val presets: List<MultiViewPresetUiModel> = emptyList(),
+ val pinnedAudioSlotIndex: Int? = null,
+ val replacementCandidates: List<Channel> = emptyList(),
+ val performancePolicy: MultiViewPerformancePolicyUiModel = MultiViewPerformancePolicyUiModel(),
+ val telemetry: MultiViewTelemetryUiModel = MultiViewTelemetryUiModel()
+)
+
+data class MultiViewPresetUiModel(
+ val index: Int,
+ val label: String,
+ val isPopulated: Boolean,
+ val channelCount: Int
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
index 95412a72..b5178b5c 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/multiview/MultiViewViewModel.kt
@@ -1,37 +1,119 @@
package com.streamvault.app.ui.screens.multiview
+import android.app.ActivityManager
+import android.content.Context
+import android.os.Build
+import android.os.PowerManager
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.FavoriteRepository
+import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.player.PlayerEngine
import dagger.hilt.android.lifecycle.HiltViewModel
+import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
-import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.isActive
import kotlinx.coroutines.launch
import javax.inject.Inject
import javax.inject.Provider
@HiltViewModel
class MultiViewViewModel @Inject constructor(
+ @ApplicationContext private val context: Context,
val multiViewManager: MultiViewManager,
- private val playerEngineProvider: Provider<PlayerEngine>
+ private val playerEngineProvider: Provider<PlayerEngine>,
+ private val preferencesRepository: PreferencesRepository,
+ private val channelRepository: ChannelRepository,
+ private val favoriteRepository: FavoriteRepository,
+ private val playbackHistoryRepository: PlaybackHistoryRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(MultiViewUiState())
val uiState: StateFlow<MultiViewUiState> = _uiState.asStateFlow()
private var borderHideJob: kotlinx.coroutines.Job? = null
+ private var telemetryJob: kotlinx.coroutines.Job? = null
+ private var pinnedAudioSlotIndex: Int? = null
+ private val detectedTier: DevicePerformanceTier by lazy { detectDeviceTier() }
+ private val powerManager: PowerManager? by lazy { context.getSystemService(Context.POWER_SERVICE) as? PowerManager }
+ private var thermalStatus: MultiViewThermalStatus = readThermalStatus()
+ private var thermalListener: PowerManager.OnThermalStatusChangedListener? = null
+ private var runtimeActiveSlotLimit: Int = MultiViewManager.MAX_SLOTS
+ private var sustainedStressSamples: Int = 0
+ private var stableSamples: Int = 0
+ private var lastPolicyAdjustmentAt: Long = 0L
+ private val lastDroppedFramesBySlot = mutableMapOf<Int, Int>()
/** Flow of the current 4 slot channels from the manager */
val slotsFlow = multiViewManager.slots
private val playerEngines = mutableMapOf<Int, PlayerEngine>()
+ init {
+ viewModelScope.launch {
+ combine(
+ preferencesRepository.getMultiViewPreset(0),
+ preferencesRepository.getMultiViewPreset(1),
+ preferencesRepository.getMultiViewPreset(2),
+ preferencesRepository.multiViewPerformanceMode
+ ) { preset1, preset2, preset3, performanceMode ->
+ listOf(preset1, preset2, preset3) to performanceMode
+ }.collect { presets ->
+ val presetList = presets.first
+ val mode = presets.second
+ ?.let { saved -> MultiViewPerformanceMode.entries.firstOrNull { it.name == saved } }
+ ?: MultiViewPerformanceMode.AUTO
+ val policy = resolvePolicy(mode, detectedTier)
+ runtimeActiveSlotLimit = runtimeActiveSlotLimit
+ .coerceAtLeast(1)
+ .coerceAtMost(policy.maxActiveSlots)
+ _uiState.value = _uiState.value.copy(
+ presets = presetList.mapIndexed { index, ids ->
+ MultiViewPresetUiModel(
+ index = index,
+ label = "Preset ${index + 1}",
+ isPopulated = ids.isNotEmpty(),
+ channelCount = ids.size
+ )
+ },
+ pinnedAudioSlotIndex = pinnedAudioSlotIndex,
+ performancePolicy = policy,
+ telemetry = _uiState.value.telemetry.copy(
+ activeSlotLimit = runtimeActiveSlotLimit,
+ thermalStatus = thermalStatus,
+ recommendation = buildTelemetryRecommendation(
+ activeSlotLimit = runtimeActiveSlotLimit,
+ thermalStatus = thermalStatus,
+ isLowMemory = false,
+ sustainedLoadScore = 0,
+ policy = policy
+ )
+ )
+ )
+ }
+ }
+
+ registerThermalListener()
+ observeReplacementCandidates()
+ }
+
/** Called when MultiViewScreen is opened — spins up player engines for occupied slots */
fun initSlots() {
+ telemetryJob?.cancel()
+ playerEngines.values.forEach { it.release() }
+ playerEngines.clear()
+ lastDroppedFramesBySlot.clear()
val channels = multiViewManager.slots.value
+ val maxActiveSlots = runtimeActiveSlotLimit
+ .coerceAtLeast(1)
+ .coerceAtMost(_uiState.value.performancePolicy.maxActiveSlots)
val slots = channels.mapIndexed { index, channel ->
if (channel != null) {
MultiViewSlot(
@@ -39,19 +121,46 @@ class MultiViewViewModel @Inject constructor(
channel = channel,
streamUrl = channel.streamUrl,
title = channel.name,
- isLoading = true
+ isLoading = index < maxActiveSlots,
+ isAudioPinned = pinnedAudioSlotIndex == index,
+ performanceBlockedReason = if (index >= maxActiveSlots) {
+ "Held back by ${_uiState.value.performancePolicy.mode.name.lowercase()} policy on this device tier."
+ } else {
+ null
+ }
)
} else {
MultiViewSlot(index = index)
}
}
- _uiState.value = MultiViewUiState(slots = slots)
+ _uiState.value = _uiState.value.copy(
+ slots = slots,
+ pinnedAudioSlotIndex = pinnedAudioSlotIndex,
+ telemetry = _uiState.value.telemetry.copy(
+ activeSlotLimit = maxActiveSlots,
+ activeSlots = slots.count { !it.isEmpty && it.performanceBlockedReason == null },
+ standbySlots = slots.count { !it.isEmpty && it.performanceBlockedReason != null },
+ throttledReason = _uiState.value.telemetry.throttledReason,
+ thermalStatus = thermalStatus,
+ recommendation = buildTelemetryRecommendation(
+ activeSlotLimit = maxActiveSlots,
+ thermalStatus = thermalStatus,
+ isLowMemory = false,
+ sustainedLoadScore = _uiState.value.telemetry.sustainedLoadScore,
+ policy = _uiState.value.performancePolicy
+ )
+ )
+ )
// Start all occupied engines
slots.forEachIndexed { index, slot ->
if (!slot.isEmpty) {
+ if (index >= maxActiveSlots) {
+ updateSlot(index) { it.copy(isLoading = false, playerEngine = null) }
+ return@forEachIndexed
+ }
viewModelScope.launch {
- kotlinx.coroutines.delay(index * 250L) // Stagger decoders to prevent Peak usage crash
+ kotlinx.coroutines.delay(index * _uiState.value.performancePolicy.startupDelayMs)
try {
val engine = playerEngineProvider.get()
playerEngines[index] = engine
@@ -75,6 +184,7 @@ class MultiViewViewModel @Inject constructor(
applyFocusAudio(0)
showSelectionBorderTemporarily()
+ startTelemetryMonitoring()
}
fun setFocus(slotIndex: Int) {
@@ -96,7 +206,8 @@ class MultiViewViewModel @Inject constructor(
private fun applyFocusAudio(focusedIndex: Int) {
playerEngines.forEach { (index, engine) ->
- if (index == focusedIndex) engine.setVolume(1f) else engine.setVolume(0f)
+ val audibleIndex = pinnedAudioSlotIndex ?: focusedIndex
+ if (index == audibleIndex) engine.setVolume(1f) else engine.setVolume(0f)
}
}
@@ -108,11 +219,76 @@ class MultiViewViewModel @Inject constructor(
/** Clear a specific slot */
fun clearSlot(slotIndex: Int) {
multiViewManager.clearSlot(slotIndex)
+ if (pinnedAudioSlotIndex == slotIndex) {
+ pinnedAudioSlotIndex = null
+ }
+ _uiState.value = _uiState.value.copy(pinnedAudioSlotIndex = pinnedAudioSlotIndex)
}
/** Clear all slots */
fun clearAll() {
multiViewManager.clearAll()
+ pinnedAudioSlotIndex = null
+ _uiState.value = _uiState.value.copy(pinnedAudioSlotIndex = null)
+ }
+
+ fun replaceFocusedSlot(channel: Channel) {
+ val slotIndex = _uiState.value.focusedSlotIndex
+ multiViewManager.setChannel(slotIndex, channel)
+ initSlots()
+ }
+
+ fun removeFocusedSlot() {
+ clearSlot(_uiState.value.focusedSlotIndex)
+ initSlots()
+ }
+
+ fun pinAudioToFocusedSlot() {
+ pinnedAudioSlotIndex = _uiState.value.focusedSlotIndex
+ _uiState.value = _uiState.value.copy(
+ pinnedAudioSlotIndex = pinnedAudioSlotIndex,
+ slots = _uiState.value.slots.mapIndexed { index, slot -> slot.copy(isAudioPinned = index == pinnedAudioSlotIndex) }
+ )
+ applyFocusAudio(_uiState.value.focusedSlotIndex)
+ }
+
+ fun clearPinnedAudio() {
+ pinnedAudioSlotIndex = null
+ _uiState.value = _uiState.value.copy(
+ pinnedAudioSlotIndex = null,
+ slots = _uiState.value.slots.map { it.copy(isAudioPinned = false) }
+ )
+ applyFocusAudio(_uiState.value.focusedSlotIndex)
+ }
+
+ fun saveCurrentAsPreset(presetIndex: Int) {
+ viewModelScope.launch {
+ val channelIds = multiViewManager.slots.value.mapNotNull { it?.id }
+ preferencesRepository.setMultiViewPreset(presetIndex, channelIds)
+ }
+ }
+
+ fun setPerformanceMode(mode: MultiViewPerformanceMode) {
+ viewModelScope.launch {
+ preferencesRepository.setMultiViewPerformanceMode(mode.name)
+ initSlots()
+ }
+ }
+
+ fun loadPreset(presetIndex: Int) {
+ viewModelScope.launch {
+ val channelIds = preferencesRepository.getMultiViewPreset(presetIndex).first()
+ if (channelIds.isEmpty()) return@launch
+ val channels = channelRepository.getChannelsByIds(channelIds).first()
+ .associateBy { it.id }
+ multiViewManager.clearAll()
+ channelIds.forEachIndexed { index, channelId ->
+ channels[channelId]?.let { channel ->
+ multiViewManager.setChannel(index, channel)
+ }
+ }
+ initSlots()
+ }
}
fun isQueued(channelId: Long): Boolean = multiViewManager.isQueued(channelId)
@@ -125,9 +301,296 @@ class MultiViewViewModel @Inject constructor(
}
}
+ private fun observeReplacementCandidates() {
+ viewModelScope.launch {
+ preferencesRepository.lastActiveProviderId.collect { providerId ->
+ if (providerId == null || providerId <= 0L) {
+ _uiState.value = _uiState.value.copy(replacementCandidates = emptyList())
+ return@collect
+ }
+ combine(
+ favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE),
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 12)
+ ) { favorites, history ->
+ val favoriteIds = favorites.map { it.contentId }
+ val historyIds = history.map { it.contentId }
+ (favoriteIds + historyIds)
+ .distinct()
+ .take(16)
+ }.collect { candidateIds ->
+ if (candidateIds.isEmpty()) {
+ _uiState.value = _uiState.value.copy(replacementCandidates = emptyList())
+ } else {
+ val channels = channelRepository.getChannelsByIds(candidateIds).first()
+ val currentSlotIds = multiViewManager.slots.value.mapNotNull { it?.id }.toSet()
+ _uiState.value = _uiState.value.copy(
+ replacementCandidates = channels.filterNot { it.id in currentSlotIds }
+ )
+ }
+ }
+ }
+ }
+ }
+
override fun onCleared() {
super.onCleared()
+ telemetryJob?.cancel()
+ unregisterThermalListener()
playerEngines.values.forEach { it.release() }
playerEngines.clear()
}
+
+ private fun detectDeviceTier(): DevicePerformanceTier {
+ val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
+ val memoryClass = activityManager?.memoryClass ?: 256
+ val isLowRam = activityManager?.isLowRamDevice ?: false
+ return when {
+ isLowRam || memoryClass <= 192 -> DevicePerformanceTier.LOW
+ memoryClass <= 320 -> DevicePerformanceTier.MID
+ else -> DevicePerformanceTier.HIGH
+ }
+ }
+
+ private fun resolvePolicy(
+ mode: MultiViewPerformanceMode,
+ tier: DevicePerformanceTier
+ ): MultiViewPerformancePolicyUiModel {
+ val (maxSlots, startupDelayMs) = when (mode) {
+ MultiViewPerformanceMode.AUTO -> when (tier) {
+ DevicePerformanceTier.LOW -> 2 to 550L
+ DevicePerformanceTier.MID -> 3 to 350L
+ DevicePerformanceTier.HIGH -> 4 to 220L
+ }
+ MultiViewPerformanceMode.CONSERVATIVE -> when (tier) {
+ DevicePerformanceTier.LOW -> 1 to 700L
+ DevicePerformanceTier.MID -> 2 to 500L
+ DevicePerformanceTier.HIGH -> 3 to 320L
+ }
+ MultiViewPerformanceMode.BALANCED -> when (tier) {
+ DevicePerformanceTier.LOW -> 2 to 550L
+ DevicePerformanceTier.MID -> 3 to 350L
+ DevicePerformanceTier.HIGH -> 4 to 240L
+ }
+ MultiViewPerformanceMode.MAXIMUM -> when (tier) {
+ DevicePerformanceTier.LOW -> 2 to 450L
+ DevicePerformanceTier.MID -> 4 to 260L
+ DevicePerformanceTier.HIGH -> 4 to 160L
+ }
+ }
+ return MultiViewPerformancePolicyUiModel(
+ tier = tier,
+ mode = mode,
+ maxActiveSlots = maxSlots,
+ startupDelayMs = startupDelayMs,
+ summary = "Runs up to $maxSlots active slot(s) on ${tier.name.lowercase()} tier with ${startupDelayMs}ms startup staggering."
+ )
+ }
+
+ private fun startTelemetryMonitoring() {
+ telemetryJob?.cancel()
+ telemetryJob = viewModelScope.launch {
+ while (isActive) {
+ evaluateTelemetry()
+ kotlinx.coroutines.delay(2_500)
+ }
+ }
+ }
+
+ private fun evaluateTelemetry() {
+ val policy = _uiState.value.performancePolicy
+ val engines = playerEngines.toMap()
+ val lowMemory = isLowMemoryDeviceState()
+ var bufferingSlots = 0
+ var errorSlots = 0
+ var totalDroppedFrames = 0
+ var droppedFramesDelta = 0
+
+ engines.forEach { (index, engine) ->
+ when (engine.playbackState.value) {
+ com.streamvault.player.PlaybackState.BUFFERING -> bufferingSlots += 1
+ com.streamvault.player.PlaybackState.ERROR -> errorSlots += 1
+ else -> Unit
+ }
+
+ val stats = engine.playerStats.value
+ totalDroppedFrames += stats.droppedFrames
+ val previousDropped = lastDroppedFramesBySlot[index] ?: stats.droppedFrames
+ droppedFramesDelta += (stats.droppedFrames - previousDropped).coerceAtLeast(0)
+ lastDroppedFramesBySlot[index] = stats.droppedFrames
+ }
+
+ val thermalPenalty = when (thermalStatus) {
+ MultiViewThermalStatus.MODERATE -> 2
+ MultiViewThermalStatus.SEVERE -> 4
+ MultiViewThermalStatus.CRITICAL -> 6
+ else -> 0
+ }
+ val loadScore = (bufferingSlots * 3) +
+ (errorSlots * 4) +
+ when {
+ droppedFramesDelta >= 24 -> 3
+ droppedFramesDelta >= 10 -> 2
+ droppedFramesDelta > 0 -> 1
+ else -> 0
+ } +
+ if (lowMemory) 2 else 0 +
+ thermalPenalty
+
+ val underStress = thermalStatus == MultiViewThermalStatus.SEVERE ||
+ thermalStatus == MultiViewThermalStatus.CRITICAL ||
+ loadScore >= 8 ||
+ (bufferingSlots >= 2 && droppedFramesDelta >= 10) ||
+ errorSlots >= 2
+ val stable = loadScore <= 2 &&
+ !lowMemory &&
+ (thermalStatus == MultiViewThermalStatus.NORMAL ||
+ thermalStatus == MultiViewThermalStatus.LIGHT ||
+ thermalStatus == MultiViewThermalStatus.UNKNOWN)
+
+ when {
+ underStress -> {
+ sustainedStressSamples += 1
+ stableSamples = 0
+ }
+ stable -> {
+ stableSamples += 1
+ sustainedStressSamples = 0
+ }
+ else -> {
+ sustainedStressSamples = 0
+ stableSamples = 0
+ }
+ }
+
+ val activeSlots = _uiState.value.slots.count { !it.isEmpty && it.performanceBlockedReason == null }
+ val standbySlots = _uiState.value.slots.count { !it.isEmpty && it.performanceBlockedReason != null }
+ var throttledReason = _uiState.value.telemetry.throttledReason
+
+ if (shouldThrottleDown()) {
+ if (runtimeActiveSlotLimit > 1) {
+ runtimeActiveSlotLimit -= 1
+ throttledReason = if (thermalStatus == MultiViewThermalStatus.SEVERE || thermalStatus == MultiViewThermalStatus.CRITICAL) {
+ "Thermal pressure forced Split Screen to hold extra slots in standby."
+ } else {
+ "Sustained load forced Split Screen to reduce active decoders on this device."
+ }
+ lastPolicyAdjustmentAt = System.currentTimeMillis()
+ _uiState.value = _uiState.value.copy(
+ telemetry = _uiState.value.telemetry.copy(throttledReason = throttledReason)
+ )
+ initSlots()
+ return
+ }
+ } else if (shouldRecover(policy)) {
+ runtimeActiveSlotLimit = (runtimeActiveSlotLimit + 1).coerceAtMost(policy.maxActiveSlots)
+ throttledReason = null
+ lastPolicyAdjustmentAt = System.currentTimeMillis()
+ _uiState.value = _uiState.value.copy(
+ telemetry = _uiState.value.telemetry.copy(throttledReason = null)
+ )
+ initSlots()
+ return
+ }
+
+ _uiState.value = _uiState.value.copy(
+ telemetry = _uiState.value.telemetry.copy(
+ activeSlotLimit = runtimeActiveSlotLimit,
+ activeSlots = activeSlots,
+ standbySlots = standbySlots,
+ bufferingSlots = bufferingSlots,
+ errorSlots = errorSlots,
+ droppedFramesDelta = droppedFramesDelta,
+ totalDroppedFrames = totalDroppedFrames,
+ sustainedLoadScore = loadScore,
+ thermalStatus = thermalStatus,
+ isLowMemory = lowMemory,
+ throttledReason = throttledReason,
+ recommendation = buildTelemetryRecommendation(
+ activeSlotLimit = runtimeActiveSlotLimit,
+ thermalStatus = thermalStatus,
+ isLowMemory = lowMemory,
+ sustainedLoadScore = loadScore,
+ policy = policy
+ )
+ )
+ )
+ }
+
+ private fun shouldThrottleDown(): Boolean {
+ val coolingDown = System.currentTimeMillis() - lastPolicyAdjustmentAt < 5_000
+ if (coolingDown) return false
+ return sustainedStressSamples >= 2 ||
+ thermalStatus == MultiViewThermalStatus.SEVERE ||
+ thermalStatus == MultiViewThermalStatus.CRITICAL
+ }
+
+ private fun shouldRecover(policy: MultiViewPerformancePolicyUiModel): Boolean {
+ val coolingDown = System.currentTimeMillis() - lastPolicyAdjustmentAt < 8_000
+ if (coolingDown) return false
+ return stableSamples >= 4 &&
+ runtimeActiveSlotLimit < policy.maxActiveSlots
+ }
+
+ private fun isLowMemoryDeviceState(): Boolean {
+ val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as? ActivityManager
+ val memoryInfo = ActivityManager.MemoryInfo()
+ activityManager?.getMemoryInfo(memoryInfo)
+ return memoryInfo.lowMemory || memoryInfo.availMem < 220L * 1024L * 1024L
+ }
+
+ private fun readThermalStatus(): MultiViewThermalStatus {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return MultiViewThermalStatus.UNKNOWN
+ val status = powerManager?.currentThermalStatus ?: return MultiViewThermalStatus.UNKNOWN
+ return mapThermalStatus(status)
+ }
+
+ private fun registerThermalListener() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q || thermalListener != null) return
+ val manager = powerManager ?: return
+ thermalListener = PowerManager.OnThermalStatusChangedListener { status ->
+ thermalStatus = mapThermalStatus(status)
+ }
+ manager.addThermalStatusListener(context.mainExecutor, thermalListener!!)
+ }
+
+ private fun unregisterThermalListener() {
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) return
+ val listener = thermalListener ?: return
+ powerManager?.removeThermalStatusListener(listener)
+ thermalListener = null
+ }
+
+ private fun mapThermalStatus(status: Int): MultiViewThermalStatus {
+ return when (status) {
+ PowerManager.THERMAL_STATUS_NONE -> MultiViewThermalStatus.NORMAL
+ PowerManager.THERMAL_STATUS_LIGHT -> MultiViewThermalStatus.LIGHT
+ PowerManager.THERMAL_STATUS_MODERATE -> MultiViewThermalStatus.MODERATE
+ PowerManager.THERMAL_STATUS_SEVERE -> MultiViewThermalStatus.SEVERE
+ PowerManager.THERMAL_STATUS_CRITICAL,
+ PowerManager.THERMAL_STATUS_EMERGENCY,
+ PowerManager.THERMAL_STATUS_SHUTDOWN -> MultiViewThermalStatus.CRITICAL
+ else -> MultiViewThermalStatus.UNKNOWN
+ }
+ }
+
+ private fun buildTelemetryRecommendation(
+ activeSlotLimit: Int,
+ thermalStatus: MultiViewThermalStatus,
+ isLowMemory: Boolean,
+ sustainedLoadScore: Int,
+ policy: MultiViewPerformancePolicyUiModel
+ ): String {
+ return when {
+ thermalStatus == MultiViewThermalStatus.SEVERE || thermalStatus == MultiViewThermalStatus.CRITICAL ->
+ "Device is under thermal pressure. Keep Split Screen in ${policy.mode.name.lowercase()} mode and limit active playback to $activeSlotLimit slot(s)."
+ isLowMemory ->
+ "Available memory is tight. Extra slots stay in standby until playback stabilizes."
+ sustainedLoadScore >= 8 ->
+ "Sustained decode load is high. Standby slots will protect lower-end Android TV devices from stutter."
+ activeSlotLimit < policy.maxActiveSlots ->
+ "Playback is stabilizing. Split Screen will restore more active slots when dropped frames and buffering settle down."
+ else ->
+ "Runtime telemetry is healthy. This device can keep up with the current Split Screen load."
+ }
+ }
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
index 28fd5d1c..f5a6b720 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt
@@ -52,6 +52,7 @@ import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.clickable
import androidx.compose.material3.Slider
import androidx.compose.material3.SliderDefaults
@@ -80,6 +81,10 @@ fun PlayerScreen(
providerId: Long? = null,
isVirtual: Boolean = false,
contentType: String = "LIVE",
+ archiveStartMs: Long? = null,
+ archiveEndMs: Long? = null,
+ archiveTitle: String? = null,
+ returnRoute: String? = null,
onBack: () -> Unit,
onNavigate: ((String) -> Unit)? = null,
viewModel: PlayerViewModel = hiltViewModel(),
@@ -100,6 +105,8 @@ fun PlayerScreen(
val showChannelListOverlay by viewModel.showChannelListOverlay.collectAsState()
val showEpgOverlay by viewModel.showEpgOverlay.collectAsState()
val currentChannelList by viewModel.currentChannelList.collectAsState()
+ val recentChannels by viewModel.recentChannels.collectAsState()
+ val lastVisitedCategory by viewModel.lastVisitedCategory.collectAsState()
val displayChannelNumber by viewModel.displayChannelNumber.collectAsState()
val upcomingPrograms by viewModel.upcomingPrograms.collectAsState()
val showChannelInfoOverlay by viewModel.showChannelInfoOverlay.collectAsState()
@@ -111,8 +118,11 @@ fun PlayerScreen(
val aspectRatio by viewModel.aspectRatio.collectAsState()
val showDiagnostics by viewModel.showDiagnostics.collectAsState()
val playerStats by viewModel.playerStats.collectAsState()
+ val playerDiagnostics by viewModel.playerDiagnostics.collectAsState()
val currentPosition by viewModel.playerEngine.currentPosition.collectAsState()
val duration by viewModel.playerEngine.duration.collectAsState()
+ val playerNotice by viewModel.playerNotice.collectAsState()
+ val currentChannelRecording by viewModel.currentChannelRecording.collectAsState()
var showTrackSelection by remember { mutableStateOf<TrackType?>(null) }
var showProgramHistory by remember { mutableStateOf(false) }
@@ -204,8 +214,20 @@ fun PlayerScreen(
)
}
- LaunchedEffect(streamUrl, epgChannelId) {
- viewModel.prepare(streamUrl, epgChannelId, internalChannelId, categoryId ?: -1, providerId ?: -1, isVirtual, contentType)
+ LaunchedEffect(streamUrl, epgChannelId, title, internalChannelId, categoryId, providerId, isVirtual, contentType, archiveStartMs, archiveEndMs, archiveTitle) {
+ viewModel.prepare(
+ streamUrl = streamUrl,
+ epgChannelId = epgChannelId,
+ internalChannelId = internalChannelId,
+ categoryId = categoryId ?: -1,
+ providerId = providerId ?: -1,
+ isVirtual = isVirtual,
+ contentType = contentType,
+ title = title,
+ archiveStartMs = archiveStartMs,
+ archiveEndMs = archiveEndMs,
+ archiveTitle = archiveTitle
+ )
}
LaunchedEffect(showControls) {
@@ -218,6 +240,17 @@ fun PlayerScreen(
}
}
+ val handlePlayerNoticeAction: (PlayerNoticeAction) -> Unit = remember(returnRoute, onNavigate) {
+ { action ->
+ if (action == PlayerNoticeAction.OPEN_GUIDE && !returnRoute.isNullOrBlank() && onNavigate != null) {
+ viewModel.dismissPlayerNotice()
+ onNavigate(returnRoute)
+ } else {
+ viewModel.runPlayerNoticeAction(action)
+ }
+ }
+ }
+
Box(
modifier = Modifier
.fillMaxSize()
@@ -289,6 +322,9 @@ fun PlayerScreen(
if (viewModel.hasPendingNumericChannelInput()) {
viewModel.clearNumericChannelInput()
true
+ } else if (playerNotice != null) {
+ viewModel.dismissPlayerNotice()
+ true
} else if (showProgramHistory) {
showProgramHistory = false
true
@@ -431,6 +467,58 @@ fun PlayerScreen(
}
}
+ AnimatedVisibility(
+ visible = playerNotice != null,
+ enter = fadeIn(),
+ exit = fadeOut(),
+ modifier = Modifier
+ .align(Alignment.TopCenter)
+ .padding(top = 116.dp)
+ ) {
+ Surface(
+ onClick = viewModel::dismissPlayerNotice,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color(0xCC5B1F1F),
+ focusedContainerColor = Color(0xFFE45757)
+ )
+ ) {
+ Column(modifier = Modifier.padding(horizontal = 18.dp, vertical = 12.dp)) {
+ Text(
+ text = playerNotice?.message.orEmpty(),
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White
+ )
+ if (!playerNotice?.actions.isNullOrEmpty()) {
+ Spacer(modifier = Modifier.height(10.dp))
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ playerNotice?.actions.orEmpty().forEach { action ->
+ Surface(
+ onClick = { handlePlayerNoticeAction(action) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.12f),
+ focusedContainerColor = Color.White.copy(alpha = 0.22f)
+ )
+ ) {
+ Text(
+ text = when (action) {
+ PlayerNoticeAction.RETRY -> stringResource(R.string.player_retry)
+ PlayerNoticeAction.LAST_CHANNEL -> stringResource(R.string.player_last_channel_action)
+ PlayerNoticeAction.ALTERNATE_STREAM -> stringResource(R.string.player_try_alternate_stream)
+ PlayerNoticeAction.OPEN_GUIDE -> stringResource(R.string.player_open_guide_action)
+ },
+ color = Color.White,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 8.dp)
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
// Error overlay
if (playbackState == PlaybackState.ERROR) {
Box(
@@ -465,27 +553,48 @@ fun PlayerScreen(
)
Spacer(modifier = Modifier.height(16.dp))
-
- // Retry button
- Surface(
- onClick = { viewModel.retryStream(streamUrl, epgChannelId) },
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = Primary,
- focusedContainerColor = PrimaryVariant
- )
+
+ val recoveryActions = buildList {
+ add(PlayerNoticeAction.RETRY)
+ if (contentType == "LIVE" && viewModel.hasAlternateStream()) add(PlayerNoticeAction.ALTERNATE_STREAM)
+ if (contentType == "LIVE" && viewModel.hasLastChannel()) add(PlayerNoticeAction.LAST_CHANNEL)
+ }
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(12.dp),
+ verticalAlignment = Alignment.CenterVertically
) {
- Text(
- text = stringResource(R.string.player_retry),
- color = OnBackground,
- modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)
- )
+ recoveryActions.forEach { action ->
+ Surface(
+ onClick = { handlePlayerNoticeAction(action) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (action == PlayerNoticeAction.RETRY) Primary else Color.White.copy(alpha = 0.08f),
+ focusedContainerColor = if (action == PlayerNoticeAction.RETRY) PrimaryVariant else Color.White.copy(alpha = 0.18f)
+ )
+ ) {
+ Text(
+ text = when (action) {
+ PlayerNoticeAction.RETRY -> stringResource(R.string.player_retry)
+ PlayerNoticeAction.LAST_CHANNEL -> stringResource(R.string.player_last_channel_action)
+ PlayerNoticeAction.ALTERNATE_STREAM -> stringResource(R.string.player_try_alternate_stream)
+ PlayerNoticeAction.OPEN_GUIDE -> stringResource(R.string.player_open_guide_action)
+ },
+ color = if (action == PlayerNoticeAction.RETRY) OnBackground else Color.White,
+ modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)
+ )
+ }
+ }
}
Spacer(modifier = Modifier.height(8.dp))
Text(
- text = stringResource(R.string.player_error_back),
+ text = if (contentType == "LIVE" && viewModel.hasLastChannel()) {
+ stringResource(R.string.player_error_live_hint)
+ } else {
+ stringResource(R.string.player_error_back)
+ },
style = MaterialTheme.typography.bodySmall,
color = OnSurfaceDim
)
@@ -612,6 +721,12 @@ fun PlayerScreen(
QuickSettingsButton(stringResource(R.string.player_restart)) { viewModel.restartCurrentProgram() }
QuickSettingsButton(stringResource(R.string.player_archive)) { showProgramHistory = true }
}
+ if (currentChannelRecording?.status == com.streamvault.domain.model.RecordingStatus.RECORDING) {
+ QuickSettingsButton(stringResource(R.string.player_stop_recording)) { viewModel.stopCurrentRecording() }
+ } else {
+ QuickSettingsButton(stringResource(R.string.player_record)) { viewModel.startManualRecording() }
+ QuickSettingsButton(stringResource(R.string.player_schedule_recording)) { viewModel.scheduleRecording() }
+ }
QuickSettingsButton(stringResource(R.string.player_aspect_ratio_label, aspectRatio.modeName)) { viewModel.toggleAspectRatio() }
if (availableSubtitleTracks.isNotEmpty()) {
QuickSettingsButton(stringResource(R.string.player_subs)) { showTrackSelection = TrackType.TEXT }
@@ -1027,6 +1142,7 @@ fun PlayerScreen(
if (showDiagnostics) {
DiagnosticsOverlay(
stats = playerStats,
+ diagnostics = playerDiagnostics,
modifier = Modifier.align(Alignment.TopStart).padding(32.dp)
)
}
@@ -1043,10 +1159,13 @@ fun PlayerScreen(
) {
ChannelListOverlay(
channels = currentChannelList,
- currentChannelId = internalChannelId,
+ recentChannels = recentChannels,
+ currentChannelId = currentChannel?.id ?: internalChannelId,
overlayFocusRequester = channelListFocusRequester,
preferredFocusedChannelId = lastFocusedChannelListItemId,
onFocusedChannelChange = { channelId -> lastFocusedChannelListItemId = channelId },
+ lastVisitedCategoryName = lastVisitedCategory?.name,
+ onOpenLastGroup = { viewModel.openLastVisitedCategory() },
onSelectChannel = { channelId -> viewModel.zapToChannel(channelId) },
onDismiss = { viewModel.closeOverlays() }
)
@@ -1094,11 +1213,20 @@ fun PlayerScreen(
currentProgram = currentProgram,
nextProgram = nextProgram,
focusRequester = channelInfoFocusRequester,
+ lastVisitedCategoryName = lastVisitedCategory?.name,
onDismiss = { viewModel.closeChannelInfoOverlay() },
onOpenFullEpg = {
viewModel.closeChannelInfoOverlay()
viewModel.openEpgOverlay()
},
+ onOpenLastGroup = {
+ viewModel.closeChannelInfoOverlay()
+ viewModel.openLastVisitedCategory()
+ },
+ onOpenRecentChannels = {
+ viewModel.closeChannelInfoOverlay()
+ viewModel.openChannelListOverlay()
+ },
onOpenFullControls = {
viewModel.closeChannelInfoOverlay()
viewModel.toggleControls()
@@ -1123,8 +1251,11 @@ fun ChannelInfoOverlay(
currentProgram: Program?,
nextProgram: Program?,
focusRequester: FocusRequester,
+ lastVisitedCategoryName: String?,
onDismiss: () -> Unit,
onOpenFullEpg: () -> Unit,
+ onOpenLastGroup: () -> Unit,
+ onOpenRecentChannels: () -> Unit,
onOpenFullControls: () -> Unit,
onRestartProgram: () -> Unit,
onToggleAspectRatio: () -> Unit,
@@ -1297,6 +1428,18 @@ fun ChannelInfoOverlay(
onClick = onToggleAspectRatio,
modifier = Modifier.focusRequester(focusRequester)
)
+ if (!lastVisitedCategoryName.isNullOrBlank()) {
+ QuickActionButton(
+ icon = "LG",
+ label = stringResource(R.string.player_last_group_label, lastVisitedCategoryName),
+ onClick = onOpenLastGroup
+ )
+ }
+ QuickActionButton(
+ icon = "RC",
+ label = stringResource(R.string.player_recent_channels),
+ onClick = onOpenRecentChannels
+ )
QuickActionButton(
icon = "EPG",
label = stringResource(R.string.player_full_epg),
@@ -1398,10 +1541,13 @@ private fun TrackItem(
@Composable
fun ChannelListOverlay(
channels: List<com.streamvault.domain.model.Channel>,
+ recentChannels: List<com.streamvault.domain.model.Channel>,
currentChannelId: Long,
overlayFocusRequester: FocusRequester = remember { FocusRequester() },
preferredFocusedChannelId: Long? = null,
onFocusedChannelChange: (Long) -> Unit = {},
+ lastVisitedCategoryName: String? = null,
+ onOpenLastGroup: () -> Unit = {},
onSelectChannel: (Long) -> Unit,
onDismiss: () -> Unit
) {
@@ -1432,14 +1578,110 @@ fun ChannelListOverlay(
.background(Color.Black.copy(alpha = 0.70f)),
contentPadding = PaddingValues(top = 16.dp, bottom = 32.dp)
) {
+ item {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 24.dp, vertical = 24.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(R.string.player_channel_list_title, channels.size),
+ style = MaterialTheme.typography.titleMedium,
+ color = Primary
+ )
+ if (!lastVisitedCategoryName.isNullOrBlank()) {
+ Surface(
+ onClick = onOpenLastGroup,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.08f),
+ focusedContainerColor = Primary
+ )
+ ) {
+ Text(
+ text = stringResource(R.string.player_last_group_label, lastVisitedCategoryName),
+ style = MaterialTheme.typography.labelMedium,
+ color = Color.White,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
+ )
+ }
+ }
+ }
+ }
+ if (!lastVisitedCategoryName.isNullOrBlank()) {
+ item {
+ Text(
+ text = stringResource(R.string.player_last_group_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 24.dp)
+ )
+ }
+ }
item {
Text(
- text = stringResource(R.string.player_channel_list_title, channels.size),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- modifier = Modifier.padding(horizontal = 24.dp, vertical = 24.dp)
+ text = stringResource(R.string.player_channel_list_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 24.dp, vertical = 8.dp)
)
}
+ if (recentChannels.isNotEmpty()) {
+ item {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(horizontal = 16.dp, vertical = 4.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.player_recent_channels),
+ style = MaterialTheme.typography.labelLarge,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 8.dp)
+ )
+ LazyRow(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ contentPadding = PaddingValues(horizontal = 8.dp, vertical = 4.dp)
+ ) {
+ items(recentChannels, key = { it.id }) { channel ->
+ Surface(
+ onClick = {
+ onSelectChannel(channel.id)
+ onDismiss()
+ },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(999.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.08f),
+ focusedContainerColor = Primary
+ )
+ ) {
+ Row(
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ val recentNumber = if (channel.number > 0) channel.number.toString() else "?"
+ Text(
+ text = recentNumber,
+ style = MaterialTheme.typography.labelMedium,
+ color = Color.White.copy(alpha = 0.75f)
+ )
+ Text(
+ text = channel.name,
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White,
+ maxLines = 1,
+ overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+ }
+ }
+ }
items(channels.size) { index ->
val channel = channels[index]
val isSelected = channel.id == currentChannelId
@@ -1572,6 +1814,12 @@ fun EpgOverlay(
)
}
}
+ Spacer(Modifier.height(8.dp))
+ Text(
+ text = stringResource(R.string.player_epg_overlay_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
}
// Now Playing section
@@ -1808,6 +2056,7 @@ private fun formatDuration(ms: Long): String {
@Composable
fun DiagnosticsOverlay(
stats: com.streamvault.player.PlayerStats,
+ diagnostics: PlayerDiagnosticsUiState,
modifier: Modifier = Modifier
) {
Box(
@@ -1818,11 +2067,45 @@ fun DiagnosticsOverlay(
Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
Text("Player Diagnostics", color = Primary, style = MaterialTheme.typography.labelMedium, fontWeight = FontWeight.Bold)
Spacer(Modifier.height(4.dp))
+ if (diagnostics.providerName.isNotBlank()) {
+ Text("Provider: ${diagnostics.providerName}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ }
+ if (diagnostics.providerSourceLabel.isNotBlank()) {
+ Text("Source: ${diagnostics.providerSourceLabel}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ }
+ Text("Decoder: ${diagnostics.decoderMode.name}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ Text("Stream Class: ${diagnostics.streamClassLabel}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ Text("Playback State: ${diagnostics.playbackStateLabel}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ if (diagnostics.archiveSupportLabel.isNotBlank()) {
+ Text("Archive: ${diagnostics.archiveSupportLabel}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ }
+ Text("Alternate Streams: ${diagnostics.alternativeStreamCount}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ if (diagnostics.channelErrorCount > 0) {
+ Text("Channel Errors: ${diagnostics.channelErrorCount}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ }
Text("Resolution: ${stats.width}x${stats.height}", color = Color.White, style = MaterialTheme.typography.bodySmall)
Text("Video Codec: ${stats.videoCodec}", color = Color.White, style = MaterialTheme.typography.bodySmall)
Text("Audio Codec: ${stats.audioCodec}", color = Color.White, style = MaterialTheme.typography.bodySmall)
Text("Video Bitrate: ${stats.videoBitrate / 1000} kbps", color = Color.White, style = MaterialTheme.typography.bodySmall)
Text("Dropped Frames: ${stats.droppedFrames}", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ diagnostics.lastFailureReason?.let { reason ->
+ Spacer(Modifier.height(4.dp))
+ Text("Last Failure: $reason", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ }
+ if (diagnostics.recentRecoveryActions.isNotEmpty()) {
+ Spacer(Modifier.height(4.dp))
+ Text("Recovery Actions", color = Primary, style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)
+ diagnostics.recentRecoveryActions.forEach { action ->
+ Text("• $action", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ }
+ }
+ if (diagnostics.troubleshootingHints.isNotEmpty()) {
+ Spacer(Modifier.height(4.dp))
+ Text("Troubleshooting", color = Primary, style = MaterialTheme.typography.labelSmall, fontWeight = FontWeight.Bold)
+ diagnostics.troubleshootingHints.forEach { hint ->
+ Text("- $hint", color = Color.White, style = MaterialTheme.typography.bodySmall)
+ }
+ }
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index c6075d48..2c154cc6 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -2,11 +2,18 @@ package com.streamvault.app.ui.screens.player
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.manager.RecordingManager
+import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Program
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.RecordingItem
+import com.streamvault.domain.model.RecordingRequest
+import com.streamvault.domain.model.RecordingStatus
+import com.streamvault.domain.model.VirtualCategoryIds
import com.streamvault.domain.model.VideoFormat
+import com.streamvault.domain.usecase.GetCustomCategories
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.EpgRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
@@ -33,6 +40,42 @@ data class NumericChannelInputState(
val invalid: Boolean = false
)
+data class PlayerNoticeState(
+ val message: String = "",
+ val recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,
+ val actions: List<PlayerNoticeAction> = emptyList()
+)
+
+data class PlayerDiagnosticsUiState(
+ val providerName: String = "",
+ val providerSourceLabel: String = "",
+ val decoderMode: DecoderMode = DecoderMode.AUTO,
+ val streamClassLabel: String = "Primary",
+ val playbackStateLabel: String = "Idle",
+ val alternativeStreamCount: Int = 0,
+ val channelErrorCount: Int = 0,
+ val archiveSupportLabel: String = "",
+ val lastFailureReason: String? = null,
+ val recentRecoveryActions: List<String> = emptyList(),
+ val troubleshootingHints: List<String> = emptyList()
+)
+
+enum class PlayerRecoveryType {
+ NETWORK,
+ SOURCE,
+ DECODER,
+ CATCH_UP,
+ BUFFER_TIMEOUT,
+ UNKNOWN
+}
+
+enum class PlayerNoticeAction {
+ RETRY,
+ LAST_CHANNEL,
+ ALTERNATE_STREAM,
+ OPEN_GUIDE
+}
+
enum class AspectRatio(val modeName: String) {
FIT("Fit"),
FILL("Stretch"),
@@ -48,7 +91,9 @@ class PlayerViewModel @Inject constructor(
private val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,
private val playbackHistoryRepository: PlaybackHistoryRepository,
private val providerRepository: com.streamvault.domain.repository.ProviderRepository,
- private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository
+ private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,
+ private val getCustomCategories: GetCustomCategories,
+ private val recordingManager: RecordingManager
) : ViewModel() {
private val _showControls = MutableStateFlow(false)
@@ -87,6 +132,12 @@ class PlayerViewModel @Inject constructor(
private val _currentChannelList = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())
val currentChannelList: StateFlow<List<com.streamvault.domain.model.Channel>> = _currentChannelList.asStateFlow()
+ private val _recentChannels = MutableStateFlow<List<com.streamvault.domain.model.Channel>>(emptyList())
+ val recentChannels: StateFlow<List<com.streamvault.domain.model.Channel>> = _recentChannels.asStateFlow()
+
+ private val _lastVisitedCategory = MutableStateFlow<Category?>(null)
+ val lastVisitedCategory: StateFlow<Category?> = _lastVisitedCategory.asStateFlow()
+
private val _displayChannelNumber = MutableStateFlow(0)
val displayChannelNumber: StateFlow<Int> = _displayChannelNumber.asStateFlow()
@@ -99,12 +150,25 @@ class PlayerViewModel @Inject constructor(
private val _showDiagnostics = MutableStateFlow(false)
val showDiagnostics: StateFlow<Boolean> = _showDiagnostics.asStateFlow()
+ private val _playerNotice = MutableStateFlow<PlayerNoticeState?>(null)
+ val playerNotice: StateFlow<PlayerNoticeState?> = _playerNotice.asStateFlow()
+ private val _playerDiagnostics = MutableStateFlow(PlayerDiagnosticsUiState())
+ val playerDiagnostics: StateFlow<PlayerDiagnosticsUiState> = _playerDiagnostics.asStateFlow()
+ private val _recordingItems = MutableStateFlow<List<RecordingItem>>(emptyList())
+ val recordingItems: StateFlow<List<RecordingItem>> = _recordingItems.asStateFlow()
+ private val _currentChannelRecording = MutableStateFlow<RecordingItem?>(null)
+ val currentChannelRecording: StateFlow<RecordingItem?> = _currentChannelRecording.asStateFlow()
+
private var channelInfoHideJob: Job? = null
private var numericInputCommitJob: Job? = null
private var numericInputFeedbackJob: Job? = null
+ private var playerNoticeHideJob: Job? = null
private var numericInputBuffer: String = ""
private val triedAlternativeStreams = mutableSetOf<String>()
+ private val failedStreamsThisSession = mutableMapOf<String, Int>()
private var hasRetriedWithSoftwareDecoder = false
+ private var lastRecordedLivePlaybackKey: Pair<Long, Long>? = null
+ private var currentStreamClassLabel: String = "Primary"
init {
viewModelScope.launch {
@@ -116,6 +180,7 @@ class PlayerViewModel @Inject constructor(
}
viewModelScope.launch {
playerEngine.playbackState.collect { state ->
+ _playerDiagnostics.update { it.copy(playbackStateLabel = state.name.replace('_', ' ')) }
if (state == PlaybackState.READY && currentContentType == ContentType.LIVE) {
zapBufferWatchdogJob?.cancel()
_currentChannel.value?.let { channel ->
@@ -126,6 +191,12 @@ class PlayerViewModel @Inject constructor(
}
}
}
+ viewModelScope.launch {
+ recordingManager.observeRecordingItems().collect { items ->
+ _recordingItems.value = items
+ refreshCurrentChannelRecording(items)
+ }
+ }
}
private fun handlePlaybackError(error: PlayerError) {
@@ -133,40 +204,64 @@ class PlayerViewModel @Inject constructor(
hasRetriedWithSoftwareDecoder = true
android.util.Log.w("PlayerVM", "Decoder error detected. Retrying with software decoder mode.")
playerEngine.setDecoderMode(DecoderMode.SOFTWARE)
+ updateDecoderMode(DecoderMode.SOFTWARE)
+ setLastFailureReason(error.message)
+ appendRecoveryAction("Switched to software decoder")
playerEngine.play()
+ showPlayerNotice(
+ message = "Retrying with software decoding for this stream.",
+ recoveryType = PlayerRecoveryType.DECODER,
+ actions = buildRecoveryActions(PlayerRecoveryType.DECODER)
+ )
+ return
+ }
+ val recoveryType = classifyPlaybackError(error)
+ val channel = _currentChannel.value
+
+ if (currentContentType != ContentType.LIVE || channel == null) {
+ showPlayerNotice(
+ message = resolvePlaybackErrorMessage(error),
+ recoveryType = recoveryType,
+ actions = buildRecoveryActions(recoveryType)
+ )
return
}
- // Only auto-switch for live TV
- if (currentContentType != ContentType.LIVE) return
-
- // Only for network or source errors (potential broken links)
- if (error is PlayerError.NetworkError || error is PlayerError.SourceError) {
- val channel = _currentChannel.value ?: return
-
- viewModelScope.launch {
- // 1. Mark as broken in DB
- channelRepository.incrementChannelErrorCount(channel.id)
-
- // 2. Try alternative streams
- val nextStream = channel.alternativeStreams.firstOrNull {
- it !in triedAlternativeStreams && it != currentStreamUrl
- }
-
- if (nextStream != null) {
- triedAlternativeStreams.add(nextStream)
- android.util.Log.d("PlayerVM", "Switching to alternative stream for current channel")
-
- val streamInfo = com.streamvault.domain.model.StreamInfo(
- url = nextStream,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
- )
- playerEngine.prepare(streamInfo)
- playerEngine.play()
- } else {
- android.util.Log.e("PlayerVM", "No more alternative streams for current channel")
- fallbackToPreviousChannel("No alternative stream")
- }
+ viewModelScope.launch {
+ markStreamFailure(currentStreamUrl)
+ setLastFailureReason(error.message)
+ channelRepository.incrementChannelErrorCount(channel.id)
+
+ val switched = when (recoveryType) {
+ PlayerRecoveryType.NETWORK,
+ PlayerRecoveryType.SOURCE,
+ PlayerRecoveryType.BUFFER_TIMEOUT -> tryAlternateStreamInternal(channel)
+ else -> false
+ }
+
+ if (switched) {
+ appendRecoveryAction("Trying alternate stream")
+ showPlayerNotice(
+ message = "Trying an alternate stream for ${channel.name}.",
+ recoveryType = recoveryType,
+ actions = buildRecoveryActions(recoveryType)
+ )
+ return@launch
+ }
+
+ if (fallbackToPreviousChannel("Recovery path exhausted for ${recoveryType.name.lowercase()}")) {
+ appendRecoveryAction("Returned to last channel")
+ showPlayerNotice(
+ message = "Playback failed on this stream. Returned to the last channel.",
+ recoveryType = recoveryType,
+ actions = buildRecoveryActions(recoveryType)
+ )
+ } else {
+ showPlayerNotice(
+ message = resolvePlaybackErrorMessage(error),
+ recoveryType = recoveryType,
+ actions = buildRecoveryActions(recoveryType)
+ )
}
}
}
@@ -213,6 +308,15 @@ class PlayerViewModel @Inject constructor(
channelInfoHideJob?.cancel()
}
+ private fun refreshCurrentChannelRecording(items: List<RecordingItem> = _recordingItems.value) {
+ val channelId = _currentChannel.value?.id ?: -1L
+ _currentChannelRecording.value = items.firstOrNull {
+ it.providerId == currentProviderId &&
+ it.channelId == channelId &&
+ (it.status == RecordingStatus.RECORDING || it.status == RecordingStatus.SCHEDULED)
+ }
+ }
+
fun toggleDiagnostics() {
_showDiagnostics.value = !_showDiagnostics.value
}
@@ -230,6 +334,8 @@ class PlayerViewModel @Inject constructor(
private var epgJob: Job? = null
private var playlistJob: Job? = null
+ private var recentChannelsJob: Job? = null
+ private var lastVisitedCategoryJob: Job? = null
private var controlsHideJob: Job? = null
private var progressTrackingJob: Job? = null
private var zapOverlayJob: Job? = null
@@ -279,15 +385,28 @@ class PlayerViewModel @Inject constructor(
providerId: Long = -1,
isVirtual: Boolean = false,
contentType: String = "CHANNEL",
- title: String = ""
+ title: String = "",
+ archiveStartMs: Long? = null,
+ archiveEndMs: Long? = null,
+ archiveTitle: String? = null
) {
currentStreamUrl = streamUrl
currentProviderId = providerId
currentContentId = internalChannelId
currentTitle = title
currentContentType = try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE }
+ currentStreamClassLabel = if (archiveStartMs != null && archiveEndMs != null) "Catch-up" else "Primary"
+ if (currentContentType != ContentType.LIVE) {
+ lastRecordedLivePlaybackKey = null
+ recentChannelsJob?.cancel()
+ _recentChannels.value = emptyList()
+ lastVisitedCategoryJob?.cancel()
+ _lastVisitedCategory.value = null
+ }
hasRetriedWithSoftwareDecoder = false
playerEngine.setDecoderMode(DecoderMode.AUTO)
+ updateDecoderMode(DecoderMode.AUTO)
+ updateStreamClass(currentStreamClassLabel)
// Reset tried streams for manual switch
triedAlternativeStreams.clear()
@@ -301,6 +420,24 @@ class PlayerViewModel @Inject constructor(
// Show context info on entry for both Live and VOD
openChannelInfoOverlay()
+
+ if (providerId > 0) {
+ viewModelScope.launch {
+ providerRepository.getProvider(providerId)?.let { provider ->
+ _playerDiagnostics.update {
+ it.copy(
+ providerName = provider.name,
+ providerSourceLabel = when (provider.type) {
+ com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "Xtream Codes"
+ com.streamvault.domain.model.ProviderType.M3U -> "M3U Playlist"
+ }
+ )
+ }
+ }
+ }
+ } else {
+ _playerDiagnostics.update { it.copy(providerName = "", providerSourceLabel = "") }
+ }
// 1. Check for Resume Position for VODs
if (currentContentType != ContentType.LIVE && currentContentId != -1L && currentProviderId != -1L) {
@@ -324,19 +461,57 @@ class PlayerViewModel @Inject constructor(
isVirtualCategory = isVirtual
loadPlaylist(categoryId, providerId, isVirtual, internalChannelId)
} else {
- // If playlist already loaded, just update index
- if (channelList.isNotEmpty() && internalChannelId != -1L) {
- currentChannelIndex = channelList.indexOfFirst { it.id == internalChannelId }
- // Fallback to URL if ID fail
- if (currentChannelIndex == -1) {
- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == streamUrl }
- }
- }
+ // If playlist already loaded, just update index
+ if (channelList.isNotEmpty() && internalChannelId != -1L) {
+ currentChannelIndex = channelList.indexOfFirst { it.id == internalChannelId }
+ if (currentChannelIndex == -1) {
+ currentChannelIndex = channelList.indexOfFirst { it.streamUrl == streamUrl }
+ }
+ }
}
- currentStreamUrl = streamUrl
-
+
+ if (
+ currentContentType == ContentType.LIVE &&
+ archiveStartMs != null &&
+ archiveEndMs != null &&
+ archiveStartMs > 0L &&
+ archiveEndMs > archiveStartMs
+ ) {
+ viewModelScope.launch {
+ val catchUpUrl = providerRepository.buildCatchUpUrl(
+ providerId = currentProviderId,
+ streamId = currentContentId,
+ start = archiveStartMs / 1000L,
+ end = archiveEndMs / 1000L
+ )
+ if (catchUpUrl != null) {
+ currentTitle = archiveTitle?.takeIf { it.isNotBlank() } ?: currentTitle
+ currentStreamUrl = catchUpUrl
+ updateStreamClass("Catch-up")
+ appendRecoveryAction("Opened catch-up stream")
+ val catchupStream = com.streamvault.domain.model.StreamInfo(
+ url = catchUpUrl,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ playerEngine.prepare(catchupStream)
+ playerEngine.play()
+ _showControls.value = true
+ } else {
+ val reason = resolveCatchUpFailureMessage(_currentChannel.value, archiveRequested = true, programHasArchive = true)
+ setLastFailureReason(reason)
+ showPlayerNotice(
+ message = reason,
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
+ )
+ }
+ }
+ }
+
// Fetch EPG if ID provided
fetchEpg(currentProviderId, epgChannelId)
+ observeRecentChannels()
+ observeLastVisitedCategory()
// Load Aspect Ratio safely (fallback to FIT if none saved)
aspectRatioJob?.cancel()
@@ -356,6 +531,23 @@ class PlayerViewModel @Inject constructor(
viewModelScope.launch {
val channel = channelRepository.getChannel(internalChannelId)
_currentChannel.value = channel
+ refreshCurrentChannelRecording()
+ if (channel != null) {
+ currentTitle = channel.name.ifBlank { currentTitle }
+ currentStreamUrl = if (currentStreamClassLabel == "Catch-up") currentStreamUrl else channel.streamUrl
+ updateStreamClass(
+ when {
+ currentStreamClassLabel == "Catch-up" -> "Catch-up"
+ streamUrl == channel.streamUrl -> "Primary"
+ channel.alternativeStreams.contains(streamUrl) -> "Alternate"
+ else -> "Direct"
+ }
+ )
+ if (currentContentType == ContentType.LIVE) {
+ recordLivePlayback(channel)
+ }
+ updateChannelDiagnostics(channel)
+ }
if (channel != null && channel.alternativeStreams.isNotEmpty()) {
val tracks = mutableListOf<com.streamvault.player.PlayerTrack>()
tracks.add(
@@ -491,7 +683,24 @@ class PlayerViewModel @Inject constructor(
playlistJob?.cancel()
playlistJob = viewModelScope.launch {
val flows = if (isVirtual) {
- if (categoryId == -999L) {
+ if (categoryId == VirtualCategoryIds.RECENT) {
+ playbackHistoryRepository.getRecentlyWatchedByProvider(providerId, limit = 24)
+ .map { history ->
+ history.asSequence()
+ .filter { it.contentType == ContentType.LIVE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.contentId }
+ .map { it.contentId }
+ .toList()
+ }
+ .flatMapLatest { ids ->
+ if (ids.isEmpty()) flowOf(emptyList())
+ else channelRepository.getChannelsByIds(ids).map { unsorted ->
+ val map = unsorted.associateBy { it.id }
+ ids.mapNotNull { map[it] }
+ }
+ }
+ } else if (categoryId == VirtualCategoryIds.FAVORITES) {
// Global Favorites
favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE)
.map { favorites -> favorites.map { it.contentId } }
@@ -525,6 +734,7 @@ class PlayerViewModel @Inject constructor(
if (currentChannelIndex != -1) {
_currentChannel.value = channelList[currentChannelIndex]
+ refreshCurrentChannelRecording()
val ch = channelList[currentChannelIndex]
_displayChannelNumber.value = if (ch.number > 0) ch.number else currentChannelIndex + 1
}
@@ -535,6 +745,76 @@ class PlayerViewModel @Inject constructor(
// Store current URL to find index later
private var currentStreamUrl: String = ""
+ private fun observeRecentChannels() {
+ recentChannelsJob?.cancel()
+ if (currentContentType != ContentType.LIVE || currentProviderId <= 0) {
+ _recentChannels.value = emptyList()
+ return
+ }
+
+ recentChannelsJob = viewModelScope.launch {
+ playbackHistoryRepository.getRecentlyWatchedByProvider(currentProviderId, limit = 12)
+ .map { history ->
+ history.asSequence()
+ .filter { it.contentType == ContentType.LIVE }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.contentId }
+ .map { it.contentId }
+ .toList()
+ }
+ .flatMapLatest { ids ->
+ if (ids.isEmpty()) flowOf(emptyList())
+ else channelRepository.getChannelsByIds(ids).map { channels ->
+ val channelMap = channels.associateBy { it.id }
+ ids.mapNotNull { channelMap[it] }
+ }
+ }
+ .collect { channels ->
+ _recentChannels.value = channels.filterNot { it.id == currentContentId }
+ }
+ }
+ }
+
+ private fun observeLastVisitedCategory() {
+ lastVisitedCategoryJob?.cancel()
+ if (currentContentType != ContentType.LIVE || currentProviderId <= 0) {
+ _lastVisitedCategory.value = null
+ return
+ }
+
+ lastVisitedCategoryJob = viewModelScope.launch {
+ combine(
+ channelRepository.getCategories(currentProviderId),
+ getCustomCategories(ContentType.LIVE),
+ preferencesRepository.getLastLiveCategoryId(currentProviderId)
+ ) { providerCategories, customCategories, lastVisitedCategoryId ->
+ if (lastVisitedCategoryId == null || lastVisitedCategoryId == VirtualCategoryIds.RECENT) {
+ null
+ } else {
+ (customCategories + providerCategories)
+ .firstOrNull { it.id == lastVisitedCategoryId }
+ }
+ }.collect { category ->
+ _lastVisitedCategory.value = category
+ }
+ }
+ }
+
+ fun openLastVisitedCategory() {
+ val category = _lastVisitedCategory.value ?: return
+ if (currentContentType != ContentType.LIVE || currentProviderId <= 0) return
+
+ currentCategoryId = category.id
+ isVirtualCategory = category.isVirtual
+ loadPlaylist(
+ categoryId = category.id,
+ providerId = currentProviderId,
+ isVirtual = category.isVirtual,
+ initialChannelId = currentContentId
+ )
+ openChannelListOverlay()
+ }
+
fun playNext() {
clearNumericChannelInput()
if (channelList.isEmpty()) return
@@ -577,6 +857,11 @@ class PlayerViewModel @Inject constructor(
changeChannel(previousChannelIndex)
}
+ fun hasLastChannel(): Boolean =
+ currentContentType == ContentType.LIVE &&
+ previousChannelIndex in channelList.indices &&
+ previousChannelIndex != currentChannelIndex
+
fun hasPendingNumericChannelInput(): Boolean = numericInputBuffer.isNotBlank()
fun inputNumericChannelDigit(digit: Int) {
@@ -646,8 +931,14 @@ class PlayerViewModel @Inject constructor(
}
val channel = channelList[index]
currentChannelIndex = index
+ currentContentId = channel.id
+ currentTitle = channel.name
+ currentStreamUrl = channel.streamUrl
+ updateStreamClass("Primary")
_currentChannel.value = channel
+ refreshCurrentChannelRecording()
_displayChannelNumber.value = if (channel.number > 0) channel.number else index + 1
+ _recentChannels.update { channels -> channels.filterNot { it.id == channel.id } }
// Prepare player
val streamInfo = com.streamvault.domain.model.StreamInfo(
@@ -667,13 +958,163 @@ class PlayerViewModel @Inject constructor(
// Reset tried streams for manual switch
triedAlternativeStreams.clear()
triedAlternativeStreams.add(channel.streamUrl)
-
+
hideZapOverlayAfterDelay()
if (currentContentType == ContentType.LIVE) {
+ recordLivePlayback(channel)
scheduleZapBufferWatchdog(index)
}
}
+ private fun recordLivePlayback(channel: com.streamvault.domain.model.Channel) {
+ if (currentProviderId <= 0 || currentContentType != ContentType.LIVE) return
+
+ val playbackKey = currentProviderId to channel.id
+ if (lastRecordedLivePlaybackKey == playbackKey) return
+ lastRecordedLivePlaybackKey = playbackKey
+
+ viewModelScope.launch {
+ playbackHistoryRepository.recordPlayback(
+ PlaybackHistory(
+ contentId = channel.id,
+ contentType = ContentType.LIVE,
+ providerId = currentProviderId,
+ title = channel.name,
+ streamUrl = channel.streamUrl,
+ lastWatchedAt = System.currentTimeMillis()
+ )
+ )
+ }
+ }
+
+ private fun classifyPlaybackError(error: PlayerError): PlayerRecoveryType = when (error) {
+ is PlayerError.NetworkError -> {
+ if (error.message.contains("timeout", ignoreCase = true)) {
+ PlayerRecoveryType.BUFFER_TIMEOUT
+ } else {
+ PlayerRecoveryType.NETWORK
+ }
+ }
+ is PlayerError.SourceError -> PlayerRecoveryType.SOURCE
+ is PlayerError.DecoderError -> PlayerRecoveryType.DECODER
+ is PlayerError.UnknownError -> {
+ if (error.message.contains("timeout", ignoreCase = true)) {
+ PlayerRecoveryType.BUFFER_TIMEOUT
+ } else {
+ PlayerRecoveryType.UNKNOWN
+ }
+ }
+ }
+
+ private fun resolvePlaybackErrorMessage(error: PlayerError): String = when (classifyPlaybackError(error)) {
+ PlayerRecoveryType.NETWORK -> "The stream stopped responding. Check the network or try another source."
+ PlayerRecoveryType.SOURCE -> "This stream is unavailable from the provider right now."
+ PlayerRecoveryType.DECODER -> "Playback failed in the current decoder path."
+ PlayerRecoveryType.BUFFER_TIMEOUT -> "Playback stalled for too long on this stream."
+ PlayerRecoveryType.CATCH_UP -> "Replay is unavailable for the selected program."
+ PlayerRecoveryType.UNKNOWN -> error.message.ifBlank { "Playback failed for an unknown reason." }
+ }
+
+ private fun buildRecoveryActions(recoveryType: PlayerRecoveryType): List<PlayerNoticeAction> = buildList {
+ add(PlayerNoticeAction.RETRY)
+ if (hasAlternateStream()) {
+ add(PlayerNoticeAction.ALTERNATE_STREAM)
+ }
+ if (hasLastChannel()) {
+ add(PlayerNoticeAction.LAST_CHANNEL)
+ }
+ if (recoveryType == PlayerRecoveryType.CATCH_UP && currentContentType == ContentType.LIVE) {
+ add(PlayerNoticeAction.OPEN_GUIDE)
+ }
+ }
+
+ private fun markStreamFailure(streamUrl: String) {
+ if (streamUrl.isBlank()) return
+ failedStreamsThisSession[streamUrl] = (failedStreamsThisSession[streamUrl] ?: 0) + 1
+ }
+
+ private fun updateDecoderMode(mode: DecoderMode) {
+ _playerDiagnostics.update { it.copy(decoderMode = mode) }
+ }
+
+ private fun updateStreamClass(label: String) {
+ currentStreamClassLabel = label
+ _playerDiagnostics.update { it.copy(streamClassLabel = label) }
+ }
+
+ private fun updateChannelDiagnostics(channel: com.streamvault.domain.model.Channel) {
+ val archiveLabel = when {
+ channel.catchUpSupported && channel.catchUpSource.isNullOrBlank() -> "Provider advertises catch-up, but replay metadata is incomplete."
+ channel.catchUpSupported -> "Catch-up supported (${channel.catchUpDays} days)"
+ else -> "No archive support advertised"
+ }
+ val hints = buildList {
+ if (channel.errorCount > 0) {
+ add("This channel has failed ${channel.errorCount} time(s) recently.")
+ }
+ if (channel.alternativeStreams.isNotEmpty()) {
+ add("${channel.alternativeStreams.size} alternate stream path(s) available.")
+ }
+ if (channel.catchUpSupported && channel.catchUpSource.isNullOrBlank()) {
+ add("Replay may fail because this provider did not expose a catch-up template.")
+ }
+ }
+ _playerDiagnostics.update {
+ it.copy(
+ alternativeStreamCount = channel.alternativeStreams.size,
+ channelErrorCount = channel.errorCount,
+ archiveSupportLabel = archiveLabel,
+ troubleshootingHints = hints.take(4)
+ )
+ }
+ }
+
+ private fun setLastFailureReason(message: String?) {
+ _playerDiagnostics.update { it.copy(lastFailureReason = message?.takeIf { reason -> reason.isNotBlank() }) }
+ }
+
+ private fun appendRecoveryAction(action: String) {
+ if (action.isBlank()) return
+ _playerDiagnostics.update { state ->
+ state.copy(recentRecoveryActions = (listOf(action) + state.recentRecoveryActions).distinct().take(5))
+ }
+ }
+
+ fun hasAlternateStream(): Boolean {
+ val channel = _currentChannel.value ?: return false
+ return channel.alternativeStreams.any { altUrl ->
+ altUrl != currentStreamUrl &&
+ altUrl !in triedAlternativeStreams &&
+ (failedStreamsThisSession[altUrl] ?: 0) == 0
+ }
+ }
+
+ fun tryAlternateStream(): Boolean {
+ val channel = _currentChannel.value ?: return false
+ return tryAlternateStreamInternal(channel)
+ }
+
+ private fun tryAlternateStreamInternal(channel: com.streamvault.domain.model.Channel): Boolean {
+ val nextStream = channel.alternativeStreams.firstOrNull { altUrl ->
+ altUrl != currentStreamUrl &&
+ altUrl !in triedAlternativeStreams &&
+ (failedStreamsThisSession[altUrl] ?: 0) == 0
+ } ?: channel.alternativeStreams.firstOrNull { altUrl ->
+ altUrl != currentStreamUrl && altUrl !in triedAlternativeStreams
+ } ?: return false
+
+ triedAlternativeStreams.add(nextStream)
+ currentStreamUrl = nextStream
+ updateStreamClass("Alternate")
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = nextStream,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ playerEngine.prepare(streamInfo)
+ playerEngine.play()
+ return true
+ }
+
private fun scheduleZapBufferWatchdog(targetIndex: Int) {
zapBufferWatchdogJob?.cancel()
zapBufferWatchdogJob = viewModelScope.launch {
@@ -682,17 +1123,31 @@ class PlayerViewModel @Inject constructor(
val state = playerEngine.playbackState.value
val stalled = state == PlaybackState.BUFFERING || state == PlaybackState.ERROR
if (stillOnTarget && stalled) {
- fallbackToPreviousChannel("Channel timed out in buffering state")
+ markStreamFailure(currentStreamUrl)
+ setLastFailureReason("Channel timed out in buffering state")
+ appendRecoveryAction("Buffer watchdog triggered")
+ val recovered = fallbackToPreviousChannel("Channel timed out in buffering state")
+ showPlayerNotice(
+ message = if (recovered) {
+ "That channel stalled too long. Returned to the last channel."
+ } else {
+ "That channel stalled too long. Try another source or open the guide."
+ },
+ recoveryType = PlayerRecoveryType.BUFFER_TIMEOUT,
+ actions = buildRecoveryActions(PlayerRecoveryType.BUFFER_TIMEOUT)
+ )
}
}
}
- private fun fallbackToPreviousChannel(reason: String) {
+ private fun fallbackToPreviousChannel(reason: String): Boolean {
val fallbackIndex = previousChannelIndex
if (fallbackIndex in channelList.indices && fallbackIndex != currentChannelIndex) {
android.util.Log.w("PlayerVM", "Falling back to previous channel: $reason")
changeChannel(fallbackIndex)
+ return true
}
+ return false
}
private fun scheduleNumericChannelCommit() {
@@ -758,12 +1213,23 @@ class PlayerViewModel @Inject constructor(
val streamId = _currentChannel.value?.id ?: 0L
val providerId = currentProviderId
- if (providerId == -1L || streamId == 0L) return@launch
+ if (providerId == -1L || streamId == 0L) {
+ setLastFailureReason("Catch-up playback needs a valid live channel context.")
+ showPlayerNotice(
+ message = "Catch-up playback needs a valid live channel context.",
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
+ )
+ return@launch
+ }
val catchUpUrl = providerRepository.buildCatchUpUrl(providerId, streamId, start, end)
if (catchUpUrl != null) {
// Update metadata for player
currentTitle = "${_currentChannel.value?.name ?: ""}: ${program.title}"
+ currentStreamUrl = catchUpUrl
+ updateStreamClass("Catch-up")
+ appendRecoveryAction("Started program replay")
val streamInfo = com.streamvault.domain.model.StreamInfo(
url = catchUpUrl,
@@ -772,6 +1238,147 @@ class PlayerViewModel @Inject constructor(
playerEngine.prepare(streamInfo)
playerEngine.play()
_showControls.value = true
+ } else {
+ val reason = resolveCatchUpFailureMessage(_currentChannel.value, archiveRequested = true, programHasArchive = program.hasArchive)
+ setLastFailureReason(reason)
+ showPlayerNotice(
+ message = reason,
+ recoveryType = PlayerRecoveryType.CATCH_UP,
+ actions = buildRecoveryActions(PlayerRecoveryType.CATCH_UP)
+ )
+ }
+ }
+ }
+
+ private fun resolveCatchUpFailureMessage(
+ channel: com.streamvault.domain.model.Channel?,
+ archiveRequested: Boolean,
+ programHasArchive: Boolean
+ ): String {
+ if (!archiveRequested || channel == null) {
+ return "Catch-up playback needs a valid live channel context."
+ }
+ return when {
+ !channel.catchUpSupported && !programHasArchive ->
+ "This channel does not advertise archive support on the current provider."
+ channel.catchUpSupported && channel.catchUpSource.isNullOrBlank() ->
+ "The provider marks this channel as catch-up capable, but no replay template was supplied."
+ channel.streamId <= 0L ->
+ "The provider did not expose a replay stream identifier for this channel."
+ else ->
+ "The provider did not return a replay stream for the selected program."
+ }
+ }
+
+ fun startManualRecording() {
+ val channel = _currentChannel.value
+ if (currentContentType != ContentType.LIVE || channel == null || currentProviderId <= 0) {
+ showPlayerNotice(message = "Recording needs a valid live channel context.")
+ return
+ }
+ viewModelScope.launch {
+ val now = System.currentTimeMillis()
+ val result = recordingManager.startManualRecording(
+ RecordingRequest(
+ providerId = currentProviderId,
+ channelId = channel.id,
+ channelName = channel.name,
+ streamUrl = currentStreamUrl,
+ scheduledStartMs = now,
+ scheduledEndMs = _currentProgram.value?.endTime ?: (now + 30 * 60_000L),
+ programTitle = _currentProgram.value?.title
+ )
+ )
+ if (result is com.streamvault.domain.model.Result.Error) {
+ showPlayerNotice(message = result.message, recoveryType = PlayerRecoveryType.SOURCE)
+ } else {
+ showPlayerNotice(message = "Recording started for ${channel.name}.")
+ }
+ }
+ }
+
+ fun scheduleRecording() {
+ val channel = _currentChannel.value
+ val targetProgram = _nextProgram.value ?: _currentProgram.value
+ if (currentContentType != ContentType.LIVE || channel == null || currentProviderId <= 0 || targetProgram == null) {
+ showPlayerNotice(message = "Recording needs guide timing for the current live channel.")
+ return
+ }
+ viewModelScope.launch {
+ val result = recordingManager.scheduleRecording(
+ RecordingRequest(
+ providerId = currentProviderId,
+ channelId = channel.id,
+ channelName = channel.name,
+ streamUrl = currentStreamUrl,
+ scheduledStartMs = maxOf(System.currentTimeMillis(), targetProgram.startTime),
+ scheduledEndMs = targetProgram.endTime,
+ programTitle = targetProgram.title
+ )
+ )
+ if (result is com.streamvault.domain.model.Result.Error) {
+ showPlayerNotice(message = result.message, recoveryType = PlayerRecoveryType.SOURCE)
+ } else {
+ showPlayerNotice(message = "Recording scheduled for ${targetProgram.title}.")
+ }
+ }
+ }
+
+ fun stopCurrentRecording() {
+ val recording = _currentChannelRecording.value ?: return
+ viewModelScope.launch {
+ val result = recordingManager.stopRecording(recording.id)
+ if (result is com.streamvault.domain.model.Result.Error) {
+ showPlayerNotice(message = result.message)
+ } else {
+ showPlayerNotice(message = "Recording stopped.")
+ }
+ }
+ }
+
+ fun dismissPlayerNotice() {
+ playerNoticeHideJob?.cancel()
+ _playerNotice.value = null
+ }
+
+ fun runPlayerNoticeAction(action: PlayerNoticeAction) {
+ when (action) {
+ PlayerNoticeAction.RETRY -> {
+ appendRecoveryAction("Manual retry")
+ retryStream(currentStreamUrl, _currentChannel.value?.epgChannelId)
+ }
+ PlayerNoticeAction.LAST_CHANNEL -> {
+ appendRecoveryAction("Returned to last channel")
+ zapToLastChannel()
+ }
+ PlayerNoticeAction.ALTERNATE_STREAM -> {
+ appendRecoveryAction("Manual alternate stream")
+ tryAlternateStream()
+ }
+ PlayerNoticeAction.OPEN_GUIDE -> {
+ appendRecoveryAction("Opened guide from recovery")
+ openEpgOverlay()
+ }
+ }
+ dismissPlayerNotice()
+ }
+
+ private fun showPlayerNotice(
+ message: String,
+ recoveryType: PlayerRecoveryType = PlayerRecoveryType.UNKNOWN,
+ actions: List<PlayerNoticeAction> = emptyList(),
+ durationMs: Long = 3600L
+ ) {
+ playerNoticeHideJob?.cancel()
+ _playerNotice.value = PlayerNoticeState(
+ message = message,
+ recoveryType = recoveryType,
+ actions = actions.distinct()
+ )
+ playerNoticeHideJob = viewModelScope.launch {
+ delay(durationMs)
+ if (_playerNotice.value?.message == message) {
+ _playerNotice.value = null
}
}
}
@@ -820,6 +1427,7 @@ class PlayerViewModel @Inject constructor(
channelInfoHideJob?.cancel()
numericInputCommitJob?.cancel()
numericInputFeedbackJob?.cancel()
+ playerNoticeHideJob?.cancel()
epgJob?.cancel()
playlistJob?.cancel()
controlsHideJob?.cancel()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
index 71aeca80..583ce69a 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
@@ -12,6 +12,7 @@ import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
+import androidx.compose.material3.TextButton
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
@@ -33,6 +34,7 @@ import com.streamvault.app.ui.components.SearchInput
import com.streamvault.app.ui.components.ChannelCard
import com.streamvault.app.ui.components.MovieCard
import com.streamvault.app.ui.components.SeriesCard
+import com.streamvault.app.ui.components.TvEmptyState
import com.streamvault.app.ui.theme.*
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Movie
@@ -59,6 +61,7 @@ class SearchViewModel @Inject constructor(
) : ViewModel() {
private companion object {
const val MAX_RESULTS_PER_SECTION = 120
+ const val MAX_RECENT_QUERIES = 6
}
private val _query = MutableStateFlow("")
@@ -66,6 +69,8 @@ class SearchViewModel @Inject constructor(
private val _selectedTab = MutableStateFlow(SearchTab.ALL)
val selectedTab: StateFlow<SearchTab> = _selectedTab.asStateFlow()
+ private val _recentQueries = MutableStateFlow<List<String>>(emptyList())
+ val recentQueries: StateFlow<List<String>> = _recentQueries.asStateFlow()
private val _parentalControlLevel = MutableStateFlow(0)
@@ -92,7 +97,13 @@ class SearchViewModel @Inject constructor(
val level = params.level
if (provider == null || query.length < 2) {
- flowOf(SearchUiState(parentalControlLevel = level))
+ flowOf(
+ SearchUiState(
+ parentalControlLevel = level,
+ hasActiveProvider = provider != null,
+ queryLength = query.length
+ )
+ )
} else {
val providerId = provider.id
combine(
@@ -109,7 +120,9 @@ class SearchViewModel @Inject constructor(
series = series.take(MAX_RESULTS_PER_SECTION),
isLoading = false,
hasSearched = true,
- parentalControlLevel = level
+ parentalControlLevel = level,
+ hasActiveProvider = true,
+ queryLength = query.length
)
}
}
@@ -119,6 +132,26 @@ class SearchViewModel @Inject constructor(
_query.value = newQuery
}
+ fun onSearchSubmitted() {
+ val normalizedQuery = _query.value.trim()
+ if (normalizedQuery.length < 2) return
+
+ _query.value = normalizedQuery
+ _recentQueries.update { existing ->
+ (listOf(normalizedQuery) + existing.filterNot { it.equals(normalizedQuery, ignoreCase = true) })
+ .take(MAX_RECENT_QUERIES)
+ }
+ }
+
+ fun onRecentQuerySelected(query: String) {
+ _query.value = query
+ onSearchSubmitted()
+ }
+
+ fun clearRecentQueries() {
+ _recentQueries.value = emptyList()
+ }
+
fun onTabSelected(tab: SearchTab) {
_selectedTab.value = tab
}
@@ -148,9 +181,12 @@ data class SearchUiState(
val series: List<Series> = emptyList(),
val isLoading: Boolean = false,
val hasSearched: Boolean = false,
- val parentalControlLevel: Int = 0
+ val parentalControlLevel: Int = 0,
+ val hasActiveProvider: Boolean = false,
+ val queryLength: Int = 0
) {
val isEmpty: Boolean get() = hasSearched && channels.isEmpty() && movies.isEmpty() && series.isEmpty()
+ val totalResults: Int get() = channels.size + movies.size + series.size
}
@OptIn(ExperimentalTvMaterial3Api::class)
@@ -163,6 +199,7 @@ fun SearchScreen(
) {
val query by viewModel.query.collectAsState()
val selectedTab by viewModel.selectedTab.collectAsState()
+ val recentQueries by viewModel.recentQueries.collectAsState()
val uiState by viewModel.uiState.collectAsState()
val focusManager = LocalFocusManager.current
val searchFocusRequester = remember { FocusRequester() }
@@ -174,6 +211,16 @@ fun SearchScreen(
var pendingSeries by remember { mutableStateOf<Series?>(null) }
val scope = rememberCoroutineScope()
+ LaunchedEffect(Unit) {
+ runCatching { searchFocusRequester.requestFocus() }
+ }
+
+ LaunchedEffect(showPinDialog) {
+ if (!showPinDialog) {
+ runCatching { searchFocusRequester.requestFocus() }
+ }
+ }
+
if (showPinDialog) {
com.streamvault.app.ui.components.dialogs.PinDialog(
onDismissRequest = {
@@ -220,7 +267,10 @@ fun SearchScreen(
onValueChange = { viewModel.onQueryChange(it) },
placeholder = stringResource(R.string.search_hint),
focusRequester = searchFocusRequester,
- onSearch = { focusManager.clearFocus() },
+ onSearch = {
+ viewModel.onSearchSubmitted()
+ focusManager.clearFocus()
+ },
modifier = Modifier.padding(bottom = 0.dp)
)
@@ -240,104 +290,164 @@ fun SearchScreen(
}
}
}
- }
- // Right Side: Results
- Box(modifier = Modifier.weight(2.5f).fillMaxHeight()) {
- if (uiState.isEmpty) {
- Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
- Text(
- text = if (query.length < 2) stringResource(R.string.search_type_to_search) else stringResource(R.string.search_no_results, query),
- style = MaterialTheme.typography.bodyLarge,
- color = OnSurfaceDim
- )
- }
- } else {
- LazyVerticalGrid(
- columns = GridCells.Adaptive(140.dp),
- verticalArrangement = Arrangement.spacedBy(16.dp),
- horizontalArrangement = Arrangement.spacedBy(16.dp),
- contentPadding = PaddingValues(bottom = 24.dp)
- ) {
- // Channels
- if (uiState.channels.isNotEmpty()) {
- if (selectedTab == SearchTab.ALL) {
- item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
- SectionHeader(stringResource(R.string.search_live_tv))
- }
+ if (recentQueries.isNotEmpty()) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = stringResource(R.string.search_recent_title),
+ style = MaterialTheme.typography.titleSmall,
+ color = OnSurface
+ )
+ TextButton(onClick = { viewModel.clearRecentQueries() }) {
+ Text(stringResource(R.string.search_clear_history))
}
- items(uiState.channels) { channel ->
- val isLocked = (channel.isAdult || channel.isUserProtected) && uiState.parentalControlLevel == 1
- ChannelCard(
- channel = channel,
- isLocked = isLocked,
+ }
+
+ androidx.compose.foundation.lazy.LazyRow(
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ items(recentQueries) { recentQuery ->
+ FilterChip(
+ selected = recentQuery.equals(query, ignoreCase = true),
onClick = {
- if (isLocked) {
- pendingChannel = channel
- showPinDialog = true
- } else {
- onChannelClick(channel)
- }
+ viewModel.onRecentQuerySelected(recentQuery)
+ focusManager.clearFocus()
},
- modifier = Modifier.aspectRatio(16f/9f)
- )
+ colors = FilterChipDefaults.colors(
+ selectedContainerColor = Primary,
+ selectedContentColor = Color.White
+ )
+ ) {
+ Text(recentQuery)
+ }
}
}
+ }
+ }
+
+ // Right Side: Results
+ Box(modifier = Modifier.weight(2.5f).fillMaxHeight()) {
+ when {
+ !uiState.hasActiveProvider -> {
+ SearchMessageState(
+ title = stringResource(R.string.search_no_provider_title),
+ subtitle = stringResource(R.string.search_no_provider_subtitle)
+ )
+ }
+
+ uiState.queryLength < 2 -> {
+ SearchMessageState(
+ title = stringResource(R.string.search_ready_title),
+ subtitle = stringResource(R.string.search_type_to_search)
+ )
+ }
+
+ uiState.isEmpty -> {
+ SearchMessageState(
+ title = stringResource(R.string.search_no_results_title),
+ subtitle = stringResource(R.string.search_no_results, query)
+ )
+ }
- // Movies
- if (uiState.movies.isNotEmpty()) {
- if (selectedTab == SearchTab.ALL) {
- item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
- SectionHeader(stringResource(R.string.search_movies))
+ else -> {
+ LazyVerticalGrid(
+ columns = GridCells.Adaptive(140.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp),
+ horizontalArrangement = Arrangement.spacedBy(16.dp),
+ contentPadding = PaddingValues(bottom = 24.dp)
+ ) {
+ item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
+ SearchResultsSummaryRow(
+ uiState = uiState,
+ selectedTab = selectedTab,
+ onTabSelected = viewModel::onTabSelected
+ )
}
- }
- items(uiState.movies) { movie ->
- val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
- MovieCard(
- movie = movie,
- isLocked = isLocked,
- onClick = {
- if (isLocked) {
- pendingMovie = movie
- showPinDialog = true
- } else {
- onMovieClick(movie)
+
+ // Channels
+ if (uiState.channels.isNotEmpty()) {
+ if (selectedTab == SearchTab.ALL) {
+ item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
+ SectionHeader(stringResource(R.string.search_live_tv))
}
- },
- modifier = Modifier.aspectRatio(2f/3f)
- )
- }
- }
+ }
+ items(uiState.channels) { channel ->
+ val isLocked = (channel.isAdult || channel.isUserProtected) && uiState.parentalControlLevel == 1
+ ChannelCard(
+ channel = channel,
+ isLocked = isLocked,
+ onClick = {
+ if (isLocked) {
+ pendingChannel = channel
+ showPinDialog = true
+ } else {
+ onChannelClick(channel)
+ }
+ },
+ modifier = Modifier.aspectRatio(16f/9f)
+ )
+ }
+ }
- // Series
- if (uiState.series.isNotEmpty()) {
- if (selectedTab == SearchTab.ALL) {
- item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
- SectionHeader(stringResource(R.string.search_series))
+ // Movies
+ if (uiState.movies.isNotEmpty()) {
+ if (selectedTab == SearchTab.ALL) {
+ item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
+ SectionHeader(stringResource(R.string.search_movies))
+ }
+ }
+ items(uiState.movies) { movie ->
+ val isLocked = (movie.isAdult || movie.isUserProtected) && uiState.parentalControlLevel == 1
+ MovieCard(
+ movie = movie,
+ isLocked = isLocked,
+ onClick = {
+ if (isLocked) {
+ pendingMovie = movie
+ showPinDialog = true
+ } else {
+ onMovieClick(movie)
+ }
+ },
+ modifier = Modifier.aspectRatio(2f/3f)
+ )
+ }
}
- }
- items(uiState.series) { series ->
- val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
- SeriesCard(
- series = series,
- isLocked = isLocked,
- onClick = {
- if (isLocked) {
- pendingSeries = series
- showPinDialog = true
- } else {
- onSeriesClick(series)
+
+ // Series
+ if (uiState.series.isNotEmpty()) {
+ if (selectedTab == SearchTab.ALL) {
+ item(span = { androidx.compose.foundation.lazy.grid.GridItemSpan(maxLineSpan) }) {
+ SectionHeader(stringResource(R.string.search_series))
}
- },
- modifier = Modifier.aspectRatio(2f/3f)
- )
+ }
+ items(uiState.series) { series ->
+ val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ SeriesCard(
+ series = series,
+ isLocked = isLocked,
+ onClick = {
+ if (isLocked) {
+ pendingSeries = series
+ showPinDialog = true
+ } else {
+ onSeriesClick(series)
+ }
+ },
+ modifier = Modifier.aspectRatio(2f/3f)
+ )
+ }
+ }
}
}
}
}
}
}
-}
@Composable
@@ -349,3 +459,61 @@ fun SectionHeader(title: String) {
modifier = Modifier.padding(vertical = 8.dp)
)
}
+
+@OptIn(ExperimentalTvMaterial3Api::class)
+@Composable
+private fun SearchResultsSummaryRow(
+ uiState: SearchUiState,
+ selectedTab: SearchTab,
+ onTabSelected: (SearchTab) -> Unit
+) {
+ val summaryChips = listOf(
+ SearchSummaryChip(SearchTab.ALL, stringResource(R.string.search_all), uiState.totalResults),
+ SearchSummaryChip(SearchTab.LIVE, stringResource(R.string.search_live_tv), uiState.channels.size),
+ SearchSummaryChip(SearchTab.MOVIES, stringResource(R.string.search_movies), uiState.movies.size),
+ SearchSummaryChip(SearchTab.SERIES, stringResource(R.string.search_series), uiState.series.size)
+ )
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.search_results_title, uiState.totalResults),
+ style = MaterialTheme.typography.titleMedium,
+ color = OnSurface
+ )
+ androidx.compose.foundation.lazy.LazyRow(
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ items(summaryChips) { chip ->
+ FilterChip(
+ selected = chip.tab == selectedTab,
+ onClick = { onTabSelected(chip.tab) },
+ colors = FilterChipDefaults.colors(
+ selectedContainerColor = Primary,
+ selectedContentColor = Color.White
+ )
+ ) {
+ Text(stringResource(R.string.search_results_count, chip.label, chip.count))
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun SearchMessageState(
+ title: String,
+ subtitle: String
+) {
+ TvEmptyState(
+ title = title,
+ subtitle = subtitle
+ )
+}
+
+private data class SearchSummaryChip(
+ val tab: SearchTab,
+ val label: String,
+ val count: Int
+)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
index 84767397..c785946c 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
@@ -36,6 +36,11 @@ import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import com.streamvault.app.navigation.Routes
import com.streamvault.app.ui.components.CategoryRow
import com.streamvault.app.ui.components.ContinueWatchingRow
+import com.streamvault.app.ui.components.SavedCategoryContextCard
+import com.streamvault.app.ui.components.SavedCategoryShortcut
+import com.streamvault.app.ui.components.SavedCategoryShortcutsRow
+import com.streamvault.app.ui.components.SelectionChip
+import com.streamvault.app.ui.components.SelectionChipRow
import com.streamvault.app.ui.components.SeriesCard
import com.streamvault.app.ui.components.SkeletonRow
import com.streamvault.app.ui.components.TopNavBar
@@ -44,8 +49,12 @@ import kotlinx.coroutines.launch
import androidx.compose.ui.res.stringResource
import com.streamvault.app.R
import androidx.compose.foundation.border
+import androidx.compose.material3.SnackbarHost
+import androidx.compose.material3.SnackbarHostState
+import androidx.compose.runtime.saveable.rememberSaveable
import com.streamvault.app.ui.components.ReorderTopBar
import com.streamvault.app.ui.components.dialogs.DeleteGroupDialog
+import com.streamvault.app.ui.components.dialogs.RenameGroupDialog
@OptIn(ExperimentalFoundationApi::class)
@Composable
@@ -56,12 +65,23 @@ fun SeriesScreen(
viewModel: SeriesViewModel = hiltViewModel()
) {
val uiState by viewModel.uiState.collectAsState()
+ val snackbarHostState = remember { SnackbarHostState() }
var showPinDialog by remember { mutableStateOf(false) }
var pinError by remember { mutableStateOf<String?>(null) }
var pendingSeriesId by remember { mutableStateOf<Long?>(null) }
+ var selectedLibraryLens by rememberSaveable { mutableStateOf(SeriesLibraryLens.FAVORITES.name) }
+ var selectedFacet by rememberSaveable { mutableStateOf(SeriesLibraryFacet.ALL.name) }
+ var selectedSort by rememberSaveable { mutableStateOf(SeriesLibrarySort.LIBRARY.name) }
val scope = rememberCoroutineScope()
val context = androidx.compose.ui.platform.LocalContext.current
+ LaunchedEffect(uiState.userMessage) {
+ uiState.userMessage?.let { message ->
+ snackbarHostState.showSnackbar(message)
+ viewModel.userMessageShown()
+ }
+ }
+
if (showPinDialog) {
com.streamvault.app.ui.components.dialogs.PinDialog(
onDismissRequest = {
@@ -85,7 +105,8 @@ fun SeriesScreen(
)
}
- Column(modifier = Modifier.fillMaxSize()) {
+ Box(modifier = Modifier.fillMaxSize()) {
+ Column(modifier = Modifier.fillMaxSize()) {
if (uiState.isReorderMode && uiState.reorderCategory != null) {
ReorderTopBar(
categoryName = uiState.reorderCategory!!.name,
@@ -119,6 +140,43 @@ fun SeriesScreen(
Row(modifier = Modifier.fillMaxSize()) {
// Category sidebar
val categorySearchFocusRequester = remember { FocusRequester() }
+ val categoryFocusRequesters = remember { mutableMapOf<String, FocusRequester>() }
+ var lastFocusedCategoryName by rememberSaveable { mutableStateOf<String?>(null) }
+ var shouldRestoreCategoryFocus by remember { mutableStateOf(false) }
+ var preferCategoryRestore by rememberSaveable { mutableStateOf(false) }
+ val heroSeries = remember(uiState.categoryNames, uiState.seriesByCategory) {
+ uiState.categoryNames
+ .asSequence()
+ .mapNotNull { categoryName -> uiState.seriesByCategory[categoryName]?.firstOrNull() }
+ .firstOrNull()
+ }
+
+ LaunchedEffect(
+ uiState.selectedCategoryForOptions,
+ uiState.showRenameGroupDialog,
+ uiState.showDeleteGroupDialog
+ ) {
+ val modalClosed =
+ uiState.selectedCategoryForOptions == null &&
+ !uiState.showRenameGroupDialog &&
+ !uiState.showDeleteGroupDialog
+ if (modalClosed && preferCategoryRestore && lastFocusedCategoryName != null) {
+ shouldRestoreCategoryFocus = true
+ preferCategoryRestore = false
+ }
+ }
+
+ LaunchedEffect(shouldRestoreCategoryFocus, uiState.categoryNames) {
+ if (!shouldRestoreCategoryFocus) return@LaunchedEffect
+ kotlinx.coroutines.delay(80)
+ val categoryName = lastFocusedCategoryName
+ if (categoryName != null) {
+ runCatching {
+ categoryFocusRequesters[categoryName]?.requestFocus()
+ }
+ }
+ shouldRestoreCategoryFocus = false
+ }
Column(
modifier = Modifier
@@ -130,7 +188,7 @@ fun SeriesScreen(
// Sticky Header
Column(modifier = Modifier.padding(horizontal = 16.dp)) {
Text(
- text = "Categories",
+ text = stringResource(R.string.series_categories_title),
style = MaterialTheme.typography.titleMedium,
color = Primary,
modifier = Modifier.padding(vertical = 8.dp)
@@ -138,7 +196,7 @@ fun SeriesScreen(
SearchInput(
value = uiState.searchQuery,
onValueChange = { viewModel.setSearchQuery(it) },
- placeholder = "Search series...",
+ placeholder = stringResource(R.string.series_search_placeholder),
focusRequester = categorySearchFocusRequester,
modifier = Modifier.padding(bottom = 8.dp)
)
@@ -149,7 +207,7 @@ fun SeriesScreen(
contentPadding = PaddingValues(bottom = 8.dp)
) {
item {
- val isAllSelected = uiState.selectedCategory == null
+ val isAllSelected = uiState.selectedCategory == null || uiState.selectedCategory == uiState.fullLibraryCategoryName
Surface(
onClick = { viewModel.selectCategory(null) },
shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(8.dp)),
@@ -174,13 +232,13 @@ fun SeriesScreen(
verticalAlignment = Alignment.CenterVertically
) {
Text(
- text = "All Categories",
+ text = stringResource(R.string.series_all_categories),
style = MaterialTheme.typography.bodyMedium,
color = if (isAllSelected) Primary else OnSurface,
modifier = Modifier.weight(1f)
)
Text(
- text = "${uiState.seriesByCategory.values.sumOf { it.size }}",
+ text = "${uiState.libraryCount}",
style = MaterialTheme.typography.labelSmall,
color = OnSurfaceDim
)
@@ -190,10 +248,13 @@ fun SeriesScreen(
items(uiState.categoryNames.size) { index ->
val categoryName = uiState.categoryNames[index]
val isSelected = uiState.selectedCategory == categoryName
- val count = uiState.seriesByCategory[categoryName]?.size ?: 0
+ val count = uiState.categoryCounts[categoryName] ?: 0
Surface(
onClick = { viewModel.selectCategory(categoryName) },
- onLongClick = { viewModel.showCategoryOptions(categoryName) },
+ onLongClick = {
+ preferCategoryRestore = true
+ viewModel.showCategoryOptions(categoryName)
+ },
shape = ClickableSurfaceDefaults.shape(androidx.compose.foundation.shape.RoundedCornerShape(8.dp)),
colors = ClickableSurfaceDefaults.colors(
containerColor = if (isSelected) Primary.copy(alpha = 0.15f) else Color.Transparent,
@@ -202,6 +263,12 @@ fun SeriesScreen(
modifier = Modifier
.fillMaxWidth()
.padding(horizontal = 8.dp, vertical = 2.dp)
+ .focusRequester(categoryFocusRequesters.getOrPut(categoryName) { FocusRequester() })
+ .onFocusChanged { focusState ->
+ if (focusState.isFocused) {
+ lastFocusedCategoryName = categoryName
+ }
+ }
.onPreviewKeyEvent { event ->
if (event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_DPAD_LEFT) {
@@ -234,8 +301,58 @@ fun SeriesScreen(
}
}
+ val savedShortcuts = remember(
+ uiState.favoriteCategoryName,
+ uiState.categories,
+ uiState.seriesByCategory
+ ) {
+ buildList {
+ val favoriteCount = uiState.categoryCounts[uiState.favoriteCategoryName] ?: 0
+ if (favoriteCount > 0) {
+ add(
+ SavedCategoryShortcut(
+ name = uiState.favoriteCategoryName,
+ count = favoriteCount
+ )
+ )
+ }
+ uiState.categories
+ .asSequence()
+ .filterNot { it.name == uiState.favoriteCategoryName }
+ .map { category ->
+ SavedCategoryShortcut(
+ name = category.name,
+ count = uiState.categoryCounts[category.name] ?: 0
+ )
+ }
+ .filter { it.count > 0 }
+ .sortedByDescending { it.count }
+ .forEach(::add)
+ }
+ }
+ val selectedSavedCategory = remember(
+ uiState.selectedCategory,
+ uiState.favoriteCategoryName,
+ uiState.categories
+ ) {
+ when (uiState.selectedCategory) {
+ null -> null
+ uiState.favoriteCategoryName -> com.streamvault.domain.model.Category(
+ id = -999L,
+ name = uiState.favoriteCategoryName,
+ type = com.streamvault.domain.model.ContentType.SERIES,
+ isVirtual = true
+ )
+ else -> uiState.categories.firstOrNull { it.name == uiState.selectedCategory }
+ }
+ }
+
// Main content
if (uiState.selectedCategory == null) {
+ val activeLibraryLens = remember(selectedLibraryLens, uiState.libraryLensRows) {
+ SeriesLibraryLens.entries.firstOrNull { it.name == selectedLibraryLens && uiState.libraryLensRows.containsKey(it) }
+ ?: uiState.libraryLensRows.keys.firstOrNull()
+ }
// Netflix-style rows (All categories view)
LazyColumn(
modifier = Modifier.fillMaxSize(),
@@ -268,7 +385,6 @@ fun SeriesScreen(
}
}
- val heroSeries = uiState.seriesByCategory.values.flatten().firstOrNull()
if (heroSeries != null) {
item {
SeriesHeroBanner(
@@ -286,6 +402,97 @@ fun SeriesScreen(
}
}
+ item(key = "saved_shortcuts") {
+ SavedCategoryShortcutsRow(
+ title = stringResource(R.string.library_saved_title),
+ subtitle = stringResource(R.string.library_saved_subtitle),
+ emptyHint = stringResource(R.string.series_saved_empty_hint),
+ shortcuts = savedShortcuts,
+ managementHint = stringResource(R.string.library_saved_manage_hint),
+ primaryShortcutLabel = stringResource(R.string.library_browse_all),
+ isPrimaryShortcutSelected = uiState.selectedCategory == null,
+ onPrimaryShortcutClick = { viewModel.selectCategory(null) },
+ selectedShortcutName = uiState.selectedCategory,
+ onShortcutLongClick = viewModel::showCategoryOptions,
+ onShortcutClick = viewModel::selectCategory
+ )
+ }
+
+ if (activeLibraryLens != null) {
+ item(key = "library_lens_chips") {
+ SelectionChipRow(
+ title = stringResource(R.string.library_lens_title),
+ subtitle = stringResource(R.string.series_library_lens_subtitle),
+ chips = uiState.libraryLensRows.keys.map { lens ->
+ SelectionChip(
+ key = lens.name,
+ label = seriesLibraryLensLabel(lens),
+ supportingText = stringResource(
+ R.string.library_saved_items_count,
+ uiState.libraryLensRows[lens]?.size ?: 0
+ )
+ )
+ },
+ selectedKey = activeLibraryLens.name,
+ onChipSelected = { selectedLibraryLens = it },
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ }
+
+ item(key = "library_lens_row") {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Surface(
+ onClick = viewModel::selectFullLibraryBrowse,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.06f),
+ focusedContainerColor = Primary
+ ),
+ modifier = Modifier.padding(horizontal = 16.dp)
+ ) {
+ Column(modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp)) {
+ Text(
+ text = stringResource(R.string.library_full_browse_title_series),
+ style = MaterialTheme.typography.titleSmall,
+ color = Color.White
+ )
+ Spacer(Modifier.height(4.dp))
+ Text(
+ text = stringResource(R.string.library_full_browse_subtitle, uiState.libraryCount),
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.8f)
+ )
+ }
+ }
+
+ CategoryRow(
+ title = seriesLibraryLensLabel(activeLibraryLens),
+ items = uiState.libraryLensRows[activeLibraryLens].orEmpty(),
+ onSeeAll = if (activeLibraryLens == SeriesLibraryLens.FAVORITES) {
+ { viewModel.selectCategory(uiState.favoriteCategoryName) }
+ } else {
+ null
+ }
+ ) { series ->
+ val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
+ SeriesCard(
+ series = series,
+ isLocked = isLocked,
+ onClick = {
+ if (isLocked) {
+ pendingSeriesId = series.id
+ showPinDialog = true
+ } else {
+ onSeriesClick(series.id)
+ }
+ },
+ onLongClick = { viewModel.onShowDialog(series) }
+ )
+ }
+ }
+ }
+ }
+
// Continue Watching row (shown first, only if non-empty)
item(key = "continue_watching") {
ContinueWatchingRow(
@@ -297,7 +504,11 @@ fun SeriesScreen(
items = uiState.seriesByCategory.entries.toList(),
key = { it.key }
) { (categoryName, seriesList) ->
- CategoryRow(title = categoryName, items = seriesList) { series ->
+ CategoryRow(
+ title = categoryName,
+ items = seriesList,
+ onSeeAll = { viewModel.selectCategory(categoryName) }
+ ) { series ->
val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
SeriesCard(
series = series,
@@ -319,8 +530,37 @@ fun SeriesScreen(
}
} else {
// Filtered grid for selected category
- val filteredSeries = uiState.seriesByCategory[uiState.selectedCategory] ?: emptyList()
- val activeSeries = if (uiState.isReorderMode) uiState.filteredSeries else filteredSeries
+ val baseSeries = if (uiState.searchQuery.isBlank()) {
+ uiState.selectedCategoryItems
+ } else {
+ uiState.seriesByCategory[uiState.selectedCategory] ?: emptyList()
+ }
+ val activeSeries = if (uiState.isReorderMode) uiState.filteredSeries else baseSeries
+ val resumeSeriesIds = remember(uiState.continueWatching) {
+ uiState.continueWatching.mapNotNull { history ->
+ history.seriesId ?: history.contentId
+ }.toSet()
+ }
+ val activeFacet = remember(selectedFacet) {
+ SeriesLibraryFacet.entries.firstOrNull { it.name == selectedFacet } ?: SeriesLibraryFacet.ALL
+ }
+ val activeSort = remember(selectedSort) {
+ SeriesLibrarySort.entries.firstOrNull { it.name == selectedSort } ?: SeriesLibrarySort.LIBRARY
+ }
+ val filteredGridSeries = remember(activeSeries, activeFacet, activeSort, resumeSeriesIds, uiState.isReorderMode) {
+ if (uiState.isReorderMode) {
+ activeSeries
+ } else {
+ applySeriesFacetAndSort(
+ items = activeSeries,
+ facet = activeFacet,
+ sort = activeSort,
+ resumeSeriesIds = resumeSeriesIds
+ )
+ }
+ }
+ val showSelectedCategoryControls = !uiState.isReorderMode &&
+ (selectedSavedCategory != null || activeSeries.size > 8)
var draggingSeries by remember { mutableStateOf<com.streamvault.domain.model.Series?>(null) }
@@ -330,41 +570,128 @@ fun SeriesScreen(
}
}
- LazyVerticalGrid(
- columns = GridCells.Adaptive(minSize = 160.dp),
- modifier = Modifier
- .fillMaxSize()
- .onPreviewKeyEvent { event ->
- if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
- if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
- if (draggingSeries != null) {
- draggingSeries = null
- true
- } else {
- viewModel.exitCategoryReorderMode()
- true
- }
- } else false
- } else false
- },
- contentPadding = PaddingValues(16.dp),
- horizontalArrangement = Arrangement.spacedBy(16.dp),
- verticalArrangement = Arrangement.spacedBy(16.dp)
+ Column(
+ modifier = Modifier.fillMaxSize()
) {
- item(span = { GridItemSpan(maxLineSpan) }) {
- Text(
- text = uiState.selectedCategory ?: "",
- style = MaterialTheme.typography.headlineSmall,
- color = Primary,
- fontWeight = androidx.compose.ui.text.font.FontWeight.Bold,
- modifier = Modifier.padding(bottom = 16.dp)
+ if (selectedSavedCategory != null) {
+ SavedCategoryShortcutsRow(
+ title = stringResource(R.string.library_saved_title),
+ subtitle = stringResource(R.string.library_saved_subtitle),
+ emptyHint = stringResource(R.string.series_saved_empty_hint),
+ shortcuts = savedShortcuts,
+ managementHint = stringResource(R.string.library_saved_manage_hint),
+ primaryShortcutLabel = stringResource(R.string.library_browse_all),
+ isPrimaryShortcutSelected = uiState.selectedCategory == null,
+ onPrimaryShortcutClick = { viewModel.selectCategory(null) },
+ selectedShortcutName = uiState.selectedCategory,
+ onShortcutLongClick = viewModel::showCategoryOptions,
+ onShortcutClick = viewModel::selectCategory
+ )
+
+ SavedCategoryContextCard(
+ categoryName = selectedSavedCategory.name,
+ itemCount = uiState.categoryCounts[selectedSavedCategory.name] ?: filteredGridSeries.size,
+ onManageClick = { viewModel.showCategoryOptions(selectedSavedCategory.name) },
+ onBrowseAllClick = { viewModel.selectCategory(null) },
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp)
)
}
-
- gridItems(
- items = activeSeries,
- key = { it.id }
- ) { series ->
+
+ if (showSelectedCategoryControls) {
+ SelectionChipRow(
+ title = stringResource(R.string.library_filter_title),
+ chips = buildSeriesFacetChips(
+ items = activeSeries,
+ resumeSeriesIds = resumeSeriesIds
+ ),
+ selectedKey = activeFacet.name,
+ onChipSelected = { selectedFacet = it },
+ modifier = Modifier.padding(horizontal = 16.dp),
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+
+ SelectionChipRow(
+ title = stringResource(R.string.library_sort_title),
+ chips = SeriesLibrarySort.entries.map { sort ->
+ SelectionChip(
+ key = sort.name,
+ label = when (sort) {
+ SeriesLibrarySort.LIBRARY -> stringResource(R.string.library_sort_library)
+ SeriesLibrarySort.TITLE -> stringResource(R.string.library_sort_az)
+ SeriesLibrarySort.UPDATED -> stringResource(R.string.library_sort_updated)
+ SeriesLibrarySort.RATING -> stringResource(R.string.library_sort_rating)
+ }
+ )
+ },
+ selectedKey = activeSort.name,
+ onChipSelected = { selectedSort = it },
+ modifier = Modifier.padding(horizontal = 16.dp),
+ contentPadding = PaddingValues(horizontal = 0.dp)
+ )
+ }
+
+ LazyVerticalGrid(
+ columns = GridCells.Adaptive(minSize = 160.dp),
+ modifier = Modifier
+ .fillMaxSize()
+ .onPreviewKeyEvent { event ->
+ if (uiState.isReorderMode && event.nativeKeyEvent.action == android.view.KeyEvent.ACTION_DOWN) {
+ if (event.nativeKeyEvent.keyCode == android.view.KeyEvent.KEYCODE_BACK) {
+ if (draggingSeries != null) {
+ draggingSeries = null
+ true
+ } else {
+ viewModel.exitCategoryReorderMode()
+ true
+ }
+ } else false
+ } else false
+ },
+ contentPadding = PaddingValues(16.dp),
+ horizontalArrangement = Arrangement.spacedBy(16.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Column(modifier = Modifier.padding(bottom = 16.dp)) {
+ Text(
+ text = when (uiState.selectedCategory) {
+ uiState.fullLibraryCategoryName -> stringResource(R.string.library_full_browse_title_series)
+ else -> uiState.selectedCategory ?: ""
+ },
+ style = MaterialTheme.typography.headlineSmall,
+ color = Primary,
+ fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
+ )
+ if (!uiState.isReorderMode && uiState.selectedCategoryTotalCount > 0) {
+ Spacer(Modifier.height(6.dp))
+ Text(
+ text = stringResource(
+ R.string.library_loaded_results,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
+ }
+
+ if (filteredGridSeries.isEmpty()) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Text(
+ text = stringResource(R.string.library_filter_empty),
+ style = MaterialTheme.typography.bodyLarge,
+ color = OnSurfaceDim,
+ modifier = Modifier.padding(bottom = 12.dp)
+ )
+ }
+ }
+
+ gridItems(
+ items = filteredGridSeries,
+ key = { it.id }
+ ) { series ->
val isLocked = (series.isAdult || series.isUserProtected) && uiState.parentalControlLevel == 1
val isDraggingThis = draggingSeries == series
@@ -406,11 +733,44 @@ fun SeriesScreen(
} else false
}
)
+ }
+
+ if (!uiState.isReorderMode && uiState.canLoadMoreSelectedCategory) {
+ item(span = { GridItemSpan(maxLineSpan) }) {
+ Surface(
+ onClick = viewModel::loadMoreSelectedCategory,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(10.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.06f),
+ focusedContainerColor = Primary
+ ),
+ modifier = Modifier.padding(top = 8.dp, bottom = 24.dp)
+ ) {
+ Text(
+ text = stringResource(
+ R.string.library_load_more,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White,
+ modifier = Modifier.padding(horizontal = 18.dp, vertical = 14.dp)
+ )
+ }
+ }
+ }
}
}
}
}
}
+ }
+ SnackbarHost(
+ hostState = snackbarHostState,
+ modifier = Modifier
+ .align(Alignment.BottomCenter)
+ .padding(bottom = 16.dp)
+ )
}
if (uiState.showDialog && uiState.selectedSeriesForDialog != null) {
@@ -437,6 +797,32 @@ fun SeriesScreen(
onConfirmDelete = { viewModel.confirmDeleteGroup() }
)
}
+
+ if (uiState.selectedCategoryForOptions != null) {
+ val category = uiState.selectedCategoryForOptions!!
+ com.streamvault.app.ui.components.dialogs.CategoryOptionsDialog(
+ category = category,
+ onDismissRequest = { viewModel.dismissCategoryOptions() },
+ onRename = if (category.isVirtual && category.id != -999L) {
+ { viewModel.requestRenameGroup(category) }
+ } else null,
+ onDelete = if (category.isVirtual && category.id != -999L) {
+ { viewModel.requestDeleteGroup(category) }
+ } else null,
+ onReorderChannels = if (category.isVirtual) {
+ { viewModel.enterCategoryReorderMode(category) }
+ } else null
+ )
+ }
+
+ if (uiState.showRenameGroupDialog && uiState.groupToRename != null) {
+ RenameGroupDialog(
+ initialName = uiState.groupToRename!!.name,
+ errorMessage = uiState.renameGroupError,
+ onDismissRequest = { viewModel.cancelRenameGroup() },
+ onConfirm = { name -> viewModel.confirmRenameGroup(name) }
+ )
+ }
}
@Composable
@@ -522,3 +908,76 @@ fun SeriesHeroBanner(
}
}
}
+
+private enum class SeriesLibraryFacet {
+ ALL,
+ FAVORITES,
+ RESUME,
+ RECENTLY_UPDATED,
+ TOP_RATED
+}
+
+private enum class SeriesLibrarySort {
+ LIBRARY,
+ TITLE,
+ UPDATED,
+ RATING
+}
+
+@Composable
+private fun seriesLibraryLensLabel(lens: SeriesLibraryLens): String =
+ when (lens) {
+ SeriesLibraryLens.FAVORITES -> stringResource(R.string.library_lens_favorites)
+ SeriesLibraryLens.CONTINUE -> stringResource(R.string.library_lens_continue)
+ SeriesLibraryLens.TOP_RATED -> stringResource(R.string.library_lens_top_rated)
+ SeriesLibraryLens.FRESH -> stringResource(R.string.library_lens_fresh_series)
+ }
+
+private fun buildSeriesFacetChips(
+ items: List<com.streamvault.domain.model.Series>,
+ resumeSeriesIds: Set<Long>
+): List<SelectionChip> {
+ val favoriteCount = items.count { it.isFavorite }
+ val resumeCount = items.count { it.id in resumeSeriesIds }
+ val updatedCount = items.count { seriesFreshnessScore(it) > 0L }
+ val topRatedCount = items.count { it.rating > 0f }
+ return listOf(
+ SelectionChip(SeriesLibraryFacet.ALL.name, "All", "${items.size} visible"),
+ SelectionChip(SeriesLibraryFacet.FAVORITES.name, "Favorites", "$favoriteCount saved"),
+ SelectionChip(SeriesLibraryFacet.RESUME.name, "Resume", "$resumeCount in progress"),
+ SelectionChip(SeriesLibraryFacet.RECENTLY_UPDATED.name, "Updated", "$updatedCount tracked"),
+ SelectionChip(SeriesLibraryFacet.TOP_RATED.name, "Top Rated", "$topRatedCount rated")
+ )
+}
+
+private fun applySeriesFacetAndSort(
+ items: List<com.streamvault.domain.model.Series>,
+ facet: SeriesLibraryFacet,
+ sort: SeriesLibrarySort,
+ resumeSeriesIds: Set<Long>
+): List<com.streamvault.domain.model.Series> {
+ val filtered = when (facet) {
+ SeriesLibraryFacet.ALL -> items
+ SeriesLibraryFacet.FAVORITES -> items.filter { it.isFavorite }
+ SeriesLibraryFacet.RESUME -> items.filter { it.id in resumeSeriesIds }
+ SeriesLibraryFacet.RECENTLY_UPDATED -> items.filter { seriesFreshnessScore(it) > 0L }
+ SeriesLibraryFacet.TOP_RATED -> items.filter { it.rating > 0f }
+ }
+
+ return when (sort) {
+ SeriesLibrarySort.LIBRARY -> filtered
+ SeriesLibrarySort.TITLE -> filtered.sortedBy { it.name.lowercase() }
+ SeriesLibrarySort.UPDATED -> filtered.sortedByDescending(::seriesFreshnessScore)
+ SeriesLibrarySort.RATING -> filtered.sortedByDescending { it.rating }
+ }
+}
+
+private fun seriesFreshnessScore(series: com.streamvault.domain.model.Series): Long {
+ return series.lastModified
+ .takeIf { it > 0L }
+ ?: series.releaseDate
+ ?.filter { it.isDigit() }
+ ?.take(8)
+ ?.toLongOrNull()
+ ?: 0L
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
index 0bc05633..0476977f 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
@@ -3,21 +3,45 @@ package com.streamvault.app.ui.screens.series
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.Series
+import com.streamvault.domain.repository.FavoriteRepository
import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.repository.SeriesRepository
+import com.streamvault.domain.usecase.GetCustomCategories
import dagger.hilt.android.lifecycle.HiltViewModel
-import kotlinx.coroutines.flow.*
-import kotlinx.coroutines.launch
import javax.inject.Inject
-import com.streamvault.domain.model.Category
-import com.streamvault.domain.model.ContentType
-import com.streamvault.domain.repository.FavoriteRepository
-import com.streamvault.domain.usecase.GetCustomCategories
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.collectLatest
+import kotlinx.coroutines.flow.combine
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.flow.filterNotNull
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.flow.flatMapLatest
+import kotlinx.coroutines.flow.flow
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+enum class SeriesLibraryLens {
+ FAVORITES,
+ CONTINUE,
+ TOP_RATED,
+ FRESH
+}
@HiltViewModel
+@OptIn(ExperimentalCoroutinesApi::class)
class SeriesViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val seriesRepository: SeriesRepository,
@@ -26,93 +50,257 @@ class SeriesViewModel @Inject constructor(
private val favoriteRepository: FavoriteRepository,
private val getCustomCategories: GetCustomCategories
) : ViewModel() {
+ private companion object {
+ const val UNCATEGORIZED = "Uncategorized"
+ const val FAVORITES_CATEGORY = "\u2605 Favorites"
+ const val FAVORITES_SENTINEL_ID = -999L
+ const val FULL_LIBRARY_CATEGORY = "__full_library__"
+ const val PREVIEW_ROW_LIMIT = 18
+ const val SELECTED_CATEGORY_PAGE_SIZE = 60
+ }
private val _uiState = MutableStateFlow(SeriesUiState())
val uiState: StateFlow<SeriesUiState> = _uiState.asStateFlow()
private val _searchQuery = MutableStateFlow("")
- private val _localSeries = MutableStateFlow<List<Series>>(emptyList())
+ private val _selectedCategoryLoadLimit = MutableStateFlow(SELECTED_CATEGORY_PAGE_SIZE)
init {
viewModelScope.launch {
providerRepository.getActiveProvider()
.filterNotNull()
- .collectLatest { provider ->
- // Series by category
- launch {
- combine(
- seriesRepository.getSeries(provider.id),
- favoriteRepository.getAllFavorites(ContentType.SERIES),
- getCustomCategories(ContentType.SERIES),
- _searchQuery
- ) { seriesList, allFavorites, customCats, query ->
- // 1. Mark global favorites
- val globalFavoriteIds = allFavorites.filter { it.groupId == null }.map { it.contentId }.toSet()
- val enrichedSeries = seriesList.map { it.copy(isFavorite = globalFavoriteIds.contains(it.id)) }
-
- // 2. Filter by search query
- val filtered = if (query.isBlank()) enrichedSeries
- else enrichedSeries.filter { it.name.contains(query, ignoreCase = true) }
-
- // 3. Group by default category
- val grouped = filtered.groupBy { it.categoryName ?: "Uncategorized" }.toMutableMap()
-
- // 4. Always add "★ Favorites" even if empty
- grouped["★ Favorites"] = enrichedSeries.filter { it.isFavorite }
-
- // 5. Always add Custom Groups even if empty, and populate them
- customCats.filter { it.id != -999L }.forEach { customCategory ->
- val groupId = -customCategory.id // Restore actual group DB ID
- val seriesIdsInGroup = allFavorites.filter { it.groupId == groupId }.map { it.contentId }.toSet()
- grouped[customCategory.name] = enrichedSeries.filter { seriesIdsInGroup.contains(it.id) }
+ .flatMapLatest { provider ->
+ combine(
+ favoriteRepository.getAllFavorites(ContentType.SERIES),
+ getCustomCategories(ContentType.SERIES),
+ seriesRepository.getCategories(provider.id),
+ seriesRepository.getCategoryItemCounts(provider.id),
+ seriesRepository.getLibraryCount(provider.id)
+ ) { allFavorites, customCategories, providerCategories, providerCategoryCounts, libraryCount ->
+ SeriesCatalogDependencies(
+ allFavorites = allFavorites,
+ customCategories = customCategories,
+ providerCategories = providerCategories,
+ providerCategoryCounts = providerCategoryCounts,
+ libraryCount = libraryCount
+ )
+ }.combine(_searchQuery) { dependencies, query ->
+ SeriesCatalogParams(
+ providerId = provider.id,
+ allFavorites = dependencies.allFavorites,
+ customCategories = dependencies.customCategories,
+ providerCategories = dependencies.providerCategories,
+ providerCategoryCounts = dependencies.providerCategoryCounts,
+ libraryCount = dependencies.libraryCount,
+ query = query.trim()
+ )
+ }
+ }
+ .flatMapLatest { params ->
+ flow {
+ emit(
+ if (params.query.isBlank()) {
+ buildPreviewCatalog(params)
+ } else {
+ val searchResults = seriesRepository.searchSeries(params.providerId, params.query).first()
+ buildSearchCatalog(
+ series = searchResults,
+ allFavorites = params.allFavorites,
+ customCategories = params.customCategories
+ ).copy(libraryCount = searchResults.size)
}
+ )
+ }
+ }
+ .collect { snapshot ->
+ val isReordering = _uiState.value.isReorderMode
+ _uiState.update {
+ it.copy(
+ seriesByCategory = snapshot.grouped,
+ categoryNames = snapshot.categoryNames,
+ categoryCounts = snapshot.categoryCounts,
+ libraryCount = snapshot.libraryCount,
+ filteredSeries = if (isReordering) it.filteredSeries else emptyList(),
+ isLoading = false
+ )
+ }
+ }
+ }
- // 6. Sort category names, ensuring "★ Favorites" is first, followed by custom groups
- val customNames = customCats.map { it.name }
- val categoryNames = grouped.keys.sortedWith(compareBy<String> {
- when (it) {
- "★ Favorites" -> 0
- in customNames -> 1
- else -> 2
- }
- }.thenBy { it })
-
- grouped to categoryNames
- }.collect { (grouped, categoryNames) ->
- val isReordering = _uiState.value.isReorderMode
- _uiState.update { it.copy(
- seriesByCategory = grouped,
- categoryNames = categoryNames,
- filteredSeries = if (isReordering) it.filteredSeries else emptyList(),
- isLoading = false
- ) }
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .flatMapLatest { provider ->
+ combine(
+ favoriteRepository.getAllFavorites(ContentType.SERIES),
+ getCustomCategories(ContentType.SERIES),
+ seriesRepository.getCategories(provider.id),
+ seriesRepository.getCategoryItemCounts(provider.id)
+ ) { allFavorites, customCategories, providerCategories, providerCategoryCounts ->
+ SeriesCategorySelectionDependencies(
+ allFavorites = allFavorites,
+ customCategories = customCategories,
+ providerCategories = providerCategories,
+ providerCategoryCounts = providerCategoryCounts
+ )
+ }.combine(
+ combine(
+ _uiState.map { it.selectedCategory }.distinctUntilChanged(),
+ _selectedCategoryLoadLimit,
+ _searchQuery
+ ) { selectedCategory, loadLimit, query ->
+ Triple(selectedCategory, loadLimit, query.trim())
}
+ ) { dependencies, selection ->
+ SelectedSeriesCategoryRequest(
+ providerId = provider.id,
+ selectedCategory = selection.first,
+ loadLimit = selection.second,
+ query = selection.third,
+ allFavorites = dependencies.allFavorites,
+ customCategories = dependencies.customCategories,
+ providerCategories = dependencies.providerCategories,
+ providerCategoryCounts = dependencies.providerCategoryCounts
+ )
+ }
+ }
+ .flatMapLatest { request ->
+ flow {
+ emit(loadSelectedCategoryItems(request))
+ }
+ }
+ .collect { snapshot ->
+ _uiState.update {
+ it.copy(
+ selectedCategoryItems = snapshot.items,
+ selectedCategoryLoadedCount = snapshot.loadedCount,
+ selectedCategoryTotalCount = snapshot.totalCount,
+ canLoadMoreSelectedCategory = snapshot.canLoadMore
+ )
}
- // Continue Watching — last 20 items for this provider
+ }
+ }
+
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .collectLatest { provider ->
launch {
playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 20)
.collect { history ->
- _uiState.update { it.copy(continueWatching = history) }
+ _uiState.update {
+ it.copy(
+ continueWatching = history.filter { entry ->
+ entry.contentType == ContentType.SERIES ||
+ entry.contentType == ContentType.SERIES_EPISODE
+ }
+ )
+ }
}
}
}
}
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .flatMapLatest { provider ->
+ combine(
+ favoriteRepository.getAllFavorites(ContentType.SERIES),
+ playbackHistoryRepository.getRecentlyWatchedByProvider(provider.id, limit = 24),
+ seriesRepository.getTopRatedPreview(provider.id, PREVIEW_ROW_LIMIT),
+ seriesRepository.getFreshPreview(provider.id, PREVIEW_ROW_LIMIT)
+ ) { allFavorites, history, topRated, fresh ->
+ SeriesLibraryLensDependencies(
+ providerId = provider.id,
+ allFavorites = allFavorites,
+ history = history,
+ topRated = topRated,
+ fresh = fresh
+ )
+ }
+ }
+ .collectLatest { dependencies ->
+ val globalFavoriteIds = dependencies.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val favoriteIds = dependencies.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .take(PREVIEW_ROW_LIMIT)
+ .toList()
+ val continueIds = dependencies.history
+ .asSequence()
+ .filter {
+ it.contentType == ContentType.SERIES || it.contentType == ContentType.SERIES_EPISODE
+ }
+ .sortedByDescending { it.lastWatchedAt }
+ .distinctBy { it.seriesId ?: it.contentId }
+ .map { it.seriesId ?: it.contentId }
+ .take(PREVIEW_ROW_LIMIT)
+ .toList()
+
+ val favoritePreview = if (favoriteIds.isEmpty()) {
+ emptyList()
+ } else {
+ seriesRepository.getSeriesByIds(favoriteIds).first().orderByIds(favoriteIds)
+ }.markFavorites(globalFavoriteIds)
+ val continuePreview = if (continueIds.isEmpty()) {
+ emptyList()
+ } else {
+ seriesRepository.getSeriesByIds(continueIds).first().orderByIds(continueIds)
+ }.markFavorites(globalFavoriteIds)
+
+ _uiState.update {
+ it.copy(
+ libraryLensRows = mapOf(
+ SeriesLibraryLens.FAVORITES to favoritePreview,
+ SeriesLibraryLens.CONTINUE to continuePreview,
+ SeriesLibraryLens.TOP_RATED to dependencies.topRated.markFavorites(globalFavoriteIds),
+ SeriesLibraryLens.FRESH to dependencies.fresh.markFavorites(globalFavoriteIds)
+ ).filterValues { rows -> rows.isNotEmpty() }
+ )
+ }
+ }
+ }
+
viewModelScope.launch {
preferencesRepository.parentalControlLevel.collect { level ->
_uiState.update { it.copy(parentalControlLevel = level) }
}
}
-
+
viewModelScope.launch {
- getCustomCategories(ContentType.SERIES).collect { cats ->
- _uiState.update { it.copy(categories = cats) }
+ getCustomCategories(ContentType.SERIES).collect { categories ->
+ _uiState.update { it.copy(categories = categories) }
}
}
}
fun selectCategory(categoryName: String?) {
- _uiState.update { it.copy(selectedCategory = categoryName) }
+ _selectedCategoryLoadLimit.value = SELECTED_CATEGORY_PAGE_SIZE
+ _uiState.update {
+ it.copy(
+ selectedCategory = categoryName,
+ selectedCategoryItems = emptyList(),
+ selectedCategoryLoadedCount = 0,
+ selectedCategoryTotalCount = 0,
+ canLoadMoreSelectedCategory = false
+ )
+ }
+ }
+
+ fun selectFullLibraryBrowse() {
+ selectCategory(FULL_LIBRARY_CATEGORY)
+ }
+
+ fun loadMoreSelectedCategory() {
+ if (!_uiState.value.canLoadMoreSelectedCategory) return
+ _selectedCategoryLoadLimit.update { it + SELECTED_CATEGORY_PAGE_SIZE }
}
fun setSearchQuery(query: String) {
@@ -127,13 +315,14 @@ class SeriesViewModel @Inject constructor(
fun onShowDialog(series: Series) {
viewModelScope.launch {
val memberships = favoriteRepository.getGroupMemberships(series.id, ContentType.SERIES)
- val isFav = favoriteRepository.isFavorite(series.id, ContentType.SERIES)
- val updatedSeries = series.copy(isFavorite = isFav)
- _uiState.update { it.copy(
- showDialog = true,
- selectedSeriesForDialog = updatedSeries,
- dialogGroupMemberships = memberships
- ) }
+ val isFavorite = favoriteRepository.isFavorite(series.id, ContentType.SERIES)
+ _uiState.update {
+ it.copy(
+ showDialog = true,
+ selectedSeriesForDialog = series.copy(isFavorite = isFavorite),
+ dialogGroupMemberships = memberships
+ )
+ }
}
}
@@ -157,8 +346,7 @@ class SeriesViewModel @Inject constructor(
fun addToGroup(series: Series, group: Category) {
viewModelScope.launch {
- val groupId = -group.id
- favoriteRepository.addFavorite(series.id, ContentType.SERIES, groupId)
+ favoriteRepository.addFavorite(series.id, ContentType.SERIES, groupId = -group.id)
val memberships = favoriteRepository.getGroupMemberships(series.id, ContentType.SERIES)
_uiState.update { it.copy(dialogGroupMemberships = memberships) }
}
@@ -166,25 +354,39 @@ class SeriesViewModel @Inject constructor(
fun removeFromGroup(series: Series, group: Category) {
viewModelScope.launch {
- val groupId = -group.id
- favoriteRepository.removeFavorite(series.id, ContentType.SERIES, groupId)
+ favoriteRepository.removeFavorite(series.id, ContentType.SERIES, groupId = -group.id)
val memberships = favoriteRepository.getGroupMemberships(series.id, ContentType.SERIES)
_uiState.update { it.copy(dialogGroupMemberships = memberships) }
}
}
fun createCustomGroup(name: String) {
+ val normalizedName = name.trim()
+ val validationError = validateGroupName(normalizedName)
+ if (validationError != null) {
+ _uiState.update { it.copy(userMessage = validationError) }
+ return
+ }
+
viewModelScope.launch {
- favoriteRepository.createGroup(name, contentType = ContentType.SERIES)
+ favoriteRepository.createGroup(normalizedName, contentType = ContentType.SERIES)
+ _uiState.update { it.copy(userMessage = "Created group $normalizedName") }
}
}
- // ── Category Options (Long-Press) ──────────────────────────────────
fun showCategoryOptions(categoryName: String) {
- val customCats = _uiState.value.categories.filter { it.isVirtual }
- val matchedCategory = customCats.find { it.name == categoryName }
- ?: if (categoryName == "★ Favorites") Category(id = -999L, name = "★ Favorites", type = ContentType.SERIES, isVirtual = true) else null
-
+ val matchedCategory = _uiState.value.categories.find { it.name == categoryName }
+ ?: if (categoryName == FAVORITES_CATEGORY) {
+ Category(
+ id = FAVORITES_SENTINEL_ID,
+ name = FAVORITES_CATEGORY,
+ type = ContentType.SERIES,
+ isVirtual = true
+ )
+ } else {
+ null
+ }
+
if (matchedCategory != null) {
_uiState.update { it.copy(selectedCategoryForOptions = matchedCategory) }
}
@@ -194,9 +396,59 @@ class SeriesViewModel @Inject constructor(
_uiState.update { it.copy(selectedCategoryForOptions = null) }
}
+ fun requestRenameGroup(category: Category) {
+ if (!category.isVirtual || category.id == FAVORITES_SENTINEL_ID) return
+ _uiState.update {
+ it.copy(
+ selectedCategoryForOptions = null,
+ showRenameGroupDialog = true,
+ groupToRename = category,
+ renameGroupError = null
+ )
+ }
+ }
+
+ fun cancelRenameGroup() {
+ _uiState.update {
+ it.copy(
+ showRenameGroupDialog = false,
+ groupToRename = null,
+ renameGroupError = null
+ )
+ }
+ }
+
+ fun confirmRenameGroup(name: String) {
+ val category = _uiState.value.groupToRename ?: return
+ val normalizedName = name.trim()
+ val validationError = validateGroupName(normalizedName, currentGroupId = category.id)
+ if (validationError != null) {
+ _uiState.update { it.copy(renameGroupError = validationError) }
+ return
+ }
+
+ viewModelScope.launch {
+ favoriteRepository.renameGroup(-category.id, normalizedName)
+ _uiState.update {
+ it.copy(
+ showRenameGroupDialog = false,
+ groupToRename = null,
+ renameGroupError = null,
+ userMessage = "Renamed group to $normalizedName"
+ )
+ }
+ }
+ }
+
fun requestDeleteGroup(category: Category) {
- if (!category.isVirtual || category.id == -999L) return
- _uiState.update { it.copy(showDeleteGroupDialog = true, groupToDelete = category) }
+ if (!category.isVirtual || category.id == FAVORITES_SENTINEL_ID) return
+ _uiState.update {
+ it.copy(
+ selectedCategoryForOptions = null,
+ showDeleteGroupDialog = true,
+ groupToDelete = category
+ )
+ }
}
fun cancelDeleteGroup() {
@@ -210,52 +462,57 @@ class SeriesViewModel @Inject constructor(
_uiState.update {
it.copy(
showDeleteGroupDialog = false,
- groupToDelete = null
+ groupToDelete = null,
+ userMessage = "Deleted group ${category.name}"
)
}
}
}
- // ── Reorder ────────────────────────────────────────────────────────
+ fun userMessageShown() {
+ _uiState.update { it.copy(userMessage = null) }
+ }
+
fun enterCategoryReorderMode(category: Category) {
dismissCategoryOptions()
- val currentCategoryName = category.name
- val seriesInView = _uiState.value.seriesByCategory[currentCategoryName] ?: emptyList()
- _localSeries.value = seriesInView
-
- _uiState.update { it.copy(
- isReorderMode = true,
- reorderCategory = category,
- filteredSeries = seriesInView
- ) }
+ viewModelScope.launch {
+ val seriesInView = loadReorderSeries(category)
+ _uiState.update {
+ it.copy(
+ isReorderMode = true,
+ reorderCategory = category,
+ filteredSeries = seriesInView
+ )
+ }
+ }
}
fun exitCategoryReorderMode() {
- _uiState.update { it.copy(
- isReorderMode = false,
- reorderCategory = null,
- filteredSeries = emptyList()
- ) }
+ _uiState.update {
+ it.copy(
+ isReorderMode = false,
+ reorderCategory = null,
+ filteredSeries = emptyList()
+ )
+ }
}
fun moveItemUp(series: Series) {
- val state = _uiState.value
- val list = state.filteredSeries.toMutableList()
- val idx = list.indexOf(series)
- if (idx > 0) {
- list.removeAt(idx)
- list.add(idx - 1, series)
+ val list = _uiState.value.filteredSeries.toMutableList()
+ val index = list.indexOf(series)
+ if (index > 0) {
+ list.removeAt(index)
+ list.add(index - 1, series)
_uiState.update { it.copy(filteredSeries = list) }
}
}
fun moveItemDown(series: Series) {
- val state = _uiState.value
- val list = state.filteredSeries.toMutableList()
- val idx = list.indexOf(series)
- if (idx >= 0 && idx < list.size - 1) {
- list.removeAt(idx)
- list.add(idx + 1, series)
+ val list = _uiState.value.filteredSeries.toMutableList()
+ val index = list.indexOf(series)
+ if (index >= 0 && index < list.lastIndex) {
+ list.removeAt(index)
+ list.add(index + 1, series)
_uiState.update { it.copy(filteredSeries = list) }
}
}
@@ -269,7 +526,7 @@ class SeriesViewModel @Inject constructor(
viewModelScope.launch {
try {
- val groupId = if (category.id == -999L) null else -category.id
+ val groupId = if (category.id == FAVORITES_SENTINEL_ID) null else -category.id
val favoritesFlow = if (groupId == null) {
favoriteRepository.getFavorites(ContentType.SERIES)
} else {
@@ -278,25 +535,338 @@ class SeriesViewModel @Inject constructor(
val favorites = favoritesFlow.first()
val favoriteMap = favorites.associateBy { it.contentId }
-
- val reorderedFavorites = currentList.mapNotNull { ser ->
- favoriteMap[ser.id]
- }.mapIndexed { i, fav ->
- fav.copy(position = i)
+ val reorderedFavorites = currentList.mapNotNull { series ->
+ favoriteMap[series.id]
+ }.mapIndexed { index, favorite ->
+ favorite.copy(position = index)
}
favoriteRepository.reorderFavorites(reorderedFavorites)
- } catch (e: Exception) {
- // Ignore silently for now
+ } catch (_: Exception) {
+ }
+ }
+ }
+
+ private suspend fun loadReorderSeries(category: Category): List<Series> {
+ if (!category.isVirtual) return emptyList()
+
+ val groupId = if (category.id == FAVORITES_SENTINEL_ID) null else -category.id
+ val favorites = if (groupId == null) {
+ favoriteRepository.getFavorites(ContentType.SERIES).first()
+ } else {
+ favoriteRepository.getFavoritesByGroup(groupId).first()
+ }
+
+ val orderedIds = favorites
+ .sortedBy { it.position }
+ .map { it.contentId }
+
+ if (orderedIds.isEmpty()) return emptyList()
+ return seriesRepository.getSeriesByIds(orderedIds).first().orderByIds(orderedIds)
+ }
+
+ private suspend fun buildPreviewCatalog(
+ params: SeriesCatalogParams
+ ): SeriesCatalogSnapshot {
+ val globalFavoriteIds = params.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val previewRows = linkedMapOf<String, List<Series>>()
+ val countMap = linkedMapOf<String, Int>()
+
+ val favoritesIds = params.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .toList()
+ if (favoritesIds.isNotEmpty()) {
+ val preview = seriesRepository.getSeriesByIds(favoritesIds.take(PREVIEW_ROW_LIMIT)).first()
+ .markFavorites(globalFavoriteIds)
+ if (preview.isNotEmpty()) {
+ previewRows[FAVORITES_CATEGORY] = preview
+ countMap[FAVORITES_CATEGORY] = favoritesIds.size
+ }
+ }
+
+ params.customCategories
+ .filter { it.id != FAVORITES_SENTINEL_ID }
+ .forEach { category ->
+ val ids = params.allFavorites
+ .asSequence()
+ .filter { it.groupId == -category.id }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .toList()
+ if (ids.isNotEmpty()) {
+ val preview = seriesRepository.getSeriesByIds(ids.take(PREVIEW_ROW_LIMIT)).first()
+ .markFavorites(globalFavoriteIds)
+ if (preview.isNotEmpty()) {
+ previewRows[category.name] = preview
+ countMap[category.name] = ids.size
+ }
+ }
+ }
+
+ val providerPreviews = coroutineScope {
+ params.providerCategories
+ .sortedBy { it.name.lowercase() }
+ .map { category ->
+ async {
+ val preview = seriesRepository
+ .getSeriesByCategoryPreview(params.providerId, category.id, PREVIEW_ROW_LIMIT)
+ .first()
+ .markFavorites(globalFavoriteIds)
+ category to preview
+ }
+ }
+ .awaitAll()
+ }
+
+ providerPreviews.forEach { (category, preview) ->
+ if (preview.isNotEmpty()) {
+ previewRows[category.name] = preview
+ countMap[category.name] = params.providerCategoryCounts[category.id] ?: preview.size
+ }
+ }
+
+ return SeriesCatalogSnapshot(
+ grouped = previewRows,
+ categoryNames = previewRows.keys.toList(),
+ categoryCounts = countMap,
+ libraryCount = params.libraryCount
+ )
+ }
+
+ private fun buildSearchCatalog(
+ series: List<Series>,
+ allFavorites: List<com.streamvault.domain.model.Favorite>,
+ customCategories: List<Category>
+ ): SeriesCatalogSnapshot {
+ val globalFavoriteIds = allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+ val enrichedSeries = series.map { it.copy(isFavorite = globalFavoriteIds.contains(it.id)) }
+ val grouped = enrichedSeries
+ .groupBy { it.categoryName ?: UNCATEGORIZED }
+ .toMutableMap()
+
+ grouped[FAVORITES_CATEGORY] = enrichedSeries.filter { it.isFavorite }
+
+ customCategories
+ .filter { it.id != FAVORITES_SENTINEL_ID }
+ .forEach { customCategory ->
+ val seriesIdsInGroup = allFavorites
+ .asSequence()
+ .filter { it.groupId == -customCategory.id }
+ .map { it.contentId }
+ .toSet()
+ grouped[customCategory.name] = enrichedSeries.filter { it.id in seriesIdsInGroup }
+ }
+
+ val customNames = customCategories.map { it.name }.toSet()
+ val categoryNames = grouped.keys.sortedWith(
+ compareBy<String> {
+ when (it) {
+ FAVORITES_CATEGORY -> 0
+ in customNames -> 1
+ else -> 2
+ }
+ }.thenBy { it }
+ )
+
+ val categoryCounts = categoryNames.associateWith { name -> grouped[name]?.size ?: 0 }
+
+ return SeriesCatalogSnapshot(
+ grouped = grouped,
+ categoryNames = categoryNames,
+ categoryCounts = categoryCounts,
+ libraryCount = series.size
+ )
+ }
+
+ private suspend fun loadSelectedCategoryItems(
+ request: SelectedSeriesCategoryRequest
+ ): SelectedSeriesCategorySnapshot {
+ if (request.selectedCategory.isNullOrBlank() || request.query.isNotBlank()) {
+ return SelectedSeriesCategorySnapshot()
+ }
+
+ val globalFavoriteIds = request.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .map { it.contentId }
+ .toSet()
+
+ val (selectedItems, totalCount) = when (request.selectedCategory) {
+ FULL_LIBRARY_CATEGORY -> {
+ val result = seriesRepository
+ .browseSeries(
+ LibraryBrowseQuery(
+ providerId = request.providerId,
+ categoryId = null,
+ limit = request.loadLimit,
+ offset = 0
+ )
+ )
+ .first()
+ result.items to result.totalCount
}
+ FAVORITES_CATEGORY -> {
+ val ids = request.allFavorites
+ .asSequence()
+ .filter { it.groupId == null }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .toList()
+ val pagedIds = ids.take(request.loadLimit)
+ val items = if (pagedIds.isEmpty()) {
+ emptyList()
+ } else {
+ seriesRepository.getSeriesByIds(pagedIds).first().orderByIds(pagedIds)
+ }
+ items to ids.size
+ }
+ else -> {
+ val customCategory = request.customCategories.firstOrNull { it.name == request.selectedCategory }
+ if (customCategory != null) {
+ val ids = request.allFavorites
+ .asSequence()
+ .filter { it.groupId == -customCategory.id }
+ .sortedBy { it.position }
+ .map { it.contentId }
+ .toList()
+ val pagedIds = ids.take(request.loadLimit)
+ val items = if (pagedIds.isEmpty()) {
+ emptyList()
+ } else {
+ seriesRepository.getSeriesByIds(pagedIds).first().orderByIds(pagedIds)
+ }
+ items to ids.size
+ } else {
+ val providerCategory = request.providerCategories.firstOrNull { it.name == request.selectedCategory }
+ if (providerCategory != null) {
+ val result = seriesRepository
+ .browseSeries(
+ LibraryBrowseQuery(
+ providerId = request.providerId,
+ categoryId = providerCategory.id,
+ limit = request.loadLimit,
+ offset = 0
+ )
+ )
+ .first()
+ result.items to result.totalCount
+ } else {
+ emptyList<Series>() to 0
+ }
+ }
+ }
+ }
+
+ val enrichedItems = selectedItems.markFavorites(globalFavoriteIds)
+ return SelectedSeriesCategorySnapshot(
+ items = enrichedItems,
+ loadedCount = enrichedItems.size,
+ totalCount = totalCount,
+ canLoadMore = totalCount > enrichedItems.size
+ )
+ }
+
+ private fun validateGroupName(name: String, currentGroupId: Long? = null): String? {
+ if (name.isBlank()) return "Enter a group name"
+ if (name.equals("favorites", ignoreCase = true)) return "Favorites is reserved"
+
+ val duplicate = _uiState.value.categories.any { category ->
+ category.id != currentGroupId && category.name.equals(name, ignoreCase = true)
}
+ return if (duplicate) "A series group with that name already exists" else null
+ }
+
+ private fun List<Series>.markFavorites(globalFavoriteIds: Set<Long>): List<Series> =
+ map { series -> series.copy(isFavorite = series.id in globalFavoriteIds) }
+
+ private fun List<Series>.orderByIds(ids: List<Long>): List<Series> {
+ val seriesMap = associateBy { it.id }
+ return ids.mapNotNull { seriesMap[it] }
}
}
+private data class SeriesCatalogParams(
+ val providerId: Long,
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val customCategories: List<Category>,
+ val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>,
+ val libraryCount: Int,
+ val query: String
+)
+
+private data class SeriesCatalogDependencies(
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val customCategories: List<Category>,
+ val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>,
+ val libraryCount: Int
+)
+
+private data class SeriesCatalogSnapshot(
+ val grouped: Map<String, List<Series>>,
+ val categoryNames: List<String>,
+ val categoryCounts: Map<String, Int>,
+ val libraryCount: Int
+)
+
+private data class SeriesLibraryLensDependencies(
+ val providerId: Long,
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val history: List<PlaybackHistory>,
+ val topRated: List<Series>,
+ val fresh: List<Series>
+)
+
+private data class SeriesCategorySelectionDependencies(
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val customCategories: List<Category>,
+ val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>
+)
+
+private data class SelectedSeriesCategoryRequest(
+ val providerId: Long,
+ val selectedCategory: String?,
+ val loadLimit: Int,
+ val query: String,
+ val allFavorites: List<com.streamvault.domain.model.Favorite>,
+ val customCategories: List<Category>,
+ val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>
+)
+
+private data class SelectedSeriesCategorySnapshot(
+ val items: List<Series> = emptyList(),
+ val loadedCount: Int = 0,
+ val totalCount: Int = 0,
+ val canLoadMore: Boolean = false
+)
+
data class SeriesUiState(
val seriesByCategory: Map<String, List<Series>> = emptyMap(),
val categoryNames: List<String> = emptyList(),
+ val categoryCounts: Map<String, Int> = emptyMap(),
+ val libraryCount: Int = 0,
+ val favoriteCategoryName: String = "\u2605 Favorites",
+ val fullLibraryCategoryName: String = "__full_library__",
+ val libraryLensRows: Map<SeriesLibraryLens, List<Series>> = emptyMap(),
val selectedCategory: String? = null,
+ val selectedCategoryItems: List<Series> = emptyList(),
+ val selectedCategoryLoadedCount: Int = 0,
+ val selectedCategoryTotalCount: Int = 0,
+ val canLoadMoreSelectedCategory: Boolean = false,
val searchQuery: String = "",
val continueWatching: List<PlaybackHistory> = emptyList(),
val isLoading: Boolean = true,
@@ -305,13 +875,13 @@ data class SeriesUiState(
val selectedSeriesForDialog: Series? = null,
val categories: List<Category> = emptyList(),
val dialogGroupMemberships: List<Long> = emptyList(),
-
- // Category Options & Deletion
+ val userMessage: String? = null,
val selectedCategoryForOptions: Category? = null,
+ val showRenameGroupDialog: Boolean = false,
+ val groupToRename: Category? = null,
+ val renameGroupError: String? = null,
val showDeleteGroupDialog: Boolean = false,
val groupToDelete: Category? = null,
-
- // Reorder State
val isReorderMode: Boolean = false,
val reorderCategory: Category? = null,
val filteredSeries: List<Series> = emptyList()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
index 8fec3ac4..35989654 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt
@@ -4,11 +4,13 @@ import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.tv.material3.*
@@ -28,15 +30,22 @@ import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import com.streamvault.app.ui.components.dialogs.PinDialog
+import com.streamvault.app.ui.components.TvEmptyState
import com.streamvault.app.ui.components.TopNavBar
import com.streamvault.app.ui.theme.*
+import com.streamvault.domain.manager.BackupConflictStrategy
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.RecordingItem
+import com.streamvault.domain.model.RecordingStatus
+import com.streamvault.app.ui.screens.settings.ProviderDiagnosticsUiModel
import kotlinx.coroutines.launch
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.window.Dialog
+import androidx.compose.ui.text.style.TextAlign
import com.streamvault.app.R
+import java.util.Locale
@Composable
@@ -53,6 +62,24 @@ fun SettingsScreen(
val snackbarHostState = remember { SnackbarHostState() }
val scope = rememberCoroutineScope()
val context = androidx.compose.ui.platform.LocalContext.current
+ val activeProvider = uiState.providers.firstOrNull { it.id == uiState.activeProviderId }
+ val appLanguageLabel = remember(uiState.appLanguage, context) {
+ when (uiState.appLanguage) {
+ "ar" -> "العربية"
+ "he" -> "עברית"
+ "ru" -> "Русский"
+ "en" -> "English"
+ else -> context.getString(R.string.settings_system_default)
+ }
+ }
+ val protectionSummary = remember(uiState.parentalControlLevel, context) {
+ when (uiState.parentalControlLevel) {
+ 0 -> context.getString(R.string.settings_level_off)
+ 1 -> context.getString(R.string.settings_level_locked)
+ 2 -> context.getString(R.string.settings_level_hidden)
+ else -> context.getString(R.string.settings_level_unknown)
+ }
+ }
// Parental Control State
var showPinDialog by remember { mutableStateOf(false) }
@@ -70,7 +97,7 @@ fun SettingsScreen(
val openDocumentLauncher = rememberLauncherForActivityResult(
contract = ActivityResultContracts.OpenDocument()
) { uri ->
- uri?.let { viewModel.importConfig(it.toString()) }
+ uri?.let { viewModel.inspectBackup(it.toString()) }
}
@@ -106,31 +133,40 @@ fun SettingsScreen(
)
}
+ item {
+ SettingsOverviewCard(
+ activeProviderName = activeProvider?.name ?: stringResource(R.string.settings_overview_no_provider),
+ providerCount = uiState.providers.size,
+ protectionSummary = protectionSummary,
+ languageLabel = appLanguageLabel
+ )
+ }
+
// Providers section
item {
- Text(
- text = stringResource(R.string.settings_providers),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- modifier = Modifier.padding(bottom = 8.dp)
+ SettingsSectionHeader(
+ title = stringResource(R.string.settings_providers),
+ subtitle = stringResource(R.string.settings_providers_subtitle)
)
}
if (uiState.providers.isEmpty()) {
item {
- Text(
- text = stringResource(R.string.settings_no_providers),
- style = MaterialTheme.typography.bodyMedium,
- color = OnSurface
+ TvEmptyState(
+ title = stringResource(R.string.settings_no_providers),
+ subtitle = stringResource(R.string.settings_no_providers_subtitle),
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(top = 8.dp, bottom = 8.dp)
)
}
} else {
- items(uiState.providers.size) { index ->
- val provider = uiState.providers[index]
+ items(uiState.providers, key = { it.id }) { provider ->
ProviderSettingsCard(
provider = provider,
isActive = provider.id == uiState.activeProviderId,
isSyncing = uiState.isSyncing,
+ diagnostics = uiState.diagnosticsByProvider[provider.id],
syncWarnings = uiState.syncWarningsByProvider[provider.id].orEmpty(),
onRetryWarningAction = { action -> viewModel.retryWarningAction(provider.id, action) },
onConnect = { viewModel.setActiveProvider(provider.id) },
@@ -177,11 +213,9 @@ fun SettingsScreen(
// Parental Control
item {
Spacer(Modifier.height(16.dp))
- Text(
- text = stringResource(R.string.settings_parental_control),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- modifier = Modifier.padding(bottom = 8.dp)
+ SettingsSectionHeader(
+ title = stringResource(R.string.settings_parental_control),
+ subtitle = stringResource(R.string.settings_parental_subtitle)
)
ParentalControlCard(
level = uiState.parentalControlLevel,
@@ -199,11 +233,9 @@ fun SettingsScreen(
// Language Settings
item {
Spacer(Modifier.height(16.dp))
- Text(
- text = stringResource(R.string.settings_language),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- modifier = Modifier.padding(bottom = 8.dp)
+ SettingsSectionHeader(
+ title = stringResource(R.string.settings_language),
+ subtitle = stringResource(R.string.settings_language_subtitle)
)
Surface(
@@ -246,11 +278,9 @@ fun SettingsScreen(
// Backup & Restore settings
item {
Spacer(Modifier.height(16.dp))
- Text(
- text = stringResource(R.string.settings_backup_restore),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- modifier = Modifier.padding(bottom = 8.dp)
+ SettingsSectionHeader(
+ title = stringResource(R.string.settings_backup_restore),
+ subtitle = stringResource(R.string.settings_backup_subtitle)
)
Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
@@ -268,7 +298,7 @@ fun SettingsScreen(
style = MaterialTheme.typography.bodyLarge,
color = OnBackground,
modifier = Modifier.padding(16.dp),
- textAlign = androidx.compose.ui.text.style.TextAlign.Center
+ textAlign = TextAlign.Center
)
}
@@ -286,20 +316,53 @@ fun SettingsScreen(
style = MaterialTheme.typography.bodyLarge,
color = OnBackground,
modifier = Modifier.padding(16.dp),
- textAlign = androidx.compose.ui.text.style.TextAlign.Center
+ textAlign = TextAlign.Center
)
}
}
}
+ item {
+ Spacer(Modifier.height(16.dp))
+ SettingsSectionHeader(
+ title = stringResource(R.string.settings_recording_title),
+ subtitle = stringResource(R.string.settings_recording_subtitle)
+ )
+ RecordingOverviewCard(
+ outputDirectory = uiState.recordingStorageState.outputDirectory,
+ availableBytes = uiState.recordingStorageState.availableBytes,
+ isWritable = uiState.recordingStorageState.isWritable,
+ activeCount = uiState.recordingItems.count { it.status == RecordingStatus.RECORDING },
+ scheduledCount = uiState.recordingItems.count { it.status == RecordingStatus.SCHEDULED }
+ )
+ }
+
+ if (uiState.recordingItems.isEmpty()) {
+ item {
+ TvEmptyState(
+ title = stringResource(R.string.settings_recording_empty_title),
+ subtitle = stringResource(R.string.settings_recording_empty_subtitle),
+ modifier = Modifier
+ .fillMaxWidth()
+ .padding(top = 8.dp, bottom = 8.dp)
+ )
+ }
+ } else {
+ items(uiState.recordingItems, key = { it.id }) { item ->
+ RecordingItemCard(
+ item = item,
+ onStop = { viewModel.stopRecording(item.id) },
+ onCancel = { viewModel.cancelRecording(item.id) }
+ )
+ }
+ }
+
// Decoder settings
item {
Spacer(Modifier.height(16.dp))
- Text(
- text = stringResource(R.string.settings_playback),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- modifier = Modifier.padding(bottom = 8.dp)
+ SettingsSectionHeader(
+ title = stringResource(R.string.settings_playback),
+ subtitle = stringResource(R.string.settings_playback_subtitle)
)
SettingsRow(label = stringResource(R.string.settings_decoder_mode), value = stringResource(R.string.settings_decoder_auto))
SettingsRow(label = stringResource(R.string.settings_buffer_duration), value = stringResource(R.string.settings_buffer_5s))
@@ -308,11 +371,9 @@ fun SettingsScreen(
// About section
item {
Spacer(Modifier.height(16.dp))
- Text(
- text = stringResource(R.string.settings_about),
- style = MaterialTheme.typography.titleMedium,
- color = Primary,
- modifier = Modifier.padding(bottom = 8.dp)
+ SettingsSectionHeader(
+ title = stringResource(R.string.settings_about),
+ subtitle = stringResource(R.string.settings_about_subtitle)
)
SettingsRow(label = stringResource(R.string.settings_app_version), value = "1.0.0")
SettingsRow(label = stringResource(R.string.settings_build), value = stringResource(R.string.settings_build_desc))
@@ -467,6 +528,22 @@ fun SettingsScreen(
)
}
}
+
+ val backupPreview = uiState.backupPreview
+ if (backupPreview != null && uiState.pendingBackupUri != null) {
+ BackupImportPreviewDialog(
+ preview = backupPreview,
+ plan = uiState.backupImportPlan,
+ onDismiss = { viewModel.dismissBackupPreview() },
+ onStrategySelected = { viewModel.setBackupConflictStrategy(it) },
+ onImportPreferencesChanged = { viewModel.setImportPreferences(it) },
+ onImportProvidersChanged = { viewModel.setImportProviders(it) },
+ onImportSavedLibraryChanged = { viewModel.setImportSavedLibrary(it) },
+ onImportPlaybackHistoryChanged = { viewModel.setImportPlaybackHistory(it) },
+ onImportMultiViewChanged = { viewModel.setImportMultiViewPresets(it) },
+ onConfirm = { viewModel.confirmBackupImport() }
+ )
+ }
}
}
@@ -633,6 +710,7 @@ private fun ProviderSettingsCard(
provider: Provider,
isActive: Boolean,
isSyncing: Boolean,
+ diagnostics: ProviderDiagnosticsUiModel?,
syncWarnings: List<String>,
onRetryWarningAction: (ProviderWarningAction) -> Unit,
onConnect: () -> Unit,
@@ -705,13 +783,20 @@ private fun ProviderSettingsCard(
color = if (expDate != null && expDate < System.currentTimeMillis() && expDate != Long.MAX_VALUE) ErrorColor else OnSurfaceDim
)
+ diagnostics?.let { model ->
+ ProviderDiagnosticsPanel(
+ provider = provider,
+ diagnostics = model
+ )
+ }
+
if (syncWarnings.isNotEmpty()) {
val hasEpgWarning = syncWarnings.any { it.contains("EPG", ignoreCase = true) }
val hasMoviesWarning = syncWarnings.any { it.contains("Movies", ignoreCase = true) }
val hasSeriesWarning = syncWarnings.any { it.contains("Series", ignoreCase = true) }
Text(
- text = "Warnings: ${syncWarnings.take(3).joinToString(", ")}",
+ text = stringResource(R.string.settings_provider_warnings, syncWarnings.take(3).joinToString(", ")),
style = MaterialTheme.typography.bodySmall,
color = Secondary
)
@@ -728,7 +813,7 @@ private fun ProviderSettingsCard(
)
) {
Text(
- text = "Retry EPG",
+ text = stringResource(R.string.settings_retry_epg),
style = MaterialTheme.typography.labelSmall,
color = Secondary,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)
@@ -746,7 +831,7 @@ private fun ProviderSettingsCard(
)
) {
Text(
- text = "Retry Movies",
+ text = stringResource(R.string.settings_retry_movies),
style = MaterialTheme.typography.labelSmall,
color = Secondary,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)
@@ -764,7 +849,7 @@ private fun ProviderSettingsCard(
)
) {
Text(
- text = "Retry Series",
+ text = stringResource(R.string.settings_retry_series),
style = MaterialTheme.typography.labelSmall,
color = Secondary,
modifier = Modifier.padding(horizontal = 10.dp, vertical = 8.dp)
@@ -867,12 +952,12 @@ private fun ProviderSettingsCard(
@Composable
private fun ProviderStatusBadge(status: ProviderStatus) {
val (label, color) = when (status) {
- ProviderStatus.ACTIVE -> "Active" to Primary
- ProviderStatus.PARTIAL -> "Partial" to Secondary
- ProviderStatus.ERROR -> "Error" to ErrorColor
- ProviderStatus.EXPIRED -> "Expired" to ErrorColor
- ProviderStatus.DISABLED -> "Disabled" to OnSurfaceDim
- ProviderStatus.UNKNOWN -> "Unknown" to OnSurfaceDim
+ ProviderStatus.ACTIVE -> stringResource(R.string.settings_status_active) to Primary
+ ProviderStatus.PARTIAL -> stringResource(R.string.settings_status_partial) to Secondary
+ ProviderStatus.ERROR -> stringResource(R.string.settings_status_error) to ErrorColor
+ ProviderStatus.EXPIRED -> stringResource(R.string.settings_status_expired) to ErrorColor
+ ProviderStatus.DISABLED -> stringResource(R.string.settings_status_disabled) to OnSurfaceDim
+ ProviderStatus.UNKNOWN -> stringResource(R.string.settings_status_unknown) to OnSurfaceDim
}
Text(
@@ -886,6 +971,215 @@ private fun ProviderStatusBadge(status: ProviderStatus) {
)
}
+@Composable
+private fun SettingsOverviewCard(
+ activeProviderName: String,
+ providerCount: Int,
+ protectionSummary: String,
+ languageLabel: String
+) {
+ Surface(
+ modifier = Modifier.fillMaxWidth(),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(16.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(14.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.settings_overview_title),
+ style = MaterialTheme.typography.titleLarge,
+ color = OnBackground
+ )
+ Text(
+ text = stringResource(R.string.settings_overview_subtitle),
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ SettingsOverviewStat(
+ modifier = Modifier.weight(1f),
+ label = stringResource(R.string.settings_overview_provider_label),
+ value = activeProviderName
+ )
+ SettingsOverviewStat(
+ modifier = Modifier.weight(1f),
+ label = stringResource(R.string.settings_overview_count_label),
+ value = providerCount.toString()
+ )
+ SettingsOverviewStat(
+ modifier = Modifier.weight(1f),
+ label = stringResource(R.string.settings_overview_protection_label),
+ value = protectionSummary
+ )
+ SettingsOverviewStat(
+ modifier = Modifier.weight(1f),
+ label = stringResource(R.string.settings_overview_language_label),
+ value = languageLabel
+ )
+ }
+ }
+
+ }
+}
+
+@Composable
+private fun ProviderDiagnosticsPanel(
+ provider: Provider,
+ diagnostics: ProviderDiagnosticsUiModel
+) {
+ Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text(
+ text = stringResource(R.string.settings_provider_diagnostics_title),
+ style = MaterialTheme.typography.titleSmall,
+ color = Primary
+ )
+ Text(
+ text = diagnostics.capabilitySummary,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = "${diagnostics.sourceLabel} • ${diagnostics.connectionSummary}",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurface
+ )
+ Text(
+ text = diagnostics.expirySummary,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurface
+ )
+ Text(
+ text = diagnostics.archiveSummary,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ ProviderDiagnosticPill(
+ title = stringResource(R.string.settings_diagnostic_live),
+ count = diagnostics.liveCount,
+ timestamp = diagnostics.lastLiveSync
+ )
+ ProviderDiagnosticPill(
+ title = stringResource(R.string.settings_diagnostic_movies),
+ count = diagnostics.movieCount,
+ timestamp = diagnostics.lastMovieSync
+ )
+ if (provider.type == ProviderType.XTREAM_CODES) {
+ ProviderDiagnosticPill(
+ title = stringResource(R.string.settings_diagnostic_series),
+ count = diagnostics.seriesCount,
+ timestamp = diagnostics.lastSeriesSync
+ )
+ }
+ ProviderDiagnosticPill(
+ title = stringResource(R.string.settings_diagnostic_epg),
+ count = diagnostics.epgCount,
+ timestamp = diagnostics.lastEpgSync
+ )
+ }
+ Text(
+ text = stringResource(R.string.settings_diagnostic_status, diagnostics.lastSyncStatus),
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurface
+ )
+ }
+}
+
+@Composable
+private fun ProviderDiagnosticPill(
+ title: String,
+ count: Int,
+ timestamp: Long
+) {
+ val syncLabel = remember(timestamp) {
+ if (timestamp <= 0L) {
+ null
+ } else {
+ java.text.SimpleDateFormat("MMM d, HH:mm", java.util.Locale.getDefault()).format(java.util.Date(timestamp))
+ }
+ }
+ Surface(
+ shape = RoundedCornerShape(10.dp),
+ colors = SurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.06f)
+ )
+ ) {
+ Column(
+ modifier = Modifier.padding(horizontal = 12.dp, vertical = 10.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = stringResource(R.string.settings_diagnostic_items, count),
+ style = MaterialTheme.typography.labelLarge,
+ color = OnBackground
+ )
+ Text(
+ text = syncLabel ?: stringResource(R.string.settings_diagnostic_never),
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurface
+ )
+ }
+ }
+}
+
+@Composable
+private fun SettingsOverviewStat(
+ label: String,
+ value: String,
+ modifier: Modifier = Modifier
+) {
+ Column(
+ modifier = modifier
+ .background(SurfaceHighlight.copy(alpha = 0.28f), RoundedCornerShape(12.dp))
+ .padding(horizontal = 14.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = label.uppercase(Locale.getDefault()),
+ style = MaterialTheme.typography.labelSmall,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = value,
+ style = MaterialTheme.typography.titleSmall,
+ color = OnBackground,
+ fontWeight = FontWeight.SemiBold
+ )
+ }
+}
+
+@Composable
+private fun SettingsSectionHeader(
+ title: String,
+ subtitle: String
+) {
+ Column(
+ modifier = Modifier.fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleMedium,
+ color = Primary
+ )
+ Text(
+ text = subtitle,
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+}
+
@Composable
private fun SettingsRow(label: String, value: String) {
Row(
@@ -898,3 +1192,298 @@ private fun SettingsRow(label: String, value: String) {
Text(text = value, style = MaterialTheme.typography.bodyMedium, color = OnBackground)
}
}
+
+@Composable
+private fun BackupImportPreviewDialog(
+ preview: com.streamvault.domain.manager.BackupPreview,
+ plan: com.streamvault.domain.manager.BackupImportPlan,
+ onDismiss: () -> Unit,
+ onStrategySelected: (BackupConflictStrategy) -> Unit,
+ onImportPreferencesChanged: (Boolean) -> Unit,
+ onImportProvidersChanged: (Boolean) -> Unit,
+ onImportSavedLibraryChanged: (Boolean) -> Unit,
+ onImportPlaybackHistoryChanged: (Boolean) -> Unit,
+ onImportMultiViewChanged: (Boolean) -> Unit,
+ onConfirm: () -> Unit
+) {
+ AlertDialog(
+ onDismissRequest = onDismiss,
+ title = { Text(stringResource(R.string.settings_backup_preview_title)) },
+ text = {
+ Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Text(
+ text = stringResource(R.string.settings_backup_preview_subtitle, preview.version),
+ style = MaterialTheme.typography.bodyMedium,
+ color = OnSurfaceDim
+ )
+ BackupPreviewRow(stringResource(R.string.settings_backup_section_preferences), preview.preferenceCount, 0)
+ BackupPreviewRow(stringResource(R.string.settings_backup_section_providers), preview.providerCount, preview.providerConflicts)
+ BackupPreviewRow(stringResource(R.string.settings_backup_section_saved), preview.favoriteCount + preview.groupCount, preview.favoriteConflicts + preview.groupConflicts)
+ BackupPreviewRow(stringResource(R.string.settings_backup_section_history), preview.playbackHistoryCount, preview.historyConflicts)
+ BackupPreviewRow(stringResource(R.string.settings_backup_section_multiview), preview.multiViewPresetCount, 0)
+ Text(
+ text = stringResource(R.string.settings_backup_conflict_strategy),
+ style = MaterialTheme.typography.titleSmall,
+ color = Primary
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ BackupStrategyChip(
+ title = stringResource(R.string.settings_backup_keep_existing),
+ selected = plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING,
+ onClick = { onStrategySelected(BackupConflictStrategy.KEEP_EXISTING) }
+ )
+ BackupStrategyChip(
+ title = stringResource(R.string.settings_backup_replace_existing),
+ selected = plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING,
+ onClick = { onStrategySelected(BackupConflictStrategy.REPLACE_EXISTING) }
+ )
+ }
+ Text(
+ text = stringResource(R.string.settings_backup_import_sections),
+ style = MaterialTheme.typography.titleSmall,
+ color = Primary
+ )
+ BackupToggleRow(stringResource(R.string.settings_backup_section_preferences), plan.importPreferences, onImportPreferencesChanged)
+ BackupToggleRow(stringResource(R.string.settings_backup_section_providers), plan.importProviders, onImportProvidersChanged)
+ BackupToggleRow(stringResource(R.string.settings_backup_section_saved), plan.importSavedLibrary, onImportSavedLibraryChanged)
+ BackupToggleRow(stringResource(R.string.settings_backup_section_history), plan.importPlaybackHistory, onImportPlaybackHistoryChanged)
+ BackupToggleRow(stringResource(R.string.settings_backup_section_multiview), plan.importMultiViewPresets, onImportMultiViewChanged)
+ }
+ },
+ confirmButton = { Button(onClick = onConfirm) { Text(stringResource(R.string.settings_backup_import_confirm)) } },
+ dismissButton = { OutlinedButton(onClick = onDismiss) { Text(stringResource(R.string.settings_cancel)) } }
+ )
+}
+
+@Composable
+private fun BackupPreviewRow(
+ title: String,
+ itemCount: Int,
+ conflictCount: Int
+) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column {
+ Text(title, style = MaterialTheme.typography.bodyLarge, color = OnBackground)
+ Text(
+ text = if (conflictCount > 0) {
+ stringResource(R.string.settings_backup_conflict_count, conflictCount)
+ } else {
+ stringResource(R.string.settings_backup_no_conflicts)
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = if (conflictCount > 0) Secondary else OnSurfaceDim
+ )
+ }
+ Text(
+ text = stringResource(R.string.settings_backup_item_count, itemCount),
+ style = MaterialTheme.typography.labelLarge,
+ color = OnBackground
+ )
+ }
+}
+
+@Composable
+private fun BackupStrategyChip(
+ title: String,
+ selected: Boolean,
+ onClick: () -> Unit
+) {
+ Surface(
+ onClick = onClick,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(24.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (selected) Primary.copy(alpha = 0.2f) else SurfaceElevated,
+ focusedContainerColor = Primary.copy(alpha = 0.35f)
+ )
+ ) {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.labelLarge,
+ color = if (selected) Primary else OnBackground,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)
+ )
+ }
+}
+
+@Composable
+private fun BackupToggleRow(
+ label: String,
+ checked: Boolean,
+ onCheckedChange: (Boolean) -> Unit
+) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(label, style = MaterialTheme.typography.bodyLarge, color = OnBackground)
+ Switch(checked = checked, onCheckedChange = onCheckedChange)
+ }
+}
+
+@Composable
+private fun RecordingOverviewCard(
+ outputDirectory: String?,
+ availableBytes: Long?,
+ isWritable: Boolean,
+ activeCount: Int,
+ scheduledCount: Int
+) {
+ Surface(
+ modifier = Modifier.fillMaxWidth(),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(16.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(20.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Text(
+ text = stringResource(R.string.settings_recording_storage_title),
+ style = MaterialTheme.typography.titleSmall,
+ color = Primary
+ )
+ Text(
+ text = outputDirectory ?: stringResource(R.string.settings_recording_storage_unknown),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ SettingsOverviewStat(
+ label = stringResource(R.string.settings_recording_active_label),
+ value = activeCount.toString(),
+ modifier = Modifier.weight(1f)
+ )
+ SettingsOverviewStat(
+ label = stringResource(R.string.settings_recording_scheduled_label),
+ value = scheduledCount.toString(),
+ modifier = Modifier.weight(1f)
+ )
+ SettingsOverviewStat(
+ label = stringResource(R.string.settings_recording_space_label),
+ value = availableBytes?.let(::formatBytes) ?: stringResource(R.string.settings_recording_storage_unknown),
+ modifier = Modifier.weight(1f)
+ )
+ }
+ Text(
+ text = if (isWritable) stringResource(R.string.settings_recording_storage_ready) else stringResource(R.string.settings_recording_storage_unavailable),
+ style = MaterialTheme.typography.bodySmall,
+ color = if (isWritable) Primary else ErrorColor
+ )
+ }
+ }
+}
+
+@Composable
+private fun RecordingItemCard(
+ item: RecordingItem,
+ onStop: () -> Unit,
+ onCancel: () -> Unit
+) {
+ Surface(
+ modifier = Modifier.fillMaxWidth(),
+ colors = SurfaceDefaults.colors(containerColor = SurfaceElevated),
+ shape = RoundedCornerShape(12.dp)
+ ) {
+ Column(
+ modifier = Modifier.padding(16.dp),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(item.programTitle ?: item.channelName, style = MaterialTheme.typography.titleSmall, color = OnBackground)
+ Text(item.channelName, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim)
+ }
+ Text(
+ text = when (item.status) {
+ RecordingStatus.SCHEDULED -> stringResource(R.string.settings_recording_status_scheduled)
+ RecordingStatus.RECORDING -> stringResource(R.string.settings_recording_status_recording)
+ RecordingStatus.COMPLETED -> stringResource(R.string.settings_recording_status_completed)
+ RecordingStatus.FAILED -> stringResource(R.string.settings_recording_status_failed)
+ RecordingStatus.CANCELLED -> stringResource(R.string.settings_recording_status_cancelled)
+ },
+ style = MaterialTheme.typography.labelMedium,
+ color = when (item.status) {
+ RecordingStatus.RECORDING -> Primary
+ RecordingStatus.COMPLETED -> OnBackground
+ RecordingStatus.FAILED -> ErrorColor
+ RecordingStatus.CANCELLED -> OnSurfaceDim
+ RecordingStatus.SCHEDULED -> Secondary
+ }
+ )
+ }
+ Text(
+ text = stringResource(
+ R.string.settings_recording_time_window,
+ formatTimestamp(item.scheduledStartMs),
+ formatTimestamp(item.scheduledEndMs)
+ ),
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurface
+ )
+ item.failureReason?.takeIf { it.isNotBlank() }?.let { reason ->
+ Text(reason, style = MaterialTheme.typography.bodySmall, color = ErrorColor)
+ }
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ if (item.status == RecordingStatus.RECORDING) {
+ Surface(
+ onClick = onStop,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = ErrorColor.copy(alpha = 0.2f),
+ focusedContainerColor = ErrorColor.copy(alpha = 0.35f)
+ )
+ ) {
+ Text(
+ text = stringResource(R.string.settings_recording_stop),
+ color = ErrorColor,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
+ )
+ }
+ }
+ if (item.status == RecordingStatus.SCHEDULED) {
+ Surface(
+ onClick = onCancel,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceHighlight,
+ focusedContainerColor = Primary.copy(alpha = 0.2f)
+ )
+ ) {
+ Text(
+ text = stringResource(R.string.settings_recording_cancel),
+ color = OnBackground,
+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)
+ )
+ }
+ }
+ }
+ }
+ }
+}
+
+private fun formatBytes(bytes: Long): String {
+ if (bytes <= 0L) return "0 B"
+ val kb = 1024.0
+ val mb = kb * 1024.0
+ val gb = mb * 1024.0
+ return when {
+ bytes >= gb -> String.format(Locale.getDefault(), "%.1f GB", bytes / gb)
+ bytes >= mb -> String.format(Locale.getDefault(), "%.1f MB", bytes / mb)
+ bytes >= kb -> String.format(Locale.getDefault(), "%.1f KB", bytes / kb)
+ else -> "$bytes B"
+ }
+}
+
+private fun formatTimestamp(timestampMs: Long): String {
+ if (timestampMs <= 0L) return "--:--"
+ return java.text.SimpleDateFormat("MMM d, HH:mm", Locale.getDefault()).format(java.util.Date(timestampMs))
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
index 2405bd16..d9c8b5ec 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt
@@ -5,18 +5,26 @@ import androidx.lifecycle.viewModelScope
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.sync.SyncManager
import com.streamvault.data.sync.SyncRepairSection
+import com.streamvault.domain.manager.BackupConflictStrategy
+import com.streamvault.domain.manager.BackupImportPlan
+import com.streamvault.domain.manager.BackupManager
+import com.streamvault.domain.manager.BackupPreview
+import com.streamvault.domain.manager.RecordingManager
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.RecordingItem
+import com.streamvault.domain.model.RecordingStorageState
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.repository.SyncMetadataRepository
import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
-import com.streamvault.domain.manager.BackupManager
-
enum class ProviderWarningAction {
EPG,
MOVIES,
@@ -24,11 +32,14 @@ enum class ProviderWarningAction {
}
@HiltViewModel
+@OptIn(ExperimentalCoroutinesApi::class)
class SettingsViewModel @Inject constructor(
private val providerRepository: ProviderRepository,
private val preferencesRepository: PreferencesRepository,
private val backupManager: BackupManager,
- private val syncManager: SyncManager
+ private val recordingManager: RecordingManager,
+ private val syncManager: SyncManager,
+ private val syncMetadataRepository: SyncMetadataRepository
) : ViewModel() {
private val _uiState = MutableStateFlow(SettingsUiState())
@@ -55,6 +66,73 @@ class SettingsViewModel @Inject constructor(
}
}
}
+
+ viewModelScope.launch {
+ providerRepository.getProviders()
+ .flatMapLatest { providers ->
+ if (providers.isEmpty()) {
+ flowOf(emptyMap())
+ } else {
+ combine(
+ providers.map { provider ->
+ syncMetadataRepository.observeMetadata(provider.id).map { metadata ->
+ provider.id to ProviderDiagnosticsUiModel(
+ lastSyncStatus = metadata?.lastSyncStatus ?: "NONE",
+ lastLiveSync = metadata?.lastLiveSync ?: 0L,
+ lastMovieSync = metadata?.lastMovieSync ?: 0L,
+ lastSeriesSync = metadata?.lastSeriesSync ?: 0L,
+ lastEpgSync = metadata?.lastEpgSync ?: 0L,
+ liveCount = metadata?.liveCount ?: 0,
+ movieCount = metadata?.movieCount ?: 0,
+ seriesCount = metadata?.seriesCount ?: 0,
+ epgCount = metadata?.epgCount ?: 0,
+ capabilitySummary = buildCapabilitySummary(provider),
+ sourceLabel = when (provider.type) {
+ ProviderType.XTREAM_CODES -> "Xtream Codes"
+ ProviderType.M3U -> "M3U Playlist"
+ },
+ expirySummary = run {
+ val expirationDate = provider.expirationDate
+ when {
+ expirationDate == null -> "Expiry unknown"
+ expirationDate == Long.MAX_VALUE -> "No expiry reported"
+ expirationDate < System.currentTimeMillis() -> "Expired"
+ else -> "Active until ${java.text.SimpleDateFormat("d MMM yyyy", java.util.Locale.getDefault()).format(java.util.Date(expirationDate))}"
+ }
+ },
+ connectionSummary = "${provider.maxConnections} connection(s)",
+ archiveSummary = when (provider.type) {
+ ProviderType.XTREAM_CODES -> "Catch-up depends on provider archive flags and replay stream ids."
+ ProviderType.M3U -> if (provider.epgUrl.isBlank()) {
+ "M3U replay is limited without guide coverage."
+ } else {
+ "M3U replay depends on channel templates and guide alignment."
+ }
+ }
+ )
+ }
+ }
+ ) { pairs ->
+ pairs.toMap()
+ }
+ }
+ }
+ .collect { diagnosticsByProvider ->
+ _uiState.update { it.copy(diagnosticsByProvider = diagnosticsByProvider) }
+ }
+ }
+
+ viewModelScope.launch {
+ recordingManager.observeRecordingItems().collect { items ->
+ _uiState.update { it.copy(recordingItems = items.sortedByDescending(RecordingItem::scheduledStartMs)) }
+ }
+ }
+
+ viewModelScope.launch {
+ recordingManager.observeStorageState().collect { storage ->
+ _uiState.update { it.copy(recordingStorageState = storage) }
+ }
+ }
}
fun setActiveProvider(providerId: Long) {
@@ -188,28 +266,154 @@ class SettingsViewModel @Inject constructor(
}
}
- fun importConfig(uriString: String) {
+ fun inspectBackup(uriString: String) {
+ viewModelScope.launch {
+ _uiState.update { it.copy(isSyncing = true) }
+ val result = backupManager.inspectBackup(uriString)
+ _uiState.update { state ->
+ when (result) {
+ is Result.Error -> state.copy(
+ isSyncing = false,
+ userMessage = "Import failed: ${result.message}"
+ )
+ is Result.Success -> state.copy(
+ isSyncing = false,
+ pendingBackupUri = uriString,
+ backupPreview = result.data,
+ backupImportPlan = BackupImportPlan()
+ )
+ else -> state.copy(isSyncing = false)
+ }
+ }
+ }
+ }
+
+ fun dismissBackupPreview() {
+ _uiState.update {
+ it.copy(
+ backupPreview = null,
+ pendingBackupUri = null,
+ backupImportPlan = BackupImportPlan()
+ )
+ }
+ }
+
+ fun setBackupConflictStrategy(strategy: BackupConflictStrategy) {
+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(conflictStrategy = strategy)) }
+ }
+
+ fun setImportPreferences(enabled: Boolean) {
+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importPreferences = enabled)) }
+ }
+
+ fun setImportProviders(enabled: Boolean) {
+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importProviders = enabled)) }
+ }
+
+ fun setImportSavedLibrary(enabled: Boolean) {
+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importSavedLibrary = enabled)) }
+ }
+
+ fun setImportPlaybackHistory(enabled: Boolean) {
+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importPlaybackHistory = enabled)) }
+ }
+
+ fun setImportMultiViewPresets(enabled: Boolean) {
+ _uiState.update { it.copy(backupImportPlan = it.backupImportPlan.copy(importMultiViewPresets = enabled)) }
+ }
+
+ fun confirmBackupImport() {
+ val uriString = _uiState.value.pendingBackupUri ?: return
+ val plan = _uiState.value.backupImportPlan
viewModelScope.launch {
_uiState.update { it.copy(isSyncing = true) }
- val result = backupManager.importConfig(uriString)
+ val result = backupManager.importConfig(uriString, plan)
_uiState.update { state ->
+ val importedSummary = if (result is Result.Success) {
+ result.data.importedSections.joinToString().ifBlank { "Nothing imported" }
+ } else {
+ null
+ }
state.copy(
isSyncing = false,
userMessage = if (result is Result.Error)
"Import failed: ${result.message}"
- else "Configuration imported successfully"
+ else "Configuration imported: $importedSummary",
+ backupPreview = null,
+ pendingBackupUri = null,
+ backupImportPlan = BackupImportPlan()
)
}
}
}
+
+ fun stopRecording(recordingId: String) {
+ viewModelScope.launch {
+ val result = recordingManager.stopRecording(recordingId)
+ _uiState.update {
+ it.copy(userMessage = if (result is Result.Error) "Stop failed: ${result.message}" else "Recording stopped")
+ }
+ }
+ }
+
+ fun cancelRecording(recordingId: String) {
+ viewModelScope.launch {
+ val result = recordingManager.cancelRecording(recordingId)
+ _uiState.update {
+ it.copy(userMessage = if (result is Result.Error) "Cancel failed: ${result.message}" else "Recording cancelled")
+ }
+ }
+ }
+
+ private fun buildCapabilitySummary(provider: Provider): String {
+ return when (provider.type) {
+ ProviderType.XTREAM_CODES -> {
+ if (provider.epgUrl.isNotBlank()) {
+ "Xtream source with guide support. Catch-up is available when the provider exposes replay streams."
+ } else {
+ "Xtream source. Catch-up depends on provider replay support."
+ }
+ }
+ ProviderType.M3U -> {
+ if (provider.epgUrl.isNotBlank()) {
+ "M3U source with XMLTV guide. Archive support depends on provider stream templates."
+ } else {
+ "M3U source without guide URL. Guide and archive coverage may be limited."
+ }
+ }
+ }
+ }
}
+data class ProviderDiagnosticsUiModel(
+ val lastSyncStatus: String = "NONE",
+ val lastLiveSync: Long = 0L,
+ val lastMovieSync: Long = 0L,
+ val lastSeriesSync: Long = 0L,
+ val lastEpgSync: Long = 0L,
+ val liveCount: Int = 0,
+ val movieCount: Int = 0,
+ val seriesCount: Int = 0,
+ val epgCount: Int = 0,
+ val capabilitySummary: String = "",
+ val sourceLabel: String = "",
+ val expirySummary: String = "",
+ val connectionSummary: String = "",
+ val archiveSummary: String = ""
+)
+
data class SettingsUiState(
val providers: List<Provider> = emptyList(),
val activeProviderId: Long? = null,
val isSyncing: Boolean = false,
val userMessage: String? = null,
val syncWarningsByProvider: Map<Long, List<String>> = emptyMap(),
+ val diagnosticsByProvider: Map<Long, ProviderDiagnosticsUiModel> = emptyMap(),
val parentalControlLevel: Int = 0,
- val appLanguage: String = "system"
+ val appLanguage: String = "system",
+ val backupPreview: BackupPreview? = null,
+ val pendingBackupUri: String? = null,
+ val backupImportPlan: BackupImportPlan = BackupImportPlan(),
+ val recordingItems: List<RecordingItem> = emptyList(),
+ val recordingStorageState: RecordingStorageState = RecordingStorageState()
)
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 80f43fe6..66ae16c8 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -3,6 +3,7 @@
<string name="app_name">StreamVault</string>
<!-- Navigation -->
+ <string name="nav_home">Home</string>
<string name="nav_live_tv">Live TV</string>
<string name="nav_movies">Movies</string>
<string name="nav_series">Series</string>
@@ -21,30 +22,79 @@
<string name="home_categories_title">Categories</string>
<string name="home_search_categories">Search categories...</string>
<string name="home_all_channels">All Channels</string>
+ <string name="home_recent_channels">Recent</string>
+ <string name="home_last_channel">Last Channel</string>
+ <string name="home_last_channel_label">Last: %1$s</string>
+ <string name="home_last_group">Last Group</string>
+ <string name="home_last_group_label">Last: %1$s</string>
<string name="home_search_channels">Search channels...</string>
<string name="home_loading">Loading...</string>
<string name="home_no_channels_found">No channels found in this category</string>
<string name="home_add_favorites_hint">Add channels to favorites to see them here</string>
+ <string name="home_recent_channels_hint">Watch a few live channels to build a recent list here</string>
+ <string name="home_saved_subtitle">Favorites and custom live groups</string>
+ <string name="home_saved_empty_hint">Favorite a channel or add it to a custom live group to pin it here.</string>
<string name="home_delete_group_title">Delete Group?</string>
<string name="home_delete_group_body">Are you sure you want to delete \'%1$s\'? This will remove all channels from this group.</string>
<string name="home_delete_group_confirm">Delete</string>
<string name="home_delete_group_cancel">Cancel</string>
+ <string name="home_group_created">Group \'%1$s\' created</string>
+ <string name="home_group_renamed">Renamed group to %1$s</string>
+ <string name="home_group_deleted">Group \'%1$s\' deleted</string>
+ <string name="home_group_name_reserved">Cannot create group named \'Favorites\'</string>
+ <string name="home_group_name_duplicate">Group \'%1$s\' already exists</string>
+ <string name="home_group_name_invalid">Enter a group name</string>
+
+ <!-- Dashboard -->
+ <string name="dashboard_title">Your Library, Ready</string>
+ <string name="dashboard_subtitle">%1$s is active. Jump back into live, catch up on progress, or browse fresh additions.</string>
+ <string name="dashboard_favorite_channels">Favorite Channels</string>
+ <string name="dashboard_recent_channels">Recent Channels</string>
+ <string name="dashboard_recent_movies">Recently Added Movies</string>
+ <string name="dashboard_recent_series">Recently Updated Series</string>
+ <string name="dashboard_search_library">Search Library</string>
+ <string name="dashboard_live_shortcuts">Live Shortcuts</string>
+ <string name="dashboard_live_shortcuts_subtitle">Return to saved groups, recent channels, and your last live context.</string>
+ <string name="dashboard_provider_health_title">Provider Health</string>
+ <string name="dashboard_provider_status">Status</string>
+ <string name="dashboard_provider_source">Source</string>
+ <string name="dashboard_provider_connections">Connections</string>
+ <string name="dashboard_provider_xtream">Xtream Codes</string>
+ <string name="dashboard_provider_m3u">M3U Playlist</string>
+ <string name="dashboard_provider_no_sync">No recent sync</string>
+ <string name="dashboard_provider_synced_at">Synced %1$s</string>
+ <string name="dashboard_provider_expires_at">Expires %1$s</string>
+ <string name="dashboard_provider_no_expiry">No expiry reported</string>
+ <string name="dashboard_warning_title">Provider Needs Attention</string>
+ <string name="dashboard_warning_review">Open Diagnostics</string>
+ <string name="dashboard_updated_series_badge">Updated series</string>
+ <string name="dashboard_stat_live">%1$d live</string>
+ <string name="dashboard_stat_favorites">%1$d favorites</string>
+ <string name="dashboard_stat_recent">%1$d recent</string>
+ <string name="dashboard_stat_resume">%1$d to resume</string>
+ <string name="dashboard_stat_movies">%1$d movies</string>
+ <string name="dashboard_stat_series">%1$d series</string>
+ <string name="dashboard_empty_title">Set up a provider to unlock the home screen</string>
+ <string name="dashboard_empty_body">Add a playlist or Xtream source first. Once a provider is active, Home will surface favorite channels, continue watching, and fresh library rows.</string>
<!-- Dialogs -->
<string name="pin_dialog_title">Enter PIN</string>
<string name="pin_dialog_cancel">Cancel</string>
<string name="category_options_set_default">Set as Default Group</string>
+ <string name="category_options_rename">Rename Group</string>
<string name="category_options_unlock">Unlock Group</string>
<string name="category_options_lock">Lock Group</string>
<string name="category_options_delete">Delete Group</string>
<string name="category_options_cancel">Cancel</string>
+ <string name="category_options_reorder">Reorder Items</string>
<string name="add_group_manage_title">Manage: %1$s</string>
<string name="add_group_close_cd">Close</string>
<string name="add_group_name_hint">Group Name</string>
<string name="add_group_cancel">Cancel</string>
<string name="add_group_create">Create</string>
+ <string name="add_group_rename">Rename</string>
<string name="add_group_remove_favorites">Remove from Favorites</string>
<string name="add_group_add_favorites">Add to Favorites</string>
<string name="add_group_reorder_title">Reorder</string>
@@ -69,24 +119,82 @@
<string name="movies_incorrect_pin">Incorrect PIN</string>
<string name="movies_loading">Loading movies...</string>
<string name="movies_no_found">No movies found</string>
+ <string name="movies_categories_title">Categories</string>
+ <string name="movies_all_categories">All Categories</string>
+ <string name="movies_search_placeholder">Search movies...</string>
+ <string name="movies_group_created">Created group %1$s</string>
+ <string name="movies_group_renamed">Renamed group to %1$s</string>
+ <string name="movies_group_deleted">Deleted group %1$s</string>
+ <string name="movies_group_name_invalid">Enter a group name</string>
+ <string name="movies_group_name_reserved">Favorites is reserved</string>
+ <string name="movies_group_name_duplicate">A movie group with that name already exists</string>
+ <string name="movies_saved_empty_hint">Favorite a movie or add it to a custom group to see it here.</string>
+ <string name="movies_filter_subtitle">Refine the selected movie category without rebuilding the whole library.</string>
+ <string name="movies_library_lens_subtitle">Surface favorites, in-progress, top-rated, and fresh movies across the whole library.</string>
+ <string name="library_full_browse_title_movies">Browse Full Movie Library</string>
+ <string name="library_full_browse_subtitle">%1$d titles available in the current provider</string>
<!-- Series -->
<string name="series_incorrect_pin">Incorrect PIN</string>
<string name="series_loading">Loading series...</string>
<string name="series_no_found">No series found</string>
+ <string name="series_categories_title">Categories</string>
+ <string name="series_all_categories">All Categories</string>
+ <string name="series_search_placeholder">Search series...</string>
+ <string name="series_group_created">Created group %1$s</string>
+ <string name="series_group_renamed">Renamed group to %1$s</string>
+ <string name="series_group_deleted">Deleted group %1$s</string>
+ <string name="series_group_name_invalid">Enter a group name</string>
+ <string name="series_group_name_reserved">Favorites is reserved</string>
+ <string name="series_group_name_duplicate">A series group with that name already exists</string>
+ <string name="series_saved_empty_hint">Favorite a series or add it to a custom group to see it here.</string>
+ <string name="series_filter_subtitle">Pivot between saved, in-progress, updated, and highly rated series.</string>
+ <string name="series_library_lens_subtitle">Surface favorites, in-progress, top-rated, and fresh series across the whole library.</string>
+ <string name="library_full_browse_title_series">Browse Full Series Library</string>
+
+ <string name="library_saved_title">Saved</string>
+ <string name="library_saved_subtitle">Favorites and custom groups</string>
+ <string name="library_saved_items_count">%1$d items</string>
+ <string name="library_saved_active_title">Saved Group</string>
+ <string name="library_saved_active_summary">%1$d items in this saved view</string>
+ <string name="library_saved_manage_action">Manage</string>
+ <string name="library_saved_primary_hint">Return to the full library</string>
+ <string name="library_saved_manage_hint">Hold a saved group for options</string>
+ <string name="library_browse_all">Browse All</string>
+ <string name="library_lens_title">Library Lens</string>
+ <string name="library_lens_favorites">Saved Favorites</string>
+ <string name="library_lens_continue">Continue Watching</string>
+ <string name="library_lens_top_rated">Top Rated</string>
+ <string name="library_lens_fresh_movies">Newest Movies</string>
+ <string name="library_lens_fresh_series">Recently Updated</string>
+ <string name="library_filter_title">Filter Library</string>
+ <string name="library_sort_title">Sort Results</string>
+ <string name="library_filter_results">Showing %1$d of %2$d items</string>
+ <string name="library_filter_empty">No items match this filter.</string>
+ <string name="library_loaded_results">Loaded %1$d of %2$d items</string>
+ <string name="library_load_more">Load more (%1$d/%2$d)</string>
+ <string name="library_sort_library">Library Order</string>
+ <string name="library_sort_az">A-Z</string>
+ <string name="library_sort_release">Newest</string>
+ <string name="library_sort_updated">Recently Updated</string>
+ <string name="library_sort_rating">Rating</string>
<!-- Settings -->
<string name="settings_title">Settings</string>
<string name="settings_providers">Providers</string>
<string name="settings_no_providers">No providers configured</string>
<string name="settings_add_provider">Add Provider</string>
+ <string name="settings_providers_subtitle">Switch, sync, edit, and troubleshoot your IPTV sources.</string>
<string name="settings_parental_control">Parental Control</string>
+ <string name="settings_parental_subtitle">Protect adult or sensitive content with TV-friendly controls.</string>
<string name="settings_playback">Playback</string>
+ <string name="settings_playback_subtitle">Tune decoder and buffering behavior for smoother playback.</string>
<string name="settings_decoder_mode">Decoder Mode</string>
<string name="settings_decoder_auto">Auto (HW preferred)</string>
<string name="settings_buffer_duration">Buffer Duration</string>
<string name="settings_buffer_5s">5 seconds</string>
<string name="settings_about">About</string>
+ <string name="settings_about_subtitle">Version, build, and support details for this installation.</string>
<string name="settings_app_version">App Version</string>
<string name="settings_build">Build</string>
<string name="settings_build_desc">StreamVault for Android TV</string>
@@ -119,29 +227,153 @@
<string name="settings_pc_btn">Parental Control</string>
<string name="settings_active">ACTIVE</string>
<string name="settings_language">Language</string>
+ <string name="settings_language_subtitle">Choose the app language without leaving the TV interface.</string>
<string name="settings_app_language">App Language</string>
<string name="settings_system_default">System Default</string>
<string name="settings_select_language">Select Language</string>
<string name="settings_backup_restore">Backup &amp; Restore</string>
+ <string name="settings_backup_subtitle">Export or import favorites, groups, and preferences.</string>
<string name="settings_backup_data">Export Data</string>
<string name="settings_restore_data">Import Data</string>
+ <string name="settings_backup_preview_title">Review Backup Import</string>
+ <string name="settings_backup_preview_subtitle">Backup version %1$d detected. Choose what to import before making changes.</string>
+ <string name="settings_backup_conflict_strategy">Conflict strategy</string>
+ <string name="settings_backup_keep_existing">Keep Existing</string>
+ <string name="settings_backup_replace_existing">Replace Existing</string>
+ <string name="settings_backup_import_sections">Import sections</string>
+ <string name="settings_backup_import_confirm">Import Backup</string>
+ <string name="settings_backup_section_preferences">Preferences</string>
+ <string name="settings_backup_section_providers">Providers</string>
+ <string name="settings_backup_section_saved">Saved Library</string>
+ <string name="settings_backup_section_history">Playback History</string>
+ <string name="settings_backup_section_multiview">Split Screen Presets</string>
+ <string name="settings_backup_conflict_count">%1$d conflicts</string>
+ <string name="settings_backup_no_conflicts">No conflicts</string>
+ <string name="settings_backup_item_count">%1$d items</string>
+ <string name="settings_provider_warnings">Warnings: %1$s</string>
+ <string name="settings_provider_diagnostics_title">Provider Diagnostics</string>
+ <string name="settings_diagnostic_live">Live</string>
+ <string name="settings_diagnostic_movies">Movies</string>
+ <string name="settings_diagnostic_series">Series</string>
+ <string name="settings_diagnostic_epg">EPG</string>
+ <string name="settings_diagnostic_status">Last sync status: %1$s</string>
+ <string name="settings_diagnostic_never">Never</string>
+ <string name="settings_diagnostic_items">%1$d items</string>
+ <string name="settings_retry_epg">Retry EPG</string>
+ <string name="settings_retry_movies">Retry Movies</string>
+ <string name="settings_retry_series">Retry Series</string>
+ <string name="settings_status_active">Active</string>
+ <string name="settings_status_partial">Partial</string>
+ <string name="settings_status_error">Error</string>
+ <string name="settings_status_expired">Expired</string>
+ <string name="settings_status_disabled">Disabled</string>
+ <string name="settings_status_unknown">Unknown</string>
+ <string name="settings_overview_title">Control Center</string>
+ <string name="settings_overview_subtitle">Review your provider, protection, and playback setup at a glance.</string>
+ <string name="settings_overview_provider_label">Provider</string>
+ <string name="settings_overview_count_label">Sources</string>
+ <string name="settings_overview_protection_label">Protection</string>
+ <string name="settings_overview_language_label">Language</string>
+ <string name="settings_overview_no_provider">No active provider</string>
+ <string name="settings_no_providers_subtitle">Add a provider to unlock playback, guide data, and the rest of the TV experience.</string>
+ <string name="settings_recording_title">Recording</string>
+ <string name="settings_recording_subtitle">Manage local live DVR jobs, storage, and scheduled captures.</string>
+ <string name="settings_recording_storage_title">Recording Storage</string>
+ <string name="settings_recording_storage_unknown">Storage unavailable</string>
+ <string name="settings_recording_storage_ready">Storage ready for local live recording</string>
+ <string name="settings_recording_storage_unavailable">Storage is not writable for recording</string>
+ <string name="settings_recording_active_label">Active</string>
+ <string name="settings_recording_scheduled_label">Scheduled</string>
+ <string name="settings_recording_space_label">Free Space</string>
+ <string name="settings_recording_empty_title">No active recordings</string>
+ <string name="settings_recording_empty_subtitle">Start a manual recording from live playback or schedule one from the player.</string>
+ <string name="settings_recording_status_scheduled">Scheduled</string>
+ <string name="settings_recording_status_recording">Recording</string>
+ <string name="settings_recording_status_completed">Completed</string>
+ <string name="settings_recording_status_failed">Failed</string>
+ <string name="settings_recording_status_cancelled">Cancelled</string>
+ <string name="settings_recording_time_window">%1$s → %2$s</string>
+ <string name="settings_recording_stop">Stop</string>
+ <string name="settings_recording_cancel">Cancel</string>
<!-- Favorites -->
- <string name="favorites_loading">Loading favorites...</string>
- <string name="favorites_no_favorites">No favorites yet</string>
- <string name="favorites_empty_hint">Long-press on any channel, movie, or series to add it to favorites</string>
+ <string name="favorites_title">Saved Library</string>
+ <string name="favorites_loading">Loading saved library...</string>
+ <string name="favorites_no_favorites">Saved library is empty</string>
+ <string name="favorites_empty_hint">Long-press on any channel, movie, or series to build your saved library</string>
+ <string name="favorites_overview_title">Saved Library Overview</string>
+ <string name="favorites_overview_subtitle">%1$d saved items across %2$d custom groups.</string>
+ <string name="favorites_continue_title">Continue Watching</string>
+ <string name="favorites_continue_subtitle">Pick up unfinished movies and series from the saved hub.</string>
+ <string name="favorites_recent_live_title">Recent Live</string>
+ <string name="favorites_recent_live_subtitle">Jump back into recently watched live channels with one click.</string>
+ <string name="favorites_continue_short">Resume</string>
+ <string name="favorites_recent_short">Recent</string>
+ <string name="favorites_filters_title">Browse by type</string>
+ <string name="favorites_filters_subtitle">Narrow the hub to the content you want to revisit.</string>
+ <string name="saved_preset_title">Saved views</string>
+ <string name="saved_preset_subtitle">Jump between watch-next, live recall, type-focused, and custom-group views.</string>
+ <string name="saved_scope_title">Provider scope</string>
+ <string name="saved_scope_subtitle">Filter the saved hub to %1$s or broaden it across every provider already loaded in the app.</string>
+ <string name="saved_scope_current_provider">Current Provider</string>
+ <string name="saved_scope_current_provider_hint">Keep Saved focused on the active provider</string>
+ <string name="saved_scope_all_providers">All Providers</string>
+ <string name="saved_scope_all_providers_hint">Browse saved items across every imported provider</string>
+ <string name="saved_preset_all_saved">All Saved</string>
+ <string name="saved_preset_home_shelf">Home Shelf</string>
+ <string name="saved_preset_home_shelf_global_title">Home Favorites</string>
+ <string name="saved_preset_home_shelf_global_subtitle">Live favorites that are eligible for the Home dashboard</string>
+ <string name="saved_preset_watch_next">Watch Next</string>
+ <string name="saved_preset_live_recall">Live Recall</string>
+ <string name="saved_preset_custom_groups">Custom Groups</string>
+ <string name="saved_group_manage_title">Manage Custom Groups</string>
+ <string name="saved_group_manage_subtitle">Open a group or hold it for merge, delete, reorder, and Home priority actions.</string>
+ <string name="saved_group_manage_count">%1$d items</string>
+ <string name="saved_group_manage_promoted">Pinned to Home • %1$d items</string>
+ <string name="saved_group_promote_home">Pin to Home</string>
+ <string name="saved_group_demote_home">Remove from Home</string>
+ <string name="saved_group_merge">Merge into Another Group</string>
+ <string name="saved_group_merge_title">Merge %1$s Into…</string>
+ <string name="saved_group_delete_empty">Delete Empty Group</string>
+ <string name="saved_item_remove_saved">Remove from Saved</string>
+ <string name="saved_item_remove_group">Remove from This Group</string>
+ <string name="saved_item_move_to">Move to %1$s</string>
+ <string name="favorites_sort_title">Sort saved library</string>
+ <string name="favorites_sort_subtitle">Switch between manual order, recent activity, and title browsing.</string>
+ <string name="favorites_sort_default">Manual</string>
+ <string name="favorites_sort_default_hint">Use your saved and group order</string>
+ <string name="favorites_sort_recent">Recent</string>
+ <string name="favorites_sort_recent_hint">Bring recently watched items forward</string>
+ <string name="favorites_sort_title_alpha">A-Z</string>
+ <string name="favorites_sort_title_hint">Alphabetical browsing across sections</string>
+ <string name="favorites_jump_title">Jump to a section</string>
+ <string name="favorites_jump_subtitle">Shortcut directly to the saved group or system section you need.</string>
<string name="favorites_reordering">Reordering</string>
+ <string name="favorites_reorder_mode">Reorder mode</string>
+ <string name="favorites_move_up">Up or Left: move earlier</string>
+ <string name="favorites_move_down">Down or Right: move later</string>
+ <string name="favorites_confirm">Center: save order</string>
+ <string name="favorites_cancel">Back: cancel</string>
<!-- Search -->
+ <string name="search_title">Search</string>
<string name="search_incorrect_pin">Incorrect PIN</string>
<string name="search_type_to_search">Type to search...</string>
<string name="search_no_results">No results found for \'%1$s\'</string>
+ <string name="search_no_results_title">No matches</string>
+ <string name="search_ready_title">Search the library</string>
+ <string name="search_no_provider_title">No active provider</string>
+ <string name="search_no_provider_subtitle">Add or activate a provider before searching the library.</string>
+ <string name="search_results_title">%1$d results</string>
+ <string name="search_results_count">%1$s %2$d</string>
<string name="search_live_tv">Live TV</string>
<string name="search_all">All</string>
<string name="search_movies">Movies</string>
<string name="search_series">Series</string>
<string name="search_hint">Search...</string>
+ <string name="search_recent_title">Recent Searches</string>
+ <string name="search_clear_history">Clear</string>
<!-- Provider Setup -->
<string name="setup_title_streamvault">StreamVault</string>
@@ -176,7 +408,13 @@
<string name="player_error_decoder">Unable to play this format — try changing decoder mode in Settings</string>
<string name="player_error_unknown">Unknown playback error</string>
<string name="player_retry">Retry</string>
+ <string name="player_last_channel_action">Last Channel</string>
+ <string name="player_try_alternate_stream">Alternate Stream</string>
+ <string name="player_open_guide_action">Open Guide</string>
<string name="player_error_back">Or press Back to return</string>
+ <string name="player_error_live_hint">Retry, jump back to the last channel, or press Back to leave playback.</string>
+ <string name="player_channel_list_hint">Select a channel to tune instantly. Back closes the list.</string>
+ <string name="player_epg_overlay_hint">Browse upcoming programs here. Select an archive-ready item to start catch-up.</string>
<string name="player_type_movie">Movie</string>
<string name="player_type_series">Series</string>
<string name="player_close">Close</string>
@@ -185,6 +423,13 @@
<string name="player_next">NEXT</string>
<string name="player_restart">Restart</string>
<string name="player_archive">Archive</string>
+ <string name="player_record">Record</string>
+ <string name="player_stop_recording">Stop Recording</string>
+ <string name="player_schedule_recording">Schedule</string>
+ <string name="player_recording_started">Recording started for %1$s.</string>
+ <string name="player_recording_stopped">Recording stopped.</string>
+ <string name="player_recording_scheduled">Recording scheduled for %1$s.</string>
+ <string name="player_recording_missing_context">Recording needs a valid live channel context.</string>
<string name="player_subs">Subs</string>
<string name="player_audio">Audio</string>
<string name="player_resume_title">Resume Playback</string>
@@ -199,6 +444,9 @@
<string name="player_selected">Selected</string>
<string name="player_channel_list_title">Channels (%1$d)</string>
<string name="player_channel_selected">Now</string>
+ <string name="player_recent_channels">Recent</string>
+ <string name="player_last_group_label">Last: %1$s</string>
+ <string name="player_last_group_hint">Jump back to the last live group you were browsing.</string>
<string name="player_archive_badge">ARCHIVE</string>
<string name="player_catchup_badge">CATCH-UP</string>
<string name="player_time_range_minutes">%1$s - %2$s | %3$d min</string>
@@ -206,10 +454,100 @@
<string name="player_full_epg">Full EPG</string>
<string name="player_stats">Stats</string>
<string name="player_minutes_remaining">%1$d min remaining</string>
+ <string name="epg_loading">Loading TV guide...</string>
+ <string name="epg_error">Unable to load the TV guide right now.</string>
+ <string name="epg_no_provider">Add or activate a provider to view the TV guide.</string>
+ <string name="epg_no_schedule">No schedule data available</string>
+ <string name="epg_watch_live">Watch Live</string>
+ <string name="epg_watch_archive">Play Catch-up</string>
+ <string name="epg_filter_label">Guide Filter</string>
+ <string name="epg_time_controls">Guide Window</string>
+ <string name="epg_day_selector_label">Browse by day</string>
+ <string name="epg_previous_day">Prev Day</string>
+ <string name="epg_page_back">Page -</string>
+ <string name="epg_jump_back_half_hour">-30m</string>
+ <string name="epg_jump_back">-3h</string>
+ <string name="epg_jump_now">Now</string>
+ <string name="epg_jump_forward_half_hour">+30m</string>
+ <string name="epg_jump_forward">+3h</string>
+ <string name="epg_page_forward">Page +</string>
+ <string name="epg_jump_prime_time">Prime Time</string>
+ <string name="epg_jump_tomorrow">Tomorrow</string>
+ <string name="epg_next_day">Next Day</string>
+ <string name="epg_day_yesterday">Yesterday</string>
+ <string name="epg_day_today">Today</string>
+ <string name="epg_day_tomorrow">Tomorrow</string>
+ <string name="epg_mode_label">Guide mode</string>
+ <string name="epg_mode_subtitle">Switch between broad browsing, anchor-time browsing, and archive-friendly rows.</string>
+ <string name="epg_favorites_filter_title">Guide source</string>
+ <string name="epg_favorites_filter_subtitle">Keep the guide on all channels or your live favorites only.</string>
+ <string name="epg_favorites_filter_all">All Channels</string>
+ <string name="epg_favorites_filter_all_hint">Browse the full live lineup</string>
+ <string name="epg_favorites_filter_favorites">Favorites Only</string>
+ <string name="epg_favorites_filter_favorites_hint">Stay on your pinned live channels</string>
+ <string name="epg_mode_all">Timeline</string>
+ <string name="epg_mode_all_hint">All visible rows</string>
+ <string name="epg_mode_anchored">At Selected Time</string>
+ <string name="epg_mode_anchored_hint">Only channels airing at the current guide anchor</string>
+ <string name="epg_mode_archive">Archive Ready</string>
+ <string name="epg_mode_archive_hint">Channels with catch-up or archive entries</string>
+ <string name="epg_density_label">Guide layout</string>
+ <string name="epg_density_subtitle">Choose how much guide detail fits on screen.</string>
+ <string name="epg_density_compact">Compact</string>
+ <string name="epg_density_compact_hint">Fits more channels on screen</string>
+ <string name="epg_density_comfortable">Comfortable</string>
+ <string name="epg_density_comfortable_hint">Balanced for everyday browsing</string>
+ <string name="epg_density_cinematic">Cinematic</string>
+ <string name="epg_density_cinematic_hint">Larger rows for distant viewing</string>
+ <string name="epg_view_options_label">Guide view</string>
+ <string name="epg_view_scheduled_only_on">Scheduled only</string>
+ <string name="epg_view_scheduled_only_off">All loaded channels</string>
+ <string name="epg_view_scheduled_only_hint">Hide channels with no guide data</string>
+ <string name="epg_showing_channels">Showing %1$d of %2$d channels</string>
+ <string name="epg_schedule_summary">Guide data available on %1$d of %2$d channels</string>
+ <string name="epg_window_label">%1$s - %2$s</string>
+ <string name="epg_timeline_label">Timeline</string>
+ <string name="epg_now_marker">Now %1$s</string>
+ <string name="epg_outside_window">Now outside loaded window</string>
+ <string name="epg_timeline_range_label">%1$s window</string>
+ <string name="epg_stale_warning">Guide data looks incomplete or stale for this selection.</string>
+ <string name="epg_updated_now">Updated just now</string>
+ <string name="epg_updated_minutes_ago">Updated %1$d min ago</string>
+ <string name="epg_retry">Retry</string>
+ <string name="epg_retry_hint">Try again or switch to another category.</string>
+ <string name="epg_no_channels_in_category">No channels found in this guide category</string>
+ <string name="epg_no_scheduled_channels">No channels with guide data in this selection</string>
+ <string name="epg_scheduled_only_hint">Turn off Scheduled only or switch to another category.</string>
+ <string name="epg_filter_hint">Choose another category or refresh the guide.</string>
<string name="epg_title">TV Guide</string>
<string name="epg_catchup_available">Catch-up available (%1$d days)</string>
+ <string name="epg_archive_ready_hint">Archive or catch-up playback should be available for this program.</string>
+ <string name="epg_archive_provider_hint">This provider supports catch-up for the channel, but this program is not marked archive-ready in the current guide window.</string>
+ <string name="epg_archive_unavailable_hint">Archive playback is not available for this channel.</string>
+ <string name="epg_archive_stale_hint">Guide data looks stale, so replay availability may be incomplete until the guide refreshes.</string>
+ <string name="epg_refresh_guide">Refresh Guide</string>
<string name="epg_upcoming_schedule">Upcoming Schedule</string>
+ <string name="epg_minutes_remaining">%1$d min left</string>
<string name="epg_no_info">No EPG information</string>
+ <string name="epg_favorite_badge">Favorite</string>
+ <string name="epg_program_channel_label">Channel</string>
+ <string name="epg_program_provider_label">Provider</string>
+ <string name="epg_program_provider_type_label">Source</string>
+ <string name="epg_program_language_label">Language</string>
+ <string name="epg_program_status_title">Replay Status</string>
+ <string name="epg_program_replay_label">Replay</string>
+ <string name="epg_program_progress_label">Progress</string>
+ <string name="epg_program_unknown_value">Unknown</string>
+ <string name="epg_program_replay_ready">Archive-ready</string>
+ <string name="epg_program_replay_partial">Provider catch-up only</string>
+ <string name="epg_program_replay_unavailable">Unavailable</string>
+ <string name="epg_program_progress_value">%1$d%% complete • %2$s</string>
+ <string name="epg_provider_troubleshooting_title">Provider Troubleshooting</string>
+ <string name="epg_provider_troubleshooting_no_archive">This channel is not flagged as archive-ready by the provider.</string>
+ <string name="epg_provider_troubleshooting_missing_template">Replay may fail because the provider exposed catch-up support without a usable replay template.</string>
+ <string name="epg_provider_troubleshooting_missing_stream_id">Replay may fail because the provider did not expose a replay stream identifier.</string>
+ <string name="epg_provider_troubleshooting_ready">Replay metadata is present, but the provider may still reject this specific program window.</string>
+ <string name="epg_provider_troubleshooting_stale">Guide freshness is low, so replay mapping may still be incomplete until the guide refreshes.</string>
<!-- Parental Control Group -->
<string name="parental_group_title">Protected Groups</string>
@@ -236,4 +574,30 @@
<string name="multiview_empty_slot">Empty Slot</string>
<string name="multiview_stream_error">Stream Error</string>
<string name="multiview_nav">Split Screen</string>
+ <string name="multiview_focused_prefix">Focused: %1$s</string>
+ <string name="multiview_preset_label">Preset %1$d</string>
+ <string name="multiview_preset_save">Save %1$d</string>
+ <string name="multiview_audio_badge">Audio</string>
+ <string name="multiview_audio_pinned_badge">Audio Pinned</string>
+ <string name="multiview_replace_slot">Replace Slot</string>
+ <string name="multiview_remove_slot">Remove Slot</string>
+ <string name="multiview_pin_audio">Pin Audio</string>
+ <string name="multiview_audio_follow_focus">Follow Focus</string>
+ <string name="multiview_replace_title">Replace Focused Slot</string>
+ <string name="multiview_replace_empty">Use Live TV favorites or recent channels first so replacement choices appear here.</string>
+ <string name="multiview_policy_summary">%1$s tier • %2$d active slot(s)</string>
+ <string name="multiview_policy_auto">Auto</string>
+ <string name="multiview_policy_conservative">Conservative</string>
+ <string name="multiview_policy_balanced">Balanced</string>
+ <string name="multiview_policy_maximum">Maximum</string>
+ <string name="multiview_policy_blocked">Standby Slot</string>
+ <string name="multiview_telemetry_snapshot">%1$d active • %2$d standby • %3$d buffering • %4$d errors</string>
+ <string name="multiview_telemetry_detail">%1$d dropped total • +%2$d recent • load %3$d • %4$s thermal</string>
+ <string name="multiview_thermal_unknown">Unknown</string>
+ <string name="multiview_thermal_normal">Normal</string>
+ <string name="multiview_thermal_light">Light</string>
+ <string name="multiview_thermal_moderate">Moderate</string>
+ <string name="multiview_thermal_severe">Severe</string>
+ <string name="multiview_thermal_critical">Critical</string>
+ <string name="multiview_low_memory_warning">Memory pressure is high. Extra slots stay in standby until playback stabilizes.</string>
</resources>
diff --git a/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt b/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt
new file mode 100644
index 00000000..3db949af
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt
@@ -0,0 +1,151 @@
+package com.streamvault.app.navigation
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.repository.ChannelRepository
+import org.junit.Test
+
+class RoutesTest {
+
+ @Test
+ fun `liveTv route supports category deep links`() {
+ assertThat(Routes.liveTv()).isEqualTo(Routes.LIVE_TV)
+ assertThat(Routes.liveTv(42L)).isEqualTo("${Routes.LIVE_TV}?categoryId=42")
+ }
+
+ @Test
+ fun `livePlayer preserves playback context`() {
+ val route = Routes.livePlayer(
+ channel = Channel(
+ id = 42L,
+ name = "News HD",
+ streamUrl = "https://example.com/live.m3u8",
+ epgChannelId = "news.hd",
+ categoryId = 9L,
+ providerId = 7L
+ ),
+ categoryId = 9L,
+ providerId = 7L,
+ isVirtual = false
+ )
+
+ assertThat(route).contains("internalId=42")
+ assertThat(route).contains("categoryId=9")
+ assertThat(route).contains("providerId=7")
+ assertThat(route).contains("channelId=news.hd")
+ assertThat(route).contains("contentType=LIVE")
+ assertThat(route).contains("isVirtual=false")
+ }
+
+ @Test
+ fun `livePlayer falls back to all channels when category is missing`() {
+ val route = Routes.livePlayer(
+ channel = Channel(
+ id = 8L,
+ name = "Sports",
+ streamUrl = "https://example.com/sports.m3u8",
+ providerId = 3L
+ ),
+ categoryId = null,
+ providerId = 3L
+ )
+
+ assertThat(route).contains("categoryId=${ChannelRepository.ALL_CHANNELS_ID}")
+ assertThat(route).contains("providerId=3")
+ }
+
+ @Test
+ fun `moviePlayer preserves provider and category context`() {
+ val route = Routes.moviePlayer(
+ Movie(
+ id = 15L,
+ name = "Film",
+ streamUrl = "https://example.com/movie.mp4",
+ categoryId = 21L,
+ providerId = 5L
+ )
+ )
+
+ assertThat(route).contains("internalId=15")
+ assertThat(route).contains("categoryId=21")
+ assertThat(route).contains("providerId=5")
+ assertThat(route).contains("contentType=MOVIE")
+ }
+
+ @Test
+ fun `episodePlayer preserves episode playback context`() {
+ val route = Routes.episodePlayer(
+ Episode(
+ id = 33L,
+ title = "Pilot",
+ episodeNumber = 1,
+ seasonNumber = 1,
+ streamUrl = "https://example.com/episode.mp4",
+ providerId = 11L
+ )
+ )
+
+ assertThat(route).contains("internalId=33")
+ assertThat(route).contains("providerId=11")
+ assertThat(route).contains("contentType=SERIES_EPISODE")
+ }
+
+ @Test
+ fun `player route supports archive playback context`() {
+ val route = Routes.player(
+ streamUrl = "https://example.com/live.m3u8",
+ title = "News HD",
+ internalId = 42L,
+ providerId = 7L,
+ contentType = "LIVE",
+ archiveStartMs = 1_700_000_000_000L,
+ archiveEndMs = 1_700_000_360_000L,
+ archiveTitle = "News HD: Morning Show"
+ )
+
+ assertThat(route).contains("archiveStartMs=1700000000000")
+ assertThat(route).contains("archiveEndMs=1700000360000")
+ assertThat(route).contains("archiveTitle=News+HD%3A+Morning+Show")
+ }
+
+ @Test
+ fun `epg route preserves guide context`() {
+ val route = Routes.epg(
+ categoryId = 21L,
+ anchorTime = 1_700_000_000_000L,
+ favoritesOnly = true
+ )
+
+ assertThat(route).isEqualTo(
+ "epg?categoryId=21&anchorTime=1700000000000&favoritesOnly=true"
+ )
+ }
+
+ @Test
+ fun `player route preserves return route back to guide`() {
+ val returnRoute = Routes.epg(
+ categoryId = 9L,
+ anchorTime = 1_700_000_360_000L,
+ favoritesOnly = false
+ )
+ val route = Routes.livePlayer(
+ channel = Channel(
+ id = 42L,
+ name = "News HD",
+ streamUrl = "https://example.com/live.m3u8",
+ epgChannelId = "news.hd",
+ categoryId = 9L,
+ providerId = 7L
+ ),
+ categoryId = 9L,
+ providerId = 7L,
+ returnRoute = returnRoute
+ )
+
+ assertThat(route).contains(
+ "returnRoute=epg%3FcategoryId%3D9%26anchorTime%3D1700000360000%26favoritesOnly%3Dfalse"
+ )
+ }
+}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
index e7f3eb0e..e7e6fbd9 100644
--- a/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
+++ b/app/src/test/java/com/streamvault/app/ui/screens/home/HomeViewModelTest.kt
@@ -1,10 +1,15 @@
package com.streamvault.app.ui.screens.home
+import android.app.Application
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.VirtualCategoryIds
import com.streamvault.domain.repository.*
import com.streamvault.domain.usecase.GetCustomCategories
import kotlinx.coroutines.Dispatchers
@@ -26,8 +31,10 @@ class HomeViewModelTest {
private val favoriteRepository: FavoriteRepository = mock()
private val preferencesRepository: PreferencesRepository = mock()
private val epgRepository: EpgRepository = mock()
+ private val playbackHistoryRepository: PlaybackHistoryRepository = mock()
private val getCustomCategories: GetCustomCategories = mock()
private val parentalControlManager: ParentalControlManager = mock()
+ private val application: Application = mock()
private lateinit var viewModel: HomeViewModel
@@ -43,14 +50,19 @@ class HomeViewModelTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(favoriteRepository.getFavorites(any())).thenReturn(flowOf(emptyList()))
whenever(preferencesRepository.defaultCategoryId).thenReturn(flowOf(null))
+ whenever(preferencesRepository.getLastLiveCategoryId(any())).thenReturn(flowOf(null))
+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(any(), any())).thenReturn(flowOf(emptyList()))
+ whenever(getCustomCategories()).thenReturn(flowOf(emptyList()))
viewModel = HomeViewModel(
+ application,
providerRepository,
channelRepository,
categoryRepository,
favoriteRepository,
preferencesRepository,
epgRepository,
+ playbackHistoryRepository,
getCustomCategories,
parentalControlManager
)
@@ -103,4 +115,239 @@ class HomeViewModelTest {
assertThat(state.selectedCategory).isEqualTo(category)
verify(parentalControlManager).clearUnlockedCategories(anyOrNull())
}
+
+ @Test
+ fun `recent live history becomes a virtual recent category`() = runTest {
+ val provider = Provider(
+ id = 9L,
+ name = "Provider",
+ type = ProviderType.M3U,
+ serverUrl = "http://test"
+ )
+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))
+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(emptyList()))
+ whenever(getCustomCategories()).thenReturn(
+ flowOf(
+ listOf(
+ Category(
+ id = VirtualCategoryIds.FAVORITES,
+ name = "Favorites",
+ isVirtual = true
+ )
+ )
+ )
+ )
+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(
+ flowOf(
+ listOf(
+ PlaybackHistory(
+ contentId = 21L,
+ contentType = ContentType.LIVE,
+ providerId = provider.id,
+ title = "News",
+ streamUrl = "http://stream"
+ )
+ )
+ )
+ )
+ whenever(channelRepository.getChannelsByIds(listOf(21L))).thenReturn(
+ flowOf(
+ listOf(
+ Channel(
+ id = 21L,
+ name = "News",
+ streamUrl = "http://stream",
+ providerId = provider.id
+ )
+ )
+ )
+ )
+ whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))
+
+ viewModel = HomeViewModel(
+ application,
+ providerRepository,
+ channelRepository,
+ categoryRepository,
+ favoriteRepository,
+ preferencesRepository,
+ epgRepository,
+ playbackHistoryRepository,
+ getCustomCategories,
+ parentalControlManager
+ )
+
+ advanceUntilIdle()
+
+ assertThat(viewModel.uiState.value.categories.map { it.id }).contains(VirtualCategoryIds.RECENT)
+ assertThat(viewModel.uiState.value.recentChannels.map { it.id }).containsExactly(21L)
+ }
+
+ @Test
+ fun `recent category stays visible in live tv even when history is empty`() = runTest {
+ val provider = Provider(
+ id = 12L,
+ name = "Provider",
+ type = ProviderType.M3U,
+ serverUrl = "http://test"
+ )
+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))
+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(emptyList()))
+ whenever(getCustomCategories()).thenReturn(
+ flowOf(
+ listOf(
+ Category(
+ id = VirtualCategoryIds.FAVORITES,
+ name = "Favorites",
+ isVirtual = true
+ )
+ )
+ )
+ )
+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))
+ whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))
+
+ viewModel = HomeViewModel(
+ application,
+ providerRepository,
+ channelRepository,
+ categoryRepository,
+ favoriteRepository,
+ preferencesRepository,
+ epgRepository,
+ playbackHistoryRepository,
+ getCustomCategories,
+ parentalControlManager
+ )
+
+ advanceUntilIdle()
+
+ val categories = viewModel.uiState.value.categories
+ assertThat(categories.map { it.id }).containsExactly(
+ VirtualCategoryIds.FAVORITES,
+ VirtualCategoryIds.RECENT
+ )
+ assertThat(categories.first { it.id == VirtualCategoryIds.RECENT }.count).isEqualTo(0)
+ }
+
+ @Test
+ fun `last visited live category is exposed for quick return`() = runTest {
+ val provider = Provider(
+ id = 14L,
+ name = "Provider",
+ type = ProviderType.M3U,
+ serverUrl = "http://test"
+ )
+ val sportsCategory = Category(id = 5L, name = "Sports")
+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))
+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(sportsCategory)))
+ whenever(getCustomCategories()).thenReturn(
+ flowOf(
+ listOf(
+ Category(
+ id = VirtualCategoryIds.FAVORITES,
+ name = "Favorites",
+ isVirtual = true
+ )
+ )
+ )
+ )
+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))
+ whenever(preferencesRepository.getLastLiveCategoryId(provider.id)).thenReturn(flowOf(sportsCategory.id))
+ whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))
+
+ viewModel = HomeViewModel(
+ application,
+ providerRepository,
+ channelRepository,
+ categoryRepository,
+ favoriteRepository,
+ preferencesRepository,
+ epgRepository,
+ playbackHistoryRepository,
+ getCustomCategories,
+ parentalControlManager
+ )
+
+ advanceUntilIdle()
+
+ assertThat(viewModel.uiState.value.lastVisitedCategory?.id).isEqualTo(sportsCategory.id)
+ assertThat(viewModel.uiState.value.lastVisitedCategory?.name).isEqualTo("Sports")
+ }
+
+ @Test
+ fun `selecting a live category remembers it for the current provider`() = runTest {
+ val provider = Provider(
+ id = 20L,
+ name = "Provider",
+ type = ProviderType.M3U,
+ serverUrl = "http://test"
+ )
+ val category = Category(id = 7L, name = "Kids")
+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))
+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(listOf(category)))
+ whenever(channelRepository.getChannelsByCategory(provider.id, category.id)).thenReturn(flowOf(emptyList()))
+ whenever(getCustomCategories()).thenReturn(flowOf(emptyList()))
+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))
+ whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))
+
+ viewModel = HomeViewModel(
+ application,
+ providerRepository,
+ channelRepository,
+ categoryRepository,
+ favoriteRepository,
+ preferencesRepository,
+ epgRepository,
+ playbackHistoryRepository,
+ getCustomCategories,
+ parentalControlManager
+ )
+
+ advanceUntilIdle()
+ viewModel.selectCategory(category)
+ advanceUntilIdle()
+
+ verify(preferencesRepository).setLastLiveCategoryId(provider.id, category.id)
+ }
+
+ @Test
+ fun `selecting recent does not overwrite remembered live group`() = runTest {
+ val provider = Provider(
+ id = 21L,
+ name = "Provider",
+ type = ProviderType.M3U,
+ serverUrl = "http://test"
+ )
+ val recentCategory = Category(
+ id = VirtualCategoryIds.RECENT,
+ name = "Recent",
+ type = ContentType.LIVE,
+ isVirtual = true
+ )
+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(provider))
+ whenever(channelRepository.getCategories(provider.id)).thenReturn(flowOf(emptyList()))
+ whenever(getCustomCategories()).thenReturn(flowOf(emptyList()))
+ whenever(playbackHistoryRepository.getRecentlyWatchedByProvider(eq(provider.id), any())).thenReturn(flowOf(emptyList()))
+ whenever(favoriteRepository.getFavorites(ContentType.LIVE)).thenReturn(flowOf(emptyList()))
+
+ viewModel = HomeViewModel(
+ application,
+ providerRepository,
+ channelRepository,
+ categoryRepository,
+ favoriteRepository,
+ preferencesRepository,
+ epgRepository,
+ playbackHistoryRepository,
+ getCustomCategories,
+ parentalControlManager
+ )
+
+ advanceUntilIdle()
+ viewModel.selectCategory(recentCategory)
+ advanceUntilIdle()
+
+ verify(preferencesRepository, never()).setLastLiveCategoryId(provider.id, recentCategory.id)
+ }
}
diff --git a/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt
new file mode 100644
index 00000000..05af0c78
--- /dev/null
+++ b/app/src/test/java/com/streamvault/app/ui/screens/search/SearchViewModelTest.kt
@@ -0,0 +1,126 @@
+package com.streamvault.app.ui.screens.search
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.MovieRepository
+import com.streamvault.domain.repository.ProviderRepository
+import com.streamvault.domain.repository.SeriesRepository
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.flowOf
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.runTest
+import kotlinx.coroutines.test.setMain
+import kotlinx.coroutines.launch
+import org.junit.After
+import org.junit.Before
+import org.junit.Test
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.whenever
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class SearchViewModelTest {
+
+ private val providerRepository: ProviderRepository = mock()
+ private val channelRepository: ChannelRepository = mock()
+ private val movieRepository: MovieRepository = mock()
+ private val seriesRepository: SeriesRepository = mock()
+ private val preferencesRepository: PreferencesRepository = mock()
+
+ private lateinit var viewModel: SearchViewModel
+
+ @Before
+ fun setup() {
+ Dispatchers.setMain(StandardTestDispatcher())
+ whenever(providerRepository.getActiveProvider()).thenReturn(flowOf(null))
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+
+ viewModel = SearchViewModel(
+ providerRepository,
+ channelRepository,
+ movieRepository,
+ seriesRepository,
+ preferencesRepository
+ )
+ }
+
+ @After
+ fun tearDown() {
+ Dispatchers.resetMain()
+ }
+
+ @Test
+ fun `submitted queries are stored trimmed deduplicated and capped`() = runTest {
+ viewModel.onQueryChange(" news ")
+ viewModel.onSearchSubmitted()
+ viewModel.onQueryChange("sports")
+ viewModel.onSearchSubmitted()
+ viewModel.onQueryChange("NEWS")
+ viewModel.onSearchSubmitted()
+ viewModel.onQueryChange("movies")
+ viewModel.onSearchSubmitted()
+ viewModel.onQueryChange("series")
+ viewModel.onSearchSubmitted()
+ viewModel.onQueryChange("kids")
+ viewModel.onSearchSubmitted()
+ viewModel.onQueryChange("music")
+ viewModel.onSearchSubmitted()
+
+ assertThat(viewModel.recentQueries.value).containsExactly(
+ "music",
+ "kids",
+ "series",
+ "movies",
+ "NEWS",
+ "sports"
+ ).inOrder()
+ }
+
+ @Test
+ fun `clearRecentQueries removes all stored search shortcuts`() = runTest {
+ viewModel.onQueryChange("news")
+ viewModel.onSearchSubmitted()
+
+ viewModel.clearRecentQueries()
+
+ assertThat(viewModel.recentQueries.value).isEmpty()
+ }
+
+ @Test
+ fun `ui state exposes provider and query readiness before results load`() = runTest {
+ whenever(providerRepository.getActiveProvider()).thenReturn(
+ flowOf(
+ Provider(
+ id = 1L,
+ name = "Provider",
+ type = ProviderType.M3U,
+ serverUrl = "http://test"
+ )
+ )
+ )
+
+ viewModel = SearchViewModel(
+ providerRepository,
+ channelRepository,
+ movieRepository,
+ seriesRepository,
+ preferencesRepository
+ )
+
+ val collectorJob = backgroundScope.launch { viewModel.uiState.collect { } }
+ advanceUntilIdle()
+ viewModel.onQueryChange("a")
+ testScheduler.advanceTimeBy(400)
+ advanceUntilIdle()
+
+ assertThat(viewModel.uiState.value.hasActiveProvider).isTrue()
+ assertThat(viewModel.uiState.value.queryLength).isEqualTo(1)
+ assertThat(viewModel.uiState.value.hasSearched).isFalse()
+ collectorJob.cancel()
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
index 30e9b236..3d97f947 100644
--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt
@@ -111,9 +111,24 @@ interface MovieDao {
@Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY name ASC")
fun getByProvider(providerId: Long): Flow<List<MovieEntity>>
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY name ASC LIMIT :limit OFFSET :offset")
+ fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<MovieEntity>>
+
@Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")
fun getByCategory(providerId: Long, categoryId: Long): Flow<List<MovieEntity>>
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit OFFSET :offset")
+ fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<MovieEntity>>
+
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit")
+ fun getByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<MovieEntity>>
+
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY rating DESC, name ASC LIMIT :limit")
+ fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<MovieEntity>>
+
+ @Query("SELECT * FROM movies WHERE provider_id = :providerId ORDER BY release_date DESC, name ASC LIMIT :limit")
+ fun getFreshPreview(providerId: Long, limit: Int): Flow<List<MovieEntity>>
+
@Query(
"""
SELECT m.* FROM movies m
@@ -183,6 +198,9 @@ interface MovieDao {
@Query("SELECT COUNT(*) FROM movies WHERE provider_id = :providerId")
fun getCount(providerId: Long): Flow<Int>
+ @Query("SELECT COUNT(*) FROM movies WHERE provider_id = :providerId AND category_id = :categoryId")
+ fun getCountByCategory(providerId: Long, categoryId: Long): Flow<Int>
+
@Query("UPDATE movies SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")
suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)
}
@@ -192,9 +210,24 @@ interface SeriesDao {
@Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY name ASC")
fun getByProvider(providerId: Long): Flow<List<SeriesEntity>>
+ @Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY name ASC LIMIT :limit OFFSET :offset")
+ fun getByProviderPage(providerId: Long, limit: Int, offset: Int): Flow<List<SeriesEntity>>
+
@Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC")
fun getByCategory(providerId: Long, categoryId: Long): Flow<List<SeriesEntity>>
+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit OFFSET :offset")
+ fun getByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<SeriesEntity>>
+
+ @Query("SELECT * FROM series WHERE provider_id = :providerId AND category_id = :categoryId ORDER BY name ASC LIMIT :limit")
+ fun getByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<SeriesEntity>>
+
+ @Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY rating DESC, name ASC LIMIT :limit")
+ fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<SeriesEntity>>
+
+ @Query("SELECT * FROM series WHERE provider_id = :providerId ORDER BY last_modified DESC, name ASC LIMIT :limit")
+ fun getFreshPreview(providerId: Long, limit: Int): Flow<List<SeriesEntity>>
+
@Query(
"""
SELECT s.* FROM series s
@@ -244,6 +277,9 @@ interface SeriesDao {
@Query("SELECT COUNT(*) FROM series WHERE provider_id = :providerId")
fun getCount(providerId: Long): Flow<Int>
+ @Query("SELECT COUNT(*) FROM series WHERE provider_id = :providerId AND category_id = :categoryId")
+ fun getCountByCategory(providerId: Long, categoryId: Long): Flow<Int>
+
@Query("UPDATE series SET is_user_protected = :isProtected WHERE provider_id = :providerId AND category_id = :categoryId")
suspend fun updateProtectionStatus(providerId: Long, categoryId: Long, isProtected: Boolean)
}
@@ -410,6 +446,9 @@ interface PlaybackHistoryDao {
@Query("SELECT * FROM playback_history WHERE provider_id = :providerId ORDER BY last_watched_at DESC LIMIT :limit")
fun getRecentlyWatchedByProvider(providerId: Long, limit: Int = 100): Flow<List<PlaybackHistoryEntity>>
+ @Query("SELECT * FROM playback_history ORDER BY last_watched_at DESC")
+ suspend fun getAllSync(): List<PlaybackHistoryEntity>
+
@Query("SELECT * FROM playback_history WHERE content_id = :contentId AND content_type = :contentType AND provider_id = :providerId")
suspend fun get(contentId: Long, contentType: String, providerId: Long): PlaybackHistoryEntity?
diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
index 356413b5..45ef2b81 100644
--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
@@ -4,12 +4,19 @@ import android.content.Context
import android.net.Uri
import com.google.gson.Gson
import com.streamvault.data.local.dao.FavoriteDao
+import com.streamvault.data.local.dao.PlaybackHistoryDao
+import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.dao.VirtualGroupDao
import com.streamvault.data.mapper.toDomain
import com.streamvault.data.mapper.toEntity
import com.streamvault.data.preferences.PreferencesRepository
+import com.streamvault.data.security.CredentialCrypto
import com.streamvault.domain.manager.BackupData
+import com.streamvault.domain.manager.BackupConflictStrategy
+import com.streamvault.domain.manager.BackupImportPlan
+import com.streamvault.domain.manager.BackupImportResult
import com.streamvault.domain.manager.BackupManager
+import com.streamvault.domain.manager.BackupPreview
import com.streamvault.domain.model.Result
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
@@ -23,8 +30,10 @@ import javax.inject.Singleton
class BackupManagerImpl @Inject constructor(
@ApplicationContext private val context: Context,
private val preferencesRepository: PreferencesRepository,
+ private val providerDao: ProviderDao,
private val favoriteDao: FavoriteDao,
private val virtualGroupDao: VirtualGroupDao,
+ private val playbackHistoryDao: PlaybackHistoryDao,
private val gson: Gson
) : BackupManager {
@@ -35,10 +44,19 @@ class BackupManagerImpl @Inject constructor(
// 1. Gather Data
val prefs = mapOf(
"parentalControlLevel" to preferencesRepository.parentalControlLevel.first().toString(),
- // We're leaving out provider credentials/URLs from the backup for security/complexity,
- // but we could back them up as well if requested.
+ "appLanguage" to preferencesRepository.appLanguage.first(),
+ "guideDensity" to (preferencesRepository.guideDensity.first() ?: ""),
+ "guideChannelMode" to (preferencesRepository.guideChannelMode.first() ?: ""),
+ "guideFavoritesOnly" to preferencesRepository.guideFavoritesOnly.first().toString(),
+ "guideAnchorTime" to (preferencesRepository.guideAnchorTime.first() ?: 0L).toString(),
+ "lastActiveProviderId" to (preferencesRepository.lastActiveProviderId.first() ?: -1L).toString(),
+ "promotedLiveGroupIds" to preferencesRepository.promotedLiveGroupIds.first().sorted().joinToString(",")
)
+ val providers = providerDao.getAll().first().map { entity ->
+ entity.toDomain().copy(password = CredentialCrypto.decryptIfNeeded(entity.password))
+ }
+
// Gather all favorites across all types
val liveFavs = favoriteDao.getAllByType("LIVE").first().map { it.toDomain() }
val movieFavs = favoriteDao.getAllByType("MOVIE").first().map { it.toDomain() }
@@ -51,11 +69,21 @@ class BackupManagerImpl @Inject constructor(
val seriesGroups = virtualGroupDao.getByType("SERIES").first().map { it.toDomain() }
val allGroups = liveGroups + movieGroups + seriesGroups
+ val playbackHistory = playbackHistoryDao.getAllSync().map { it.toDomain() }
+ val multiViewPresets = mapOf(
+ "preset_1" to preferencesRepository.getMultiViewPreset(0).first(),
+ "preset_2" to preferencesRepository.getMultiViewPreset(1).first(),
+ "preset_3" to preferencesRepository.getMultiViewPreset(2).first()
+ )
+
val backupData = BackupData(
- version = 1,
+ version = 2,
preferences = prefs,
+ providers = providers,
favorites = allFavorites,
- virtualGroups = allGroups
+ virtualGroups = allGroups,
+ playbackHistory = playbackHistory,
+ multiViewPresets = multiViewPresets
)
// 2. Serialize and write to URI
@@ -71,45 +99,223 @@ class BackupManagerImpl @Inject constructor(
}
}
- override suspend fun importConfig(uriString: String): com.streamvault.domain.model.Result<Unit> = withContext(Dispatchers.IO) {
+ override suspend fun inspectBackup(uriString: String): Result<BackupPreview> = withContext(Dispatchers.IO) {
try {
- val uri = Uri.parse(uriString)
+ val backupData = readBackupData(uriString)
+ ?: return@withContext Result.error("Failed to open input stream")
+ if (backupData.version > 2) {
+ return@withContext Result.error("Unsupported backup version")
+ }
- // 1. Read and Deserialize
- val backupData = context.contentResolver.openInputStream(uri)?.use { inputStream ->
- InputStreamReader(inputStream).use { reader ->
- gson.fromJson(reader, BackupData::class.java)
+ val existingProviders = providerDao.getAll().first()
+ val existingGroups = buildList {
+ addAll(virtualGroupDao.getByType("LIVE").first())
+ addAll(virtualGroupDao.getByType("MOVIE").first())
+ addAll(virtualGroupDao.getByType("SERIES").first())
+ }
+ val existingFavorites = buildList {
+ addAll(favoriteDao.getAllByType("LIVE").first())
+ addAll(favoriteDao.getAllByType("MOVIE").first())
+ addAll(favoriteDao.getAllByType("SERIES").first())
+ }
+ val existingHistory = playbackHistoryDao.getAllSync()
+
+ val providerConflicts = backupData.providers.orEmpty().count { incoming ->
+ existingProviders.any { it.serverUrl == incoming.serverUrl && it.username == incoming.username }
+ }
+ val groupConflicts = backupData.virtualGroups.orEmpty().count { incoming ->
+ existingGroups.any { it.name.equals(incoming.name, ignoreCase = true) && it.contentType == incoming.contentType.name }
+ }
+ val favoriteConflicts = backupData.favorites.orEmpty().count { incoming ->
+ existingFavorites.any {
+ it.contentId == incoming.contentId &&
+ it.contentType == incoming.contentType.name &&
+ it.groupId == incoming.groupId
}
- } ?: return@withContext com.streamvault.domain.model.Result.error("Failed to open input stream")
+ }
+ val historyConflicts = backupData.playbackHistory.orEmpty().count { incoming ->
+ existingHistory.any {
+ it.contentId == incoming.contentId &&
+ it.contentType == incoming.contentType.name &&
+ it.providerId == incoming.providerId
+ }
+ }
+
+ Result.success(
+ BackupPreview(
+ version = backupData.version,
+ providerCount = backupData.providers.orEmpty().size,
+ favoriteCount = backupData.favorites.orEmpty().size,
+ groupCount = backupData.virtualGroups.orEmpty().size,
+ playbackHistoryCount = backupData.playbackHistory.orEmpty().size,
+ multiViewPresetCount = backupData.multiViewPresets.orEmpty().count { it.value.isNotEmpty() },
+ preferenceCount = backupData.preferences.orEmpty().size,
+ providerConflicts = providerConflicts,
+ favoriteConflicts = favoriteConflicts,
+ groupConflicts = groupConflicts,
+ historyConflicts = historyConflicts
+ )
+ )
+ } catch (e: Exception) {
+ Result.error("Failed to inspect backup: ${e.message}", e)
+ }
+ }
+
+ override suspend fun importConfig(
+ uriString: String,
+ plan: BackupImportPlan
+ ): com.streamvault.domain.model.Result<BackupImportResult> = withContext(Dispatchers.IO) {
+ try {
+ val backupData = readBackupData(uriString)
+ ?: return@withContext com.streamvault.domain.model.Result.error("Failed to open input stream")
- if (backupData.version > 1) {
+ if (backupData.version > 2) {
return@withContext com.streamvault.domain.model.Result.error("Unsupported backup version")
}
+ val importedSections = mutableListOf<String>()
+ val skippedSections = mutableListOf<String>()
+
// 2. Restore Preferences
- backupData.preferences?.let { prefs ->
+ if (plan.importPreferences) {
+ backupData.preferences?.let { prefs ->
prefs["parentalControlLevel"]?.toIntOrNull()?.let {
preferencesRepository.setParentalControlLevel(it)
}
+ prefs["appLanguage"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setAppLanguage(it) }
+ prefs["guideDensity"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setGuideDensity(it) }
+ prefs["guideChannelMode"]?.takeIf { it.isNotBlank() }?.let { preferencesRepository.setGuideChannelMode(it) }
+ prefs["guideFavoritesOnly"]?.toBooleanStrictOrNull()?.let { preferencesRepository.setGuideFavoritesOnly(it) }
+ prefs["guideAnchorTime"]?.toLongOrNull()?.takeIf { it > 0L }?.let { preferencesRepository.setGuideAnchorTime(it) }
+ prefs["promotedLiveGroupIds"]?.let { token ->
+ preferencesRepository.setPromotedLiveGroupIds(
+ token.split(",").mapNotNull { it.toLongOrNull() }.toSet()
+ )
+ }
+ importedSections += "Preferences"
+ } ?: run { skippedSections += "Preferences" }
+ } else {
+ skippedSections += "Preferences"
+ }
+
+ if (plan.importProviders) {
+ backupData.providers?.let { providers ->
+ providers.forEach { provider ->
+ val existing = providerDao.getByUrlAndUser(provider.serverUrl, provider.username)
+ if (existing != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {
+ return@forEach
+ }
+ val entity = provider.copy(
+ id = existing?.id ?: provider.id
+ ).toSecureEntityForBackup()
+ providerDao.insert(entity)
+ }
+ backupData.preferences
+ ?.get("lastActiveProviderId")
+ ?.toLongOrNull()
+ ?.takeIf { it > 0L }
+ ?.let { activeId ->
+ providerDao.deactivateAll()
+ providerDao.activate(activeId)
+ }
+ importedSections += "Providers"
+ } ?: run { skippedSections += "Providers" }
+ } else {
+ skippedSections += "Providers"
}
// 3. Restore Virtual Groups
- backupData.virtualGroups?.let { groups ->
+ if (plan.importSavedLibrary) {
+ backupData.virtualGroups?.let { groups ->
+ val existingGroups = buildList {
+ addAll(virtualGroupDao.getByType("LIVE").first())
+ addAll(virtualGroupDao.getByType("MOVIE").first())
+ addAll(virtualGroupDao.getByType("SERIES").first())
+ }
groups.forEach { group ->
+ val conflict = existingGroups.firstOrNull {
+ it.name.equals(group.name, ignoreCase = true) &&
+ it.contentType == group.contentType.name
+ }
+ if (conflict != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {
+ return@forEach
+ }
virtualGroupDao.insert(group.toEntity())
}
- }
+ } ?: run { skippedSections += "Saved Library" }
// 4. Restore Favorites
- backupData.favorites?.let { favs ->
+ backupData.favorites?.let { favs ->
favs.forEach { fav ->
+ val existing = favoriteDao.get(
+ contentId = fav.contentId,
+ contentType = fav.contentType.name,
+ groupId = fav.groupId
+ )
+ if (existing != null && plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {
+ return@forEach
+ }
favoriteDao.insert(fav.toEntity())
}
+ }
+ importedSections += "Saved Library"
+ } else {
+ skippedSections += "Saved Library"
}
- com.streamvault.domain.model.Result.success(Unit)
+ if (plan.importPlaybackHistory) {
+ backupData.playbackHistory?.let { history ->
+ if (plan.conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING) {
+ playbackHistoryDao.deleteAll()
+ }
+ history.forEach { item ->
+ if (plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {
+ val existing = playbackHistoryDao.get(
+ contentId = item.contentId,
+ contentType = item.contentType.name,
+ providerId = item.providerId
+ )
+ if (existing != null) return@forEach
+ }
+ playbackHistoryDao.insertOrUpdate(item.toEntity())
+ }
+ importedSections += "Playback History"
+ } ?: run { skippedSections += "Playback History" }
+ } else {
+ skippedSections += "Playback History"
+ }
+
+ if (plan.importMultiViewPresets) {
+ backupData.multiViewPresets?.let { presets ->
+ preferencesRepository.setMultiViewPreset(0, presets["preset_1"].orEmpty())
+ preferencesRepository.setMultiViewPreset(1, presets["preset_2"].orEmpty())
+ preferencesRepository.setMultiViewPreset(2, presets["preset_3"].orEmpty())
+ importedSections += "Split Screen Presets"
+ } ?: run { skippedSections += "Split Screen Presets" }
+ } else {
+ skippedSections += "Split Screen Presets"
+ }
+
+ com.streamvault.domain.model.Result.success(
+ BackupImportResult(
+ importedSections = importedSections.distinct(),
+ skippedSections = skippedSections.distinct()
+ )
+ )
} catch (e: Exception) {
com.streamvault.domain.model.Result.error("Failed to import backup: ${e.message}", e)
}
}
+
+ private fun readBackupData(uriString: String): BackupData? {
+ val uri = Uri.parse(uriString)
+ return context.contentResolver.openInputStream(uri)?.use { inputStream ->
+ InputStreamReader(inputStream).use { reader ->
+ gson.fromJson(reader, BackupData::class.java)
+ }
+ }
+ }
}
+
+private fun com.streamvault.domain.model.Provider.toSecureEntityForBackup() =
+ copy(password = CredentialCrypto.encryptIfNeeded(password)).toEntity()
diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt
new file mode 100644
index 00000000..6f5cc9fa
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt
@@ -0,0 +1,236 @@
+package com.streamvault.data.manager
+
+import android.content.Context
+import android.os.StatFs
+import com.google.gson.Gson
+import com.google.gson.reflect.TypeToken
+import com.streamvault.domain.manager.RecordingManager
+import com.streamvault.domain.model.RecordingItem
+import com.streamvault.domain.model.RecordingRequest
+import com.streamvault.domain.model.RecordingStatus
+import com.streamvault.domain.model.RecordingStorageState
+import com.streamvault.domain.model.Result
+import dagger.hilt.android.qualifiers.ApplicationContext
+import java.io.File
+import java.io.FileInputStream
+import java.io.FileOutputStream
+import java.net.HttpURLConnection
+import java.net.URL
+import java.util.UUID
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.isActive
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.withContext
+
+@Singleton
+class RecordingManagerImpl @Inject constructor(
+ @ApplicationContext private val context: Context,
+ private val gson: Gson
+) : RecordingManager {
+
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val stateFile by lazy { File(recordingsDir, "recordings_state.json") }
+ private val recordingsDir by lazy { File(context.filesDir, "recordings").apply { mkdirs() } }
+
+ private val itemsState = MutableStateFlow(loadState())
+ private val storageState = MutableStateFlow(readStorageState())
+ private val activeJobs = mutableMapOf<String, Job>()
+
+ init {
+ scope.launch {
+ while (true) {
+ processSchedules()
+ storageState.value = readStorageState()
+ delay(15_000L)
+ }
+ }
+ }
+
+ override fun observeRecordingItems(): Flow<List<RecordingItem>> = itemsState.asStateFlow()
+
+ override fun observeStorageState(): Flow<RecordingStorageState> = storageState.asStateFlow()
+
+ override suspend fun startManualRecording(request: RecordingRequest): Result<RecordingItem> = withContext(Dispatchers.IO) {
+ if (isAdaptiveStream(request.streamUrl)) {
+ return@withContext Result.error("Live recording currently supports direct stream URLs only. Adaptive streams are not recordable yet.")
+ }
+ if (!storageState.value.isWritable) {
+ return@withContext Result.error("Recording storage is not writable.")
+ }
+
+ val item = RecordingItem(
+ id = UUID.randomUUID().toString(),
+ providerId = request.providerId,
+ channelId = request.channelId,
+ channelName = request.channelName,
+ streamUrl = request.streamUrl,
+ scheduledStartMs = System.currentTimeMillis(),
+ scheduledEndMs = request.scheduledEndMs,
+ programTitle = request.programTitle,
+ outputPath = request.outputPath ?: buildOutputFile(request).absolutePath,
+ status = RecordingStatus.RECORDING
+ )
+ itemsState.value = itemsState.value + item
+ persistState()
+ startCapture(item)
+ storageState.value = readStorageState()
+ Result.success(item)
+ }
+
+ override suspend fun scheduleRecording(request: RecordingRequest): Result<RecordingItem> = withContext(Dispatchers.IO) {
+ val item = RecordingItem(
+ id = UUID.randomUUID().toString(),
+ providerId = request.providerId,
+ channelId = request.channelId,
+ channelName = request.channelName,
+ streamUrl = request.streamUrl,
+ scheduledStartMs = request.scheduledStartMs,
+ scheduledEndMs = request.scheduledEndMs,
+ programTitle = request.programTitle,
+ outputPath = request.outputPath ?: buildOutputFile(request).absolutePath,
+ status = RecordingStatus.SCHEDULED
+ )
+ itemsState.value = itemsState.value + item
+ persistState()
+ Result.success(item)
+ }
+
+ override suspend fun stopRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {
+ activeJobs.remove(recordingId)?.cancel()
+ val item = itemsState.value.firstOrNull { it.id == recordingId }
+ ?: return@withContext Result.error("Recording not found")
+ val fileLength = item.outputPath?.let { path -> File(path).takeIf { it.exists() }?.length() } ?: 0L
+ updateItem(recordingId) {
+ it.copy(
+ status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,
+ scheduledEndMs = System.currentTimeMillis()
+ )
+ }
+ Result.success(Unit)
+ }
+
+ override suspend fun cancelRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {
+ activeJobs.remove(recordingId)?.cancel()
+ updateItem(recordingId) { it.copy(status = RecordingStatus.CANCELLED) }
+ Result.success(Unit)
+ }
+
+ private fun processSchedules() {
+ val now = System.currentTimeMillis()
+ itemsState.value
+ .filter { it.status == RecordingStatus.SCHEDULED && it.scheduledStartMs <= now }
+ .forEach { scheduled ->
+ if (isAdaptiveStream(scheduled.streamUrl)) {
+ updateItem(scheduled.id) {
+ it.copy(
+ status = RecordingStatus.FAILED,
+ failureReason = "Scheduled recording supports direct stream URLs only."
+ )
+ }
+ } else {
+ startCapture(scheduled.copy(status = RecordingStatus.RECORDING))
+ updateItem(scheduled.id) { current -> current.copy(status = RecordingStatus.RECORDING) }
+ }
+ }
+
+ itemsState.value
+ .filter { it.status == RecordingStatus.RECORDING && it.scheduledEndMs in 1 until now }
+ .forEach { stopCandidate ->
+ activeJobs.remove(stopCandidate.id)?.cancel()
+ updateItem(stopCandidate.id) { it.copy(status = RecordingStatus.COMPLETED) }
+ }
+ }
+
+ private fun startCapture(item: RecordingItem) {
+ if (activeJobs.containsKey(item.id)) return
+ val job = scope.launch {
+ val outputFile = File(item.outputPath ?: return@launch)
+ outputFile.parentFile?.mkdirs()
+ runCatching {
+ val connection = URL(item.streamUrl).openConnection() as HttpURLConnection
+ connection.connectTimeout = 15_000
+ connection.readTimeout = 15_000
+ connection.instanceFollowRedirects = true
+ connection.connect()
+ connection.inputStream.use { input ->
+ FileOutputStream(outputFile, true).use { output ->
+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)
+ while (true) {
+ val bytes = input.read(buffer)
+ if (bytes <= 0) break
+ output.write(buffer, 0, bytes)
+ if (!kotlin.coroutines.coroutineContext.isActive) break
+ }
+ }
+ }
+ }.onSuccess {
+ updateItem(item.id) { current ->
+ current.copy(status = RecordingStatus.COMPLETED)
+ }
+ }.onFailure { error ->
+ if (error is kotlinx.coroutines.CancellationException) {
+ val fileLength = outputFile.takeIf { it.exists() }?.length() ?: 0L
+ updateItem(item.id) { current ->
+ current.copy(status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED)
+ }
+ } else {
+ updateItem(item.id) { current ->
+ current.copy(status = RecordingStatus.FAILED, failureReason = error.message)
+ }
+ }
+ }
+ activeJobs.remove(item.id)
+ storageState.value = readStorageState()
+ }
+ activeJobs[item.id] = job
+ }
+
+ private fun updateItem(recordingId: String, transform: (RecordingItem) -> RecordingItem) {
+ itemsState.value = itemsState.value.map { item ->
+ if (item.id == recordingId) transform(item) else item
+ }
+ persistState()
+ }
+
+ private fun buildOutputFile(request: RecordingRequest): File {
+ val safeName = request.channelName.replace(Regex("[^a-zA-Z0-9._-]"), "_")
+ return File(recordingsDir, "${safeName}_${request.scheduledStartMs}.ts")
+ }
+
+ private fun readStorageState(): RecordingStorageState {
+ recordingsDir.mkdirs()
+ val stat = StatFs(recordingsDir.absolutePath)
+ return RecordingStorageState(
+ outputDirectory = recordingsDir.absolutePath,
+ availableBytes = stat.availableBytes,
+ isWritable = recordingsDir.canWrite()
+ )
+ }
+
+ private fun persistState() {
+ stateFile.parentFile?.mkdirs()
+ stateFile.writeText(gson.toJson(itemsState.value))
+ }
+
+ private fun loadState(): List<RecordingItem> {
+ if (!stateFile.exists()) return emptyList()
+ return runCatching {
+ val listType = object : TypeToken<List<RecordingItem>>() {}.type
+ gson.fromJson<List<RecordingItem>>(FileInputStream(stateFile).bufferedReader(), listType).orEmpty()
+ }.getOrDefault(emptyList())
+ }
+
+ private fun isAdaptiveStream(url: String): Boolean {
+ val lower = url.lowercase()
+ return lower.contains(".m3u8") || lower.contains(".mpd")
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
index 08cbaef2..42f42df7 100644
--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
@@ -40,6 +40,15 @@ class PreferencesRepository @Inject constructor(
val PARENTAL_PIN_SALT = stringPreferencesKey("parental_pin_salt")
val DEFAULT_CATEGORY_ID = longPreferencesKey("default_category_id")
val APP_LANGUAGE = stringPreferencesKey("app_language")
+ val GUIDE_DENSITY = stringPreferencesKey("guide_density")
+ val GUIDE_CHANNEL_MODE = stringPreferencesKey("guide_channel_mode")
+ val GUIDE_FAVORITES_ONLY = intPreferencesKey("guide_favorites_only")
+ val GUIDE_ANCHOR_TIME = longPreferencesKey("guide_anchor_time")
+ val PROMOTED_LIVE_GROUP_IDS = stringPreferencesKey("promoted_live_group_ids")
+ val MULTIVIEW_PRESET_1 = stringPreferencesKey("multiview_preset_1")
+ val MULTIVIEW_PRESET_2 = stringPreferencesKey("multiview_preset_2")
+ val MULTIVIEW_PRESET_3 = stringPreferencesKey("multiview_preset_3")
+ val MULTIVIEW_PERFORMANCE_MODE = stringPreferencesKey("multiview_performance_mode")
}
val lastActiveProviderId: Flow<Long?> = context.dataStore.data.map { preferences ->
@@ -127,6 +136,20 @@ class PreferencesRepository @Inject constructor(
}
}
+ fun getLastLiveCategoryId(providerId: Long): Flow<Long?> {
+ val key = longPreferencesKey("last_live_category_id_$providerId")
+ return context.dataStore.data.map { preferences ->
+ preferences[key]
+ }
+ }
+
+ suspend fun setLastLiveCategoryId(providerId: Long, categoryId: Long) {
+ val key = longPreferencesKey("last_live_category_id_$providerId")
+ context.dataStore.edit { preferences ->
+ preferences[key] = categoryId
+ }
+ }
+
val appLanguage: Flow<String> = context.dataStore.data.map { preferences ->
preferences[PreferencesKeys.APP_LANGUAGE] ?: "system"
}
@@ -137,6 +160,103 @@ class PreferencesRepository @Inject constructor(
}
}
+ val guideDensity: Flow<String?> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.GUIDE_DENSITY]
+ }
+
+ suspend fun setGuideDensity(density: String) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.GUIDE_DENSITY] = density
+ }
+ }
+
+ val guideChannelMode: Flow<String?> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.GUIDE_CHANNEL_MODE]
+ }
+
+ suspend fun setGuideChannelMode(mode: String) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.GUIDE_CHANNEL_MODE] = mode
+ }
+ }
+
+ val guideFavoritesOnly: Flow<Boolean> = context.dataStore.data.map { preferences ->
+ (preferences[PreferencesKeys.GUIDE_FAVORITES_ONLY] ?: 0) == 1
+ }
+
+ suspend fun setGuideFavoritesOnly(enabled: Boolean) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.GUIDE_FAVORITES_ONLY] = if (enabled) 1 else 0
+ }
+ }
+
+ val guideAnchorTime: Flow<Long?> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.GUIDE_ANCHOR_TIME]
+ }
+
+ suspend fun setGuideAnchorTime(anchorTimeMs: Long) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.GUIDE_ANCHOR_TIME] = anchorTimeMs
+ }
+ }
+
+ val promotedLiveGroupIds: Flow<Set<Long>> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.PROMOTED_LIVE_GROUP_IDS]
+ ?.split(",")
+ ?.mapNotNull { token -> token.toLongOrNull() }
+ ?.toSet()
+ .orEmpty()
+ }
+
+ suspend fun setPromotedLiveGroupIds(groupIds: Set<Long>) {
+ context.dataStore.edit { preferences ->
+ if (groupIds.isEmpty()) {
+ preferences.remove(PreferencesKeys.PROMOTED_LIVE_GROUP_IDS)
+ } else {
+ preferences[PreferencesKeys.PROMOTED_LIVE_GROUP_IDS] = groupIds.sorted().joinToString(",")
+ }
+ }
+ }
+
+ fun getMultiViewPreset(presetIndex: Int): Flow<List<Long>> {
+ val key = when (presetIndex) {
+ 0 -> PreferencesKeys.MULTIVIEW_PRESET_1
+ 1 -> PreferencesKeys.MULTIVIEW_PRESET_2
+ else -> PreferencesKeys.MULTIVIEW_PRESET_3
+ }
+ return context.dataStore.data.map { preferences ->
+ preferences[key]
+ ?.split(",")
+ ?.mapNotNull { token -> token.toLongOrNull() }
+ .orEmpty()
+ }
+ }
+
+ suspend fun setMultiViewPreset(presetIndex: Int, channelIds: List<Long>) {
+ val key = when (presetIndex) {
+ 0 -> PreferencesKeys.MULTIVIEW_PRESET_1
+ 1 -> PreferencesKeys.MULTIVIEW_PRESET_2
+ else -> PreferencesKeys.MULTIVIEW_PRESET_3
+ }
+ context.dataStore.edit { preferences ->
+ if (channelIds.isEmpty()) {
+ preferences.remove(key)
+ } else {
+ preferences[key] = channelIds.joinToString(",")
+ }
+ }
+ }
+
+ val multiViewPerformanceMode: Flow<String?> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.MULTIVIEW_PERFORMANCE_MODE]
+ }
+
+ suspend fun setMultiViewPerformanceMode(mode: String) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.MULTIVIEW_PERFORMANCE_MODE] = mode
+ }
+ }
+
fun getAspectRatioForChannel(channelId: Long): Flow<String?> {
val key = stringPreferencesKey("aspect_ratio_$channelId")
return context.dataStore.data.map { preferences ->
diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
index 663e7876..d6fbcff7 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -7,7 +7,9 @@ import com.streamvault.data.local.entity.CategoryEntity
import com.streamvault.data.mapper.toDomain
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.PagedResult
import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.MovieRepository
import kotlinx.coroutines.flow.Flow
@@ -49,6 +51,59 @@ class MovieRepositoryImpl @Inject constructor(
}
}.map { list -> list.map { it.toDomain() } }
+ override fun getMoviesByCategoryPage(
+ providerId: Long,
+ categoryId: Long,
+ limit: Int,
+ offset: Int
+ ): Flow<List<Movie>> =
+ combine(
+ movieDao.getByCategoryPage(providerId, categoryId, limit, offset),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<MovieEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list -> list.map { it.toDomain() } }
+
+ override fun getMoviesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Movie>> =
+ combine(
+ movieDao.getByCategoryPreview(providerId, categoryId, limit),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<MovieEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list -> list.map { it.toDomain() } }
+
+ override fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Movie>> =
+ combine(
+ movieDao.getTopRatedPreview(providerId, limit),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<MovieEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list -> list.map { it.toDomain() } }
+
+ override fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Movie>> =
+ combine(
+ movieDao.getFreshPreview(providerId, limit),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<MovieEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list -> list.map { it.toDomain() } }
+
override fun getMoviesByIds(ids: List<Long>): Flow<List<Movie>> =
movieDao.getByIds(ids).map { entities -> entities.map { it.toDomain() } }
@@ -65,6 +120,41 @@ class MovieRepositoryImpl @Inject constructor(
}
}
+ override fun getCategoryItemCounts(providerId: Long): Flow<Map<Long, Int>> =
+ movieDao.getCategoryCounts(providerId).map { counts ->
+ counts.associate { it.categoryId to it.item_count }
+ }
+
+ override fun getLibraryCount(providerId: Long): Flow<Int> =
+ movieDao.getCount(providerId)
+
+ override fun browseMovies(query: LibraryBrowseQuery): Flow<PagedResult<Movie>> {
+ val categoryId = query.categoryId
+ val pageFlow = if (query.categoryId == null) {
+ movieDao.getByProviderPage(query.providerId, query.limit, query.offset)
+ } else {
+ movieDao.getByCategoryPage(query.providerId, categoryId!!, query.limit, query.offset)
+ }
+ val countFlow = if (query.categoryId == null) {
+ movieDao.getCount(query.providerId)
+ } else {
+ movieDao.getCountByCategory(query.providerId, categoryId!!)
+ }
+ return combine(pageFlow, countFlow, preferencesRepository.parentalControlLevel) { entities, totalCount, level ->
+ val filtered = if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ PagedResult(
+ items = filtered.map { it.toDomain() },
+ totalCount = totalCount,
+ offset = query.offset,
+ limit = query.limit
+ )
+ }
+ }
+
override fun searchMovies(providerId: Long, query: String): Flow<List<Movie>> =
query.toFtsPrefixQuery().let { ftsQuery ->
if (ftsQuery.isBlank()) {
diff --git a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
index 9c93070c..bce18e4f 100644
--- a/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/PlaybackHistoryRepositoryImpl.kt
@@ -28,6 +28,17 @@ class PlaybackHistoryRepositoryImpl @Inject constructor(
return dao.get(contentId, contentType.name, providerId)?.toDomain()
}
+ override suspend fun recordPlayback(history: PlaybackHistory) {
+ val existing = dao.get(history.contentId, history.contentType.name, history.providerId)
+ val updatedHistory = history.copy(
+ resumePositionMs = 0,
+ totalDurationMs = 0,
+ watchCount = (existing?.watchCount ?: 0) + 1,
+ lastWatchedAt = System.currentTimeMillis()
+ )
+ dao.insertOrUpdate(updatedHistory.toEntity())
+ }
+
override suspend fun updateResumePosition(history: PlaybackHistory) {
val existing = dao.get(history.contentId, history.contentType.name, history.providerId)
diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
index d438018f..f8603397 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -50,6 +50,59 @@ class SeriesRepositoryImpl @Inject constructor(
}
}.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+ override fun getSeriesByCategoryPage(
+ providerId: Long,
+ categoryId: Long,
+ limit: Int,
+ offset: Int
+ ): Flow<List<Series>> =
+ combine(
+ seriesDao.getByCategoryPage(providerId, categoryId, limit, offset),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<SeriesEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+
+ override fun getSeriesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Series>> =
+ combine(
+ seriesDao.getByCategoryPreview(providerId, categoryId, limit),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<SeriesEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+
+ override fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Series>> =
+ combine(
+ seriesDao.getTopRatedPreview(providerId, limit),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<SeriesEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+
+ override fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Series>> =
+ combine(
+ seriesDao.getFreshPreview(providerId, limit),
+ preferencesRepository.parentalControlLevel
+ ) { entities: List<SeriesEntity>, level: Int ->
+ if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ }.map { list: List<SeriesEntity> -> list.map { it.toDomain() } }
+
override fun getSeriesByIds(ids: List<Long>): Flow<List<Series>> =
seriesDao.getByIds(ids).map { entities -> entities.map { it.toDomain() } }
@@ -66,6 +119,41 @@ class SeriesRepositoryImpl @Inject constructor(
}
}
+ override fun getCategoryItemCounts(providerId: Long): Flow<Map<Long, Int>> =
+ seriesDao.getCategoryCounts(providerId).map { counts ->
+ counts.associate { it.categoryId to it.item_count }
+ }
+
+ override fun getLibraryCount(providerId: Long): Flow<Int> =
+ seriesDao.getCount(providerId)
+
+ override fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>> {
+ val categoryId = query.categoryId
+ val pageFlow = if (query.categoryId == null) {
+ seriesDao.getByProviderPage(query.providerId, query.limit, query.offset)
+ } else {
+ seriesDao.getByCategoryPage(query.providerId, categoryId!!, query.limit, query.offset)
+ }
+ val countFlow = if (query.categoryId == null) {
+ seriesDao.getCount(query.providerId)
+ } else {
+ seriesDao.getCountByCategory(query.providerId, categoryId!!)
+ }
+ return combine(pageFlow, countFlow, preferencesRepository.parentalControlLevel) { entities: List<SeriesEntity>, totalCount: Int, level: Int ->
+ val filtered = if (level == 2) {
+ entities.filter { !it.isUserProtected }
+ } else {
+ entities
+ }
+ PagedResult(
+ items = filtered.map { it.toDomain() },
+ totalCount = totalCount,
+ offset = query.offset,
+ limit = query.limit
+ )
+ }
+ }
+
override fun searchSeries(providerId: Long, query: String): Flow<List<Series>> =
query.toFtsPrefixQuery().let { ftsQuery ->
if (ftsQuery.isBlank()) {
diff --git a/docs/code-review/PREMIUM_TV_AUDIT_2026-03-11.md b/docs/code-review/PREMIUM_TV_AUDIT_2026-03-11.md
new file mode 100644
index 00000000..23e04f33
--- /dev/null
+++ b/docs/code-review/PREMIUM_TV_AUDIT_2026-03-11.md
@@ -0,0 +1,408 @@
+# StreamVault Premium TV Audit
+
+Branch: `session/premium-audit-2026-03-11`
+Base: `master`
+Method: source-level audit plus targeted implementation pass
+Confidence: `confirmed` for code-backed findings, `likely` for runtime/perf behavior inferred from structure, `assumption` where device-level validation is still missing
+
+## A. Executive Product Assessment
+- Overall quality: `7.5/10`
+- Biggest strengths:
+ - `confirmed`: strong feature surface for an Android TV IPTV app: Live TV, Movies, Series, EPG, favorites, custom groups, parental control, resume history, multiview, numeric zapping, audio/subtitle switching.
+ - `confirmed`: clean module split across `app`, `data`, `domain`, and `player`.
+ - `confirmed`: the player stack is already better than average IPTV apps: Media3, error recovery, alternative-stream fallback, numeric input, diagnostics, catch-up entry points.
+- Biggest weaknesses:
+ - `confirmed`: several flows looked complete but were context-fragile. Search and Favorites were launching player with incomplete provider/category/internal IDs until this branch.
+ - `confirmed`: the full-screen EPG was visually present but functionally weak: placeholder click handlers and only now-playing data.
+ - `confirmed`: Movies and Series were still doing extra UI-side filtering/grouping work instead of using repository search for typed queries.
+ - `confirmed`: the app now has a real dashboard-style Home screen instead of treating the Live TV browser as the landing surface; recent-live workflows still exist, but the extra `Recent` / `Last Channel` / `Last Group` chips were intentionally pulled back out of the Live TV browse header because that surface was getting jammed and low quality.
+- Why it still does not fully feel premium:
+ - `confirmed`: some screens are polished while others still expose placeholder behavior, hardcoded copy, or weaker empty/error states, though Movies/Series category copy and group-management affordances are stronger after this pass.
+ - `likely`: huge-library responsiveness will still be uneven because Live is more optimized than VOD/Series browsing.
+ - `likely`: full premium feel needs one more pass on information architecture, cross-screen consistency, and power-user workflows.
+- Top opportunities:
+ 1. Finish Live TV information architecture: better recent-channel memory, better full EPG, better catch-up and stale-guide handling.
+ 2. Rework VOD/Series browsing for very large libraries beyond the first search optimization already implemented.
+ 3. Make favorites/groups and multi-provider workflows feel intentional instead of merely available.
+ 4. Unify TV-native polish across Search, Favorites, Settings, Series detail, and EPG.
+
+## B. Full Feature Inventory
+| Feature | Status | Notes |
+|---|---|---|
+| Xtream provider login | Full | `confirmed`: auth, sync, edit, active-provider switching exist. |
+| M3U URL import | Full | `confirmed`: validation and sync path exist. |
+| Local M3U file import | Full | `confirmed`: file picker, local copy, cleanup policy, storage-full messaging exist. |
+| Multi-provider support | Full | `confirmed`: multiple providers, active provider, refresh, edit, delete. |
+| Welcome/onboarding | Partial | `confirmed`: welcome split and auto-bypass exist; still basic for premium onboarding and trust-building. |
+| Home dashboard | Partial | `confirmed`: Home now has a real premium direction: featured hero state, dashboard stats, provider-health surfacing, provider-warning drill-down, live-memory shortcut cards, favorite channels, recent channels, continue watching, and fresh Movies/Series shelves, plus category-aware deep links back into Live TV; it is much stronger, but still needs deeper personalization to feel fully premium. |
+| Sync status / partial refresh warnings | Full | `confirmed`: provider status, partial warning actions, section retries exist. |
+| Live TV categories | Full | `confirmed`: provider categories plus virtual favorites/groups/recent remain in the category rail; the browse surface was simplified in this pass so Live TV is back to being a channel browser instead of a pseudo-home screen. |
+| Movies catalog | Full | `confirmed`: category rail, hero banner, continue watching, favorites/groups, a reachable saved-shortcuts strip for Favorites/custom groups, repository-backed all-library lens rows for Favorites, Continue Watching, Top Rated, and Fresh content, and a query-backed full-library browse mode. |
+| Series catalog | Full | `confirmed`: category rail, continue watching, favorites/groups, detail screen, a reachable saved-shortcuts strip for Favorites/custom groups, repository-backed all-library lens rows for Favorites, Continue Watching, Top Rated, and Fresh content, and a query-backed full-library browse mode. |
+| Series detail / seasons / episodes | Full | `confirmed`: series detail loads seasons/episodes and plays episodes. |
+| Full-screen EPG | Full | `confirmed`: now actionable, category-aware, schedule-based, clearer about stale/missing data, exposes visible time-window controls and window labels, includes a dense aligned timeline grid with shared half-hour markers, current-time line, and time-scaled program placement, supports direct day browsing, has `Scheduled only` cleanup mode, guide-mode filters for timeline, anchor-time, and archive-ready browsing, now adds density/layout controls, full-window paging, persisted guide defaults, a favorite-channel-only mode, exact return-route handoff back from player, and a real TV-style program side panel with provider/channel/replay/progress metadata, surrounding schedule context, and stale-guide refresh. |
+| Player EPG overlay | Full | `confirmed`: current/next/upcoming/history overlays exist. |
+| Favorites | Partial | `confirmed`: the standalone saved-library route is now reachable from Home and behaves like a real hub with overview stats, type filters, sort presets, provider scope, section-jump chips, Continue Watching, Recent Live rows, higher-level saved presets including `Home Shelf`, and in-hub management actions; it is no longer effectively dead code, but it still lacks deeper merged-provider behavior and final cross-surface polish. |
+| Custom virtual groups | Partial | `confirmed`: create/add/remove/delete/reorder/rename now exist in Live TV, Movies, and Series category sidebars, and saved shortcut cards can now long-press directly into those management flows; the overall saved-library UX is still fragmented across screens. |
+| Continue watching | Partial | `confirmed`: movies and series continue-watching exists; live now has a separate recent-channels workflow instead of resume-style continue watching. |
+| Resume playback | Full | `confirmed`: movies and series episodes resume with prompt. |
+| Search | Partial | `confirmed`: FTS-backed search exists across Live/Movies/Series, Search exposes recent-query shortcuts with clear-history controls, and it now has visible no-provider/min-query states plus results-summary chips for one-click narrowing; it still lacks deeper filtering and stronger power-user UX. |
+| Numeric channel entry | Full | `confirmed`: timed input, preview, invalid feedback, last-channel on `0`. |
+| Channel zapping | Full | `confirmed`: next/previous, overlays, watchdog fallback, last channel. |
+| Audio track switching | Full | `confirmed`: track discovery and selection exist. |
+| Subtitle switching | Full | `confirmed`: subtitle track selection with disable option exists. |
+| Video quality switching | Partial | `confirmed`: implemented as alternative-stream selection, not full adaptive/manual quality UX. |
+| Catch-up / replay | Partial | `confirmed`: catch-up URL building and archive entry exist, and guide/player now expose provider-aware replay reasoning plus richer failure messages; provider compatibility handling and deeper archive intelligence still need more work. |
+| Multiview / split screen | Full | `confirmed`: 4-slot multiview now includes slot manager, focused audio, saved presets, focused-slot replace/remove actions, audio pinning, device-tier performance modes, active-slot caps, staged decoder startup, runtime telemetry snapshots, sustained-load throttling, low-memory standby behavior, and thermal-aware slot reduction on supported Android TV devices. Manual lower-end device profiling is still required for final acceptance, but the in-app protection layer is now implemented. |
+| Parental control | Full | `confirmed`: PIN, lock levels, category protection for Live/Movies/Series exist. |
+| Backup / restore | Partial | `confirmed`: backup now includes expanded preferences, providers, playback history, promoted groups, and multiview presets, and Settings now exposes restore preview/conflict UX with section toggles and conflict-strategy selection; broader media/library validation and post-import reporting are still limited. |
+| Settings | Partial | `confirmed`: provider, playback, parental, language, and backup controls already existed; this pass improves hierarchy with an overview card, section descriptions, cleaner provider status/warning copy, a real provider diagnostics panel with per-domain sync timestamps/counts and capability summaries, plus backup preview/import planning and a DVR status section, but deeper organization is still needed. |
+| Localization | Full | `confirmed`: many translations and RTL handling exist. |
+| Diagnostics overlay | Partial | `confirmed`: player stats now include provider/source, decoder mode, stream class, playback state, archive support, alternate stream count, channel error history, last failure reason, recovery actions, and troubleshooting hints; it is substantially stronger, but still not a dedicated end-to-end troubleshooting center. |
+| Channel history / recent channels | Partial | `confirmed`: Live TV still exposes a reachable `Recent` category in the sidebar, and Player still surfaces recent channels plus remembered `Last Group` context inside playback overlays; the extra Live TV header shortcuts were removed because they cluttered browsing. |
+| External player support | Missing | `confirmed`: no external player path found. |
+| Recording | Partial | `confirmed`: local live DVR v1 now has a real recording manager, scheduled/manual recording state, reachable Player actions for record/stop/schedule, and a Settings surface for storage plus job management; it is still limited to direct stream URLs and does not yet include a recordings browser or background-robust scheduling. |
+| Playlist merge / cross-provider unified library | Missing | `confirmed`: one active provider model, not merged unified browsing. |
+
+## C. Partial / Incomplete Feature Report
+- Favorites and custom groups
+ - `confirmed`: storage and group membership are implemented.
+ - `confirmed`: the main user path is the in-context category rails for Live, Movies, and Series, not the standalone Favorites route.
+ - `confirmed`: Home now exposes the standalone saved-library route directly, so users have a real landing-surface entry point into that broader saved view.
+ - `confirmed`: Live TV, Movies, and Series now support rename/delete/reorder management for custom groups directly from category long-press actions, with visible on-screen feedback.
+ - `confirmed`: rename persistence had a real bug in Movies/Series because the UI was passing virtual negative IDs instead of stored group IDs; this branch fixes that.
+ - `confirmed`: Movies and Series expose saved shortcuts in the main browse surface, but Live TV was deliberately simplified again after user review, so saved groups now stay primarily in the category rail there instead of competing with the channel grid.
+ - `confirmed`: Movies and Series now keep saved shortcuts visible when you are inside a saved category, and they expose an explicit `Browse All` return path from that same strip instead of forcing a sidebar bounce.
+ - `confirmed`: saved shortcut cards in Movies and Series can now long-press directly into group-management flows, so users do not have to backtrack to the sidebar just to rename, delete, or reorder a saved group.
+ - `confirmed`: reorder mode now uses the long-pressed saved category itself in Live TV, Movies, and Series instead of accidentally reordering whatever category happened to be open or whatever preview shelf data was already on screen.
+ - `confirmed`: Movies and Series saved-category views now show an inline saved-group context card with item counts plus direct `Manage` and `Browse All` actions, so saved views feel like intentional destinations instead of generic filtered grids.
+ - `confirmed`: saved shortcut ordering is cleaner now: no duplicate `Favorites`, and empty groups are no longer surfaced as if they were meaningful saved destinations.
+ - `confirmed`: the standalone Saved Library screen now exposes a proper overview card, type filters, quick section jumps, direct Continue Watching plus Recent Live rows, visible browse sort presets for manual order, recent activity, and alphabetical browsing, and higher-level saved presets like `Watch Next`, `Live Recall`, Movies, Series, and Custom Groups.
+ - `confirmed`: the Saved Library hub now also exposes managed custom-group actions directly inside the route itself: remove from current saved context, move items between groups, merge groups, delete groups, and pin or unpin live groups for Home surfacing.
+ - `confirmed`: Home now respects promoted live groups from the Saved Library hub, so the cross-surface saved model is no longer purely passive.
+ - `confirmed`: the Saved Library hub now supports current-provider versus all-provider scoping without leaving the route.
+ - `confirmed`: the Saved Library hub now also exposes a dedicated `Home Shelf` preset so live favorites and promoted live groups can be reviewed as a real dashboard policy, not just hidden long-press state.
+ - Still incomplete: current-provider scope is real, but `All Providers` is still a cross-provider filter over saved/history data, not a true merged-provider browse model, and saved-group policy controls still stop at Home promotion.
+ - Production-grade finish: keep unifying favorites, recents, continue watching, and custom groups into one coherent library model while adding true merged-provider behavior, stronger preset policy, and richer in-place actions.
+- Recent channels / live history
+ - `confirmed`: live playback now records into history and Live TV exposes a dedicated `Recent` virtual category in the category rail.
+ - `confirmed`: `Recent` now stays visible in the Live TV category rail even before it has any channel history, so the feature is actually discoverable from reachable UI.
+ - `confirmed`: this pass removes the extra Live TV header shortcuts for `Recent`, `Last Channel`, and `Last Group`; those controls were making the browse surface feel jammed instead of premium.
+ - `confirmed`: Home now surfaces live memory where it belongs: recent channels plus quick-access shortcuts for Favorites, Recent, Last Group, and populated custom live groups.
+ - `confirmed`: Player still surfaces recent channels and the remembered `Last Group`, so the live-memory model remains available where it is more contextually appropriate.
+ - `confirmed`: Player now surfaces recent channels through the live info/channel-list flow instead of trapping recents on Home only.
+ - `confirmed`: Player now also exposes the remembered `Last Group` through the live info overlay and channel-list header, so the browsing-memory model carries into playback instead of stopping at the Live TV screen.
+ - Still incomplete: no top-nav shortcut, no richer timeline/history presentation, and no broader recall model outside Live TV, Player, Home, and Saved Library.
+ - Production-grade finish: add recent-channel row/shortcut entry points, mini-guide recall, and broader provider-aware surfacing across Live TV, Player, and any future landing surface.
+- Full-screen EPG
+ - `confirmed`: was placeholder-heavy and only now-playing based.
+ - `confirmed`: earlier work added actionable channel launch and program detail dialog plus short schedule loading.
+ - `confirmed`: this pass adds category filtering, guide summary metadata, retry handling, stale/missing-data messaging, visible time-window controls, direct day browsing, half-hour and prime-time jumps, a shared aligned timeline grid with current-time line, time-scaled program placement, a `Scheduled only` mode that hides channels with no guide data, and guide modes for anchor-time and archive-ready browsing.
+ - `confirmed`: the full guide now launches archive-capable programs directly into catch-up playback instead of stopping at a read-only detail dialog.
+ - `confirmed`: the guide now exposes layout-density controls for compact, comfortable, and larger-screen browsing.
+ - `confirmed`: the guide now exposes full-window paging actions, so users can move across broader timeline blocks without chaining repeated small jumps.
+ - `confirmed`: favorite live channels now get visible overlay treatment inside the guide grid, and program dialogs now explain archive availability more clearly by distinguishing archive-ready programs from provider-level catch-up support and fully unavailable replay.
+ - `confirmed`: the guide side panel now also includes provider-source metadata and a provider troubleshooting card that explains replay template issues, missing stream ids, stale guide risk, and other provider-specific replay blockers more explicitly.
+ - `confirmed`: full-guide launches now preserve exact category, anchor-time, and favorites-only context into Player and can navigate back through the same guide route instead of dropping users into a generic guide state.
+ - `confirmed`: the program detail surface now exposes channel, provider, language, replay state, progress, stale-guide refresh, and nearby schedule context through a dedicated TV-style side panel instead of a thin alert dialog.
+ - Still incomplete: deeper archive reasoning is materially better now, but it is still bounded by provider metadata quality rather than guide-surface mechanics alone.
+- Movies and Series browsing
+ - `confirmed`: rows, hero content, category rails, continue watching, and dialogs exist.
+ - `confirmed`: typed search path previously relied on extra UI-side filtering over full collections.
+ - `confirmed`: this pass moves typed query mode onto repository-backed search flows, shifts selected-category loading onto category-scoped repository queries, and changes all-library rows into preview shelves with accurate category counts instead of treating every category row as a full in-memory list.
+ - `confirmed`: Movies and Series now expose real `See All` actions per row, and selected-category views use dedicated full-list loads while all-category mode stays preview-oriented.
+ - `confirmed`: selected Movies and Series categories now expose visible filter and sort chips for favorites, resume/in-progress, unwatched or updated content, top-rated content, and ordering by library, title, freshness, or rating, but the UI now suppresses that control stack for very small non-saved categories where it was crowding out the actual titles.
+ - `confirmed`: selected Movies and Series categories now load in bounded pages with explicit `Load more` affordances and visible loaded-count feedback, so large provider categories no longer dump their full contents into the UI at once.
+ - `confirmed`: all-library mode now adds repository-backed lens rows for Favorites, Continue Watching, Top Rated, and Fresh content instead of relying only on broad category maps.
+ - `confirmed`: Movies and Series now expose a query-backed `Browse Full Library` mode from the all-library surface, so full-provider paging is no longer limited to category-specific views.
+ - Still incomplete: there is still no full-library section virtualization, no provider-scoped advanced sort/filter surface, and no repository-backed multi-facet retrieval model beyond the current lens layer, full-library browse mode, and selected-category view.
+- Search
+ - `confirmed`: search results work and now launch player with correct context.
+ - `confirmed`: Search now keeps recent queries in reachable UI so repeat searches are faster on TV remotes.
+ - `confirmed`: Search now avoids blank result panes by surfacing explicit no-provider and minimum-query states, and the results side now exposes one-click content-type narrowing with visible counts.
+ - `confirmed`: Search now restores focus back to the main query field after PIN interruptions, which makes repeated TV search sessions less awkward.
+ - `confirmed`: Search now renders those empty and readiness states through the same elevated empty-state treatment instead of a plainer one-off layout, which improves consistency with the rest of the premium TV direction.
+ - Still incomplete: no top-level filter/sort presets, no provider scoping toggle, and no deeper power-user shortcuts beyond text entry, recent queries, and content-type narrowing.
+- Catch-up / archive
+ - `confirmed`: program archive and restart actions exist.
+ - `confirmed`: the full guide now exposes a direct catch-up handoff into Player for archive-capable programs instead of only offering live-channel launch.
+ - `confirmed`: Player now surfaces explicit typed in-player recovery notices when catch-up context is missing or a provider does not return a replay stream, instead of failing silently.
+ - `confirmed`: the player diagnostics overlay now also carries provider/source, stream-class, playback state, archive support status, alternate-stream count, channel error history, last failure reason, recent recovery actions, and troubleshooting hints, so archive failures are not just raw error toasts anymore.
+ - `confirmed`: catch-up failure messages now distinguish between missing archive support, missing replay template, missing replay stream id, and provider replay rejection more clearly.
+ - `confirmed`: the live playback error surface now exposes a direct `Last Channel` recovery action alongside retry when a previous live channel exists, which is a more TV-native recovery path than forcing users to back out manually.
+ - `likely`: real-world provider reliability will still vary because catch-up templates/providers are messy and provider-specific degradation handling is still limited.
+ - Production-grade finish: provider-specific replay failure reasons and richer archive metadata.
+- Home dashboard
+ - `confirmed`: Home is no longer just a hero plus static rows; it now exposes provider-health context directly and reorders its shelves around the current feature/action focus.
+ - `confirmed`: this makes the landing surface feel more responsive to actual user state instead of forcing one fixed rail order all the time.
+ - `confirmed`: Home now also surfaces active-provider warnings with a direct Settings drill-down instead of burying those issues only inside Settings.
+ - Still incomplete: no editorial curation and no user-configurable layout.
+- Multiview
+ - `confirmed`: working slot playback exists.
+ - `confirmed`: the multiview screen now has focused-slot replace/remove actions plus audio pinning so users can keep one tile audible while moving focus elsewhere.
+ - `confirmed`: multiview now auto-detects a device performance tier, exposes a visible performance-mode selector, caps active simultaneous slots by policy, and holds extra slots in standby instead of trying to decode everything at once on weaker hardware.
+ - `confirmed`: multiview now samples live slot telemetry, exposes a visible runtime profiling summary, tracks dropped-frame/buffering/error pressure, and dynamically reduces active decoders when sustained load, memory pressure, or thermal status demand it.
+- Provider diagnostics
+ - `confirmed`: Home already exposed warning and health surfacing, and Settings already had warning-driven retry actions.
+ - `confirmed`: this pass turns the provider card into a real diagnostics entry point with sync-domain timestamps, item counts, last sync status, provider source/expiry/connection/archive summaries, and provider capability notes.
+ - Still incomplete: no dedicated diagnostics route and no historical sync logs.
+- Backup / restore
+ - `confirmed`: backup now carries expanded preferences, provider definitions, playback history, promoted groups, and multiview presets.
+ - `confirmed`: Settings now inspects a backup before import, shows section counts/conflicts, lets users choose keep-versus-replace behavior, and supports selective section import.
+ - Still incomplete: import reporting is still summary-level, not a detailed conflict-by-conflict report, and broader media/library validation is limited.
+ - Production-grade finish: add integrity reporting, richer skipped-item diagnostics, and clearer partial-restore messaging.
+
+## D. Premium Gap Analysis
+- What premium IPTV apps do better
+ - `confirmed`: they preserve playback context consistently across every launch path. StreamVault had gaps in Search and Favorites until this pass.
+ - `confirmed`: they make the guide actionable and central to Live TV, not a secondary placeholder screen.
+ - `likely`: they use stronger VOD/Series information architecture for huge libraries, often with faster facet/filter systems than StreamVault currently exposes.
+ - `likely`: they surface recent channels, better favorites/group workflows, and clearer provider health/troubleshooting.
+- What this app still lacks
+ - External player support.
+ - Deeper full-guide personalization and overlays on top of the current timeline/return-context model.
+ - Unified multi-provider or merged-library workflows.
+ - A fuller recordings browser and more robust DVR scheduling lifecycle.
+- Highest impact remaining changes
+ 1. Deepen Favorites into a stronger saved-library hub with better management presets and saved views.
+ 2. Extend recent channels into a stronger live-memory model anchored in Home and Player, not jammed into the Live TV browse header.
+ 3. Upgrade full-screen EPG from the current strong timeline surface into a more personalized and overlay-rich guide.
+ 4. Push Movies/Series from the current lens layer and selected-category paging into deeper repository-backed multi-facet retrieval and large-library virtualization.
+
+## E. UI / UX Findings
+- TV navigation issues
+ - `confirmed`: Search and Favorites player launches were missing context, which broke zap/EPG behavior from those entry points.
+ - `confirmed`: full-screen EPG row/program clicks were placeholders.
+- Focus issues
+ - `confirmed`: many screens already manage focus well; Home and Player are stronger than average.
+ - `likely`: Search, Favorites, Settings, and Series detail still need a consistency pass to reach the same standard.
+- Discoverability issues
+ - `confirmed`: custom groups, replay, diagnostics, and some long-press actions are more discoverable to expert users than first-time TV users.
+- Visual hierarchy issues
+ - `confirmed`: Home/Player/Movies feel more premium than EPG/Favorites/Series detail.
+ - `confirmed`: some screens still use hardcoded or generic copy instead of a shared premium tone, though Settings is noticeably stronger after the overview/section polish pass.
+- Workflow friction
+ - `confirmed`: recent-live browsing now lives in the Live TV category rail plus Player overlays, and Home now adds category-aware live shortcuts and a recent-channels row without polluting the Live TV browse screen.
+ - `confirmed`: favorites/group workflows are improved in the category rails users actually use, Movies/Series still expose saved shortcuts directly in the main browse surface with long-press management and inline saved-group context cards, Home now exposes a direct saved-library entry point, and the Saved Library route now also covers Continue Watching and Recent Live; Live TV was intentionally simplified after review so saved groups do not crowd the main browse area there.
+ - `confirmed`: the guide now behaves like a real aligned schedule surface with shared time markers, denser jump controls, and properly scaled program placement across rows, which is a major quality jump over the earlier pseudo-timeline list.
+ - `confirmed`: the guide now offers visible density/layout choices and full-window paging, so users can trade channel density against readability and move across broader time blocks without repetitive step-jumping.
+ - `confirmed`: Movies and Series now expose a visible Library Lens row in all-library mode, so Favorites, Continue Watching, Top Rated, and Fresh content are reachable without drilling into raw categories first.
+ - `confirmed`: Search no longer drops into a blank pane when prerequisites are missing, and result narrowing is now possible from the results side instead of forcing users back to the left-side tab chips only.
+ - `confirmed`: Settings now exposes a clearer top-level overview and section subtitles, so it reads more like a control center than a long undifferentiated list.
+ - `confirmed`: Settings now also gives the no-provider case a proper empty state instead of a bare line of copy, and Player overlays now explain the channel-list and mini-guide actions more clearly from within playback.
+- Premium polish issues
+ - `confirmed`: loading/error/empty states are inconsistent.
+ - `likely`: transitions and screen-to-screen rhythm still need one dedicated polish pass.
+
+## F. Performance & Reliability Findings
+- Bottlenecks
+ - `confirmed`: Movies and Series were still doing redundant UI-side filtering for search.
+ - `confirmed`: full-library grouping for VOD/Series was too eager; this pass shifts selected-category loads to category-scoped repository queries and changes all-category browsing into lighter preview shelves.
+ - `confirmed`: selected provider-category views no longer need to load the entire category at once; they now use bounded page loads with explicit expansion.
+ - `likely`: full-screen EPG should stay bounded; the current pass limits guide loading to a visible subset for safety while rendering that window as a denser aligned grid.
+- Risks
+ - `confirmed`: favorites/global routes had broken playback context before this pass.
+ - `confirmed`: live channel identity inside Player was going stale after zaps before this pass; that is now fixed.
+ - `likely`: current "all categories" VOD/Series presentations still scale worse than Live TV.
+ - `confirmed`: the app now contains runtime multiview telemetry and thermal/load guards, but `likely` lower-end Android TV hardware still needs manual profiling sessions to validate sustained behavior under real decoder, thermal, and memory pressure.
+- Optimization opportunities
+ - Introduce richer image sizing/prefetch policies for posters/backdrops/logos.
+ - Add recent-query and cached-result layers for search.
+ - Consider a dedicated guide cache/view model for longer-range EPG timeline navigation.
+- Scalability concerns
+ - `confirmed`: Live is still architecturally ahead of VOD/Series in large-library readiness, but the gap is smaller now that Movies/Series use preview shelves, category-scoped exact loads, bounded page loads, and repository-backed all-library lens rows.
+ - `likely`: 50k+ VOD/Series libraries will still need a deeper data-flow rewrite beyond this pass, especially for full-library paging, virtualization, and richer multi-facet retrieval across mixed provider/category surfaces.
+
+## G. Missing Features Roadmap
+### Core expected
+- Merged-provider Saved Library behavior and final management polish
+ - User value: high
+ - UX impact: high
+ - Complexity: medium
+ - Effort: medium
+- Deeper recent channels / live history workflows
+ - User value: high
+ - UX impact: high
+ - Complexity: medium
+ - Effort: medium
+- Premium full-screen guide overlays and personalization
+ - User value: high
+ - UX impact: high
+ - Complexity: medium-high
+ - Effort: medium-large
+
+### Premium
+- Repository-backed full-library VOD/Series paging and deeper multi-facet retrieval
+ - User value: high
+ - UX impact: high
+ - Complexity: high
+ - Effort: medium-large
+- Provider diagnostics and troubleshooting center
+ - User value: medium
+ - UX impact: medium
+ - Complexity: medium
+ - Effort: medium
+- Backup/restore integrity reporting and detailed conflict diagnostics
+ - User value: medium
+ - UX impact: medium
+ - Complexity: medium
+ - Effort: medium
+
+### Exceptional / differentiating
+- Unified multi-provider merged library
+ - User value: high
+ - UX impact: high
+ - Complexity: high
+ - Effort: large
+- Channel surfing memory model
+ - Notes: recent channels, smart last-groups, mini-guide recall, provider-aware history
+ - User value: high
+ - Effort: medium
+- Advanced multiview control layer
+ - Notes: slot presets, audio pinning, quick replace/remove, and device-tier runtime resource profiles are now implemented; remaining gap is real-device tuning on weaker Android TV hardware.
+ - User value: medium-high
+ - Effort: medium-large
+- DVR / recording
+ - Notes: local live DVR v1 now exists; remaining gap is a recordings browser, more robust scheduling lifecycle, and broader protocol/provider support
+ - User value: high
+ - Effort: large
+
+## H. Changes Implemented
+- `confirmed`: created session branch `session/premium-audit-2026-03-11`.
+- `confirmed`: tightened the internal player launch contract by adding route helpers for Live, Movie, and Episode playback.
+- `confirmed`: fixed Search player navigation so it now preserves `providerId`, `categoryId`, `internalId`, and content type.
+- `confirmed`: fixed Favorites player navigation so live/movie launches retain provider and playback context instead of using `-1` fallbacks, including grouped-live playback context.
+- `confirmed`: enriched `FavoriteUiModel` with provider/category/EPG context and launch metadata needed for correct playback behavior.
+- `confirmed`: made full-screen EPG actionable by wiring channel launch and program detail dialog instead of leaving TODO click handlers.
+- `confirmed`: upgraded full-screen EPG data loading from "now playing only" to a bounded schedule window per visible channel.
+- `confirmed`: added Live category filtering to the full-screen EPG instead of always loading the first global channel slice.
+- `confirmed`: added guide summary/status UI for channel coverage, last refresh timing, and stale-data warnings.
+- `confirmed`: upgraded EPG empty/error states with retry actions and clearer no-provider/no-category feedback.
+- `confirmed`: added visible guide time controls for jumping backward, jumping forward, returning to now, and moving to tomorrow.
+- `confirmed`: added direct day-navigation controls to the TV Guide so users can move across dates without chaining repeated time-window jumps.
+- `confirmed`: added a `Scheduled only` guide mode so large or messy provider guides can hide empty channels instead of mixing no-data rows into the main schedule view.
+- `confirmed`: added guide-mode chips for full timeline browsing, anchor-time browsing, and archive-ready rows so the guide can pivot between broad exploration and IPTV-specific catch-up hunting.
+- `confirmed`: added guide density/layout chips so users can switch between compact, comfortable, and larger-row guide presentations from the TV Guide itself.
+- `confirmed`: added full-window guide paging actions so users can move across larger guide blocks without repeatedly stacking half-hour and three-hour jumps.
+- `confirmed`: added a clear guide-window label so the EPG shows which time range is currently loaded.
+- `confirmed`: added a visible timeline-style ruler to the TV Guide so the loaded window reads more like a real guide surface instead of a plain list of program cards.
+- `confirmed`: added live progress treatment to currently airing guide cards, including progress bars and remaining-time labels.
+- `confirmed`: upgraded the full-screen guide into an aligned timeline grid with shared half-hour markers, a persistent current-time line, and time-scaled program placement across channel rows.
+- `confirmed`: added denser guide time navigation with half-hour jumps and a direct `Prime Time` jump alongside the existing day/window controls.
+- `confirmed`: added archive-ready program labeling inside the full guide so catch-up-capable entries are visually distinct without opening Player first.
+- `confirmed`: persisted TV Guide density, mode, favorite-channel-only filtering, and anchor-time defaults so the guide reopens in the user’s last working state instead of resetting each session.
+- `confirmed`: added a favorite-channel-only guide source filter so the full guide can collapse down to pinned live channels without changing categories.
+- `confirmed`: extended the full-guide navigation contract so guide category, anchor time, and favorites-only state can be passed through player launches as an exact return route.
+- `confirmed`: moved Movies and Series typed search mode onto repository-backed search flows instead of re-filtering the full in-memory list.
+- `confirmed`: added repository-backed preview queries and count flows for Movies and Series so all-library browsing can stay preview-oriented while selected categories load their full contents on demand.
+- `confirmed`: moved Movies and Series selected-category views onto dedicated category-scoped repository loading instead of relying on the all-library grouped map as the working dataset.
+- `confirmed`: turned Movies and Series category rows into true preview shelves with actionable `See All` controls and accurate category/library counts.
+- `confirmed`: added repository-backed page loading for selected provider categories in Movies and Series, plus visible `Loaded X of Y` feedback and `Load more` actions on the grid surfaces.
+- `confirmed`: introduced explicit `LibraryBrowseQuery` and `PagedResult` contracts plus repository-backed browse methods for Movies and Series so category paging is no longer just a UI convention.
+- `confirmed`: added a visible query-backed `Browse Full Library` mode to Movies and Series so users can page through the full provider catalog without drilling into categories first.
+- `confirmed`: added recent-search shortcuts and clear-history controls to the Search screen so repeat searches are reachable without retyping.
+- `confirmed`: added SearchViewModel coverage for recent-query history behavior.
+- `confirmed`: upgraded Search empty-state behavior so it now shows explicit no-provider, ready-to-search, and no-results messaging instead of leaving the results pane visually blank.
+- `confirmed`: added results-summary chips to Search so users can narrow to Live TV, Movies, or Series directly from the results side with visible counts.
+- `confirmed`: added SearchViewModel coverage for provider/query readiness state under the debounced search flow.
+- `confirmed`: upgraded Settings with a top-level overview card, section subtitles, and cleaner provider warning/status copy so the screen feels more deliberate and TV-native.
+- `confirmed`: upgraded Settings provider cards into a real diagnostics surface with per-domain sync timestamps and counts, last sync status, capability summaries, and the existing retry actions in one place.
+- `confirmed`: reduced a broad hero selection flattening path in Movies to a first-item-per-category scan.
+- `confirmed`: added a shared virtual-category contract for Favorites and Recent channels.
+- `confirmed`: rebuilt the Favorites screen into real saved-library sections: global favorites plus populated Live/Movie/Series custom groups.
+- `confirmed`: added section-scoped reorder behavior in Favorites instead of global flat-list reorder only.
+- `confirmed`: turned the standalone Saved Library route into a real hub with overview stats, type filters, and section-jump chips now that Home exposes it.
+- `confirmed`: expanded the Saved Library hub with Continue Watching and Recent Live rows so the route now unifies saved items with playback recall workflows instead of only listing favorites/groups.
+- `confirmed`: added Saved Library sort presets for manual order, recent activity, and alphabetical browsing without breaking the existing manual reorder flow.
+- `confirmed`: tied Saved Library recent sorting to playback-history activity so the new sort presets reflect actual use instead of static metadata.
+- `confirmed`: added higher-level Saved Library preset views for `All Saved`, `Watch Next`, `Live Recall`, Movies, Series, and Custom Groups so the hub now behaves more like a recall dashboard than a flat saved list.
+- `confirmed`: added a managed custom-groups row to the Saved Library hub with direct long-press actions for merge, delete, reorder, and Home promotion, plus item-level remove and move-between-group actions without leaving the hub.
+- `confirmed`: changed Saved Library group clicks to jump within the hub itself instead of bouncing users out to other top-level screens, keeping the route as the canonical cross-type management surface.
+- `confirmed`: added provider scoping inside the Saved Library hub so users can switch between current-provider and all-provider saved/history views without leaving the screen.
+- `confirmed`: added a dedicated `Home Shelf` saved preset so promoted live groups and dashboard-eligible live favorites can be reviewed and managed intentionally.
+- `confirmed`: added recent-live history recording and surfaced it as a Live TV virtual category with proper playlist/zap context.
+- `confirmed`: made the Live TV `Recent` category permanently visible in the sidebar, even when empty, so the feature is discoverable from reachable UI.
+- `confirmed`: added provider-scoped `Last Group` memory for Live TV and Player, then intentionally removed the extra Live TV header shortcuts after review so the browse screen is no longer acting like a cluttered pseudo-home.
+- `confirmed`: surfaced recent live channels inside Player via a visible quick action and a recent row in the channel list overlay.
+- `confirmed`: surfaced the remembered live `Last Group` inside Player through both the live info overlay and the channel-list header, so browsing memory carries into playback UI too.
+- `confirmed`: updated Player state on channel changes so live playback context, title, and URL do not go stale after zapping.
+- `confirmed`: fixed the Player channel-list selection highlight so it tracks the currently tuned channel instead of the original route channel ID after zapping.
+- `confirmed`: added a non-resume playback history write path for live sessions while keeping VOD resume writes separate.
+- `confirmed`: filtered Movies and Series continue-watching rows so newly recorded live history does not pollute VOD surfaces.
+- `confirmed`: added custom-group rename/manage actions directly to Movies and Series category sidebars instead of treating the standalone Favorites route as the primary workflow.
+- `confirmed`: added the same custom-group rename flow to the reachable Live TV category rail for parity with Movies and Series.
+- `confirmed`: fixed custom-group rename persistence so Movies, Series, and Live TV now map virtual category IDs back to the real stored group IDs before renaming.
+- `confirmed`: kept the built-in `Favorites` bucket fixed/reserved and limited rename management to true custom groups.
+- `confirmed`: added visible snackbar feedback for Movies and Series group create/rename/delete actions.
+- `confirmed`: replaced more hardcoded Movies/Series category sidebar copy with string resources.
+- `confirmed`: removed a broad `flatten()` hero-pick path in Series in favor of the same first-item-per-category scan used in Movies.
+- `confirmed`: added reachable saved-shortcuts strips to the Movies and Series main browse surfaces so Favorites and populated custom groups are one-click targets instead of being buried only in the sidebar.
+- `confirmed`: added empty-state guidance to those saved-shortcut strips so users can tell how to populate saved items before the shortcuts appear.
+- `confirmed`: fixed Movie/Series saved shortcut construction so `Favorites` is no longer duplicated, empty groups are filtered out, and an explicit `Browse All` shortcut is available from the same strip.
+- `confirmed`: kept the saved shortcut strips visible in saved-category Movies/Series views so switching between Favorites, custom groups, and the full library no longer depends on going back to the sidebar, while normal provider categories stay visually cleaner.
+- `confirmed`: added direct long-press management from saved shortcut cards in Movies and Series, plus an on-screen hint so saved groups are not browse-only shortcuts anymore.
+- `confirmed`: added inline saved-group context cards to selected Movies and Series saved views with direct `Manage` and `Browse All` actions plus visible item counts.
+- `confirmed`: added category-scoped Movies and Series facet/sort chips so users can narrow selected categories by favorites, resume state, unwatched or updated content, and rating without forcing a full-library load.
+- `confirmed`: trimmed the selected-category VOD/Series chrome so normal provider categories no longer show the full Saved block, and small categories now skip the bulky facet/sort stack that was pushing the actual titles off-screen.
+- `confirmed`: added repository-backed all-library Library Lens rows to Movies and Series for Favorites, Continue Watching, Top Rated, and Fresh content so premium discovery is no longer limited to raw category rails.
+- `confirmed`: created a real dashboard-style Home screen and split Live TV into its own dedicated top-level route instead of using the Live browser as the landing page.
+- `confirmed`: expanded Home into a richer landing surface with featured hero state, library stats, live shortcut cards, recent live channels, and category-aware deep links back into Live TV groups.
+- `confirmed`: added provider-health surfacing to Home so the dashboard now exposes provider status, source type, sync recency, expiry context, and connection count without sending users into Settings first.
+- `confirmed`: made Home shelf ordering more adaptive by biasing the row order toward the current hero/feature context instead of leaving the dashboard static.
+- `confirmed`: added provider-warning surfacing on Home with a direct Settings drill-down so partial sync issues are visible from the landing surface.
+- `confirmed`: reinforced Home-to-diagnostics flow by making the provider-health card itself expose the diagnostics drill-down action instead of relying only on warning states.
+- `confirmed`: extended the player route contract with optional archive-window parameters so the full TV Guide can launch directly into catch-up playback.
+- `confirmed`: added a full-guide `Play Catch-up` action for archive-capable programs instead of limiting program dialogs to live-channel launch only.
+- `confirmed`: added an in-player archive failure notice so missing catch-up URLs or invalid replay context are surfaced to the user instead of failing silently.
+- `confirmed`: added favorite-channel badging directly inside the guide grid and upgraded the program dialog with provider-level archive hints plus stale-guide replay caveats so archive-heavy browsing gives clearer context before playback starts.
+- `confirmed`: added a direct saved-library entry point from Home and promoted the standalone Favorites route into an actual reachable product surface instead of leaving it effectively hidden.
+- `confirmed`: simplified the Live TV browse surface by removing the added saved/recent/last-group shortcut strip from the content area.
+- `confirmed`: added category-aware `Live TV` route deep links so Home shortcuts can open Favorites, Recent, Last Group, and custom live groups directly instead of always landing on the generic Live view.
+- `confirmed`: fixed focus restoration after closing category/group option dialogs so the previously focused group stays active in Live TV, Movies, and Series.
+- `confirmed`: fixed category reorder targeting so Live TV, Movies, and Series now reorder the long-pressed saved category instead of the currently open category or a partial preview list.
+- `confirmed`: replaced the inline custom-group creation mode inside the add-to-group dialog with a dedicated create-group dialog to reduce keyboard/back-flow conflicts.
+- `confirmed`: removed nested-dialog stacking during group creation so the Add-to-Group sheet now yields to dedicated create/split dialogs instead of keeping multiple active dialog layers alive under the TV keyboard.
+- `confirmed`: tightened Create Group dialog behavior by trimming names, disabling empty confirmation, and hiding the software keyboard on confirm/dismiss.
+- `confirmed`: tightened PIN dialog behavior by showing the numeric keyboard on entry and hiding it on submit/dismiss so TV modal transitions leave less keyboard residue behind.
+- `confirmed`: restored Search focus to the main query field on entry and after PIN dismissal so repeated search/refine flows behave more like a TV-native search surface.
+- `confirmed`: upgraded the player error surface with an explicit `Last Channel` recovery action for live playback instead of leaving recovery at `Retry` plus a passive back hint only.
+- `confirmed`: replaced plain player notice strings with typed recovery notices that can expose `Retry`, `Alternate Stream`, `Last Channel`, and `Open Guide` actions directly from the playback surface.
+- `confirmed`: added session-level alternate-stream failure memory so the player deprioritizes already-failed alternates during the same viewing session before surfacing fallback actions.
+- `confirmed`: expanded the in-player diagnostics overlay with provider/source, decoder mode, stream class, playback state, archive support, alternate-stream count, channel error history, last failure reason, recovery actions, and troubleshooting hints so the player now shows actual troubleshooting context instead of only raw codec/bitrate stats.
+- `confirmed`: added exact guide-return behavior from player notices so `Open Guide` can navigate back to the originating full-guide route instead of only opening a generic overlay.
+- `confirmed`: replaced the old guide alert dialog with a TV-style program side panel that adds provider/channel/language/replay/progress metadata, nearby schedule context, and a direct stale-guide refresh action.
+- `confirmed`: updated Player back behavior so transient player notices dismiss before playback exits, which makes the overlay stack feel less abrupt on the remote.
+- `confirmed`: added clearer inline guidance to the Player channel list and mini-guide overlays, and upgraded the Settings no-provider surface to the same elevated empty-state treatment used elsewhere.
+- `confirmed`: added multiview presets backed by preferences so common split-screen slot layouts can be saved and restored.
+- `confirmed`: added focused-slot multiview controls for replace, remove, and audio pinning, so split-screen management no longer depends only on the planner dialog or focus-follow audio.
+- `confirmed`: added a device-tier multiview performance policy with persisted Auto / Conservative / Balanced / Maximum modes, effective active-slot caps, staged decoder startup, and standby messaging for slots held back on weaker devices.
+- `confirmed`: added telemetry-backed multiview protection with dropped-frame/buffering/error sampling, runtime profiling summaries, low-memory standby handling, and thermal-aware slot throttling on supported Android TV versions.
+- `confirmed`: expanded Settings provider diagnostics with source, expiry, connection, and archive summaries instead of only capability text plus sync counts.
+- `confirmed`: expanded the guide side panel with provider-specific replay troubleshooting so catch-up blockers like missing templates, missing replay stream ids, and stale guide risk are explained in-place.
+- `confirmed`: upgraded catch-up failure reasoning in Player so replay errors describe the likely provider-side blocker instead of collapsing into one generic replay failure message.
+- `confirmed`: expanded backup/restore into version 2 data bundles that now include providers, playback history, promoted live groups, guide preferences, and multiview presets.
+- `confirmed`: upgraded Settings backup import into a real preview/conflict flow with section counts, conflict counts, keep-vs-replace strategy, and per-section import toggles before applying a restore.
+- `confirmed`: wired the existing recording manager into DI and shipped local live DVR v1 with manual recording, scheduled recording, storage state, persisted recording jobs, and stop/cancel actions.
+- `confirmed`: added reachable DVR UI in Player for `Record`, `Stop Recording`, and `Schedule`, and added a Settings recording section that surfaces storage health, active jobs, scheduled jobs, and failure reasons.
+- `confirmed`: added navigation contract tests for Live/Movie/Episode routes.
+- `confirmed`: added route tests covering full-guide route context and player return-route preservation.
+- `confirmed`: added HomeViewModel coverage for the new recent-live virtual category behavior, including empty-history visibility.
+- `confirmed`: `./gradlew test` passes after the changes.
+
+## I. Recommended Next Roadmap
+1. Quick wins
+ - Refine the new Home dashboard with deeper personalization on top of the new hero/health/warning/shortcut structure.
+ - Tighten Saved Library policy controls beyond provider scoping and Home promotion.
+2. Medium effort / high value
+ - Move Movies/Series from the current browse-query foundation and selected-category paging into repository-backed multi-facet retrieval and deeper full-library paging.
+ - Deeper Settings reorganization around Provider, Playback, Library, and Privacy beyond the new overview/section polish.
+ - Stronger Search UX with saved queries and result shortcuts.
+ - Expand the typed player recovery model into a fuller diagnostics and recovery panel with deeper provider-account troubleshooting context.
+3. Major premium upgrades
+ - DVR recordings browser plus stronger scheduling lifecycle beyond in-app state.
+ - Backup/restore integrity reporting and conflict-by-conflict diagnostics.
+ - Advanced archive overlays and personalization on top of the new aligned timeline grid.
+4. Standout differentiators
+ - Manual multiview profiling and tuning on real lower-end Android TV hardware now that the in-app telemetry/protection layer exists.
+ - Unified multi-provider browsing.
+ - Live-TV surfer mode with recent-channel intelligence and ultra-fast recall.
diff --git a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt
index c08c2634..89ecc7be 100644
--- a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt
+++ b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt
@@ -1,13 +1,51 @@
package com.streamvault.domain.manager
+import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.Provider
import kotlinx.coroutines.flow.Flow
import com.streamvault.domain.model.Result
data class BackupData(
- val version: Int = 1,
+ val version: Int = 2,
val preferences: Map<String, String>? = null,
+ val providers: List<Provider>? = null,
val favorites: List<com.streamvault.domain.model.Favorite>? = null,
- val virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = null
+ val virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = null,
+ val playbackHistory: List<PlaybackHistory>? = null,
+ val multiViewPresets: Map<String, List<Long>>? = null
+)
+
+enum class BackupConflictStrategy {
+ KEEP_EXISTING,
+ REPLACE_EXISTING
+}
+
+data class BackupPreview(
+ val version: Int,
+ val providerCount: Int,
+ val favoriteCount: Int,
+ val groupCount: Int,
+ val playbackHistoryCount: Int,
+ val multiViewPresetCount: Int,
+ val preferenceCount: Int,
+ val providerConflicts: Int,
+ val favoriteConflicts: Int,
+ val groupConflicts: Int,
+ val historyConflicts: Int
+)
+
+data class BackupImportPlan(
+ val importPreferences: Boolean = true,
+ val importProviders: Boolean = true,
+ val importSavedLibrary: Boolean = true,
+ val importPlaybackHistory: Boolean = true,
+ val importMultiViewPresets: Boolean = true,
+ val conflictStrategy: BackupConflictStrategy = BackupConflictStrategy.KEEP_EXISTING
+)
+
+data class BackupImportResult(
+ val importedSections: List<String> = emptyList(),
+ val skippedSections: List<String> = emptyList()
)
interface BackupManager {
@@ -16,8 +54,16 @@ interface BackupManager {
*/
suspend fun exportConfig(uriString: String): com.streamvault.domain.model.Result<Unit>
+ /**
+ * Reads a backup and returns a preview with conflict counts before importing.
+ */
+ suspend fun inspectBackup(uriString: String): Result<BackupPreview>
+
/**
* Imports the configuration from the provided URI string (SAF document URI)
*/
- suspend fun importConfig(uriString: String): com.streamvault.domain.model.Result<Unit>
+ suspend fun importConfig(
+ uriString: String,
+ plan: BackupImportPlan = BackupImportPlan()
+ ): Result<BackupImportResult>
}
diff --git a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt
new file mode 100644
index 00000000..441aaf06
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt
@@ -0,0 +1,17 @@
+package com.streamvault.domain.manager
+
+import com.streamvault.domain.model.RecordingItem
+import com.streamvault.domain.model.RecordingRequest
+import com.streamvault.domain.model.RecordingStorageState
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.flow.Flow
+
+interface RecordingManager {
+ fun observeRecordingItems(): Flow<List<RecordingItem>>
+ fun observeStorageState(): Flow<RecordingStorageState>
+
+ suspend fun startManualRecording(request: RecordingRequest): Result<RecordingItem>
+ suspend fun scheduleRecording(request: RecordingRequest): Result<RecordingItem>
+ suspend fun stopRecording(recordingId: String): Result<Unit>
+ suspend fun cancelRecording(recordingId: String): Result<Unit>
+}
diff --git a/domain/src/main/java/com/streamvault/domain/model/LibraryBrowseQuery.kt b/domain/src/main/java/com/streamvault/domain/model/LibraryBrowseQuery.kt
new file mode 100644
index 00000000..1fc8bc2d
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/LibraryBrowseQuery.kt
@@ -0,0 +1,15 @@
+package com.streamvault.domain.model
+
+data class LibraryBrowseQuery(
+ val providerId: Long,
+ val categoryId: Long? = null,
+ val offset: Int = 0,
+ val limit: Int = 40
+)
+
+data class PagedResult<T>(
+ val items: List<T>,
+ val totalCount: Int,
+ val offset: Int,
+ val limit: Int
+)
diff --git a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt
new file mode 100644
index 00000000..e11efc46
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt
@@ -0,0 +1,40 @@
+package com.streamvault.domain.model
+
+enum class RecordingStatus {
+ SCHEDULED,
+ RECORDING,
+ COMPLETED,
+ FAILED,
+ CANCELLED
+}
+
+data class RecordingRequest(
+ val providerId: Long,
+ val channelId: Long,
+ val channelName: String,
+ val streamUrl: String,
+ val scheduledStartMs: Long,
+ val scheduledEndMs: Long,
+ val programTitle: String? = null,
+ val outputPath: String? = null
+)
+
+data class RecordingItem(
+ val id: String,
+ val providerId: Long,
+ val channelId: Long,
+ val channelName: String,
+ val streamUrl: String,
+ val scheduledStartMs: Long,
+ val scheduledEndMs: Long,
+ val programTitle: String? = null,
+ val outputPath: String? = null,
+ val status: RecordingStatus = RecordingStatus.SCHEDULED,
+ val failureReason: String? = null
+)
+
+data class RecordingStorageState(
+ val outputDirectory: String? = null,
+ val availableBytes: Long? = null,
+ val isWritable: Boolean = false
+)
diff --git a/domain/src/main/java/com/streamvault/domain/model/VirtualCategoryIds.kt b/domain/src/main/java/com/streamvault/domain/model/VirtualCategoryIds.kt
new file mode 100644
index 00000000..103c3285
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/VirtualCategoryIds.kt
@@ -0,0 +1,6 @@
+package com.streamvault.domain.model
+
+object VirtualCategoryIds {
+ const val RECENT = -998L
+ const val FAVORITES = -999L
+}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt
index 66380a66..3bc881d9 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/MovieRepository.kt
@@ -1,15 +1,24 @@
package com.streamvault.domain.repository
import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.LibraryBrowseQuery
import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.PagedResult
import com.streamvault.domain.model.Result
import kotlinx.coroutines.flow.Flow
interface MovieRepository {
fun getMovies(providerId: Long): Flow<List<Movie>>
fun getMoviesByCategory(providerId: Long, categoryId: Long): Flow<List<Movie>>
+ fun getMoviesByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<Movie>>
+ fun getMoviesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Movie>>
+ fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Movie>>
+ fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Movie>>
fun getMoviesByIds(ids: List<Long>): Flow<List<Movie>>
fun getCategories(providerId: Long): Flow<List<Category>>
+ fun getCategoryItemCounts(providerId: Long): Flow<Map<Long, Int>>
+ fun getLibraryCount(providerId: Long): Flow<Int>
+ fun browseMovies(query: LibraryBrowseQuery): Flow<PagedResult<Movie>>
fun searchMovies(providerId: Long, query: String): Flow<List<Movie>>
suspend fun getMovie(movieId: Long): Movie?
suspend fun getMovieDetails(providerId: Long, movieId: Long): Result<Movie>
diff --git a/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt
index e69a467d..889802f0 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/PlaybackHistoryRepository.kt
@@ -8,7 +8,8 @@ interface PlaybackHistoryRepository {
fun getRecentlyWatched(limit: Int = 100): Flow<List<PlaybackHistory>>
fun getRecentlyWatchedByProvider(providerId: Long, limit: Int = 100): Flow<List<PlaybackHistory>>
suspend fun getPlaybackHistory(contentId: Long, contentType: ContentType, providerId: Long): PlaybackHistory?
-
+
+ suspend fun recordPlayback(history: PlaybackHistory)
suspend fun updateResumePosition(history: PlaybackHistory)
suspend fun removeFromHistory(contentId: Long, contentType: ContentType, providerId: Long)
suspend fun clearAllHistory()
diff --git a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt
index 5a918f24..32e77f5e 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/SeriesRepository.kt
@@ -2,6 +2,8 @@ package com.streamvault.domain.repository
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.LibraryBrowseQuery
+import com.streamvault.domain.model.PagedResult
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
import kotlinx.coroutines.flow.Flow
@@ -9,8 +11,15 @@ import kotlinx.coroutines.flow.Flow
interface SeriesRepository {
fun getSeries(providerId: Long): Flow<List<Series>>
fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>>
+ fun getSeriesByCategoryPage(providerId: Long, categoryId: Long, limit: Int, offset: Int): Flow<List<Series>>
+ fun getSeriesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Series>>
+ fun getTopRatedPreview(providerId: Long, limit: Int): Flow<List<Series>>
+ fun getFreshPreview(providerId: Long, limit: Int): Flow<List<Series>>
fun getSeriesByIds(ids: List<Long>): Flow<List<Series>>
fun getCategories(providerId: Long): Flow<List<Category>>
+ fun getCategoryItemCounts(providerId: Long): Flow<Map<Long, Int>>
+ fun getLibraryCount(providerId: Long): Flow<Int>
+ fun browseSeries(query: LibraryBrowseQuery): Flow<PagedResult<Series>>
fun searchSeries(providerId: Long, query: String): Flow<List<Series>>
suspend fun getSeriesById(seriesId: Long): Series?
suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series>
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt b/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt
index 3a163893..b97149f0 100644
--- a/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt
+++ b/domain/src/main/java/com/streamvault/domain/usecase/GetCustomCategories.kt
@@ -2,6 +2,7 @@ package com.streamvault.domain.usecase
import com.streamvault.domain.model.Category
import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.VirtualCategoryIds
import com.streamvault.domain.repository.FavoriteRepository
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
@@ -30,7 +31,7 @@ class GetCustomCategories @Inject constructor(
categories.add(
index = 0,
element = Category(
- id = -999L,
+ id = VirtualCategoryIds.FAVORITES,
name = "Favorites",
type = contentType,
isVirtual = true,