StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
Build background DVR recording system
David Nashash6603bd4ef3ef
diff --git a/app/build.gradle.kts b/app/build.gradle.ktsindex 0cf69011..a4af17b3 100644--- a/app/build.gradle.kts+++ b/app/build.gradle.kts@@ -146,6 +146,7 @@ dependencies {// Coreimplementation(libs.core.ktx)+ implementation(libs.documentfile)implementation(libs.coroutines.android)implementation(libs.appcompat)implementation(libs.mediarouter)diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 70e31540..0c0dbd56 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -8,6 +8,9 @@<uses-permission android:name="com.android.providers.tv.permission.READ_EPG_DATA" /><uses-permission android:name="com.android.providers.tv.permission.WRITE_EPG_DATA" /><uses-permission android:name="android.permission.BIND_TV_INPUT" />+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />+ <uses-permission android:name="android.permission.FOREGROUND_SERVICE" />+ <uses-permission android:name="android.permission.SCHEDULE_EXACT_ALARM" /><uses-featureandroid:name="android.software.leanback"diff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.ktindex b02aee0f..98017ac5 100644--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt@@ -25,6 +25,7 @@ import androidx.work.ExistingPeriodicWorkPolicyimport androidx.work.NetworkTypeimport androidx.work.PeriodicWorkRequestBuilderimport androidx.work.WorkManager+import com.streamvault.data.manager.recording.RecordingReconcileWorkerimport javax.inject.Inject@HiltAndroidApp@@ -62,6 +63,9 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {ExistingPeriodicWorkPolicy.KEEP,gcWorkRequest)++ RecordingReconcileWorker.enqueuePeriodic(this)+ RecordingReconcileWorker.enqueueOneShot(this)}override fun onTerminate() {diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.ktindex 2621fb80..ef124f07 100644--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt@@ -52,7 +52,8 @@ object DatabaseModule {StreamVaultDatabase.MIGRATION_24_25,StreamVaultDatabase.MIGRATION_25_26,StreamVaultDatabase.MIGRATION_26_27,- StreamVaultDatabase.MIGRATION_27_28+ StreamVaultDatabase.MIGRATION_27_28,+ StreamVaultDatabase.MIGRATION_28_29)// NOTE: fallbackToDestructiveMigration() intentionally removed.// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.@@ -78,4 +79,7 @@ object DatabaseModule {@Provides fun provideEpgChannelDao(db: StreamVaultDatabase): EpgChannelDao = db.epgChannelDao()@Provides fun provideEpgProgrammeDao(db: StreamVaultDatabase): EpgProgrammeDao = db.epgProgrammeDao()@Provides fun provideChannelEpgMappingDao(db: StreamVaultDatabase): ChannelEpgMappingDao = db.channelEpgMappingDao()+ @Provides fun provideRecordingScheduleDao(db: StreamVaultDatabase): RecordingScheduleDao = db.recordingScheduleDao()+ @Provides fun provideRecordingRunDao(db: StreamVaultDatabase): RecordingRunDao = db.recordingRunDao()+ @Provides fun provideRecordingStorageDao(db: StreamVaultDatabase): RecordingStorageDao = db.recordingStorageDao()}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 9a855a02..533ae91b 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@@ -50,6 +50,7 @@ import androidx.compose.material3.OutlinedButtonimport androidx.compose.material3.HorizontalDividerimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts+import androidx.documentfile.provider.DocumentFileimport com.streamvault.app.ui.interaction.TvClickableSurfaceimport com.streamvault.app.ui.interaction.TvButtonimport com.streamvault.app.ui.interaction.TvIconButton@@ -76,8 +77,10 @@ import com.streamvault.domain.model.DecoderModeimport com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.ProviderStatus+import com.streamvault.domain.model.RecordingFailureCategoryimport com.streamvault.domain.model.RecordingItemimport com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingSourceTypeimport com.streamvault.domain.model.RecordingStatusimport com.streamvault.app.ui.screens.settings.ProviderDiagnosticsUiModelimport kotlinx.coroutines.launch@@ -202,6 +205,9 @@ fun SettingsScreen(}var showEthernetQualityDialog by rememberSaveable { mutableStateOf(false) }var showClearHistoryDialog by rememberSaveable { mutableStateOf(false) }+ var showRecordingPatternDialog by rememberSaveable { mutableStateOf(false) }+ var showRecordingRetentionDialog by rememberSaveable { mutableStateOf(false) }+ var showRecordingConcurrencyDialog by rememberSaveable { mutableStateOf(false) }var categorySortDialogType by rememberSaveable { mutableStateOf<String?>(null) }var selectedCategory by rememberSaveable { mutableStateOf(0) }var pinError by rememberSaveable { mutableStateOf<String?>(null) }@@ -220,6 +226,22 @@ fun SettingsScreen(uri?.let { viewModel.inspectBackup(it.toString()) }}+ val recordingFolderLauncher = rememberLauncherForActivityResult(+ contract = ActivityResultContracts.OpenDocumentTree()+ ) { uri ->+ uri?.let {+ runCatching {+ context.contentResolver.takePersistableUriPermission(+ it,+ android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION or+ android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION+ )+ }+ val displayName = DocumentFile.fromTreeUri(context, it)?.name+ viewModel.updateRecordingFolder(it.toString(), displayName)+ }+ }+val uriHandler = LocalUriHandler.currentLaunchedEffect(uiState.userMessage) {@@ -671,11 +693,21 @@ fun SettingsScreen(else if (selectedCategory == 3) {item {RecordingOverviewCard(+ treeLabel = uiState.recordingStorageState.displayName,outputDirectory = uiState.recordingStorageState.outputDirectory,availableBytes = uiState.recordingStorageState.availableBytes,isWritable = uiState.recordingStorageState.isWritable,activeCount = uiState.recordingItems.count { it.status == RecordingStatus.RECORDING },- scheduledCount = uiState.recordingItems.count { it.status == RecordingStatus.SCHEDULED }+ scheduledCount = uiState.recordingItems.count { it.status == RecordingStatus.SCHEDULED },+ fileNamePattern = uiState.recordingStorageState.fileNamePattern,+ retentionDays = uiState.recordingStorageState.retentionDays,+ maxSimultaneousRecordings = uiState.recordingStorageState.maxSimultaneousRecordings,+ onChooseFolder = { recordingFolderLauncher.launch(null) },+ onUseAppStorage = { viewModel.updateRecordingFolder(null, null) },+ onChangePattern = { showRecordingPatternDialog = true },+ onChangeRetention = { showRecordingRetentionDialog = true },+ onChangeConcurrency = { showRecordingConcurrencyDialog = true },+ onRepairSchedule = { viewModel.reconcileRecordings() })}if (uiState.recordingItems.isEmpty()) {@@ -701,7 +733,9 @@ fun SettingsScreen(item = item,onStop = { viewModel.stopRecording(item.id) },onCancel = { viewModel.cancelRecording(item.id) },- onDelete = { viewModel.deleteRecording(item.id) }+ onDelete = { viewModel.deleteRecording(item.id) },+ onRetry = { viewModel.retryRecording(item.id) },+ onToggleSchedule = { enabled -> viewModel.setRecordingScheduleEnabled(item.id, enabled) })}}@@ -1561,6 +1595,62 @@ fun SettingsScreen()}+ if (showRecordingPatternDialog) {+ SimpleTextValueDialog(+ title = stringResource(R.string.settings_recording_pattern_title),+ subtitle = stringResource(R.string.settings_recording_pattern_hint),+ initialValue = uiState.recordingStorageState.fileNamePattern,+ onDismiss = { showRecordingPatternDialog = false },+ onConfirm = { pattern ->+ viewModel.updateRecordingFileNamePattern(pattern)+ showRecordingPatternDialog = false+ }+ )+ }++ if (showRecordingRetentionDialog) {+ val retentionOptions = listOf<Int?>(null, 7, 14, 30, 60, 90)+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_recording_retention_title),+ onDismiss = { showRecordingRetentionDialog = false }+ ) {+ retentionOptions.forEachIndexed { index, days ->+ LevelOption(+ level = index,+ text = if (days == null) {+ stringResource(R.string.settings_recording_retention_keep_all)+ } else {+ stringResource(R.string.settings_recording_retention_days, days)+ },+ currentLevel = if (days == uiState.recordingStorageState.retentionDays) index else -1,+ onSelect = {+ viewModel.updateRecordingRetentionDays(days)+ showRecordingRetentionDialog = false+ }+ )+ }+ }+ }++ if (showRecordingConcurrencyDialog) {+ PremiumSelectionDialog(+ title = stringResource(R.string.settings_recording_concurrency_title),+ onDismiss = { showRecordingConcurrencyDialog = false }+ ) {+ (1..4).forEach { value ->+ LevelOption(+ level = value,+ text = value.toString(),+ currentLevel = if (value == uiState.recordingStorageState.maxSimultaneousRecordings) value else -1,+ onSelect = {+ viewModel.updateRecordingMaxSimultaneous(value)+ showRecordingConcurrencyDialog = false+ }+ )+ }+ }+ }+if (showClearHistoryDialog) {androidx.compose.material3.AlertDialog(onDismissRequest = { showClearHistoryDialog = false },@@ -3466,11 +3556,21 @@ private fun BackupToggleRow(@Composableprivate fun RecordingOverviewCard(+ treeLabel: String?,outputDirectory: String?,availableBytes: Long?,isWritable: Boolean,activeCount: Int,- scheduledCount: Int+ scheduledCount: Int,+ fileNamePattern: String,+ retentionDays: Int?,+ maxSimultaneousRecordings: Int,+ onChooseFolder: () -> Unit,+ onUseAppStorage: () -> Unit,+ onChangePattern: () -> Unit,+ onChangeRetention: () -> Unit,+ onChangeConcurrency: () -> Unit,+ onRepairSchedule: () -> Unit) {TvClickableSurface(onClick = {},@@ -3497,6 +3597,13 @@ private fun RecordingOverviewCard(style = MaterialTheme.typography.bodySmall,color = OnSurfaceDim)+ treeLabel?.takeIf { it.isNotBlank() }?.let {+ Text(+ text = it,+ style = MaterialTheme.typography.bodySmall,+ color = Secondary+ )+ }Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {SettingsOverviewStat(label = stringResource(R.string.settings_recording_active_label),@@ -3519,6 +3626,33 @@ private fun RecordingOverviewCard(style = MaterialTheme.typography.bodySmall,color = if (isWritable) Primary else ErrorColor)+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_pattern_title),+ value = fileNamePattern+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_retention_title),+ value = retentionDays?.let {+ stringResource(R.string.settings_recording_retention_days, it)+ } ?: stringResource(R.string.settings_recording_retention_keep_all)+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_concurrency_title),+ value = maxSimultaneousRecordings.toString()+ )+ }+ Row(+ horizontalArrangement = Arrangement.spacedBy(10.dp),+ modifier = Modifier.fillMaxWidth()+ ) {+ RecordingActionButton(stringResource(R.string.settings_recording_choose_folder), Primary, onChooseFolder)+ RecordingActionButton(stringResource(R.string.settings_recording_use_app_storage), Secondary, onUseAppStorage)+ RecordingActionButton(stringResource(R.string.settings_recording_pattern_title), OnBackground, onChangePattern)+ RecordingActionButton(stringResource(R.string.settings_recording_retention_title), OnBackground, onChangeRetention)+ RecordingActionButton(stringResource(R.string.settings_recording_concurrency_title), OnBackground, onChangeConcurrency)+ RecordingActionButton(stringResource(R.string.settings_recording_reconcile), Secondary, onRepairSchedule)+ }}}}@@ -3528,7 +3662,9 @@ private fun RecordingItemCard(item: RecordingItem,onStop: () -> Unit,onCancel: () -> Unit,- onDelete: () -> Unit+ onDelete: () -> Unit,+ onRetry: () -> Unit,+ onToggleSchedule: (Boolean) -> Unit) {Surface(modifier = Modifier.fillMaxWidth(),@@ -3589,6 +3725,44 @@ private fun RecordingItemCard(item.failureReason?.takeIf { it.isNotBlank() }?.let { reason ->Text(reason, style = MaterialTheme.typography.bodySmall, color = ErrorColor)}+ Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_source_label),+ value = formatRecordingSourceType(item.sourceType)+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_bytes_label),+ value = formatBytes(item.bytesWritten)+ )+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_speed_label),+ value = if (item.averageThroughputBytesPerSecond > 0L) {+ "${formatBytes(item.averageThroughputBytesPerSecond)}/s"+ } else {+ "–"+ }+ )+ if (item.retryCount > 0) {+ RecordingMetaPill(+ label = stringResource(R.string.settings_recording_retry_count_label),+ value = item.retryCount.toString()+ )+ }+ }+ item.outputDisplayPath?.takeIf { it.isNotBlank() }?.let { output ->+ Text(+ text = "${stringResource(R.string.settings_recording_output_label)}: $output",+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim+ )+ }+ if (item.failureCategory != RecordingFailureCategory.NONE) {+ Text(+ text = "${stringResource(R.string.settings_recording_failure_label)}: ${formatRecordingFailureCategory(item.failureCategory)}",+ style = MaterialTheme.typography.bodySmall,+ color = ErrorColor+ )+ }Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {if (item.status == RecordingStatus.RECORDING) {TvClickableSurface(@@ -3607,6 +3781,23 @@ private fun RecordingItemCard(}}if (item.status == RecordingStatus.SCHEDULED) {+ TvClickableSurface(+ onClick = { onToggleSchedule(!item.scheduleEnabled) },+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Secondary.copy(alpha = 0.16f),+ focusedContainerColor = Secondary.copy(alpha = 0.3f)+ )+ ) {+ Text(+ text = stringResource(+ if (item.scheduleEnabled) R.string.settings_recording_disable+ else R.string.settings_recording_enable+ ),+ color = Secondary,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)+ )+ }TvClickableSurface(onClick = onCancel,shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),@@ -3623,6 +3814,22 @@ private fun RecordingItemCard(}}if (item.status == RecordingStatus.COMPLETED || item.status == RecordingStatus.FAILED || item.status == RecordingStatus.CANCELLED) {+ if (item.status == RecordingStatus.FAILED) {+ TvClickableSurface(+ onClick = onRetry,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Primary.copy(alpha = 0.16f),+ focusedContainerColor = Primary.copy(alpha = 0.3f)+ )+ ) {+ Text(+ text = stringResource(R.string.settings_recording_retry),+ color = Primary,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)+ )+ }+ }TvClickableSurface(onClick = onDelete,shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),@@ -4061,6 +4268,94 @@ private fun formatPlaybackSpeedLabel(speed: Float): String {}}+@Composable+private fun RecordingMetaPill(label: String, value: String) {+ Column(+ modifier = Modifier+ .background(Color.White.copy(alpha = 0.05f), RoundedCornerShape(10.dp))+ .padding(horizontal = 10.dp, vertical = 8.dp)+ ) {+ Text(text = label, style = MaterialTheme.typography.labelSmall, color = OnSurfaceDim)+ Text(text = value, style = MaterialTheme.typography.bodySmall, color = OnBackground)+ }+}++@Composable+private fun RecordingActionButton(label: String, accent: Color, onClick: () -> Unit) {+ TvClickableSurface(+ onClick = onClick,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(8.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = accent.copy(alpha = 0.14f),+ focusedContainerColor = accent.copy(alpha = 0.28f)+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f)+ ) {+ Text(+ text = label,+ color = accent,+ style = MaterialTheme.typography.labelMedium,+ modifier = Modifier.padding(horizontal = 14.dp, vertical = 10.dp)+ )+ }+}++@Composable+private fun SimpleTextValueDialog(+ title: String,+ subtitle: String,+ initialValue: String,+ onDismiss: () -> Unit,+ onConfirm: (String) -> Unit+) {+ var value by remember(initialValue) { mutableStateOf(initialValue) }+ PremiumDialog(+ title = title,+ subtitle = subtitle,+ onDismissRequest = onDismiss,+ widthFraction = 0.58f,+ content = {+ EpgSourceTextField(+ value = value,+ onValueChange = { value = it },+ placeholder = initialValue+ )+ },+ footer = {+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss+ )+ PremiumDialogActionButton(+ label = stringResource(R.string.settings_save),+ onClick = { onConfirm(value.trim()) }+ )+ }+ }+ )+}++private fun formatRecordingSourceType(sourceType: RecordingSourceType): String = when (sourceType) {+ RecordingSourceType.TS -> "TS"+ RecordingSourceType.HLS -> "HLS"+ RecordingSourceType.DASH -> "DASH"+ RecordingSourceType.UNKNOWN -> "Auto"+}++private fun formatRecordingFailureCategory(category: RecordingFailureCategory): String = when (category) {+ RecordingFailureCategory.NONE -> "None"+ RecordingFailureCategory.NETWORK -> "Network"+ RecordingFailureCategory.STORAGE -> "Storage"+ RecordingFailureCategory.AUTH -> "Auth"+ RecordingFailureCategory.TOKEN_EXPIRED -> "Token"+ RecordingFailureCategory.DRM_UNSUPPORTED -> "DRM"+ RecordingFailureCategory.FORMAT_UNSUPPORTED -> "Format"+ RecordingFailureCategory.SCHEDULE_CONFLICT -> "Conflict"+ RecordingFailureCategory.PROVIDER_LIMIT -> "Connection limit"+ RecordingFailureCategory.UNKNOWN -> "Unknown"+}+private fun playerTimeoutOptions(): List<Int> = listOf(2, 3, 4, 5, 6, 8, 10, 15, 20, 30)private fun formatDecoderModeLabel(mode: DecoderMode, context: android.content.Context): String {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.ktindex dafe36a2..a199c1fa 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsViewModel.kt@@ -31,6 +31,7 @@ import com.streamvault.domain.model.Providerimport com.streamvault.domain.model.ProviderStatusimport com.streamvault.domain.model.ProviderTypeimport com.streamvault.domain.model.RecordingItem+import com.streamvault.domain.model.RecordingStorageConfigimport com.streamvault.domain.model.RecordingStorageStateimport com.streamvault.domain.model.EpgResolutionSummaryimport com.streamvault.domain.model.Result@@ -1244,6 +1245,150 @@ class SettingsViewModel @Inject constructor(}}+ fun retryRecording(recordingId: String) {+ viewModelScope.launch {+ val result = recordingManager.retryRecording(recordingId)+ _uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_retry_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_retry_started)+ }+ )+ }+ }+ }++ fun setRecordingScheduleEnabled(recordingId: String, enabled: Boolean) {+ viewModelScope.launch {+ val result = recordingManager.setScheduleEnabled(recordingId, enabled)+ _uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_schedule_toggle_failed, result.message)+ } else {+ appContext.getString(+ if (enabled) R.string.settings_recording_schedule_enabled+ else R.string.settings_recording_schedule_disabled+ )+ }+ )+ }+ }+ }++ fun reconcileRecordings() {+ viewModelScope.launch {+ val result = recordingManager.reconcileRecordingState()+ _uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_reconcile_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_reconcile_complete)+ }+ )+ }+ }+ }++ fun updateRecordingFolder(treeUri: String?, displayName: String?) {+ viewModelScope.launch {+ val current = _uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = treeUri,+ displayName = displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ )+ )+ _uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_storage_update_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_storage_updated)+ }+ )+ }+ }+ }++ fun updateRecordingFileNamePattern(pattern: String) {+ viewModelScope.launch {+ val current = _uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = pattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ )+ )+ _uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_pattern_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_pattern_saved)+ }+ )+ }+ }+ }++ fun updateRecordingRetentionDays(retentionDays: Int?) {+ viewModelScope.launch {+ val current = _uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = retentionDays,+ maxSimultaneousRecordings = current.maxSimultaneousRecordings+ )+ )+ _uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_retention_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_retention_saved)+ }+ )+ }+ }+ }++ fun updateRecordingMaxSimultaneous(maxSimultaneousRecordings: Int) {+ viewModelScope.launch {+ val current = _uiState.value.recordingStorageState+ val result = recordingManager.updateStorageConfig(+ RecordingStorageConfig(+ treeUri = current.treeUri,+ displayName = current.displayName,+ fileNamePattern = current.fileNamePattern,+ retentionDays = current.retentionDays,+ maxSimultaneousRecordings = maxSimultaneousRecordings+ )+ )+ _uiState.update {+ it.copy(+ userMessage = if (result is Result.Error) {+ appContext.getString(R.string.settings_recording_concurrency_failed, result.message)+ } else {+ appContext.getString(R.string.settings_recording_concurrency_saved)+ }+ )+ }+ }+ }+// ── EPG Source Management ────────────────────────────────────────fun loadEpgSources() {diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex b1a5d8fd..5881bce3 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -583,6 +583,41 @@<string name="settings_recording_stop_failed">Stop failed: %1$s</string><string name="settings_recording_cancel_failed">Cancel failed: %1$s</string><string name="settings_recording_delete_failed">Delete failed: %1$s</string>+ <string name="settings_recording_retry">Retry</string>+ <string name="settings_recording_enable">Enable</string>+ <string name="settings_recording_disable">Disable</string>+ <string name="settings_recording_retry_started">Recording retry scheduled</string>+ <string name="settings_recording_retry_failed">Retry failed: %1$s</string>+ <string name="settings_recording_schedule_enabled">Recording schedule enabled</string>+ <string name="settings_recording_schedule_disabled">Recording schedule disabled</string>+ <string name="settings_recording_schedule_toggle_failed">Schedule update failed: %1$s</string>+ <string name="settings_recording_reconcile">Repair Schedule</string>+ <string name="settings_recording_reconcile_complete">Recording schedule repaired</string>+ <string name="settings_recording_reconcile_failed">Repair failed: %1$s</string>+ <string name="settings_recording_choose_folder">Choose Folder</string>+ <string name="settings_recording_use_app_storage">Use App Storage</string>+ <string name="settings_recording_storage_updated">Recording storage updated</string>+ <string name="settings_recording_storage_update_failed">Storage update failed: %1$s</string>+ <string name="settings_recording_pattern_title">Filename Pattern</string>+ <string name="settings_recording_pattern_summary">%1$s</string>+ <string name="settings_recording_pattern_saved">Filename pattern saved</string>+ <string name="settings_recording_pattern_failed">Filename pattern update failed: %1$s</string>+ <string name="settings_recording_retention_title">Retention Policy</string>+ <string name="settings_recording_retention_keep_all">Keep until deleted</string>+ <string name="settings_recording_retention_days">%1$d days</string>+ <string name="settings_recording_retention_saved">Retention policy saved</string>+ <string name="settings_recording_retention_failed">Retention policy update failed: %1$s</string>+ <string name="settings_recording_concurrency_title">Max Simultaneous Recordings</string>+ <string name="settings_recording_concurrency_saved">Recording concurrency saved</string>+ <string name="settings_recording_concurrency_failed">Concurrency update failed: %1$s</string>+ <string name="settings_recording_source_label">Source</string>+ <string name="settings_recording_output_label">Output</string>+ <string name="settings_recording_bytes_label">Written</string>+ <string name="settings_recording_speed_label">Avg Speed</string>+ <string name="settings_recording_failure_label">Failure</string>+ <string name="settings_recording_retry_count_label">Retries</string>+ <string name="settings_recording_pattern_hint">Use tokens like ChannelName, ProgramTitle, yyyy-MM-dd_HH-mm</string>+ <string name="settings_save">Save</string><string name="settings_capability_xtream_with_epg">Xtream source with XMLTV guide support and on-demand guide fallback. Catch-up is available when the provider exposes replay streams.</string><string name="settings_capability_xtream_without_epg">Xtream source with on-demand guide fallback. Catch-up depends on provider replay support.</string><string name="settings_capability_m3u_with_epg">M3U source with XMLTV guide. Archive support depends on provider stream templates.</string>diff --git a/data/build.gradle.kts b/data/build.gradle.ktsindex 89fcdb6b..bbf46672 100644--- a/data/build.gradle.kts+++ b/data/build.gradle.kts@@ -79,6 +79,7 @@ dependencies {// Coreimplementation(libs.core.ktx)+ implementation(libs.documentfile)// Unit teststestImplementation(libs.junit)diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/29.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/29.jsonnew file mode 100644index 00000000..8b0deab1--- /dev/null+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/29.json@@ -0,0 +1,3496 @@+{+ "formatVersion": 1,+ "database": {+ "version": 29,+ "identityHash": "accec725df1d6dc8d8668907cc7d2529",+ "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, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `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"+ },+ {+ "fieldPath": "apiVersion",+ "columnName": "api_version",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "allowedOutputFormatsJson",+ "columnName": "allowed_output_formats_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSyncMode",+ "columnName": "epg_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "xtreamFastSyncEnabled",+ "columnName": "xtream_fast_sync_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "m3uVodClassificationEnabled",+ "columnName": "m3u_vod_classification_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "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`)"+ }+ ]+ },+ {+ "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, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "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"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "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": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "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+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "qualityOptionsJson",+ "columnName": "quality_options_json",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "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_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `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`)"+ },+ {+ "name": "index_channels_logical_group_id",+ "unique": false,+ "columnNames": [+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"+ },+ {+ "name": "index_channels_provider_id_category_id_logical_group_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id",+ "logical_group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_preferences",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "aspectRatio",+ "columnName": "aspect_ratio",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_preferences_channel_id",+ "unique": true,+ "columnNames": [+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "channels",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "channel_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channels_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "channels",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "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, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "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"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "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+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "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_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `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": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movies_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "movies",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "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, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "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"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "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+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "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_provider_id_category_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `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": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_fts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",+ "fields": [+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": []+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "simple",+ "tokenizerArgs": [],+ "contentTable": "series",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"+ ]+ },+ {+ "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, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "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"+ },+ {+ "fieldPath": "coverUrl",+ "columnName": "cover_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "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": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "series",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "series_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "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, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "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"+ },+ {+ "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+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "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_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ },+ {+ "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": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_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"+ },+ {+ "fieldPath": "groupTitle",+ "columnName": "group_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgChannelId",+ "columnName": "epg_channel_id",+ "affinity": "TEXT"+ },+ {+ "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": "catchUpSource",+ "columnName": "catchUpSource",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "logicalGroupId",+ "columnName": "logical_group_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "errorCount",+ "columnName": "error_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_channel_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER 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, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_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"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "containerExtension",+ "columnName": "container_extension",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "duration",+ "columnName": "duration",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "durationSeconds",+ "columnName": "duration_seconds",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "year",+ "columnName": "year",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "stream_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_movie_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER 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, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `series_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_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"+ },+ {+ "fieldPath": "backdropUrl",+ "columnName": "backdrop_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "categoryName",+ "columnName": "category_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "plot",+ "columnName": "plot",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cast",+ "columnName": "cast",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "director",+ "columnName": "director",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "releaseDate",+ "columnName": "release_date",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "tmdbId",+ "columnName": "tmdb_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "youtubeTrailer",+ "columnName": "youtube_trailer",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeRunTime",+ "columnName": "episode_run_time",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lastModified",+ "columnName": "last_modified",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "series_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_series_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "category_import_stage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "sessionId",+ "columnName": "session_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_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"+ },+ {+ "fieldPath": "type",+ "columnName": "type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "isAdult",+ "columnName": "is_adult",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "syncFingerprint",+ "columnName": "sync_fingerprint",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "session_id",+ "provider_id",+ "category_id",+ "type"+ ]+ },+ "indices": [+ {+ "name": "index_category_import_stage_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_category_import_stage_session_id_provider_id",+ "unique": false,+ "columnNames": [+ "session_id",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"+ },+ {+ "name": "index_category_import_stage_provider_id_type",+ "unique": false,+ "columnNames": [+ "provider_id",+ "type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "programs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER 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, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_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": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "genre",+ "columnName": "genre",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasArchive",+ "columnName": "has_archive",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_programs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_programs_provider_id_channel_id",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"+ },+ {+ "name": "index_programs_provider_id_start_time_end_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"+ },+ {+ "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_provider_id_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"+ },+ {+ "name": "index_programs_provider_id_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "provider_id",+ "channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"+ }+ ]+ },+ {+ "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, FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET 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"+ },+ {+ "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_content_type_group_id",+ "unique": false,+ "columnNames": [+ "content_type",+ "group_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_content_type_group_id` ON `${TABLE_NAME}` (`content_type`, `group_id`)"+ },+ {+ "name": "index_favorites_group_id_position",+ "unique": false,+ "columnNames": [+ "group_id",+ "position"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "virtual_groups",+ "onDelete": "SET NULL",+ "onUpdate": "NO ACTION",+ "columns": [+ "group_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "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, `content_type` TEXT 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"+ },+ {+ "fieldPath": "position",+ "columnName": "position",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "contentType",+ "columnName": "content_type",+ "affinity": "TEXT",+ "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`)"+ },+ {+ "name": "index_virtual_groups_content_type",+ "unique": false,+ "columnNames": [+ "content_type"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"+ }+ ]+ },+ {+ "tableName": "playback_history",+ "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, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "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": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "posterUrl",+ "columnName": "poster_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resumePositionMs",+ "columnName": "resume_position_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "totalDurationMs",+ "columnName": "total_duration_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastWatchedAt",+ "columnName": "last_watched_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchCount",+ "columnName": "watch_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "watchedStatus",+ "columnName": "watched_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "seriesId",+ "columnName": "series_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "seasonNumber",+ "columnName": "season_number",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "episodeNumber",+ "columnName": "episode_number",+ "affinity": "INTEGER"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_playback_history_content_id_content_type_provider_id",+ "unique": true,+ "columnNames": [+ "content_id",+ "content_type",+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"+ },+ {+ "name": "index_playback_history_last_watched_at",+ "unique": false,+ "columnNames": [+ "last_watched_at"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"+ },+ {+ "name": "index_playback_history_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "sync_metadata",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastLiveSync",+ "columnName": "last_live_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSync",+ "columnName": "last_movie_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSeriesSync",+ "columnName": "last_series_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastEpgSync",+ "columnName": "last_epg_sync",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieAttempt",+ "columnName": "last_movie_attempt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMovieSuccess",+ "columnName": "last_movie_success",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastMoviePartial",+ "columnName": "last_movie_partial",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveCount",+ "columnName": "live_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCount",+ "columnName": "movie_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesCount",+ "columnName": "series_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgCount",+ "columnName": "epg_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSyncStatus",+ "columnName": "last_sync_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieSyncMode",+ "columnName": "movie_sync_mode",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "movieWarningsCount",+ "columnName": "movie_warnings_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieCatalogStale",+ "columnName": "movie_catalog_stale",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveAvoidFullUntil",+ "columnName": "live_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieAvoidFullUntil",+ "columnName": "movie_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesAvoidFullUntil",+ "columnName": "series_avoid_full_until",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveSequentialFailuresRemembered",+ "columnName": "live_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "liveHealthySyncStreak",+ "columnName": "live_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieParallelFailuresRemembered",+ "columnName": "movie_parallel_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "movieHealthySyncStreak",+ "columnName": "movie_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesSequentialFailuresRemembered",+ "columnName": "series_sequential_failures_remembered",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "seriesHealthySyncStreak",+ "columnName": "series_healthy_sync_streak",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id"+ ]+ },+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "movie_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_movie_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "series_category_hydration",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "categoryId",+ "columnName": "category_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastHydratedAt",+ "columnName": "last_hydrated_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "itemCount",+ "columnName": "item_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastStatus",+ "columnName": "last_status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "provider_id",+ "category_id"+ ]+ },+ "indices": [+ {+ "name": "index_series_category_hydration_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "url",+ "columnName": "url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastRefreshAt",+ "columnName": "last_refresh_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastSuccessAt",+ "columnName": "last_success_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "last_error",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_sources_url",+ "unique": true,+ "columnNames": [+ "url"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"+ }+ ]+ },+ {+ "tableName": "provider_epg_sources",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_provider_epg_sources_provider_id_epg_source_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"+ },+ {+ "name": "index_provider_epg_sources_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_channels",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "normalizedName",+ "columnName": "normalized_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "iconUrl",+ "columnName": "icon_url",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"+ },+ {+ "name": "index_epg_channels_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_channels_normalized_name",+ "unique": false,+ "columnNames": [+ "normalized_name"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "epg_programmes",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "startTime",+ "columnName": "start_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "endTime",+ "columnName": "end_time",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "title",+ "columnName": "title",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subtitle",+ "columnName": "subtitle",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "description",+ "columnName": "description",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "category",+ "columnName": "category",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "lang",+ "columnName": "lang",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "rating",+ "columnName": "rating",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "imageUrl",+ "columnName": "image_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "episodeInfo",+ "columnName": "episode_info",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",+ "unique": false,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",+ "unique": true,+ "columnNames": [+ "epg_source_id",+ "xmltv_channel_id",+ "start_time",+ "end_time"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"+ },+ {+ "name": "index_epg_programmes_epg_source_id",+ "unique": false,+ "columnNames": [+ "epg_source_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"+ },+ {+ "name": "index_epg_programmes_start_time",+ "unique": false,+ "columnNames": [+ "start_time"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "epg_sources",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "epg_source_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "channel_epg_mappings",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerChannelId",+ "columnName": "provider_channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "epgSourceId",+ "columnName": "epg_source_id",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "xmltvChannelId",+ "columnName": "xmltv_channel_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "matchType",+ "columnName": "match_type",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "confidence",+ "columnName": "confidence",+ "affinity": "REAL",+ "notNull": true+ },+ {+ "fieldPath": "isManualOverride",+ "columnName": "is_manual_override",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",+ "unique": true,+ "columnNames": [+ "provider_id",+ "provider_channel_id"+ ],+ "orders": [],+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"+ },+ {+ "name": "index_channel_epg_mappings_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_schedules",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "requestedStartMs",+ "columnName": "requested_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "requestedEndMs",+ "columnName": "requested_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "enabled",+ "columnName": "enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isManual",+ "columnName": "is_manual",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_schedules_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_schedules_enabled_requested_start_ms",+ "unique": false,+ "columnNames": [+ "enabled",+ "requested_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"+ },+ {+ "name": "index_recording_schedules_recurring_rule_id",+ "unique": false,+ "columnNames": [+ "recurring_rule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_runs",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "scheduleId",+ "columnName": "schedule_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "providerId",+ "columnName": "provider_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelId",+ "columnName": "channel_id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "channelName",+ "columnName": "channel_name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "streamUrl",+ "columnName": "stream_url",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "programTitle",+ "columnName": "program_title",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "scheduledStartMs",+ "columnName": "scheduled_start_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledEndMs",+ "columnName": "scheduled_end_ms",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "recurrence",+ "columnName": "recurrence",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "recurringRuleId",+ "columnName": "recurring_rule_id",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "status",+ "columnName": "status",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "sourceType",+ "columnName": "source_type",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "resolvedUrl",+ "columnName": "resolved_url",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "headersJson",+ "columnName": "headers_json",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "userAgent",+ "columnName": "user_agent",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expirationTime",+ "columnName": "expiration_time",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "providerLabel",+ "columnName": "provider_label",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputUri",+ "columnName": "output_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDisplayPath",+ "columnName": "output_display_path",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bytesWritten",+ "columnName": "bytes_written",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "averageThroughputBytesPerSecond",+ "columnName": "average_throughput_bps",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "retryCount",+ "columnName": "retry_count",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastProgressAtMs",+ "columnName": "last_progress_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "failureCategory",+ "columnName": "failure_category",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "failureReason",+ "columnName": "failure_reason",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "terminalAtMs",+ "columnName": "terminal_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "startedAtMs",+ "columnName": "started_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "endedAtMs",+ "columnName": "ended_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "scheduleEnabled",+ "columnName": "schedule_enabled",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "priority",+ "columnName": "priority",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "alarmStartAtMs",+ "columnName": "alarm_start_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "alarmStopAtMs",+ "columnName": "alarm_stop_at_ms",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "created_at",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_recording_runs_schedule_id",+ "unique": false,+ "columnNames": [+ "schedule_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"+ },+ {+ "name": "index_recording_runs_provider_id",+ "unique": false,+ "columnNames": [+ "provider_id"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"+ },+ {+ "name": "index_recording_runs_status_scheduled_start_ms",+ "unique": false,+ "columnNames": [+ "status",+ "scheduled_start_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_start_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_start_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"+ },+ {+ "name": "index_recording_runs_alarm_stop_at_ms",+ "unique": false,+ "columnNames": [+ "alarm_stop_at_ms"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"+ }+ ],+ "foreignKeys": [+ {+ "table": "recording_schedules",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "schedule_id"+ ],+ "referencedColumns": [+ "id"+ ]+ },+ {+ "table": "providers",+ "onDelete": "CASCADE",+ "onUpdate": "NO ACTION",+ "columns": [+ "provider_id"+ ],+ "referencedColumns": [+ "id"+ ]+ }+ ]+ },+ {+ "tableName": "recording_storage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "treeUri",+ "columnName": "tree_uri",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "displayName",+ "columnName": "display_name",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "outputDirectory",+ "columnName": "output_directory",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "availableBytes",+ "columnName": "available_bytes",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "isWritable",+ "columnName": "is_writable",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "fileNamePattern",+ "columnName": "file_name_pattern",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "retentionDays",+ "columnName": "retention_days",+ "affinity": "INTEGER"+ },+ {+ "fieldPath": "maxSimultaneousRecordings",+ "columnName": "max_simultaneous_recordings",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updated_at",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "id"+ ]+ }+ }+ ],+ "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, 'accec725df1d6dc8d8668907cc7d2529')"+ ]+ }+}\ No newline at end of filediff --git a/data/src/main/AndroidManifest.xml b/data/src/main/AndroidManifest.xmlindex 9a40236b..bdfd18c2 100644--- a/data/src/main/AndroidManifest.xml+++ b/data/src/main/AndroidManifest.xml@@ -1,3 +1,24 @@<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android">+ <application>+ <service+ android:name="com.streamvault.data.manager.recording.RecordingForegroundService"+ android:exported="false"+ android:foregroundServiceType="dataSync" />++ <receiver+ android:name="com.streamvault.data.manager.recording.RecordingAlarmReceiver"+ android:exported="false" />++ <receiver+ android:name="com.streamvault.data.manager.recording.RecordingRestoreReceiver"+ android:enabled="true"+ android:exported="true">+ <intent-filter>+ <action android:name="android.intent.action.BOOT_COMPLETED" />+ <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+ </intent-filter>+ </receiver>+ </application></manifest>diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.ktindex e44e2dd5..1d587093 100644--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt@@ -35,9 +35,12 @@ import com.streamvault.data.local.entity.*ProviderEpgSourceEntity::class,EpgChannelEntity::class,EpgProgrammeEntity::class,- ChannelEpgMappingEntity::class+ ChannelEpgMappingEntity::class,+ RecordingScheduleEntity::class,+ RecordingRunEntity::class,+ RecordingStorageEntity::class],- version = 28,+ version = 29,exportSchema = true // ← was false; schema JSON now tracked in version control)@TypeConverters(RoomEnumConverters::class)@@ -62,6 +65,9 @@ abstract class StreamVaultDatabase : RoomDatabase() {abstract fun epgChannelDao(): EpgChannelDaoabstract fun epgProgrammeDao(): EpgProgrammeDaoabstract fun channelEpgMappingDao(): ChannelEpgMappingDao+ abstract fun recordingScheduleDao(): RecordingScheduleDao+ abstract fun recordingRunDao(): RecordingRunDao+ abstract fun recordingStorageDao(): RecordingStorageDaocompanion object {/**@@ -1212,6 +1218,113 @@ abstract class StreamVaultDatabase : RoomDatabase() {}}+ val MIGRATION_28_29 = object : Migration(28, 29) {+ override fun migrate(database: SupportSQLiteDatabase) {+ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS recording_schedules (+ id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,+ provider_id INTEGER NOT NULL,+ channel_id INTEGER NOT NULL,+ channel_name TEXT NOT NULL,+ stream_url TEXT NOT NULL,+ program_title TEXT,+ requested_start_ms INTEGER NOT NULL,+ requested_end_ms INTEGER NOT NULL,+ recurrence TEXT NOT NULL,+ recurring_rule_id TEXT,+ enabled INTEGER NOT NULL DEFAULT 1,+ is_manual INTEGER NOT NULL DEFAULT 0,+ priority INTEGER NOT NULL DEFAULT 0,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_provider_id ON recording_schedules(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_enabled_requested_start_ms ON recording_schedules(enabled, requested_start_ms)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_schedules_recurring_rule_id ON recording_schedules(recurring_rule_id)")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS recording_runs (+ id TEXT PRIMARY KEY NOT NULL,+ schedule_id INTEGER NOT NULL,+ provider_id INTEGER NOT NULL,+ channel_id INTEGER NOT NULL,+ channel_name TEXT NOT NULL,+ stream_url TEXT NOT NULL,+ program_title TEXT,+ scheduled_start_ms INTEGER NOT NULL,+ scheduled_end_ms INTEGER NOT NULL,+ recurrence TEXT NOT NULL,+ recurring_rule_id TEXT,+ status TEXT NOT NULL,+ source_type TEXT NOT NULL,+ resolved_url TEXT,+ headers_json TEXT NOT NULL DEFAULT '{}',+ user_agent TEXT,+ expiration_time INTEGER,+ provider_label TEXT,+ output_uri TEXT,+ output_display_path TEXT,+ bytes_written INTEGER NOT NULL DEFAULT 0,+ average_throughput_bps INTEGER NOT NULL DEFAULT 0,+ retry_count INTEGER NOT NULL DEFAULT 0,+ last_progress_at_ms INTEGER,+ failure_category TEXT NOT NULL DEFAULT 'NONE',+ failure_reason TEXT,+ terminal_at_ms INTEGER,+ started_at_ms INTEGER,+ ended_at_ms INTEGER,+ schedule_enabled INTEGER NOT NULL DEFAULT 1,+ priority INTEGER NOT NULL DEFAULT 0,+ alarm_start_at_ms INTEGER,+ alarm_stop_at_ms INTEGER,+ created_at INTEGER NOT NULL,+ updated_at INTEGER NOT NULL,+ FOREIGN KEY(schedule_id) REFERENCES recording_schedules(id) ON DELETE CASCADE,+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON DELETE CASCADE+ )+ """.trimIndent()+ )+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_schedule_id ON recording_runs(schedule_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_provider_id ON recording_runs(provider_id)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_status_scheduled_start_ms ON recording_runs(status, scheduled_start_ms)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_alarm_start_at_ms ON recording_runs(alarm_start_at_ms)")+ database.execSQL("CREATE INDEX IF NOT EXISTS index_recording_runs_alarm_stop_at_ms ON recording_runs(alarm_stop_at_ms)")++ database.execSQL(+ """+ CREATE TABLE IF NOT EXISTS recording_storage (+ id INTEGER PRIMARY KEY NOT NULL,+ tree_uri TEXT,+ display_name TEXT,+ output_directory TEXT,+ available_bytes INTEGER,+ is_writable INTEGER NOT NULL DEFAULT 0,+ file_name_pattern TEXT NOT NULL DEFAULT 'ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts',+ retention_days INTEGER,+ max_simultaneous_recordings INTEGER NOT NULL DEFAULT 2,+ updated_at INTEGER NOT NULL+ )+ """.trimIndent()+ )+ val now = System.currentTimeMillis()+ database.execSQL(+ """+ INSERT OR IGNORE INTO recording_storage (+ id, tree_uri, display_name, output_directory, available_bytes, is_writable, file_name_pattern,+ retention_days, max_simultaneous_recordings, updated_at+ ) VALUES (+ 1, NULL, NULL, NULL, NULL, 0, 'ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts', NULL, 2, $now+ )+ """.trimIndent()+ )+ }+ }+val MIGRATION_24_25 = object : Migration(24, 25) {override fun migrate(database: SupportSQLiteDatabase) {// ── epg_sources ──diff --git a/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt b/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.ktnew file mode 100644index 00000000..e1fb6549--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/dao/RecordingDaos.kt@@ -0,0 +1,114 @@+package com.streamvault.data.local.dao++import androidx.room.Dao+import androidx.room.Insert+import androidx.room.OnConflictStrategy+import androidx.room.Query+import androidx.room.Update+import com.streamvault.data.local.entity.RecordingRunEntity+import com.streamvault.data.local.entity.RecordingRunWithSchedule+import com.streamvault.data.local.entity.RecordingScheduleEntity+import com.streamvault.data.local.entity.RecordingStorageEntity+import com.streamvault.domain.model.RecordingStatus+import kotlinx.coroutines.flow.Flow++@Dao+interface RecordingScheduleDao {+ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun insert(schedule: RecordingScheduleEntity): Long++ @Update+ suspend fun update(schedule: RecordingScheduleEntity)++ @Query("SELECT * FROM recording_schedules WHERE id = :id")+ suspend fun getById(id: Long): RecordingScheduleEntity?++ @Query("DELETE FROM recording_schedules WHERE id = :id")+ suspend fun delete(id: Long)+}++@Dao+interface RecordingRunDao {+ @Query(+ """+ SELECT+ rr.id,+ rr.schedule_id,+ rr.provider_id,+ rr.channel_id,+ rr.channel_name,+ rr.stream_url,+ rr.program_title,+ rr.scheduled_start_ms,+ rr.scheduled_end_ms,+ rr.recurrence,+ rr.recurring_rule_id,+ rr.status,+ rr.source_type,+ rr.output_uri,+ rr.output_display_path,+ rr.bytes_written,+ rr.average_throughput_bps,+ rr.retry_count,+ rr.last_progress_at_ms,+ rr.failure_category,+ rr.failure_reason,+ rr.terminal_at_ms,+ rr.schedule_enabled,+ rr.priority+ FROM recording_runs rr+ ORDER BY rr.scheduled_start_ms DESC, rr.created_at DESC+ """+ )+ fun observeAll(): Flow<List<RecordingRunWithSchedule>>++ @Query("SELECT * FROM recording_runs WHERE id = :id")+ suspend fun getById(id: String): RecordingRunEntity?++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun insert(run: RecordingRunEntity)++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun insertAll(runs: List<RecordingRunEntity>)++ @Update+ suspend fun update(run: RecordingRunEntity)++ @Query("DELETE FROM recording_runs WHERE id = :id")+ suspend fun delete(id: String)++ @Query("DELETE FROM recording_runs")+ suspend fun deleteAll()++ @Query("SELECT * FROM recording_runs WHERE status = :status ORDER BY scheduled_start_ms ASC")+ suspend fun getByStatus(status: RecordingStatus): List<RecordingRunEntity>++ @Query(+ """+ SELECT * FROM recording_runs+ WHERE (status = 'SCHEDULED' OR status = 'RECORDING')+ AND scheduled_start_ms < :windowEndMs+ AND scheduled_end_ms > :windowStartMs+ ORDER BY scheduled_start_ms ASC+ """+ )+ suspend fun getOverlapping(windowStartMs: Long, windowEndMs: Long): List<RecordingRunEntity>++ @Query("SELECT * FROM recording_runs WHERE alarm_start_at_ms IS NOT NULL AND status = 'SCHEDULED'")+ suspend fun getAlarmManagedScheduledRuns(): List<RecordingRunEntity>++ @Query("SELECT * FROM recording_runs WHERE status = 'RECORDING'")+ suspend fun getRecordingRuns(): List<RecordingRunEntity>+}++@Dao+interface RecordingStorageDao {+ @Query("SELECT * FROM recording_storage WHERE id = 1")+ fun observe(): Flow<RecordingStorageEntity?>++ @Query("SELECT * FROM recording_storage WHERE id = 1")+ suspend fun get(): RecordingStorageEntity?++ @Insert(onConflict = OnConflictStrategy.REPLACE)+ suspend fun upsert(storage: RecordingStorageEntity)+}diff --git a/data/src/main/java/com/streamvault/data/local/entity/RecordingEntities.kt b/data/src/main/java/com/streamvault/data/local/entity/RecordingEntities.ktnew file mode 100644index 00000000..c73a30cf--- /dev/null+++ b/data/src/main/java/com/streamvault/data/local/entity/RecordingEntities.kt@@ -0,0 +1,151 @@+package com.streamvault.data.local.entity++import androidx.room.ColumnInfo+import androidx.room.Entity+import androidx.room.ForeignKey+import androidx.room.Index+import androidx.room.PrimaryKey+import com.streamvault.domain.model.RecordingFailureCategory+import com.streamvault.domain.model.RecordingRecurrence+import com.streamvault.domain.model.RecordingSourceType+import com.streamvault.domain.model.RecordingStatus++@Entity(+ tableName = "recording_schedules",+ foreignKeys = [+ ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )+ ],+ indices = [+ Index(value = ["provider_id"]),+ Index(value = ["enabled", "requested_start_ms"]),+ Index(value = ["recurring_rule_id"])+ ]+)+data class RecordingScheduleEntity(+ @PrimaryKey(autoGenerate = true)+ val id: Long = 0,+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "channel_id") val channelId: Long,+ @ColumnInfo(name = "channel_name") val channelName: String,+ @ColumnInfo(name = "stream_url") val streamUrl: String,+ @ColumnInfo(name = "program_title") val programTitle: String? = null,+ @ColumnInfo(name = "requested_start_ms") val requestedStartMs: Long,+ @ColumnInfo(name = "requested_end_ms") val requestedEndMs: Long,+ val recurrence: RecordingRecurrence = RecordingRecurrence.NONE,+ @ColumnInfo(name = "recurring_rule_id") val recurringRuleId: String? = null,+ val enabled: Boolean = true,+ @ColumnInfo(name = "is_manual") val isManual: Boolean = false,+ val priority: Int = 0,+ @ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis(),+ @ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis()+)++@Entity(+ tableName = "recording_runs",+ foreignKeys = [+ ForeignKey(+ entity = RecordingScheduleEntity::class,+ parentColumns = ["id"],+ childColumns = ["schedule_id"],+ onDelete = ForeignKey.CASCADE+ ),+ ForeignKey(+ entity = ProviderEntity::class,+ parentColumns = ["id"],+ childColumns = ["provider_id"],+ onDelete = ForeignKey.CASCADE+ )+ ],+ indices = [+ Index(value = ["schedule_id"]),+ Index(value = ["provider_id"]),+ Index(value = ["status", "scheduled_start_ms"]),+ Index(value = ["alarm_start_at_ms"]),+ Index(value = ["alarm_stop_at_ms"])+ ]+)+data class RecordingRunEntity(+ @PrimaryKey+ val id: String,+ @ColumnInfo(name = "schedule_id") val scheduleId: Long,+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "channel_id") val channelId: Long,+ @ColumnInfo(name = "channel_name") val channelName: String,+ @ColumnInfo(name = "stream_url") val streamUrl: String,+ @ColumnInfo(name = "program_title") val programTitle: String? = null,+ @ColumnInfo(name = "scheduled_start_ms") val scheduledStartMs: Long,+ @ColumnInfo(name = "scheduled_end_ms") val scheduledEndMs: Long,+ val recurrence: RecordingRecurrence = RecordingRecurrence.NONE,+ @ColumnInfo(name = "recurring_rule_id") val recurringRuleId: String? = null,+ val status: RecordingStatus = RecordingStatus.SCHEDULED,+ @ColumnInfo(name = "source_type") val sourceType: RecordingSourceType = RecordingSourceType.UNKNOWN,+ @ColumnInfo(name = "resolved_url") val resolvedUrl: String? = null,+ @ColumnInfo(name = "headers_json") val headersJson: String = "{}",+ @ColumnInfo(name = "user_agent") val userAgent: String? = null,+ @ColumnInfo(name = "expiration_time") val expirationTime: Long? = null,+ @ColumnInfo(name = "provider_label") val providerLabel: String? = null,+ @ColumnInfo(name = "output_uri") val outputUri: String? = null,+ @ColumnInfo(name = "output_display_path") val outputDisplayPath: String? = null,+ @ColumnInfo(name = "bytes_written") val bytesWritten: Long = 0L,+ @ColumnInfo(name = "average_throughput_bps") val averageThroughputBytesPerSecond: Long = 0L,+ @ColumnInfo(name = "retry_count") val retryCount: Int = 0,+ @ColumnInfo(name = "last_progress_at_ms") val lastProgressAtMs: Long? = null,+ @ColumnInfo(name = "failure_category") val failureCategory: RecordingFailureCategory = RecordingFailureCategory.NONE,+ @ColumnInfo(name = "failure_reason") val failureReason: String? = null,+ @ColumnInfo(name = "terminal_at_ms") val terminalAtMs: Long? = null,+ @ColumnInfo(name = "started_at_ms") val startedAtMs: Long? = null,+ @ColumnInfo(name = "ended_at_ms") val endedAtMs: Long? = null,+ @ColumnInfo(name = "schedule_enabled") val scheduleEnabled: Boolean = true,+ val priority: Int = 0,+ @ColumnInfo(name = "alarm_start_at_ms") val alarmStartAtMs: Long? = null,+ @ColumnInfo(name = "alarm_stop_at_ms") val alarmStopAtMs: Long? = null,+ @ColumnInfo(name = "created_at") val createdAt: Long = System.currentTimeMillis(),+ @ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis()+)++@Entity(tableName = "recording_storage")+data class RecordingStorageEntity(+ @PrimaryKey+ val id: Long = 1L,+ @ColumnInfo(name = "tree_uri") val treeUri: String? = null,+ @ColumnInfo(name = "display_name") val displayName: String? = null,+ @ColumnInfo(name = "output_directory") val outputDirectory: String? = null,+ @ColumnInfo(name = "available_bytes") val availableBytes: Long? = null,+ @ColumnInfo(name = "is_writable") val isWritable: Boolean = false,+ @ColumnInfo(name = "file_name_pattern") val fileNamePattern: String = "ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts",+ @ColumnInfo(name = "retention_days") val retentionDays: Int? = null,+ @ColumnInfo(name = "max_simultaneous_recordings") val maxSimultaneousRecordings: Int = 2,+ @ColumnInfo(name = "updated_at") val updatedAt: Long = System.currentTimeMillis()+)++data class RecordingRunWithSchedule(+ @ColumnInfo(name = "id") val id: String,+ @ColumnInfo(name = "schedule_id") val scheduleId: Long,+ @ColumnInfo(name = "provider_id") val providerId: Long,+ @ColumnInfo(name = "channel_id") val channelId: Long,+ @ColumnInfo(name = "channel_name") val channelName: String,+ @ColumnInfo(name = "stream_url") val streamUrl: String,+ @ColumnInfo(name = "program_title") val programTitle: String? = null,+ @ColumnInfo(name = "scheduled_start_ms") val scheduledStartMs: Long,+ @ColumnInfo(name = "scheduled_end_ms") val scheduledEndMs: Long,+ val recurrence: RecordingRecurrence,+ @ColumnInfo(name = "recurring_rule_id") val recurringRuleId: String? = null,+ val status: RecordingStatus,+ @ColumnInfo(name = "source_type") val sourceType: RecordingSourceType,+ @ColumnInfo(name = "output_uri") val outputUri: String? = null,+ @ColumnInfo(name = "output_display_path") val outputDisplayPath: String? = null,+ @ColumnInfo(name = "bytes_written") val bytesWritten: Long,+ @ColumnInfo(name = "average_throughput_bps") val averageThroughputBytesPerSecond: Long,+ @ColumnInfo(name = "retry_count") val retryCount: Int,+ @ColumnInfo(name = "last_progress_at_ms") val lastProgressAtMs: Long? = null,+ @ColumnInfo(name = "failure_category") val failureCategory: RecordingFailureCategory,+ @ColumnInfo(name = "failure_reason") val failureReason: String? = null,+ @ColumnInfo(name = "terminal_at_ms") val terminalAtMs: Long? = null,+ @ColumnInfo(name = "schedule_enabled") val scheduleEnabled: Boolean,+ val priority: Int+)diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingConflictDetector.kt b/data/src/main/java/com/streamvault/data/manager/RecordingConflictDetector.ktnew file mode 100644index 00000000..e7cd950a--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/RecordingConflictDetector.kt@@ -0,0 +1,16 @@+package com.streamvault.data.manager++import com.streamvault.domain.model.RecordingItem+import com.streamvault.domain.model.RecordingStatus++internal fun Iterable<RecordingItem>.findRecordingConflict(+ candidateStartMs: Long,+ candidateEndMs: Long,+ statuses: Set<RecordingStatus>+): RecordingItem? {+ return firstOrNull { item ->+ item.status in statuses &&+ item.scheduledStartMs < candidateEndMs &&+ item.scheduledEndMs > candidateStartMs+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.ktindex ec282c00..fed34376 100644--- a/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/RecordingManagerImpl.kt@@ -1,620 +1,704 @@package com.streamvault.data.managerimport android.content.Context-import android.os.StatFs+import android.util.Logimport com.google.gson.Gsonimport com.google.gson.reflect.TypeToken-import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver+import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.local.dao.RecordingRunDao+import com.streamvault.data.local.dao.RecordingScheduleDao+import com.streamvault.data.local.dao.RecordingStorageDao+import com.streamvault.data.local.entity.RecordingRunEntity+import com.streamvault.data.local.entity.RecordingScheduleEntity+import com.streamvault.data.local.entity.RecordingStorageEntity+import com.streamvault.data.manager.recording.CaptureProgress+import com.streamvault.data.manager.recording.HlsLiveCaptureEngine+import com.streamvault.data.manager.recording.RecordingAlarmScheduler+import com.streamvault.data.manager.recording.RecordingForegroundService+import com.streamvault.data.manager.recording.RecordingOutputTarget+import com.streamvault.data.manager.recording.RecordingSourceResolver+import com.streamvault.data.manager.recording.ResolvedRecordingSource+import com.streamvault.data.manager.recording.TsPassThroughCaptureEngine+import com.streamvault.data.manager.recording.UnsupportedRecordingException+import com.streamvault.data.manager.recording.asPersistenceValues+import com.streamvault.data.manager.recording.createOutputTarget+import com.streamvault.data.manager.recording.deleteOutputTarget+import com.streamvault.data.manager.recording.headersFromJson+import com.streamvault.data.manager.recording.headersToJson+import com.streamvault.data.manager.recording.inferFailureCategory+import com.streamvault.data.manager.recording.resolveStorageDetails+import com.streamvault.data.manager.recording.sanitizeRecordingFileName+import com.streamvault.data.manager.recording.toEntity+import com.streamvault.data.manager.recording.toDomainimport com.streamvault.domain.manager.RecordingManager-import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.RecordingFailureCategoryimport com.streamvault.domain.model.RecordingItemimport com.streamvault.domain.model.RecordingRecurrenceimport com.streamvault.domain.model.RecordingRequest+import com.streamvault.domain.model.RecordingSourceTypeimport com.streamvault.domain.model.RecordingStatus+import com.streamvault.domain.model.RecordingStorageConfigimport com.streamvault.domain.model.RecordingStorageStateimport com.streamvault.domain.model.Resultimport dagger.hilt.android.qualifiers.ApplicationContextimport java.io.Fileimport java.io.FileInputStream-import java.io.FileOutputStreamimport java.util.UUIDimport javax.inject.Injectimport javax.inject.Singleton-import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.CancellationException+import kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.CoroutineStartimport kotlinx.coroutines.Jobimport kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.cancel-import kotlinx.coroutines.currentCoroutineContext-import kotlinx.coroutines.delay-import kotlinx.coroutines.ensureActiveimport kotlinx.coroutines.flow.Flow-import kotlinx.coroutines.flow.MutableStateFlow-import kotlinx.coroutines.flow.asStateFlow-import kotlinx.coroutines.isActive+import kotlinx.coroutines.flow.mapimport kotlinx.coroutines.launchimport kotlinx.coroutines.sync.Muteximport kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContext-import okhttp3.OkHttpClient-import okhttp3.Request-import okhttp3.Response-import java.io.IOException-import kotlin.coroutines.coroutineContext@Singletonclass RecordingManagerImpl @Inject constructor(@ApplicationContext private val context: Context,private val gson: Gson,- private val okHttpClient: OkHttpClient,- private val xtreamStreamUrlResolver: XtreamStreamUrlResolver+ private val providerDao: ProviderDao,+ private val recordingScheduleDao: RecordingScheduleDao,+ private val recordingRunDao: RecordingRunDao,+ private val recordingStorageDao: RecordingStorageDao,+ private val recordingSourceResolver: RecordingSourceResolver,+ private val tsPassThroughCaptureEngine: TsPassThroughCaptureEngine,+ private val hlsLiveCaptureEngine: HlsLiveCaptureEngine,+ private val alarmScheduler: RecordingAlarmScheduler) : RecordingManager {private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)- private val stateFile by lazy { File(recordingsDir, "recordings_state.json") }- private val recordingsDir by lazy { File(context.filesDir, "recordings").apply { mkdirs() } }-- private val itemsState = MutableStateFlow(loadState())- private val storageState = MutableStateFlow(readStorageState())- private val stateMutex = Mutex()private val activeJobs = mutableMapOf<String, Job>()- private var lastRetentionSweepMs = 0L-- /** Cancels the background polling coroutine. Call when the manager is no longer needed. */- fun cancel() {- scope.cancel()- }+ private val activeJobsMutex = Mutex()+ private val legacyStateFile by lazy { File(File(context.filesDir, "recordings"), "recordings_state.json") }init {scope.launch {- while (isActive) {- processSchedules()- runRetentionSweepIfDue()- storageState.value = readStorageState()- delay(15_000L)- }+ migrateLegacyStateIfNeeded()+ ensureStorageState()+ reconcileRecordingState()}}- override fun observeRecordingItems(): Flow<List<RecordingItem>> = itemsState.asStateFlow()+ override fun observeRecordingItems(): Flow<List<RecordingItem>> =+ recordingRunDao.observeAll().map { runs -> runs.map { it.toDomain() } }- override fun observeStorageState(): Flow<RecordingStorageState> = storageState.asStateFlow()+ override fun observeStorageState(): Flow<RecordingStorageState> =+ recordingStorageDao.observe().map { entity ->+ (entity ?: ensureStorageStateSync()).toDomain()+ }override suspend fun startManualRecording(request: RecordingRequest): Result<RecordingItem> = withContext(Dispatchers.IO) {- val effectiveStreamUrl = resolveRecordingStreamUrl(request.providerId, request.channelId, request.streamUrl)- ?: return@withContext Result.error("Recording stream URL could not be resolved.")- if (isAdaptiveStream(effectiveStreamUrl)) {- return@withContext Result.error("Live recording currently supports direct stream URLs only. Adaptive streams are not recordable yet.")- }- if (!storageState.value.isWritable) {- return@withContext Result.error("Recording storage is not writable.")- }+ runCatching {+ val storage = ensureStorageStateSync()+ if (!storage.isWritable) {+ return@withContext Result.error("Recording storage is not writable.")+ }+ validateRecordingWindow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)+ ?.let { return@withContext Result.error(it) }++ val scheduleId = recordingScheduleDao.insert(+ RecordingScheduleEntity(+ providerId = request.providerId,+ channelId = request.channelId,+ channelName = request.channelName,+ streamUrl = request.streamUrl,+ programTitle = request.programTitle,+ requestedStartMs = request.scheduledStartMs,+ requestedEndMs = request.scheduledEndMs,+ recurrence = RecordingRecurrence.NONE,+ enabled = true,+ isManual = true,+ priority = request.priority+ )+ )- val item = RecordingItem(- id = UUID.randomUUID().toString(),- providerId = request.providerId,- channelId = request.channelId,- channelName = request.channelName,- streamUrl = request.streamUrl,- scheduledStartMs = System.currentTimeMillis(),- scheduledEndMs = request.scheduledEndMs,- programTitle = request.programTitle,- outputPath = request.outputPath ?: buildOutputFile(request).absolutePath,- recurrence = RecordingRecurrence.NONE,- recurringRuleId = null,- status = RecordingStatus.RECORDING+ val recordingId = UUID.randomUUID().toString()+ val source = resolveRecordableSource(request.providerId, request.channelId, request.streamUrl)+ val outputTarget = createOutputTarget(+ context = context,+ storage = storage,+ fileName = sanitizeRecordingFileName(+ channelName = request.channelName,+ programTitle = request.programTitle,+ startMs = request.scheduledStartMs,+ pattern = storage.fileNamePattern+ )+ )+ val (outputUri, outputDisplayPath) = outputTarget.asPersistenceValues()+ val now = System.currentTimeMillis()+ val run = RecordingRunEntity(+ id = recordingId,+ scheduleId = scheduleId,+ providerId = request.providerId,+ channelId = request.channelId,+ channelName = request.channelName,+ streamUrl = request.streamUrl,+ programTitle = request.programTitle,+ scheduledStartMs = request.scheduledStartMs,+ scheduledEndMs = request.scheduledEndMs,+ recurrence = RecordingRecurrence.NONE,+ status = RecordingStatus.RECORDING,+ sourceType = source.sourceType,+ resolvedUrl = source.url,+ headersJson = headersToJson(gson, source.headers),+ userAgent = source.userAgent,+ expirationTime = source.expirationTime,+ providerLabel = source.providerLabel,+ outputUri = outputUri,+ outputDisplayPath = outputDisplayPath,+ startedAtMs = now,+ scheduleEnabled = true,+ priority = request.priority,+ alarmStopAtMs = request.scheduledEndMs,+ createdAt = now,+ updatedAt = now+ )+ recordingRunDao.insert(run)+ alarmScheduler.scheduleStop(recordingId, request.scheduledEndMs)+ RecordingForegroundService.startCapture(context, recordingId)+ run.toStandaloneDomain()+ }.fold(+ onSuccess = { Result.success(it) },+ onFailure = { error -> Result.error(error.message ?: "Failed to start recording", error) })- val conflict = appendItemIfNoConflict(item)- if (conflict != null) {- return@withContext Result.error(recordingConflictMessage(conflict))- }- startCapture(item)- storageState.value = readStorageState()- Result.success(item)}override suspend fun scheduleRecording(request: RecordingRequest): Result<RecordingItem> = withContext(Dispatchers.IO) {- val item = RecordingItem(- id = UUID.randomUUID().toString(),- providerId = request.providerId,- channelId = request.channelId,- channelName = request.channelName,- streamUrl = request.streamUrl,- scheduledStartMs = request.scheduledStartMs,- scheduledEndMs = request.scheduledEndMs,- programTitle = request.programTitle,- outputPath = request.outputPath ?: buildOutputFile(request).absolutePath,- recurrence = request.recurrence,- recurringRuleId = request.recurringRuleId ?: request.recurrence.takeIf { it != RecordingRecurrence.NONE }?.let { UUID.randomUUID().toString() },- status = RecordingStatus.SCHEDULED+ runCatching {+ val storage = ensureStorageStateSync()+ if (!storage.isWritable) {+ return@withContext Result.error("Recording storage is not writable.")+ }+ validateRecordingWindow(request.scheduledStartMs, request.scheduledEndMs, request.providerId)+ ?.let { return@withContext Result.error(it) }++ val recurringRuleId = request.recurringRuleId+ ?: request.recurrence.takeIf { it != RecordingRecurrence.NONE }?.let { UUID.randomUUID().toString() }+ val scheduleId = recordingScheduleDao.insert(+ RecordingScheduleEntity(+ providerId = request.providerId,+ channelId = request.channelId,+ channelName = request.channelName,+ streamUrl = request.streamUrl,+ programTitle = request.programTitle,+ requestedStartMs = request.scheduledStartMs,+ requestedEndMs = request.scheduledEndMs,+ recurrence = request.recurrence,+ recurringRuleId = recurringRuleId,+ enabled = true,+ isManual = false,+ priority = request.priority+ )+ )+ val run = createPendingRun(+ scheduleId = scheduleId,+ request = request.copy(recurringRuleId = recurringRuleId)+ )+ recordingRunDao.insert(run)+ alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)+ run.toStandaloneDomain()+ }.fold(+ onSuccess = { Result.success(it) },+ onFailure = { error -> Result.error(error.message ?: "Failed to schedule recording", error) })- val conflict = appendItemIfNoConflict(item)- if (conflict != null) {- return@withContext Result.error(recordingConflictMessage(conflict))- }- Result.success(item)}override suspend fun stopRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {- removeActiveJob(recordingId)?.cancel()- val item = getItem(recordingId)- ?: return@withContext Result.error("Recording not found")+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ cancelActiveJob(recordingId)+ alarmScheduler.cancel(recordingId)val now = System.currentTimeMillis()- val fileLength = item.outputPath?.let { path -> File(path).takeIf { it.exists() }?.length() } ?: 0L- updateItem(recordingId) {- it.copy(- status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,- scheduledEndMs = now,- terminalAtMs = now+ recordingRunDao.update(+ run.copy(+ status = if (run.bytesWritten > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,+ endedAtMs = now,+ terminalAtMs = now,+ updatedAt = now)- }+ )Result.success(Unit)}override suspend fun cancelRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {- removeActiveJob(recordingId)?.cancel()+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ cancelActiveJob(recordingId)+ alarmScheduler.cancel(recordingId)val now = System.currentTimeMillis()- updateItem(recordingId) {- it.copy(+ recordingRunDao.update(+ run.copy(status = RecordingStatus.CANCELLED,- terminalAtMs = now+ terminalAtMs = now,+ endedAtMs = now,+ scheduleEnabled = false,+ updatedAt = now)+ )+ recordingScheduleDao.getById(run.scheduleId)?.let { schedule ->+ recordingScheduleDao.update(schedule.copy(enabled = false, updatedAt = now))}Result.success(Unit)}override suspend fun deleteRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {- removeActiveJob(recordingId)?.cancel()- val item = getItem(recordingId)- ?: return@withContext Result.error("Recording not found")- if (item.status == RecordingStatus.RECORDING || item.status == RecordingStatus.SCHEDULED) {+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ if (run.status == RecordingStatus.SCHEDULED || run.status == RecordingStatus.RECORDING) {return@withContext Result.error("Only finished recordings can be deleted.")}- deleteOutputFile(item.outputPath)- removeItem(recordingId)- storageState.value = readStorageState()+ deleteOutputTarget(context, run.outputUri, run.outputDisplayPath)+ recordingRunDao.delete(recordingId)+ Result.success(Unit)+ }++ override suspend fun retryRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ val schedule = recordingScheduleDao.getById(run.scheduleId) ?: return@withContext Result.error("Recording schedule not found")+ val retriedRun = createPendingRun(+ scheduleId = schedule.id,+ request = RecordingRequest(+ providerId = schedule.providerId,+ channelId = schedule.channelId,+ channelName = schedule.channelName,+ streamUrl = schedule.streamUrl,+ scheduledStartMs = maxOf(System.currentTimeMillis() + 2_000L, schedule.requestedStartMs),+ scheduledEndMs = schedule.requestedEndMs,+ programTitle = schedule.programTitle,+ recurrence = schedule.recurrence,+ recurringRuleId = schedule.recurringRuleId,+ priority = schedule.priority+ )+ )+ recordingRunDao.insert(retriedRun)+ alarmScheduler.scheduleStart(retriedRun.id, retriedRun.scheduledStartMs)Result.success(Unit)}- private suspend fun processSchedules() {+ override suspend fun setScheduleEnabled(recordingId: String, enabled: Boolean): Result<Unit> = withContext(Dispatchers.IO) {+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ val schedule = recordingScheduleDao.getById(run.scheduleId) ?: return@withContext Result.error("Recording schedule not found")val now = System.currentTimeMillis()- val snapshot = stateMutex.withLock { itemsState.value }-- snapshot- .filter { it.status == RecordingStatus.SCHEDULED && it.scheduledStartMs <= now }- .sortedBy(RecordingItem::scheduledStartMs)- .forEach { scheduled ->- val startDecision = promoteScheduledItemToRecordingIfNoConflict(scheduled.id)- if (startDecision == null) {- return@forEach- }- if (startDecision.conflict != null) {- scheduleNextRecurringOccurrence(startDecision.recording)- val failureTime = System.currentTimeMillis()- updateItemIf(scheduled.id, expectedStatus = RecordingStatus.SCHEDULED) {- it.copy(- status = RecordingStatus.FAILED,- failureReason = recordingConflictMessage(startDecision.conflict),- terminalAtMs = failureTime- )- }- return@forEach- }+ recordingScheduleDao.update(schedule.copy(enabled = enabled, updatedAt = now))+ recordingRunDao.update(run.copy(scheduleEnabled = enabled, updatedAt = now))+ if (enabled && run.status == RecordingStatus.SCHEDULED) {+ alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)+ } else {+ alarmScheduler.cancel(run.id)+ }+ Result.success(Unit)+ }- scheduleNextRecurringOccurrence(startDecision.recording)-- val effectiveStreamUrl = resolveRecordingStreamUrl(scheduled.providerId, scheduled.channelId, scheduled.streamUrl)- if (effectiveStreamUrl == null) {- val failureTime = System.currentTimeMillis()- updateItemIf(scheduled.id, expectedStatus = RecordingStatus.RECORDING) {- it.copy(- status = RecordingStatus.FAILED,- failureReason = "Recording stream URL could not be resolved.",- terminalAtMs = failureTime- )- }- } else if (isAdaptiveStream(effectiveStreamUrl)) {- val failureTime = System.currentTimeMillis()- updateItemIf(scheduled.id, expectedStatus = RecordingStatus.RECORDING) {- it.copy(- status = RecordingStatus.FAILED,- failureReason = "Scheduled recording supports direct stream URLs only.",- terminalAtMs = failureTime- )+ override suspend fun updateStorageConfig(config: RecordingStorageConfig): Result<RecordingStorageState> = withContext(Dispatchers.IO) {+ runCatching {+ val existing = recordingStorageDao.get()+ val (outputDirectory, availableBytes, isWritable) = resolveStorageDetails(context, config.treeUri)+ val entity = config.toEntity(existing, outputDirectory, availableBytes, isWritable)+ recordingStorageDao.upsert(entity)+ reconcileRecordingState()+ entity.toDomain()+ }.fold(+ onSuccess = { Result.success(it) },+ onFailure = { error -> Result.error(error.message ?: "Failed to update recording storage", error) }+ )+ }++ override suspend fun reconcileRecordingState(): Result<Unit> = withContext(Dispatchers.IO) {+ runCatching<Unit> {+ ensureStorageState()+ recordingRunDao.getAlarmManagedScheduledRuns()+ .filter { it.scheduleEnabled && it.status == RecordingStatus.SCHEDULED }+ .forEach { run ->+ if (run.scheduledEndMs <= System.currentTimeMillis()) {+ markRunFailed(run.id, "Recording window expired before capture started.", RecordingFailureCategory.UNKNOWN)+ } else {+ alarmScheduler.scheduleStart(run.id, run.scheduledStartMs)}- } else {- startCapture(startDecision.recording)}- }-- snapshot- .filter { it.status == RecordingStatus.RECORDING && it.scheduledEndMs in 1 until now }- .forEach { stopCandidate ->- removeActiveJob(stopCandidate.id)?.cancel()- val fileLength = stopCandidate.outputPath?.let { path -> File(path).takeIf { it.exists() }?.length() } ?: 0L- updateItemIf(stopCandidate.id, expectedStatus = RecordingStatus.RECORDING) {- it.copy(- status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,- scheduledEndMs = now,- terminalAtMs = now- )+ recordingRunDao.getRecordingRuns().forEach { run ->+ if (run.scheduledEndMs <= System.currentTimeMillis()) {+ stopRecording(run.id)+ } else if (!isActiveJob(run.id)) {+ RecordingForegroundService.startCapture(context, run.id)}}+ }.fold(+ onSuccess = { Result.success(Unit) },+ onFailure = { error -> Result.error(error.message ?: "Failed to reconcile recording state", error) }+ )}- private suspend fun startCapture(item: RecordingItem) {- val job = scope.launch(start = CoroutineStart.LAZY) {- val outputFile = File(item.outputPath ?: return@launch)- outputFile.parentFile?.mkdirs()- runCatching {- captureStreamToFile(item, outputFile)- }.onSuccess {- val completedAt = System.currentTimeMillis()- updateItemIf(item.id, expectedStatus = RecordingStatus.RECORDING) { current ->- current.copy(status = RecordingStatus.COMPLETED, terminalAtMs = completedAt)+ override suspend fun promoteScheduledRecording(recordingId: String): Result<Unit> = withContext(Dispatchers.IO) {+ val run = recordingRunDao.getById(recordingId) ?: return@withContext Result.error("Recording not found")+ when (run.status) {+ RecordingStatus.RECORDING -> startCapture(run)+ RecordingStatus.SCHEDULED -> {+ val source = resolveRecordableSource(run.providerId, run.channelId, run.streamUrl)+ val storage = ensureStorageStateSync()+ if (!storage.isWritable) {+ return@withContext Result.error("Recording storage is not writable.")}- }.onFailure { error ->- if (error is CancellationException) {- val cancelledAt = System.currentTimeMillis()- val fileLength = outputFile.takeIf { it.exists() }?.length() ?: 0L- updateItemIf(item.id, expectedStatus = RecordingStatus.RECORDING) { current ->- current.copy(- status = if (fileLength > 0L) RecordingStatus.COMPLETED else RecordingStatus.CANCELLED,- terminalAtMs = cancelledAt- )- }+ val outputTarget = if (!run.outputUri.isNullOrBlank() || !run.outputDisplayPath.isNullOrBlank()) {+ existingOutputTarget(run)} else {- val failureTime = System.currentTimeMillis()- updateItemIf(item.id, expectedStatus = RecordingStatus.RECORDING) { current ->- current.copy(- status = RecordingStatus.FAILED,- failureReason = error.message,- terminalAtMs = failureTime- )- }+ createOutputTarget(+ context = context,+ storage = storage,+ fileName = sanitizeRecordingFileName(run.channelName, run.programTitle, run.scheduledStartMs, storage.fileNamePattern)+ )}+ val (outputUri, outputDisplayPath) = outputTarget.asPersistenceValues()+ val now = System.currentTimeMillis()+ val updatedRun = run.copy(+ status = RecordingStatus.RECORDING,+ sourceType = source.sourceType,+ resolvedUrl = source.url,+ headersJson = headersToJson(gson, source.headers),+ userAgent = source.userAgent,+ expirationTime = source.expirationTime,+ providerLabel = source.providerLabel,+ outputUri = outputUri ?: run.outputUri,+ outputDisplayPath = outputDisplayPath ?: run.outputDisplayPath,+ startedAtMs = now,+ updatedAt = now,+ alarmStopAtMs = run.scheduledEndMs+ )+ recordingRunDao.update(updatedRun)+ alarmScheduler.scheduleStop(updatedRun.id, updatedRun.scheduledEndMs)+ spawnNextRecurringRunIfNeeded(updatedRun)+ startCapture(updatedRun)}- removeActiveJob(item.id)- storageState.value = readStorageState()+ else -> Result.error("Recording is no longer active.")}- val replaced = stateMutex.withLock { activeJobs.putIfAbsent(item.id, job) }- if (replaced != null) {- job.cancel()- return+ }++ internal suspend fun onCaptureFinished(recordingId: String) {+ val remaining = observeActiveRecordingCountSync().coerceAtLeast(0)+ if (remaining == 0) {+ RecordingForegroundService.stopIfIdle(context)}- job.start()}- private suspend fun captureStreamToFile(item: RecordingItem, outputFile: File) {- val resolvedUrl = resolveRecordingStreamUrl(item.providerId, item.channelId, item.streamUrl)- ?: throw IOException("Recording stream URL could not be resolved")- var attempt = 0- var retryDelayMs = 1_000L- while (true) {- currentCoroutineContext().ensureActive()+ private suspend fun startCapture(run: RecordingRunEntity): Result<Unit> {+ if (isActiveJob(run.id)) return Result.success(Unit)+ val target = existingOutputTarget(run)+ val source = ResolvedRecordingSource(+ url = run.resolvedUrl ?: return Result.error("Recording stream URL could not be resolved."),+ sourceType = run.sourceType,+ headers = headersFromJson(gson, run.headersJson),+ userAgent = run.userAgent,+ expirationTime = run.expirationTime,+ providerLabel = run.providerLabel+ )+ val engine = when (source.sourceType) {+ RecordingSourceType.HLS -> hlsLiveCaptureEngine+ RecordingSourceType.TS,+ RecordingSourceType.UNKNOWN -> tsPassThroughCaptureEngine+ RecordingSourceType.DASH -> return Result.error("DASH live recording is not supported yet.")+ }+ val job = scope.launch {try {- streamResponseBody(resolvedUrl, outputFile)- return+ engine.capture(+ source = source,+ outputTarget = target,+ contentResolver = context.contentResolver,+ scheduledEndMs = run.scheduledEndMs,+ onProgress = { progress -> updateRunProgress(run.id, progress) }+ )+ completeRun(run.id)+ } catch (cancelled: CancellationException) {+ Log.i("RecordingManager", "Capture cancelled for ${run.id}")+ } catch (unsupported: UnsupportedRecordingException) {+ markRunFailed(run.id, unsupported.message ?: "Recording format is unsupported.", unsupported.category)} catch (error: Throwable) {- if (error is CancellationException || !isRetryableRecordingError(error) || attempt >= MAX_RECORDING_RETRIES) {- throw error- }- attempt++- delay(retryDelayMs)- retryDelayMs = (retryDelayMs * 2).coerceAtMost(8_000L)+ markRunFailed(run.id, error.message ?: "Recording failed.", inferFailureCategory(error.message))+ } finally {+ removeActiveJob(run.id)+ onCaptureFinished(run.id)}}- }-- private fun buildOutputFile(request: RecordingRequest): File {- return buildOutputFile(request.channelName, request.scheduledStartMs)- }-- private fun buildOutputFile(channelName: String, scheduledStartMs: Long): File {- val safeName = channelName.replace(Regex("[^a-zA-Z0-9._-]"), "_")- return File(recordingsDir, "${safeName}_${scheduledStartMs}.ts")- }-- private fun readStorageState(): RecordingStorageState {- recordingsDir.mkdirs()- val stat = StatFs(recordingsDir.absolutePath)- return RecordingStorageState(- outputDirectory = recordingsDir.absolutePath,- availableBytes = stat.availableBytes,- isWritable = recordingsDir.canWrite()- )- }-- private fun persistStateLocked() {- stateFile.parentFile?.mkdirs()- val tmpFile = File(stateFile.parentFile, "${stateFile.name}.tmp")- tmpFile.writeText(gson.toJson(itemsState.value))- tmpFile.renameTo(stateFile)- }-- private fun loadState(): List<RecordingItem> {- if (!stateFile.exists()) return emptyList()- return runCatching {- val listType = object : TypeToken<List<RecordingItem>>() {}.type- FileInputStream(stateFile).bufferedReader().use { reader ->+ registerActiveJob(run.id, job)+ return Result.success(Unit)+ }++ private suspend fun migrateLegacyStateIfNeeded() {+ if (!legacyStateFile.exists()) return+ val hasExistingRuns = runCatching {+ recordingRunDao.getByStatus(RecordingStatus.SCHEDULED).isNotEmpty() || recordingRunDao.getRecordingRuns().isNotEmpty()+ }.getOrDefault(false)+ if (hasExistingRuns) return+ val listType = object : TypeToken<List<RecordingItem>>() {}.type+ val legacyItems = runCatching {+ FileInputStream(legacyStateFile).bufferedReader().use { reader ->gson.fromJson<List<RecordingItem>>(reader, listType).orEmpty()}}.getOrDefault(emptyList())- }-- private fun isAdaptiveStream(url: String): Boolean {- val lower = url.lowercase()- return lower.contains(".m3u8") || lower.contains(".mpd")- }-- private suspend fun resolveRecordingStreamUrl(providerId: Long, channelId: Long, logicalUrl: String): String? {- return xtreamStreamUrlResolver.resolve(- url = logicalUrl,- fallbackProviderId = providerId,- fallbackStreamId = channelId,- fallbackContentType = ContentType.LIVE- )- }-- private suspend fun appendItem(item: RecordingItem) {- stateMutex.withLock {- itemsState.value = itemsState.value + item- persistStateLocked()- }- }-- private suspend fun appendItemIfNoConflict(item: RecordingItem): RecordingItem? = stateMutex.withLock {- val conflict = itemsState.value.findRecordingConflict(- candidateStartMs = item.scheduledStartMs,- candidateEndMs = item.scheduledEndMs,- statuses = ACTIVE_RECORDING_STATUSES- )- if (conflict != null) {- return@withLock conflict+ legacyItems.forEach { item ->+ val scheduleId = recordingScheduleDao.insert(+ RecordingScheduleEntity(+ providerId = item.providerId,+ channelId = item.channelId,+ channelName = item.channelName,+ streamUrl = item.streamUrl,+ programTitle = item.programTitle,+ requestedStartMs = item.scheduledStartMs,+ requestedEndMs = item.scheduledEndMs,+ recurrence = item.recurrence,+ recurringRuleId = item.recurringRuleId,+ enabled = item.scheduleEnabled,+ isManual = item.recurrence == RecordingRecurrence.NONE && item.status == RecordingStatus.RECORDING,+ priority = item.priority+ )+ )+ recordingRunDao.insert(+ RecordingRunEntity(+ id = item.id,+ scheduleId = scheduleId,+ providerId = item.providerId,+ channelId = item.channelId,+ channelName = item.channelName,+ streamUrl = item.streamUrl,+ programTitle = item.programTitle,+ scheduledStartMs = item.scheduledStartMs,+ scheduledEndMs = item.scheduledEndMs,+ recurrence = item.recurrence,+ recurringRuleId = item.recurringRuleId,+ status = item.status,+ sourceType = item.sourceType,+ outputUri = item.outputUri,+ outputDisplayPath = item.outputDisplayPath ?: item.outputPath,+ bytesWritten = item.bytesWritten,+ averageThroughputBytesPerSecond = item.averageThroughputBytesPerSecond,+ retryCount = item.retryCount,+ lastProgressAtMs = item.lastProgressAtMs,+ failureCategory = item.failureCategory,+ failureReason = item.failureReason,+ terminalAtMs = item.terminalAtMs,+ startedAtMs = item.scheduledStartMs,+ endedAtMs = item.terminalAtMs,+ scheduleEnabled = item.scheduleEnabled,+ priority = item.priority+ )+ )}- itemsState.value = itemsState.value + item- persistStateLocked()- null+ legacyStateFile.delete()}- private suspend fun removeItem(recordingId: String): RecordingItem? = stateMutex.withLock {- val existing = itemsState.value.firstOrNull { it.id == recordingId } ?: return@withLock null- itemsState.value = itemsState.value.filterNot { it.id == recordingId }- persistStateLocked()- existing+ private suspend fun ensureStorageState() {+ ensureStorageStateSync()}- private suspend fun getItem(recordingId: String): RecordingItem? =- stateMutex.withLock { itemsState.value.firstOrNull { it.id == recordingId } }-- private suspend fun updateItem(- recordingId: String,- transform: (RecordingItem) -> RecordingItem- ): RecordingItem? = stateMutex.withLock {- var updated: RecordingItem? = null- itemsState.value = itemsState.value.map { item ->- if (item.id == recordingId) {- transform(item).also { updated = it }- } else {- item- }+ private suspend fun ensureStorageStateSync(): RecordingStorageEntity {+ val existing = recordingStorageDao.get()+ if (existing != null) {+ val (outputDirectory, availableBytes, isWritable) = resolveStorageDetails(context, existing.treeUri)+ val refreshed = existing.copy(+ outputDirectory = outputDirectory,+ availableBytes = availableBytes,+ isWritable = isWritable,+ updatedAt = System.currentTimeMillis()+ )+ recordingStorageDao.upsert(refreshed)+ return refreshed}- if (updated != null) {- persistStateLocked()+ val (outputDirectory, availableBytes, isWritable) = resolveStorageDetails(context, null)+ return RecordingStorageEntity(+ outputDirectory = outputDirectory,+ availableBytes = availableBytes,+ isWritable = isWritable+ ).also { recordingStorageDao.upsert(it) }+ }++ private suspend fun resolveRecordableSource(providerId: Long, channelId: Long, streamUrl: String): ResolvedRecordingSource {+ val source = recordingSourceResolver.resolveLiveSource(providerId, channelId, streamUrl)+ return when (source.sourceType) {+ RecordingSourceType.DASH -> throw UnsupportedRecordingException("DASH live recording is not supported yet.", RecordingFailureCategory.FORMAT_UNSUPPORTED)+ else -> source}- updated}- private suspend fun updateItemIf(- recordingId: String,- expectedStatus: RecordingStatus,- transform: (RecordingItem) -> RecordingItem- ): RecordingItem? = stateMutex.withLock {- var updated: RecordingItem? = null- itemsState.value = itemsState.value.map { item ->- if (item.id == recordingId && item.status == expectedStatus) {- transform(item).also { updated = it }- } else {- item- }- }- if (updated != null) {- persistStateLocked()- }- updated+ private suspend fun updateRunProgress(recordingId: String, progress: CaptureProgress) {+ val run = recordingRunDao.getById(recordingId) ?: return+ recordingRunDao.update(+ run.copy(+ bytesWritten = progress.bytesWritten,+ averageThroughputBytesPerSecond = progress.averageThroughputBytesPerSecond,+ retryCount = maxOf(run.retryCount, progress.retryCount),+ lastProgressAtMs = progress.lastProgressAtMs,+ updatedAt = System.currentTimeMillis()+ )+ )}- private suspend fun removeActiveJob(recordingId: String): Job? =- stateMutex.withLock { activeJobs.remove(recordingId) }-- private suspend fun scheduleNextRecurringOccurrence(source: RecordingItem) {- if (source.recurrence == RecordingRecurrence.NONE || source.recurringRuleId.isNullOrBlank()) {- return- }- stateMutex.withLock {- val nextStartMs = source.scheduledStartMs + source.recurrence.intervalMs- val duplicateExists = itemsState.value.any { item ->- item.recurringRuleId == source.recurringRuleId &&- item.scheduledStartMs == nextStartMs &&- item.status == RecordingStatus.SCHEDULED- }- if (duplicateExists) {- return@withLock- }- val nextItem = source.copy(- id = UUID.randomUUID().toString(),- scheduledStartMs = nextStartMs,- scheduledEndMs = source.scheduledEndMs + source.recurrence.intervalMs,- outputPath = buildOutputFile(source.channelName, nextStartMs).absolutePath,- status = RecordingStatus.SCHEDULED,- failureReason = null,- terminalAtMs = null+ private suspend fun completeRun(recordingId: String) {+ val run = recordingRunDao.getById(recordingId) ?: return+ val now = System.currentTimeMillis()+ recordingRunDao.update(+ run.copy(+ status = RecordingStatus.COMPLETED,+ terminalAtMs = now,+ endedAtMs = now,+ updatedAt = now)- itemsState.value = itemsState.value + nextItem- persistStateLocked()- }+ )+ alarmScheduler.cancel(recordingId)}- private suspend fun promoteScheduledItemToRecordingIfNoConflict(recordingId: String): RecordingStartDecision? =- stateMutex.withLock {- val scheduled = itemsState.value.firstOrNull {- it.id == recordingId && it.status == RecordingStatus.SCHEDULED- } ?: return@withLock null- val conflict = itemsState.value.findRecordingConflict(- candidateStartMs = scheduled.scheduledStartMs,- candidateEndMs = scheduled.scheduledEndMs,- ignoreRecordingId = recordingId,- statuses = setOf(RecordingStatus.RECORDING)+ private suspend fun markRunFailed(recordingId: String, reason: String, category: RecordingFailureCategory) {+ val run = recordingRunDao.getById(recordingId) ?: return+ val now = System.currentTimeMillis()+ recordingRunDao.update(+ run.copy(+ status = RecordingStatus.FAILED,+ failureReason = reason,+ failureCategory = category,+ terminalAtMs = now,+ endedAtMs = now,+ updatedAt = now)- if (conflict != null) {- return@withLock RecordingStartDecision(recording = scheduled, conflict = conflict)- }- val updated = scheduled.copy(status = RecordingStatus.RECORDING)- itemsState.value = itemsState.value.map { item ->- if (item.id == recordingId) updated else item- }- persistStateLocked()- RecordingStartDecision(recording = updated, conflict = null)- }+ )+ alarmScheduler.cancel(recordingId)+ }- private suspend fun runRetentionSweepIfDue() {+ private fun createPendingRun(scheduleId: Long, request: RecordingRequest): RecordingRunEntity {val now = System.currentTimeMillis()- if (now - lastRetentionSweepMs < RETENTION_SWEEP_INTERVAL_MS) {- return- }- lastRetentionSweepMs = now-- val expiredIds = stateMutex.withLock {- itemsState.value- .filter { item ->- item.status.isTerminal() &&- item.terminalAtMs?.let { terminalAt -> now - terminalAt >= FINISHED_RECORDING_RETENTION_MS } == true- }- .map(RecordingItem::id)- }- if (expiredIds.isEmpty()) {- return- }- expiredIds.forEach { recordingId ->- val removed = removeItem(recordingId)- deleteOutputFile(removed?.outputPath)- }+ return RecordingRunEntity(+ id = UUID.randomUUID().toString(),+ scheduleId = scheduleId,+ providerId = request.providerId,+ channelId = request.channelId,+ channelName = request.channelName,+ streamUrl = request.streamUrl,+ programTitle = request.programTitle,+ scheduledStartMs = request.scheduledStartMs,+ scheduledEndMs = request.scheduledEndMs,+ recurrence = request.recurrence,+ recurringRuleId = request.recurringRuleId,+ status = RecordingStatus.SCHEDULED,+ scheduleEnabled = true,+ priority = request.priority,+ alarmStartAtMs = request.scheduledStartMs,+ createdAt = now,+ updatedAt = now+ )}- private fun deleteOutputFile(path: String?) {- if (path.isNullOrBlank()) return- runCatching {- val file = File(path)- if (file.exists()) {- file.delete()- }+ private suspend fun spawnNextRecurringRunIfNeeded(run: RecordingRunEntity) {+ if (run.recurrence == RecordingRecurrence.NONE || run.recurringRuleId.isNullOrBlank()) return+ val interval = recurrenceIntervalMs(run.recurrence)+ val nextStart = run.scheduledStartMs + interval+ val overlappingPending = recordingRunDao.getByStatus(RecordingStatus.SCHEDULED).any {+ it.recurringRuleId == run.recurringRuleId && it.scheduledStartMs == nextStart}- }-- private suspend fun streamResponseBody(url: String, outputFile: File) {- val request = Request.Builder().url(url).get().build()- val call = okHttpClient.newCall(request)- val cancellationHandle = coroutineContext[Job]?.invokeOnCompletion { cause ->- if (cause is CancellationException) {- call.cancel()- }+ if (overlappingPending) return+ val nextRun = run.copy(+ id = UUID.randomUUID().toString(),+ status = RecordingStatus.SCHEDULED,+ scheduledStartMs = nextStart,+ scheduledEndMs = run.scheduledEndMs + interval,+ sourceType = RecordingSourceType.UNKNOWN,+ resolvedUrl = null,+ headersJson = "{}",+ userAgent = null,+ expirationTime = null,+ providerLabel = null,+ outputUri = null,+ outputDisplayPath = null,+ bytesWritten = 0L,+ averageThroughputBytesPerSecond = 0L,+ retryCount = 0,+ lastProgressAtMs = null,+ failureCategory = RecordingFailureCategory.NONE,+ failureReason = null,+ terminalAtMs = null,+ startedAtMs = null,+ endedAtMs = null,+ alarmStartAtMs = nextStart,+ alarmStopAtMs = null,+ createdAt = System.currentTimeMillis(),+ updatedAt = System.currentTimeMillis()+ )+ recordingRunDao.insert(nextRun)+ alarmScheduler.scheduleStart(nextRun.id, nextRun.scheduledStartMs)+ }++ private suspend fun validateRecordingWindow(startMs: Long, endMs: Long, providerId: Long): String? {+ val storage = ensureStorageStateSync()+ val overlapping = recordingRunDao.getOverlapping(startMs, endMs)+ .filter { it.status == RecordingStatus.SCHEDULED || it.status == RecordingStatus.RECORDING }+ .filter { it.scheduleEnabled }+ if (overlapping.size >= storage.maxSimultaneousRecordings) {+ val title = overlapping.firstOrNull()?.programTitle ?: overlapping.firstOrNull()?.channelName.orEmpty()+ return "Recording conflicts with an existing active recording for $title."}- try {- call.execute().use { response ->- ensureSuccessfulRecordingResponse(response)- val body = response.body ?: throw IOException("Recording stream returned an empty body")- body.byteStream().use { input ->- FileOutputStream(outputFile, false).use { output ->- val buffer = ByteArray(DEFAULT_BUFFER_SIZE)- while (true) {- currentCoroutineContext().ensureActive()- val bytes = input.read(buffer)- if (bytes <= 0) {- break- }- output.write(buffer, 0, bytes)- }- }- }- }- } finally {- cancellationHandle?.dispose()+ val providerMaxConnections = providerDao.getById(providerId)?.maxConnections ?: Int.MAX_VALUE+ if (overlapping.count { it.providerId == providerId } >= providerMaxConnections) {+ return "Recording exceeds the provider connection limit for this account."}+ return null}- private fun ensureSuccessfulRecordingResponse(response: Response) {- if (response.isSuccessful) {- return- }- if (response.code in 500..599 || response.code == 429) {- throw IOException("Transient HTTP ${response.code}")- }- throw IllegalStateException("Recording stream failed with HTTP ${response.code}")+ private suspend fun registerActiveJob(id: String, job: Job) {+ activeJobsMutex.withLock { activeJobs[id] = job }}- private fun isRetryableRecordingError(error: Throwable): Boolean {- if (error is IOException) {- return true- }- val message = error.message.orEmpty().lowercase()- return message.contains("timeout") ||- message.contains("timed out") ||- message.contains("connection reset") ||- message.contains("connect") ||- message.contains("network")- }+ private suspend fun removeActiveJob(id: String): Job? =+ activeJobsMutex.withLock { activeJobs.remove(id) }- private companion object {- val ACTIVE_RECORDING_STATUSES = setOf(RecordingStatus.SCHEDULED, RecordingStatus.RECORDING)- const val MAX_RECORDING_RETRIES = 3- const val FINISHED_RECORDING_RETENTION_MS = 30L * 24L * 60L * 60L * 1000L- const val RETENTION_SWEEP_INTERVAL_MS = 60L * 60L * 1000L+ private suspend fun cancelActiveJob(id: String) {+ removeActiveJob(id)?.cancel()}-}-private data class RecordingStartDecision(- val recording: RecordingItem,- val conflict: RecordingItem?-)--internal fun List<RecordingItem>.findRecordingConflict(- candidateStartMs: Long,- candidateEndMs: Long,- ignoreRecordingId: String? = null,- statuses: Set<RecordingStatus>-): RecordingItem? = asSequence()- .filter { it.id != ignoreRecordingId }- .filter { it.status in statuses }- .sortedWith(compareBy<RecordingItem> { it.scheduledStartMs }.thenBy { it.id })- .firstOrNull { existing ->- candidateStartMs < existing.scheduledEndMs && existing.scheduledStartMs < candidateEndMs- }+ private suspend fun isActiveJob(id: String): Boolean =+ activeJobsMutex.withLock { activeJobs[id]?.isActive == true }-private fun recordingConflictMessage(conflict: RecordingItem): String {- val title = conflict.programTitle?.takeIf { it.isNotBlank() } ?: conflict.channelName- val stateLabel = when (conflict.status) {- RecordingStatus.SCHEDULED -> "scheduled"- RecordingStatus.RECORDING -> "active"- RecordingStatus.COMPLETED,- RecordingStatus.FAILED,- RecordingStatus.CANCELLED -> "finished"- }- return "Recording conflicts with an existing $stateLabel recording for $title on ${conflict.channelName}."-}+ private suspend fun observeActiveRecordingCountSync(): Int =+ activeJobsMutex.withLock { activeJobs.values.count { it.isActive } }-private val RecordingRecurrence.intervalMs: Long- get() = when (this) {+ private fun existingOutputTarget(run: RecordingRunEntity): RecordingOutputTarget =+ when {+ !run.outputUri.isNullOrBlank() -> RecordingOutputTarget.DocumentTarget(+ uri = android.net.Uri.parse(run.outputUri),+ displayPath = run.outputDisplayPath+ )+ !run.outputDisplayPath.isNullOrBlank() -> RecordingOutputTarget.FileTarget(File(run.outputDisplayPath))+ else -> throw IllegalStateException("Recording output target is unavailable.")+ }++ private fun RecordingRunEntity.toStandaloneDomain(): RecordingItem = RecordingItem(+ id = id,+ scheduleId = scheduleId,+ providerId = providerId,+ channelId = channelId,+ channelName = channelName,+ streamUrl = streamUrl,+ scheduledStartMs = scheduledStartMs,+ scheduledEndMs = scheduledEndMs,+ programTitle = programTitle,+ outputPath = outputDisplayPath,+ outputUri = outputUri,+ outputDisplayPath = outputDisplayPath,+ recurrence = recurrence,+ recurringRuleId = recurringRuleId,+ status = status,+ sourceType = sourceType,+ bytesWritten = bytesWritten,+ averageThroughputBytesPerSecond = averageThroughputBytesPerSecond,+ retryCount = retryCount,+ lastProgressAtMs = lastProgressAtMs,+ failureCategory = failureCategory,+ scheduleEnabled = scheduleEnabled,+ priority = priority,+ failureReason = failureReason,+ terminalAtMs = terminalAtMs+ )++ private fun recurrenceIntervalMs(recurrence: RecordingRecurrence): Long = when (recurrence) {RecordingRecurrence.NONE -> 0LRecordingRecurrence.DAILY -> 24L * 60L * 60L * 1000LRecordingRecurrence.WEEKLY -> 7L * 24L * 60L * 60L * 1000L}--private fun RecordingStatus.isTerminal(): Boolean = when (this) {- RecordingStatus.SCHEDULED,- RecordingStatus.RECORDING -> false- RecordingStatus.COMPLETED,- RecordingStatus.FAILED,- RecordingStatus.CANCELLED -> true}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmReceiver.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmReceiver.ktnew file mode 100644index 00000000..930f3b87--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmReceiver.kt@@ -0,0 +1,22 @@+package com.streamvault.data.manager.recording++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent++class RecordingAlarmReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ val recordingId = intent.getStringExtra(EXTRA_RECORDING_ID).orEmpty()+ when (intent.action) {+ ACTION_START_RECORDING -> RecordingForegroundService.startCapture(context, recordingId)+ ACTION_STOP_RECORDING -> RecordingForegroundService.stopRecording(context, recordingId)+ }+ }++ companion object {+ const val ACTION_START_RECORDING = "com.streamvault.data.recording.action.START"+ const val ACTION_STOP_RECORDING = "com.streamvault.data.recording.action.STOP"+ const val EXTRA_RECORDING_ID = "recording_id"+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.ktnew file mode 100644index 00000000..9d970f62--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingAlarmScheduler.kt@@ -0,0 +1,92 @@+package com.streamvault.data.manager.recording++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.core.app.AlarmManagerCompat+import dagger.hilt.android.qualifiers.ApplicationContext+import javax.inject.Inject+import javax.inject.Singleton++@Singleton+class RecordingAlarmScheduler @Inject constructor(+ @ApplicationContext private val context: Context+) {++ private val alarmManager: AlarmManager? by lazy {+ context.getSystemService(AlarmManager::class.java)+ }++ fun scheduleStart(recordingId: String, whenMs: Long) {+ schedule(+ action = RecordingAlarmReceiver.ACTION_START_RECORDING,+ recordingId = recordingId,+ whenMs = whenMs+ )+ }++ fun scheduleStop(recordingId: String, whenMs: Long) {+ schedule(+ action = RecordingAlarmReceiver.ACTION_STOP_RECORDING,+ recordingId = recordingId,+ whenMs = whenMs+ )+ }++ fun cancel(recordingId: String) {+ alarmManager?.cancel(+ buildPendingIntent(+ action = RecordingAlarmReceiver.ACTION_START_RECORDING,+ recordingId = recordingId,+ flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ )+ alarmManager?.cancel(+ buildPendingIntent(+ action = RecordingAlarmReceiver.ACTION_STOP_RECORDING,+ recordingId = recordingId,+ flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ )+ }++ private fun schedule(action: String, recordingId: String, whenMs: Long) {+ val pendingIntent = buildPendingIntent(+ action = action,+ recordingId = recordingId,+ flags = PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ val manager = alarmManager ?: return+ runCatching {+ AlarmManagerCompat.setExactAndAllowWhileIdle(+ manager,+ AlarmManager.RTC_WAKEUP,+ whenMs,+ pendingIntent+ )+ }.getOrElse {+ AlarmManagerCompat.setAndAllowWhileIdle(+ manager,+ AlarmManager.RTC_WAKEUP,+ whenMs,+ pendingIntent+ )+ }+ }++ private fun buildPendingIntent(action: String, recordingId: String, flags: Int): PendingIntent {+ val intent = Intent(context, RecordingAlarmReceiver::class.java)+ .setAction(action)+ .putExtra(RecordingAlarmReceiver.EXTRA_RECORDING_ID, recordingId)+ return PendingIntent.getBroadcast(+ context,+ requestCode(action, recordingId),+ intent,+ flags+ )+ }++ private fun requestCode(action: String, recordingId: String): Int =+ 31 * action.hashCode() + recordingId.hashCode()+}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.ktnew file mode 100644index 00000000..562d6102--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingCaptureEngine.kt@@ -0,0 +1,295 @@+package com.streamvault.data.manager.recording++import android.content.ContentResolver+import com.streamvault.domain.model.RecordingFailureCategory+import com.streamvault.domain.model.RecordingSourceType+import java.io.ByteArrayOutputStream+import java.io.IOException+import java.net.URI+import java.util.Locale+import javax.crypto.Cipher+import javax.crypto.spec.IvParameterSpec+import javax.crypto.spec.SecretKeySpec+import javax.inject.Inject+import javax.inject.Singleton+import kotlinx.coroutines.delay+import kotlinx.coroutines.ensureActive+import kotlinx.coroutines.isActive+import okhttp3.OkHttpClient+import okhttp3.Request++data class CaptureProgress(+ val bytesWritten: Long,+ val averageThroughputBytesPerSecond: Long,+ val lastProgressAtMs: Long,+ val retryCount: Int = 0+)++interface RecordingCaptureEngine {+ val sourceType: RecordingSourceType++ suspend fun capture(+ source: ResolvedRecordingSource,+ outputTarget: RecordingOutputTarget,+ contentResolver: ContentResolver,+ scheduledEndMs: Long,+ onProgress: suspend (CaptureProgress) -> Unit+ )+}++@Singleton+class TsPassThroughCaptureEngine @Inject constructor(+ private val okHttpClient: OkHttpClient+) : RecordingCaptureEngine {+ override val sourceType: RecordingSourceType = RecordingSourceType.TS++ override suspend fun capture(+ source: ResolvedRecordingSource,+ outputTarget: RecordingOutputTarget,+ contentResolver: ContentResolver,+ scheduledEndMs: Long,+ onProgress: suspend (CaptureProgress) -> Unit+ ) {+ val startMs = System.currentTimeMillis()+ var bytesWritten = 0L+ val request = Request.Builder().url(source.url).apply {+ source.userAgent?.takeIf { it.isNotBlank() }?.let { header("User-Agent", it) }+ source.headers.forEach { (key, value) -> header(key, value) }+ }.build()+ okHttpClient.newCall(request).execute().use { response ->+ if (!response.isSuccessful) throw IOException("Recording stream failed with HTTP ${response.code}")+ val body = response.body ?: throw IOException("Recording stream returned an empty body")+ val output = outputTarget.openOutputStream(contentResolver)+ ?: throw IOException("Could not open recording output target")+ output.use { sink ->+ body.byteStream().use { input ->+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ while (true) {+ kotlinx.coroutines.currentCoroutineContext().ensureActive()+ if (scheduledEndMs <= System.currentTimeMillis()) break+ val read = input.read(buffer)+ if (read <= 0) break+ sink.write(buffer, 0, read)+ bytesWritten += read+ val elapsedMs = (System.currentTimeMillis() - startMs).coerceAtLeast(1L)+ onProgress(+ CaptureProgress(+ bytesWritten = bytesWritten,+ averageThroughputBytesPerSecond = (bytesWritten * 1000L) / elapsedMs,+ lastProgressAtMs = System.currentTimeMillis()+ )+ )+ }+ sink.flush()+ }+ }+ }+ }+}++@Singleton+class HlsLiveCaptureEngine @Inject constructor(+ private val okHttpClient: OkHttpClient+) : RecordingCaptureEngine {+ override val sourceType: RecordingSourceType = RecordingSourceType.HLS++ override suspend fun capture(+ source: ResolvedRecordingSource,+ outputTarget: RecordingOutputTarget,+ contentResolver: ContentResolver,+ scheduledEndMs: Long,+ onProgress: suspend (CaptureProgress) -> Unit+ ) {+ val startMs = System.currentTimeMillis()+ var bytesWritten = 0L+ var retryCount = 0+ val headers = buildMap {+ putAll(source.headers)+ source.userAgent?.takeIf { it.isNotBlank() }?.let { put("User-Agent", it) }+ }+ val output = outputTarget.openOutputStream(contentResolver)+ ?: throw IOException("Could not open recording output target")+ output.use { sink ->+ var currentPlaylistUrl = source.url+ val seenSegments = linkedSetOf<String>()+ while (kotlinx.coroutines.currentCoroutineContext().isActive && System.currentTimeMillis() < scheduledEndMs) {+ val playlistText = fetchText(currentPlaylistUrl, headers)+ val playlist = parsePlaylist(currentPlaylistUrl, playlistText)+ when (playlist) {+ is ParsedHlsPlaylist.Master -> {+ currentPlaylistUrl = playlist.bestVariantUrl+ }+ is ParsedHlsPlaylist.Media -> {+ if (playlist.key?.method?.equals("NONE", ignoreCase = true) == false &&+ !playlist.key.method.equals("AES-128", ignoreCase = true)+ ) {+ throw UnsupportedRecordingException(+ "This HLS stream uses unsupported DRM or encryption.",+ RecordingFailureCategory.DRM_UNSUPPORTED+ )+ }+ val keyBytes = playlist.key?.takeIf { it.method.equals("AES-128", ignoreCase = true) }+ ?.let { fetchBytes(it.uri, headers) }+ playlist.segments.forEach { segment ->+ kotlinx.coroutines.currentCoroutineContext().ensureActive()+ if (segment.uri in seenSegments) return@forEach+ seenSegments += segment.uri+ val bytes = fetchBytes(segment.uri, headers)+ val payload = if (keyBytes != null) decryptAes128(bytes, keyBytes, segment.keyIv ?: playlist.key?.iv) else bytes+ sink.write(payload)+ bytesWritten += payload.size+ val elapsedMs = (System.currentTimeMillis() - startMs).coerceAtLeast(1L)+ onProgress(+ CaptureProgress(+ bytesWritten = bytesWritten,+ averageThroughputBytesPerSecond = (bytesWritten * 1000L) / elapsedMs,+ lastProgressAtMs = System.currentTimeMillis(),+ retryCount = retryCount+ )+ )+ if (System.currentTimeMillis() >= scheduledEndMs) return@forEach+ }+ sink.flush()+ retryCount = 0+ if (playlist.endList) break+ delay((playlist.targetDurationSeconds.coerceAtLeast(2) * 1000L) / 2L)+ }+ }+ }+ }+ }++ private fun fetchText(url: String, headers: Map<String, String>): String {+ val request = Request.Builder().url(url).apply {+ headers.forEach { (key, value) -> header(key, value) }+ }.build()+ okHttpClient.newCall(request).execute().use { response ->+ if (!response.isSuccessful) throw IOException("Recording stream failed with HTTP ${response.code}")+ return response.body?.string().orEmpty()+ }+ }++ private fun fetchBytes(url: String, headers: Map<String, String>): ByteArray {+ val request = Request.Builder().url(url).apply {+ headers.forEach { (key, value) -> header(key, value) }+ }.build()+ okHttpClient.newCall(request).execute().use { response ->+ if (!response.isSuccessful) throw IOException("Recording stream failed with HTTP ${response.code}")+ return response.body?.bytes() ?: ByteArray(0)+ }+ }++ private fun decryptAes128(payload: ByteArray, keyBytes: ByteArray, ivHex: String?): ByteArray {+ val iv = ivHex?.removePrefix("0x")+ ?.chunked(2)+ ?.mapNotNull { it.toIntOrNull(16)?.toByte() }+ ?.toByteArray()+ ?.takeIf { it.size == 16 }+ ?: ByteArray(16)+ val cipher = Cipher.getInstance("AES/CBC/PKCS5Padding")+ cipher.init(Cipher.DECRYPT_MODE, SecretKeySpec(keyBytes, "AES"), IvParameterSpec(iv))+ return cipher.doFinal(payload)+ }++ private fun parsePlaylist(baseUrl: String, rawText: String): ParsedHlsPlaylist {+ val lines = rawText.lineSequence().map(String::trim).filter { it.isNotEmpty() }.toList()+ if (lines.any { it.startsWith("#EXT-X-STREAM-INF", ignoreCase = true) }) {+ val variants = mutableListOf<Pair<Int, String>>()+ var pendingBandwidth = 0+ lines.forEachIndexed { index, line ->+ if (line.startsWith("#EXT-X-STREAM-INF", ignoreCase = true)) {+ pendingBandwidth = Regex("""BANDWIDTH=(\d+)""")+ .find(line)+ ?.groupValues+ ?.getOrNull(1)+ ?.toIntOrNull()+ ?: 0+ val next = lines.getOrNull(index + 1)?.takeIf { !it.startsWith("#") } ?: return@forEachIndexed+ variants += pendingBandwidth to resolveRelativeUrl(baseUrl, next)+ }+ }+ val bestVariantUrl = variants.maxByOrNull { it.first }?.second+ ?: throw IOException("No playable HLS variants were available.")+ return ParsedHlsPlaylist.Master(bestVariantUrl)+ }++ var targetDuration = 6+ var endList = false+ var currentKey: HlsKey? = null+ val segments = mutableListOf<HlsSegment>()+ lines.forEach { line ->+ when {+ line.startsWith("#EXT-X-TARGETDURATION", ignoreCase = true) -> {+ targetDuration = line.substringAfter(':', "6").toIntOrNull() ?: 6+ }+ line.startsWith("#EXT-X-ENDLIST", ignoreCase = true) -> {+ endList = true+ }+ line.startsWith("#EXT-X-KEY", ignoreCase = true) -> {+ val attrs = parseHlsAttributes(line.substringAfter(':'))+ currentKey = HlsKey(+ method = attrs["METHOD"].orEmpty(),+ uri = attrs["URI"]?.let { resolveRelativeUrl(baseUrl, it) }.orEmpty(),+ iv = attrs["IV"]+ )+ }+ line.startsWith("#") -> Unit+ else -> {+ segments += HlsSegment(+ uri = resolveRelativeUrl(baseUrl, line),+ keyIv = currentKey?.iv+ )+ }+ }+ }+ return ParsedHlsPlaylist.Media(+ targetDurationSeconds = targetDuration,+ endList = endList,+ key = currentKey,+ segments = segments+ )+ }++ private fun parseHlsAttributes(raw: String): Map<String, String> {+ val attrs = mutableMapOf<String, String>()+ val parts = raw.split(',')+ parts.forEach { part ->+ val key = part.substringBefore('=').trim()+ val value = part.substringAfter('=', "").trim().removeSurrounding("\"")+ if (key.isNotBlank()) {+ attrs[key.uppercase(Locale.ROOT)] = value+ }+ }+ return attrs+ }++ private fun resolveRelativeUrl(baseUrl: String, value: String): String {+ return runCatching { URI(baseUrl).resolve(value).toString() }.getOrDefault(value)+ }+}++private sealed interface ParsedHlsPlaylist {+ data class Master(val bestVariantUrl: String) : ParsedHlsPlaylist+ data class Media(+ val targetDurationSeconds: Int,+ val endList: Boolean,+ val key: HlsKey?,+ val segments: List<HlsSegment>+ ) : ParsedHlsPlaylist+}++private data class HlsSegment(+ val uri: String,+ val keyIv: String? = null+)++private data class HlsKey(+ val method: String,+ val uri: String,+ val iv: String? = null+)++class UnsupportedRecordingException(+ message: String,+ val category: RecordingFailureCategory+) : IOException(message)diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundService.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundService.ktnew file mode 100644index 00000000..488747c6--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingForegroundService.kt@@ -0,0 +1,163 @@+package com.streamvault.data.manager.recording++import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.app.Service+import android.content.Context+import android.content.Intent+import android.os.Build+import android.os.IBinder+import androidx.core.app.NotificationCompat+import androidx.core.content.ContextCompat+import com.streamvault.data.R+import com.streamvault.domain.manager.RecordingManager+import dagger.hilt.EntryPoint+import dagger.hilt.InstallIn+import dagger.hilt.android.EntryPointAccessors+import dagger.hilt.components.SingletonComponent+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.flow.collectLatest+import kotlinx.coroutines.launch++class RecordingForegroundService : Service() {++ @EntryPoint+ @InstallIn(SingletonComponent::class)+ interface RecordingServiceEntryPoint {+ fun recordingManager(): RecordingManager+ }++ private val serviceScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate)+ private var notificationJob: Job? = null++ override fun onCreate() {+ super.onCreate()+ createNotificationChannel()+ }++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ startForeground(NOTIFICATION_ID, buildNotification(activeCount = 0))+ ensureNotificationObserver()+ val manager = entryPoint().recordingManager()+ when (intent?.action) {+ ACTION_START_CAPTURE -> {+ val recordingId = intent.getStringExtra(EXTRA_RECORDING_ID).orEmpty()+ serviceScope.launch { manager.promoteScheduledRecording(recordingId) }+ }+ ACTION_STOP_CAPTURE -> {+ val recordingId = intent.getStringExtra(EXTRA_RECORDING_ID).orEmpty()+ serviceScope.launch { manager.stopRecording(recordingId) }+ }+ ACTION_RECONCILE -> {+ serviceScope.launch { manager.reconcileRecordingState() }+ }+ }+ return START_STICKY+ }++ override fun onDestroy() {+ notificationJob?.cancel()+ serviceScope.cancel()+ super.onDestroy()+ }++ override fun onBind(intent: Intent?): IBinder? = null++ private fun ensureNotificationObserver() {+ if (notificationJob != null) return+ notificationJob = serviceScope.launch {+ entryPoint().recordingManager().observeActiveRecordingCount().collectLatest { activeCount ->+ val count = activeCount.coerceAtLeast(0)+ val manager = getSystemService(NotificationManager::class.java)+ manager.notify(NOTIFICATION_ID, buildNotification(count))+ if (count == 0) {+ stopForeground(STOP_FOREGROUND_REMOVE)+ stopSelf()+ }+ }+ }+ }++ private fun buildNotification(activeCount: Int): Notification {+ val title = if (activeCount > 0) {+ "$activeCount recording${if (activeCount == 1) "" else "s"} in progress"+ } else {+ "Preparing recording service"+ }+ return NotificationCompat.Builder(this, CHANNEL_ID)+ .setSmallIcon(android.R.drawable.stat_sys_warning)+ .setContentTitle("StreamVault DVR")+ .setContentText(title)+ .setOngoing(activeCount > 0)+ .setOnlyAlertOnce(true)+ .setCategory(NotificationCompat.CATEGORY_SERVICE)+ .setPriority(NotificationCompat.PRIORITY_LOW)+ .setContentIntent(defaultContentIntent())+ .build()+ }++ private fun defaultContentIntent(): PendingIntent? {+ val launchIntent = packageManager.getLaunchIntentForPackage(packageName) ?: return null+ return PendingIntent.getActivity(+ this,+ 1001,+ launchIntent,+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ }++ private fun createNotificationChannel() {+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return+ val manager = getSystemService(NotificationManager::class.java)+ val channel = NotificationChannel(+ CHANNEL_ID,+ "StreamVault DVR",+ NotificationManager.IMPORTANCE_LOW+ ).apply {+ description = "Active recording and scheduling status"+ }+ manager.createNotificationChannel(channel)+ }++ private fun entryPoint(): RecordingServiceEntryPoint =+ EntryPointAccessors.fromApplication(applicationContext, RecordingServiceEntryPoint::class.java)++ companion object {+ private const val CHANNEL_ID = "streamvault_recording"+ private const val NOTIFICATION_ID = 4102+ private const val ACTION_START_CAPTURE = "com.streamvault.data.recording.service.START_CAPTURE"+ private const val ACTION_STOP_CAPTURE = "com.streamvault.data.recording.service.STOP_CAPTURE"+ private const val ACTION_RECONCILE = "com.streamvault.data.recording.service.RECONCILE"+ private const val EXTRA_RECORDING_ID = "recording_id"++ fun startCapture(context: Context, recordingId: String) {+ val intent = Intent(context, RecordingForegroundService::class.java)+ .setAction(ACTION_START_CAPTURE)+ .putExtra(EXTRA_RECORDING_ID, recordingId)+ ContextCompat.startForegroundService(context, intent)+ }++ fun stopRecording(context: Context, recordingId: String) {+ val intent = Intent(context, RecordingForegroundService::class.java)+ .setAction(ACTION_STOP_CAPTURE)+ .putExtra(EXTRA_RECORDING_ID, recordingId)+ ContextCompat.startForegroundService(context, intent)+ }++ fun requestReconcile(context: Context) {+ val intent = Intent(context, RecordingForegroundService::class.java)+ .setAction(ACTION_RECONCILE)+ ContextCompat.startForegroundService(context, intent)+ }++ fun stopIfIdle(context: Context) {+ context.stopService(Intent(context, RecordingForegroundService::class.java))+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.ktnew file mode 100644index 00000000..fa651427--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingReconcileWorker.kt@@ -0,0 +1,70 @@+package com.streamvault.data.manager.recording++import android.content.Context+import androidx.work.CoroutineWorker+import androidx.work.ExistingPeriodicWorkPolicy+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.PeriodicWorkRequestBuilder+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import androidx.work.Constraints+import dagger.hilt.EntryPoint+import dagger.hilt.InstallIn+import dagger.hilt.android.EntryPointAccessors+import dagger.hilt.components.SingletonComponent+import java.util.concurrent.TimeUnit++class RecordingReconcileWorker(+ appContext: Context,+ workerParams: WorkerParameters+) : CoroutineWorker(appContext, workerParams) {++ @EntryPoint+ @InstallIn(SingletonComponent::class)+ interface RecordingWorkerEntryPoint {+ fun recordingManager(): com.streamvault.domain.manager.RecordingManager+ }++ override suspend fun doWork(): Result {+ val manager = EntryPointAccessors.fromApplication(+ applicationContext,+ RecordingWorkerEntryPoint::class.java+ ).recordingManager()+ return when (manager.reconcileRecordingState()) {+ is com.streamvault.domain.model.Result.Success -> Result.success()+ is com.streamvault.domain.model.Result.Error -> Result.retry()+ com.streamvault.domain.model.Result.Loading -> Result.retry()+ }+ }++ companion object {+ private const val PERIODIC_WORK_NAME = "RecordingReconcileWorker"+ private const val ONE_SHOT_WORK_NAME = "RecordingReconcileWorkerOneShot"++ fun enqueuePeriodic(context: Context) {+ val constraints = Constraints.Builder()+ .setRequiredNetworkType(NetworkType.CONNECTED)+ .setRequiresBatteryNotLow(false)+ .build()+ val request = PeriodicWorkRequestBuilder<RecordingReconcileWorker>(6, TimeUnit.HOURS)+ .setConstraints(constraints)+ .build()+ WorkManager.getInstance(context).enqueueUniquePeriodicWork(+ PERIODIC_WORK_NAME,+ ExistingPeriodicWorkPolicy.UPDATE,+ request+ )+ }++ fun enqueueOneShot(context: Context) {+ val request = OneTimeWorkRequestBuilder<RecordingReconcileWorker>().build()+ WorkManager.getInstance(context).enqueueUniqueWork(+ ONE_SHOT_WORK_NAME,+ ExistingWorkPolicy.REPLACE,+ request+ )+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.ktnew file mode 100644index 00000000..7026cbbf--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingRestoreReceiver.kt@@ -0,0 +1,19 @@+package com.streamvault.data.manager.recording++import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent++class RecordingRestoreReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ when (intent.action) {+ Intent.ACTION_BOOT_COMPLETED,+ Intent.ACTION_MY_PACKAGE_REPLACED,+ Intent.ACTION_LOCKED_BOOT_COMPLETED -> {+ RecordingForegroundService.requestReconcile(context)+ RecordingReconcileWorker.enqueueOneShot(context)+ }+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.ktnew file mode 100644index 00000000..65989a56--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSourceResolver.kt@@ -0,0 +1,97 @@+package com.streamvault.data.manager.recording++import com.streamvault.data.local.dao.ProviderDao+import com.streamvault.data.remote.xtream.ResolvedStreamUrl+import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver+import com.streamvault.domain.model.ContentType+import com.streamvault.domain.model.RecordingFailureCategory+import com.streamvault.domain.model.RecordingSourceType+import java.io.IOException+import java.util.Locale+import javax.inject.Inject+import javax.inject.Singleton+import okhttp3.OkHttpClient+import okhttp3.Request++data class ResolvedRecordingSource(+ val url: String,+ val sourceType: RecordingSourceType,+ val headers: Map<String, String> = emptyMap(),+ val userAgent: String? = null,+ val expirationTime: Long? = null,+ val providerLabel: String? = null,+ val failureCategory: RecordingFailureCategory = RecordingFailureCategory.NONE+)++@Singleton+class RecordingSourceResolver @Inject constructor(+ private val okHttpClient: OkHttpClient,+ private val providerDao: ProviderDao,+ private val xtreamStreamUrlResolver: XtreamStreamUrlResolver+) {++ suspend fun resolveLiveSource(+ providerId: Long,+ channelId: Long,+ logicalUrl: String+ ): ResolvedRecordingSource {+ val resolved = xtreamStreamUrlResolver.resolveWithMetadata(+ url = logicalUrl,+ fallbackProviderId = providerId,+ fallbackStreamId = channelId,+ fallbackContentType = ContentType.LIVE+ ) ?: throw IOException("Recording stream URL could not be resolved.")++ val providerLabel = providerDao.getById(providerId)?.let { provider ->+ when {+ provider.type == com.streamvault.domain.model.ProviderType.XTREAM_CODES -> "${provider.name} • Xtream"+ provider.type == com.streamvault.domain.model.ProviderType.M3U -> "${provider.name} • M3U"+ else -> provider.name+ }+ }+ val inferred = sniffSourceType(resolved)+ return ResolvedRecordingSource(+ url = resolved.url,+ sourceType = inferred,+ expirationTime = resolved.expirationTime,+ providerLabel = providerLabel+ )+ }++ private fun sniffSourceType(resolved: ResolvedStreamUrl): RecordingSourceType {+ val url = resolved.url.lowercase(Locale.ROOT)+ return when {+ url.contains(".mpd") || url.contains("ext=mpd") -> RecordingSourceType.DASH+ url.contains(".ts") || url.contains("ext=ts") -> RecordingSourceType.TS+ url.contains(".m3u8") || url.contains("ext=m3u8") || url.contains("/hd") || url.contains("/sd") -> {+ probeAdaptiveType(resolved.url)+ }+ else -> probeAdaptiveType(resolved.url)+ }+ }++ private fun probeAdaptiveType(url: String): RecordingSourceType {+ val request = Request.Builder()+ .url(url)+ .header("Range", "bytes=0-2047")+ .get()+ .build()++ val bodyPrefix = runCatching {+ okHttpClient.newCall(request).execute().use { response ->+ val contentType = response.header("Content-Type").orEmpty().lowercase(Locale.ROOT)+ when {+ "application/vnd.apple.mpegurl" in contentType || "application/x-mpegurl" in contentType -> return RecordingSourceType.HLS+ "application/dash+xml" in contentType -> return RecordingSourceType.DASH+ }+ response.body?.string().orEmpty().take(1024)+ }+ }.getOrDefault("")++ return when {+ bodyPrefix.contains("#EXTM3U", ignoreCase = true) -> RecordingSourceType.HLS+ bodyPrefix.contains("<MPD", ignoreCase = true) -> RecordingSourceType.DASH+ else -> RecordingSourceType.TS+ }+ }+}diff --git a/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.kt b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.ktnew file mode 100644index 00000000..a2beb34e--- /dev/null+++ b/data/src/main/java/com/streamvault/data/manager/recording/RecordingSupport.kt@@ -0,0 +1,190 @@+package com.streamvault.data.manager.recording++import android.content.ContentResolver+import android.content.Context+import android.net.Uri+import android.os.StatFs+import androidx.documentfile.provider.DocumentFile+import com.google.gson.Gson+import com.google.gson.reflect.TypeToken+import com.streamvault.data.local.entity.RecordingRunEntity+import com.streamvault.data.local.entity.RecordingRunWithSchedule+import com.streamvault.data.local.entity.RecordingStorageEntity+import com.streamvault.domain.model.RecordingFailureCategory+import com.streamvault.domain.model.RecordingItem+import com.streamvault.domain.model.RecordingStorageConfig+import com.streamvault.domain.model.RecordingStorageState+import java.io.File+import java.io.FileOutputStream+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale++internal fun RecordingRunWithSchedule.toDomain(): RecordingItem = RecordingItem(+ id = id,+ scheduleId = scheduleId,+ providerId = providerId,+ channelId = channelId,+ channelName = channelName,+ streamUrl = streamUrl,+ scheduledStartMs = scheduledStartMs,+ scheduledEndMs = scheduledEndMs,+ programTitle = programTitle,+ outputPath = outputDisplayPath,+ outputUri = outputUri,+ outputDisplayPath = outputDisplayPath,+ recurrence = recurrence,+ recurringRuleId = recurringRuleId,+ status = status,+ sourceType = sourceType,+ bytesWritten = bytesWritten,+ averageThroughputBytesPerSecond = averageThroughputBytesPerSecond,+ retryCount = retryCount,+ lastProgressAtMs = lastProgressAtMs,+ failureCategory = failureCategory,+ scheduleEnabled = scheduleEnabled,+ priority = priority,+ failureReason = failureReason,+ terminalAtMs = terminalAtMs+)++internal fun RecordingStorageEntity.toDomain(): RecordingStorageState = RecordingStorageState(+ treeUri = treeUri,+ displayName = displayName,+ outputDirectory = outputDirectory,+ availableBytes = availableBytes,+ isWritable = isWritable,+ fileNamePattern = fileNamePattern,+ retentionDays = retentionDays,+ maxSimultaneousRecordings = maxSimultaneousRecordings+)++internal fun RecordingStorageConfig.toEntity(existing: RecordingStorageEntity?, outputDirectory: String?, availableBytes: Long?, isWritable: Boolean): RecordingStorageEntity =+ RecordingStorageEntity(+ id = existing?.id ?: 1L,+ treeUri = treeUri,+ displayName = displayName,+ outputDirectory = outputDirectory,+ availableBytes = availableBytes,+ isWritable = isWritable,+ fileNamePattern = fileNamePattern,+ retentionDays = retentionDays,+ maxSimultaneousRecordings = maxSimultaneousRecordings,+ updatedAt = System.currentTimeMillis()+ )++internal fun headersToJson(gson: Gson, headers: Map<String, String>): String =+ gson.toJson(headers)++internal fun headersFromJson(gson: Gson, raw: String?): Map<String, String> {+ if (raw.isNullOrBlank()) return emptyMap()+ val type = object : TypeToken<Map<String, String>>() {}.type+ return runCatching { gson.fromJson<Map<String, String>>(raw, type).orEmpty() }.getOrDefault(emptyMap())+}++internal fun inferFailureCategory(message: String?, fallback: RecordingFailureCategory = RecordingFailureCategory.UNKNOWN): RecordingFailureCategory {+ val normalized = message.orEmpty().lowercase(Locale.ROOT)+ return when {+ normalized.isBlank() -> fallback+ "drm" in normalized -> RecordingFailureCategory.DRM_UNSUPPORTED+ "storage" in normalized || "space" in normalized || "writable" in normalized -> RecordingFailureCategory.STORAGE+ "conflict" in normalized -> RecordingFailureCategory.SCHEDULE_CONFLICT+ "connection" in normalized || "http 401" in normalized || "http 403" in normalized || "forbidden" in normalized -> RecordingFailureCategory.AUTH+ "expired" in normalized || "token" in normalized -> RecordingFailureCategory.TOKEN_EXPIRED+ "unsupported" in normalized || "dash" in normalized -> RecordingFailureCategory.FORMAT_UNSUPPORTED+ "network" in normalized || "timeout" in normalized || "http" in normalized -> RecordingFailureCategory.NETWORK+ else -> fallback+ }+}++internal fun sanitizeRecordingFileName(+ channelName: String,+ programTitle: String?,+ startMs: Long,+ pattern: String+): String {+ val formatter = SimpleDateFormat("yyyy-MM-dd_HH-mm", Locale.US)+ val startLabel = formatter.format(Date(startMs))+ val safeChannel = channelName.replace(Regex("[^a-zA-Z0-9._ -]"), "_").trim().ifBlank { "Channel" }+ val safeProgram = programTitle+ ?.replace(Regex("[^a-zA-Z0-9._ -]"), "_")+ ?.trim()+ ?.takeIf { it.isNotBlank() }+ ?: "Program"+ val rendered = pattern+ .replace("ChannelName", safeChannel)+ .replace("ProgramTitle", safeProgram)+ .replace("yyyy-MM-dd_HH-mm", startLabel)+ return if (rendered.endsWith(".ts", ignoreCase = true)) rendered else "$rendered.ts"+}++internal fun resolveStorageDetails(+ context: Context,+ treeUriString: String?+): Triple<String?, Long?, Boolean> {+ if (treeUriString.isNullOrBlank()) {+ val recordingsDir = File(context.filesDir, "recordings").apply { mkdirs() }+ val available = runCatching { StatFs(recordingsDir.absolutePath).availableBytes }.getOrNull()+ return Triple(recordingsDir.absolutePath, available, recordingsDir.canWrite())+ }++ val treeUri = runCatching { Uri.parse(treeUriString) }.getOrNull() ?: return Triple(null, null, false)+ val documentTree = DocumentFile.fromTreeUri(context, treeUri)+ val isWritable = documentTree?.canWrite() == true+ return Triple(documentTree?.name ?: treeUriString, null, isWritable)+}++sealed interface RecordingOutputTarget {+ data class FileTarget(val file: File) : RecordingOutputTarget+ data class DocumentTarget(val uri: Uri, val displayPath: String?) : RecordingOutputTarget+}++internal fun createOutputTarget(+ context: Context,+ storage: RecordingStorageEntity,+ fileName: String+): RecordingOutputTarget {+ val treeUri = storage.treeUri+ if (treeUri.isNullOrBlank()) {+ val outputFile = File(storage.outputDirectory ?: File(context.filesDir, "recordings").absolutePath, fileName)+ outputFile.parentFile?.mkdirs()+ return RecordingOutputTarget.FileTarget(outputFile)+ }++ val uri = Uri.parse(treeUri)+ val documentTree = DocumentFile.fromTreeUri(context, uri)+ ?: throw IllegalStateException("Recording folder is unavailable.")+ val existing = documentTree.findFile(fileName)+ val document = existing ?: documentTree.createFile("video/mp2t", fileName.removeSuffix(".ts"))+ requireNotNull(document?.uri) { "Failed to create recording file." }+ return RecordingOutputTarget.DocumentTarget(document.uri, "${documentTree.name ?: "Recordings"}/$fileName")+}++internal fun deleteOutputTarget(context: Context, outputUri: String?, outputPath: String?) {+ outputUri?.let { rawUri ->+ runCatching {+ val document = DocumentFile.fromSingleUri(context, Uri.parse(rawUri))+ if (document?.exists() == true) {+ document.delete()+ }+ }+ }+ outputPath?.takeIf { it.isNotBlank() }?.let { path ->+ runCatching {+ val file = File(path)+ if (file.exists()) {+ file.delete()+ }+ }+ }+}++internal fun RecordingOutputTarget.asPersistenceValues(): Pair<String?, String?> = when (this) {+ is RecordingOutputTarget.FileTarget -> null to file.absolutePath+ is RecordingOutputTarget.DocumentTarget -> uri.toString() to displayPath+}++internal fun RecordingOutputTarget.openOutputStream(contentResolver: ContentResolver, append: Boolean = false) = when (this) {+ is RecordingOutputTarget.FileTarget -> FileOutputStream(file, append).buffered()+ is RecordingOutputTarget.DocumentTarget -> contentResolver.openOutputStream(uri, if (append) "wa" else "w")+}diff --git a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.ktindex 95cc87db..6665dee7 100644--- a/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/RecordingManager.kt@@ -2,17 +2,30 @@ package com.streamvault.domain.managerimport com.streamvault.domain.model.RecordingItemimport com.streamvault.domain.model.RecordingRequest+import com.streamvault.domain.model.RecordingStorageConfigimport com.streamvault.domain.model.RecordingStorageStateimport com.streamvault.domain.model.Resultimport kotlinx.coroutines.flow.Flow+import kotlinx.coroutines.flow.mapinterface RecordingManager {fun observeRecordingItems(): Flow<List<RecordingItem>>fun observeStorageState(): Flow<RecordingStorageState>+ fun observeActiveRecordingCount(): Flow<Int> = observeRecordingItems().map { items ->+ items.count { it.status == com.streamvault.domain.model.RecordingStatus.RECORDING }+ }suspend fun startManualRecording(request: RecordingRequest): Result<RecordingItem>suspend fun scheduleRecording(request: RecordingRequest): Result<RecordingItem>suspend fun stopRecording(recordingId: String): Result<Unit>suspend fun cancelRecording(recordingId: String): Result<Unit>suspend fun deleteRecording(recordingId: String): Result<Unit>+ suspend fun retryRecording(recordingId: String): Result<Unit> = Result.error("Retry is not supported by this recording manager.")+ suspend fun setScheduleEnabled(recordingId: String, enabled: Boolean): Result<Unit> =+ Result.error("Schedule enablement is not supported by this recording manager.")+ suspend fun updateStorageConfig(config: RecordingStorageConfig): Result<RecordingStorageState> =+ Result.error("Storage configuration is not supported by this recording manager.")+ suspend fun reconcileRecordingState(): Result<Unit> = Result.success(Unit)+ suspend fun promoteScheduledRecording(recordingId: String): Result<Unit> =+ Result.error("Scheduled promotion is not supported by this recording manager.")}diff --git a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.ktindex fa51a124..087ae0f2 100644--- a/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt+++ b/domain/src/main/java/com/streamvault/domain/model/RecordingModels.kt@@ -8,6 +8,26 @@ enum class RecordingStatus {CANCELLED}+enum class RecordingSourceType {+ TS,+ HLS,+ DASH,+ UNKNOWN+}++enum class RecordingFailureCategory {+ NONE,+ NETWORK,+ STORAGE,+ AUTH,+ TOKEN_EXPIRED,+ DRM_UNSUPPORTED,+ FORMAT_UNSUPPORTED,+ SCHEDULE_CONFLICT,+ PROVIDER_LIMIT,+ UNKNOWN+}+enum class RecordingRecurrence {NONE,DAILY,@@ -24,7 +44,9 @@ data class RecordingRequest(val programTitle: String? = null,val outputPath: String? = null,val recurrence: RecordingRecurrence = RecordingRecurrence.NONE,- val recurringRuleId: String? = null+ val recurringRuleId: String? = null,+ val recordNextProgram: Boolean = false,+ val priority: Int = 0) {init {require(channelName.isNotBlank()) { "channelName must not be blank" }@@ -36,6 +58,7 @@ data class RecordingRequest(data class RecordingItem(val id: String,+ val scheduleId: Long? = null,val providerId: Long,val channelId: Long,val channelName: String,@@ -44,9 +67,19 @@ data class RecordingItem(val scheduledEndMs: Long,val programTitle: String? = null,val outputPath: String? = null,+ val outputUri: String? = null,+ val outputDisplayPath: String? = null,val recurrence: RecordingRecurrence = RecordingRecurrence.NONE,val recurringRuleId: String? = null,val status: RecordingStatus = RecordingStatus.SCHEDULED,+ val sourceType: RecordingSourceType = RecordingSourceType.UNKNOWN,+ val bytesWritten: Long = 0L,+ val averageThroughputBytesPerSecond: Long = 0L,+ val retryCount: Int = 0,+ val lastProgressAtMs: Long? = null,+ val failureCategory: RecordingFailureCategory = RecordingFailureCategory.NONE,+ val scheduleEnabled: Boolean = true,+ val priority: Int = 0,val failureReason: String? = null,val terminalAtMs: Long? = null) {@@ -55,15 +88,39 @@ data class RecordingItem(require(channelName.isNotBlank()) { "channelName must not be blank" }require(streamUrl.isNotBlank()) { "streamUrl must not be blank" }require(scheduledEndMs > scheduledStartMs) { "scheduledEndMs must be after scheduledStartMs" }+ require(bytesWritten >= 0L) { "bytesWritten must not be negative" }+ require(averageThroughputBytesPerSecond >= 0L) { "averageThroughputBytesPerSecond must not be negative" }+ require(retryCount >= 0) { "retryCount must not be negative" }+ }+}++data class RecordingStorageConfig(+ val treeUri: String? = null,+ val displayName: String? = null,+ val fileNamePattern: String = "ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts",+ val retentionDays: Int? = null,+ val maxSimultaneousRecordings: Int = 2+) {+ init {+ require(fileNamePattern.isNotBlank()) { "fileNamePattern must not be blank" }+ require(maxSimultaneousRecordings >= 1) { "maxSimultaneousRecordings must be at least 1" }+ retentionDays?.let { require(it >= 1) { "retentionDays must be at least 1 when set" } }}}data class RecordingStorageState(+ val treeUri: String? = null,+ val displayName: String? = null,val outputDirectory: String? = null,val availableBytes: Long? = null,- val isWritable: Boolean = false+ val isWritable: Boolean = false,+ val fileNamePattern: String = "ChannelName_yyyy-MM-dd_HH-mm_ProgramTitle.ts",+ val retentionDays: Int? = null,+ val maxSimultaneousRecordings: Int = 2) {init {availableBytes?.let { require(it >= 0) { "availableBytes must be non-negative" } }+ require(maxSimultaneousRecordings >= 1) { "maxSimultaneousRecordings must be at least 1" }+ retentionDays?.let { require(it >= 1) { "retentionDays must be at least 1 when set" } }}}diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.tomlindex 36e37016..143a656e 100644--- a/gradle/libs.versions.toml+++ b/gradle/libs.versions.toml@@ -102,6 +102,7 @@ security-crypto = { group = "androidx.security", name = "security-crypto", versi# Corecore-ktx = { group = "androidx.core", name = "core-ktx", version = "1.18.0" }+documentfile = { group = "androidx.documentfile", name = "documentfile", version = "1.1.0" }activity-compose = { group = "androidx.activity", name = "activity-compose", version = "1.13.0" }work-runtime-ktx = { group = "androidx.work", name = "work-runtime-ktx", version.ref = "work" }appcompat = { group = "androidx.appcompat", name = "appcompat", version.ref = "appcompat" }diff --git a/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt b/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.ktindex ac20e275..db2bbc8b 100644--- a/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt+++ b/player/src/main/java/com/streamvault/player/playback/StreamTypeResolver.kt@@ -20,6 +20,9 @@ object StreamTypeResolver {"application/x-mpegurl")private val dashMimeHints = listOf("application/dash+xml")+ private val hlsQueryHints = listOf("ext=m3u8", "output=m3u8", "format=m3u8", "type=m3u8")+ private val tsQueryHints = listOf("ext=ts", "output=ts", "format=ts", "type=ts")+ private val hlsLiveAliases = setOf("sd", "hd", "fhd", "uhd", "4k", "playlist", "master", "index")fun resolve(streamInfo: StreamInfo, mimeType: String? = null): ResolvedStreamType {return when (streamInfo.streamType) {@@ -33,16 +36,26 @@ object StreamTypeResolver {fun resolve(url: String, mimeType: String? = null, isLive: Boolean = false): ResolvedStreamType {val normalizedMimeType = mimeType?.trim()?.lowercase(Locale.ROOT)- val path = runCatching { URI(url).path.orEmpty() }.getOrDefault(url)+ val uri = runCatching { URI(url) }.getOrNull()+ val path = uri?.path.orEmpty().ifBlank { url }.substringBefore('?').substringBefore('#').lowercase(Locale.ROOT)+ val query = uri?.rawQuery+ ?.lowercase(Locale.ROOT)+ ?: url.substringAfter('?', "")+ .substringBefore('#')+ .lowercase(Locale.ROOT)+ val lastSegment = path.substringAfterLast('/').trim()return when {normalizedMimeType != null && hlsMimeHints.any(normalizedMimeType::contains) -> ResolvedStreamType.HLSnormalizedMimeType != null && dashMimeHints.any(normalizedMimeType::contains) -> ResolvedStreamType.DASH+ hlsQueryHints.any(query::contains) -> ResolvedStreamType.HLS+ tsQueryHints.any(query::contains) -> ResolvedStreamType.MPEG_TS_LIVEpath.contains(".m3u8") -> ResolvedStreamType.HLSpath.contains(".mpd") -> ResolvedStreamType.DASHpath.endsWith(".ts") -> ResolvedStreamType.MPEG_TS_LIVE+ isLive && path.contains("/live/") && lastSegment in hlsLiveAliases -> ResolvedStreamType.HLSisLive && path.contains("/live/") && progressiveExtensions.none(path::endsWith) ->ResolvedStreamType.MPEG_TS_LIVEprogressiveExtensions.any(path::endsWith) -> ResolvedStreamType.PROGRESSIVEdiff --git a/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt b/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.ktindex baf6be1f..7232e2b1 100644--- a/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt+++ b/player/src/test/java/com/streamvault/player/playback/StreamTypeResolverTest.kt@@ -23,6 +23,24 @@ class StreamTypeResolverTest {.isEqualTo(ResolvedStreamType.MPEG_TS_LIVE)}+ @Test+ fun `live quality alias resolves to HLS`() {+ assertThat(StreamTypeResolver.resolve("https://example.com/live/AEEast/hd", isLive = true))+ .isEqualTo(ResolvedStreamType.HLS)+ }++ @Test+ fun `query hint ext m3u8 resolves to HLS`() {+ assertThat(StreamTypeResolver.resolve("https://example.com/play?id=7&ext=m3u8", isLive = true))+ .isEqualTo(ResolvedStreamType.HLS)+ }++ @Test+ fun `query hint ext ts resolves to MPEG TS live`() {+ assertThat(StreamTypeResolver.resolve("https://example.com/play?id=7&ext=ts", isLive = true))+ .isEqualTo(ResolvedStreamType.MPEG_TS_LIVE)+ }+@Testfun `mp4 resolves to progressive`() {assertThat(StreamTypeResolver.resolve("http://example.com/movie.mp4"))