Skip to content

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

Complete Phase 4 Playback Enhancements

Davidona80d88d14592c
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 17b9c499..6c3f4e06 100644
--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigation.kt
@@ -23,7 +23,7 @@ object Routes {
const val SERIES = "series"
const val FAVORITES = "favorites"
const val SETTINGS = "settings"
- const val PLAYER = "player/{streamUrl}?title={title}&channelId={channelId}&internalId={internalId}&categoryId={categoryId}&providerId={providerId}&isVirtual={isVirtual}"
+ const val PLAYER = "player/{streamUrl}?title={title}&channelId={channelId}&internalId={internalId}&categoryId={categoryId}&providerId={providerId}&isVirtual={isVirtual}&contentType={contentType}"
const val SEARCH = "search"
const val SERIES_DETAIL = "series_detail/{seriesId}"
const val WELCOME = "welcome"
@@ -39,11 +39,12 @@ object Routes {
internalId: Long = -1L,
categoryId: Long? = null,
providerId: Long? = null,
- isVirtual: Boolean = false
+ isVirtual: Boolean = false,
+ contentType: String = "LIVE"
): 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"
+ return "player/$encodedUrl?title=$encodedTitle&channelId=${channelId ?: ""}&internalId=$internalId&categoryId=${categoryId ?: -1L}&providerId=${providerId ?: -1L}&isVirtual=$isVirtual&contentType=$contentType"
}
fun seriesDetail(seriesId: Long) = "series_detail/$seriesId"
@@ -103,7 +104,8 @@ fun AppNavigation() {
internalId = channel.id,
categoryId = category?.id,
providerId = provider?.id,
- isVirtual = category?.isVirtual == true
+ isVirtual = category?.isVirtual == true,
+ contentType = "LIVE"
)
)
},
@@ -122,7 +124,14 @@ fun AppNavigation() {
composable(Routes.MOVIES) {
MoviesScreen(
onMovieClick = { movie ->
- navController.navigate(Routes.player(movie.streamUrl, movie.name))
+ navController.navigate(Routes.player(
+ streamUrl = movie.streamUrl,
+ title = movie.name,
+ internalId = movie.id,
+ categoryId = movie.categoryId,
+ providerId = movie.providerId,
+ contentType = "MOVIE"
+ ))
},
onNavigate = { route ->
navController.navigate(route) {
@@ -238,7 +247,8 @@ fun AppNavigation() {
navArgument("internalId") { type = NavType.LongType; defaultValue = -1L },
navArgument("categoryId") { type = NavType.LongType; defaultValue = -1L },
navArgument("providerId") { type = NavType.LongType; defaultValue = -1L },
- navArgument("isVirtual") { type = NavType.BoolType; defaultValue = false }
+ navArgument("isVirtual") { type = NavType.BoolType; defaultValue = false },
+ navArgument("contentType") { type = NavType.StringType; defaultValue = "LIVE" }
)
) { backStackEntry ->
val streamUrl = java.net.URLDecoder.decode(
@@ -254,6 +264,7 @@ fun AppNavigation() {
val categoryId = backStackEntry.arguments?.getLong("categoryId")?.takeIf { it != -1L }
val providerId = backStackEntry.arguments?.getLong("providerId")?.takeIf { it != -1L }
val isVirtual = backStackEntry.arguments?.getBoolean("isVirtual") ?: false
+ val contentType = backStackEntry.arguments?.getString("contentType") ?: "LIVE"
PlayerScreen(
streamUrl = streamUrl,
@@ -263,6 +274,7 @@ fun AppNavigation() {
categoryId = categoryId,
providerId = providerId,
isVirtual = isVirtual,
+ contentType = contentType,
onBack = { navController.popBackStack() }
)
}
@@ -276,7 +288,13 @@ fun AppNavigation() {
com.streamvault.app.ui.screens.series.SeriesDetailScreen(
onEpisodeClick = { episode ->
// Navigate to player
- navController.navigate(Routes.player(episode.streamUrl, "${episode.title} - S${episode.seasonNumber}E${episode.episodeNumber}"))
+ 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"
+ ))
},
onBack = { navController.popBackStack() }
)
diff --git a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
index 69d6599f..6a4eda07 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/Cards.kt
@@ -188,6 +188,15 @@ fun ChannelCard(
Text("★", style = MaterialTheme.typography.labelSmall, color = Color.Black)
}
}
+ if (channel.catchUpSupported) {
+ Box(
+ modifier = Modifier
+ .background(Primary, RoundedCornerShape(4.dp))
+ .padding(horizontal = 6.dp, vertical = 2.dp)
+ ) {
+ Text("📼", style = MaterialTheme.typography.labelSmall, color = Color.White)
+ }
+ }
Box(
modifier = Modifier
.background(AccentRed, RoundedCornerShape(4.dp))
diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt
new file mode 100644
index 00000000..089d4394
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/ProgramHistoryDialog.kt
@@ -0,0 +1,124 @@
+package com.streamvault.app.ui.components.dialogs
+
+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.material.icons.Icons
+import androidx.compose.material.icons.filled.Close
+import androidx.compose.material3.*
+import androidx.compose.runtime.*
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.font.FontWeight
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.compose.ui.window.Dialog
+import com.streamvault.domain.model.Program
+import java.text.SimpleDateFormat
+import java.util.*
+
+@Composable
+fun ProgramHistoryDialog(
+ programs: List<Program>,
+ onDismiss: () -> Unit,
+ onProgramSelect: (Program) -> Unit
+) {
+ val focusRequester = remember { FocusRequester() }
+ val timeFormat = remember { SimpleDateFormat("HH:mm", Locale.getDefault()) }
+ val dayFormat = remember { SimpleDateFormat("EEE, MMM d", Locale.getDefault()) }
+
+ LaunchedEffect(Unit) {
+ focusRequester.requestFocus()
+ }
+
+ Dialog(onDismissRequest = onDismiss) {
+ Surface(
+ shape = RoundedCornerShape(16.dp),
+ color = MaterialTheme.colorScheme.surface,
+ modifier = Modifier
+ .width(450.dp)
+ .heightIn(max = 600.dp)
+ .padding(16.dp)
+ ) {
+ Column(modifier = Modifier.padding(24.dp)) {
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(bottom = 16.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = "Program Archive",
+ style = MaterialTheme.typography.titleLarge,
+ fontWeight = FontWeight.Bold
+ )
+ IconButton(onClick = onDismiss) {
+ Icon(Icons.Default.Close, contentDescription = "Close")
+ }
+ }
+
+ if (programs.isEmpty()) {
+ Box(
+ modifier = Modifier.fillMaxWidth().height(200.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ Text("No archived programs found", color = MaterialTheme.colorScheme.onSurfaceVariant)
+ }
+ } else {
+ LazyColumn(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ items(programs) { program ->
+ var isFocused by remember { mutableStateOf(false) }
+
+ Surface(
+ onClick = { onProgramSelect(program) },
+ modifier = Modifier
+ .fillMaxWidth()
+ .onFocusChanged { isFocused = it.isFocused }
+ .focusRequester(if (program == programs.first()) focusRequester else FocusRequester())
+ .border(
+ width = if (isFocused) 2.dp else 1.dp,
+ color = if (isFocused) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant,
+ shape = RoundedCornerShape(8.dp)
+ ),
+ shape = RoundedCornerShape(8.dp),
+ color = if (isFocused) MaterialTheme.colorScheme.surfaceVariant else Color.Transparent
+ ) {
+ Row(
+ modifier = Modifier.padding(12.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(
+ text = program.title,
+ style = MaterialTheme.typography.bodyLarge,
+ fontWeight = FontWeight.Medium,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ Text(
+ text = "${dayFormat.format(program.startTime)} | ${timeFormat.format(program.startTime)} - ${timeFormat.format(program.endTime)}",
+ style = MaterialTheme.typography.labelMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ if (program.hasArchive) {
+ Text("📼", modifier = Modifier.padding(start = 8.dp))
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+}
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 af932583..0eb8ae45 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
@@ -12,6 +12,12 @@ import androidx.compose.ui.input.key.onKeyEvent
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.compose.ui.viewinterop.AndroidView
+import androidx.compose.animation.*
+import androidx.compose.ui.graphics.Brush
+import androidx.compose.ui.text.font.FontWeight
+import java.text.SimpleDateFormat
+import java.util.Date
+import java.util.Locale
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
@@ -31,229 +37,20 @@ import com.streamvault.domain.repository.EpgRepository
import com.streamvault.player.PlaybackState
import com.streamvault.player.PlayerEngine
import com.streamvault.player.PlayerError
+import com.streamvault.player.PlayerTrack
+import com.streamvault.player.TrackType
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import javax.inject.Inject
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.clickable
+import androidx.compose.material3.Slider
+import androidx.compose.material3.SliderDefaults
+import com.streamvault.app.ui.components.dialogs.ProgramHistoryDialog
-@HiltViewModel
-class PlayerViewModel @Inject constructor(
- val playerEngine: PlayerEngine,
- private val epgRepository: EpgRepository,
- private val channelRepository: com.streamvault.domain.repository.ChannelRepository,
- private val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository
-) : ViewModel() {
- private val _showControls = MutableStateFlow(true)
- val showControls: StateFlow<Boolean> = _showControls.asStateFlow()
-
- private val _showZapOverlay = MutableStateFlow(false)
- val showZapOverlay: StateFlow<Boolean> = _showZapOverlay.asStateFlow()
-
- private val _currentProgram = MutableStateFlow<Program?>(null)
- val currentProgram: StateFlow<Program?> = _currentProgram.asStateFlow()
-
- private val _currentChannel = MutableStateFlow<com.streamvault.domain.model.Channel?>(null)
- val currentChannel: StateFlow<com.streamvault.domain.model.Channel?> = _currentChannel.asStateFlow()
-
- // Zapping state
- private var channelList: List<com.streamvault.domain.model.Channel> = emptyList()
- private var currentChannelIndex = -1
- private var currentCategoryId: Long = -1
- private var currentProviderId: Long = -1
- private var isVirtualCategory: Boolean = false
-
- private var epgJob: kotlinx.coroutines.Job? = null
- private var playlistJob: kotlinx.coroutines.Job? = null
- private var hideControlsJob: kotlinx.coroutines.Job? = null
- private var hideZapOverlayJob: kotlinx.coroutines.Job? = null
-
- val playerError: StateFlow<PlayerError?> = playerEngine.error
- .stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), null)
-
- val videoFormat: StateFlow<VideoFormat> = playerEngine.videoFormat
-
- fun prepare(streamUrl: String, epgChannelId: String?, internalChannelId: Long, categoryId: Long = -1, providerId: Long = -1, isVirtual: Boolean = false) {
- val streamInfo = StreamInfo(
- url = streamUrl,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
- )
- playerEngine.prepare(streamInfo)
-
- // Load playlist if context changed
- if (categoryId != -1L && (categoryId != currentCategoryId || providerId != currentProviderId)) {
- currentCategoryId = categoryId
- currentProviderId = providerId
- 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 }
- }
- }
- }
- currentStreamUrl = streamUrl
-
- // Fetch EPG if ID provided
- fetchEpg(epgChannelId)
- }
-
- private fun fetchEpg(epgChannelId: String?) {
- epgJob?.cancel()
- if (epgChannelId != null) {
- epgJob = viewModelScope.launch {
- epgRepository.getNowPlaying(epgChannelId).collect { program ->
- _currentProgram.value = program
- }
- }
- } else {
- _currentProgram.value = null
- }
- }
-
- private fun loadPlaylist(categoryId: Long, providerId: Long, isVirtual: Boolean, initialChannelId: Long) {
- playlistJob?.cancel()
- playlistJob = viewModelScope.launch {
- val flows = if (isVirtual) {
- if (categoryId == -999L) {
- // Global Favorites
- favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE)
- .map { favorites -> favorites.map { it.contentId } }
- .flatMapLatest { ids ->
- if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids)
- }
- } else {
- // Custom Group
- // categoryId is positive here from args?
- // In HomeViewModel, category.id is negative for custom groups.
- // We passed category.id directly. So it should be negative if it came from HomeViewModel.
- // But wait, HomeViewModel passes `category.id`.
- // If it is a custom group, ID is negative.
- // So we should handle it.
- // BUT `FavoriteRepository.getFavoritesByGroup` expects positive Group ID.
- // In HomeViewModel: `groupId = -category.id`.
- // So here strict check:
- val groupId = if (categoryId < 0) -categoryId else categoryId
- favoriteRepository.getFavoritesByGroup(groupId)
- .map { favorites -> favorites.map { it.contentId } }
- .flatMapLatest { ids ->
- if (ids.isEmpty()) flowOf(emptyList())
- else channelRepository.getChannelsByIds(ids)
- }
- }
- } else {
- channelRepository.getChannelsByCategory(providerId, categoryId)
- }
-
- flows.collect { channels ->
- channelList = channels
- // Recalculate index based on initial ID or URL
- if (initialChannelId != -1L) {
- currentChannelIndex = channelList.indexOfFirst { it.id == initialChannelId }
- }
- if (currentChannelIndex == -1) {
- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
- }
-
- if (currentChannelIndex != -1) {
- _currentChannel.value = channelList[currentChannelIndex]
- }
- }
- }
- }
-
- // Store current URL to find index later
- private var currentStreamUrl: String = ""
-
- fun playNext() {
- if (channelList.isEmpty()) return
-
- if (currentChannelIndex == -1) {
- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
- if (currentChannelIndex == -1) return
- }
-
- val nextIndex = (currentChannelIndex + 1) % channelList.size
- changeChannel(nextIndex)
- }
-
- fun playPrevious() {
- if (channelList.isEmpty()) return
-
- if (currentChannelIndex == -1) {
- currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
- if (currentChannelIndex == -1) return
- }
-
- val prevIndex = if (currentChannelIndex - 1 < 0) channelList.size - 1 else currentChannelIndex - 1
- changeChannel(prevIndex)
- }
-
- private fun changeChannel(index: Int) {
- val channel = channelList[index]
- currentChannelIndex = index
- _currentChannel.value = channel
-
- // Prepare player
- val streamInfo = StreamInfo(
- url = channel.streamUrl,
- streamType = com.streamvault.domain.model.StreamType.UNKNOWN
- )
- playerEngine.prepare(streamInfo)
- playerEngine.play()
-
- fetchEpg(channel.epgChannelId)
-
- // Show Zap Overlay
- _showZapOverlay.value = true
- _showControls.value = false // Hide full controls
- hideZapOverlayAfterDelay()
- }
-
- fun play() = playerEngine.play()
- fun pause() = playerEngine.pause()
- fun seekForward() = playerEngine.seekForward()
- fun seekBackward() = playerEngine.seekBackward()
-
- fun toggleControls() {
- _showControls.value = !_showControls.value
- }
-
- fun hideControlsAfterDelay() {
- // Cancel previous job to prevent race condition
- hideControlsJob?.cancel()
- hideControlsJob = viewModelScope.launch {
- delay(5000)
- _showControls.value = false
- }
- }
-
- private fun hideZapOverlayAfterDelay() {
- hideZapOverlayJob?.cancel()
- hideZapOverlayJob = viewModelScope.launch {
- delay(4000)
- _showZapOverlay.value = false
- }
- }
-
- fun retryStream(streamUrl: String, epgChannelId: String?) {
- val currentId = if (currentChannelIndex != -1 && channelList.isNotEmpty()) channelList[currentChannelIndex].id else -1L
- prepare(streamUrl, epgChannelId, currentId, currentCategoryId, currentProviderId, isVirtualCategory)
- }
-
- override fun onCleared() {
- super.onCleared()
- hideControlsJob?.cancel()
- hideZapOverlayJob?.cancel()
- playerEngine.release()
- }
-}
@androidx.annotation.OptIn(UnstableApi::class)
@Composable
@@ -265,6 +62,7 @@ fun PlayerScreen(
categoryId: Long? = null,
providerId: Long? = null,
isVirtual: Boolean = false,
+ contentType: String = "LIVE",
onBack: () -> Unit,
viewModel: PlayerViewModel = hiltViewModel()
) {
@@ -274,8 +72,20 @@ fun PlayerScreen(
val videoFormat by viewModel.videoFormat.collectAsState()
val playerError by viewModel.playerError.collectAsState()
val currentProgram by viewModel.currentProgram.collectAsState()
+ val nextProgram by viewModel.nextProgram.collectAsState()
+ val programHistory by viewModel.programHistory.collectAsState()
val currentChannel by viewModel.currentChannel.collectAsState()
val showZapOverlay by viewModel.showZapOverlay.collectAsState()
+ val resumePrompt by viewModel.resumePrompt.collectAsState()
+
+ val availableAudioTracks by viewModel.availableAudioTracks.collectAsState()
+ val availableSubtitleTracks by viewModel.availableSubtitleTracks.collectAsState()
+ val aspectRatio by viewModel.aspectRatio.collectAsState()
+ val currentPosition by viewModel.playerEngine.currentPosition.collectAsState()
+ val duration by viewModel.playerEngine.duration.collectAsState()
+
+ var showTrackSelection by remember { mutableStateOf<TrackType?>(null) }
+ var showProgramHistory by remember { mutableStateOf(false) }
val focusRequester = remember { FocusRequester() }
@@ -294,8 +104,19 @@ fun PlayerScreen(
}
}
+ if (showProgramHistory) {
+ ProgramHistoryDialog(
+ programs = programHistory,
+ onDismiss = { showProgramHistory = false },
+ onProgramSelect = { program ->
+ viewModel.playCatchUp(program)
+ showProgramHistory = false
+ }
+ )
+ }
+
LaunchedEffect(streamUrl, epgChannelId) {
- viewModel.prepare(streamUrl, epgChannelId, internalChannelId, categoryId ?: -1, providerId ?: -1, isVirtual)
+ viewModel.prepare(streamUrl, epgChannelId, internalChannelId, categoryId ?: -1, providerId ?: -1, isVirtual, contentType)
}
LaunchedEffect(showControls) {
@@ -333,8 +154,13 @@ fun PlayerScreen(
true
}
KeyEvent.KEYCODE_BACK -> {
- onBack()
- true
+ if (showTrackSelection != null) {
+ showTrackSelection = null
+ true
+ } else {
+ onBack()
+ true
+ }
}
KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE -> {
if (isPlaying) viewModel.pause() else viewModel.play()
@@ -358,12 +184,19 @@ fun PlayerScreen(
// ExoPlayer Video Surface
val player = viewModel.playerEngine.getPlayerView()
if (player is androidx.media3.common.Player) {
- AndroidView<PlayerView>(
+ AndroidView<androidx.media3.ui.PlayerView>(
factory = { context ->
- PlayerView(context).apply {
+ androidx.media3.ui.PlayerView(context).apply {
this.player = player
useController = false
- setShowBuffering(PlayerView.SHOW_BUFFERING_WHEN_PLAYING)
+ setShowBuffering(androidx.media3.ui.PlayerView.SHOW_BUFFERING_WHEN_PLAYING)
+ }
+ },
+ update = { playerView ->
+ playerView.resizeMode = when (aspectRatio) {
+ AspectRatio.FIT -> androidx.media3.ui.AspectRatioFrameLayout.RESIZE_MODE_FIT
+ AspectRatio.FILL -> androidx.media3.ui.AspectRatioFrameLayout.RESIZE_MODE_FILL
+ AspectRatio.ZOOM -> androidx.media3.ui.AspectRatioFrameLayout.RESIZE_MODE_ZOOM
}
},
modifier = Modifier.fillMaxSize()
@@ -446,132 +279,339 @@ fun PlayerScreen(
}
}
- // Controls overlay
- if (showControls) {
- Box(
- modifier = Modifier
- .fillMaxSize()
- .background(Color.Black.copy(alpha = 0.5f))
- ) {
- // Title at top
- Text(
- text = title,
- style = MaterialTheme.typography.titleLarge,
- color = Color.White,
+ // Cinematic Controls Overlay
+ AnimatedVisibility(
+ visible = showControls,
+ enter = fadeIn() + expandVertically(),
+ exit = fadeOut() + shrinkVertically(),
+ modifier = Modifier.fillMaxSize()
+ ) {
+ Box(modifier = Modifier.fillMaxSize()) {
+ // Top Gradient & Bar
+ Box(
modifier = Modifier
- .align(Alignment.TopStart)
- .padding(32.dp)
- )
-
- // Current Program Info
- if (currentProgram != null) {
- Column(
- modifier = Modifier
- .align(Alignment.BottomStart)
- .padding(start = 32.dp, bottom = 32.dp, end = 32.dp)
- .widthIn(max = 600.dp)
- ) {
- Text(
- text = currentProgram?.title ?: "",
- style = MaterialTheme.typography.titleMedium,
- color = Color.White
+ .fillMaxWidth()
+ .height(120.dp)
+ .background(
+ Brush.verticalGradient(
+ colors = listOf(Color.Black.copy(alpha = 0.8f), Color.Transparent)
+ )
)
-
- val now = System.currentTimeMillis()
- val start = currentProgram?.startTime ?: 0
- val end = currentProgram?.endTime ?: 0
-
- if (start > 0 && end > 0) {
- val totalDuration = end - start
- val elapsed = now - start
- val progress = if (totalDuration > 0) elapsed.toFloat() / totalDuration else 0f
-
- Spacer(modifier = Modifier.height(8.dp))
- androidx.compose.material3.LinearProgressIndicator(
- progress = { progress.coerceIn(0f, 1f) },
- modifier = Modifier
- .fillMaxWidth()
- .height(4.dp),
- color = Primary,
- trackColor = Color.White.copy(alpha = 0.3f)
+ .align(Alignment.TopCenter)
+ .padding(horizontal = 32.dp, vertical = 24.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column {
+ Text(
+ text = title,
+ style = MaterialTheme.typography.titleLarge,
+ color = Color.White,
+ fontWeight = FontWeight.Bold
+ )
+ if (contentType != "LIVE") {
+ Text(
+ text = if (contentType == "MOVIE") "Movie" else "Series",
+ style = MaterialTheme.typography.labelMedium,
+ color = Color.White.copy(alpha = 0.6f)
+ )
+ }
+ }
+
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ // System Clock
+ val currentTime = remember { mutableStateOf(SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date())) }
+ LaunchedEffect(Unit) {
+ while(true) {
+ delay(10000)
+ currentTime.value = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date())
+ }
+ }
+ Text(
+ text = currentTime.value,
+ style = MaterialTheme.typography.titleMedium,
+ color = Color.White.copy(alpha = 0.8f),
+ modifier = Modifier.padding(end = 24.dp)
+ )
+
+ // Exit Button
+ Surface(
+ onClick = onBack,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.1f),
+ focusedContainerColor = Primary.copy(alpha = 0.9f)
+ )
+ ) {
+ Text(
+ text = "✕ Close",
+ color = Color.White,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
+ )
+ }
+ }
+ }
+ }
+
+ // Bottom Gradient & Bar
+ Box(
+ modifier = Modifier
+ .fillMaxWidth()
+ .height(180.dp)
+ .background(
+ Brush.verticalGradient(
+ colors = listOf(Color.Transparent, Color.Black.copy(alpha = 0.8f))
)
+ )
+ .align(Alignment.BottomCenter)
+ .padding(horizontal = 32.dp, vertical = 32.dp)
+ ) {
+ Column(modifier = Modifier.fillMaxWidth()) {
+ if (contentType == "LIVE" && currentProgram != null) {
+ // Live TV Program Info
+ Row(verticalAlignment = Alignment.Bottom) {
+ Column(modifier = Modifier.weight(1f)) {
+ Text(
+ text = currentProgram?.title ?: "",
+ style = MaterialTheme.typography.titleMedium,
+ color = Color.White,
+ maxLines = 1
+ )
+ Spacer(modifier = Modifier.height(4.dp))
+ currentChannel?.let {
+ Text(
+ text = "${it.number}. ${it.name}",
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.6f)
+ )
+ }
+ }
+
+ // Next Program Preview
+ if (nextProgram != null) {
+ Column(
+ modifier = Modifier
+ .padding(end = 24.dp)
+ .widthIn(max = 200.dp),
+ horizontalAlignment = Alignment.End
+ ) {
+ Text(
+ text = "NEXT",
+ style = MaterialTheme.typography.labelSmall,
+ color = Primary,
+ fontWeight = FontWeight.Bold
+ )
+ Text(
+ text = nextProgram?.title ?: "",
+ style = MaterialTheme.typography.bodySmall,
+ color = Color.White.copy(alpha = 0.8f),
+ maxLines = 1,
+ overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
+ )
+ Text(
+ text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(nextProgram?.startTime ?: 0)),
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.5f)
+ )
+ }
+ }
+
+ // Track selection buttons shifted here for Live
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (currentChannel?.catchUpSupported == true) {
+ QuickSettingsButton("🔄 Restart") { viewModel.restartCurrentProgram() }
+ QuickSettingsButton("📼 Archive") { showProgramHistory = true }
+ }
+ QuickSettingsButton("📺 ${aspectRatio.modeName}") { viewModel.toggleAspectRatio() }
+ if (availableSubtitleTracks.isNotEmpty()) {
+ QuickSettingsButton("💬 Subs") { showTrackSelection = TrackType.TEXT }
+ }
+ if (availableAudioTracks.size > 1) {
+ QuickSettingsButton("🔊 Audio") { showTrackSelection = TrackType.AUDIO }
+ }
+ }
+ }
+
+ Spacer(modifier = Modifier.height(12.dp))
- Spacer(modifier = Modifier.height(4.dp))
- Row {
+ // Progress bar for Live TV
+ val now = System.currentTimeMillis()
+ val start = currentProgram?.startTime ?: 0
+ val end = currentProgram?.endTime ?: 0
+ if (start > 0 && end > 0) {
+ val progress = (now - start).toFloat() / (end - start)
+ androidx.compose.material3.LinearProgressIndicator(
+ progress = { progress.coerceIn(0f, 1f) },
+ modifier = Modifier.fillMaxWidth().height(4.dp),
+ color = Primary,
+ trackColor = Color.White.copy(alpha = 0.2f)
+ )
+ Spacer(modifier = Modifier.height(6.dp))
+ Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
+ Text(
+ text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(start)),
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.5f)
+ )
+ Text(
+ text = SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(end)),
+ style = MaterialTheme.typography.labelSmall,
+ color = Color.White.copy(alpha = 0.5f)
+ )
+ }
+ }
+ } else if (contentType != "LIVE") {
+ // VOD Seek Bar
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ text = formatDuration(currentPosition),
+ style = MaterialTheme.typography.labelMedium,
+ color = Color.White
+ )
+ Slider(
+ value = if (duration > 0) currentPosition.toFloat() / duration else 0f,
+ onValueChange = { /* Handled via DPAD usually */ },
+ modifier = Modifier.weight(1f).padding(horizontal = 16.dp),
+ colors = SliderDefaults.colors(
+ activeTrackColor = Primary,
+ inactiveTrackColor = Color.White.copy(alpha = 0.2f)
+ )
+ )
Text(
- text = java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault()).format(java.util.Date(start)),
- style = MaterialTheme.typography.bodySmall,
- color = Color.White.copy(alpha = 0.7f)
+ text = formatDuration(duration),
+ style = MaterialTheme.typography.labelMedium,
+ color = Color.White
)
- Spacer(modifier = Modifier.weight(1f))
+ }
+
+ Spacer(modifier = Modifier.height(12.dp))
+
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ // Content info for VOD
Text(
- text = java.text.SimpleDateFormat("HH:mm", java.util.Locale.getDefault()).format(java.util.Date(end)),
- style = MaterialTheme.typography.bodySmall,
- color = Color.White.copy(alpha = 0.7f)
+ text = title,
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White.copy(alpha = 0.8f)
)
+
+ // Track selection for VOD
+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ QuickSettingsButton("📺 ${aspectRatio.modeName}") { viewModel.toggleAspectRatio() }
+ if (availableSubtitleTracks.isNotEmpty()) {
+ QuickSettingsButton("💬 Subs") { showTrackSelection = TrackType.TEXT }
+ }
+ if (availableAudioTracks.size > 1) {
+ QuickSettingsButton("🔊 Audio") { showTrackSelection = TrackType.AUDIO }
+ }
+ }
}
}
}
}
- // Playback controls at center
+ // Center Playback Controls
Row(
modifier = Modifier.align(Alignment.Center),
- horizontalArrangement = Arrangement.spacedBy(24.dp),
+ horizontalArrangement = Arrangement.spacedBy(32.dp),
verticalAlignment = Alignment.CenterVertically
) {
- ControlButton("⏪") { viewModel.seekBackward() }
- ControlButton(if (isPlaying) "⏸" else "▶") {
- if (isPlaying) viewModel.pause() else viewModel.play()
+ if (contentType != "LIVE") {
+ TransportButton("⏪") { viewModel.seekBackward() }
+ }
+
+ Surface(
+ onClick = { if (isPlaying) viewModel.pause() else viewModel.play() },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(50)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Primary.copy(alpha = 0.8f),
+ focusedContainerColor = Primary
+ ),
+ modifier = Modifier.size(80.dp)
+ ) {
+ Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
+ Text(
+ text = if (isPlaying) "⏸" else "▶",
+ style = MaterialTheme.typography.headlineMedium,
+ color = Color.White
+ )
+ }
}
- ControlButton("⏩") { viewModel.seekForward() }
- }
- // Back button
- Surface(
- onClick = onBack,
- modifier = Modifier
- .align(Alignment.TopEnd)
- .padding(32.dp),
- shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
- colors = ClickableSurfaceDefaults.colors(
- containerColor = Color.Black.copy(alpha = 0.6f),
- focusedContainerColor = Primary.copy(alpha = 0.6f)
- )
- ) {
- Text(
- text = "✕ Back",
- color = Color.White,
- modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
- )
+ if (contentType != "LIVE") {
+ TransportButton("⏩") { viewModel.seekForward() }
+ }
}
}
}
- // Zap Overlay (Bottom Left)
- if (showZapOverlay && !showControls && currentChannel != null) {
+ // Cinematic Zap Overlay
+ AnimatedVisibility(
+ visible = showZapOverlay && !showControls && currentChannel != null,
+ enter = fadeIn() + slideInHorizontally(),
+ exit = fadeOut() + slideOutHorizontally(),
+ modifier = Modifier.align(Alignment.BottomStart)
+ ) {
Box(
modifier = Modifier
- .align(Alignment.BottomStart)
.padding(32.dp)
- .background(Color.Black.copy(alpha = 0.7f), RoundedCornerShape(8.dp))
+ .background(
+ brush = Brush.horizontalGradient(
+ colors = listOf(Color.Black.copy(alpha = 0.8f), Color.Transparent)
+ ),
+ shape = RoundedCornerShape(8.dp)
+ )
.padding(16.dp)
- .widthIn(max = 400.dp)
+ .widthIn(min = 300.dp, max = 450.dp)
) {
Column {
- Text(
- text = "${currentChannel?.number}. ${currentChannel?.name}",
- style = MaterialTheme.typography.titleMedium,
- color = Color.White
- )
- if (currentProgram != null) {
- Spacer(modifier = Modifier.height(4.dp))
+ Row(verticalAlignment = Alignment.CenterVertically) {
Text(
- text = currentProgram?.title ?: "",
- style = MaterialTheme.typography.bodyMedium,
- color = Color.White.copy(alpha=0.8f)
+ text = currentChannel?.number?.toString() ?: "",
+ style = MaterialTheme.typography.headlineMedium,
+ color = Primary,
+ fontWeight = FontWeight.Bold
)
- }
+ Spacer(modifier = Modifier.width(16.dp))
+ Column {
+ Text(
+ text = currentChannel?.name ?: "",
+ style = MaterialTheme.typography.titleMedium,
+ color = Color.White
+ )
+ if (currentProgram != null) {
+ Text(
+ text = currentProgram?.title ?: "",
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White.copy(alpha = 0.8f),
+ maxLines = 1,
+ overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+
+ if (currentProgram != null) {
+ val now = System.currentTimeMillis()
+ val start = currentProgram?.startTime ?: 0
+ val end = currentProgram?.endTime ?: 0
+ if (start > 0 && end > 0) {
+ val progress = (now - start).toFloat() / (end - start)
+ Spacer(modifier = Modifier.height(8.dp))
+ androidx.compose.material3.LinearProgressIndicator(
+ progress = { progress.coerceIn(0f, 1f) },
+ modifier = Modifier.fillMaxWidth().height(2.dp),
+ color = Primary,
+ trackColor = Color.White.copy(alpha = 0.2f)
+ )
+ }
+ }
}
}
}
@@ -593,11 +633,196 @@ fun PlayerScreen(
)
}
}
+
+ // Resume Prompt Dialog
+ if (resumePrompt.show) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.85f)),
+ contentAlignment = Alignment.Center
+ ) {
+ Column(
+ modifier = Modifier
+ .widthIn(max = 500.dp)
+ .background(SurfaceElevated, RoundedCornerShape(12.dp))
+ .padding(32.dp),
+ horizontalAlignment = Alignment.CenterHorizontally
+ ) {
+ Text(
+ text = "Resume Playback",
+ style = MaterialTheme.typography.headlineMedium,
+ color = Color.White
+ )
+ Spacer(modifier = Modifier.height(16.dp))
+ Text(
+ text = "Do you want to resume ${resumePrompt.title} from where you left off?",
+ style = MaterialTheme.typography.bodyLarge,
+ color = TextSecondary,
+ textAlign = androidx.compose.ui.text.style.TextAlign.Center
+ )
+ Spacer(modifier = Modifier.height(32.dp))
+
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ Surface(
+ onClick = { viewModel.dismissResumePrompt(resume = false) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = SurfaceVariant,
+ focusedContainerColor = SurfaceHighlight
+ ),
+ modifier = Modifier.weight(1f)
+ ) {
+ Text(
+ "Start Over",
+ modifier = Modifier.padding(vertical = 12.dp).fillMaxWidth(),
+ textAlign = androidx.compose.ui.text.style.TextAlign.Center,
+ color = Color.White
+ )
+ }
+
+ Surface(
+ onClick = { viewModel.dismissResumePrompt(resume = true) },
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Primary,
+ focusedContainerColor = PrimaryVariant
+ ),
+ modifier = Modifier.weight(1f)
+ ) {
+ Text(
+ "Resume",
+ modifier = Modifier.padding(vertical = 12.dp).fillMaxWidth(),
+ textAlign = androidx.compose.ui.text.style.TextAlign.Center,
+ color = Color.White,
+ fontWeight = androidx.compose.ui.text.font.FontWeight.Bold
+ )
+ }
+ }
+ }
+ }
+ }
+
+ // Track Selection Dialog
+ if (showTrackSelection != null) {
+ Box(
+ modifier = Modifier
+ .fillMaxSize()
+ .background(Color.Black.copy(alpha = 0.8f))
+ .clickable(onClick = { showTrackSelection = null }),
+ contentAlignment = Alignment.Center
+ ) {
+ val tracks = if (showTrackSelection == TrackType.AUDIO) availableAudioTracks else availableSubtitleTracks
+
+ Column(
+ modifier = Modifier
+ .widthIn(min = 300.dp, max = 400.dp)
+ .background(SurfaceElevated, RoundedCornerShape(12.dp))
+ .padding(24.dp)
+ ) {
+ Text(
+ text = if (showTrackSelection == TrackType.AUDIO) "Select Audio Track" else "Select Subtitles",
+ style = MaterialTheme.typography.titleLarge,
+ color = Color.White,
+ modifier = Modifier.padding(bottom = 16.dp)
+ )
+
+ androidx.compose.foundation.lazy.LazyColumn(
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ if (showTrackSelection == TrackType.TEXT) {
+ item {
+ TrackItem(
+ name = "Off",
+ isSelected = tracks.none { it.isSelected },
+ onClick = {
+ viewModel.selectSubtitleTrack(null)
+ showTrackSelection = null
+ }
+ )
+ }
+ }
+
+ items(tracks.size) { index ->
+ val track = tracks[index]
+ TrackItem(
+ name = track.name,
+ isSelected = track.isSelected,
+ onClick = {
+ if (showTrackSelection == TrackType.AUDIO) {
+ viewModel.selectAudioTrack(track.id)
+ } else {
+ viewModel.selectSubtitleTrack(track.id)
+ }
+ showTrackSelection = null
+ }
+ )
+ }
+ }
+ }
+ }
+ }
}
}
@Composable
-private fun ControlButton(
+private fun TrackItem(
+ name: String,
+ isSelected: Boolean,
+ onClick: () -> Unit
+) {
+ Surface(
+ onClick = onClick,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = if (isSelected) Primary.copy(alpha = 0.2f) else Color.Transparent,
+ focusedContainerColor = SurfaceHighlight
+ ),
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Row(
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Text(
+ text = name,
+ style = MaterialTheme.typography.bodyLarge,
+ color = if (isSelected) Primary else TextPrimary,
+ modifier = Modifier.weight(1f)
+ )
+ if (isSelected) {
+ Text("✓", color = Primary, style = MaterialTheme.typography.bodyLarge)
+ }
+ }
+ }
+}
+
+@Composable
+private fun QuickSettingsButton(
+ text: String,
+ onClick: () -> Unit
+) {
+ Surface(
+ onClick = onClick,
+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),
+ colors = ClickableSurfaceDefaults.colors(
+ containerColor = Color.White.copy(alpha = 0.1f),
+ focusedContainerColor = Primary.copy(alpha = 0.9f)
+ )
+ ) {
+ Text(
+ text = text,
+ color = Color.White,
+ style = MaterialTheme.typography.labelMedium,
+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)
+ )
+ }
+}
+
+@Composable
+private fun TransportButton(
text: String,
onClick: () -> Unit
) {
@@ -605,10 +830,10 @@ private fun ControlButton(
onClick = onClick,
shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(50)),
colors = ClickableSurfaceDefaults.colors(
- containerColor = Color.White.copy(alpha = 0.2f),
- focusedContainerColor = Primary.copy(alpha = 0.8f)
+ containerColor = Color.White.copy(alpha = 0.1f),
+ focusedContainerColor = Color.White.copy(alpha = 0.3f)
),
- modifier = Modifier.size(64.dp)
+ modifier = Modifier.size(56.dp)
) {
Box(contentAlignment = Alignment.Center, modifier = Modifier.fillMaxSize()) {
Text(
@@ -619,3 +844,17 @@ private fun ControlButton(
}
}
}
+
+private fun formatDuration(ms: Long): String {
+ val totalSeconds = ms / 1000
+ val minutes = totalSeconds / 60
+ val seconds = totalSeconds % 60
+ val hours = minutes / 60
+ val remainingMinutes = minutes % 60
+
+ return if (hours > 0) {
+ String.format(Locale.getDefault(), "%02d:%02d:%02d", hours, remainingMinutes, seconds)
+ } else {
+ String.format(Locale.getDefault(), "%02d:%02d", remainingMinutes, seconds)
+ }
+}
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
new file mode 100644
index 00000000..b5d0bd31
--- /dev/null
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -0,0 +1,394 @@
+package com.streamvault.app.ui.screens.player
+
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.PlaybackHistory
+import com.streamvault.domain.model.VideoFormat
+import com.streamvault.domain.repository.ChannelRepository
+import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.PlaybackHistoryRepository
+import com.streamvault.player.PlaybackState
+import com.streamvault.player.PlayerEngine
+import com.streamvault.player.PlayerError
+import dagger.hilt.android.lifecycle.HiltViewModel
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.*
+import kotlinx.coroutines.launch
+import javax.inject.Inject
+
+data class ResumePromptState(
+ val show: Boolean = false,
+ val positionMs: Long = 0L,
+ val title: String = ""
+)
+
+enum class AspectRatio(val modeName: String) {
+ FIT("Fit"),
+ FILL("Stretch"),
+ ZOOM("Zoom")
+}
+
+@HiltViewModel
+class PlayerViewModel @Inject constructor(
+ val playerEngine: PlayerEngine,
+ private val epgRepository: EpgRepository,
+ private val channelRepository: ChannelRepository,
+ private val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,
+ private val playbackHistoryRepository: PlaybackHistoryRepository,
+ private val providerRepository: com.streamvault.domain.repository.ProviderRepository
+) : ViewModel() {
+
+ private val _showControls = MutableStateFlow(true)
+ val showControls: StateFlow<Boolean> = _showControls.asStateFlow()
+
+ private val _showZapOverlay = MutableStateFlow(false)
+ val showZapOverlay: StateFlow<Boolean> = _showZapOverlay.asStateFlow()
+
+ private val _currentProgram = MutableStateFlow<Program?>(null)
+ val currentProgram: StateFlow<Program?> = _currentProgram.asStateFlow()
+
+ private val _nextProgram = MutableStateFlow<Program?>(null)
+ val nextProgram: StateFlow<Program?> = _nextProgram.asStateFlow()
+
+ private val _programHistory = MutableStateFlow<List<Program>>(emptyList())
+ val programHistory: StateFlow<List<Program>> = _programHistory.asStateFlow()
+
+ private val _currentChannel = MutableStateFlow<com.streamvault.domain.model.Channel?>(null)
+ val currentChannel: StateFlow<com.streamvault.domain.model.Channel?> = _currentChannel.asStateFlow()
+
+ private val _resumePrompt = MutableStateFlow(ResumePromptState())
+ val resumePrompt: StateFlow<ResumePromptState> = _resumePrompt.asStateFlow()
+
+ private val _aspectRatio = MutableStateFlow(AspectRatio.FIT)
+ val aspectRatio: StateFlow<AspectRatio> = _aspectRatio.asStateFlow()
+
+ // Zapping state
+ private var channelList: List<com.streamvault.domain.model.Channel> = emptyList()
+ private var currentChannelIndex = -1
+ private var currentCategoryId: Long = -1
+ private var currentProviderId: Long = -1L
+ private var currentContentId: Long = -1L
+ private var currentContentType: ContentType = ContentType.LIVE
+ private var currentTitle: String = ""
+ private var isVirtualCategory: Boolean = false
+
+ private var epgJob: Job? = null
+ private var playlistJob: Job? = null
+ private var controlsHideJob: Job? = null
+ private var progressTrackingJob: Job? = null
+ private var zapOverlayJob: Job? = null
+
+ val playerError: StateFlow<PlayerError?> = playerEngine.error
+ .stateIn(viewModelScope, kotlinx.coroutines.flow.SharingStarted.WhileSubscribed(5000), null)
+
+ val videoFormat: StateFlow<VideoFormat> = playerEngine.videoFormat
+
+ val availableAudioTracks = playerEngine.availableAudioTracks
+ val availableSubtitleTracks = playerEngine.availableSubtitleTracks
+
+ fun selectAudioTrack(trackId: String) {
+ playerEngine.selectAudioTrack(trackId)
+ }
+
+ fun selectSubtitleTrack(trackId: String?) {
+ playerEngine.selectSubtitleTrack(trackId)
+ }
+
+ fun prepare(
+ streamUrl: String,
+ epgChannelId: String?,
+ internalChannelId: Long,
+ categoryId: Long = -1,
+ providerId: Long = -1,
+ isVirtual: Boolean = false,
+ contentType: String = "CHANNEL",
+ title: String = ""
+ ) {
+ currentStreamUrl = streamUrl
+ currentProviderId = providerId
+ currentContentId = internalChannelId
+ currentTitle = title
+ currentContentType = try { ContentType.valueOf(contentType) } catch (e: Exception) { ContentType.LIVE }
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = streamUrl,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ playerEngine.prepare(streamInfo)
+
+ // 1. Check for Resume Position for VODs
+ if (currentContentType != ContentType.LIVE && currentContentId != -1L && currentProviderId != -1L) {
+ viewModelScope.launch {
+ val history = playbackHistoryRepository.getPlaybackHistory(currentContentId, currentContentType, currentProviderId)
+ if (history != null && history.resumePositionMs > 5000L && history.totalDurationMs > 0 && history.resumePositionMs < history.totalDurationMs * 0.95) {
+ playerEngine.pause()
+ _resumePrompt.value = ResumePromptState(
+ show = true,
+ positionMs = history.resumePositionMs,
+ title = currentTitle
+ )
+ }
+ }
+ }
+
+ // Load playlist if context changed
+ if (categoryId != -1L && (categoryId != currentCategoryId || providerId != currentProviderId)) {
+ currentCategoryId = categoryId
+ currentProviderId = providerId
+ 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 }
+ }
+ }
+ }
+ currentStreamUrl = streamUrl
+
+ // Fetch EPG if ID provided
+ fetchEpg(epgChannelId)
+
+ // 2. Start Progress Tracking for VODs
+ startProgressTracking()
+ }
+
+ private fun startProgressTracking() {
+ progressTrackingJob?.cancel()
+ if (currentContentType == ContentType.LIVE) return
+
+ progressTrackingJob = viewModelScope.launch {
+ while (true) {
+ delay(5000) // Track every 5 seconds
+ val pos = playerEngine.currentPosition.value
+ val dur = playerEngine.duration.value
+
+ if (pos > 0 && dur > 0 && currentContentId != -1L) {
+ val history = PlaybackHistory(
+ contentId = currentContentId,
+ contentType = currentContentType,
+ providerId = currentProviderId,
+ title = currentTitle,
+ streamUrl = currentStreamUrl,
+ resumePositionMs = pos,
+ totalDurationMs = dur,
+ lastWatchedAt = System.currentTimeMillis()
+ )
+ playbackHistoryRepository.updateResumePosition(history)
+ }
+ }
+ }
+ }
+
+ private fun fetchEpg(epgChannelId: String?) {
+ epgJob?.cancel()
+ if (epgChannelId != null) {
+ epgJob = viewModelScope.launch {
+ epgRepository.getNowAndNext(epgChannelId).collect { (now, next) ->
+ _currentProgram.value = now
+ _nextProgram.value = next
+ }
+ }
+ fetchProgramHistory(epgChannelId)
+ } else {
+ _currentProgram.value = null
+ _nextProgram.value = null
+ _programHistory.value = emptyList()
+ }
+ }
+
+ private fun fetchProgramHistory(channelId: String) {
+ viewModelScope.launch {
+ // Fetch last 24 hours
+ val now = System.currentTimeMillis()
+ val start = now - (24 * 60 * 60 * 1000L)
+ epgRepository.getProgramsForChannel(channelId, start, now).collect { programs ->
+ // Only show programs that have archive (for Xtream)
+ _programHistory.value = programs.filter { it.hasArchive }.sortedByDescending { it.startTime }
+ }
+ }
+ }
+
+ private fun loadPlaylist(categoryId: Long, providerId: Long, isVirtual: Boolean, initialChannelId: Long) {
+ playlistJob?.cancel()
+ playlistJob = viewModelScope.launch {
+ val flows = if (isVirtual) {
+ if (categoryId == -999L) {
+ // Global Favorites
+ favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE)
+ .map { favorites -> favorites.map { it.contentId } }
+ .flatMapLatest { ids ->
+ if (ids.isEmpty()) flowOf(emptyList())
+ else channelRepository.getChannelsByIds(ids)
+ }
+ } else {
+ val groupId = if (categoryId < 0) -categoryId else categoryId
+ favoriteRepository.getFavoritesByGroup(groupId)
+ .map { favorites -> favorites.map { it.contentId } }
+ .flatMapLatest { ids ->
+ if (ids.isEmpty()) flowOf(emptyList())
+ else channelRepository.getChannelsByIds(ids)
+ }
+ }
+ } else {
+ channelRepository.getChannelsByCategory(providerId, categoryId)
+ }
+
+ flows.collect { channels ->
+ channelList = channels
+ // Recalculate index based on initial ID or URL
+ if (initialChannelId != -1L) {
+ currentChannelIndex = channelList.indexOfFirst { it.id == initialChannelId }
+ }
+ if (currentChannelIndex == -1) {
+ currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
+ }
+
+ if (currentChannelIndex != -1) {
+ _currentChannel.value = channelList[currentChannelIndex]
+ }
+ }
+ }
+ }
+
+ // Store current URL to find index later
+ private var currentStreamUrl: String = ""
+
+ fun playNext() {
+ if (channelList.isEmpty()) return
+
+ if (currentChannelIndex == -1) {
+ currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
+ if (currentChannelIndex == -1) return
+ }
+
+ val nextIndex = (currentChannelIndex + 1) % channelList.size
+ changeChannel(nextIndex)
+ }
+
+ fun playPrevious() {
+ if (channelList.isEmpty()) return
+
+ if (currentChannelIndex == -1) {
+ currentChannelIndex = channelList.indexOfFirst { it.streamUrl == currentStreamUrl }
+ if (currentChannelIndex == -1) return
+ }
+
+ val prevIndex = if (currentChannelIndex - 1 < 0) channelList.size - 1 else currentChannelIndex - 1
+ changeChannel(prevIndex)
+ }
+
+ private fun changeChannel(index: Int) {
+ val channel = channelList[index]
+ currentChannelIndex = index
+ _currentChannel.value = channel
+
+ // Prepare player
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = channel.streamUrl,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ playerEngine.prepare(streamInfo)
+ playerEngine.play()
+
+ fetchEpg(channel.epgChannelId)
+
+ // Show Zap Overlay
+ _showZapOverlay.value = true
+ _showControls.value = false // Hide full controls
+ hideZapOverlayAfterDelay()
+ }
+
+ fun play() = playerEngine.play()
+ fun pause() = playerEngine.pause()
+ fun seekForward() = playerEngine.seekForward()
+ fun seekBackward() = playerEngine.seekBackward()
+
+ fun toggleControls() {
+ _showControls.value = !_showControls.value
+ }
+
+ fun toggleAspectRatio() {
+ _aspectRatio.value = when (_aspectRatio.value) {
+ AspectRatio.FIT -> AspectRatio.FILL
+ AspectRatio.FILL -> AspectRatio.ZOOM
+ AspectRatio.ZOOM -> AspectRatio.FIT
+ }
+ }
+
+ fun playCatchUp(program: Program) {
+ viewModelScope.launch {
+ val start = program.startTime / 1000L
+ val end = program.endTime / 1000L
+ val streamId = _currentChannel.value?.id ?: 0L
+ val providerId = currentProviderId
+
+ if (providerId == -1L || streamId == 0L) return@launch
+
+ val catchUpUrl = providerRepository.buildCatchUpUrl(providerId, streamId, start, end)
+ if (catchUpUrl != null) {
+ // Update metadata for player
+ currentTitle = "${_currentChannel.value?.name ?: ""}: ${program.title}"
+
+ val streamInfo = com.streamvault.domain.model.StreamInfo(
+ url = catchUpUrl,
+ streamType = com.streamvault.domain.model.StreamType.UNKNOWN
+ )
+ playerEngine.prepare(streamInfo)
+ playerEngine.play()
+ _showControls.value = true
+ }
+ }
+ }
+
+ fun restartCurrentProgram() {
+ val program = _currentProgram.value ?: return
+ if (program.hasArchive || (_currentChannel.value?.catchUpSupported == true)) {
+ playCatchUp(program)
+ }
+ }
+
+ fun hideControlsAfterDelay() {
+ // Cancel previous job to prevent race condition
+ controlsHideJob?.cancel()
+ controlsHideJob = viewModelScope.launch {
+ delay(5000)
+ _showControls.value = false
+ }
+ }
+
+ private fun hideZapOverlayAfterDelay() {
+ zapOverlayJob?.cancel()
+ zapOverlayJob = viewModelScope.launch {
+ delay(4000)
+ _showZapOverlay.value = false
+ }
+ }
+
+ fun retryStream(streamUrl: String, epgChannelId: String?) {
+ val currentId = if (currentChannelIndex != -1 && channelList.isNotEmpty()) channelList[currentChannelIndex].id else -1L
+ prepare(streamUrl, epgChannelId, currentId, currentCategoryId, currentProviderId, isVirtualCategory, currentContentType.name, currentTitle)
+ }
+
+ fun dismissResumePrompt(resume: Boolean) {
+ val prompt = _resumePrompt.value
+ _resumePrompt.value = ResumePromptState() // hide
+ if (resume && prompt.positionMs > 0) {
+ playerEngine.seekTo(prompt.positionMs)
+ }
+ playerEngine.play()
+ }
+
+ override fun onCleared() {
+ super.onCleared()
+ controlsHideJob?.cancel()
+ zapOverlayJob?.cancel()
+ progressTrackingJob?.cancel()
+ playerEngine.release()
+ }
+}
diff --git a/build.log b/build.log
index b71becd4..052d4944 100644
--- a/build.log
+++ b/build.log
@@ -1,6 +1,3 @@
-> Task :app:preBuild UP-TO-DATE
-> Task :app:preDebugBuild UP-TO-DATE
-> Task :app:mergeDebugNativeDebugMetadata NO-SOURCE
> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :domain:compileKotlin UP-TO-DATE
> Task :domain:compileJava NO-SOURCE
@@ -8,6 +5,8 @@
> Task :domain:classes UP-TO-DATE
> Task :domain:jar UP-TO-DATE
> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :app:preBuild UP-TO-DATE
+> Task :app:preDebugBuild UP-TO-DATE
> Task :data:preBuild UP-TO-DATE
> Task :data:preDebugBuild UP-TO-DATE
> Task :data:writeDebugAarMetadata UP-TO-DATE
@@ -44,7 +43,13 @@
> Task :player:generateDebugRFile UP-TO-DATE
> Task :app:processDebugResources UP-TO-DATE
> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :data:kspDebugKotlin UP-TO-DATE
+> Task :data:compileDebugKotlin UP-TO-DATE
> Task :data:javaPreCompileDebug UP-TO-DATE
+> Task :data:compileDebugJavaWithJavac UP-TO-DATE
+> Task :data:copyRoomSchemas NO-SOURCE
+> Task :data:transformDebugClassesWithAsm UP-TO-DATE
+> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
> Task :player:kspDebugKotlin UP-TO-DATE
> Task :player:compileDebugKotlin UP-TO-DATE
@@ -52,57 +57,26 @@
> Task :player:compileDebugJavaWithJavac UP-TO-DATE
> Task :player:transformDebugClassesWithAsm UP-TO-DATE
> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
-> Task :app:javaPreCompileDebug UP-TO-DATE
-> Task :app:mergeDebugShaders UP-TO-DATE
-> Task :app:compileDebugShaders NO-SOURCE
-> Task :app:generateDebugAssets UP-TO-DATE
-> Task :data:mergeDebugShaders UP-TO-DATE
-> Task :data:compileDebugShaders NO-SOURCE
-> Task :data:generateDebugAssets UP-TO-DATE
-> Task :data:packageDebugAssets UP-TO-DATE
-> Task :player:mergeDebugShaders UP-TO-DATE
-> Task :player:compileDebugShaders NO-SOURCE
-> Task :player:generateDebugAssets UP-TO-DATE
-> Task :player:packageDebugAssets UP-TO-DATE
-> Task :app:mergeDebugAssets UP-TO-DATE
-> Task :app:compressDebugAssets UP-TO-DATE
-> Task :player:bundleLibRuntimeToJarDebug UP-TO-DATE
-> Task :app:desugarDebugFileDependencies UP-TO-DATE
-> Task :player:processDebugJavaRes UP-TO-DATE
-> Task :app:checkDebugDuplicateClasses UP-TO-DATE
-> Task :app:mergeExtDexDebug UP-TO-DATE
-> Task :player:bundleLibRuntimeToDirDebug UP-TO-DATE
-> Task :app:mergeDebugJniLibFolders UP-TO-DATE
-> Task :data:mergeDebugJniLibFolders UP-TO-DATE
-> Task :data:mergeDebugNativeLibs NO-SOURCE
-> Task :data:copyDebugJniLibsProjectOnly UP-TO-DATE
-> Task :player:mergeDebugJniLibFolders UP-TO-DATE
-> Task :player:mergeDebugNativeLibs NO-SOURCE
-> Task :player:copyDebugJniLibsProjectOnly UP-TO-DATE
-> Task :app:mergeDebugNativeLibs UP-TO-DATE
-> Task :app:stripDebugDebugSymbols UP-TO-DATE
-> Task :app:validateSigningDebug UP-TO-DATE
-> Task :app:writeDebugAppMetadata UP-TO-DATE
-> Task :app:writeDebugSigningConfigVersions UP-TO-DATE
-> Task :data:stripDebugDebugSymbols NO-SOURCE
-> Task :data:copyDebugJniLibsProjectAndLocalJars UP-TO-DATE
-> Task :data:extractDeepLinksForAarDebug UP-TO-DATE
-> Task :data:prepareDebugArtProfile UP-TO-DATE
-> Task :data:prepareLintJarForPublish UP-TO-DATE
-> Task :player:stripDebugDebugSymbols NO-SOURCE
-> Task :player:copyDebugJniLibsProjectAndLocalJars UP-TO-DATE
-> Task :player:extractDebugAnnotations UP-TO-DATE
-> Task :player:extractDeepLinksForAarDebug UP-TO-DATE
-> Task :player:mergeDebugGeneratedProguardFiles UP-TO-DATE
-> Task :player:mergeDebugConsumerProguardFiles UP-TO-DATE
-> Task :player:prepareDebugArtProfile UP-TO-DATE
-> Task :player:prepareLintJarForPublish UP-TO-DATE
-> Task :player:mergeDebugJavaResource UP-TO-DATE
-> Task :player:syncDebugLibJars UP-TO-DATE
-> Task :player:bundleDebugAar UP-TO-DATE
-> Task :player:assembleDebug UP-TO-DATE
+> Task :app:kspDebugKotlin UP-TO-DATE
-> Task :data:kspDebugKotlin FAILED
+> Task :app:compileDebugKotlin FAILED
+e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:105:9 Unresolved reference 'ProgramHistoryDialog'.
+e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:108:33 Cannot infer type for this parameter. Please specify it explicitly.
+e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:471:33 Unresolved reference 'Slider'.
+e: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerScreen.kt:475:46 Unresolved reference 'SliderDefaults'.
-> Task :data:copyRoomSchemas NO-SOURCE
-79 actionable tasks: 1 executed, 78 up-to-date
+FAILURE: Build failed with an exception.
+
+* What went wrong:
+Execution failed for task ':app:compileDebugKotlin'.
+> A failure occurred while executing org.jetbrains.kotlin.compilerRunner.GradleCompilerRunnerWithWorkers$GradleKotlinCompilerWorkAction
+ > Compilation error. See log for more details
+
+* Try:
+> Run with --stacktrace option to get the stack trace.
+> Run with --info or --debug option to get more log output.
+> Run with --scan to get full insights.
+> Get more help at https://help.gradle.org.
+
+BUILD FAILED in 6s
+47 actionable tasks: 1 executed, 46 up-to-date
diff --git a/build2.log b/build2.log
new file mode 100644
index 00000000..f1d0059e
--- /dev/null
+++ b/build2.log
@@ -0,0 +1,71 @@
+> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :domain:compileKotlin UP-TO-DATE
+> Task :domain:compileJava NO-SOURCE
+> Task :domain:processResources NO-SOURCE
+> Task :domain:classes UP-TO-DATE
+> Task :domain:jar UP-TO-DATE
+> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :app:preBuild UP-TO-DATE
+> Task :app:preDebugBuild UP-TO-DATE
+> Task :data:preBuild UP-TO-DATE
+> Task :data:preDebugBuild UP-TO-DATE
+> Task :data:writeDebugAarMetadata UP-TO-DATE
+> Task :player:preBuild UP-TO-DATE
+> Task :player:preDebugBuild UP-TO-DATE
+> Task :player:writeDebugAarMetadata UP-TO-DATE
+> Task :app:checkDebugAarMetadata UP-TO-DATE
+> Task :app:generateDebugResValues UP-TO-DATE
+> Task :data:generateDebugResValues UP-TO-DATE
+> Task :data:generateDebugResources UP-TO-DATE
+> Task :data:packageDebugResources UP-TO-DATE
+> Task :player:generateDebugResValues UP-TO-DATE
+> Task :player:generateDebugResources UP-TO-DATE
+> Task :player:packageDebugResources UP-TO-DATE
+> Task :app:mapDebugSourceSetPaths UP-TO-DATE
+> Task :app:generateDebugResources UP-TO-DATE
+> Task :app:mergeDebugResources UP-TO-DATE
+> Task :app:packageDebugResources UP-TO-DATE
+> Task :app:parseDebugLocalResources UP-TO-DATE
+> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
+> Task :app:extractDeepLinksDebug UP-TO-DATE
+> Task :data:extractDeepLinksDebug UP-TO-DATE
+> Task :data:processDebugManifest UP-TO-DATE
+> Task :player:extractDeepLinksDebug UP-TO-DATE
+> Task :player:processDebugManifest UP-TO-DATE
+> Task :app:processDebugMainManifest UP-TO-DATE
+> Task :app:processDebugManifest UP-TO-DATE
+> Task :app:processDebugManifestForPackage UP-TO-DATE
+> Task :data:compileDebugLibraryResources UP-TO-DATE
+> Task :data:parseDebugLocalResources UP-TO-DATE
+> Task :data:generateDebugRFile UP-TO-DATE
+> Task :player:compileDebugLibraryResources UP-TO-DATE
+> Task :player:parseDebugLocalResources UP-TO-DATE
+> Task :player:generateDebugRFile UP-TO-DATE
+> Task :app:processDebugResources UP-TO-DATE
+> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :data:kspDebugKotlin UP-TO-DATE
+> Task :data:compileDebugKotlin UP-TO-DATE
+> Task :data:javaPreCompileDebug UP-TO-DATE
+> Task :data:compileDebugJavaWithJavac UP-TO-DATE
+> Task :data:copyRoomSchemas NO-SOURCE
+> Task :data:transformDebugClassesWithAsm UP-TO-DATE
+> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
+> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :player:kspDebugKotlin UP-TO-DATE
+> Task :player:compileDebugKotlin UP-TO-DATE
+> Task :player:javaPreCompileDebug UP-TO-DATE
+> Task :player:compileDebugJavaWithJavac UP-TO-DATE
+> Task :player:transformDebugClassesWithAsm UP-TO-DATE
+> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
+> Task :app:kspDebugKotlin
+
+> Task :app:compileDebugKotlin
+w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt:159:26 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
+w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt:171:26 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
+w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt:225:26 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
+w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt:233:26 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
+w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt:77:7 This declaration needs opt-in. Its usage should be marked with '@kotlinx.coroutines.ExperimentalCoroutinesApi' or '@OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class)'
+w: file:///C:/Users/david/.gemini/antigravity/scratch/iptv-player/app/src/main/java/com/streamvault/app/ui/screens/settings/parental/ParentalControlGroupScreen.kt:59:36 'val Icons.Filled.ArrowBack: ImageVector' is deprecated. Use the AutoMirrored version at Icons.AutoMirrored.Filled.ArrowBack.
+
+BUILD SUCCESSFUL in 35s
+47 actionable tasks: 2 executed, 45 up-to-date
diff --git a/build_apk.log b/build_apk.log
new file mode 100644
index 00000000..4b275242
--- /dev/null
+++ b/build_apk.log
@@ -0,0 +1,137 @@
+> Task :app:preBuild UP-TO-DATE
+> Task :app:preDebugBuild UP-TO-DATE
+> Task :app:mergeDebugNativeDebugMetadata NO-SOURCE
+> Task :domain:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :domain:compileKotlin UP-TO-DATE
+> Task :domain:compileJava NO-SOURCE
+> Task :domain:processResources NO-SOURCE
+> Task :domain:classes UP-TO-DATE
+> Task :domain:jar UP-TO-DATE
+> Task :app:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :data:preBuild UP-TO-DATE
+> Task :data:preDebugBuild UP-TO-DATE
+> Task :data:writeDebugAarMetadata UP-TO-DATE
+> Task :player:preBuild UP-TO-DATE
+> Task :player:preDebugBuild UP-TO-DATE
+> Task :player:writeDebugAarMetadata UP-TO-DATE
+> Task :app:checkDebugAarMetadata UP-TO-DATE
+> Task :app:generateDebugResValues UP-TO-DATE
+> Task :data:generateDebugResValues UP-TO-DATE
+> Task :data:generateDebugResources UP-TO-DATE
+> Task :data:packageDebugResources UP-TO-DATE
+> Task :player:generateDebugResValues UP-TO-DATE
+> Task :player:generateDebugResources UP-TO-DATE
+> Task :player:packageDebugResources UP-TO-DATE
+> Task :app:mapDebugSourceSetPaths UP-TO-DATE
+> Task :app:generateDebugResources UP-TO-DATE
+> Task :app:mergeDebugResources UP-TO-DATE
+> Task :app:packageDebugResources UP-TO-DATE
+> Task :app:parseDebugLocalResources UP-TO-DATE
+> Task :app:createDebugCompatibleScreenManifests UP-TO-DATE
+> Task :app:extractDeepLinksDebug UP-TO-DATE
+> Task :data:extractDeepLinksDebug UP-TO-DATE
+> Task :data:processDebugManifest UP-TO-DATE
+> Task :player:extractDeepLinksDebug UP-TO-DATE
+> Task :player:processDebugManifest UP-TO-DATE
+> Task :app:processDebugMainManifest UP-TO-DATE
+> Task :app:processDebugManifest UP-TO-DATE
+> Task :app:processDebugManifestForPackage UP-TO-DATE
+> Task :data:compileDebugLibraryResources UP-TO-DATE
+> Task :data:parseDebugLocalResources UP-TO-DATE
+> Task :data:generateDebugRFile UP-TO-DATE
+> Task :player:compileDebugLibraryResources UP-TO-DATE
+> Task :player:parseDebugLocalResources UP-TO-DATE
+> Task :player:generateDebugRFile UP-TO-DATE
+> Task :app:processDebugResources UP-TO-DATE
+> Task :data:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :data:kspDebugKotlin UP-TO-DATE
+> Task :data:compileDebugKotlin UP-TO-DATE
+> Task :data:javaPreCompileDebug UP-TO-DATE
+> Task :data:compileDebugJavaWithJavac UP-TO-DATE
+> Task :data:copyRoomSchemas NO-SOURCE
+> Task :data:transformDebugClassesWithAsm UP-TO-DATE
+> Task :data:bundleLibCompileToJarDebug UP-TO-DATE
+> Task :player:checkKotlinGradlePluginConfigurationErrors SKIPPED
+> Task :player:kspDebugKotlin UP-TO-DATE
+> Task :player:compileDebugKotlin UP-TO-DATE
+> Task :player:javaPreCompileDebug UP-TO-DATE
+> Task :player:compileDebugJavaWithJavac UP-TO-DATE
+> Task :player:transformDebugClassesWithAsm UP-TO-DATE
+> Task :player:bundleLibCompileToJarDebug UP-TO-DATE
+> Task :app:kspDebugKotlin UP-TO-DATE
+> Task :app:compileDebugKotlin UP-TO-DATE
+> Task :app:javaPreCompileDebug UP-TO-DATE
+> Task :app:compileDebugJavaWithJavac
+> Task :app:mergeDebugShaders UP-TO-DATE
+> Task :app:compileDebugShaders NO-SOURCE
+> Task :app:generateDebugAssets UP-TO-DATE
+> Task :data:mergeDebugShaders UP-TO-DATE
+> Task :data:compileDebugShaders NO-SOURCE
+> Task :data:generateDebugAssets UP-TO-DATE
+> Task :data:packageDebugAssets UP-TO-DATE
+> Task :player:mergeDebugShaders UP-TO-DATE
+> Task :player:compileDebugShaders NO-SOURCE
+> Task :player:generateDebugAssets UP-TO-DATE
+> Task :player:packageDebugAssets UP-TO-DATE
+> Task :app:mergeDebugAssets UP-TO-DATE
+> Task :app:compressDebugAssets UP-TO-DATE
+> Task :data:bundleLibRuntimeToJarDebug UP-TO-DATE
+> Task :player:bundleLibRuntimeToJarDebug UP-TO-DATE
+> Task :app:desugarDebugFileDependencies UP-TO-DATE
+> Task :data:processDebugJavaRes UP-TO-DATE
+> Task :player:processDebugJavaRes UP-TO-DATE
+> Task :app:checkDebugDuplicateClasses UP-TO-DATE
+> Task :app:mergeExtDexDebug UP-TO-DATE
+> Task :data:bundleLibRuntimeToDirDebug UP-TO-DATE
+> Task :player:bundleLibRuntimeToDirDebug UP-TO-DATE
+> Task :app:mergeLibDexDebug UP-TO-DATE
+> Task :app:mergeDebugJniLibFolders UP-TO-DATE
+> Task :data:mergeDebugJniLibFolders UP-TO-DATE
+> Task :data:mergeDebugNativeLibs NO-SOURCE
+> Task :data:copyDebugJniLibsProjectOnly UP-TO-DATE
+> Task :player:mergeDebugJniLibFolders UP-TO-DATE
+> Task :player:mergeDebugNativeLibs NO-SOURCE
+> Task :player:copyDebugJniLibsProjectOnly UP-TO-DATE
+> Task :app:mergeDebugNativeLibs UP-TO-DATE
+> Task :app:stripDebugDebugSymbols UP-TO-DATE
+> Task :app:validateSigningDebug UP-TO-DATE
+> Task :app:writeDebugAppMetadata UP-TO-DATE
+> Task :app:writeDebugSigningConfigVersions UP-TO-DATE
+> Task :data:stripDebugDebugSymbols NO-SOURCE
+> Task :data:copyDebugJniLibsProjectAndLocalJars UP-TO-DATE
+> Task :app:hiltAggregateDepsDebug
+> Task :data:extractDebugAnnotations UP-TO-DATE
+> Task :app:hiltJavaCompileDebug
+> Task :app:processDebugJavaRes
+> Task :data:extractDeepLinksForAarDebug UP-TO-DATE
+> Task :data:mergeDebugGeneratedProguardFiles UP-TO-DATE
+> Task :data:mergeDebugConsumerProguardFiles UP-TO-DATE
+> Task :data:prepareDebugArtProfile UP-TO-DATE
+> Task :data:prepareLintJarForPublish UP-TO-DATE
+> Task :data:mergeDebugJavaResource UP-TO-DATE
+> Task :data:syncDebugLibJars UP-TO-DATE
+> Task :data:bundleDebugAar UP-TO-DATE
+> Task :data:assembleDebug UP-TO-DATE
+> Task :player:stripDebugDebugSymbols NO-SOURCE
+> Task :player:copyDebugJniLibsProjectAndLocalJars UP-TO-DATE
+> Task :player:extractDebugAnnotations UP-TO-DATE
+> Task :player:extractDeepLinksForAarDebug UP-TO-DATE
+> Task :player:mergeDebugGeneratedProguardFiles UP-TO-DATE
+> Task :player:mergeDebugConsumerProguardFiles UP-TO-DATE
+> Task :player:prepareDebugArtProfile UP-TO-DATE
+> Task :player:prepareLintJarForPublish UP-TO-DATE
+> Task :player:mergeDebugJavaResource UP-TO-DATE
+> Task :player:syncDebugLibJars UP-TO-DATE
+> Task :player:bundleDebugAar UP-TO-DATE
+> Task :player:assembleDebug UP-TO-DATE
+> Task :app:mergeDebugJavaResource
+> Task :app:transformDebugClassesWithAsm
+> Task :app:dexBuilderDebug
+> Task :app:mergeDebugGlobalSynthetics
+> Task :app:mergeProjectDexDebug
+> Task :app:packageDebug
+> Task :app:createDebugApkListingFileRedirect
+> Task :app:assembleDebug
+
+BUILD SUCCESSFUL in 32s
+106 actionable tasks: 11 executed, 95 up-to-date
diff --git a/build_log.txt b/build_log.txt
new file mode 100644
index 00000000..49c4c353
Binary files /dev/null and b/build_log.txt differ
diff --git a/compile_log.txt b/compile_log.txt
new file mode 100644
index 00000000..b541ef92
Binary files /dev/null and b/compile_log.txt differ
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/4.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/4.json
index 133f55ee..e6400b67 100644
--- a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/4.json
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/4.json
@@ -2,7 +2,7 @@
"formatVersion": 1,
"database": {
"version": 4,
- "identityHash": "b14c1de6571c191aec43a79a67ebc1ef",
+ "identityHash": "55a757cfaa70d7e240ef719680f48d09",
"entities": [
{
"tableName": "providers",
@@ -115,7 +115,7 @@
},
{
"tableName": "channels",
- "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL)",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL)",
"fields": [
{
"fieldPath": "id",
@@ -189,6 +189,12 @@
"affinity": "INTEGER",
"notNull": true
},
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT",
+ "notNull": false
+ },
{
"fieldPath": "providerId",
"columnName": "provider_id",
@@ -1273,7 +1279,7 @@
"views": [],
"setupQueries": [
"CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
- "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, 'b14c1de6571c191aec43a79a67ebc1ef')"
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '55a757cfaa70d7e240ef719680f48d09')"
]
}
}
\ No newline at end of file
diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
index 009ef3da..440cd3a8 100644
--- a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
+++ b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
@@ -49,6 +49,7 @@ data class ChannelEntity(
val number: Int = 0,
@ColumnInfo(name = "catch_up_supported") val catchUpSupported: Boolean = false,
@ColumnInfo(name = "catch_up_days") val catchUpDays: Int = 0,
+ val catchUpSource: String? = null,
@ColumnInfo(name = "provider_id") val providerId: Long = 0,
@ColumnInfo(name = "is_adult") val isAdult: Boolean = false,
@ColumnInfo(name = "is_user_protected") val isUserProtected: Boolean = false
diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
index 4bf37f3b..db31c5a0 100644
--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
@@ -53,6 +53,7 @@ fun ChannelEntity.toDomain() = Channel(
number = number,
catchUpSupported = catchUpSupported,
catchUpDays = catchUpDays,
+ catchUpSource = catchUpSource,
providerId = providerId,
isAdult = isAdult,
isUserProtected = isUserProtected
@@ -71,6 +72,7 @@ fun Channel.toEntity() = ChannelEntity(
number = number,
catchUpSupported = catchUpSupported,
catchUpDays = catchUpDays,
+ catchUpSource = catchUpSource,
providerId = providerId,
isAdult = isAdult,
isUserProtected = isUserProtected
diff --git a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
index b66cc330..6d579ff8 100644
--- a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
+++ b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
@@ -28,6 +28,7 @@ class M3uParser {
val tvgLogo: String?,
val tvgChno: Int?,
val catchUp: String?,
+ val catchUpDays: Int?,
val catchUpSource: String?,
val url: String,
val extraAttributes: Map<String, String> = emptyMap()
@@ -88,6 +89,8 @@ class M3uParser {
number = entry.tvgChno ?: (index + 1),
streamUrl = entry.url,
catchUpSupported = entry.catchUp != null,
+ catchUpDays = entry.catchUpDays ?: 0,
+ catchUpSource = entry.catchUpSource,
providerId = providerId
)
}
@@ -128,6 +131,7 @@ class M3uParser {
tvgLogo = attributes["tvg-logo"]?.takeIf { it.isNotBlank() },
tvgChno = attributes["tvg-chno"]?.toIntOrNull(),
catchUp = attributes["catchup"]?.takeIf { it.isNotBlank() },
+ catchUpDays = attributes["catchup-days"]?.toIntOrNull(),
catchUpSource = attributes["catchup-source"]?.takeIf { it.isNotBlank() },
url = url,
extraAttributes = attributes
diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
index 8c551ff6..4c68208e 100644
--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
@@ -181,6 +181,26 @@ class ProviderRepositoryImpl @Inject constructor(
onProgress: ((String) -> Unit)?
): Result<Unit> = syncManager.sync(providerId, onProgress)
+ override suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String? {
+ val provider = providerDao.getById(providerId) ?: return null
+ return if (provider.type == ProviderType.XTREAM_CODES.name) {
+ createXtreamProvider(providerId, provider.serverUrl, provider.username, provider.password)
+ .buildCatchUpUrl(streamId, start, end)
+ } else {
+ // M3U catch-up
+ val channel = channelDao.getById(streamId) ?: return null
+ val source = channel.catchUpSource ?: return null
+
+ // Substitute variables in template
+ source.replace("{start}", start.toString())
+ .replace("{end}", end.toString())
+ .replace("{duration}", (end - start).toString())
+ .replace("{utc}", start.toString())
+ .replace("{lutc}", end.toString())
+ .replace("{timestamp}", start.toString())
+ }
+ }
+
fun createXtreamProvider(
providerId: Long,
serverUrl: String,
diff --git a/domain/bin/main/com/streamvault/domain/manager/ParentalControlManager.kt b/domain/bin/main/com/streamvault/domain/manager/ParentalControlManager.kt
new file mode 100644
index 00000000..2f82762d
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/manager/ParentalControlManager.kt
@@ -0,0 +1,27 @@
+package com.streamvault.domain.manager
+
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import javax.inject.Inject
+import javax.inject.Singleton
+
+@Singleton
+class ParentalControlManager @Inject constructor() {
+ private val _unlockedCategories = MutableStateFlow<Set<Long>>(emptySet())
+ val unlockedCategories: StateFlow<Set<Long>> = _unlockedCategories.asStateFlow()
+
+ fun unlockCategory(categoryId: Long) {
+ val current = _unlockedCategories.value.toMutableSet()
+ current.add(categoryId)
+ _unlockedCategories.value = current
+ }
+
+ fun isCategoryUnlocked(categoryId: Long): Boolean {
+ return _unlockedCategories.value.contains(categoryId)
+ }
+
+ fun clearUnlockedCategories() {
+ _unlockedCategories.value = emptySet()
+ }
+}
diff --git a/domain/bin/main/com/streamvault/domain/model/Category.kt b/domain/bin/main/com/streamvault/domain/model/Category.kt
new file mode 100644
index 00000000..a26bfd47
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/Category.kt
@@ -0,0 +1,12 @@
+package com.streamvault.domain.model
+
+data class Category(
+ val id: Long,
+ val name: String,
+ val parentId: Long? = null,
+ val type: ContentType = ContentType.LIVE,
+ val isVirtual: Boolean = false,
+ val count: Int = 0,
+ val isAdult: Boolean = false,
+ val isUserProtected: Boolean = false
+)
diff --git a/domain/bin/main/com/streamvault/domain/model/Channel.kt b/domain/bin/main/com/streamvault/domain/model/Channel.kt
new file mode 100644
index 00000000..45ea5713
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/Channel.kt
@@ -0,0 +1,22 @@
+package com.streamvault.domain.model
+
+data class Channel(
+ val id: Long,
+ val name: String,
+ val logoUrl: String? = null,
+ val groupTitle: String? = null,
+ val categoryId: Long? = null,
+ val categoryName: String? = null,
+ val streamUrl: String = "",
+ val epgChannelId: String? = null,
+ val number: Int = 0,
+ val isFavorite: Boolean = false,
+ val catchUpSupported: Boolean = false,
+ val catchUpDays: Int = 0,
+ val catchUpSource: String? = null,
+ val providerId: Long = 0,
+ val currentProgram: Program? = null,
+ val nextProgram: Program? = null,
+ val isAdult: Boolean = false,
+ val isUserProtected: Boolean = false
+)
diff --git a/domain/bin/main/com/streamvault/domain/model/ContentType.kt b/domain/bin/main/com/streamvault/domain/model/ContentType.kt
new file mode 100644
index 00000000..283a509d
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/ContentType.kt
@@ -0,0 +1,8 @@
+package com.streamvault.domain.model
+
+enum class ContentType {
+ LIVE,
+ MOVIE,
+ SERIES,
+ SERIES_EPISODE
+}
diff --git a/domain/bin/main/com/streamvault/domain/model/Favorite.kt b/domain/bin/main/com/streamvault/domain/model/Favorite.kt
new file mode 100644
index 00000000..f78307bf
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/Favorite.kt
@@ -0,0 +1,18 @@
+package com.streamvault.domain.model
+
+data class Favorite(
+ val id: Long = 0,
+ val contentId: Long,
+ val contentType: ContentType,
+ val position: Int = 0,
+ val groupId: Long? = null,
+ val addedAt: Long = System.currentTimeMillis()
+)
+
+data class VirtualGroup(
+ val id: Long = 0,
+ val name: String,
+ val iconEmoji: String? = null,
+ val position: Int = 0,
+ val createdAt: Long = System.currentTimeMillis()
+)
diff --git a/domain/bin/main/com/streamvault/domain/model/Movie.kt b/domain/bin/main/com/streamvault/domain/model/Movie.kt
new file mode 100644
index 00000000..365804fe
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/Movie.kt
@@ -0,0 +1,29 @@
+package com.streamvault.domain.model
+
+data class Movie(
+ val id: Long,
+ val name: String,
+ val posterUrl: String? = null,
+ val backdropUrl: String? = null,
+ val categoryId: Long? = null,
+ val categoryName: String? = null,
+ val streamUrl: String = "",
+ val containerExtension: String? = null,
+ val plot: String? = null,
+ val cast: String? = null,
+ val director: String? = null,
+ val genre: String? = null,
+ val releaseDate: String? = null,
+ val duration: String? = null,
+ val durationSeconds: Int = 0,
+ val rating: Float = 0f,
+ val year: String? = null,
+ val tmdbId: Long? = null,
+ val youtubeTrailer: String? = null,
+ val isFavorite: Boolean = false,
+ val providerId: Long = 0,
+ val watchProgress: Long = 0L,
+ val lastWatchedAt: Long = 0L,
+ val isAdult: Boolean = false,
+ val isUserProtected: Boolean = false
+)
diff --git a/domain/bin/main/com/streamvault/domain/model/PlaybackHistory.kt b/domain/bin/main/com/streamvault/domain/model/PlaybackHistory.kt
new file mode 100644
index 00000000..9c502588
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/PlaybackHistory.kt
@@ -0,0 +1,18 @@
+package com.streamvault.domain.model
+
+data class PlaybackHistory(
+ val id: Long = 0,
+ val contentId: Long,
+ val contentType: ContentType,
+ val providerId: Long,
+ val title: String,
+ val posterUrl: String? = null,
+ val streamUrl: String,
+ val resumePositionMs: Long = 0,
+ val totalDurationMs: Long = 0,
+ val lastWatchedAt: Long = 0,
+ val watchCount: Int = 1,
+ val seriesId: Long? = null,
+ val seasonNumber: Int? = null,
+ val episodeNumber: Int? = null
+)
diff --git a/domain/bin/main/com/streamvault/domain/model/Program.kt b/domain/bin/main/com/streamvault/domain/model/Program.kt
new file mode 100644
index 00000000..6264b748
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/Program.kt
@@ -0,0 +1,24 @@
+package com.streamvault.domain.model
+
+data class Program(
+ val id: Long = 0,
+ val channelId: String,
+ val title: String,
+ val description: String = "",
+ val startTime: Long = 0L,
+ val endTime: Long = 0L,
+ val lang: String = "",
+ val hasArchive: Boolean = false,
+ val isNowPlaying: Boolean = false
+) {
+ val durationMinutes: Int
+ get() = ((endTime - startTime) / 60000).toInt()
+
+ val progressPercent: Float
+ get() {
+ if (!isNowPlaying) return 0f
+ val now = System.currentTimeMillis()
+ if (now < startTime || endTime <= startTime) return 0f
+ return ((now - startTime).toFloat() / (endTime - startTime).toFloat()).coerceIn(0f, 1f)
+ }
+}
diff --git a/domain/bin/main/com/streamvault/domain/model/Provider.kt b/domain/bin/main/com/streamvault/domain/model/Provider.kt
new file mode 100644
index 00000000..6b5a6d06
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/Provider.kt
@@ -0,0 +1,31 @@
+package com.streamvault.domain.model
+
+data class Provider(
+ val id: Long = 0,
+ val name: String,
+ val type: ProviderType,
+ val serverUrl: String,
+ val username: String = "",
+ val password: String = "",
+ val m3uUrl: String = "",
+ val epgUrl: String = "",
+ val isActive: Boolean = true,
+ val maxConnections: Int = 1,
+ val expirationDate: Long? = null,
+ val status: ProviderStatus = ProviderStatus.UNKNOWN,
+ val lastSyncedAt: Long = 0L,
+ val createdAt: Long = System.currentTimeMillis()
+)
+
+enum class ProviderType {
+ XTREAM_CODES,
+ M3U
+}
+
+enum class ProviderStatus {
+ ACTIVE,
+ EXPIRED,
+ DISABLED,
+ ERROR,
+ UNKNOWN
+}
diff --git a/domain/bin/main/com/streamvault/domain/model/Result.kt b/domain/bin/main/com/streamvault/domain/model/Result.kt
new file mode 100644
index 00000000..b9240014
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/Result.kt
@@ -0,0 +1,27 @@
+package com.streamvault.domain.model
+
+/**
+ * Generic result wrapper for handling success/failure across layers.
+ */
+sealed class Result<out T> {
+ data class Success<T>(val data: T) : Result<T>()
+ data class Error(val message: String, val exception: Throwable? = null) : Result<Nothing>()
+ data object Loading : Result<Nothing>()
+
+ val isSuccess: Boolean get() = this is Success
+ val isError: Boolean get() = this is Error
+
+ fun getOrNull(): T? = (this as? Success)?.data
+ fun errorMessageOrNull(): String? = (this as? Error)?.message
+
+ fun <R> map(transform: (T) -> R): Result<R> = when (this) {
+ is Success -> Success(transform(data))
+ is Error -> Error(message, exception)
+ is Loading -> Loading
+ }
+
+ companion object {
+ fun <T> success(data: T) = Success(data)
+ fun error(message: String, exception: Throwable? = null) = Error(message, exception)
+ }
+}
diff --git a/domain/bin/main/com/streamvault/domain/model/Series.kt b/domain/bin/main/com/streamvault/domain/model/Series.kt
new file mode 100644
index 00000000..61c5efd6
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/Series.kt
@@ -0,0 +1,55 @@
+package com.streamvault.domain.model
+
+data class Series(
+ val id: Long,
+ val name: String,
+ val posterUrl: String? = null,
+ val backdropUrl: String? = null,
+ val categoryId: Long? = null,
+ val categoryName: String? = null,
+ val plot: String? = null,
+ val cast: String? = null,
+ val director: String? = null,
+ val genre: String? = null,
+ val releaseDate: String? = null,
+ val rating: Float = 0f,
+ val tmdbId: Long? = null,
+ val youtubeTrailer: String? = null,
+ val isFavorite: Boolean = false,
+ val providerId: Long = 0,
+ val seasons: List<Season> = emptyList(),
+ val episodeRunTime: String? = null,
+ val lastModified: Long = 0L,
+ val isAdult: Boolean = false,
+ val isUserProtected: Boolean = false
+)
+
+data class Season(
+ val seasonNumber: Int,
+ val name: String = "Season $seasonNumber",
+ val coverUrl: String? = null,
+ val episodes: List<Episode> = emptyList(),
+ val airDate: String? = null,
+ val episodeCount: Int = 0
+)
+
+data class Episode(
+ val id: Long,
+ val title: String,
+ val episodeNumber: Int,
+ val seasonNumber: Int,
+ val streamUrl: String = "",
+ val containerExtension: String? = null,
+ val coverUrl: String? = null,
+ val plot: String? = null,
+ val duration: String? = null,
+ val durationSeconds: Int = 0,
+ val rating: Float = 0f,
+ val releaseDate: String? = null,
+ val seriesId: Long = 0,
+ val providerId: Long = 0,
+ val watchProgress: Long = 0L,
+ val lastWatchedAt: Long = 0L,
+ val isAdult: Boolean = false,
+ val isUserProtected: Boolean = false
+)
diff --git a/domain/bin/main/com/streamvault/domain/model/StreamInfo.kt b/domain/bin/main/com/streamvault/domain/model/StreamInfo.kt
new file mode 100644
index 00000000..c9019467
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/StreamInfo.kt
@@ -0,0 +1,24 @@
+package com.streamvault.domain.model
+
+data class StreamInfo(
+ val url: String,
+ val headers: Map<String, String> = emptyMap(),
+ val userAgent: String? = null,
+ val streamType: StreamType = StreamType.UNKNOWN,
+ val containerExtension: String? = null,
+ val catchUpUrl: String? = null
+)
+
+enum class StreamType {
+ HLS,
+ DASH,
+ MPEG_TS,
+ PROGRESSIVE,
+ UNKNOWN
+}
+
+enum class DecoderMode {
+ AUTO,
+ HARDWARE,
+ SOFTWARE
+}
diff --git a/domain/bin/main/com/streamvault/domain/model/SyncMetadata.kt b/domain/bin/main/com/streamvault/domain/model/SyncMetadata.kt
new file mode 100644
index 00000000..1189253e
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/SyncMetadata.kt
@@ -0,0 +1,14 @@
+package com.streamvault.domain.model
+
+data class SyncMetadata(
+ val providerId: Long,
+ val lastLiveSync: Long = 0,
+ val lastMovieSync: Long = 0,
+ val lastSeriesSync: Long = 0,
+ val lastEpgSync: Long = 0,
+ val liveCount: Int = 0,
+ val movieCount: Int = 0,
+ val seriesCount: Int = 0,
+ val epgCount: Int = 0,
+ val lastSyncStatus: String = "NONE"
+)
diff --git a/domain/bin/main/com/streamvault/domain/model/SyncState.kt b/domain/bin/main/com/streamvault/domain/model/SyncState.kt
new file mode 100644
index 00000000..7be31580
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/SyncState.kt
@@ -0,0 +1,33 @@
+package com.streamvault.domain.model
+
+/**
+ * Represents every stage of a provider sync operation.
+ *
+ * Designed as a sealed hierarchy so `when` branches are exhaustive and
+ * the compiler enforces handling of every state.
+ */
+sealed class SyncState {
+
+ /** No sync is in progress and no result is available yet. */
+ object Idle : SyncState()
+
+ /** A sync is actively running. [phase] describes the current work (e.g. "Downloading Live TV…"). */
+ data class Syncing(val phase: String = "") : SyncState()
+
+ /** The most recent sync completed successfully at [timestamp] (epoch millis). */
+ data class Success(val timestamp: Long = System.currentTimeMillis()) : SyncState()
+
+ /**
+ * The most recent sync failed.
+ *
+ * @param message Human-readable description of the failure.
+ * @param cause Optional underlying exception for diagnostics.
+ */
+ data class Error(val message: String, val cause: Throwable? = null) : SyncState()
+
+ // ── Convenience helpers ─────────────────────────────────────────
+
+ val isSyncing: Boolean get() = this is Syncing
+ val isError: Boolean get() = this is Error
+ val isSuccess: Boolean get() = this is Success
+}
diff --git a/domain/bin/main/com/streamvault/domain/model/VideoFormat.kt b/domain/bin/main/com/streamvault/domain/model/VideoFormat.kt
new file mode 100644
index 00000000..6dfe7bbe
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/model/VideoFormat.kt
@@ -0,0 +1,22 @@
+package com.streamvault.domain.model
+
+data class VideoFormat(
+ val width: Int,
+ val height: Int,
+ val frameRate: Float = 0f,
+ val bitrate: Int = 0,
+ val codecV: String? = null,
+ val codecA: String? = null
+) {
+ val resolutionLabel: String
+ get() = when {
+ height >= 2160 -> "4K"
+ height >= 1440 -> "1440p"
+ height >= 1080 -> "1080p"
+ height >= 720 -> "720p"
+ height > 0 -> "${height}p"
+ else -> "Unknown"
+ }
+
+ val isEmpty: Boolean get() = width == 0 && height == 0
+}
diff --git a/domain/bin/main/com/streamvault/domain/provider/IptvProvider.kt b/domain/bin/main/com/streamvault/domain/provider/IptvProvider.kt
new file mode 100644
index 00000000..b9e92e2b
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/provider/IptvProvider.kt
@@ -0,0 +1,30 @@
+package com.streamvault.domain.provider
+
+import com.streamvault.domain.model.*
+
+/**
+ * Shared interface for all IPTV providers (Xtream Codes, M3U, etc.).
+ * Each provider type implements this to normalize data into domain models.
+ */
+interface IptvProvider {
+ val providerId: Long
+
+ suspend fun authenticate(): Result<Provider>
+
+ suspend fun getLiveCategories(): Result<List<Category>>
+ suspend fun getLiveStreams(categoryId: Long? = null): Result<List<Channel>>
+
+ suspend fun getVodCategories(): Result<List<Category>>
+ suspend fun getVodStreams(categoryId: Long? = null): Result<List<Movie>>
+ suspend fun getVodInfo(vodId: Long): Result<Movie>
+
+ suspend fun getSeriesCategories(): Result<List<Category>>
+ suspend fun getSeriesList(categoryId: Long? = null): Result<List<Series>>
+ suspend fun getSeriesInfo(seriesId: Long): Result<Series>
+
+ suspend fun getEpg(channelId: String): Result<List<Program>>
+ suspend fun getShortEpg(channelId: String, limit: Int = 4): Result<List<Program>>
+
+ suspend fun buildStreamUrl(streamId: Long, containerExtension: String? = null): String
+ suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String?
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/CategoryRepository.kt b/domain/bin/main/com/streamvault/domain/repository/CategoryRepository.kt
new file mode 100644
index 00000000..a5fb174b
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/CategoryRepository.kt
@@ -0,0 +1,9 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Category
+import kotlinx.coroutines.flow.Flow
+
+interface CategoryRepository {
+ fun getCategories(providerId: Long): Flow<List<Category>>
+ suspend fun setCategoryProtection(categoryId: Long, isProtected: Boolean)
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/ChannelRepository.kt b/domain/bin/main/com/streamvault/domain/repository/ChannelRepository.kt
new file mode 100644
index 00000000..9515373a
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/ChannelRepository.kt
@@ -0,0 +1,21 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.flow.Flow
+
+interface ChannelRepository {
+ fun getChannels(providerId: Long): Flow<List<Channel>>
+ fun getChannelsByCategory(providerId: Long, categoryId: Long): Flow<List<Channel>>
+ fun getCategories(providerId: Long): Flow<List<Category>>
+ fun searchChannels(providerId: Long, query: String): Flow<List<Channel>>
+ suspend fun getChannel(channelId: Long): Channel?
+ suspend fun getStreamUrl(channel: Channel): Result<String>
+ suspend fun refreshChannels(providerId: Long): Result<Unit>
+ fun getChannelsByIds(ids: List<Long>): Flow<List<Channel>>
+
+ companion object {
+ const val ALL_CHANNELS_ID = -1_000_000L
+ }
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/EpgRepository.kt b/domain/bin/main/com/streamvault/domain/repository/EpgRepository.kt
new file mode 100644
index 00000000..c09aa489
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/EpgRepository.kt
@@ -0,0 +1,14 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.flow.Flow
+
+interface EpgRepository {
+ fun getProgramsForChannel(channelId: String, startTime: Long, endTime: Long): Flow<List<Program>>
+ fun getNowPlaying(channelId: String): Flow<Program?>
+ fun getNowPlayingForChannels(channelIds: List<String>): Flow<List<Program>>
+ fun getNowAndNext(channelId: String): Flow<Pair<Program?, Program?>>
+ suspend fun refreshEpg(providerId: Long, epgUrl: String): Result<Unit>
+ suspend fun clearOldPrograms(beforeTime: Long)
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/FavoriteRepository.kt b/domain/bin/main/com/streamvault/domain/repository/FavoriteRepository.kt
new file mode 100644
index 00000000..7e9aac48
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/FavoriteRepository.kt
@@ -0,0 +1,28 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Favorite
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.VirtualGroup
+import kotlinx.coroutines.flow.Flow
+
+interface FavoriteRepository {
+ fun getFavorites(contentType: ContentType? = null): Flow<List<Favorite>>
+ fun getFavoritesByGroup(groupId: Long): Flow<List<Favorite>>
+ fun getGroups(): Flow<List<VirtualGroup>>
+
+ fun getGlobalLiveFavoriteCount(): Flow<Int>
+ fun getGroupLiveFavoriteCounts(): Flow<Map<Long, Int>>
+
+ suspend fun addFavorite(contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>
+ suspend fun removeFavorite(contentId: Long, contentType: ContentType, groupId: Long? = null): Result<Unit>
+
+ suspend fun reorderFavorites(favorites: List<Favorite>): Result<Unit>
+ suspend fun isFavorite(contentId: Long, contentType: ContentType): Boolean
+
+ suspend fun getGroupMemberships(contentId: Long, contentType: ContentType): List<Long>
+
+ suspend fun createGroup(name: String, iconEmoji: String? = null): Result<VirtualGroup>
+ suspend fun deleteGroup(groupId: Long): Result<Unit>
+ suspend fun renameGroup(groupId: Long, newName: String): Result<Unit>
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/MovieRepository.kt b/domain/bin/main/com/streamvault/domain/repository/MovieRepository.kt
new file mode 100644
index 00000000..3f9bef68
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/MovieRepository.kt
@@ -0,0 +1,18 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.Movie
+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 getCategories(providerId: Long): Flow<List<Category>>
+ fun searchMovies(providerId: Long, query: String): Flow<List<Movie>>
+ suspend fun getMovie(movieId: Long): Movie?
+ suspend fun getMovieDetails(providerId: Long, movieId: Long): Result<Movie>
+ suspend fun getStreamUrl(movie: Movie): Result<String>
+ suspend fun refreshMovies(providerId: Long): Result<Unit>
+ suspend fun updateWatchProgress(movieId: Long, progress: Long)
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/PlaybackHistoryRepository.kt b/domain/bin/main/com/streamvault/domain/repository/PlaybackHistoryRepository.kt
new file mode 100644
index 00000000..e69a467d
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/PlaybackHistoryRepository.kt
@@ -0,0 +1,16 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.PlaybackHistory
+import kotlinx.coroutines.flow.Flow
+
+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 updateResumePosition(history: PlaybackHistory)
+ suspend fun removeFromHistory(contentId: Long, contentType: ContentType, providerId: Long)
+ suspend fun clearAllHistory()
+ suspend fun clearHistoryForProvider(providerId: Long)
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/ProviderRepository.kt b/domain/bin/main/com/streamvault/domain/repository/ProviderRepository.kt
new file mode 100644
index 00000000..14939dc0
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/ProviderRepository.kt
@@ -0,0 +1,19 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.flow.Flow
+
+interface ProviderRepository {
+ fun getProviders(): Flow<List<Provider>>
+ fun getActiveProvider(): Flow<Provider?>
+ suspend fun getProvider(id: Long): Provider?
+ suspend fun addProvider(provider: Provider): Result<Long>
+ suspend fun updateProvider(provider: Provider): Result<Unit>
+ suspend fun deleteProvider(id: Long): Result<Unit>
+ suspend fun setActiveProvider(id: Long): Result<Unit>
+ suspend fun loginXtream(serverUrl: String, username: String, password: String, name: String, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>
+ suspend fun validateM3u(url: String, name: String, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>
+ suspend fun refreshProviderData(providerId: Long, onProgress: ((String) -> Unit)? = null): Result<Unit>
+ suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String?
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/SeriesRepository.kt b/domain/bin/main/com/streamvault/domain/repository/SeriesRepository.kt
new file mode 100644
index 00000000..6c394dc2
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/SeriesRepository.kt
@@ -0,0 +1,19 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.Episode
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.Series
+import kotlinx.coroutines.flow.Flow
+
+interface SeriesRepository {
+ fun getSeries(providerId: Long): Flow<List<Series>>
+ fun getSeriesByCategory(providerId: Long, categoryId: Long): Flow<List<Series>>
+ fun getCategories(providerId: Long): Flow<List<Category>>
+ fun searchSeries(providerId: Long, query: String): Flow<List<Series>>
+ suspend fun getSeriesById(seriesId: Long): Series?
+ suspend fun getSeriesDetails(providerId: Long, seriesId: Long): Result<Series>
+ suspend fun getEpisodeStreamUrl(episode: Episode): Result<String>
+ suspend fun refreshSeries(providerId: Long): Result<Unit>
+ suspend fun updateEpisodeWatchProgress(episodeId: Long, progress: Long)
+}
diff --git a/domain/bin/main/com/streamvault/domain/repository/SyncMetadataRepository.kt b/domain/bin/main/com/streamvault/domain/repository/SyncMetadataRepository.kt
new file mode 100644
index 00000000..48faefe6
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/repository/SyncMetadataRepository.kt
@@ -0,0 +1,11 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.SyncMetadata
+import kotlinx.coroutines.flow.Flow
+
+interface SyncMetadataRepository {
+ fun observeMetadata(providerId: Long): Flow<SyncMetadata?>
+ suspend fun getMetadata(providerId: Long): SyncMetadata?
+ suspend fun updateMetadata(metadata: SyncMetadata)
+ suspend fun clearMetadata(providerId: Long)
+}
diff --git a/domain/bin/main/com/streamvault/domain/usecase/GetCustomCategories.kt b/domain/bin/main/com/streamvault/domain/usecase/GetCustomCategories.kt
new file mode 100644
index 00000000..8587e6c8
--- /dev/null
+++ b/domain/bin/main/com/streamvault/domain/usecase/GetCustomCategories.kt
@@ -0,0 +1,49 @@
+package com.streamvault.domain.usecase
+
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.repository.FavoriteRepository
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+import javax.inject.Inject
+
+class GetCustomCategories @Inject constructor(
+ private val favoriteRepository: FavoriteRepository
+) {
+ operator fun invoke(): Flow<List<Category>> {
+ return kotlinx.coroutines.flow.combine(
+ favoriteRepository.getGroups(),
+ favoriteRepository.getGlobalLiveFavoriteCount(),
+ favoriteRepository.getGroupLiveFavoriteCounts()
+ ) { groups, globalCount, groupCounts ->
+ try {
+ println("GetCustomCategories: Processing ${groups.size} groups. Global: $globalCount, Counts: ${groupCounts.size}")
+
+ val categories = groups.map { group ->
+ Category(
+ id = -group.id, // Use negative ID for virtual groups
+ name = group.name,
+ type = ContentType.LIVE,
+ isVirtual = true,
+ count = groupCounts.getOrDefault(group.id, 0)
+ )
+ }.toMutableList()
+
+ // prepend "Favorites" as a special virtual category
+ categories.add(0, Category(
+ id = -999L, // Special ID for "All Favorites"
+ name = "★ Favorites",
+ type = ContentType.LIVE,
+ isVirtual = true,
+ count = globalCount
+ ))
+
+ categories
+ } catch (e: Exception) {
+ println("GetCustomCategories: Error processing categories: ${e.message}")
+ e.printStackTrace()
+ emptyList<Category>()
+ }
+ }
+ }
+}
diff --git a/domain/src/main/java/com/streamvault/domain/model/Channel.kt b/domain/src/main/java/com/streamvault/domain/model/Channel.kt
index 02e859f8..45ea5713 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Channel.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Channel.kt
@@ -13,6 +13,7 @@ data class Channel(
val isFavorite: Boolean = false,
val catchUpSupported: Boolean = false,
val catchUpDays: Int = 0,
+ val catchUpSource: String? = null,
val providerId: Long = 0,
val currentProgram: Program? = null,
val nextProgram: Program? = null,
diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
index 54a2b3ce..14939dc0 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
@@ -15,4 +15,5 @@ interface ProviderRepository {
suspend fun loginXtream(serverUrl: String, username: String, password: String, name: String, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>
suspend fun validateM3u(url: String, name: String, onProgress: ((String) -> Unit)? = null, id: Long? = null): Result<Provider>
suspend fun refreshProviderData(providerId: Long, onProgress: ((String) -> Unit)? = null): Result<Unit>
+ suspend fun buildCatchUpUrl(providerId: Long, streamId: Long, start: Long, end: Long): String?
}
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index 70fa9430..6b6c92f7 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -22,6 +22,7 @@ import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.StreamType
import com.streamvault.domain.model.VideoFormat
import dagger.hilt.android.qualifiers.ApplicationContext
+import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import okhttp3.OkHttpClient
import javax.inject.Inject
@@ -34,8 +35,10 @@ class Media3PlayerEngine @Inject constructor(
private val okHttpClient: OkHttpClient
) : PlayerEngine {
+ private val scope = CoroutineScope(Dispatchers.Main + SupervisorJob())
private var exoPlayer: ExoPlayer? = null
private var currentDecoderMode: DecoderMode = DecoderMode.AUTO
+ private var pollingJob: Job? = null
private val _playbackState = MutableStateFlow(PlaybackState.IDLE)
override val playbackState: StateFlow<PlaybackState> = _playbackState.asStateFlow()
@@ -55,6 +58,12 @@ class Media3PlayerEngine @Inject constructor(
private val _error = MutableSharedFlow<PlayerError?>(replay = 1)
override val error: Flow<PlayerError?> = _error.asSharedFlow()
+ private val _availableAudioTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
+ override val availableAudioTracks: StateFlow<List<PlayerTrack>> = _availableAudioTracks.asStateFlow()
+
+ private val _availableSubtitleTracks = MutableStateFlow<List<PlayerTrack>>(emptyList())
+ override val availableSubtitleTracks: StateFlow<List<PlayerTrack>> = _availableSubtitleTracks.asStateFlow()
+
private fun getOrCreatePlayer(): ExoPlayer {
return exoPlayer ?: createPlayer().also { exoPlayer = it }
}
@@ -86,6 +95,11 @@ class Media3PlayerEngine @Inject constructor(
override fun onIsPlayingChanged(playing: Boolean) {
_isPlaying.value = playing
+ if (playing) {
+ startPolling()
+ } else {
+ stopPolling()
+ }
}
override fun onVideoSizeChanged(videoSize: androidx.media3.common.VideoSize) {
@@ -110,6 +124,43 @@ class Media3PlayerEngine @Inject constructor(
) {
_currentPosition.value = newPosition.positionMs
}
+
+ override fun onTracksChanged(tracks: androidx.media3.common.Tracks) {
+ val audioTracks = mutableListOf<PlayerTrack>()
+ val subtitleTracks = mutableListOf<PlayerTrack>()
+
+ for (group in tracks.groups) {
+ val type = group.mediaTrackGroup.type
+ val isAudio = type == C.TRACK_TYPE_AUDIO
+ val isText = type == C.TRACK_TYPE_TEXT
+
+ if (isAudio || isText) {
+ for (i in 0 until group.length) {
+ val format = group.mediaTrackGroup.getFormat(i)
+ val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$i"
+ val name = format.label ?: format.language ?: "Track ${i + 1}"
+ val isSelected = group.isTrackSelected(i)
+
+ val track = PlayerTrack(
+ id = id,
+ name = name,
+ language = format.language,
+ type = if (isAudio) TrackType.AUDIO else TrackType.TEXT,
+ isSelected = isSelected
+ )
+
+ if (isAudio && group.isTrackSupported(i, false)) {
+ audioTracks.add(track)
+ } else if (isText && group.isTrackSupported(i, false)) {
+ subtitleTracks.add(track)
+ }
+ }
+ }
+ }
+
+ _availableAudioTracks.value = audioTracks
+ _availableSubtitleTracks.value = subtitleTracks
+ }
})
}
}
@@ -223,12 +274,101 @@ class Media3PlayerEngine @Inject constructor(
exoPlayer?.volume = volume.coerceIn(0f, 1f)
}
+ override fun selectAudioTrack(trackId: String) {
+ exoPlayer?.let { player ->
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_AUDIO, false)
+ .build()
+
+ val tracks = player.currentTracks
+ for (group in tracks.groups) {
+ if (group.mediaTrackGroup.type == C.TRACK_TYPE_AUDIO) {
+ for (i in 0 until group.length) {
+ val format = group.mediaTrackGroup.getFormat(i)
+ val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$i"
+ if (id == trackId) {
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setOverrideForType(
+ androidx.media3.common.TrackSelectionOverride(
+ group.mediaTrackGroup,
+ listOf(i)
+ )
+ )
+ .build()
+ return
+ }
+ }
+ }
+ }
+ }
+ }
+
+ override fun selectSubtitleTrack(trackId: String?) {
+ exoPlayer?.let { player ->
+ if (trackId == null) {
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, true)
+ .clearOverridesOfType(C.TRACK_TYPE_TEXT)
+ .build()
+ } else {
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setTrackTypeDisabled(C.TRACK_TYPE_TEXT, false)
+ .build()
+
+ val tracks = player.currentTracks
+ for (group in tracks.groups) {
+ if (group.mediaTrackGroup.type == C.TRACK_TYPE_TEXT) {
+ for (i in 0 until group.length) {
+ val format = group.mediaTrackGroup.getFormat(i)
+ val id = format.id ?: "${group.mediaTrackGroup.hashCode()}_$i"
+ if (id == trackId) {
+ player.trackSelectionParameters = player.trackSelectionParameters
+ .buildUpon()
+ .setOverrideForType(
+ androidx.media3.common.TrackSelectionOverride(
+ group.mediaTrackGroup,
+ listOf(i)
+ )
+ )
+ .build()
+ return
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
override fun release() {
+ stopPolling()
exoPlayer?.release()
exoPlayer = null
_playbackState.value = PlaybackState.IDLE
_isPlaying.value = false
}
+ private fun startPolling() {
+ pollingJob?.cancel()
+ pollingJob = scope.launch {
+ while (isActive) {
+ exoPlayer?.let { player ->
+ _currentPosition.value = player.currentPosition
+ _duration.value = player.duration.coerceAtLeast(0L)
+ }
+ delay(500) // Poll every 500ms for smooth UI
+ }
+ }
+ }
+
+ private fun stopPolling() {
+ pollingJob?.cancel()
+ pollingJob = null
+ }
+
override fun getPlayerView(): Any? = exoPlayer
}
diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
index 3d72f947..4c333f25 100644
--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
@@ -18,6 +18,10 @@ interface PlayerEngine {
val videoFormat: StateFlow<VideoFormat>
val error: Flow<PlayerError?>
+ // Tracks
+ val availableAudioTracks: StateFlow<List<PlayerTrack>>
+ val availableSubtitleTracks: StateFlow<List<PlayerTrack>>
+
fun prepare(streamInfo: StreamInfo)
fun play()
fun pause()
@@ -27,6 +31,8 @@ interface PlayerEngine {
fun seekBackward(ms: Long = 10_000)
fun setDecoderMode(mode: DecoderMode)
fun setVolume(volume: Float)
+ fun selectAudioTrack(trackId: String)
+ fun selectSubtitleTrack(trackId: String?) // null to disable subtitles
fun release()
/** Returns the underlying player view for Compose embedding */
diff --git a/player/src/main/java/com/streamvault/player/PlayerTrack.kt b/player/src/main/java/com/streamvault/player/PlayerTrack.kt
new file mode 100644
index 00000000..d94c0aa0
--- /dev/null
+++ b/player/src/main/java/com/streamvault/player/PlayerTrack.kt
@@ -0,0 +1,15 @@
+package com.streamvault.player
+
+data class PlayerTrack(
+ val id: String,
+ val name: String,
+ val language: String?,
+ val type: TrackType,
+ val isSelected: Boolean
+)
+
+enum class TrackType {
+ AUDIO,
+ TEXT, // Subtitles
+ VIDEO
+}