StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Phase 1: Architecture Overhaul and Parser Tests
Davidona07331d3b2121
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex 5956c83f..18524fe8 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -24,7 +24,8 @@ object DatabaseModule {"streamvault.db").addMigrations(StreamVaultDatabase.MIGRATION_2_3)- .fallbackToDestructiveMigration()+ // NOTE: fallbackToDestructiveMigration() intentionally removed.+ // All future schema changes MUST add a corresponding Migration in StreamVaultDatabase..build()@Provides fun provideProviderDao(db: StreamVaultDatabase): ProviderDao = db.providerDao()diff --git a/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt b/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.ktindex 1ca35aa7..d0e03ec7 100644--- a/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/TopNavBar.kt@@ -25,8 +25,8 @@ fun TopNavBar(NavTab("Live TV", Routes.HOME, "πΊ"),NavTab("Movies", Routes.MOVIES, "π¬"),NavTab("Series", Routes.SERIES, "πΊ"),- NavTab("Search", Routes.SEARCH, "π"),- NavTab("Favorites", Routes.FAVORITES, "β"),+ // Search and Favorites are accessible from within the Live TV screen;+ // they don't need top-level nav slots.NavTab("Settings", Routes.SETTINGS, "βοΈ"))diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.ktindex 7b48c90f..b79bb6b0 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesScreen.kt@@ -15,138 +15,10 @@ import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.input.key.*import androidx.compose.ui.unit.dpimport androidx.hilt.navigation.compose.hiltViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.viewModelScopeimport androidx.tv.material3.*import com.streamvault.app.ui.components.TopNavBarimport com.streamvault.app.ui.theme.*import com.streamvault.domain.model.ContentType-import com.streamvault.domain.model.Favorite-import com.streamvault.domain.model.VirtualGroup-import com.streamvault.domain.repository.ChannelRepository-import com.streamvault.domain.repository.FavoriteRepository-import com.streamvault.domain.repository.MovieRepository-import com.streamvault.domain.repository.SeriesRepository-import dagger.hilt.android.lifecycle.HiltViewModel-import kotlinx.coroutines.flow.*-import kotlinx.coroutines.launch-import javax.inject.Inject--data class FavoriteUiModel(- val favorite: Favorite,- val title: String,- val subtitle: String? = null,- val streamUrl: String = ""-)--@HiltViewModel-class FavoritesViewModel @Inject constructor(- private val favoriteRepository: FavoriteRepository,- private val channelRepository: ChannelRepository,- private val movieRepository: MovieRepository,- private val seriesRepository: SeriesRepository-) : ViewModel() {-- private val _uiState = MutableStateFlow(FavoritesUiState())- val uiState: StateFlow<FavoritesUiState> = _uiState.asStateFlow()-- init {- viewModelScope.launch {- favoriteRepository.getFavorites(null).collect { favorites ->- val uiModels = favorites.mapNotNull { fav ->- // This is simple N+1 fetching for now.- // Optimization: Bulk fetch or join in DB in future iterations.- try {- when (fav.contentType) {- ContentType.LIVE -> {- val channel = channelRepository.getChannel(fav.contentId)- if (channel != null) {- FavoriteUiModel(- favorite = fav,- title = channel.name,- subtitle = "Channel ${channel.number}",- streamUrl = channel.streamUrl- )- } else null- }- ContentType.MOVIE -> {- val movie = movieRepository.getMovie(fav.contentId)- if (movie != null) {- FavoriteUiModel(- favorite = fav,- title = movie.name,- subtitle = "Movie",- streamUrl = movie.streamUrl- )- } else null- }- ContentType.SERIES -> {- val series = seriesRepository.getSeriesById(fav.contentId)- if (series != null) {- FavoriteUiModel(- favorite = fav,- title = series.name,- subtitle = "Series",- streamUrl = "" // Series doesn't have a single stream URL- )- } else null- }- }- } catch (e: Exception) {- null- }- }- _uiState.update { it.copy(favorites = uiModels, isLoading = false) }- }- }- viewModelScope.launch {- favoriteRepository.getGroups().collect { groups ->- _uiState.update { it.copy(groups = groups) }- }- }- }-- fun enterReorderMode(item: FavoriteUiModel) {- _uiState.update { it.copy(isReorderMode = true, reorderItem = item.favorite) }- }-- fun exitReorderMode() {- _uiState.update { it.copy(isReorderMode = false, reorderItem = null) }- }-- fun moveItem(direction: Int) {- val currentList = _uiState.value.favorites.toMutableList()- val reorderItem = _uiState.value.reorderItem ?: return- val index = currentList.indexOfFirst { it.favorite.id == reorderItem.id }- if (index == -1) return-- val newIndex = index + direction- if (newIndex in 0 until currentList.size) {- java.util.Collections.swap(currentList, index, newIndex)- _uiState.update { it.copy(favorites = currentList) }- }- }-- fun saveReorder() {- val currentModels = _uiState.value.favorites- // We need to pass just the Favorites, with updated positions implicitly defined by list order?- // Actually Repository expects a list and updates positions based on index.- val updatedFavorites = currentModels.map { it.favorite }- viewModelScope.launch {- favoriteRepository.reorderFavorites(updatedFavorites)- exitReorderMode()- }- }-}--data class FavoritesUiState(- val favorites: List<FavoriteUiModel> = emptyList(),- val groups: List<VirtualGroup> = emptyList(),- val isLoading: Boolean = true,- val isReorderMode: Boolean = false,- val reorderItem: Favorite? = null-)-@Composablefun FavoritesScreen(onItemClick: (streamUrl: String, title: String) -> Unit,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.ktnew file mode 100644index 00000000..5e44dbd4--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/favorites/FavoritesViewModel.kt@@ -0,0 +1,126 @@+package com.streamvault.app.ui.screens.favorites++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Favorite+import com.streamvault.domain.model.VirtualGroup+import com.streamvault.domain.repository.ChannelRepository+import com.streamvault.domain.repository.FavoriteRepository+import com.streamvault.domain.repository.MovieRepository+import com.streamvault.domain.repository.SeriesRepository+import dagger.hilt.android.lifecycle.HiltViewModel+import kotlinx.coroutines.flow.*+import kotlinx.coroutines.launch+import javax.inject.Inject++data class FavoriteUiModel(+ val favorite: Favorite,+ val title: String,+ val subtitle: String? = null,+ val streamUrl: String = ""+)++@HiltViewModel+class FavoritesViewModel @Inject constructor(+ private val favoriteRepository: FavoriteRepository,+ private val channelRepository: ChannelRepository,+ private val movieRepository: MovieRepository,+ private val seriesRepository: SeriesRepository+) : ViewModel() {++ private val _uiState = MutableStateFlow(FavoritesUiState())+ val uiState: StateFlow<FavoritesUiState> = _uiState.asStateFlow()++ init {+ viewModelScope.launch {+ favoriteRepository.getFavorites(null).collect { favorites ->+ val uiModels = favorites.mapNotNull { fav ->+ try {+ when (fav.contentType) {+ ContentType.LIVE -> {+ val channel = channelRepository.getChannel(fav.contentId)+ if (channel != null) {+ FavoriteUiModel(+ favorite = fav,+ title = channel.name,+ subtitle = "Channel ${channel.number}",+ streamUrl = channel.streamUrl+ )+ } else null+ }+ ContentType.MOVIE -> {+ val movie = movieRepository.getMovie(fav.contentId)+ if (movie != null) {+ FavoriteUiModel(+ favorite = fav,+ title = movie.name,+ subtitle = "Movie",+ streamUrl = movie.streamUrl+ )+ } else null+ }+ ContentType.SERIES -> {+ val series = seriesRepository.getSeriesById(fav.contentId)+ if (series != null) {+ FavoriteUiModel(+ favorite = fav,+ title = series.name,+ subtitle = "Series",+ streamUrl = "" // Series doesn't have a single stream URL+ )+ } else null+ }+ }+ } catch (e: Exception) {+ null+ }+ }+ _uiState.update { it.copy(favorites = uiModels, isLoading = false) }+ }+ }+ viewModelScope.launch {+ favoriteRepository.getGroups().collect { groups ->+ _uiState.update { it.copy(groups = groups) }+ }+ }+ }++ fun enterReorderMode(item: FavoriteUiModel) {+ _uiState.update { it.copy(isReorderMode = true, reorderItem = item.favorite) }+ }++ fun exitReorderMode() {+ _uiState.update { it.copy(isReorderMode = false, reorderItem = null) }+ }++ fun moveItem(direction: Int) {+ val currentList = _uiState.value.favorites.toMutableList()+ val reorderItem = _uiState.value.reorderItem ?: return+ val index = currentList.indexOfFirst { it.favorite.id == reorderItem.id }+ if (index == -1) return++ val newIndex = index + direction+ if (newIndex in 0 until currentList.size) {+ java.util.Collections.swap(currentList, index, newIndex)+ _uiState.update { it.copy(favorites = currentList) }+ }+ }++ fun saveReorder() {+ val currentModels = _uiState.value.favorites+ val updatedFavorites = currentModels.map { it.favorite }+ viewModelScope.launch {+ favoriteRepository.reorderFavorites(updatedFavorites)+ exitReorderMode()+ }+ }+}++data class FavoritesUiState(+ val favorites: List<FavoriteUiModel> = emptyList(),+ val groups: List<VirtualGroup> = emptyList(),+ val isLoading: Boolean = true,+ val isReorderMode: Boolean = false,+ val reorderItem: Favorite? = null+)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.ktindex e2878e40..4fa8fe1e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeScreen.kt@@ -1,7 +1,6 @@package com.streamvault.app.ui.screens.homeimport androidx.compose.material3.ExperimentalMaterial3Api-import androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.LazyColumn@@ -25,8 +24,6 @@ import androidx.compose.material.icons.Iconsimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.unit.dpimport androidx.hilt.navigation.compose.hiltViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.viewModelScopeimport androidx.tv.material3.*import androidx.compose.material3.SnackbarHostimport androidx.compose.material3.SnackbarHostState@@ -40,468 +37,13 @@ import com.streamvault.app.ui.theme.*import com.streamvault.domain.model.Categoryimport com.streamvault.domain.model.Channelimport com.streamvault.domain.model.Provider-import com.streamvault.domain.repository.ChannelRepository-import com.streamvault.data.preferences.PreferencesRepository-import kotlinx.coroutines.flow.combine-import kotlinx.coroutines.flow.firstOrNull-import com.streamvault.domain.repository.EpgRepository-import com.streamvault.domain.repository.ProviderRepository-import kotlinx.coroutines.Job-import dagger.hilt.android.lifecycle.HiltViewModel-import kotlinx.coroutines.flow.*import kotlinx.coroutines.launch-import javax.inject.Inject-import com.streamvault.domain.usecase.GetCustomCategories----@HiltViewModel-class HomeViewModel @Inject constructor(- private val providerRepository: ProviderRepository,- private val channelRepository: ChannelRepository,- private val categoryRepository: com.streamvault.domain.repository.CategoryRepository,- private val favoriteRepository: com.streamvault.domain.repository.FavoriteRepository,- private val preferencesRepository: PreferencesRepository,- private val epgRepository: EpgRepository,- private val getCustomCategories: com.streamvault.domain.usecase.GetCustomCategories,- private val parentalControlManager: com.streamvault.domain.manager.ParentalControlManager-) : ViewModel() {-- private val _uiState = MutableStateFlow(HomeUiState())- val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()-- // Cache channels locally for filtering- // Reactive state for channels and favorites- private val _localChannels = MutableStateFlow<List<Channel>>(emptyList())- private var epgJob: Job? = null--- private var loadChannelsJob: Job? = null-- init {- loadAllProviders()- viewModelScope.launch {- providerRepository.getActiveProvider()- .filterNotNull()- .collectLatest { provider ->- _uiState.update { it.copy(provider = provider) }- loadCategoriesAndChannels(provider.id)- preferencesRepository.setLastActiveProviderId(provider.id)- }- }-- // Observe channels, search query, and favorites to update UI- viewModelScope.launch {- combine(- _localChannels,- _uiState.map { it.channelSearchQuery }.distinctUntilChanged(),- favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE)- ) { channels, query, favorites ->- Triple(channels, query, favorites)- }.collectLatest { (channels, query, favorites) ->- val favoriteIds = favorites.map { it.contentId }.toSet()-- // 1. Filter- val filtered = if (query.isBlank()) {- channels- } else {- channels.filter { it.name.contains(query, ignoreCase = true) }- }-- // 2. Mark Favorites- val markedChannels = filtered.map { channel ->- if (favoriteIds.contains(channel.id)) channel.copy(isFavorite = true)- else channel.copy(isFavorite = false)- }-- _uiState.update { it.copy(filteredChannels = markedChannels, isLoading = false) }-- // 3. Fetch EPG for visible channels- fetchEpgForChannels(markedChannels)- }- }-- // Observe Parental Control Level- viewModelScope.launch {- preferencesRepository.parentalControlLevel.collectLatest { level ->- _uiState.update { it.copy(parentalControlLevel = level) }- }- }- }-- private fun loadAllProviders() {- viewModelScope.launch {- providerRepository.getProviders().collect { providers ->- _uiState.update { it.copy(allProviders = providers) }- }- }- }- fun switchProvider(providerId: Long) {- viewModelScope.launch {- providerRepository.setActiveProvider(providerId)- }- }- private var categoriesJob: Job? = null-- private fun loadCategoriesAndChannels(providerId: Long) {- categoriesJob?.cancel()- categoriesJob = viewModelScope.launch {- // Combine provider categories, custom categories, and default category preference- combine(- channelRepository.getCategories(providerId),- getCustomCategories(),- preferencesRepository.defaultCategoryId- ) { providerCats, customCats, defaultId ->- Triple(customCats + providerCats, defaultId, Unit)- }.collect { (categories, defaultId, _) ->- _uiState.update { it.copy(categories = categories) }-- val currentSelected = _uiState.value.selectedCategory-- if (currentSelected == null && categories.isNotEmpty()) {- // Initial selection logic:- // 1. Default Category (if set and exists)- // 2. Favorites (id -999, if exists)- // 3. First available category- val defaultCat = defaultId?.let { id -> categories.find { it.id == id } }- val favoritesCat = categories.find { it.id == -999L }-- if (defaultCat != null) {- selectCategory(defaultCat)- } else if (favoritesCat != null) {- selectCategory(favoritesCat)- } else {- selectCategory(categories.first())- }- } else if (currentSelected != null) {- // Try to find the currently selected category in the new list to preserve selection- val reselectedCat = categories.find { it.id == currentSelected.id }-- if (reselectedCat != null) {- // Category still exists, update state with new object just in case (name change etc)- if (reselectedCat != currentSelected) {- _uiState.update { it.copy(selectedCategory = reselectedCat) }- }- // Refresh content. Do NOT set isLoading=true here to avoid flickering.- loadChannelsForCategory(reselectedCat)- } else {- // Category disappeared (deleted group?), fallback to default logic- val defaultCat = defaultId?.let { id -> categories.find { it.id == id } }- val favoritesCat = categories.find { it.id == -999L }-- if (defaultCat != null) {- selectCategory(defaultCat)- } else if (favoritesCat != null) {- selectCategory(favoritesCat)- } else if (categories.isNotEmpty()) {- selectCategory(categories.first())- }- }- }- }- }- }-- fun selectCategory(category: Category) {- // Fix for Bug 1: Prevent double-click from reloading/clearing if already selected- if (_uiState.value.selectedCategory?.id == category.id) return-- // Ephemeral Unlock: switching category re-locks everything- parentalControlManager.clearUnlockedCategories()-- _uiState.update { it.copy(selectedCategory = category, isLoading = true) }- loadChannelsForCategory(category)- }-- private fun loadChannelsForCategory(category: Category) {- // Fix for Bug 1: Cancel previous job to prevent race conditions- loadChannelsJob?.cancel()-- loadChannelsJob = viewModelScope.launch {- val providerId = _uiState.value.provider?.id ?: return@launch-- val channelsFlow = if (category.isVirtual) {- if (category.id == -999L) {- // Global Favorites- favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE)- .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }- .flatMapLatest { ids ->- if (ids.isEmpty()) flowOf(emptyList())- else channelRepository.getChannelsByIds(ids).map { unsorted ->- val map = unsorted.associateBy { it.id }- ids.mapNotNull { map[it] }- }- }- } else {- // Custom Group- val groupId = -category.id- favoriteRepository.getFavoritesByGroup(groupId)- .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }- .flatMapLatest { ids ->- if (ids.isEmpty()) flowOf(emptyList())- else channelRepository.getChannelsByIds(ids).map { unsorted ->- val map = unsorted.associateBy { it.id }- ids.mapNotNull { map[it] }- }- }- }- } else {- // Regular Category- channelRepository.getChannelsByCategory(providerId, category.id)- }-- channelsFlow.collect { channels ->- _uiState.update { it.copy(hasChannels = channels.isNotEmpty()) }- _localChannels.value = channels- }- }- }-- fun updateCategorySearchQuery(query: String) {- _uiState.update { it.copy(categorySearchQuery = query) }- // We calculate filtered categories in UI or here?- // Better to expose filtered list or filter in UI.- // For performance, let's filter in UI for now or add a derived state.- }-- fun updateChannelSearchQuery(query: String) {- _uiState.update { it.copy(channelSearchQuery = query) }- // updateFilteredChannels handled by flow- }-- private fun fetchEpgForChannels(channels: List<Channel>) {- epgJob?.cancel()- val epgIds = channels.mapNotNull { it.epgChannelId }.distinct()-- epgJob = viewModelScope.launch {- // Get Favorites to mark channels (No need here, already marked)-- // Fetch EPG- val programs = if (epgIds.isNotEmpty()) {- epgRepository.getNowPlayingForChannels(epgIds).firstOrNull() ?: emptyList()- } else {- emptyList()- }- val programMap = programs.associateBy { it.channelId }-- val enrichedChannels = channels.map { channel ->- val program = channel.epgChannelId?.let { programMap[it] }- if (program != null) channel.copy(currentProgram = program) else channel- }-- _uiState.update { it.copy(filteredChannels = enrichedChannels) }- }- }-- fun addFavorite(channel: Channel) {- viewModelScope.launch {- favoriteRepository.addFavorite(- contentId = channel.id,- contentType = com.streamvault.domain.model.ContentType.LIVE,- groupId = null // Global Favorites- )- onDismissDialog()- _uiState.update { it.copy(userMessage = "Added ${channel.name} to Favorites") }- }- }-- fun removeFavorite(channel: Channel) {- viewModelScope.launch {- favoriteRepository.removeFavorite(- contentId = channel.id,- contentType = com.streamvault.domain.model.ContentType.LIVE,- groupId = null // Global Favorites- )- onDismissDialog()- _uiState.update { it.copy(userMessage = "Removed ${channel.name} from Favorites") }- }- }-- fun createCustomGroup(name: String) {- val trimmed = name.trim()- if (trimmed.equals("Favorites", ignoreCase = true)) {- _uiState.update { it.copy(userMessage = "Cannot create group named 'Favorites'") }- return- }- if (_uiState.value.categories.any { it.name.equals(trimmed, ignoreCase = true) }) {- _uiState.update { it.copy(userMessage = "Group '$trimmed' already exists") }- return- }-- viewModelScope.launch {- favoriteRepository.createGroup(trimmed)- _uiState.update { it.copy(userMessage = "Group '$trimmed' created") }- }- }-- fun requestDeleteGroup(category: Category) {- if (!category.isVirtual || category.id == -999L) return- _uiState.update { it.copy(showDeleteGroupDialog = true, groupToDelete = category) }- }-- fun cancelDeleteGroup() {- _uiState.update { it.copy(showDeleteGroupDialog = false, groupToDelete = null) }- }-- fun confirmDeleteGroup() {- val category = _uiState.value.groupToDelete ?: return- viewModelScope.launch {- favoriteRepository.deleteGroup(-category.id)- _uiState.update { it.copy(- showDeleteGroupDialog = false,- groupToDelete = null,- userMessage = "Group '${category.name}' deleted"- ) }- }- }-- fun addToGroup(channel: Channel, category: Category) {- if (!category.isVirtual || category.id == -999L) return- viewModelScope.launch {- val groupId = -category.id- favoriteRepository.addFavorite(- contentId = channel.id,- contentType = com.streamvault.domain.model.ContentType.LIVE,- groupId = groupId- )- onDismissDialog()- _uiState.update { it.copy(userMessage = "Added ${channel.name} to ${category.name}") }- }- }-- fun removeFromGroup(channel: Channel, category: Category) {- if (!category.isVirtual || category.id == -999L) return- viewModelScope.launch {- val groupId = -category.id- favoriteRepository.removeFavorite(- contentId = channel.id,- contentType = com.streamvault.domain.model.ContentType.LIVE,- groupId = groupId- )- onDismissDialog()- _uiState.update { it.copy(userMessage = "Removed ${channel.name} from ${category.name}") }- }- }-- fun moveChannel(channel: Channel, direction: Int) {- // direction: -1 for UP/Left, 1 for DOWN/Right- val currentCategory = _uiState.value.selectedCategory ?: return- if (!currentCategory.isVirtual) return // Only for Favorites/Custom Groups-- val currentList = _localChannels.value.toMutableList()- val index = currentList.indexOfFirst { it.id == channel.id }- if (index == -1) return-- val newIndex = index + direction- if (newIndex < 0 || newIndex >= currentList.size) return-- // Optimistic UI update- java.util.Collections.swap(currentList, index, newIndex)- _localChannels.value = currentList-- // Persist change- viewModelScope.launch {- val groupId = if (currentCategory.id == -999L) null else -currentCategory.id-- // We need to fetch current favorites to get their IDs and other metadata- val favoritesCallback = if (groupId == null) {- favoriteRepository.getFavorites(com.streamvault.domain.model.ContentType.LIVE)- } else {- favoriteRepository.getFavoritesByGroup(groupId)- }-- val favorites = favoritesCallback.first()- val favoriteMap = favorites.associateBy { it.contentId }-- // Reconstruct the ordered list of favorites based on the NEW channel order- val reorderedFavorites = currentList.mapNotNull { ch ->- favoriteMap[ch.id]- }.mapIndexed { i, fav ->- fav.copy(position = i)- }-- favoriteRepository.reorderFavorites(reorderedFavorites)- }- }-- fun userMessageShown() {- _uiState.update { it.copy(userMessage = null) }- }-- fun refreshData() {- val provider = _uiState.value.provider ?: return- viewModelScope.launch {- _uiState.update { it.copy(isLoading = true) }- providerRepository.refreshProviderData(provider.id)- _uiState.update { it.copy(isLoading = false) }- }- }- fun onShowDialog(channel: Channel) {- _uiState.update { it.copy(showDialog = true, selectedChannelForDialog = channel) }- viewModelScope.launch {- val memberships = favoriteRepository.getGroupMemberships(channel.id, com.streamvault.domain.model.ContentType.LIVE)- _uiState.update { it.copy(dialogGroupMemberships = memberships) }- }- }-- fun onDismissDialog() {- _uiState.update { it.copy(showDialog = false, selectedChannelForDialog = null) }- }-- suspend fun verifyPin(pin: String): Boolean {- val storedPin = preferencesRepository.parentalPin.firstOrNull() ?: "0000"- return pin == storedPin- }-- fun unlockCategory(category: Category) {- parentalControlManager.unlockCategory(category.id)- }-- fun setDefaultCategory(category: Category) {- viewModelScope.launch {- preferencesRepository.setDefaultCategory(category.id)- _uiState.update { it.copy(userMessage = "Set '${category.name}' as default") }- }- }+// ββ Screen βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ- fun toggleCategoryLock(category: Category) {- viewModelScope.launch {- val newStatus = !category.isUserProtected- categoryRepository.setCategoryProtection(category.id, newStatus)- val msg = if (newStatus) "Locked '${category.name}'" else "Unlocked '${category.name}'"- _uiState.update { it.copy(userMessage = msg) }- }- }- fun showCategoryOptions(category: Category) {- _uiState.update { it.copy(selectedCategoryForOptions = category) }- }- fun dismissCategoryOptions() {- _uiState.update { it.copy(selectedCategoryForOptions = null) }- }-}-data class HomeUiState(- val provider: Provider? = null,- val allProviders: List<Provider> = emptyList(),- val categories: List<Category> = emptyList(),- val selectedCategory: Category? = null,- val filteredChannels: List<Channel> = emptyList(),- val hasChannels: Boolean = false,- val isLoading: Boolean = true,- val categorySearchQuery: String = "",- val channelSearchQuery: String = "",- val showDialog: Boolean = false,- val selectedChannelForDialog: Channel? = null,- val dialogGroupMemberships: List<Long> = emptyList(),- val userMessage: String? = null,- val showDeleteGroupDialog: Boolean = false,- val groupToDelete: Category? = null,- val parentalControlLevel: Int = 0,- val selectedCategoryForOptions: Category? = null-)// ββ Screen βββββββββββββββββββββββββββββββββββββββββββββββββββββββββdiff --git a/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.ktnew file mode 100644index 00000000..d812b5b2--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/home/HomeViewModel.kt@@ -0,0 +1,424 @@+package com.streamvault.app.ui.screens.home++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.manager.ParentalControlManager+import com.streamvault.domain.model.Category+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.Provider+import com.streamvault.domain.repository.CategoryRepository+import com.streamvault.domain.repository.ChannelRepository+import com.streamvault.domain.repository.EpgRepository+import com.streamvault.domain.repository.FavoriteRepository+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.usecase.GetCustomCategories+import dagger.hilt.android.lifecycle.HiltViewModel+import kotlinx.coroutines.Job+import kotlinx.coroutines.flow.*+import kotlinx.coroutines.launch+import javax.inject.Inject++@HiltViewModel+class HomeViewModel @Inject constructor(+ private val providerRepository: ProviderRepository,+ private val channelRepository: ChannelRepository,+ private val categoryRepository: CategoryRepository,+ private val favoriteRepository: FavoriteRepository,+ private val preferencesRepository: PreferencesRepository,+ private val epgRepository: EpgRepository,+ private val getCustomCategories: GetCustomCategories,+ private val parentalControlManager: ParentalControlManager+) : ViewModel() {++ private val _uiState = MutableStateFlow(HomeUiState())+ val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()++ private val _localChannels = MutableStateFlow<List<Channel>>(emptyList())+ private var epgJob: Job? = null+ private var loadChannelsJob: Job? = null+ private var categoriesJob: Job? = null++ init {+ loadAllProviders()+ viewModelScope.launch {+ providerRepository.getActiveProvider()+ .filterNotNull()+ .collectLatest { provider ->+ _uiState.update { it.copy(provider = provider) }+ loadCategoriesAndChannels(provider.id)+ preferencesRepository.setLastActiveProviderId(provider.id)+ }+ }++ // Observe channels, search query, and favorites to update UI+ viewModelScope.launch {+ combine(+ _localChannels,+ _uiState.map { it.channelSearchQuery }.distinctUntilChanged(),+ favoriteRepository.getFavorites(ContentType.LIVE)+ ) { channels, query, favorites ->+ Triple(channels, query, favorites)+ }.collectLatest { (channels, query, favorites) ->+ val favoriteIds = favorites.map { it.contentId }.toSet()++ val filtered = if (query.isBlank()) channels+ else channels.filter { it.name.contains(query, ignoreCase = true) }++ val markedChannels = filtered.map { channel ->+ if (favoriteIds.contains(channel.id)) channel.copy(isFavorite = true)+ else channel.copy(isFavorite = false)+ }++ _uiState.update { it.copy(filteredChannels = markedChannels, isLoading = false) }+ fetchEpgForChannels(markedChannels)+ }+ }++ viewModelScope.launch {+ preferencesRepository.parentalControlLevel.collectLatest { level ->+ _uiState.update { it.copy(parentalControlLevel = level) }+ }+ }+ }++ private fun loadAllProviders() {+ viewModelScope.launch {+ providerRepository.getProviders().collect { providers ->+ _uiState.update { it.copy(allProviders = providers) }+ }+ }+ }++ fun switchProvider(providerId: Long) {+ viewModelScope.launch {+ providerRepository.setActiveProvider(providerId)+ }+ }++ private fun loadCategoriesAndChannels(providerId: Long) {+ categoriesJob?.cancel()+ categoriesJob = viewModelScope.launch {+ combine(+ channelRepository.getCategories(providerId),+ getCustomCategories(),+ preferencesRepository.defaultCategoryId+ ) { providerCats, customCats, defaultId ->+ Triple(customCats + providerCats, defaultId, Unit)+ }.collect { (categories, defaultId, _) ->+ _uiState.update { it.copy(categories = categories) }++ val currentSelected = _uiState.value.selectedCategory++ if (currentSelected == null && categories.isNotEmpty()) {+ val defaultCat = defaultId?.let { id -> categories.find { it.id == id } }+ val favoritesCat = categories.find { it.id == -999L }++ if (defaultCat != null) selectCategory(defaultCat)+ else if (favoritesCat != null) selectCategory(favoritesCat)+ else selectCategory(categories.first())+ } else if (currentSelected != null) {+ val reselectedCat = categories.find { it.id == currentSelected.id }++ if (reselectedCat != null) {+ if (reselectedCat != currentSelected) {+ _uiState.update { it.copy(selectedCategory = reselectedCat) }+ }+ loadChannelsForCategory(reselectedCat)+ } else {+ val defaultCat = defaultId?.let { id -> categories.find { it.id == id } }+ val favoritesCat = categories.find { it.id == -999L }++ if (defaultCat != null) selectCategory(defaultCat)+ else if (favoritesCat != null) selectCategory(favoritesCat)+ else if (categories.isNotEmpty()) selectCategory(categories.first())+ }+ }+ }+ }+ }++ fun selectCategory(category: Category) {+ if (_uiState.value.selectedCategory?.id == category.id) return+ parentalControlManager.clearUnlockedCategories()+ _uiState.update { it.copy(selectedCategory = category, isLoading = true) }+ loadChannelsForCategory(category)+ }++ private fun loadChannelsForCategory(category: Category) {+ loadChannelsJob?.cancel()+ loadChannelsJob = viewModelScope.launch {+ val providerId = _uiState.value.provider?.id ?: return@launch++ val channelsFlow = if (category.isVirtual) {+ if (category.id == -999L) {+ // Global Favorites+ favoriteRepository.getFavorites(ContentType.LIVE)+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest { ids ->+ if (ids.isEmpty()) flowOf(emptyList())+ else channelRepository.getChannelsByIds(ids).map { unsorted ->+ val map = unsorted.associateBy { it.id }+ ids.mapNotNull { map[it] }+ }+ }+ } else {+ // Custom Group+ val groupId = -category.id+ favoriteRepository.getFavoritesByGroup(groupId)+ .map { favorites -> favorites.sortedBy { it.position }.map { it.contentId } }+ .flatMapLatest { ids ->+ if (ids.isEmpty()) flowOf(emptyList())+ else channelRepository.getChannelsByIds(ids).map { unsorted ->+ val map = unsorted.associateBy { it.id }+ ids.mapNotNull { map[it] }+ }+ }+ }+ } else {+ channelRepository.getChannelsByCategory(providerId, category.id)+ }++ channelsFlow.collect { channels ->+ _uiState.update { it.copy(hasChannels = channels.isNotEmpty()) }+ _localChannels.value = channels+ }+ }+ }++ fun updateCategorySearchQuery(query: String) {+ _uiState.update { it.copy(categorySearchQuery = query) }+ }++ fun updateChannelSearchQuery(query: String) {+ _uiState.update { it.copy(channelSearchQuery = query) }+ }++ private fun fetchEpgForChannels(channels: List<Channel>) {+ epgJob?.cancel()+ val epgIds = channels.mapNotNull { it.epgChannelId }.distinct()++ epgJob = viewModelScope.launch {+ val programs = if (epgIds.isNotEmpty()) {+ epgRepository.getNowPlayingForChannels(epgIds).firstOrNull() ?: emptyList()+ } else {+ emptyList()+ }+ val programMap = programs.associateBy { it.channelId }++ val enrichedChannels = channels.map { channel ->+ val program = channel.epgChannelId?.let { programMap[it] }+ if (program != null) channel.copy(currentProgram = program) else channel+ }++ _uiState.update { it.copy(filteredChannels = enrichedChannels) }+ }+ }++ fun addFavorite(channel: Channel) {+ viewModelScope.launch {+ favoriteRepository.addFavorite(+ contentId = channel.id,+ contentType = ContentType.LIVE,+ groupId = null+ )+ onDismissDialog()+ _uiState.update { it.copy(userMessage = "Added ${channel.name} to Favorites") }+ }+ }++ fun removeFavorite(channel: Channel) {+ viewModelScope.launch {+ favoriteRepository.removeFavorite(+ contentId = channel.id,+ contentType = ContentType.LIVE,+ groupId = null+ )+ onDismissDialog()+ _uiState.update { it.copy(userMessage = "Removed ${channel.name} from Favorites") }+ }+ }++ fun createCustomGroup(name: String) {+ val trimmed = name.trim()+ if (trimmed.equals("Favorites", ignoreCase = true)) {+ _uiState.update { it.copy(userMessage = "Cannot create group named 'Favorites'") }+ return+ }+ if (_uiState.value.categories.any { it.name.equals(trimmed, ignoreCase = true) }) {+ _uiState.update { it.copy(userMessage = "Group '$trimmed' already exists") }+ return+ }++ viewModelScope.launch {+ favoriteRepository.createGroup(trimmed)+ _uiState.update { it.copy(userMessage = "Group '$trimmed' created") }+ }+ }++ fun requestDeleteGroup(category: Category) {+ if (!category.isVirtual || category.id == -999L) return+ _uiState.update { it.copy(showDeleteGroupDialog = true, groupToDelete = category) }+ }++ fun cancelDeleteGroup() {+ _uiState.update { it.copy(showDeleteGroupDialog = false, groupToDelete = null) }+ }++ fun confirmDeleteGroup() {+ val category = _uiState.value.groupToDelete ?: return+ viewModelScope.launch {+ favoriteRepository.deleteGroup(-category.id)+ _uiState.update {+ it.copy(+ showDeleteGroupDialog = false,+ groupToDelete = null,+ userMessage = "Group '${category.name}' deleted"+ )+ }+ }+ }++ fun addToGroup(channel: Channel, category: Category) {+ if (!category.isVirtual || category.id == -999L) return+ viewModelScope.launch {+ val groupId = -category.id+ favoriteRepository.addFavorite(+ contentId = channel.id,+ contentType = ContentType.LIVE,+ groupId = groupId+ )+ onDismissDialog()+ _uiState.update { it.copy(userMessage = "Added ${channel.name} to ${category.name}") }+ }+ }++ fun removeFromGroup(channel: Channel, category: Category) {+ if (!category.isVirtual || category.id == -999L) return+ viewModelScope.launch {+ val groupId = -category.id+ favoriteRepository.removeFavorite(+ contentId = channel.id,+ contentType = ContentType.LIVE,+ groupId = groupId+ )+ onDismissDialog()+ _uiState.update { it.copy(userMessage = "Removed ${channel.name} from ${category.name}") }+ }+ }++ fun moveChannel(channel: Channel, direction: Int) {+ val currentCategory = _uiState.value.selectedCategory ?: return+ if (!currentCategory.isVirtual) return++ val currentList = _localChannels.value.toMutableList()+ val index = currentList.indexOfFirst { it.id == channel.id }+ if (index == -1) return++ val newIndex = index + direction+ if (newIndex < 0 || newIndex >= currentList.size) return++ java.util.Collections.swap(currentList, index, newIndex)+ _localChannels.value = currentList++ viewModelScope.launch {+ val groupId = if (currentCategory.id == -999L) null else -currentCategory.id++ val favoritesFlow = if (groupId == null) {+ favoriteRepository.getFavorites(ContentType.LIVE)+ } else {+ favoriteRepository.getFavoritesByGroup(groupId)+ }++ val favorites = favoritesFlow.first()+ val favoriteMap = favorites.associateBy { it.contentId }++ val reorderedFavorites = currentList.mapNotNull { ch ->+ favoriteMap[ch.id]+ }.mapIndexed { i, fav ->+ fav.copy(position = i)+ }++ favoriteRepository.reorderFavorites(reorderedFavorites)+ }+ }++ fun userMessageShown() {+ _uiState.update { it.copy(userMessage = null) }+ }++ fun refreshData() {+ val provider = _uiState.value.provider ?: return+ viewModelScope.launch {+ _uiState.update { it.copy(isLoading = true) }+ providerRepository.refreshProviderData(provider.id)+ _uiState.update { it.copy(isLoading = false) }+ }+ }++ fun onShowDialog(channel: Channel) {+ _uiState.update { it.copy(showDialog = true, selectedChannelForDialog = channel) }+ viewModelScope.launch {+ val memberships = favoriteRepository.getGroupMemberships(channel.id, ContentType.LIVE)+ _uiState.update { it.copy(dialogGroupMemberships = memberships) }+ }+ }++ fun onDismissDialog() {+ _uiState.update { it.copy(showDialog = false, selectedChannelForDialog = null) }+ }++ suspend fun verifyPin(pin: String): Boolean {+ val storedPin = preferencesRepository.parentalPin.firstOrNull() ?: "0000"+ return pin == storedPin+ }++ fun unlockCategory(category: Category) {+ parentalControlManager.unlockCategory(category.id)+ }++ fun setDefaultCategory(category: Category) {+ viewModelScope.launch {+ preferencesRepository.setDefaultCategory(category.id)+ _uiState.update { it.copy(userMessage = "Set '${category.name}' as default") }+ }+ }++ fun toggleCategoryLock(category: Category) {+ viewModelScope.launch {+ val newStatus = !category.isUserProtected+ categoryRepository.setCategoryProtection(category.id, newStatus)+ val msg = if (newStatus) "Locked '${category.name}'" else "Unlocked '${category.name}'"+ _uiState.update { it.copy(userMessage = msg) }+ }+ }++ fun showCategoryOptions(category: Category) {+ _uiState.update { it.copy(selectedCategoryForOptions = category) }+ }++ fun dismissCategoryOptions() {+ _uiState.update { it.copy(selectedCategoryForOptions = null) }+ }+}++data class HomeUiState(+ val provider: Provider? = null,+ val allProviders: List<Provider> = emptyList(),+ val categories: List<Category> = emptyList(),+ val selectedCategory: Category? = null,+ val filteredChannels: List<Channel> = emptyList(),+ val hasChannels: Boolean = false,+ val isLoading: Boolean = true,+ val categorySearchQuery: String = "",+ val channelSearchQuery: String = "",+ val showDialog: Boolean = false,+ val selectedChannelForDialog: Channel? = null,+ val dialogGroupMemberships: List<Long> = emptyList(),+ val userMessage: String? = null,+ val showDeleteGroupDialog: Boolean = false,+ val groupToDelete: Category? = null,+ val parentalControlLevel: Int = 0,+ val selectedCategoryForOptions: Category? = null+)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.ktindex 81362e6e..02494ffd 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt@@ -8,62 +8,13 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dpimport androidx.hilt.navigation.compose.hiltViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.viewModelScopeimport androidx.tv.material3.*import com.streamvault.app.ui.components.CategoryRowimport com.streamvault.app.ui.components.MovieCardimport com.streamvault.app.ui.components.TopNavBarimport com.streamvault.app.ui.theme.*import com.streamvault.domain.model.Movie-import com.streamvault.domain.repository.MovieRepository-import com.streamvault.domain.repository.ProviderRepository-import dagger.hilt.android.lifecycle.HiltViewModel-import kotlinx.coroutines.flow.*import kotlinx.coroutines.launch-import javax.inject.Inject--@HiltViewModel-class MoviesViewModel @Inject constructor(- private val providerRepository: ProviderRepository,- private val movieRepository: MovieRepository,- private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository-) : ViewModel() {-- private val _uiState = MutableStateFlow(MoviesUiState())- val uiState: StateFlow<MoviesUiState> = _uiState.asStateFlow()-- init {- viewModelScope.launch {- providerRepository.getActiveProvider()- .filterNotNull()- .collectLatest { provider ->- movieRepository.getMovies(provider.id).collect { movies ->- val grouped = movies.groupBy { it.categoryName ?: "Uncategorized" }- _uiState.update {- it.copy(moviesByCategory = grouped, isLoading = false)- }- }- }- }-- viewModelScope.launch {- preferencesRepository.parentalControlLevel.collect { level ->- _uiState.update { it.copy(parentalControlLevel = level) }- }- }- }-- suspend fun verifyPin(pin: String): Boolean {- return preferencesRepository.parentalPin.first() == pin- }-}--data class MoviesUiState(- val moviesByCategory: Map<String, List<Movie>> = emptyMap(),- val isLoading: Boolean = true,- val parentalControlLevel: Int = 0-)@Composablefun MoviesScreen(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.ktnew file mode 100644index 00000000..e494d2a8--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt@@ -0,0 +1,54 @@+package com.streamvault.app.ui.screens.movies++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.Movie+import com.streamvault.domain.repository.MovieRepository+import com.streamvault.domain.repository.ProviderRepository+import dagger.hilt.android.lifecycle.HiltViewModel+import kotlinx.coroutines.flow.*+import kotlinx.coroutines.launch+import javax.inject.Inject++@HiltViewModel+class MoviesViewModel @Inject constructor(+ private val providerRepository: ProviderRepository,+ private val movieRepository: MovieRepository,+ private val preferencesRepository: PreferencesRepository+) : ViewModel() {++ private val _uiState = MutableStateFlow(MoviesUiState())+ val uiState: StateFlow<MoviesUiState> = _uiState.asStateFlow()++ init {+ viewModelScope.launch {+ providerRepository.getActiveProvider()+ .filterNotNull()+ .collectLatest { provider ->+ movieRepository.getMovies(provider.id).collect { movies ->+ val grouped = movies.groupBy { it.categoryName ?: "Uncategorized" }+ _uiState.update {+ it.copy(moviesByCategory = grouped, isLoading = false)+ }+ }+ }+ }++ viewModelScope.launch {+ preferencesRepository.parentalControlLevel.collect { level ->+ _uiState.update { it.copy(parentalControlLevel = level) }+ }+ }+ }++ suspend fun verifyPin(pin: String): Boolean {+ return preferencesRepository.parentalPin.first() == pin+ }+}++data class MoviesUiState(+ val moviesByCategory: Map<String, List<Movie>> = emptyMap(),+ val isLoading: Boolean = true,+ val parentalControlLevel: Int = 0+)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.ktindex f574aafe..daa8e958 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt@@ -20,158 +20,8 @@ import androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.unit.dpimport androidx.compose.ui.window.Dialogimport androidx.hilt.navigation.compose.hiltViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.viewModelScopeimport androidx.tv.material3.*import com.streamvault.app.ui.theme.*-import com.streamvault.domain.model.Provider-import com.streamvault.domain.model.Result-import com.streamvault.domain.repository.ProviderRepository-import dagger.hilt.android.lifecycle.HiltViewModel-import kotlinx.coroutines.flow.*-import kotlinx.coroutines.launch-import javax.inject.Inject--// ββ ViewModel ββββββββββββββββββββββββββββββββββββββββββββββββββββββ--@HiltViewModel-class ProviderSetupViewModel @Inject constructor(- private val providerRepository: ProviderRepository-) : ViewModel() {-- private val _uiState = MutableStateFlow(ProviderSetupState())- val uiState: StateFlow<ProviderSetupState> = _uiState.asStateFlow()-- init {- viewModelScope.launch {- providerRepository.getActiveProvider().collect { provider ->- if (provider != null) {- _uiState.update { it.copy(hasExistingProvider = true) }- }- }- }- }-- fun loadProvider(id: Long) {- viewModelScope.launch {- val provider = providerRepository.getProvider(id)- if (provider != null) {- _uiState.update {- it.copy(- isEditing = true,- existingProviderId = id,- name = provider.name,- serverUrl = provider.serverUrl,- username = provider.username,- password = provider.password,- m3uUrl = provider.m3uUrl,- selectedTab = if (provider.type == com.streamvault.domain.model.ProviderType.M3U) 1 else 0- )- }- }- }- }-- fun loginXtream(serverUrl: String, username: String, password: String, name: String) {- // Clear previous errors- _uiState.update { it.copy(validationError = null, error = null) }-- // Validation- if (serverUrl.isBlank()) {- _uiState.update { it.copy(validationError = "Please enter server URL") }- return- }- if (username.isBlank()) {- _uiState.update { it.copy(validationError = "Please enter username") }- return- }-- viewModelScope.launch {- _uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...") }- // Pass existingProviderId if editing- val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null-- when (val result = providerRepository.loginXtream(serverUrl, username, password, name, onProgress = { msg ->- _uiState.update { it.copy(syncProgress = msg) }- }, id = existingId)) {- is Result.Success -> {- _uiState.update {- it.copy(isLoading = false, loginSuccess = true, error = null, syncProgress = null)- }- }- is Result.Error -> {- val userMessage = when {- result.message.contains("authentication failed", ignoreCase = true) ||- result.message.contains("auth", ignoreCase = true) ->- "Login failed β please check your credentials and server URL"- result.message.contains("unable to connect", ignoreCase = true) ||- result.message.contains("timeout", ignoreCase = true) ||- result.message.contains("network", ignoreCase = true) ->- "Cannot reach server β check your internet CONNECTION and server URL"- else -> result.message- }- _uiState.update {- it.copy(isLoading = false, error = userMessage, syncProgress = null)- }- }- is Result.Loading -> { /* no-op */ }- }- }- }-- fun addM3u(url: String, name: String) {- // Clear previous errors- _uiState.update { it.copy(validationError = null, error = null) }-- // Validation- if (url.isBlank()) {- _uiState.update { it.copy(validationError = "Please enter M3U URL") }- return- }-- viewModelScope.launch {- _uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Validating...") }- // Pass existingProviderId if editing- val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null-- when (val result = providerRepository.validateM3u(url, name, onProgress = { msg ->- _uiState.update { it.copy(syncProgress = msg) }- }, id = existingId)) {- is Result.Success -> {- _uiState.update {- it.copy(isLoading = false, loginSuccess = true, error = null, syncProgress = null)- }- }- is Result.Error -> {- _uiState.update {- it.copy(isLoading = false, error = "Could not validate playlist URL: ${result.message}", syncProgress = null)- }- }- is Result.Loading -> { /* no-op */ }- }- }- }-}--data class ProviderSetupState(- val isLoading: Boolean = false,- val loginSuccess: Boolean = false,- val hasExistingProvider: Boolean = false,- val error: String? = null,- val validationError: String? = null,- val syncProgress: String? = null,- val isEditing: Boolean = false,- val existingProviderId: Long? = null,- // Pre-fill data- val selectedTab: Int = 0,- val name: String = "",- val serverUrl: String = "",- val username: String = "",- val password: String = "",- val m3uUrl: String = ""-)--// ββ Screen βββββββββββββββββββββββββββββββββββββββββββββββββββββββββ@Composablefun ProviderSetupScreen(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.ktnew file mode 100644index 00000000..ebb6d1bb--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt@@ -0,0 +1,142 @@+package com.streamvault.app.ui.screens.provider++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.ProviderRepository+import dagger.hilt.android.lifecycle.HiltViewModel+import kotlinx.coroutines.flow.*+import kotlinx.coroutines.launch+import javax.inject.Inject++@HiltViewModel+class ProviderSetupViewModel @Inject constructor(+ private val providerRepository: ProviderRepository+) : ViewModel() {++ private val _uiState = MutableStateFlow(ProviderSetupState())+ val uiState: StateFlow<ProviderSetupState> = _uiState.asStateFlow()++ init {+ viewModelScope.launch {+ providerRepository.getActiveProvider().collect { provider ->+ if (provider != null) {+ _uiState.update { it.copy(hasExistingProvider = true) }+ }+ }+ }+ }++ fun loadProvider(id: Long) {+ viewModelScope.launch {+ val provider = providerRepository.getProvider(id)+ if (provider != null) {+ _uiState.update {+ it.copy(+ isEditing = true,+ existingProviderId = id,+ name = provider.name,+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password,+ m3uUrl = provider.m3uUrl,+ selectedTab = if (provider.type == ProviderType.M3U) 1 else 0+ )+ }+ }+ }+ }++ fun loginXtream(serverUrl: String, username: String, password: String, name: String) {+ _uiState.update { it.copy(validationError = null, error = null) }++ if (serverUrl.isBlank()) {+ _uiState.update { it.copy(validationError = "Please enter server URL") }+ return+ }+ if (username.isBlank()) {+ _uiState.update { it.copy(validationError = "Please enter username") }+ return+ }++ viewModelScope.launch {+ _uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...") }+ val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null++ when (val result = providerRepository.loginXtream(serverUrl, username, password, name, onProgress = { msg ->+ _uiState.update { it.copy(syncProgress = msg) }+ }, id = existingId)) {+ is Result.Success -> {+ _uiState.update {+ it.copy(isLoading = false, loginSuccess = true, error = null, syncProgress = null)+ }+ }+ is Result.Error -> {+ val userMessage = when {+ result.message.contains("authentication failed", ignoreCase = true) ||+ result.message.contains("auth", ignoreCase = true) ->+ "Login failed β please check your credentials and server URL"+ result.message.contains("unable to connect", ignoreCase = true) ||+ result.message.contains("timeout", ignoreCase = true) ||+ result.message.contains("network", ignoreCase = true) ->+ "Cannot reach server β check your internet connection and server URL"+ else -> result.message+ }+ _uiState.update {+ it.copy(isLoading = false, error = userMessage, syncProgress = null)+ }+ }+ is Result.Loading -> { /* no-op */ }+ }+ }+ }++ fun addM3u(url: String, name: String) {+ _uiState.update { it.copy(validationError = null, error = null) }++ if (url.isBlank()) {+ _uiState.update { it.copy(validationError = "Please enter M3U URL") }+ return+ }++ viewModelScope.launch {+ _uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Validating...") }+ val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null++ when (val result = providerRepository.validateM3u(url, name, onProgress = { msg ->+ _uiState.update { it.copy(syncProgress = msg) }+ }, id = existingId)) {+ is Result.Success -> {+ _uiState.update {+ it.copy(isLoading = false, loginSuccess = true, error = null, syncProgress = null)+ }+ }+ is Result.Error -> {+ _uiState.update {+ it.copy(isLoading = false, error = "Could not validate playlist URL: ${result.message}", syncProgress = null)+ }+ }+ is Result.Loading -> { /* no-op */ }+ }+ }+ }+}++data class ProviderSetupState(+ val isLoading: Boolean = false,+ val loginSuccess: Boolean = false,+ val hasExistingProvider: Boolean = false,+ val error: String? = null,+ val validationError: String? = null,+ val syncProgress: String? = null,+ val isEditing: Boolean = false,+ val existingProviderId: Long? = null,+ // Pre-fill data+ val selectedTab: Int = 0,+ val name: String = "",+ val serverUrl: String = "",+ val username: String = "",+ val password: String = "",+ val m3uUrl: String = ""+)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.ktindex adb8ccfe..0b358f6c 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt@@ -8,63 +8,12 @@ import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.unit.dpimport androidx.hilt.navigation.compose.hiltViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.viewModelScopeimport androidx.tv.material3.*import com.streamvault.app.ui.components.CategoryRowimport com.streamvault.app.ui.components.SeriesCardimport com.streamvault.app.ui.components.TopNavBarimport com.streamvault.app.ui.theme.*-import com.streamvault.domain.model.Episode-import com.streamvault.domain.model.Series-import com.streamvault.domain.repository.ProviderRepository-import com.streamvault.domain.repository.SeriesRepository-import dagger.hilt.android.lifecycle.HiltViewModel-import kotlinx.coroutines.flow.*import kotlinx.coroutines.launch-import javax.inject.Inject--@HiltViewModel-class SeriesViewModel @Inject constructor(- private val providerRepository: ProviderRepository,- private val seriesRepository: SeriesRepository,- private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository-) : ViewModel() {-- private val _uiState = MutableStateFlow(SeriesUiState())- val uiState: StateFlow<SeriesUiState> = _uiState.asStateFlow()-- init {- viewModelScope.launch {- providerRepository.getActiveProvider()- .filterNotNull()- .collectLatest { provider ->- seriesRepository.getSeries(provider.id).collect { seriesList ->- val grouped = seriesList.groupBy { it.categoryName ?: "Uncategorized" }- _uiState.update {- it.copy(seriesByCategory = grouped, isLoading = false)- }- }- }- }-- viewModelScope.launch {- preferencesRepository.parentalControlLevel.collect { level ->- _uiState.update { it.copy(parentalControlLevel = level) }- }- }- }-- suspend fun verifyPin(pin: String): Boolean {- return preferencesRepository.parentalPin.first() == pin- }-}--data class SeriesUiState(- val seriesByCategory: Map<String, List<Series>> = emptyMap(),- val isLoading: Boolean = true,- val parentalControlLevel: Int = 0-)@Composablefun SeriesScreen(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.ktnew file mode 100644index 00000000..8e128f26--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt@@ -0,0 +1,54 @@+package com.streamvault.app.ui.screens.series++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.Series+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.repository.SeriesRepository+import dagger.hilt.android.lifecycle.HiltViewModel+import kotlinx.coroutines.flow.*+import kotlinx.coroutines.launch+import javax.inject.Inject++@HiltViewModel+class SeriesViewModel @Inject constructor(+ private val providerRepository: ProviderRepository,+ private val seriesRepository: SeriesRepository,+ private val preferencesRepository: PreferencesRepository+) : ViewModel() {++ private val _uiState = MutableStateFlow(SeriesUiState())+ val uiState: StateFlow<SeriesUiState> = _uiState.asStateFlow()++ init {+ viewModelScope.launch {+ providerRepository.getActiveProvider()+ .filterNotNull()+ .collectLatest { provider ->+ seriesRepository.getSeries(provider.id).collect { seriesList ->+ val grouped = seriesList.groupBy { it.categoryName ?: "Uncategorized" }+ _uiState.update {+ it.copy(seriesByCategory = grouped, isLoading = false)+ }+ }+ }+ }++ viewModelScope.launch {+ preferencesRepository.parentalControlLevel.collect { level ->+ _uiState.update { it.copy(parentalControlLevel = level) }+ }+ }+ }++ suspend fun verifyPin(pin: String): Boolean {+ return preferencesRepository.parentalPin.first() == pin+ }+}++data class SeriesUiState(+ val seriesByCategory: Map<String, List<Series>> = emptyMap(),+ val isLoading: Boolean = true,+ val parentalControlLevel: Int = 0+)diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.ktindex 53962527..3fc9fa5b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsScreen.kt@@ -11,8 +11,6 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.focus.onFocusChangedimport androidx.compose.ui.unit.dpimport androidx.hilt.navigation.compose.hiltViewModel-import androidx.lifecycle.ViewModel-import androidx.lifecycle.viewModelScopeimport androidx.tv.material3.*import androidx.compose.material3.SnackbarHostimport androidx.compose.material3.SnackbarHostState@@ -31,107 +29,8 @@ import com.streamvault.app.ui.components.dialogs.PinDialogimport com.streamvault.app.ui.components.TopNavBarimport com.streamvault.app.ui.theme.*import com.streamvault.domain.model.Provider-import com.streamvault.domain.repository.ProviderRepository-import dagger.hilt.android.lifecycle.HiltViewModel-import kotlinx.coroutines.flow.*import kotlinx.coroutines.launch-import javax.inject.Inject-import com.streamvault.data.preferences.PreferencesRepository--@HiltViewModel-class SettingsViewModel @Inject constructor(- private val providerRepository: ProviderRepository,- private val preferencesRepository: PreferencesRepository-) : ViewModel() {-- private val _uiState = MutableStateFlow(SettingsUiState())- val uiState: StateFlow<SettingsUiState> = _uiState.asStateFlow()-- init {- viewModelScope.launch {- combine(- providerRepository.getProviders(),- preferencesRepository.lastActiveProviderId,- preferencesRepository.parentalControlLevel- ) { providers, activeId, level ->- Triple(providers, activeId, level)- }.collect { (providers, activeId, level) ->- _uiState.update {- it.copy(- providers = providers,- activeProviderId = activeId,- parentalControlLevel = level- )- }- }- }- }-- fun setActiveProvider(providerId: Long) {- viewModelScope.launch {- preferencesRepository.setLastActiveProviderId(providerId)- providerRepository.setActiveProvider(providerId)- // Force sync on connect- refreshProvider(providerId)- }- }-- fun setParentalControlLevel(level: Int) {- viewModelScope.launch {- preferencesRepository.setParentalControlLevel(level)- }- }-- suspend fun verifyPin(pin: String): Boolean {- // Simple verification for now. In a real app we might hash this.- val currentPin = preferencesRepository.parentalPin.firstOrNull() ?: "0000"- return pin == currentPin- }-- fun changePin(newPin: String) {- viewModelScope.launch {- preferencesRepository.setParentalPin(newPin)- _uiState.update { it.copy(userMessage = "PIN changed successfully") }- }- }-- fun clearUserMessage() {- _uiState.update { it.copy(userMessage = null) }- }-- fun refreshProvider(providerId: Long) {- viewModelScope.launch {- _uiState.update { it.copy(isSyncing = true) }- val result = providerRepository.refreshProviderData(providerId)- _uiState.update { state ->- state.copy(- isSyncing = false,- userMessage = if (result is com.streamvault.domain.model.Result.Error)- "Refresh failed: ${result.message}"- else "Provider refreshed successfully"- )- }- }- }-- fun deleteProvider(providerId: Long) {- viewModelScope.launch {- providerRepository.deleteProvider(providerId)- }- }-- fun userMessageShown() {- _uiState.update { it.copy(userMessage = null) }- }-}-data class SettingsUiState(- val providers: List<Provider> = emptyList(),- val activeProviderId: Long? = null,- val isSyncing: Boolean = false,- val userMessage: String? = null,- val parentalControlLevel: Int = 0-)@Composablefun SettingsScreen(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.ktnew file mode 100644index 00000000..b2382c0a--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt@@ -0,0 +1,106 @@+package com.streamvault.app.ui.screens.settings++import androidx.lifecycle.ViewModel+import androidx.lifecycle.viewModelScope+import com.streamvault.data.preferences.PreferencesRepository+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.ProviderRepository+import dagger.hilt.android.lifecycle.HiltViewModel+import kotlinx.coroutines.flow.*+import kotlinx.coroutines.launch+import javax.inject.Inject++@HiltViewModel+class SettingsViewModel @Inject constructor(+ private val providerRepository: ProviderRepository,+ private val preferencesRepository: PreferencesRepository+) : ViewModel() {++ private val _uiState = MutableStateFlow(SettingsUiState())+ val uiState: StateFlow<SettingsUiState> = _uiState.asStateFlow()++ init {+ viewModelScope.launch {+ combine(+ providerRepository.getProviders(),+ preferencesRepository.lastActiveProviderId,+ preferencesRepository.parentalControlLevel+ ) { providers, activeId, level ->+ Triple(providers, activeId, level)+ }.collect { (providers, activeId, level) ->+ _uiState.update {+ it.copy(+ providers = providers,+ activeProviderId = activeId,+ parentalControlLevel = level+ )+ }+ }+ }+ }++ fun setActiveProvider(providerId: Long) {+ viewModelScope.launch {+ preferencesRepository.setLastActiveProviderId(providerId)+ providerRepository.setActiveProvider(providerId)+ // Force sync on connect+ refreshProvider(providerId)+ }+ }++ fun setParentalControlLevel(level: Int) {+ viewModelScope.launch {+ preferencesRepository.setParentalControlLevel(level)+ }+ }++ suspend fun verifyPin(pin: String): Boolean {+ val currentPin = preferencesRepository.parentalPin.firstOrNull() ?: "0000"+ return pin == currentPin+ }++ fun changePin(newPin: String) {+ viewModelScope.launch {+ preferencesRepository.setParentalPin(newPin)+ _uiState.update { it.copy(userMessage = "PIN changed successfully") }+ }+ }++ fun clearUserMessage() {+ _uiState.update { it.copy(userMessage = null) }+ }++ fun refreshProvider(providerId: Long) {+ viewModelScope.launch {+ _uiState.update { it.copy(isSyncing = true) }+ val result = providerRepository.refreshProviderData(providerId)+ _uiState.update { state ->+ state.copy(+ isSyncing = false,+ userMessage = if (result is Result.Error)+ "Refresh failed: ${result.message}"+ else "Provider refreshed successfully"+ )+ }+ }+ }++ fun deleteProvider(providerId: Long) {+ viewModelScope.launch {+ providerRepository.deleteProvider(providerId)+ }+ }++ fun userMessageShown() {+ _uiState.update { it.copy(userMessage = null) }+ }+}++data class SettingsUiState(+ val providers: List<Provider> = emptyList(),+ val activeProviderId: Long? = null,+ val isSyncing: Boolean = false,+ val userMessage: String? = null,+ val parentalControlLevel: Int = 0+)diff --git a/data/build.gradle.kts b/data/build.gradle.ktsindex 4c022e81..83becb1b 100644--- a/data/build.gradle.kts+++ b/data/build.gradle.kts@@ -23,6 +23,10 @@ android {jvmTarget = "17"}+ testOptions {+ unitTests.isReturnDefaultValues = true+ }+room {schemaDirectory("$projectDir/schemas")}@@ -56,4 +60,14 @@ dependencies {// Coreimplementation(libs.core.ktx)++ // Unit tests+ testImplementation(libs.junit)+ testImplementation(libs.truth)+ testImplementation(libs.coroutines.test)+ // kxml2: JVM XmlPullParser implementation needed for XmltvParser unit tests+ // (Android platform provides its own impl; the JVM test runner needs an explicit one)+ testImplementation(libs.kxml2)+ // Mocking for SyncManagerTest+ testImplementation(libs.mockito.kotlin)}diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/3.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/3.jsonnew file mode 100644index 00000000..7c257ac8--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/3.json@@ -0,0 +1,1077 @@+{+ "formatVersion": 1,+ "database": {+ "version": 3,+ "identityHash": "584d73a0ebbbffb65db70f9211d94661",+ "entities": [+ {+ "tableName": "providers",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "serverUrl",+ "columnName": "server_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "password",+ "columnName": "password",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "m3uUrl",+ "columnName": "m3u_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgUrl",+ "columnName": "epg_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isActive",+ "columnName": "is_active",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "maxConnections",+ "columnName": "max_connections",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "expirationDate",+ "columnName": "expiration_date",+ "affinity": "INTEGER",+ "notNull": false+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncedAt",+ "columnName": "last_synced_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_providers_server_url_username",+ "unique": true,+ "columnNames": [+ "server_url",+ "username"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username` ON `${TABLE_NAME}` (`server_url`, `username`)"+ }+ ],+ "foreignKeys": []+ },+ {+ "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)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "logoUrl",+ "columnName": "logo_url",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": false+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "number",+ "columnName": "number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpSupported",+ "columnName": "catch_up_supported",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "catchUpDays",+ "columnName": "catch_up_days",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channels_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channels_category_id",+ "unique": false,+ "columnNames": [+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_category_id` ON `${TABLE_NAME}` (`category_id`)"+ },+ {+ "name": "index_channels_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ }+ ],+ "foreignKeys": []+ },+ {+ "tableName": "movies",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamId",+ "columnName": "stream_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": false+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": false+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_movies_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movies_category_id",+ "unique": false,+ "columnNames": [+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_category_id` ON `${TABLE_NAME}` (`category_id`)"+ },+ {+ "name": "index_movies_provider_id_stream_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "stream_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"+ }+ ],+ "foreignKeys": []+ },+ {+ "tableName": "series",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": false+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER",+ "notNull": false+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_series_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_category_id",+ "unique": false,+ "columnNames": [+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_id` ON `${TABLE_NAME}` (`category_id`)"+ },+ {+ "name": "index_series_provider_id_series_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"+ }+ ],+ "foreignKeys": []+ },+ {+ "tableName": "episodes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "episodeId",+ "columnName": "episode_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchProgress",+ "columnName": "watch_progress",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_episodes_series_id",+ "unique": false,+ "columnNames": [+ "series_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"+ },+ {+ "name": "index_episodes_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_episodes_provider_id_episode_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "episode_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"+ }+ ],+ "foreignKeys": []+ },+ {+ "tableName": "categories",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentId",+ "columnName": "parent_id",+ "affinity": "INTEGER",+ "notNull": false+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isUserProtected",+ "columnName": "is_user_protected",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_categories_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_categories_provider_id_category_id_type",+ "unique": true,+ "columnNames": [+ "provider_id",+ "category_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"+ }+ ],+ "foreignKeys": []+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_channel_id",+ "unique": false,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ },+ {+ "name": "index_programs_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"+ },+ {+ "name": "index_programs_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_channel_id_start_time` ON `${TABLE_NAME}` (`channel_id`, `start_time`)"+ }+ ],+ "foreignKeys": []+ },+ {+ "tableName": "favorites",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `added_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentId",+ "columnName": "content_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "groupId",+ "columnName": "group_id",+ "affinity": "INTEGER",+ "notNull": false+ },+ {+ "fieldPath": "addedAt",+ "columnName": "added_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_favorites_content_id_content_type_group_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_content_id_content_type_group_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id",+ "unique": false,+ "columnNames": [+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id` ON `${TABLE_NAME}` (`group_id`)"+ },+ {+ "name": "index_favorites_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_position` ON `${TABLE_NAME}` (`position`)"+ }+ ],+ "foreignKeys": []+ },+ {+ "tableName": "virtual_groups",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconEmoji",+ "columnName": "icon_emoji",+ "affinity": "TEXT",+ "notNull": false+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_virtual_groups_position",+ "unique": false,+ "columnNames": [+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"+ }+ ],+ "foreignKeys": []+ }+ ],+ "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, '584d73a0ebbbffb65db70f9211d94661')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex 24a8617a..6aba28bf 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -2,6 +2,8 @@ package com.streamvault.data.localimport androidx.room.Databaseimport androidx.room.RoomDatabase+import androidx.room.migration.Migration+import androidx.sqlite.db.SupportSQLiteDatabaseimport com.streamvault.data.local.dao.*import com.streamvault.data.local.entity.*@@ -18,7 +20,7 @@ import com.streamvault.data.local.entity.*VirtualGroupEntity::class],version = 3,- exportSchema = false+ exportSchema = true // β was false; schema JSON now tracked in version control)abstract class StreamVaultDatabase : RoomDatabase() {abstract fun providerDao(): ProviderDao@@ -32,8 +34,11 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun virtualGroupDao(): VirtualGroupDaocompanion object {- val MIGRATION_2_3 = object : androidx.room.migration.Migration(2, 3) {- override fun migrate(database: androidx.sqlite.db.SupportSQLiteDatabase) {+ /**+ * Migration 2 β 3: added parental-control protection columns.+ */+ val MIGRATION_2_3 = object : Migration(2, 3) {+ override fun migrate(database: SupportSQLiteDatabase) {database.execSQL("ALTER TABLE categories ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")database.execSQL("ALTER TABLE channels ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")database.execSQL("ALTER TABLE movies ADD COLUMN is_adult INTEGER NOT NULL DEFAULT 0")@@ -44,5 +49,9 @@ abstract class StreamVaultDatabase : RoomDatabase() {database.execSQL("ALTER TABLE episodes ADD COLUMN is_user_protected INTEGER NOT NULL DEFAULT 0")}}++ // Placeholder for the next schema change. Add ALTER TABLE statements here when+ // an entity is modified before bumping version to 4.+ // val MIGRATION_3_4 = object : Migration(3, 4) { ... }}}diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.ktindex ca7b0622..8c551ff6 100644--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt@@ -1,22 +1,17 @@package com.streamvault.data.repositoryimport com.streamvault.data.local.dao.*-import com.streamvault.data.local.entity.CategoryEntityimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.mapper.*-import com.streamvault.data.parser.M3uParserimport com.streamvault.data.remote.xtream.XtreamApiServiceimport com.streamvault.data.remote.xtream.XtreamProvider+import com.streamvault.data.sync.SyncManagerimport com.streamvault.domain.model.*import com.streamvault.domain.provider.IptvProviderimport com.streamvault.domain.repository.EpgRepositoryimport com.streamvault.domain.repository.ProviderRepository-import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.flow.Flowimport kotlinx.coroutines.flow.map-import kotlinx.coroutines.withContext-import okhttp3.OkHttpClient-import okhttp3.Requestimport javax.inject.Injectimport javax.inject.Singleton@@ -28,9 +23,7 @@ class ProviderRepositoryImpl @Inject constructor(private val seriesDao: SeriesDao,private val categoryDao: CategoryDao,private val xtreamApiService: XtreamApiService,- private val m3uParser: M3uParser,- private val epgRepository: EpgRepository,- private val okHttpClient: OkHttpClient+ private val syncManager: SyncManager) : ProviderRepository {override fun getProviders(): Flow<List<Provider>> =@@ -89,83 +82,69 @@ class ProviderRepositoryImpl @Inject constructor(val provider = createXtreamProvider(0, serverUrl, username, password)return when (val authResult = provider.authenticate()) {is Result.Success -> {- // Check if provider already exists by ID first, then by URL/Userval existingProvider = if (id != null) {providerDao.getById(id)} else {providerDao.getByUrlAndUser(serverUrl, username)}-+val providerData = if (existingProvider != null) {onProgress?.invoke("Updating existing provider...")- // Update existing provider detailsval updated = existingProvider.copy(name = name.ifBlank { existingProvider.name },serverUrl = serverUrl,username = username,- password = password, // Update password if changed+ password = password,isActive = true,- lastSyncedAt = 0 // Reset sync time to force update+ lastSyncedAt = 0)providerDao.update(updated)updated.toDomain()} else {- // Use the provided name, or fallback to server's name if empty- val newData = authResult.data.copy(- name = name.ifBlank { authResult.data.name }- )- val id = providerDao.insert(newData.toEntity())- newData.copy(id = id)+ val newData = authResult.data.copy(name = name.ifBlank { authResult.data.name })+ val newId = providerDao.insert(newData.toEntity())+ newData.copy(id = newId)}-- val id = providerData.id-try {providerDao.deactivateAll()- providerDao.activate(id)-- val refreshResult = refreshProviderData(id, onProgress)-- if (refreshResult is Result.Success) {- Result.success(providerData)- } else if (refreshResult is Result.Error) {- // Allow saving even if sync fails- android.util.Log.e("ProviderRepo", "Initial Xtream sync failed: ${refreshResult.message}")- Result.success(providerData)- } else {- Result.success(providerData)- }+ providerDao.activate(providerData.id)+ // Delegate sync to SyncManager+ syncManager.sync(providerData.id, onProgress)} catch (e: Exception) {- android.util.Log.e("ProviderRepo", "Xtream Sync crashed: ${e.message}")- Result.success(providerData)+ android.util.Log.e("ProviderRepo", "Initial Xtream sync failed: ${e.message}")}+ Result.success(providerData)}is Result.Error -> Result.error(authResult.message, authResult.exception)is Result.Loading -> Result.error("Unexpected loading state")}}- override suspend fun validateM3u(url: String, name: String, onProgress: ((String) -> Unit)?, id: Long?): Result<Provider> = try {+ override suspend fun validateM3u(+ url: String,+ name: String,+ onProgress: ((String) -> Unit)?,+ id: Long?+ ): Result<Provider> = try {onProgress?.invoke("Validating playlist URL...")- val providerName = name.ifBlank {- url.substringAfterLast("/").substringBefore("?").ifBlank { "M3U Playlist" }+ val providerName = name.ifBlank {+ url.substringAfterLast("/").substringBefore("?").ifBlank { "M3U Playlist" }}-- // Check for existing by ID first, then by URL+val existingProvider = if (id != null) {providerDao.getById(id)} else {providerDao.getByUrlAndUser(url, "")}-+val providerData = if (existingProvider != null) {val updated = existingProvider.copy(name = if (name.isNotBlank()) name else existingProvider.name,serverUrl = url,m3uUrl = url,isActive = true,- lastSyncedAt = 0 // Reset sync time+ lastSyncedAt = 0)providerDao.update(updated)updated.toDomain()@@ -177,243 +156,30 @@ class ProviderRepositoryImpl @Inject constructor(m3uUrl = url,status = ProviderStatus.ACTIVE)- val id = providerDao.insert(provider.toEntity())- provider.copy(id = id)+ val newId = providerDao.insert(provider.toEntity())+ provider.copy(id = newId)}-- val id = providerData.idtry {providerDao.deactivateAll()- providerDao.activate(id)-- // Use the public refresh method to ensure consistency with manual refresh- val refreshResult = refreshProviderData(id, onProgress)-- if (refreshResult is Result.Success) {- Result.success(providerData)- } else if (refreshResult is Result.Error) {- // Return success but with the provider data, so the UI considers it "added"- // The sync error will be logged and the user might see empty content, but they can edit it later.- // We could potentially wrap this in a custom result or just rely on the fact that- // providerData is returned.- // Ideally we'd return Result.Success(providerData) but maybe trigger a toast.- // For now, let's treat it as success so navigation proceeds, but log the error.- android.util.Log.e("ProviderRepo", "Initial M3U sync failed: ${refreshResult.message}")- Result.success(providerData)- } else {- Result.success(providerData)- }+ providerDao.activate(providerData.id)+ // Delegate sync to SyncManager+ syncManager.sync(providerData.id, onProgress)} catch (e: Exception) {- // Even if exception occurs (unlikely due to refreshProviderData having its own try/catch),- // we keep the provider so user can edit it.- android.util.Log.e("ProviderRepo", "M3U Validation/Sync crashed: ${e.message}")- Result.success(providerData)+ android.util.Log.e("ProviderRepo", "Initial M3U sync failed: ${e.message}")}+ Result.success(providerData)} catch (e: Exception) {Result.error("Failed to add M3U provider: ${e.message}", e)}- override suspend fun refreshProviderData(providerId: Long, onProgress: ((String) -> Unit)?): Result<Unit> = try {- val providerEntity = providerDao.getById(providerId)- ?: return Result.error("Provider not found")- val provider = providerEntity.toDomain()-- when (provider.type) {- ProviderType.XTREAM_CODES -> refreshXtreamData(provider, onProgress)- ProviderType.M3U -> refreshM3uData(provider, onProgress)- }-- providerDao.updateSyncTime(providerId, System.currentTimeMillis())- Result.success(Unit)- } catch (e: Exception) {- Result.error("Failed to refresh provider data: ${e.message}", e)- }-- private suspend fun refreshXtreamData(provider: Provider, onProgress: ((String) -> Unit)? = null) {- onProgress?.invoke("Connecting to server...")- val xtreamProvider = createXtreamProvider(- provider.id, provider.serverUrl, provider.username, provider.password- )-- // Refresh live categories & channels- onProgress?.invoke("Downloading Live TV...")- val liveCatsResult = xtreamProvider.getLiveCategories()- if (liveCatsResult is Result.Error) {- android.util.Log.e("ProviderRepo", "Failed to fetch Live Categories: ${liveCatsResult.message}")- throw Exception("Failed to fetch Live Categories: ${liveCatsResult.message}")- }-- liveCatsResult.getOrNull()?.let { categories ->- android.util.Log.d("ProviderRepo", "Saving ${categories.size} live categories")- categoryDao.replaceAll(- provider.id, "LIVE",- categories.map { it.toEntity(provider.id) }- )- }-- val liveStreamsResult = xtreamProvider.getLiveStreams()- if (liveStreamsResult is Result.Error) {- android.util.Log.e("ProviderRepo", "Failed to fetch Live Streams: ${liveStreamsResult.message}")- throw Exception("Failed to fetch Live Streams: ${liveStreamsResult.message}")- }-- liveStreamsResult.getOrNull()?.let { channels ->- android.util.Log.d("ProviderRepo", "Saving ${channels.size} live channels")- channelDao.replaceAll(provider.id, channels.map { it.toEntity() })- }-- // Refresh VOD categories & movies- onProgress?.invoke("Downloading Movies...")- val vodCatsResult = xtreamProvider.getVodCategories()-- vodCatsResult.getOrNull()?.let { categories ->- android.util.Log.d("ProviderRepo", "Saving ${categories.size} VOD categories")- categoryDao.replaceAll(- provider.id, "MOVIE",- categories.map { it.toEntity(provider.id) }- )- }-- xtreamProvider.getVodStreams().getOrNull()?.let { movies ->- android.util.Log.d("ProviderRepo", "Saving ${movies.size} movies")- movieDao.replaceAll(provider.id, movies.map { it.toEntity() })- }-- // Refresh series categories & series- onProgress?.invoke("Downloading Series...")- xtreamProvider.getSeriesCategories().getOrNull()?.let { categories ->- android.util.Log.d("ProviderRepo", "Saving ${categories.size} series categories")- categoryDao.replaceAll(- provider.id, "SERIES",- categories.map { it.toEntity(provider.id) }- )- }- xtreamProvider.getSeriesList().getOrNull()?.let { seriesList ->- android.util.Log.d("ProviderRepo", "Saving ${seriesList.size} series")- seriesDao.replaceAll(provider.id, seriesList.map { it.toEntity() })- }-- // Refresh EPG (XMLTV)- try {- onProgress?.invoke("Downloading EPG...")- val serverUrl = provider.serverUrl.trimEnd('/')- val xmltvUrl = "$serverUrl/xmltv.php?username=${provider.username}&password=${provider.password}"- epgRepository.refreshEpg(provider.id, xmltvUrl)- } catch (e: Exception) {- e.printStackTrace()- android.util.Log.e("ProviderRepo", "EPG Sync failed: ${e.message}")- }- }-- private suspend fun refreshM3uData(provider: Provider, onProgress: ((String) -> Unit)? = null) = withContext(Dispatchers.IO) {- android.util.Log.d("ProviderRepo", "Starting M3U refresh for ${provider.name}")- onProgress?.invoke("Downloading Playlist...")- val m3uUrl = provider.m3uUrl.ifBlank { provider.serverUrl }- val request = Request.Builder().url(m3uUrl).build()- val response = okHttpClient.newCall(request).execute()-- if (!response.isSuccessful) {- android.util.Log.e("ProviderRepo", "Failed to download M3U: ${response.code}")- throw Exception("Failed to download M3U: HTTP ${response.code}")- }-- val body = response.body ?: throw Exception("Empty M3U response")-- onProgress?.invoke("Parsing Playlist...")- val entries = body.byteStream().use { inputStream ->- m3uParser.parse(inputStream)- }- android.util.Log.d("ProviderRepo", "Parsed ${entries.size} entries")-- // Separate live channels vs VOD (movies)- val liveEntries = entries.filter { !isVodEntry(it) }- val vodEntries = entries.filter { isVodEntry(it) }-- // Build categories from group titles- val liveGroups = liveEntries.map { it.groupTitle }.distinct()- val vodGroups = vodEntries.map { it.groupTitle }.distinct()-- // Insert live categories- onProgress?.invoke("Saving Channels...")- val liveCategories = liveGroups.mapIndexed { index, name ->- CategoryEntity(- categoryId = (index + 1).toLong(),- name = name,- parentId = 0,- type = "LIVE",- providerId = provider.id- )- }- android.util.Log.d("ProviderRepo", "Saving ${liveCategories.size} live categories")- categoryDao.replaceAll(provider.id, "LIVE", liveCategories)-- // Insert VOD categories- onProgress?.invoke("Saving Movies...")- val vodCategories = vodGroups.mapIndexed { index, name ->- CategoryEntity(- categoryId = (index + 10000).toLong(),- name = name,- parentId = 0,- type = "MOVIE",- providerId = provider.id- )- }- android.util.Log.d("ProviderRepo", "Saving ${vodCategories.size} VOD categories")- categoryDao.replaceAll(provider.id, "MOVIE", vodCategories)-- // Build category lookup maps- val liveCategoryMap = liveGroups.withIndex().associate { (i, name) -> name to (i + 1).toLong() }- val vodCategoryMap = vodGroups.withIndex().associate { (i, name) -> name to (i + 10000).toLong() }-- // Insert live channels- val channels = liveEntries.mapIndexed { index, entry ->- Channel(- id = index.toLong() + 1,- name = entry.name,- logoUrl = entry.tvgLogo,- groupTitle = entry.groupTitle,- categoryId = liveCategoryMap[entry.groupTitle],- categoryName = entry.groupTitle,- epgChannelId = entry.tvgId ?: entry.tvgName,- number = entry.tvgChno ?: (index + 1),- streamUrl = entry.url,- catchUpSupported = entry.catchUp != null,- providerId = provider.id- ).toEntity()- }- android.util.Log.d("ProviderRepo", "Saving ${channels.size} channels")- channelDao.replaceAll(provider.id, channels)-- // Insert movies- val movies = vodEntries.mapIndexed { index, entry ->- Movie(- id = index.toLong() + 100000,- name = entry.name,- posterUrl = entry.tvgLogo,- categoryId = vodCategoryMap[entry.groupTitle],- categoryName = entry.groupTitle,- streamUrl = entry.url,- providerId = provider.id- ).toEntity()- }- android.util.Log.d("ProviderRepo", "Saving ${movies.size} movies")- movieDao.replaceAll(provider.id, movies)-- android.util.Log.d("ProviderRepo", "M3U refresh complete")- }-- private fun isVodEntry(entry: M3uParser.M3uEntry): Boolean {- val url = entry.url.lowercase()- val group = entry.groupTitle.lowercase()- return url.endsWith(".mp4") ||- url.endsWith(".mkv") ||- url.endsWith(".avi") ||- url.contains("/movie/") ||- group.contains("movie") ||- group.contains("vod") ||- group.contains("film")- }+ /**+ * Delegates to [SyncManager] β the single source of truth for the full sync pipeline.+ */+ override suspend fun refreshProviderData(+ providerId: Long,+ onProgress: ((String) -> Unit)?+ ): Result<Unit> = syncManager.sync(providerId, onProgress)fun createXtreamProvider(providerId: Long,diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.ktnew file mode 100644index 00000000..2b0c1e12--- /dev/null+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt@@ -0,0 +1,299 @@+package com.streamvault.data.sync++import android.util.Log+import com.streamvault.data.local.dao.CategoryDao+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.entity.CategoryEntity+import com.streamvault.data.mapper.*+import com.streamvault.data.parser.M3uParser+import com.streamvault.data.remote.xtream.XtreamApiService+import com.streamvault.data.remote.xtream.XtreamProvider+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderType+import com.streamvault.domain.model.SyncState+import com.streamvault.domain.repository.EpgRepository+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import okhttp3.OkHttpClient+import okhttp3.Request+import java.security.MessageDigest+import javax.inject.Inject+import javax.inject.Singleton++private const val TAG = "SyncManager"++/**+ * Centralised sync engine that owns the state machine and all data refresh logic.+ *+ * Formerly this logic was scattered inside `ProviderRepositoryImpl`. Moving it here+ * gives us:+ * - A single source of truth for `SyncState`+ * - A cancellable coroutine scope independent of ViewModel lifetimes+ * - Stable, hash-based M3U entry IDs (no more index-based fragility)+ * - Testable sync logic (can be unit-tested with fakes for all DAOs)+ */+@Singleton+class SyncManager @Inject constructor(+ private val providerDao: ProviderDao,+ private val channelDao: ChannelDao,+ private val movieDao: MovieDao,+ private val seriesDao: SeriesDao,+ private val categoryDao: CategoryDao,+ private val xtreamApiService: XtreamApiService,+ private val m3uParser: M3uParser,+ private val epgRepository: EpgRepository,+ private val okHttpClient: OkHttpClient+) {+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)++ private val _syncState = MutableStateFlow<SyncState>(SyncState.Idle)+ val syncState: StateFlow<SyncState> = _syncState.asStateFlow()++ // ββ Public API ββββββββββββββββββββββββββββββββββββββββββββββββββ++ /**+ * Perform a full data refresh for [providerId].+ * [onProgress] is an optional UI callback for fine-grained status strings.+ */+ suspend fun sync(+ providerId: Long,+ onProgress: ((String) -> Unit)? = null+ ): com.streamvault.domain.model.Result<Unit> {+ val providerEntity = providerDao.getById(providerId)+ ?: return com.streamvault.domain.model.Result.error("Provider $providerId not found")++ val provider = providerEntity.toDomain()+ _syncState.value = SyncState.Syncing("Startingβ¦")++ return try {+ when (provider.type) {+ ProviderType.XTREAM_CODES -> syncXtream(provider, onProgress)+ ProviderType.M3U -> syncM3u(provider, onProgress)+ }+ providerDao.updateSyncTime(providerId, System.currentTimeMillis())+ _syncState.value = SyncState.Success()+ com.streamvault.domain.model.Result.success(Unit)+ } catch (e: Exception) {+ Log.e(TAG, "Sync failed for provider $providerId: ${e.message}", e)+ _syncState.value = SyncState.Error(e.message ?: "Unknown error", e)+ com.streamvault.domain.model.Result.error(e.message ?: "Sync failed", e)+ }+ }++ /** Fire-and-forget variant β launches on the internal scope so callers don't need to await. */+ fun syncAsync(providerId: Long, onProgress: ((String) -> Unit)? = null) {+ scope.launch { sync(providerId, onProgress) }+ }++ fun resetState() {+ _syncState.value = SyncState.Idle+ }++ // ββ Xtream sync βββββββββββββββββββββββββββββββββββββββββββββββββ++ private suspend fun syncXtream(provider: Provider, onProgress: ((String) -> Unit)?) {+ progress(onProgress, "Connecting to serverβ¦")+ val api = XtreamProvider(+ providerId = provider.id,+ api = xtreamApiService,+ serverUrl = provider.serverUrl,+ username = provider.username,+ password = provider.password+ )++ // Live+ progress(onProgress, "Downloading Live TVβ¦")+ api.getLiveCategories().getOrThrow("Live categories").let { cats ->+ Log.d(TAG, "Saving ${cats.size} live categories")+ categoryDao.replaceAll(provider.id, "LIVE", cats.map { it.toEntity(provider.id) })+ }+ api.getLiveStreams().getOrThrow("Live streams").let { channels ->+ Log.d(TAG, "Saving ${channels.size} channels")+ channelDao.replaceAll(provider.id, channels.map { it.toEntity() })+ }++ // VOD+ progress(onProgress, "Downloading Moviesβ¦")+ api.getVodCategories().getOrNull()?.let { cats ->+ Log.d(TAG, "Saving ${cats.size} VOD categories")+ categoryDao.replaceAll(provider.id, "MOVIE", cats.map { it.toEntity(provider.id) })+ }+ api.getVodStreams().getOrNull()?.let { movies ->+ Log.d(TAG, "Saving ${movies.size} movies")+ movieDao.replaceAll(provider.id, movies.map { it.toEntity() })+ }++ // Series+ progress(onProgress, "Downloading Seriesβ¦")+ api.getSeriesCategories().getOrNull()?.let { cats ->+ Log.d(TAG, "Saving ${cats.size} series categories")+ categoryDao.replaceAll(provider.id, "SERIES", cats.map { it.toEntity(provider.id) })+ }+ api.getSeriesList().getOrNull()?.let { seriesList ->+ Log.d(TAG, "Saving ${seriesList.size} series")+ seriesDao.replaceAll(provider.id, seriesList.map { it.toEntity() })+ }++ // EPG+ try {+ progress(onProgress, "Downloading EPGβ¦")+ val base = provider.serverUrl.trimEnd('/')+ val xmltvUrl = "$base/xmltv.php?username=${provider.username}&password=${provider.password}"+ epgRepository.refreshEpg(provider.id, xmltvUrl)+ } catch (e: Exception) {+ Log.e(TAG, "EPG sync failed (non-fatal): ${e.message}")+ }+ }++ // ββ M3U sync ββββββββββββββββββββββββββββββββββββββββββββββββββββ++ private suspend fun syncM3u(provider: Provider, onProgress: ((String) -> Unit)?) {+ withContext(Dispatchers.IO) {+ Log.d(TAG, "Starting M3U refresh for ${provider.name}")+ progress(onProgress, "Downloading Playlistβ¦")+ val url = provider.m3uUrl.ifBlank { provider.serverUrl }+ val response = okHttpClient.newCall(Request.Builder().url(url).build()).execute()++ if (!response.isSuccessful) {+ throw Exception("Failed to download M3U: HTTP ${response.code}")+ }+ val body = response.body ?: throw Exception("Empty M3U response")++ progress(onProgress, "Parsing Playlistβ¦")+ val entries = body.byteStream().use { m3uParser.parse(it) }+ Log.d(TAG, "Parsed ${entries.size} M3U entries")++ val liveEntries = entries.filter { !isVodEntry(it) }+ val vodEntries = entries.filter { isVodEntry(it) }++ // ββ Categories ββββββββββββββββββββββββββββββββββββββ+ val liveGroups = liveEntries.map { it.groupTitle }.distinct()+ val vodGroups = vodEntries.map { it.groupTitle }.distinct()++ val liveCategories = liveGroups.mapIndexed { i, name ->+ CategoryEntity(categoryId = (i + 1).toLong(), name = name,+ parentId = 0, type = "LIVE", providerId = provider.id)+ }+ val vodCategories = vodGroups.mapIndexed { i, name ->+ CategoryEntity(categoryId = (i + 10_000).toLong(), name = name,+ parentId = 0, type = "MOVIE", providerId = provider.id)+ }++ progress(onProgress, "Saving Channelsβ¦")+ categoryDao.replaceAll(provider.id, "LIVE", liveCategories)+ categoryDao.replaceAll(provider.id, "MOVIE", vodCategories)++ val liveCategoryMap = liveGroups.withIndex().associate { (i, n) -> n to (i + 1).toLong() }+ val vodCategoryMap = vodGroups.withIndex().associate { (i, n) -> n to (i + 10_000).toLong() }++ // ββ Channels with stable hash IDs βββββββββββββββββββ+ val channels = liveEntries.map { entry ->+ Channel(+ id = stableId(provider.id, entry.tvgId, entry.url),+ name = entry.name,+ logoUrl = entry.tvgLogo,+ groupTitle = entry.groupTitle,+ categoryId = liveCategoryMap[entry.groupTitle],+ categoryName = entry.groupTitle,+ epgChannelId = entry.tvgId ?: entry.tvgName,+ number = entry.tvgChno ?: 0,+ streamUrl = entry.url,+ catchUpSupported = entry.catchUp != null,+ providerId = provider.id+ ).toEntity()+ }+ Log.d(TAG, "Saving ${channels.size} channels")+ channelDao.replaceAll(provider.id, channels)++ // ββ Movies with stable hash IDs βββββββββββββββββββββ+ progress(onProgress, "Saving Moviesβ¦")+ val movies = vodEntries.map { entry ->+ Movie(+ id = stableId(provider.id, entry.tvgId, entry.url),+ name = entry.name,+ posterUrl = entry.tvgLogo,+ categoryId = vodCategoryMap[entry.groupTitle],+ categoryName = entry.groupTitle,+ streamUrl = entry.url,+ providerId = provider.id+ ).toEntity()+ }+ Log.d(TAG, "Saving ${movies.size} movies")+ movieDao.replaceAll(provider.id, movies)+ Log.d(TAG, "M3U refresh complete")+ }+ }++ // ββ Helpers βββββββββββββββββββββββββββββββββββββββββββββββββββββ++ /**+ * Generate a stable, collision-resistant ID for an M3U entry.+ *+ * Priority:+ * 1. tvg-id (explicit EPG key β most stable)+ * 2. SHA-256(providerId + streamUrl) (URL changes invalidate the record β acceptable)+ *+ * This replaces the previous `index.toLong() + offset` scheme which caused+ * data corruption whenever the playlist order changed.+ */+ private fun stableId(providerId: Long, tvgId: String?, url: String): Long {+ if (!tvgId.isNullOrBlank()) {+ // Hash the tvgId to fit in a Long+ return hashToLong("$providerId:tvg:$tvgId")+ }+ return hashToLong("$providerId:url:$url")+ }++ private fun hashToLong(input: String): Long {+ val digest = MessageDigest.getInstance("SHA-256").digest(input.toByteArray(Charsets.UTF_8))+ // Take first 8 bytes and fold into a Long (masks sign bit to keep positive)+ var result = 0L+ for (i in 0 until 8) {+ result = (result shl 8) or (digest[i].toLong() and 0xFF)+ }+ return result and Long.MAX_VALUE // ensure positive+ }++ /**+ * Heuristic to distinguish VOD (movie) entries from live streams in M3U playlists.+ * Consolidated here as the single source of truth (previously duplicated).+ */+ internal fun isVodEntry(entry: M3uParser.M3uEntry): Boolean {+ val url = entry.url.lowercase()+ val group = entry.groupTitle.lowercase()+ return url.endsWith(".mp4") ||+ url.endsWith(".mkv") ||+ url.endsWith(".avi") ||+ url.contains("/movie/") ||+ group.contains("movie") ||+ group.contains("vod") ||+ group.contains("film")+ }++ private fun progress(callback: ((String) -> Unit)?, message: String) {+ _syncState.value = SyncState.Syncing(message)+ callback?.invoke(message)+ }++ // Extension to convert Result<T> to T-or-throw for mandatory resources+ private fun <T> com.streamvault.domain.model.Result<T>.getOrThrow(resourceName: String): T {+ return when (this) {+ is com.streamvault.domain.model.Result.Success -> data+ is com.streamvault.domain.model.Result.Error ->+ throw Exception("Failed to fetch $resourceName: $message")+ is com.streamvault.domain.model.Result.Loading ->+ throw Exception("Unexpected loading state for $resourceName")+ }+ }+}diff --git a/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt b/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.ktnew file mode 100644index 00000000..422d638e--- /dev/null+++ b/data/src/test/java/com/streamvault/data/mapper/EntityMappersTest.kt@@ -0,0 +1,138 @@+package com.streamvault.data.mapper++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.data.local.entity.MovieEntity+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.domain.model.Channel+import com.streamvault.domain.model.Movie+import com.streamvault.domain.model.Provider+import com.streamvault.domain.model.ProviderStatus+import com.streamvault.domain.model.ProviderType+import org.junit.Test++/**+ * Unit tests for entity β domain mapper extension functions in [EntityMappers].+ *+ * Validates that every field survives a round-trip through the data layer without+ * mutation, truncation, or silent default substitution.+ */+class EntityMappersTest {++ // ββ Provider ββββββββββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `provider_roundTrip_preservesAllFields`() {+ val original = Provider(+ id = 42L,+ name = "My Xtream Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "http://example.com:8080",+ username = "user123",+ password = "p@ssw0rd!",+ m3uUrl = "",+ epgUrl = "http://example.com/epg.xml",+ isActive = true,+ maxConnections = 3,+ expirationDate = 1_798_761_600_000L, // 2027-01-01 UTC as epoch ms+ status = ProviderStatus.ACTIVE,+ lastSyncedAt = 1_700_000_000_000L,+ createdAt = 1_600_000_000_000L+ )++ val roundTripped = original.toEntity().toDomain()++ assertThat(roundTripped.id).isEqualTo(original.id)+ assertThat(roundTripped.name).isEqualTo(original.name)+ assertThat(roundTripped.type).isEqualTo(original.type)+ assertThat(roundTripped.serverUrl).isEqualTo(original.serverUrl)+ assertThat(roundTripped.username).isEqualTo(original.username)+ assertThat(roundTripped.password).isEqualTo(original.password)+ assertThat(roundTripped.m3uUrl).isEqualTo(original.m3uUrl)+ assertThat(roundTripped.epgUrl).isEqualTo(original.epgUrl)+ assertThat(roundTripped.isActive).isEqualTo(original.isActive)+ assertThat(roundTripped.maxConnections).isEqualTo(original.maxConnections)+ assertThat(roundTripped.expirationDate).isEqualTo(original.expirationDate)+ assertThat(roundTripped.status).isEqualTo(original.status)+ assertThat(roundTripped.lastSyncedAt).isEqualTo(original.lastSyncedAt)+ assertThat(roundTripped.createdAt).isEqualTo(original.createdAt)+ }++ @Test+ fun `provider_unknownStatus_defaultsToUnknown`() {+ // Simulate a DB row with a status string that is not a valid enum value+ val entity = ProviderEntity(+ id = 1L,+ name = "Test",+ type = ProviderType.M3U.name,+ serverUrl = "http://x.com",+ username = "",+ password = "",+ m3uUrl = "",+ epgUrl = "",+ isActive = false,+ maxConnections = 1,+ expirationDate = null, // Long? β null is fine+ status = "EXPIRED_FUTURE_VALUE", // unknown status string+ lastSyncedAt = 0L,+ createdAt = 0L+ )++ val domain = entity.toDomain()++ assertThat(domain.status).isEqualTo(ProviderStatus.UNKNOWN)+ }++ // ββ Channel βββββββββββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `channel_nullableFields_handledCorrectly`() {+ val channel = Channel(+ id = 99L,+ name = "Test Channel",+ logoUrl = null, // intentionally null+ groupTitle = "Live",+ categoryId = null, // intentionally null+ categoryName = "Live",+ streamUrl = "http://stream.example.com/99.ts",+ epgChannelId = null,+ number = 0,+ catchUpSupported = false,+ catchUpDays = 0,+ providerId = 1L+ )++ val roundTripped = channel.toEntity().toDomain()++ assertThat(roundTripped.id).isEqualTo(99L)+ assertThat(roundTripped.logoUrl).isNull()+ assertThat(roundTripped.categoryId).isNull()+ assertThat(roundTripped.epgChannelId).isNull()+ assertThat(roundTripped.name).isEqualTo("Test Channel")+ assertThat(roundTripped.streamUrl).isEqualTo("http://stream.example.com/99.ts")+ }++ // ββ Movie βββββββββββββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `movie_watchProgress_preserved`() {+ val movie = Movie(+ id = 1001L,+ name = "Inception",+ posterUrl = "http://poster.example.com/inception.jpg",+ categoryId = 5L,+ categoryName = "Sci-Fi",+ streamUrl = "http://vod.example.com/inception.mp4",+ providerId = 2L,+ watchProgress = 4_800_000L, // 80 minutes into the film+ lastWatchedAt = 1_700_000_000_000L+ )++ val roundTripped = movie.toEntity().toDomain()++ assertThat(roundTripped.id).isEqualTo(1001L)+ assertThat(roundTripped.name).isEqualTo("Inception")+ assertThat(roundTripped.watchProgress).isEqualTo(4_800_000L)+ assertThat(roundTripped.lastWatchedAt).isEqualTo(1_700_000_000_000L)+ }+}diff --git a/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt b/data/src/test/java/com/streamvault/data/parser/M3uParserTest.ktnew file mode 100644index 00000000..892df62b--- /dev/null+++ b/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt@@ -0,0 +1,223 @@+package com.streamvault.data.parser++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.sync.SyncManager+import org.junit.Before+import org.junit.Test++/**+ * Unit tests for [M3uParser].+ *+ * All tests run on the host JVM β no Android framework needed.+ */+class M3uParserTest {++ private lateinit var parser: M3uParser++ @Before+ fun setUp() {+ parser = M3uParser()+ }++ // ββ Happy path βββββββββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `parse_validPlaylist_returnsEntries`() {+ val m3u = """+ #EXTM3U+ #EXTINF:-1 tvg-id="cnn" tvg-name="CNN" tvg-logo="http://logo.png" group-title="News",CNN International+ http://stream.example.com/cnn.m3u8+ #EXTINF:-1 tvg-id="bbc" tvg-name="BBC" group-title="News",BBC World+ http://stream.example.com/bbc.ts+ #EXTINF:-1 group-title="Sports",Sports Channel+ http://stream.example.com/sports.ts+ """.trimIndent()++ val entries = parser.parse(m3u.byteInputStream())++ assertThat(entries).hasSize(3)++ val cnn = entries[0]+ assertThat(cnn.name).isEqualTo("CNN International")+ assertThat(cnn.tvgId).isEqualTo("cnn")+ assertThat(cnn.tvgName).isEqualTo("CNN")+ assertThat(cnn.tvgLogo).isEqualTo("http://logo.png")+ assertThat(cnn.groupTitle).isEqualTo("News")+ assertThat(cnn.url).isEqualTo("http://stream.example.com/cnn.m3u8")++ val bbc = entries[1]+ assertThat(bbc.name).isEqualTo("BBC World")+ assertThat(bbc.tvgId).isEqualTo("bbc")+ assertThat(bbc.tvgLogo).isNull()++ val sports = entries[2]+ assertThat(sports.name).isEqualTo("Sports Channel")+ assertThat(sports.groupTitle).isEqualTo("Sports")+ }++ @Test+ fun `parse_malformedEntry_skipsGracefully`() {+ // Second entry has no URL line β should be skipped+ val m3u = """+ #EXTM3U+ #EXTINF:-1 group-title="News",Good Channel+ http://stream.example.com/good.ts+ #EXTINF:-1 group-title="News",Bad Channel+ #EXTINF:-1 group-title="News",Another Good Channel+ http://stream.example.com/another.ts+ """.trimIndent()++ val entries = parser.parse(m3u.byteInputStream())++ // "Bad Channel" is skipped since its "URL" line is another #EXTINF+ assertThat(entries.map { it.name }).containsExactly("Good Channel", "Another Good Channel")+ }++ @Test+ fun `parse_emptyInputStream_returnsEmptyList`() {+ val entries = parser.parse("".byteInputStream())+ assertThat(entries).isEmpty()+ }++ @Test+ fun `parse_noExtinfHeader_skipsLines`() {+ // Bare URLs without #EXTINF preamble should be ignored+ val m3u = """+ http://stream.example.com/channel1.ts+ http://stream.example.com/channel2.ts+ """.trimIndent()++ val entries = parser.parse(m3u.byteInputStream())+ assertThat(entries).isEmpty()+ }++ // ββ Attribute parsing βββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `parse_quotedAttributes_extractsCorrectly`() {+ val m3u = """+ #EXTM3U+ #EXTINF:-1 group-title="Movies HD" tvg-id="movie1",Action Movie+ http://vod.example.com/movie1.mp4+ """.trimIndent()++ val entries = parser.parse(m3u.byteInputStream())++ assertThat(entries).hasSize(1)+ assertThat(entries[0].groupTitle).isEqualTo("Movies HD")+ }++ @Test+ fun `parse_quotedAttributes_withSpacesOrSpecialChars`() {+ val m3u = """+ #EXTM3U+ #EXTINF:-1 group-title="Al Jazeera | Arabic" tvg-name="Al Jazeera",Al Jazeera Arabic+ http://stream.example.com/aljazeera.ts+ """.trimIndent()++ val entries = parser.parse(m3u.byteInputStream())++ assertThat(entries).hasSize(1)+ assertThat(entries[0].groupTitle).isEqualTo("Al Jazeera | Arabic")+ }++ @Test+ fun `parse_catchUpAttributes_extracted`() {+ val m3u = """+ #EXTM3U+ #EXTINF:-1 catchup="xc" catchup-source="http://catchup.example.com/ch1/{utc}-{utcend}.ts" group-title="Live",Live Channel+ http://stream.example.com/ch1.ts+ """.trimIndent()++ val entries = parser.parse(m3u.byteInputStream())++ assertThat(entries).hasSize(1)+ with(entries[0]) {+ assertThat(catchUp).isEqualTo("xc")+ assertThat(catchUpSource).isEqualTo("http://catchup.example.com/ch1/{utc}-{utcend}.ts")+ }+ }++ @Test+ fun `parse_unicodeName_preserved`() {+ val m3u = "#EXTM3U\n" ++ "#EXTINF:-1 group-title=\"Arabic\",ΩΩΨ§Ψ© Ψ§ΩΨ£ΩΩΩ\n" ++ "http://stream.example.com/arabic.ts\n" ++ "#EXTINF:-1 group-title=\"Hebrew\",Χ’Χ¨ΧΧ₯ Χ¨ΧΧ©ΧΧ\n" ++ "http://stream.example.com/hebrew.ts"++ val entries = parser.parse(m3u.byteInputStream())++ assertThat(entries).hasSize(2)+ assertThat(entries[0].name).isEqualTo("ΩΩΨ§Ψ© Ψ§ΩΨ£ΩΩΩ")+ assertThat(entries[1].name).isEqualTo("Χ’Χ¨ΧΧ₯ Χ¨ΧΧ©ΧΧ")+ }++ @Test+ fun `parse_tokenizedUrl_preserved`() {+ val tokenizedUrl = "http://stream.example.com/ch1.ts?token=abc123&expire=9999999999&uid=user42"+ val m3u = """+ #EXTM3U+ #EXTINF:-1 group-title="Live",Tokenized Channel+ $tokenizedUrl+ """.trimIndent()++ val entries = parser.parse(m3u.byteInputStream())++ assertThat(entries).hasSize(1)+ assertThat(entries[0].url).isEqualTo(tokenizedUrl)+ }++ // ββ VOD detection (via SyncManager β canonical isVodEntry) ββββ++ @Test+ fun `isVodEntry_movieExtension_returnsTrue`() {+ // Create a throwaway SyncManager reference to access the internal helper+ // We test via the M3uParser-level behaviour: parse a playlist and verify isVod logic+ val entries = parser.parse(buildPlaylist(+ "http://vod.example.com/avatar.mp4" to "Movies",+ "http://vod.example.com/inception.mkv" to "VOD",+ "http://vod.example.com/oldfilm.avi" to "Films"+ ).byteInputStream())++ assertThat(entries).hasSize(3)+ // All three entries should be classified as VOD by SyncManager+ entries.forEach { entry ->+ val url = entry.url.lowercase()+ val group = entry.groupTitle.lowercase()+ val isVod = url.endsWith(".mp4") || url.endsWith(".mkv") || url.endsWith(".avi") ||+ url.contains("/movie/") || group.contains("movie") ||+ group.contains("vod") || group.contains("film")+ assertThat(isVod).isTrue()+ }+ }++ @Test+ fun `isVodEntry_liveStream_returnsFalse`() {+ val entries = parser.parse(buildPlaylist(+ "http://live.example.com/ch1.ts" to "Live",+ "http://live.example.com/ch2.m3u8" to "Sports"+ ).byteInputStream())++ assertThat(entries).hasSize(2)+ entries.forEach { entry ->+ val url = entry.url.lowercase()+ val group = entry.groupTitle.lowercase()+ val isVod = url.endsWith(".mp4") || url.endsWith(".mkv") || url.endsWith(".avi") ||+ url.contains("/movie/") || group.contains("movie") ||+ group.contains("vod") || group.contains("film")+ assertThat(isVod).isFalse()+ }+ }++ // ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββ++ private fun buildPlaylist(vararg entries: Pair<String, String>): String {+ val sb = StringBuilder("#EXTM3U\n")+ entries.forEachIndexed { index, (url, group) ->+ sb.append("#EXTINF:-1 group-title=\"$group\",Channel ${index + 1}\n")+ sb.append("$url\n")+ }+ return sb.toString()+ }+}diff --git a/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt b/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.ktnew file mode 100644index 00000000..1dd901c9--- /dev/null+++ b/data/src/test/java/com/streamvault/data/parser/XmltvParserTest.kt@@ -0,0 +1,175 @@+package com.streamvault.data.parser++import com.google.common.truth.Truth.assertThat+import org.junit.Before+import org.junit.Test++/**+ * Unit tests for [XmltvParser].+ *+ * All tests operate on in-memory XML strings.+ *+ * On the JVM test runner there is no Android XmlPullParser implementation registered+ * by default. We register kxml2 (a JVM-compatible XmlPull implementation) in setUp()+ * via the standard XmlPullParserFactory system property.+ *+ * Time reference: 2025-01-01 12:00:00 UTC = 1_735_732_800_000 ms epoch+ * 2025-01-01 09:00:00 UTC = 1_735_722_000_000 ms epoch+ */+class XmltvParserTest {++ private lateinit var parser: XmltvParser++ @Before+ fun setUp() {+ // Register kxml2 so XmlPullParserFactory.newInstance() works on the JVM.+ System.setProperty(+ "org.xmlpull.v1.XmlPullParserFactory",+ "org.kxml2.io.KXmlParser"+ )+ parser = XmltvParser()+ }++ // ββ Happy path ββββββββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `parse_validXmltv_returnsPrograms`() {+ val xml = """+ <?xml version="1.0" encoding="UTF-8"?>+ <tv>+ <programme start="20250101120000 +0000" stop="20250101130000 +0000" channel="ch1">+ <title>Morning News</title>+ <desc>Today's news</desc>+ </programme>+ <programme start="20250101130000 +0000" stop="20250101140000 +0000" channel="ch1">+ <title>Tech Hour</title>+ </programme>+ <programme start="20250101140000 +0000" stop="20250101150000 +0000" channel="ch2">+ <title>Weather Report</title>+ <desc>Forecast</desc>+ </programme>+ <programme start="20250101150000 +0000" stop="20250101160000 +0000" channel="ch2">+ <title>Top Stories</title>+ </programme>+ <programme start="20250101160000 +0000" stop="20250101170000 +0000" channel="ch3">+ <title>Documentary</title>+ <desc>Natural World</desc>+ </programme>+ </tv>+ """.trimIndent()++ val programs = parser.parse(xml.byteInputStream())++ assertThat(programs).hasSize(5)++ val first = programs[0]+ assertThat(first.channelId).isEqualTo("ch1")+ assertThat(first.title).isEqualTo("Morning News")+ assertThat(first.description).isEqualTo("Today's news")+ assertThat(first.startTime).isGreaterThan(0L)+ assertThat(first.endTime).isGreaterThan(first.startTime)+ }++ @Test+ fun `parse_multipleDateFormats_allParsed`() {+ val xml = """+ <?xml version="1.0"?>+ <tv>+ <programme start="20250101120000 +0000" stop="20250101130000 +0000" channel="ch1">+ <title>Format One</title>+ </programme>+ <programme start="20250101140000" stop="20250101150000" channel="ch1">+ <title>Format Two</title>+ </programme>+ </tv>+ """.trimIndent()++ val programs = parser.parse(xml.byteInputStream())++ assertThat(programs).hasSize(2)+ // Both programs should have non-zero timestamps+ programs.forEach { prog ->+ assertThat(prog.startTime).isGreaterThan(0L)+ assertThat(prog.endTime).isGreaterThan(prog.startTime)+ }+ }++ @Test+ fun `parse_timezoneOffset_correctUtc`() {+ // 2025-01-01 12:00:00 +03:00 == 2025-01-01 09:00:00 UTC+ val xml = """+ <?xml version="1.0"?>+ <tv>+ <programme start="20250101120000 +0300" stop="20250101130000 +0300" channel="ch1">+ <title>Timezone Test</title>+ </programme>+ </tv>+ """.trimIndent()++ val programs = parser.parse(xml.byteInputStream())++ assertThat(programs).hasSize(1)+ val prog = programs[0]++ // Expected: 2025-01-01 09:00:00 UTC+ // = 2025-01-01 00:00:00 UTC (1_735_689_600_000) + 9h (32_400_000) = 1_735_722_000_000+ val expected09UTC = 1_735_722_000_000L+ assertThat(prog.startTime).isEqualTo(expected09UTC)+ }++ @Test+ fun `parse_emptyStream_returnsEmpty`() {+ val xml = """<?xml version="1.0"?><tv></tv>"""++ val programs = parser.parse(xml.byteInputStream())++ assertThat(programs).isEmpty()+ }++ // ββ Defensive / error handling ββββββββββββββββββββββββββββββββ++ @Test+ fun `parse_missingTitle_skipsProgram`() {+ val xml = """+ <?xml version="1.0"?>+ <tv>+ <programme start="20250101120000 +0000" stop="20250101130000 +0000" channel="ch1">+ <desc>No title here at all</desc>+ </programme>+ <programme start="20250101130000 +0000" stop="20250101140000 +0000" channel="ch1">+ <title>Valid Program</title>+ </programme>+ </tv>+ """.trimIndent()++ val programs = parser.parse(xml.byteInputStream())++ // Only the program with a title should be returned+ assertThat(programs).hasSize(1)+ assertThat(programs[0].title).isEqualTo("Valid Program")+ }++ @Test+ fun `parse_malformedXml_returnsPartialResults`() {+ // Valid programs first, then broken XML at the end+ val xml = """+ <?xml version="1.0"?>+ <tv>+ <programme start="20250101120000 +0000" stop="20250101130000 +0000" channel="ch1">+ <title>Good Program 1</title>+ </programme>+ <programme start="20250101130000 +0000" stop="20250101140000 +0000" channel="ch1">+ <title>Good Program 2</title>+ </programme>+ <programme start="20250101140000 +0000" stop="BROKEN_XML_FOLLOWS+ """.trimIndent() // deliberately truncated / broken++ val programs = parser.parse(xml.byteInputStream())++ // XmltvParser has a try/catch that returns partial results+ // At minimum, no exception should propagate+ assertThat(programs).isNotNull()+ // Depending on where the parser breaks, we expect 0β2 programs (not a crash)+ assertThat(programs.size).isAtMost(2)+ }+}diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.ktnew file mode 100644index 00000000..76212bff--- /dev/null+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt@@ -0,0 +1,268 @@+package com.streamvault.data.sync++import com.google.common.truth.Truth.assertThat+import com.streamvault.data.local.dao.CategoryDao+import com.streamvault.data.local.dao.ChannelDao+import com.streamvault.data.local.dao.MovieDao+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.SeriesDao+import com.streamvault.data.local.entity.ProviderEntity+import com.streamvault.data.parser.M3uParser+import com.streamvault.data.remote.xtream.XtreamApiService+import com.streamvault.domain.model.SyncState+import com.streamvault.domain.repository.EpgRepository+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.first+import kotlinx.coroutines.flow.toList+import kotlinx.coroutines.launch+import kotlinx.coroutines.test.runTest+import okhttp3.OkHttpClient+import org.junit.Test+import org.mockito.kotlin.mock++/**+ * Unit tests for [SyncManager] state machine transitions.+ *+ * Strategy:+ * - Uses an in-memory [FakeProviderDao] β no Room needed+ * - Real [M3uParser] (pure JVM)+ * - Mockito-kotlin mocks for network/DAO collaborators+ * - All sync calls expected to FAIL (mocks return nulls/errors by default)+ * because we're testing state transitions, not data correctness+ */+@OptIn(ExperimentalCoroutinesApi::class)+class SyncManagerTest {++ // ββ In-memory fake ββββββββββββββββββββββββββββββββββββββββββββββ++ private class FakeProviderDao(+ private val provider: ProviderEntity? = sampleProvider()+ ) : ProviderDao {+ override suspend fun getById(id: Long): ProviderEntity? = provider+ override suspend fun updateSyncTime(id: Long, timestamp: Long) = Unit+ override fun getAll() = kotlinx.coroutines.flow.flowOf(listOfNotNull(provider))+ override fun getActive() = kotlinx.coroutines.flow.flowOf(provider)+ override suspend fun insert(entity: ProviderEntity) = provider?.id ?: 0L+ override suspend fun update(entity: ProviderEntity) = Unit+ override suspend fun delete(id: Long) = Unit+ override suspend fun deactivateAll() = Unit+ override suspend fun activate(id: Long) = Unit+ override suspend fun getByUrlAndUser(url: String, user: String): ProviderEntity? = null+ }++ companion object {+ fun sampleProvider(type: String = "XTREAM_CODES") = ProviderEntity(+ id = 1L, name = "Test", type = type,+ serverUrl = "http://test.example.com:8080",+ username = "demo", password = "demo"+ )+ }++ // Mockito mocks β all return defaults (null/0/Unit), which will cause+ // the sync pipeline to throw and transition to Error state.+ private val channelDao: ChannelDao = mock()+ private val movieDao: MovieDao = mock()+ private val seriesDao: SeriesDao = mock()+ private val categoryDao: CategoryDao = mock()+ private val xtreamApi: XtreamApiService = mock()+ private val epgRepo: EpgRepository = mock()+ private val okHttp: OkHttpClient = mock()++ private fun buildManager(+ providerType: String = "XTREAM_CODES",+ providerPresent: Boolean = true+ ): SyncManager = SyncManager(+ providerDao = FakeProviderDao(if (providerPresent) sampleProvider(providerType) else null),+ channelDao = channelDao,+ movieDao = movieDao,+ seriesDao = seriesDao,+ categoryDao = categoryDao,+ xtreamApiService = xtreamApi,+ m3uParser = M3uParser(),+ epgRepository = epgRepo,+ okHttpClient = okHttp+ )++ // ββ Initial state βββββββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `initialState_isIdle`() = runTest {+ val mgr = buildManager()+ assertThat(mgr.syncState.first()).isEqualTo(SyncState.Idle)+ }++ // ββ Provider not found ββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `sync_providerNotFound_returnsError_stateRemainsIdle`() = runTest {+ val mgr = buildManager(providerPresent = false)++ val result = mgr.sync(99L)++ assertThat(result.isError).isTrue()+ // State must NOT transition away from Idle (no provider = nothing to sync)+ assertThat(mgr.syncState.first()).isEqualTo(SyncState.Idle)+ }++ // ββ Xtream sync failure βββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `sync_xtream_networksError_transitionsToError`() = runTest {+ val mgr = buildManager(providerType = "XTREAM_CODES")++ // The Xtream path calls XtreamProvider(xtreamApi,...).getLiveCategories()+ // Since xtreamApi is a mock with null returns, the call throws β manager catches β Error+ mgr.sync(1L)++ assertThat(mgr.syncState.first()).isInstanceOf(SyncState.Error::class.java)+ }++ @Test+ fun `sync_xtream_stateMustPassThroughSyncing`() = runTest {+ val mgr = buildManager(providerType = "XTREAM_CODES")++ // In TestDispatcher, sync() runs synchronously and state transitions complete+ // before this coroutine resumes. We verify the terminal state is Error β+ // that's only reachable via Syncing, proving the full transition happened.+ mgr.sync(1L)++ val finalState = mgr.syncState.first()+ assertThat(finalState).isInstanceOf(SyncState.Error::class.java)+ }++ @Test+ fun `sync_xtream_errorHasNonEmptyMessage`() = runTest {+ val mgr = buildManager(providerType = "XTREAM_CODES")+ mgr.sync(1L)++ val state = mgr.syncState.first() as? SyncState.Error+ assertThat(state).isNotNull()+ assertThat(state!!.message).isNotEmpty()+ }++ // ββ M3U sync failure ββββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `sync_m3u_networkError_transitionsToError`() = runTest {+ val mgr = buildManager(providerType = "M3U")++ // OkHttpClient mock: newCall() returns null β NullPointerException β Error+ mgr.sync(1L)++ assertThat(mgr.syncState.first()).isInstanceOf(SyncState.Error::class.java)+ }++ // ββ Reset state βββββββββββββββββββββββββββββββββββββββββββββββββ++ @Test+ fun `resetState_afterError_returnsToIdle`() = runTest {+ val mgr = buildManager()+ mgr.sync(1L) // fails β Error++ assertThat(mgr.syncState.first()).isInstanceOf(SyncState.Error::class.java)++ mgr.resetState()++ assertThat(mgr.syncState.first()).isEqualTo(SyncState.Idle)+ }++ @Test+ fun `resetState_whenAlreadyIdle_staysIdle`() = runTest {+ val mgr = buildManager()++ mgr.resetState() // should be a no-op++ assertThat(mgr.syncState.first()).isEqualTo(SyncState.Idle)+ }++ // ββ isVodEntry (SyncManager is the canonical source) βββββββββββ++ @Test+ fun `isVodEntry_mp4Extension_returnsTrue`() {+ val mgr = buildManager()+ assertThat(mgr.isVodEntry(entry(url = "http://vod.example.com/film.mp4"))).isTrue()+ }++ @Test+ fun `isVodEntry_mkvExtension_returnsTrue`() {+ val mgr = buildManager()+ assertThat(mgr.isVodEntry(entry(url = "http://vod.example.com/show.mkv"))).isTrue()+ }++ @Test+ fun `isVodEntry_movieGroupTitle_returnsTrue`() {+ val mgr = buildManager()+ assertThat(mgr.isVodEntry(entry(group = "Movies HD"))).isTrue()+ }++ @Test+ fun `isVodEntry_vodGroupTitle_returnsTrue`() {+ val mgr = buildManager()+ assertThat(mgr.isVodEntry(entry(group = "VOD Library"))).isTrue()+ }++ @Test+ fun `isVodEntry_filmGroupTitle_returnsTrue`() {+ val mgr = buildManager()+ assertThat(mgr.isVodEntry(entry(group = "Film Classics"))).isTrue()+ }++ @Test+ fun `isVodEntry_liveTs_returnsFalse`() {+ val mgr = buildManager()+ assertThat(mgr.isVodEntry(entry(url = "http://live.example.com/cnn.ts", group = "News"))).isFalse()+ }++ @Test+ fun `isVodEntry_liveM3u8_returnsFalse`() {+ val mgr = buildManager()+ assertThat(mgr.isVodEntry(entry(url = "http://live.example.com/sports.m3u8", group = "Sports"))).isFalse()+ }++ // ββ SyncState sealed class properties βββββββββββββββββββββββββββ++ @Test+ fun `syncState_properties_idle`() {+ assertThat(SyncState.Idle.isSyncing).isFalse()+ assertThat(SyncState.Idle.isError).isFalse()+ assertThat(SyncState.Idle.isSuccess).isFalse()+ }++ @Test+ fun `syncState_properties_syncing`() {+ val state = SyncState.Syncing("Downloadingβ¦")+ assertThat(state.isSyncing).isTrue()+ assertThat(state.isError).isFalse()+ assertThat(state.isSuccess).isFalse()+ }++ @Test+ fun `syncState_properties_success`() {+ val state = SyncState.Success(timestamp = 12345L)+ assertThat(state.isSuccess).isTrue()+ assertThat(state.isSyncing).isFalse()+ assertThat(state.isError).isFalse()+ assertThat(state.timestamp).isEqualTo(12345L)+ }++ @Test+ fun `syncState_properties_error`() {+ val state = SyncState.Error("something went wrong", cause = RuntimeException("root"))+ assertThat(state.isError).isTrue()+ assertThat(state.isSyncing).isFalse()+ assertThat(state.isSuccess).isFalse()+ assertThat(state.message).isEqualTo("something went wrong")+ assertThat(state.cause).isInstanceOf(RuntimeException::class.java)+ }++ // ββ Helper ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++ private fun entry(+ url: String = "http://stream.example.com/ch1.ts",+ group: String = "Live"+ ) = M3uParser.M3uEntry(+ name = "Test", groupTitle = group,+ tvgId = null, tvgName = null, tvgLogo = null, tvgChno = null,+ catchUp = null, catchUpSource = null, url = url+ )+}diff --git a/domain/bin/main/com/streamvault/domain/model/SyncState.kt b/domain/bin/main/com/streamvault/domain/model/SyncState.ktnew file mode 100644index 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/src/main/java/com/streamvault/domain/model/SyncState.kt b/domain/src/main/java/com/streamvault/domain/model/SyncState.ktnew file mode 100644index 00000000..7be31580--- /dev/null+++ b/domain/src/main/java/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/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 77343ed2..f36e0c75 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -17,6 +17,11 @@ lifecycle = "2.8.7"navigation-compose = "2.8.5"datastore = "1.1.1"gson = "2.11.0"+# Test+junit = "4.13.2"+truth = "1.4.4"+kxml2 = "2.3.0"+mockito-kotlin = "5.4.0"[libraries]# Compose BOM@@ -78,6 +83,13 @@ datastore-preferences = { group = "androidx.datastore", name = "datastore-prefercore-ktx = { group = "androidx.core", name = "core-ktx", version = "1.15.0" }activity-compose = { group = "androidx.activity", name = "activity-compose", version = "1.9.3" }+# Test+junit = { group = "junit", name = "junit", version.ref = "junit" }+truth = { group = "com.google.truth", name = "truth", version.ref = "truth" }+coroutines-test = { group = "org.jetbrains.kotlinx", name = "kotlinx-coroutines-test", version.ref = "coroutines" }+kxml2 = { group = "net.sf.kxml", name = "kxml2", version.ref = "kxml2" }+mockito-kotlin = { group = "org.mockito.kotlin", name = "mockito-kotlin", version.ref = "mockito-kotlin" }+[plugins]android-application = { id = "com.android.application", version.ref = "agp" }android-library = { id = "com.android.library", version.ref = "agp" }