StreamVault is a TV-first free IPTV player for Android TV built with Kotlin, Jetpack Compose, Room, Hilt, and Media3.
Kotlin iptv-player
feat: Enhance backup and restore functionality
David Nashashbbebf7ea84af
diff --git a/app/proguard-rules.pro b/app/proguard-rules.proindex 808c532f..59d35773 100644--- a/app/proguard-rules.pro+++ b/app/proguard-rules.pro@@ -51,6 +51,15 @@# ── Domain models (serialized by GSON / passed across modules) ──-keep class com.streamvault.domain.model.** { *; }+-keep class com.streamvault.domain.manager.BackupData { *; }+-keep class com.streamvault.domain.manager.ProviderBackupSnapshot { *; }+-keep class com.streamvault.domain.manager.PortableProviderPreferencesBackup { *; }+-keep class com.streamvault.domain.manager.BackupProviderReference { *; }+-keep class com.streamvault.domain.manager.PortableCategoryReference { *; }+-keep class com.streamvault.domain.manager.PortableVirtualGroupReference { *; }+-keep class com.streamvault.domain.manager.PortableChannelReference { *; }+-keep class com.streamvault.domain.manager.ProtectedCategoryBackup { *; }+-keep class com.streamvault.domain.manager.ScheduledRecordingBackup { *; }-keep class com.streamvault.data.local.entity.** { *; }-keep class com.streamvault.data.remote.xtream.model.** { *; }diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 7a7401e5..adf571d9 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -94,6 +94,9 @@<data android:mimeType="application/json" /><data android:mimeType="text/json" /><data android:mimeType="application/x-json" />+ <!-- TV file managers often label a JSON file generically. -->+ <data android:mimeType="application/octet-stream" />+ <data android:mimeType="text/plain" /><data android:scheme="content" android:pathPattern=".*\\.json" /><data android:scheme="file" android:pathPattern=".*\\.json" /></intent-filter>diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.ktindex 6185cd44..85465d9e 100644--- a/app/src/main/java/com/streamvault/app/MainActivity.kt+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt@@ -421,10 +421,15 @@ class MainActivity : ComponentActivity() {private fun Intent.isBackupJsonCandidate(uri: Uri): Boolean {val normalizedPath = uri.toString().substringBefore('?').lowercase(Locale.ROOT)val mimeType = type?.lowercase(Locale.ROOT).orEmpty()- val isJsonMime = mimeType in setOf("application/json", "text/json", "application/x-json")+ val isJsonMime = mimeType in setOf(+ "application/json",+ "text/json",+ "application/x-json",+ "application/octet-stream",+ "text/plain",+ )val isJsonPath = normalizedPath.endsWith(".json")- val isGenericJsonFile = mimeType == "application/octet-stream" && isJsonPath- if (!isJsonMime && !isJsonPath && !isGenericJsonFile) return false+ if (!isJsonMime && !isJsonPath) return falsereturn uri.scheme?.lowercase(Locale.ROOT) in setOf("content", "file")}diff --git a/app/src/main/java/com/streamvault/app/backup/BackupFileBridge.kt b/app/src/main/java/com/streamvault/app/backup/BackupFileBridge.ktindex a2d4d20a..55e9f8f8 100644--- a/app/src/main/java/com/streamvault/app/backup/BackupFileBridge.kt+++ b/app/src/main/java/com/streamvault/app/backup/BackupFileBridge.kt@@ -1,26 +1,228 @@package com.streamvault.app.backup+import android.content.ContentValues+import android.content.ContentUrisimport android.content.Contextimport android.content.Intentimport android.net.Uri+import android.os.Buildimport android.os.Environment+import android.provider.MediaStoreimport androidx.core.content.FileProviderimport com.streamvault.app.BuildConfigimport java.io.File+import java.io.IOExceptionimport java.time.LocalDateTimeimport java.time.format.DateTimeFormatterobject BackupFileBridge {const val MIME_TYPE_JSON = "application/json"+ private const val MAX_IMPORT_BYTES = 16L * 1024L * 1024Lprivate const val BACKUP_EXPORTS_DIR = "Backups"private const val BACKUP_IMPORTS_DIR = "backup_imports"- private val exportNameFormatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")+ private const val MANAGED_EXPORTS_PREFERENCES = "managed_backup_exports"+ private const val MANAGED_EXPORT_URIS_KEY = "uris"+ private const val MAX_MANAGED_EXPORT_URIS = 100+ private const val MANAGED_EXPORT_PREFIX = "streamvault_backup_"+ private val exportNameFormatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss_SSS")++ data class BackupFileCandidate(+ val displayName: String,+ val uri: Uri,+ val lastModifiedMs: Long,+ )++ /**+ * Lists files that StreamVault created itself and can therefore delete+ * safely. Arbitrary JSON files in a user-selected folder are intentionally+ * excluded; those remain under the user's normal file-manager control.+ */+ fun listManagedBackups(context: Context): List<BackupFileCandidate> {+ val candidates = mutableListOf<BackupFileCandidate>()+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ runCatching {+ val projection = arrayOf(+ MediaStore.MediaColumns._ID,+ MediaStore.MediaColumns.DISPLAY_NAME,+ MediaStore.MediaColumns.DATE_MODIFIED,+ )+ val relativePath = Environment.DIRECTORY_DOWNLOADS + "/StreamVault/"+ context.contentResolver.query(+ MediaStore.Downloads.EXTERNAL_CONTENT_URI,+ projection,+ "${MediaStore.MediaColumns.RELATIVE_PATH} = ? AND " ++ "${MediaStore.MediaColumns.DISPLAY_NAME} LIKE ?",+ arrayOf(relativePath, "$MANAGED_EXPORT_PREFIX%"),+ "${MediaStore.MediaColumns.DATE_MODIFIED} DESC",+ )?.use { cursor ->+ val idIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)+ val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME)+ val modifiedIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED)+ while (cursor.moveToNext()) {+ candidates += BackupFileCandidate(+ displayName = cursor.getString(nameIndex).orEmpty(),+ uri = ContentUris.withAppendedId(+ MediaStore.Downloads.EXTERNAL_CONTENT_URI,+ cursor.getLong(idIndex),+ ),+ lastModifiedMs = cursor.getLong(modifiedIndex) * 1000L,+ )+ }+ }+ }+ }++ val documentsDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) ?: context.filesDir+ listBackupFiles(documentsDir)+ .filter { it.name.startsWith(MANAGED_EXPORT_PREFIX, ignoreCase = true) }+ .mapTo(candidates, ::candidateForFile)++ registeredExportUris(context)+ .mapNotNull { uriString -> candidateForUri(context, Uri.parse(uriString)) }+ .forEach(candidates::add)++ return candidates+ .distinctBy { it.uri.toString() }+ .sortedByDescending { it.lastModifiedMs }+ }++ /** Remembers a successful export made to a user-selected SAF destination. */+ fun rememberManagedExport(context: Context, uri: Uri) {+ val preferences = context.getSharedPreferences(MANAGED_EXPORTS_PREFERENCES, Context.MODE_PRIVATE)+ val uris = (preferences.getStringSet(MANAGED_EXPORT_URIS_KEY, emptySet()).orEmpty() + uri.toString())+ .toList()+ .takeLast(MAX_MANAGED_EXPORT_URIS)+ .toSet()+ preferences.edit().putStringSet(MANAGED_EXPORT_URIS_KEY, uris).apply()+ }++ /** Deletes one entry previously returned by [listManagedBackups]. */+ fun deleteManagedBackup(context: Context, candidate: BackupFileCandidate): Boolean {+ val deleted = runCatching {+ when (candidate.uri.scheme) {+ "content" -> context.contentResolver.delete(candidate.uri, null, null) > 0+ "file" -> candidate.uri.path?.let { File(it).delete() } == true+ else -> false+ }+ }.getOrDefault(false)+ if (deleted) forgetManagedExport(context, candidate.uri)+ return deleted+ }++ fun candidateForFile(file: File): BackupFileCandidate = BackupFileCandidate(+ displayName = file.name,+ uri = Uri.fromFile(file),+ lastModifiedMs = file.lastModified(),+ )fun createExportFile(context: Context): File {val documentsDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) ?: context.filesDirreturn createExportFile(documentsDir)}+ /**+ * Creates an export destination without invoking the system document picker.+ * Android TV images commonly omit DocumentsUI, so Q+ devices use the public+ * Downloads provider and older devices fall back to app-specific storage.+ */+ fun createPickerFreeExportUri(context: Context): Uri? {+ val fileName = nextExportFileName()+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ val values = ContentValues().apply {+ put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)+ put(MediaStore.MediaColumns.MIME_TYPE, MIME_TYPE_JSON)+ put(+ MediaStore.MediaColumns.RELATIVE_PATH,+ Environment.DIRECTORY_DOWNLOADS + "/StreamVault/"+ )+ put(MediaStore.MediaColumns.IS_PENDING, 1)+ }+ val publicUri = runCatching {+ context.contentResolver.insert(+ MediaStore.Downloads.EXTERNAL_CONTENT_URI,+ values,+ )+ }.getOrNull()+ if (publicUri != null) return publicUri+ }+ return runCatching { Uri.fromFile(createExportFile(context)) }.getOrNull()+ }++ /** Publishes a picker-free export or removes its partial target on failure. */+ fun finishPickerFreeExport(context: Context, uri: Uri, success: Boolean): Boolean {+ if (uri.scheme == "content" && Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ if (!success) {+ context.contentResolver.delete(uri, null, null)+ return true+ }+ val values = ContentValues().apply {+ put(MediaStore.MediaColumns.IS_PENDING, 0)+ }+ val published = context.contentResolver.update(uri, values, null, null) > 0+ if (!published) context.contentResolver.delete(uri, null, null)+ return published+ }+ if (!success) {+ uri.path?.let { File(it).delete() }+ }+ return success+ }++ /**+ * Finds backups that StreamVault can import without launching a document+ * picker. This includes visible MediaStore downloads and the+ * app-specific fallback directory used on older Android versions.+ */+ fun listPickerFreeBackups(context: Context): List<BackupFileCandidate> {+ val candidates = mutableListOf<BackupFileCandidate>()+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {+ runCatching {+ val projection = arrayOf(+ MediaStore.MediaColumns._ID,+ MediaStore.MediaColumns.DISPLAY_NAME,+ MediaStore.MediaColumns.DATE_MODIFIED,+ )+ context.contentResolver.query(+ MediaStore.Downloads.EXTERNAL_CONTENT_URI,+ projection,+ null,+ null,+ "${MediaStore.MediaColumns.DATE_MODIFIED} DESC",+ )?.use { cursor ->+ val idIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns._ID)+ val nameIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DISPLAY_NAME)+ val modifiedIndex = cursor.getColumnIndexOrThrow(MediaStore.MediaColumns.DATE_MODIFIED)+ while (cursor.moveToNext()) {+ val displayName = cursor.getString(nameIndex).orEmpty()+ if (!displayName.endsWith(".json", ignoreCase = true)) continue+ val id = cursor.getLong(idIndex)+ candidates += BackupFileCandidate(+ displayName = displayName,+ uri = ContentUris.withAppendedId(+ MediaStore.Downloads.EXTERNAL_CONTENT_URI,+ id,+ ),+ lastModifiedMs = cursor.getLong(modifiedIndex) * 1000L,+ )+ }+ }+ }+ }++ val documentsDir = context.getExternalFilesDir(Environment.DIRECTORY_DOCUMENTS) ?: context.filesDir+ listBackupFiles(documentsDir).forEach { file ->+ candidates += BackupFileCandidate(+ displayName = file.name,+ uri = Uri.fromFile(file),+ lastModifiedMs = file.lastModified(),+ )+ }++ return candidates+ .distinctBy { it.uri.toString() }+ .sortedByDescending { it.lastModifiedMs }+ }+/*** Creates an empty timestamped backup file under [baseDir]/Backups. Used for app-private folders* on a USB drive, which can be written with a plain `file://` URI (no FileProvider needed since@@ -28,10 +230,17 @@ object BackupFileBridge {*/fun createExportFile(baseDir: File): File {val backupsDir = File(baseDir, BACKUP_EXPORTS_DIR).apply { mkdirs() }- return File(backupsDir, "streamvault_backup_${LocalDateTime.now().format(exportNameFormatter)}.json")- .also { file ->- file.parentFile?.mkdirs()- if (!file.exists()) file.createNewFile()+ val stem = nextExportFileName().removeSuffix(".json")+ var suffix = 0+ var file: File+ do {+ val suffixText = if (suffix == 0) "" else "_$suffix"+ file = File(backupsDir, "$stem$suffixText.json")+ suffix+++ } while (file.exists())+ return file.also {+ it.parentFile?.mkdirs()+ it.createNewFile()}}@@ -42,16 +251,65 @@ object BackupFileBridge {?.sortedByDescending { it.lastModified() }?: emptyList()+ private fun registeredExportUris(context: Context): Set<String> =+ context.getSharedPreferences(MANAGED_EXPORTS_PREFERENCES, Context.MODE_PRIVATE)+ .getStringSet(MANAGED_EXPORT_URIS_KEY, emptySet())+ .orEmpty()++ private fun forgetManagedExport(context: Context, uri: Uri) {+ val preferences = context.getSharedPreferences(MANAGED_EXPORTS_PREFERENCES, Context.MODE_PRIVATE)+ val remaining = registeredExportUris(context) - uri.toString()+ preferences.edit().putStringSet(MANAGED_EXPORT_URIS_KEY, remaining).apply()+ }++ private fun candidateForUri(context: Context, uri: Uri): BackupFileCandidate? = when (uri.scheme) {+ "file" -> uri.path?.let { path ->+ File(path).takeIf { it.exists() && it.isFile }?.let(::candidateForFile)+ }+ "content" -> runCatching {+ val projection = arrayOf(+ MediaStore.MediaColumns.DISPLAY_NAME,+ MediaStore.MediaColumns.DATE_MODIFIED,+ )+ context.contentResolver.query(uri, projection, null, null, null)?.use { cursor ->+ if (!cursor.moveToFirst()) return@use null+ val nameIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DISPLAY_NAME)+ val modifiedIndex = cursor.getColumnIndex(MediaStore.MediaColumns.DATE_MODIFIED)+ BackupFileCandidate(+ displayName = if (nameIndex >= 0) cursor.getString(nameIndex).orEmpty() else "backup.json",+ uri = uri,+ lastModifiedMs = if (modifiedIndex >= 0) cursor.getLong(modifiedIndex) * 1000L else 0L,+ )+ }+ }.getOrNull()+ else -> null+ }+fun copyToImportInbox(context: Context, sourceUri: Uri): Uri? {pruneImportInbox(context)val inboxDir = File(context.cacheDir, BACKUP_IMPORTS_DIR).apply { mkdirs() }val targetFile = File(inboxDir, "streamvault_import_${System.currentTimeMillis()}.json")return runCatching {context.contentResolver.openInputStream(sourceUri)?.use { input ->- targetFile.outputStream().use { output -> input.copyTo(output) }+ targetFile.outputStream().use { output ->+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ var total = 0L+ while (true) {+ val read = input.read(buffer)+ if (read < 0) break+ total += read+ if (total > MAX_IMPORT_BYTES) {+ throw IOException("Backup exceeds the ${MAX_IMPORT_BYTES / (1024 * 1024)} MiB import limit")+ }+ output.write(buffer, 0, read)+ }+ }} ?: return nullproviderUriForFile(context, targetFile)- }.getOrNull()+ }.getOrElse {+ targetFile.delete()+ null+ }}fun providerUriForFile(context: Context, file: File): Uri {@@ -75,4 +333,8 @@ object BackupFileBridge {?.filter { it.isFile && it.lastModified() < cutoff }?.forEach { it.delete() }}-}\ No newline at end of file++ private fun nextExportFileName(): String =+ "streamvault_backup_${LocalDateTime.now().format(exportNameFormatter)}.json"++}diff --git a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.ktindex 587c9a43..21b7754a 100644--- a/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/components/dialogs/PremiumDialog.kt@@ -14,15 +14,18 @@ import androidx.compose.foundation.layout.RowScopeimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.fillMaxHeightimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.focusGroupimport androidx.compose.foundation.rememberScrollStateimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.foundation.verticalScrollimport androidx.compose.runtime.Composableimport androidx.compose.runtime.LaunchedEffectimport androidx.compose.runtime.compositionLocalOf+import androidx.compose.runtime.derivedStateOfimport androidx.compose.runtime.getValueimport androidx.compose.runtime.mutableStateOfimport androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScopeimport androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier@@ -34,6 +37,7 @@ import androidx.compose.ui.input.key.onPreviewKeyEventimport androidx.compose.ui.unit.dpimport androidx.compose.ui.window.Dialogimport androidx.compose.ui.window.DialogProperties+import kotlinx.coroutines.launchimport androidx.tv.material3.Buttonimport androidx.tv.material3.ButtonDefaultsimport androidx.tv.material3.MaterialTheme@@ -41,6 +45,7 @@ import androidx.tv.material3.Surfaceimport androidx.tv.material3.SurfaceDefaultsimport androidx.tv.material3.Textimport com.streamvault.app.device.rememberIsTelevisionDevice+import com.streamvault.app.ui.design.requestFocusSafelyimport com.streamvault.app.ui.interaction.mouseClickableimport com.streamvault.app.ui.design.AppColorsimport com.streamvault.app.ui.design.FocusSpec@@ -71,6 +76,8 @@ fun PremiumDialog(widthFraction: Float = 0.42f,heightFraction: Float? = 0.88f,bodyHeightFraction: Float = 0.5f,+ bodyScrollHint: String? = null,+ initialBodyFocusRequester: androidx.compose.ui.focus.FocusRequester? = null,content: @Composable ColumnScope.() -> Unit,footer: @Composable RowScope.() -> Unit = {}) {@@ -133,14 +140,12 @@ fun PremiumDialog(}}- Box(- modifier = Modifier- .weight(1f, fill = false)- .heightIn(max = maxDialogBodyHeight)- .verticalScroll(rememberScrollState())- ) {- Column(verticalArrangement = Arrangement.spacedBy(12.dp), content = content)- }+ PremiumDialogScrollableBody(+ maxHeight = maxDialogBodyHeight,+ scrollHint = bodyScrollHint,+ initialFocusRequester = initialBodyFocusRequester,+ content = content,+ )Row(modifier = Modifier.fillMaxWidth(),@@ -202,14 +207,12 @@ fun PremiumDialog(}}- Box(- modifier = Modifier- .weight(1f, fill = false)- .heightIn(max = maxDialogBodyHeight)- .verticalScroll(rememberScrollState())- ) {- Column(verticalArrangement = Arrangement.spacedBy(12.dp), content = content)- }+ PremiumDialogScrollableBody(+ maxHeight = maxDialogBodyHeight,+ scrollHint = bodyScrollHint,+ initialFocusRequester = initialBodyFocusRequester,+ content = content,+ )Row(modifier = Modifier.fillMaxWidth(),@@ -224,6 +227,79 @@ fun PremiumDialog(}}+@Composable+private fun ColumnScope.PremiumDialogScrollableBody(+ maxHeight: androidx.compose.ui.unit.Dp,+ scrollHint: String?,+ initialFocusRequester: androidx.compose.ui.focus.FocusRequester?,+ content: @Composable ColumnScope.() -> Unit,+) {+ val scrollState = rememberScrollState()+ val coroutineScope = rememberCoroutineScope()+ val canScrollUp by remember { derivedStateOf { scrollState.value > 0 } }+ val canScrollDown by remember { derivedStateOf { scrollState.value < scrollState.maxValue } }+ LaunchedEffect(initialFocusRequester) {+ initialFocusRequester?.requestFocusSafely(+ tag = "PremiumDialogScrollableBody",+ target = "Initial body focus"+ )+ }+ Box(+ modifier = Modifier+ .weight(1f, fill = false)+ .heightIn(max = maxHeight)+ .fillMaxWidth()+ .focusGroup()+ .onPreviewKeyEvent { event ->+ if (event.nativeKeyEvent.action != AndroidKeyEvent.ACTION_DOWN) {+ return@onPreviewKeyEvent false+ }+ val delta = when (event.nativeKeyEvent.keyCode) {+ AndroidKeyEvent.KEYCODE_DPAD_UP -> -240+ AndroidKeyEvent.KEYCODE_DPAD_DOWN -> 240+ else -> 0+ }+ if (delta == 0 || scrollState.maxValue == 0) {+ return@onPreviewKeyEvent false+ }+ val target = (scrollState.value + delta).coerceIn(0, scrollState.maxValue)+ if (target != scrollState.value) {+ coroutineScope.launch {+ scrollState.animateScrollTo(target)+ }+ }+ // Keep the event available to focus navigation. This scrolls+ // the body while the focused control advances normally.+ false+ }+ ) {+ Box(+ modifier = Modifier+ .fillMaxWidth()+ .verticalScroll(scrollState)+ ) {+ Column(verticalArrangement = Arrangement.spacedBy(12.dp), content = content)+ }++ if (!scrollHint.isNullOrBlank() && (canScrollUp || canScrollDown)) {+ val arrow = when {+ canScrollUp && canScrollDown -> "↕"+ canScrollDown -> "↓"+ else -> "↑"+ }+ Text(+ text = "$arrow $scrollHint",+ modifier = Modifier+ .align(Alignment.BottomCenter)+ .background(AppColors.Surface.copy(alpha = 0.94f), RoundedCornerShape(10.dp))+ .padding(horizontal = 12.dp, vertical = 7.dp),+ style = MaterialTheme.typography.labelSmall,+ color = AppColors.TextSecondary,+ )+ }+ }+}+@Composablefun PremiumDialogActionButton(label: String,@@ -275,6 +351,7 @@ fun PremiumDialogActionButton(fun PremiumDialogFooterButton(label: String,onClick: () -> Unit,+ modifier: Modifier = Modifier,enabled: Boolean = true,destructive: Boolean = false,emphasized: Boolean = false@@ -290,7 +367,7 @@ fun PremiumDialogFooterButton(Button(onClick = { if (canInteract) onClick() },enabled = enabled,- modifier = Modifier.mouseClickable(enabled = enabled, onClick = { if (canInteract) onClick() }),+ modifier = modifier.mouseClickable(enabled = enabled, onClick = { if (canInteract) onClick() }),colors = ButtonDefaults.colors(containerColor = containerColor,contentColor = contentColor,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.ktindex bc6f06f2..1c3a3435 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupScreen.kt@@ -93,6 +93,7 @@ import com.streamvault.domain.model.StalkerCompatibilityProfileIdsimport com.streamvault.domain.model.StalkerProfileVerificationimport com.streamvault.domain.model.StalkerProtocolPreferenceimport com.streamvault.domain.model.StalkerTransportChallengeReason+import com.streamvault.domain.manager.DriveBackupSnapshotimport com.google.zxing.qrcode.QRCodeWriterimport com.google.zxing.BarcodeFormatimport android.graphics.Bitmap@@ -713,6 +714,14 @@ fun ProviderSetupScreen()}+ if (uiState.driveBackupOptions.isNotEmpty()) {+ DriveBackupSnapshotChoiceDialog(+ snapshots = uiState.driveBackupOptions,+ onSelect = viewModel::selectDriveBackup,+ onDismiss = viewModel::dismissDriveBackupOptions,+ )+ }+uiState.stalkerTransportChallenge?.let { challenge ->val (title, body) = when (challenge.reason) {StalkerTransportChallengeReason.INVALID_TLS ->@@ -3320,6 +3329,61 @@ private fun ImportOptionsDialog()}+@Composable+private fun DriveBackupSnapshotChoiceDialog(+ snapshots: List<DriveBackupSnapshot>,+ onSelect: (String) -> Unit,+ onDismiss: () -> Unit,+) {+ PremiumDialog(+ title = stringResource(R.string.settings_drive_choose_backup_title),+ subtitle = stringResource(R.string.settings_drive_choose_backup_subtitle),+ onDismissRequest = onDismiss,+ widthFraction = 0.52f,+ heightFraction = 0.82f,+ bodyHeightFraction = 0.64f,+ content = {+ Column(+ modifier = Modifier+ .fillMaxWidth()+ .verticalScroll(rememberScrollState()),+ verticalArrangement = Arrangement.spacedBy(10.dp),+ ) {+ snapshots.forEach { snapshot ->+ SmallActionButton(+ text = snapshot.fileName,+ isLoading = false,+ onClick = { onSelect(snapshot.id) },+ )+ Text(+ text = formatDriveSnapshotDetails(snapshot),+ style = MaterialTheme.typography.bodySmall,+ color = OnSurface.copy(alpha = 0.72f),+ modifier = Modifier.padding(horizontal = 8.dp),+ )+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_drive_cancel_backup_choice),+ onClick = onDismiss,+ )+ },+ )+}++private fun formatDriveSnapshotDetails(snapshot: DriveBackupSnapshot): String {+ val date = snapshot.modifiedAtMs?.let {+ java.text.DateFormat.getDateTimeInstance(+ java.text.DateFormat.SHORT,+ java.text.DateFormat.SHORT,+ ).format(java.util.Date(it))+ } ?: "Date unavailable"+ val size = if (snapshot.sizeBytes > 0L) "${snapshot.sizeBytes / 1024L} KB" else "Size unavailable"+ return "$date · $size"+}+@Composableprivate fun ImportDialogActionButton(text: String,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.ktindex 7039096f..71179acb 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModel.kt@@ -11,7 +11,9 @@ import com.streamvault.data.remote.xtream.XtreamRequestExceptionimport com.streamvault.data.remote.xtream.XtreamResponseTooLargeExceptionimport com.streamvault.data.security.CredentialDecryptionExceptionimport com.streamvault.domain.manager.BackupConflictStrategy+import com.streamvault.domain.manager.BackupRestoreOutcomeimport com.streamvault.domain.manager.DriveAuthState+import com.streamvault.domain.manager.DriveBackupSnapshotimport com.streamvault.domain.manager.DriveBackupSyncManagerimport com.streamvault.domain.manager.ProviderCredentialsimport com.streamvault.domain.model.Result as DomainResult@@ -166,35 +168,102 @@ class ProviderSetupViewModel @Inject constructor(_uiState.update {it.copy(isImportingBackup = true,+ driveBackupOptions = emptyList(),syncProgress = "Downloading from Drive...",validationError = null,- error = null+ error = null,+ pendingDriveCredentials = null)}- when (val pullResult = driveBackupSyncManager.pullBackup()) {+ when (val listResult = driveBackupSyncManager.listBackups()) {is DomainResult.Success -> {- // Best-effort companion fetch (M3). Failures are non-fatal.- val credentials = (driveBackupSyncManager.pullCredentials() as? DomainResult.Success)?.data+ if (listResult.data.isEmpty()) {+ _uiState.update {+ it.copy(+ isImportingBackup = false,+ syncProgress = null,+ pendingDriveCredentials = null,+ error = "Drive pull failed: no backups found",+ )+ }+ } else if (listResult.data.size > 1) {+ _uiState.update {+ it.copy(+ isImportingBackup = false,+ syncProgress = null,+ driveBackupOptions = listResult.data,+ )+ }+ } else {+ downloadBackupFromDrive(listResult.data.single().id)+ }+ }+ is DomainResult.Error -> {_uiState.update {it.copy(isImportingBackup = false,+ syncProgress = null,+ driveBackupOptions = emptyList(),+ pendingDriveCredentials = null,+ error = "Drive pull failed: ${listResult.message}"+ )+ }+ }+ is DomainResult.Loading -> Unit+ }+ }+ }++ fun selectDriveBackup(snapshotId: String) {+ viewModelScope.launch {+ _uiState.update {+ it.copy(+ isImportingBackup = true,+ driveBackupOptions = emptyList(),+ syncProgress = "Downloading from Drive...",+ validationError = null,+ error = null,+ pendingDriveCredentials = null,+ )+ }+ downloadBackupFromDrive(snapshotId)+ }+ }++ fun dismissDriveBackupOptions() {+ _uiState.update { it.copy(driveBackupOptions = emptyList()) }+ }++ private suspend fun downloadBackupFromDrive(snapshotId: String) {+ when (val pullResult = driveBackupSyncManager.pullBackup(snapshotId)) {+ is DomainResult.Success -> {+ // New bundles carry credentials with the exact backup+ // snapshot. Legacy standalone backups fall back to the+ // old companion credentials file.+ val credentials = pullResult.data.credentials+ ?: (driveBackupSyncManager.pullCredentials() as? DomainResult.Success)?.data+ _uiState.update {+ it.copy(+ isImportingBackup = false,+ driveBackupOptions = emptyList(),pendingDriveCredentials = credentials,)}- inspectBackup(pullResult.data.localUriString)+ inspectBackup(pullResult.data.localUriString, preserveDriveCredentials = true)}is DomainResult.Error -> {_uiState.update {it.copy(isImportingBackup = false,syncProgress = null,+ driveBackupOptions = emptyList(),+ pendingDriveCredentials = null,error = "Drive pull failed: ${pullResult.message}")}}is DomainResult.Loading -> Unit}- }}private suspend fun applyPendingDriveCredentials() {@@ -925,13 +994,18 @@ class ProviderSetupViewModel @Inject constructor(}}- fun inspectBackup(uriString: String) {+ fun inspectBackup(uriString: String, preserveDriveCredentials: Boolean = false) {viewModelScope.launch {_uiState.update {it.copy(syncProgress = "Reading backup...",validationError = null,- error = null+ error = null,+ pendingDriveCredentials = if (preserveDriveCredentials) {+ it.pendingDriveCredentials+ } else {+ null+ })}val result = importBackup.inspect(InspectBackupCommand(uriString))@@ -939,6 +1013,7 @@ class ProviderSetupViewModel @Inject constructor(when (result) {is InspectBackupResult.Error -> state.copy(syncProgress = null,+ pendingDriveCredentials = null,error = "Import failed: ${result.message}")@@ -958,7 +1033,8 @@ class ProviderSetupViewModel @Inject constructor(it.copy(backupPreview = null,pendingBackupUri = null,- backupImportPlan = BackupImportPlan()+ backupImportPlan = BackupImportPlan(),+ pendingDriveCredentials = null)}}@@ -1015,7 +1091,10 @@ class ProviderSetupViewModel @Inject constructor(val plan = capturedPlan ?: returnviewModelScope.launch {val result = importBackup.confirm(ImportBackupCommand(uriString, plan))- if (result is ImportBackupResult.Success) {+ val completed = (result as? ImportBackupResult.Success)+ ?.result+ ?.outcome == BackupRestoreOutcome.COMPLETE+ if (completed) {applyPendingDriveCredentials()}val hasProviders = if (result is ImportBackupResult.Success) {@@ -1027,9 +1106,9 @@ class ProviderSetupViewModel @Inject constructor(state.copy(isImportingBackup = false,syncProgress = null,- backupPreview = null,- pendingBackupUri = null,- backupImportPlan = BackupImportPlan(),+ backupPreview = if (completed) null else state.backupPreview,+ pendingBackupUri = if (completed) null else state.pendingBackupUri,+ backupImportPlan = if (completed) BackupImportPlan() else state.backupImportPlan,backupImportSuccess = hasProviders,error = if (result is ImportBackupResult.Error) {"Import failed: ${result.message}"@@ -1275,6 +1354,7 @@ data class ProviderSetupState(val backupImportPlan: BackupImportPlan = BackupImportPlan(),val pendingDriveCredentials: List<ProviderCredentials>? = null,val driveSignedIn: Boolean = false,+ val driveBackupOptions: List<DriveBackupSnapshot> = emptyList(),val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,val stalkerCatalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,val xtreamLiveSyncMode: ProviderXtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO,diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.ktindex 2a3b1151..486e8bd8 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupAboutSections.kt@@ -6,6 +6,7 @@ import androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.layout.widthimport androidx.compose.foundation.lazy.LazyListScopeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.runtime.LaunchedEffect@@ -14,7 +15,6 @@ import androidx.compose.ui.Modifierimport androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.text.font.FontWeight-import androidx.compose.ui.text.style.TextAlignimport androidx.compose.ui.unit.dpimport androidx.tv.material3.ClickableSurfaceDefaultsimport androidx.tv.material3.MaterialTheme@@ -31,6 +31,7 @@ import com.streamvault.domain.manager.DriveAuthStateinternal fun LazyListScope.settingsBackupSection(onCreateBackup: () -> Unit,+ onManageLocalBackups: () -> Unit,onShareBackup: () -> Unit,onRestoreBackup: () -> Unit,onCreateBackupUsb: (() -> Unit)? = null,@@ -41,6 +42,10 @@ internal fun LazyListScope.settingsBackupSection(verticalArrangement = Arrangement.spacedBy(16.dp),modifier = Modifier.fillMaxWidth()) {+ SettingsSectionHeader(+ title = stringResource(R.string.settings_backup_restore),+ subtitle = stringResource(R.string.settings_backup_subtitle)+ )Row(horizontalArrangement = Arrangement.spacedBy(16.dp),modifier = Modifier.fillMaxWidth()@@ -70,6 +75,14 @@ internal fun LazyListScope.settingsBackupSection(onClick = onRestoreBackup,modifier = Modifier.fillMaxWidth())+ BackupActionCard(+ icon = "≡",+ title = stringResource(R.string.settings_manage_local_backups),+ subtitle = stringResource(R.string.settings_manage_local_backups_subtitle),+ accent = OnSurface,+ onClick = onManageLocalBackups,+ modifier = Modifier.fillMaxWidth()+ )if (onCreateBackupUsb != null && onRestoreBackupUsb != null) {Row(horizontalArrangement = Arrangement.spacedBy(16.dp),@@ -102,7 +115,8 @@ internal fun LazyListScope.settingsDriveBackupSection(onSignIn: () -> Unit,onSignOut: () -> Unit,onPush: () -> Unit,- onPull: () -> Unit+ onPull: () -> Unit,+ onManageBackups: () -> Unit,) {item(key = "settings_drive_section") {Column(@@ -155,12 +169,36 @@ internal fun LazyListScope.settingsDriveBackupSection(modifier = Modifier.weight(1f))}+ BackupActionCard(+ icon = "≡",+ title = stringResource(R.string.settings_manage_drive_backups),+ subtitle = stringResource(R.string.settings_manage_drive_backups_subtitle),+ accent = OnSurface,+ onClick = onManageBackups,+ modifier = Modifier.fillMaxWidth()+ )}}}}}+internal fun formatSnapshotDetails(snapshot: com.streamvault.domain.manager.DriveBackupSnapshot): String {+ val date = snapshot.modifiedAtMs?.let {+ java.text.DateFormat.getDateTimeInstance(+ java.text.DateFormat.SHORT,+ java.text.DateFormat.SHORT,+ ).format(java.util.Date(it))+ } ?: stringResource(R.string.settings_drive_unknown_backup_date)+ val size = if (snapshot.sizeBytes > 0L) {+ "${snapshot.sizeBytes / 1024L} KB"+ } else {+ stringResource(R.string.settings_drive_backup_size_unknown)+ }+ return "$date · $size"+}+@androidx.compose.runtime.Composableprivate fun DriveAccountRow(accountLabel: String,@@ -239,14 +277,35 @@ private fun BackupActionCard(scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),modifier = modifier) {- Column(- modifier = Modifier.padding(24.dp),- verticalArrangement = Arrangement.spacedBy(8.dp),- horizontalAlignment = Alignment.CenterHorizontally+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 20.dp, vertical = 18.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(16.dp)) {- Text(text = icon, style = MaterialTheme.typography.titleLarge, color = accent, fontWeight = FontWeight.Bold)- Text(text = title, style = MaterialTheme.typography.titleSmall, color = accent, textAlign = TextAlign.Center)- Text(text = subtitle, style = MaterialTheme.typography.bodySmall, color = OnSurfaceDim, textAlign = TextAlign.Center)+ Text(+ text = icon,+ modifier = Modifier.width(34.dp),+ style = MaterialTheme.typography.headlineSmall,+ color = accent,+ fontWeight = FontWeight.Bold,+ )+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ Text(+ text = title,+ style = MaterialTheme.typography.titleSmall,+ color = OnSurface,+ )+ Text(+ text = subtitle,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ )+ }}}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.ktindex 78d39a18..eba51882 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupActions.kt@@ -21,14 +21,21 @@ internal class SettingsBackupActions(private val importBackup: ImportBackup,private val uiState: MutableStateFlow<SettingsUiState>) {- fun exportConfig(scope: CoroutineScope, uriString: String, onSuccess: (() -> Unit)? = null) {+ fun exportConfig(+ scope: CoroutineScope,+ uriString: String,+ onSuccess: (() -> Unit)? = null,+ successMessage: String? = null,+ onFinished: ((Boolean) -> Unit)? = null,+ ) {scope.launch {uiState.update {it.copy(isSyncing = true,syncStartedAt = 0L,syncSectionLabel = null,- syncCanCancel = false+ syncCanCancel = false,+ pendingDriveCredentials = null)}val result = exportBackup(ExportBackupCommand(uriString))@@ -44,10 +51,11 @@ internal class SettingsBackupActions(userMessage = if (result is ExportBackupResult.Error) {"Export failed: ${result.message}"} else {- "Configuration exported successfully"+ successMessage ?: "Configuration exported successfully"})}+ onFinished?.invoke(result is ExportBackupResult.Success)}}@@ -58,7 +66,8 @@ internal class SettingsBackupActions(isSyncing = true,syncStartedAt = 0L,syncSectionLabel = null,- syncCanCancel = false+ syncCanCancel = false,+ pendingDriveCredentials = null)}val result = importBackup.inspect(InspectBackupCommand(uriString))@@ -90,7 +99,8 @@ internal class SettingsBackupActions(it.copy(backupPreview = null,pendingBackupUri = null,- backupImportPlan = BackupImportPlan()+ backupImportPlan = BackupImportPlan(),+ pendingDriveCredentials = null)}}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupDialogs.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupDialogs.ktnew file mode 100644index 00000000..51d12adc--- /dev/null+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupDialogs.kt@@ -0,0 +1,269 @@+package com.streamvault.app.ui.screens.settings++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.foundation.shape.RoundedCornerShape+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.graphics.Color+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.unit.dp+import androidx.tv.material3.ClickableSurfaceDefaults+import androidx.tv.material3.MaterialTheme+import androidx.tv.material3.Text+import com.streamvault.app.R+import com.streamvault.app.ui.components.dialogs.PremiumDialog+import com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButton+import com.streamvault.app.ui.interaction.TvClickableSurface+import com.streamvault.app.ui.theme.OnSurface+import com.streamvault.app.ui.theme.OnSurfaceDim+import com.streamvault.app.ui.theme.Primary+import com.streamvault.app.ui.theme.SurfaceElevated++internal data class BackupDialogItem(+ val id: String,+ val title: String,+ val subtitle: String = "",+)++@Composable+internal fun BackupSelectionDialog(+ title: String,+ subtitle: String,+ items: List<BackupDialogItem>,+ emptyMessage: String,+ onSelect: (String) -> Unit,+ onDismiss: () -> Unit,+) {+ val firstItemFocusRequester = remember { FocusRequester() }++ PremiumDialog(+ title = title,+ subtitle = subtitle,+ onDismissRequest = onDismiss,+ widthFraction = 0.62f,+ heightFraction = 0.78f,+ bodyHeightFraction = 0.58f,+ bodyScrollHint = stringResource(R.string.settings_backup_preview_scroll_hint),+ initialBodyFocusRequester = firstItemFocusRequester.takeIf { items.isNotEmpty() },+ content = {+ if (items.isEmpty()) {+ Text(+ text = emptyMessage,+ style = MaterialTheme.typography.bodyLarge,+ color = OnSurfaceDim,+ )+ } else {+ items.forEachIndexed { index, item ->+ BackupDialogItemSurface(+ item = item,+ modifier = if (index == 0) {+ Modifier.focusRequester(firstItemFocusRequester)+ } else {+ Modifier+ },+ onClick = { onSelect(item.id) },+ )+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss,+ )+ },+ )+}++@Composable+internal fun BackupManagementDialog(+ title: String,+ subtitle: String,+ items: List<BackupDialogItem>,+ emptyMessage: String,+ isBusy: Boolean = false,+ onDelete: (String) -> Unit,+ onDismiss: () -> Unit,+) {+ var deleteTarget by remember { mutableStateOf<BackupDialogItem?>(null) }+ val firstItemFocusRequester = remember { FocusRequester() }++ PremiumDialog(+ title = title,+ subtitle = subtitle,+ onDismissRequest = onDismiss,+ widthFraction = 0.62f,+ heightFraction = 0.78f,+ bodyHeightFraction = 0.58f,+ bodyScrollHint = stringResource(R.string.settings_backup_preview_scroll_hint),+ initialBodyFocusRequester = firstItemFocusRequester.takeIf { items.isNotEmpty() },+ content = {+ if (items.isEmpty()) {+ Text(+ text = emptyMessage,+ style = MaterialTheme.typography.bodyLarge,+ color = OnSurfaceDim,+ )+ } else {+ items.forEachIndexed { index, item ->+ BackupDialogManagementRow(+ item = item,+ modifier = if (index == 0) {+ Modifier.focusRequester(firstItemFocusRequester)+ } else {+ Modifier+ },+ enabled = !isBusy,+ onDelete = { deleteTarget = item },+ )+ }+ }+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = onDismiss,+ enabled = !isBusy,+ )+ },+ )++ deleteTarget?.let { item ->+ PremiumDialog(+ title = stringResource(R.string.settings_backup_delete_title),+ onDismissRequest = { deleteTarget = null },+ widthFraction = 0.44f,+ heightFraction = null,+ bodyHeightFraction = 0.22f,+ content = {+ Text(+ text = stringResource(R.string.settings_backup_delete_body, item.title),+ style = MaterialTheme.typography.bodyLarge,+ color = OnSurfaceDim,+ )+ },+ footer = {+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_cancel),+ onClick = { deleteTarget = null },+ )+ PremiumDialogFooterButton(+ label = stringResource(R.string.settings_delete),+ onClick = {+ deleteTarget = null+ onDelete(item.id)+ },+ destructive = true,+ emphasized = true,+ )+ },+ )+ }+}++@Composable+private fun BackupDialogItemSurface(+ item: BackupDialogItem,+ modifier: Modifier = Modifier,+ onClick: () -> Unit,+) {+ TvClickableSurface(+ onClick = onClick,+ modifier = modifier.fillMaxWidth(),+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(16.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = SurfaceElevated.copy(alpha = 0.72f),+ focusedContainerColor = Primary.copy(alpha = 0.28f),+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1.02f),+ ) {+ Row(+ modifier = Modifier+ .fillMaxWidth()+ .padding(horizontal = 18.dp, vertical = 16.dp),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(16.dp),+ ) {+ Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ text = item.title,+ style = MaterialTheme.typography.titleSmall,+ color = OnSurface,+ )+ if (item.subtitle.isNotBlank()) {+ Text(+ text = item.subtitle,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ )+ }+ }+ Text(+ text = "→",+ style = MaterialTheme.typography.titleMedium,+ color = Primary,+ )+ }+ }+}++@Composable+private fun BackupDialogManagementRow(+ item: BackupDialogItem,+ modifier: Modifier = Modifier,+ enabled: Boolean,+ onDelete: () -> Unit,+) {+ Row(+ modifier = modifier.fillMaxWidth(),+ verticalAlignment = Alignment.CenterVertically,+ horizontalArrangement = Arrangement.spacedBy(14.dp),+ ) {+ Column(+ modifier = Modifier.weight(1f),+ verticalArrangement = Arrangement.spacedBy(4.dp),+ ) {+ Text(+ text = item.title,+ style = MaterialTheme.typography.titleSmall,+ color = OnSurface,+ )+ if (item.subtitle.isNotBlank()) {+ Text(+ text = item.subtitle,+ style = MaterialTheme.typography.bodySmall,+ color = OnSurfaceDim,+ )+ }+ }+ TvClickableSurface(+ onClick = onDelete,+ enabled = enabled,+ shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(12.dp)),+ colors = ClickableSurfaceDefaults.colors(+ containerColor = Color.White.copy(alpha = 0.08f),+ focusedContainerColor = Color.White.copy(alpha = 0.18f),+ disabledContainerColor = Color.White.copy(alpha = 0.04f),+ ),+ scale = ClickableSurfaceDefaults.scale(focusedScale = 1f),+ ) {+ Text(+ text = stringResource(R.string.settings_delete),+ modifier = Modifier.padding(horizontal = 16.dp, vertical = 11.dp),+ style = MaterialTheme.typography.labelLarge,+ color = OnSurface,+ )+ }+ }+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.ktindex 1d33fe41..2e4b3f8e 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsBackupImportPreviewDialog.kt@@ -1,21 +1,34 @@package com.streamvault.app.ui.screens.settings+import androidx.compose.foundation.BorderStrokeimport androidx.compose.foundation.layout.Arrangementimport androidx.compose.foundation.layout.Columnimport androidx.compose.foundation.layout.Rowimport androidx.compose.foundation.layout.fillMaxWidthimport androidx.compose.foundation.layout.padding+import androidx.compose.foundation.border+import androidx.compose.foundation.shape.CircleShapeimport androidx.compose.foundation.shape.RoundedCornerShapeimport androidx.compose.material3.Switchimport androidx.compose.runtime.Composable+import androidx.compose.runtime.remember+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.getValue+import androidx.compose.runtime.setValueimport androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifier+import androidx.compose.ui.focus.FocusRequester+import androidx.compose.ui.focus.focusProperties+import androidx.compose.ui.focus.focusRequester+import androidx.compose.ui.focus.onFocusChanged+import androidx.compose.ui.graphics.Colorimport androidx.compose.ui.res.stringResourceimport androidx.compose.ui.unit.dpimport androidx.tv.material3.ClickableSurfaceDefaultsimport androidx.tv.material3.MaterialThemeimport androidx.tv.material3.Textimport com.streamvault.app.R+import com.streamvault.app.device.rememberIsTelevisionDeviceimport com.streamvault.app.ui.components.dialogs.PremiumDialogimport com.streamvault.app.ui.components.dialogs.PremiumDialogFooterButtonimport com.streamvault.app.ui.interaction.TvClickableSurface@@ -45,11 +58,18 @@ internal fun BackupImportPreviewDialog() {val anyEnabled = plan.importPreferences || plan.importProviders || plan.importSavedLibrary ||plan.importPlaybackHistory || plan.importMultiViewPresets || plan.importRecordingSchedules+ val isTelevisionDevice = rememberIsTelevisionDevice()+ val firstBodyFocusRequester = remember { FocusRequester() }+PremiumDialog(title = stringResource(R.string.settings_backup_preview_title),subtitle = stringResource(R.string.settings_backup_preview_subtitle, preview.version),onDismissRequest = if (isImporting) ({}) else onDismiss,widthFraction = 0.58f,+ heightFraction = 0.78f,+ bodyHeightFraction = 0.58f,+ bodyScrollHint = stringResource(R.string.settings_backup_preview_scroll_hint),+ initialBodyFocusRequester = if (isTelevisionDevice) firstBodyFocusRequester else null,content = {BackupPreviewRow(stringResource(R.string.settings_backup_section_preferences), preview.preferenceCount, 0)BackupPreviewRow(stringResource(R.string.settings_backup_section_providers), preview.providerCount, preview.providerConflicts)@@ -66,6 +86,7 @@ internal fun BackupImportPreviewDialog(BackupStrategyChip(title = stringResource(R.string.settings_backup_keep_existing),selected = plan.conflictStrategy == BackupConflictStrategy.KEEP_EXISTING,+ modifier = Modifier.focusRequester(firstBodyFocusRequester),onClick = { onStrategySelected(BackupConflictStrategy.KEEP_EXISTING) })BackupStrategyChip(@@ -90,11 +111,13 @@ internal fun BackupImportPreviewDialog(PremiumDialogFooterButton(label = stringResource(R.string.settings_cancel),onClick = onDismiss,+ modifier = Modifier.focusProperties { up = firstBodyFocusRequester },enabled = !isImporting)PremiumDialogFooterButton(label = stringResource(R.string.settings_backup_import_confirm),onClick = onConfirm,+ modifier = Modifier.focusProperties { up = firstBodyFocusRequester },emphasized = true,enabled = anyEnabled && !isImporting)@@ -137,10 +160,12 @@ private fun BackupPreviewRow(private fun BackupStrategyChip(title: String,selected: Boolean,+ modifier: Modifier = Modifier,onClick: () -> Unit) {TvClickableSurface(onClick = onClick,+ modifier = modifier,shape = ClickableSurfaceDefaults.shape(RoundedCornerShape(24.dp)),colors = ClickableSurfaceDefaults.colors(containerColor = if (selected) Primary.copy(alpha = 0.2f) else SurfaceElevated,@@ -162,12 +187,26 @@ private fun BackupToggleRow(checked: Boolean,onCheckedChange: (Boolean) -> Unit) {+ var isFocused by remember { mutableStateOf(false) }+Row(modifier = Modifier.fillMaxWidth(),horizontalArrangement = Arrangement.SpaceBetween,verticalAlignment = Alignment.CenterVertically) {Text(label, style = MaterialTheme.typography.bodyLarge, color = OnBackground)- Switch(checked = checked, onCheckedChange = onCheckedChange)+ Switch(+ checked = checked,+ onCheckedChange = onCheckedChange,+ modifier = Modifier+ .onFocusChanged { isFocused = it.isFocused }+ .then(+ if (isFocused) {+ Modifier.border(BorderStroke(2.dp, Color.White), CircleShape)+ } else {+ Modifier+ }+ ),+ )}-}\ No newline at end of file+}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.ktindex a6beaffd..2bcdff3b 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsContentPane.kt@@ -25,6 +25,7 @@ internal fun SettingsContentPane(onChooseRecordingFolder: () -> Unit,onUseUsbRecordingStorage: (() -> Unit)?,onCreateBackup: () -> Unit,+ onManageLocalBackups: () -> Unit,onCreateBackupUsb: (() -> Unit)?,onRestoreBackupUsb: (() -> Unit)?,onShareBackup: () -> Unit,@@ -169,6 +170,7 @@ internal fun SettingsContentPane(} else if (dialogState.selectedCategory == 5) {settingsBackupSection(onCreateBackup = onCreateBackup,+ onManageLocalBackups = onManageLocalBackups,onShareBackup = onShareBackup,onRestoreBackup = onRestoreBackup,onCreateBackupUsb = onCreateBackupUsb,@@ -179,7 +181,8 @@ internal fun SettingsContentPane(onSignIn = onDriveSignIn,onSignOut = onDriveSignOut,onPush = onDrivePush,- onPull = onDrivePull+ onPull = onDrivePull,+ onManageBackups = viewModel::manageDriveBackups,)} else if (dialogState.selectedCategory == 6) {epgSourcesSection(diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDriveBackupActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDriveBackupActions.ktindex 31bd9cbf..4f623907 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDriveBackupActions.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsDriveBackupActions.kt@@ -119,7 +119,14 @@ internal class SettingsDriveBackupActions(fun signOut(scope: CoroutineScope) {scope.launch {- uiState.update { it.copy(driveIsBusy = true) }+ uiState.update {+ it.copy(+ driveIsBusy = true,+ driveBackupOptions = emptyList(),+ driveBackupManagementOptions = emptyList(),+ pendingDriveCredentials = null,+ )+ }val result = driveManager.signOut()uiState.update { state ->when (result) {@@ -128,13 +135,24 @@ internal class SettingsDriveBackupActions(driveSyncStatus = DriveSyncStatus(),driveLastPushAt = null,driveLastPullAt = null,+ driveBackupOptions = emptyList(),+ driveBackupManagementOptions = emptyList(),+ pendingDriveCredentials = null,userMessage = "Signed out of Google Drive")is Result.Error -> state.copy(driveIsBusy = false,+ driveBackupOptions = emptyList(),+ driveBackupManagementOptions = emptyList(),+ pendingDriveCredentials = null,userMessage = "Drive sign-out failed: ${result.message}")- is Result.Loading -> state.copy(driveIsBusy = false)+ is Result.Loading -> state.copy(+ driveIsBusy = false,+ driveBackupOptions = emptyList(),+ driveBackupManagementOptions = emptyList(),+ pendingDriveCredentials = null,+ )}}}@@ -146,8 +164,34 @@ internal class SettingsDriveBackupActions(uiState.update { it.copy(userMessage = "Sign in to Google Drive first") }return@launch}- uiState.update { it.copy(driveIsBusy = true) }- val backupResult = driveManager.pushBackup()+ var started = false+ uiState.update {+ if (it.driveIsBusy) {+ it+ } else {+ started = true+ it.copy(+ driveIsBusy = true,+ driveBackupManagementOptions = emptyList(),+ pendingDriveCredentials = null,+ )+ }+ }+ if (!started) return@launch+ // Read credentials before starting the export so the Drive manager+ // can commit one matching backup+credentials bundle atomically.+ val credentials = runCatching {+ providerRepository.getAllProviderCredentials()+ }.getOrElse { error ->+ uiState.update {+ it.copy(+ driveIsBusy = false,+ userMessage = "Drive push failed: ${error.message ?: "credentials unavailable"}"+ )+ }+ return@launch+ }+ val backupResult = driveManager.pushBackup(credentials)if (backupResult is Result.Error) {uiState.update {it.copy(@@ -157,57 +201,212 @@ internal class SettingsDriveBackupActions(}return@launch}- // Chain credentials push (M3). The repository handles decryption- // internally so the cleartext never crosses the data layer except- // via the typed ProviderCredentials payload returned here.- val credentials = providerRepository.getAllProviderCredentials()- val credsResult = driveManager.pushCredentials(credentials)- uiState.update { state ->- when (credsResult) {- is Result.Success -> state.copy(+ uiState.update {+ it.copy(+ driveIsBusy = false,+ userMessage = "Backup uploaded to Google Drive"+ )+ }+ }+ }++ fun pullBackup(scope: CoroutineScope) {+ scope.launch {+ if (uiState.value.driveAuthState !is DriveAuthState.SignedIn) {+ uiState.update { it.copy(userMessage = "Sign in to Google Drive first") }+ return@launch+ }+ var started = false+ uiState.update {+ if (it.driveIsBusy) {+ it+ } else {+ started = true+ it.copy(+ driveIsBusy = true,+ driveBackupOptions = emptyList(),+ pendingDriveCredentials = null,+ )+ }+ }+ if (!started) return@launch+ val listResult = driveManager.listBackups()+ if (listResult !is Result.Success) {+ uiState.update {+ it.copy(driveIsBusy = false,- userMessage = "Backup uploaded to Google Drive"+ driveBackupOptions = emptyList(),+ pendingDriveCredentials = null,+ userMessage = "Drive pull failed: ${resultMessage(listResult)}")- is Result.Error -> state.copy(+ }+ return@launch+ }+ val snapshots = listResult.data+ if (snapshots.isEmpty()) {+ uiState.update {+ it.copy(driveIsBusy = false,- userMessage = "Backup uploaded but credentials failed: ${credsResult.message}"+ driveBackupOptions = emptyList(),+ pendingDriveCredentials = null,+ userMessage = "Drive pull failed: no backups found"+ )+ }+ return@launch+ }+ if (snapshots.size > 1) {+ uiState.update {+ it.copy(+ driveIsBusy = false,+ driveBackupOptions = snapshots,+ pendingDriveCredentials = null,)- is Result.Loading -> state.copy(driveIsBusy = false)}+ return@launch}+ pullSelectedBackup(snapshots.single().id)}}- fun pullBackup(scope: CoroutineScope) {+ fun selectBackup(scope: CoroutineScope, snapshotId: String) {+ scope.launch {+ var started = false+ uiState.update {+ if (it.driveIsBusy) {+ it+ } else {+ started = true+ it.copy(+ driveIsBusy = true,+ driveBackupOptions = emptyList(),+ pendingDriveCredentials = null,+ )+ }+ }+ if (!started) return@launch+ pullSelectedBackup(snapshotId)+ }+ }++ fun dismissBackupOptions() {+ uiState.update { it.copy(driveBackupOptions = emptyList()) }+ }++ fun manageBackups(scope: CoroutineScope) {scope.launch {if (uiState.value.driveAuthState !is DriveAuthState.SignedIn) {uiState.update { it.copy(userMessage = "Sign in to Google Drive first") }return@launch}- uiState.update { it.copy(driveIsBusy = true) }- val pullResult = driveManager.pullBackup()- if (pullResult is Result.Error) {- uiState.update {+ var started = false+ uiState.update {+ if (it.driveIsBusy) {+ it+ } else {+ started = true+ it.copy(driveIsBusy = true, driveBackupManagementOptions = emptyList())+ }+ }+ if (!started) return@launch+ when (val result = driveManager.listBackups()) {+ is Result.Success -> uiState.update {it.copy(driveIsBusy = false,- userMessage = "Drive pull failed: ${pullResult.message}"+ driveBackupManagementOptions = result.data,+ userMessage = if (result.data.isEmpty()) "No Google Drive backups found" else null,)}- return@launch+ is Result.Error -> uiState.update {+ it.copy(+ driveIsBusy = false,+ driveBackupManagementOptions = emptyList(),+ userMessage = "Drive backup management failed: ${result.message}",+ )+ }+ is Result.Loading -> uiState.update { it.copy(driveIsBusy = false) }+ }+ }+ }++ fun dismissBackupManagement() {+ uiState.update { it.copy(driveBackupManagementOptions = emptyList()) }+ }++ fun deleteBackup(scope: CoroutineScope, snapshotId: String) {+ scope.launch {+ var started = false+ uiState.update {+ if (it.driveIsBusy) {+ it+ } else {+ started = true+ it.copy(driveIsBusy = true)+ }}- val artifact = (pullResult as Result.Success).data- // Best-effort companion fetch (M3). Failures here are non-fatal —- // the user can still complete the import without credentials.- val credentialsResult = driveManager.pullCredentials()- val pendingCredentials = (credentialsResult as? Result.Success)?.data- if (credentialsResult is Result.Error) {- Log.w("DriveSync", "pullCredentials failed (non-fatal): ${credentialsResult.message}")+ if (!started) return@launch+ when (val result = driveManager.deleteBackup(snapshotId)) {+ is Result.Success -> {+ val refreshed = driveManager.listBackups()+ uiState.update {+ when (refreshed) {+ is Result.Success -> it.copy(+ driveIsBusy = false,+ driveBackupManagementOptions = refreshed.data,+ userMessage = "Drive backup deleted",+ )+ is Result.Error -> it.copy(+ driveIsBusy = false,+ driveBackupManagementOptions = emptyList(),+ userMessage = "Drive backup deleted",+ )+ is Result.Loading -> it.copy(+ driveIsBusy = false,+ driveBackupManagementOptions = emptyList(),+ userMessage = "Drive backup deleted",+ )+ }+ }+ }+ is Result.Error -> uiState.update {+ it.copy(+ driveIsBusy = false,+ userMessage = "Drive backup deletion failed: ${result.message}",+ )+ }+ is Result.Loading -> uiState.update { it.copy(driveIsBusy = false) }+ }+ }+ }++ private suspend fun pullSelectedBackup(snapshotId: String) {+ val pullResult = driveManager.pullBackup(snapshotId)+ if (pullResult is Result.Error) {+ uiState.update {+ it.copy(+ driveIsBusy = false,+ driveBackupOptions = emptyList(),+ pendingDriveCredentials = null,+ userMessage = "Drive pull failed: ${pullResult.message}"+ )+ }+ return+ }+ val artifact = (pullResult as Result.Success).data+ // New bundles carry credentials with the exact backup snapshot.+ // Legacy standalone backups still use the old companion file.+ val pendingCredentials = artifact.credentials ?: run {+ val credentialsResult = driveManager.pullCredentials()+ if (credentialsResult is Result.Error) {+ Log.w("DriveSync", "pullCredentials failed (non-fatal): ${credentialsResult.message}")+ }+ (credentialsResult as? Result.Success)?.data}val inspectResult = importBackup.inspect(InspectBackupCommand(artifact.localUriString))uiState.update { state ->when (inspectResult) {is InspectBackupResult.Success -> state.copy(driveIsBusy = false,+ driveBackupOptions = emptyList(),pendingBackupUri = inspectResult.uriString,backupPreview = inspectResult.preview,backupImportPlan = inspectResult.defaultPlan,@@ -215,11 +414,18 @@ internal class SettingsDriveBackupActions()is InspectBackupResult.Error -> state.copy(driveIsBusy = false,+ driveBackupOptions = emptyList(),+ pendingDriveCredentials = null,userMessage = "Drive import failed: ${inspectResult.message}")}}- }+ }++ private fun resultMessage(result: Result<*>): String = when (result) {+ is Result.Error -> result.message+ is Result.Loading -> "still loading"+ is Result.Success -> "unknown error"}/**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 d1f5be09..bb3536ca 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@@ -5,11 +5,8 @@ import android.content.Contextimport androidx.compose.foundation.backgroundimport androidx.compose.foundation.layout.*import androidx.compose.foundation.lazy.LazyColumn-import androidx.compose.foundation.rememberScrollState-import androidx.compose.foundation.verticalScrollimport androidx.lifecycle.compose.collectAsStateWithLifecycleimport androidx.compose.runtime.*-import androidx.compose.ui.Alignmentimport androidx.compose.ui.Modifierimport androidx.compose.ui.focus.FocusRequesterimport androidx.compose.ui.focus.focusRequester@@ -17,10 +14,8 @@ import androidx.compose.ui.platform.LocalUriHandlerimport androidx.compose.ui.unit.dpimport androidx.hilt.lifecycle.viewmodel.compose.hiltViewModelimport androidx.tv.material3.*-import androidx.compose.material3.AlertDialogimport androidx.compose.material3.SnackbarHostimport androidx.compose.material3.SnackbarHostState-import androidx.compose.material3.TextButtonimport androidx.compose.ui.graphics.Colorimport androidx.activity.compose.rememberLauncherForActivityResultimport androidx.activity.result.contract.ActivityResultContracts@@ -28,6 +23,7 @@ import android.net.Uriimport androidx.documentfile.provider.DocumentFileimport com.streamvault.app.backup.BackupFileBridgeimport com.streamvault.app.device.isFireTvDevice+import com.streamvault.app.device.isTelevisionDeviceimport com.streamvault.app.device.removableAppStorageDirsimport java.io.Fileimport com.streamvault.app.diagnostics.CrashReportStore@@ -44,15 +40,14 @@ import kotlinx.coroutines.delayimport java.time.LocalDateTimeimport java.time.format.DateTimeFormatter-private val backupFileNameFormatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss")+private val backupFileNameFormatter = DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss_SSS")private fun buildBackupFileName(): String ="streamvault_backup_${LocalDateTime.now().format(backupFileNameFormatter)}.json"-// Fire OS strips the AOSP DocumentsUI, so ACTION_CREATE_DOCUMENT and-// ACTION_OPEN_DOCUMENT have no handler and throw ActivityNotFoundException.-// ACTION_OPEN_DOCUMENT_TREE is handled by Amazon's storage UI, so on Fire TV-// we route backup export/import through a folder picker instead.+// Fire OS and some Android TV images do not ship a usable AOSP DocumentsUI.+// TV backup actions therefore use the app-managed local path directly instead+// of launching an external picker that may show "you need an app".private fun Context.isFireTv(): Boolean =packageManager.hasSystemFeature("amazon.hardware.fire_tv")@@ -87,7 +82,19 @@ fun SettingsScreen(val createDocumentLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.CreateDocument("application/json")) { uri ->- uri?.let { viewModel.exportConfig(it.toString()) }+ uri?.let {+ runCatching {+ context.contentResolver.takePersistableUriPermission(+ it,+ android.content.Intent.FLAG_GRANT_READ_URI_PERMISSION or+ android.content.Intent.FLAG_GRANT_WRITE_URI_PERMISSION,+ )+ }+ viewModel.exportConfig(+ uriString = it.toString(),+ onSuccess = { BackupFileBridge.rememberManagedExport(context, it) },+ )+ }}val openDocumentLauncher = rememberLauncherForActivityResult(@@ -96,7 +103,27 @@ fun SettingsScreen(uri?.let { viewModel.inspectBackup(it.toString()) }}- var pendingImportCandidates by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) }+ var pendingImportCandidates by remember { mutableStateOf<List<BackupDialogItem>>(emptyList()) }++ fun restoreBackupFromLocalStorage() {+ val candidates = BackupFileBridge.listPickerFreeBackups(context)+ .map {+ BackupDialogItem(+ id = it.uri.toString(),+ title = it.displayName,+ subtitle = formatBackupTimestamp(+ it.lastModifiedMs,+ context.getString(R.string.settings_drive_unknown_backup_date),+ ),+ )+ }+ when {+ candidates.isEmpty() ->+ viewModel.showUserMessage(context.getString(R.string.settings_backup_no_local_files))+ candidates.size == 1 -> viewModel.inspectBackup(candidates.first().id)+ else -> pendingImportCandidates = candidates+ }+ }val exportTreeLauncher = rememberLauncherForActivityResult(contract = ActivityResultContracts.OpenDocumentTree()@@ -119,7 +146,10 @@ fun SettingsScreen(viewModel.showUserMessage(context.getString(R.string.settings_backup_folder_create_failed))return@rememberLauncherForActivityResult}- viewModel.exportConfig(newFile.uri.toString())+ viewModel.exportConfig(+ uriString = newFile.uri.toString(),+ onSuccess = { BackupFileBridge.rememberManagedExport(context, newFile.uri) },+ )}val importTreeLauncher = rememberLauncherForActivityResult(@@ -140,11 +170,20 @@ fun SettingsScreen(val candidates = folder.listFiles().filter { it.isFile && it.name?.endsWith(".json", ignoreCase = true) == true }.sortedByDescending { it.lastModified() }- .map { (it.name ?: "backup.json") to it.uri.toString() }+ .map {+ BackupDialogItem(+ id = it.uri.toString(),+ title = it.name ?: "backup.json",+ subtitle = formatBackupTimestamp(+ it.lastModified(),+ context.getString(R.string.settings_drive_unknown_backup_date),+ ),+ )+ }when {candidates.isEmpty() ->viewModel.showUserMessage(context.getString(R.string.settings_backup_no_files_in_folder))- candidates.size == 1 -> viewModel.inspectBackup(candidates.first().second)+ candidates.size == 1 -> viewModel.inspectBackup(candidates.first().id)else -> pendingImportCandidates = candidates}}@@ -162,12 +201,60 @@ fun SettingsScreen(}}+ fun exportBackupWithoutPicker() {+ val uri = BackupFileBridge.createPickerFreeExportUri(context)+ if (uri == null) {+ viewModel.showUserMessage(context.getString(R.string.settings_backup_picker_free_failed))+ return+ }+ viewModel.exportConfig(+ uriString = uri.toString(),+ successMessage = context.getString(R.string.settings_backup_picker_free_saved),+ onFinished = { success ->+ val published = BackupFileBridge.finishPickerFreeExport(context, uri, success)+ if (success && !published) {+ viewModel.showUserMessage(context.getString(R.string.settings_backup_picker_free_failed))+ }+ },+ )+ }+// Fire-Stick-only: app-private folder on a plugged-in USB OTG drive. Null on every other device// and when no removable drive is attached, which keeps all USB controls hidden elsewhere.val usbStorageDir: File? = remember(context) {if (context.isFireTvDevice()) context.removableAppStorageDirs().firstOrNull() else null}+ var showLocalBackupManager by remember { mutableStateOf(false) }+ var managedLocalBackups by remember { mutableStateOf<List<BackupFileBridge.BackupFileCandidate>>(emptyList()) }++ fun refreshManagedLocalBackups() {+ val usbCandidates = usbStorageDir+ ?.let { dir ->+ BackupFileBridge.listBackupFiles(dir)+ .filter { it.name.startsWith("streamvault_backup_", ignoreCase = true) }+ .map(BackupFileBridge::candidateForFile)+ }+ .orEmpty()+ managedLocalBackups = (BackupFileBridge.listManagedBackups(context) + usbCandidates)+ .distinctBy { it.uri.toString() }+ .sortedByDescending { it.lastModifiedMs }+ }++ fun manageLocalBackups() {+ refreshManagedLocalBackups()+ showLocalBackupManager = true+ }++ fun deleteLocalBackup(candidate: BackupFileBridge.BackupFileCandidate) {+ if (BackupFileBridge.deleteManagedBackup(context, candidate)) {+ refreshManagedLocalBackups()+ viewModel.showUserMessage(context.getString(R.string.settings_backup_deleted))+ } else {+ viewModel.showUserMessage(context.getString(R.string.settings_backup_delete_failed))+ }+ }+fun createBackupToUsb() {val dir = usbStorageDir ?: returnval file = runCatching { BackupFileBridge.createExportFile(dir) }.getOrNull()@@ -181,11 +268,20 @@ fun SettingsScreen(fun restoreBackupFromUsb() {val dir = usbStorageDir ?: returnval candidates = BackupFileBridge.listBackupFiles(dir)- .map { (it.name) to Uri.fromFile(it).toString() }+ .map {+ BackupDialogItem(+ id = Uri.fromFile(it).toString(),+ title = it.name,+ subtitle = formatBackupTimestamp(+ it.lastModified(),+ context.getString(R.string.settings_drive_unknown_backup_date),+ ),+ )+ }when {candidates.isEmpty() ->viewModel.showUserMessage(context.getString(R.string.settings_backup_no_files_in_folder))- candidates.size == 1 -> viewModel.inspectBackup(candidates.first().second)+ candidates.size == 1 -> viewModel.inspectBackup(candidates.first().id)else -> pendingImportCandidates = candidates}}@@ -310,62 +406,67 @@ fun SettingsScreen(onCreateBackupUsb = usbStorageDir?.let { { createBackupToUsb() } },onRestoreBackupUsb = usbStorageDir?.let { { restoreBackupFromUsb() } },onCreateBackup = {- val onFireTv = context.isFireTv()- val primary: () -> Unit = if (onFireTv) {- { exportTreeLauncher.launch(null) }- } else {- { createDocumentLauncher.launch("streamvault_backup.json") }- }- val fallback: () -> Unit = if (onFireTv) {- { createDocumentLauncher.launch("streamvault_backup.json") }+ if (context.isTelevisionDevice()) {+ exportBackupWithoutPicker()} else {- { exportTreeLauncher.launch(null) }- }- try {- primary()- } catch (e: ActivityNotFoundException) {+ val onFireTv = context.isFireTv()+ val primary: () -> Unit = if (onFireTv) {+ { exportTreeLauncher.launch(null) }+ } else {+ { createDocumentLauncher.launch("streamvault_backup.json") }+ }+ val fallback: () -> Unit = if (onFireTv) {+ { createDocumentLauncher.launch("streamvault_backup.json") }+ } else {+ { exportTreeLauncher.launch(null) }+ }try {- fallback()- } catch (e2: ActivityNotFoundException) {- viewModel.showUserMessage(- context.getString(R.string.settings_backup_folder_picker_unavailable)- )+ primary()+ } catch (e: ActivityNotFoundException) {+ try {+ fallback()+ } catch (e2: ActivityNotFoundException) {+ exportBackupWithoutPicker()+ }}}},+ onManageLocalBackups = ::manageLocalBackups,onShareBackup = ::shareBackup,onViewCrashReport = viewModel::viewCrashReport,onShareCrashReport = ::shareCrashReport,onDeleteCrashReport = viewModel::deleteCrashReport,onRestoreBackup = {- val onFireTv = context.isFireTv()- val primary: () -> Unit = if (onFireTv) {- { importTreeLauncher.launch(null) }+ if (context.isTelevisionDevice()) {+ restoreBackupFromLocalStorage()} else {- {- openDocumentLauncher.launch(- arrayOf("application/json", "text/json", "application/x-json", "application/octet-stream", "*/*")- )+ val onFireTv = context.isFireTv()+ val primary: () -> Unit = if (onFireTv) {+ { importTreeLauncher.launch(null) }+ } else {+ {+ openDocumentLauncher.launch(+ arrayOf("application/json", "text/json", "application/x-json", "application/octet-stream", "*/*")+ )+ }}- }- val fallback: () -> Unit = if (onFireTv) {- {- openDocumentLauncher.launch(- arrayOf("application/json", "text/json", "application/x-json", "application/octet-stream", "*/*")- )+ val fallback: () -> Unit = if (onFireTv) {+ {+ openDocumentLauncher.launch(+ arrayOf("application/json", "text/json", "application/x-json", "application/octet-stream", "*/*")+ )+ }+ } else {+ { importTreeLauncher.launch(null) }}- } else {- { importTreeLauncher.launch(null) }- }- try {- primary()- } catch (e: ActivityNotFoundException) {try {- fallback()- } catch (e2: ActivityNotFoundException) {- viewModel.showUserMessage(- context.getString(R.string.settings_backup_folder_picker_unavailable)- )+ primary()+ } catch (e: ActivityNotFoundException) {+ try {+ fallback()+ } catch (e2: ActivityNotFoundException) {+ restoreBackupFromLocalStorage()+ }}}},@@ -392,41 +493,95 @@ fun SettingsScreen()if (pendingImportCandidates.isNotEmpty()) {- AlertDialog(- onDismissRequest = { pendingImportCandidates = emptyList() },- title = {- androidx.compose.material3.Text(- text = stringResource(R.string.settings_backup_choose_file_title)+ BackupSelectionDialog(+ title = stringResource(R.string.settings_backup_choose_file_title),+ subtitle = stringResource(R.string.settings_restore_subtitle),+ items = pendingImportCandidates,+ emptyMessage = stringResource(R.string.settings_backup_no_local_files),+ onSelect = { uri ->+ pendingImportCandidates = emptyList()+ viewModel.inspectBackup(uri)+ },+ onDismiss = { pendingImportCandidates = emptyList() },+ )+ }++ if (showLocalBackupManager) {+ BackupManagementDialog(+ title = stringResource(R.string.settings_manage_local_backups),+ subtitle = stringResource(R.string.settings_manage_local_backups_subtitle),+ items = managedLocalBackups.map { candidate ->+ BackupDialogItem(+ id = candidate.uri.toString(),+ title = candidate.displayName,+ subtitle = formatLocalBackupDetails(candidate),)},- text = {- Column(modifier = Modifier.verticalScroll(rememberScrollState())) {- pendingImportCandidates.forEach { (name, uri) ->- TextButton(- onClick = {- pendingImportCandidates = emptyList()- viewModel.inspectBackup(uri)- },- modifier = Modifier.fillMaxWidth()- ) {- androidx.compose.material3.Text(text = name, color = OnSurface)- }- }- }+ emptyMessage = stringResource(R.string.settings_backup_no_managed_files),+ onDelete = { uri ->+ managedLocalBackups+ .firstOrNull { it.uri.toString() == uri }+ ?.let(::deleteLocalBackup)},- confirmButton = {- TextButton(onClick = { pendingImportCandidates = emptyList() }) {- androidx.compose.material3.Text(- text = stringResource(R.string.settings_cancel),- color = OnSurface- )- }+ onDismiss = { showLocalBackupManager = false },+ )+ }++ if (uiState.driveBackupOptions.isNotEmpty()) {+ BackupSelectionDialog(+ title = stringResource(R.string.settings_drive_choose_backup_title),+ subtitle = stringResource(R.string.settings_drive_choose_backup_subtitle),+ items = uiState.driveBackupOptions.map { snapshot ->+ BackupDialogItem(+ id = snapshot.id,+ title = snapshot.fileName,+ subtitle = formatSnapshotDetails(snapshot),+ )+ },+ emptyMessage = stringResource(R.string.settings_backup_no_local_files),+ onSelect = viewModel::selectDriveBackup,+ onDismiss = viewModel::dismissDriveBackupOptions,+ )+ }++ if (uiState.driveBackupManagementOptions.isNotEmpty()) {+ BackupManagementDialog(+ title = stringResource(R.string.settings_drive_manage_title),+ subtitle = stringResource(R.string.settings_drive_manage_subtitle),+ items = uiState.driveBackupManagementOptions.map { snapshot ->+ BackupDialogItem(+ id = snapshot.id,+ title = snapshot.fileName,+ subtitle = formatSnapshotDetails(snapshot),+ )},- containerColor = SurfaceElevated,- titleContentColor = OnSurface,- textContentColor = TextSecondary+ emptyMessage = stringResource(R.string.settings_drive_manage_subtitle),+ isBusy = uiState.driveIsBusy,+ onDelete = viewModel::deleteDriveBackup,+ onDismiss = viewModel::dismissDriveBackupManagement,)}}++}++@Composable+internal fun formatLocalBackupDetails(candidate: BackupFileBridge.BackupFileCandidate): String {+ return formatBackupTimestamp(+ candidate.lastModifiedMs,+ stringResource(R.string.settings_drive_unknown_backup_date),+ )+}++internal fun formatBackupTimestamp(lastModifiedMs: Long, unknownDate: String): String {+ val date = if (lastModifiedMs > 0L) {+ java.text.DateFormat.getDateTimeInstance(+ java.text.DateFormat.SHORT,+ java.text.DateFormat.SHORT,+ ).format(java.util.Date(lastModifiedMs))+ } else {+ unknownDate+ }+ return date}diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.ktindex fe755813..c92b1cd6 100644--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsUiStateModel.kt@@ -6,6 +6,7 @@ import com.streamvault.app.ui.model.VodViewModeimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupPreviewimport com.streamvault.domain.manager.DriveAuthState+import com.streamvault.domain.manager.DriveBackupSnapshotimport com.streamvault.domain.manager.DriveSignInRequestimport com.streamvault.domain.manager.DriveSyncStatusimport com.streamvault.domain.manager.ProviderCredentials@@ -122,6 +123,10 @@ data class SettingsUiState(val driveLastPullAt: Long? = null,val drivePendingSignIn: DriveSignInRequest? = null,val driveIsBusy: Boolean = false,+ /** Drive snapshots waiting for the user to choose one before preview/import. */+ val driveBackupOptions: List<DriveBackupSnapshot> = emptyList(),+ /** Drive snapshots shown in the explicit manage/delete screen. */+ val driveBackupManagementOptions: List<DriveBackupSnapshot> = emptyList(),// M3 — credentials downloaded by pullBackup, waiting to be applied// to providers once the import confirm completes.val pendingDriveCredentials: List<ProviderCredentials>? = null,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 17397869..255adb80 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@@ -1135,8 +1135,19 @@ class SettingsViewModel @Inject constructor(_uiState.update { it.copy(userMessage = null) }}- fun exportConfig(uriString: String, onSuccess: (() -> Unit)? = null) {- backupActions.exportConfig(viewModelScope, uriString, onSuccess)+ fun exportConfig(+ uriString: String,+ onSuccess: (() -> Unit)? = null,+ successMessage: String? = null,+ onFinished: ((Boolean) -> Unit)? = null,+ ) {+ backupActions.exportConfig(+ scope = viewModelScope,+ uriString = uriString,+ onSuccess = onSuccess,+ successMessage = successMessage,+ onFinished = onFinished,+ )}fun inspectBackup(uriString: String) {@@ -1201,6 +1212,26 @@ class SettingsViewModel @Inject constructor(driveBackupActions.pullBackup(viewModelScope)}+ fun selectDriveBackup(snapshotId: String) {+ driveBackupActions.selectBackup(viewModelScope, snapshotId)+ }++ fun dismissDriveBackupOptions() {+ driveBackupActions.dismissBackupOptions()+ }++ fun manageDriveBackups() {+ driveBackupActions.manageBackups(viewModelScope)+ }++ fun dismissDriveBackupManagement() {+ driveBackupActions.dismissBackupManagement()+ }++ fun deleteDriveBackup(snapshotId: String) {+ driveBackupActions.deleteBackup(viewModelScope, snapshotId)+ }+fun stopRecording(recordingId: String) {recordingActions.stopRecording(viewModelScope, recordingId)}diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex a729eced..3272aa88 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -748,9 +748,19 @@<string name="settings_backup_share_failed">No app could receive the backup file.</string><string name="settings_backup_choose_file_title">Choose a backup file</string><string name="settings_backup_no_files_in_folder">No backup files (.json) found in that folder.</string>+ <string name="settings_backup_no_local_files">No local StreamVault backups found. Export one first or open a backup file with StreamVault.</string><string name="settings_backup_folder_picker_unavailable">No folder picker is available on this device.</string><string name="settings_backup_folder_create_failed">Could not create the backup file in that folder.</string><string name="settings_backup_folder_read_failed">Could not read that folder.</string>+ <string name="settings_backup_picker_free_saved">Backup saved locally. On supported TVs it is in Downloads/StreamVault; open it with a file manager.</string>+ <string name="settings_backup_picker_free_failed">Could not save the backup without a file picker.</string>+ <string name="settings_manage_local_backups">Manage local backups</string>+ <string name="settings_manage_local_backups_subtitle">Review and delete backups created by StreamVault.</string>+ <string name="settings_backup_no_managed_files">No StreamVault-created local backups found.</string>+ <string name="settings_backup_delete_title">Delete backup?</string>+ <string name="settings_backup_delete_body">Delete “%1$s” permanently?</string>+ <string name="settings_backup_deleted">Local backup deleted.</string>+ <string name="settings_backup_delete_failed">Could not delete that backup file.</string><string name="settings_crash_reports_title">Crash Reports</string><string name="settings_crash_reports_subtitle">Fatal crashes are saved locally only when the app is already crashing. You can review or share the latest report.</string><string name="settings_crash_report_latest">Latest crash</string>@@ -770,6 +780,7 @@<string name="settings_restore_subtitle">Choose a backup file, or open a backup with StreamVault from a file manager.</string><string name="settings_backup_preview_title">Review Backup Import</string><string name="settings_backup_preview_subtitle">Backup version %1$d detected. Choose what to import before making changes.</string>+ <string name="settings_backup_preview_scroll_hint">Use ↑/↓ on the remote to scroll</string><string name="settings_backup_conflict_strategy">Conflict strategy</string><string name="settings_backup_keep_existing">Keep Existing</string><string name="settings_backup_replace_existing">Replace Existing</string>@@ -1721,7 +1732,17 @@<string name="settings_drive_push">Send to Drive</string><string name="settings_drive_push_subtitle">Upload the current configuration to your Drive backup.</string><string name="settings_drive_pull">Restore from Drive</string>- <string name="settings_drive_pull_subtitle">Download the latest Drive backup and preview the import.</string>+ <string name="settings_drive_pull_subtitle">Choose a Drive backup and preview the import.</string>+ <string name="settings_drive_choose_backup_title">Choose a Drive backup</string>+ <string name="settings_drive_choose_backup_subtitle">Select a saved snapshot to preview and restore.</string>+ <string name="settings_drive_cancel_backup_choice">Cancel backup choice</string>+ <string name="settings_drive_cancel_backup_choice_subtitle">Return to the Drive backup actions.</string>+ <string name="settings_drive_unknown_backup_date">Date unavailable</string>+ <string name="settings_drive_backup_size_unknown">Size unavailable</string>+ <string name="settings_manage_drive_backups">Manage Drive backups</string>+ <string name="settings_manage_drive_backups_subtitle">Review or delete saved Drive snapshots.</string>+ <string name="settings_drive_manage_title">Saved Drive backups</string>+ <string name="settings_drive_manage_subtitle">Delete only snapshots you no longer need.</string><string name="settings_drive_last_push">Pushed: %1$s</string><string name="settings_drive_last_pull">Pulled: %1$s</string><string name="settings_drive_never_synced">Never synced yet</string>diff --git a/app/src/test/java/com/streamvault/app/backup/BackupFileBridgeTest.kt b/app/src/test/java/com/streamvault/app/backup/BackupFileBridgeTest.ktnew file mode 100644index 00000000..c86fdde3--- /dev/null+++ b/app/src/test/java/com/streamvault/app/backup/BackupFileBridgeTest.kt@@ -0,0 +1,120 @@+package com.streamvault.app.backup++import android.content.ContentResolver+import android.content.Context+import android.content.SharedPreferences+import android.net.Uri+import android.os.Build+import com.google.common.truth.Truth.assertThat+import java.io.File+import java.io.InputStream+import java.nio.file.Files+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.mockito.kotlin.mock+import org.mockito.kotlin.any+import org.mockito.kotlin.whenever+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [Build.VERSION_CODES.P])+class BackupFileBridgeTest {++ private lateinit var cacheDir: java.io.File+ private val context: Context = mock()+ private val resolver: ContentResolver = mock()+ private val sourceUri: Uri = mock()+ private val preferences: SharedPreferences = mock()+ private val preferencesEditor: SharedPreferences.Editor = mock()++ @Before+ fun setUp() {+ cacheDir = Files.createTempDirectory("backup-bridge-test").toFile()+ whenever(context.cacheDir).thenReturn(cacheDir)+ whenever(context.filesDir).thenReturn(cacheDir)+ whenever(context.contentResolver).thenReturn(resolver)+ whenever(context.getSharedPreferences(any(), any())).thenReturn(preferences)+ whenever(preferences.getStringSet(any(), any())).thenReturn(emptySet())+ whenever(preferences.edit()).thenReturn(preferencesEditor)+ whenever(preferencesEditor.putStringSet(any(), any())).thenReturn(preferencesEditor)+ }++ @After+ fun tearDown() {+ cacheDir.deleteRecursively()+ }++ @Test+ fun oversizedExternalImport_isRejectedAndPartialInboxFileIsRemoved() {+ whenever(resolver.openInputStream(sourceUri)).thenReturn(+ GeneratedInputStream(16L * 1024L * 1024L + 1L)+ )++ val result = BackupFileBridge.copyToImportInbox(context, sourceUri)++ assertThat(result).isNull()+ val inbox = java.io.File(cacheDir, "backup_imports")+ assertThat(inbox.listFiles().orEmpty()).isEmpty()+ }++ @Test+ fun pickerFreeExport_createsFallbackFileAndRemovesItOnFailure() {+ val uri = BackupFileBridge.createPickerFreeExportUri(context)+ assertThat(uri).isNotNull()+ val file = File(uri!!.path!!)+ assertThat(uri?.scheme).isEqualTo("file")+ assertThat(file.exists()).isTrue()++ assertThat(BackupFileBridge.finishPickerFreeExport(context, uri!!, success = false)).isFalse()+ assertThat(file.exists()).isFalse()+ }++ @Test+ fun pickerFreeImport_listsAppSpecificBackupsWithoutAFilePicker() {+ val backup = BackupFileBridge.createExportFile(context).apply {+ writeText("{}")+ }++ val candidates = BackupFileBridge.listPickerFreeBackups(context)++ assertThat(candidates).hasSize(1)+ assertThat(candidates.single().displayName).isEqualTo(backup.name)+ assertThat(candidates.single().uri.scheme).isEqualTo("file")+ }++ @Test+ fun managedBackups_listsAndDeletesOnlyStreamVaultCreatedFiles() {+ val backup = BackupFileBridge.createExportFile(context).apply {+ writeText("{}")+ }+ File(cacheDir, "Backups/not-created-by-streamvault.json").apply {+ parentFile?.mkdirs()+ writeText("{}")+ }++ val candidates = BackupFileBridge.listManagedBackups(context)++ assertThat(candidates.map { it.displayName }).containsExactly(backup.name)+ assertThat(BackupFileBridge.deleteManagedBackup(context, candidates.single())).isTrue()+ assertThat(backup.exists()).isFalse()+ }++ private class GeneratedInputStream(private var remaining: Long) : InputStream() {+ override fun read(): Int {+ if (remaining == 0L) return -1+ remaining--+ return 0+ }++ override fun read(buffer: ByteArray, offset: Int, length: Int): Int {+ if (remaining == 0L) return -1+ val count = minOf(remaining, length.toLong()).toInt()+ java.util.Arrays.fill(buffer, offset, offset + count, 0.toByte())+ remaining -= count+ return count+ }+ }+}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.ktindex 8a467c05..c76c3d21 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/provider/ProviderSetupViewModelTest.kt@@ -17,8 +17,12 @@ import com.streamvault.domain.repository.CombinedM3uRepositoryimport com.streamvault.domain.repository.ProviderRepositoryimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupImportResult+import com.streamvault.domain.manager.BackupRestoreOutcomeimport com.streamvault.domain.manager.DriveAuthState+import com.streamvault.domain.manager.DriveBackupSnapshotimport com.streamvault.domain.manager.DriveBackupSyncManager+import com.streamvault.domain.manager.ProviderCredentials+import com.streamvault.domain.model.Result as DomainResultimport com.streamvault.domain.usecase.ImportBackupimport com.streamvault.domain.usecase.ImportBackupResultimport com.streamvault.domain.usecase.ValidateAndAddProvider@@ -39,6 +43,7 @@ import org.mockito.kotlin.anyimport org.mockito.kotlin.argumentCaptorimport org.mockito.kotlin.eqimport org.mockito.kotlin.mock+import org.mockito.kotlin.neverimport org.mockito.kotlin.verifyimport org.mockito.kotlin.whenever@@ -180,6 +185,72 @@ class ProviderSetupViewModelTest {assertThat(viewModel.uiState.value.error).isNull()}+ @Test+ fun `partial backup import does not apply pending Drive credentials`() = runTest {+ whenever(importBackup.confirm(any())).thenReturn(+ ImportBackupResult.Success(+ BackupImportResult(+ outcome = BackupRestoreOutcome.PARTIAL,+ failedSections = listOf("Saved library/history: 1 unresolved")+ )+ )+ )+ val viewModel = ProviderSetupViewModel(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup,+ driveBackupSyncManager = driveBackupSyncManager,+ providerQrPairingManager = providerQrPairingManager,+ )+ val credentials = listOf(+ ProviderCredentials(+ serverUrl = "https://example.com",+ username = "alice",+ password = "secret"+ )+ )+ val field = ProviderSetupViewModel::class.java.getDeclaredField("_uiState").apply { isAccessible = true }+ @Suppress("UNCHECKED_CAST")+ val stateFlow = field.get(viewModel) as kotlinx.coroutines.flow.MutableStateFlow<ProviderSetupState>+ stateFlow.value = stateFlow.value.copy(+ pendingBackupUri = "content://drive-backup.json",+ backupImportPlan = BackupImportPlan(),+ pendingDriveCredentials = credentials+ )++ viewModel.confirmBackupImport()+ advanceUntilIdle()++ verify(providerRepository, org.mockito.kotlin.never()).updateProviderPassword(any(), any(), any())+ assertThat(viewModel.uiState.value.pendingDriveCredentials).isEqualTo(credentials)+ assertThat(viewModel.uiState.value.pendingBackupUri).isEqualTo("content://drive-backup.json")+ }++ @Test+ fun `drive import shows snapshot choice before downloading when multiple exist`() = runTest {+ val snapshots = listOf(+ DriveBackupSnapshot("new", "streamvault_backup_bundle_new.json"),+ DriveBackupSnapshot("old", "streamvault_backup_bundle_old.json"),+ )+ whenever(driveBackupSyncManager.listBackups()).thenReturn(DomainResult.Success(snapshots))+ val viewModel = ProviderSetupViewModel(+ providerRepository = providerRepository,+ combinedM3uRepository = combinedM3uRepository,+ validateAndAddProvider = validateAndAddProvider,+ importBackup = importBackup,+ driveBackupSyncManager = driveBackupSyncManager,+ providerQrPairingManager = providerQrPairingManager,+ )++ viewModel.importBackupFromDrive()+ advanceUntilIdle()++ assertThat(viewModel.uiState.value.driveBackupOptions).isEqualTo(snapshots)+ assertThat(viewModel.uiState.value.isImportingBackup).isFalse()+ verify(driveBackupSyncManager, never()).pullBackup(any())+ }+@Testfun `attach created provider to combined keeps combined source active`() = runTest {val viewModel = ProviderSetupViewModel(diff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsBackupActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsBackupActionsTest.ktindex 028732b0..9e595f1a 100644--- a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsBackupActionsTest.kt+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsBackupActionsTest.kt@@ -3,10 +3,12 @@ package com.streamvault.app.ui.screens.settingsimport com.google.common.truth.Truth.assertThatimport com.streamvault.domain.manager.BackupImportPlanimport com.streamvault.domain.manager.BackupImportResult+import com.streamvault.domain.manager.BackupPreviewimport com.streamvault.domain.manager.BackupRestoreOutcomeimport com.streamvault.domain.usecase.ExportBackupimport com.streamvault.domain.usecase.ImportBackupimport com.streamvault.domain.usecase.ImportBackupResult+import com.streamvault.domain.usecase.InspectBackupResultimport kotlinx.coroutines.ExperimentalCoroutinesApiimport kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.test.StandardTestDispatcher@@ -70,4 +72,47 @@ class SettingsBackupActionsTest {assertThat(uiState.value.backupImportPlan).isEqualTo(BackupImportPlan())assertThat(onSuccessCalled).isTrue()}++ @Test+ fun normalInspect_clearsCredentialsPendingFromAnEarlierDrivePull() = runTest(StandardTestDispatcher()) {+ val uiState = MutableStateFlow(+ SettingsUiState(+ pendingDriveCredentials = listOf(+ com.streamvault.domain.manager.ProviderCredentials(+ serverUrl = "https://example.com",+ username = "alice",+ password = "secret"+ )+ )+ )+ )+ val actions = SettingsBackupActions(exportBackup, importBackup, uiState)+ whenever(importBackup.inspect(org.mockito.kotlin.any())).thenReturn(+ InspectBackupResult.Success(+ uriString = "content://local-backup",+ preview = BackupPreview(+ version = 12,+ providerCount = 0,+ favoriteCount = 0,+ groupCount = 0,+ playbackHistoryCount = 0,+ multiViewPresetCount = 0,+ preferenceCount = 0,+ protectedCategoryCount = 0,+ scheduledRecordingCount = 0,+ providerConflicts = 0,+ favoriteConflicts = 0,+ groupConflicts = 0,+ historyConflicts = 0,+ protectedCategoryConflicts = 0,+ recordingConflicts = 0+ )+ )+ )++ actions.inspectBackup(this, "content://local-backup")+ advanceUntilIdle()++ assertThat(uiState.value.pendingDriveCredentials).isNull()+ }}diff --git a/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsDriveBackupActionsTest.kt b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsDriveBackupActionsTest.ktnew file mode 100644index 00000000..a0fb1ced--- /dev/null+++ b/app/src/test/java/com/streamvault/app/ui/screens/settings/SettingsDriveBackupActionsTest.kt@@ -0,0 +1,208 @@+package com.streamvault.app.ui.screens.settings++import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.manager.BackupPreview+import com.streamvault.domain.manager.DriveAuthState+import com.streamvault.domain.manager.DriveAccount+import com.streamvault.domain.manager.DriveBackupArtifact+import com.streamvault.domain.manager.DriveBackupSnapshot+import com.streamvault.domain.manager.DriveBackupSyncManager+import com.streamvault.domain.manager.DriveSyncStatus+import com.streamvault.domain.manager.ProviderCredentials+import com.streamvault.domain.model.Result+import com.streamvault.domain.repository.ProviderRepository+import com.streamvault.domain.usecase.ImportBackup+import com.streamvault.domain.usecase.InspectBackupResult+import kotlinx.coroutines.ExperimentalCoroutinesApi+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.test.StandardTestDispatcher+import kotlinx.coroutines.test.advanceUntilIdle+import kotlinx.coroutines.test.runTest+import org.junit.Test+import org.mockito.kotlin.any+import org.mockito.kotlin.eq+import org.mockito.kotlin.mock+import org.mockito.kotlin.never+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever++@OptIn(ExperimentalCoroutinesApi::class)+class SettingsDriveBackupActionsTest {++ private val driveManager: DriveBackupSyncManager = mock()+ private val importBackup: ImportBackup = mock()+ private val providerRepository: ProviderRepository = mock()++ @Test+ fun pushBackup_passesOneCredentialSnapshotAndDoesNotUseLegacySecondUpload() =+ runTest(StandardTestDispatcher()) {+ val credentials = listOf(+ ProviderCredentials("https://example.com", "alice", "secret")+ )+ whenever(providerRepository.getAllProviderCredentials()).thenReturn(credentials)+ whenever(driveManager.pushBackup(eq(credentials))).thenReturn(+ Result.Success(DriveSyncStatus(lastPushAtMs = 123L))+ )+ val uiState = MutableStateFlow(+ SettingsUiState(driveAuthState = DriveAuthState.SignedIn(DriveAccount(null, null)))+ )+ val actions = SettingsDriveBackupActions(+ driveManager = driveManager,+ importBackup = importBackup,+ providerRepository = providerRepository,+ uiState = uiState,+ )++ actions.pushBackup(this)+ advanceUntilIdle()++ verify(driveManager).pushBackup(eq(credentials))+ verify(driveManager, never()).pushCredentials(any())+ assertThat(uiState.value.userMessage).isEqualTo("Backup uploaded to Google Drive")+ assertThat(uiState.value.driveIsBusy).isFalse()+ }++ @Test+ fun pullBackup_usesBundleCredentialsWithoutFetchingLegacyCompanionFile() =+ runTest(StandardTestDispatcher()) {+ val credentials = listOf(+ ProviderCredentials("https://example.com", "alice", "secret")+ )+ whenever(driveManager.listBackups()).thenReturn(+ Result.Success(listOf(DriveBackupSnapshot("bundle-id", "backup.json")))+ )+ whenever(driveManager.pullBackup(eq("bundle-id"))).thenReturn(+ Result.Success(+ DriveBackupArtifact(+ localUriString = "file:///cache/bundle-backup.json",+ sizeBytes = 256L,+ credentials = credentials,+ )+ )+ )+ whenever(importBackup.inspect(any())).thenReturn(+ InspectBackupResult.Success(+ uriString = "file:///cache/bundle-backup.json",+ preview = emptyPreview(),+ )+ )+ val uiState = MutableStateFlow(+ SettingsUiState(driveAuthState = DriveAuthState.SignedIn(DriveAccount(null, null)))+ )+ val actions = SettingsDriveBackupActions(+ driveManager = driveManager,+ importBackup = importBackup,+ providerRepository = providerRepository,+ uiState = uiState,+ )++ actions.pullBackup(this)+ advanceUntilIdle()++ verify(driveManager).listBackups()+ verify(driveManager).pullBackup(eq("bundle-id"))+ verify(driveManager, never()).pullCredentials()+ assertThat(uiState.value.pendingDriveCredentials).isEqualTo(credentials)+ assertThat(uiState.value.pendingBackupUri).isEqualTo("file:///cache/bundle-backup.json")+ }++ @Test+ fun busyDriveOperation_isIgnored() = runTest(StandardTestDispatcher()) {+ val uiState = MutableStateFlow(+ SettingsUiState(+ driveAuthState = DriveAuthState.SignedIn(DriveAccount(null, null)),+ driveIsBusy = true,+ )+ )+ val actions = SettingsDriveBackupActions(+ driveManager = driveManager,+ importBackup = importBackup,+ providerRepository = providerRepository,+ uiState = uiState,+ )++ actions.pushBackup(this)+ actions.pullBackup(this)+ advanceUntilIdle()++ verify(driveManager, never()).pushBackup(any())+ verify(driveManager, never()).listBackups()+ verify(driveManager, never()).pullBackup(any())+ assertThat(uiState.value.driveIsBusy).isTrue()+ }++ @Test+ fun pullBackup_withMultipleSnapshots_waitsForUserSelection() =+ runTest(StandardTestDispatcher()) {+ val snapshots = listOf(+ DriveBackupSnapshot("new", "streamvault_backup_bundle_new.json"),+ DriveBackupSnapshot("old", "streamvault_backup_bundle_old.json"),+ )+ whenever(driveManager.listBackups()).thenReturn(Result.Success(snapshots))+ val uiState = MutableStateFlow(+ SettingsUiState(driveAuthState = DriveAuthState.SignedIn(DriveAccount(null, null)))+ )+ val actions = SettingsDriveBackupActions(+ driveManager = driveManager,+ importBackup = importBackup,+ providerRepository = providerRepository,+ uiState = uiState,+ )++ actions.pullBackup(this)+ advanceUntilIdle()++ assertThat(uiState.value.driveBackupOptions).isEqualTo(snapshots)+ assertThat(uiState.value.driveIsBusy).isFalse()+ verify(driveManager, never()).pullBackup(any())+ }++ @Test+ fun manageBackups_listsSnapshotsAndRefreshesAfterDelete() =+ runTest(StandardTestDispatcher()) {+ val snapshot = DriveBackupSnapshot("snapshot-id", "streamvault_backup_bundle_test.json")+ whenever(driveManager.listBackups()).thenReturn(+ Result.Success(listOf(snapshot)),+ Result.Success(emptyList()),+ )+ whenever(driveManager.deleteBackup(eq(snapshot.id))).thenReturn(Result.Success(Unit))+ val uiState = MutableStateFlow(+ SettingsUiState(driveAuthState = DriveAuthState.SignedIn(DriveAccount(null, null)))+ )+ val actions = SettingsDriveBackupActions(+ driveManager = driveManager,+ importBackup = importBackup,+ providerRepository = providerRepository,+ uiState = uiState,+ )++ actions.manageBackups(this)+ advanceUntilIdle()+ assertThat(uiState.value.driveBackupManagementOptions).containsExactly(snapshot)++ actions.deleteBackup(this, snapshot.id)+ advanceUntilIdle()++ verify(driveManager).deleteBackup(eq(snapshot.id))+ assertThat(uiState.value.driveBackupManagementOptions).isEmpty()+ assertThat(uiState.value.userMessage).isEqualTo("Drive backup deleted")+ }++ private fun emptyPreview() = BackupPreview(+ version = 12,+ providerCount = 0,+ favoriteCount = 0,+ groupCount = 0,+ playbackHistoryCount = 0,+ multiViewPresetCount = 0,+ preferenceCount = 0,+ protectedCategoryCount = 0,+ scheduledRecordingCount = 0,+ providerConflicts = 0,+ favoriteConflicts = 0,+ groupConflicts = 0,+ historyConflicts = 0,+ protectedCategoryConflicts = 0,+ recordingConflicts = 0,+ )+}diff --git a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt b/data/src/main/java/com/streamvault/data/local/dao/Daos.ktindex c06a9007..6bc9a255 100644--- a/data/src/main/java/com/streamvault/data/local/dao/Daos.kt+++ b/data/src/main/java/com/streamvault/data/local/dao/Daos.kt@@ -431,6 +431,9 @@ abstract class ChannelDao {@Query("SELECT * FROM channels WHERE id = :id")abstract suspend fun getById(id: Long): ChannelEntity?+ @Query("SELECT * FROM channels WHERE provider_id = :providerId AND stream_id = :streamId LIMIT 1")+ abstract suspend fun getByStreamId(providerId: Long, streamId: Long): ChannelEntity?+@Query("""SELECT c.id, c.stream_id, c.name, c.logo_url, c.group_title, c.category_id, c.category_name, c.stream_url,@@ -2812,6 +2815,11 @@ interface EpisodeDao {@Query("SELECT * FROM episodes WHERE id = :id")suspend fun getById(id: Long): EpisodeEntity?+ @Query(+ "SELECT * FROM episodes WHERE provider_id = :providerId AND series_id = :seriesId AND episode_id = :episodeId LIMIT 1"+ )+ suspend fun getByProviderSeriesAndEpisodeId(providerId: Long, seriesId: Long, episodeId: Long): EpisodeEntity?+@Query("""SELECT COUNT(*)@@ -3326,6 +3334,9 @@ abstract class FavoriteDao {@Query("DELETE FROM favorites WHERE provider_id = :providerId AND content_id = :contentId AND content_type = :contentType AND (:groupId IS NULL AND group_id IS NULL OR group_id = :groupId)")abstract suspend fun delete(providerId: Long, contentId: Long, contentType: String, groupId: Long?)+ @Query("DELETE FROM favorites WHERE provider_id = :providerId AND content_type = :contentType")+ abstract suspend fun deleteByProviderAndType(providerId: Long, contentType: String)+@Query("DELETE FROM favorites WHERE content_type = 'LIVE' AND content_id NOT IN (SELECT id FROM channels)")abstract suspend fun deleteMissingLiveFavorites(): Int@@ -3408,6 +3419,9 @@ interface VirtualGroupDao {@Query("DELETE FROM virtual_groups WHERE id = :id")suspend fun delete(id: Long)++ @Query("DELETE FROM virtual_groups WHERE provider_id = :providerId AND content_type = :contentType")+ suspend fun deleteByProviderAndType(providerId: Long, contentType: String)}@Daodiff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.ktindex 9e8b5f5f..a346b999 100644--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt@@ -5,6 +5,7 @@ import com.streamvault.domain.model.Provider as StableProviderimport android.content.Contextimport android.net.Uriimport com.google.gson.Gson+import com.google.gson.JsonElementimport com.google.gson.JsonParseExceptionimport com.google.gson.reflect.TypeTokenimport com.google.gson.stream.JsonReader@@ -22,6 +23,7 @@ import com.streamvault.data.local.dao.PlaybackHistoryDaoimport com.streamvault.data.local.dao.ProviderDaoimport com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.RecordingScheduleDao+import com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.ProviderAccountRuntimeEntity@@ -59,6 +61,7 @@ import com.streamvault.domain.manager.PortableProviderPreferencesBackupimport com.streamvault.domain.manager.PortableVirtualGroupReferenceimport com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.manager.ScheduledRecordingBackup+import com.streamvault.domain.manager.ProviderCredentialsimport com.streamvault.domain.model.AppTopLevelDestinationimport com.streamvault.domain.model.AppHomeDashboardShelfimport com.streamvault.domain.model.ContentType@@ -84,6 +87,8 @@ import kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.flow.firstimport kotlinx.coroutines.withContextimport java.io.OutputStream+import java.io.ByteArrayInputStream+import java.io.ByteArrayOutputStreamimport java.io.Fileimport java.io.FileInputStreamimport java.io.FileOutputStream@@ -95,7 +100,9 @@ import java.io.InputStreamReaderimport java.io.OutputStreamWriterimport java.io.Writerimport java.lang.reflect.Type+import java.net.URIimport java.security.MessageDigest+import java.util.Localeimport java.util.zip.CRC32import javax.inject.Injectimport javax.inject.Singleton@@ -121,6 +128,7 @@ class BackupManagerImpl @Inject constructor(private val providerConfigurationCodec: ProviderConfigurationCodec? = null,private val backupRestoreCheckpointDao: BackupRestoreCheckpointDao? = null,private val channelDao: ChannelDao,+ private val seriesDao: SeriesDao,private val epgSourceDao: EpgSourceDao? = null) : BackupManager {@@ -186,8 +194,11 @@ class BackupManagerImpl @Inject constructor(}}- val providers = providerEntities.mapNotNull { entity ->- providerSnapshotRepository?.getSnapshot(entity.id)?.toLegacyProvider()?.copy(+ val sourceProviders = providerEntities.mapNotNull { entity ->+ providerSnapshotRepository?.getSnapshot(entity.id)?.toLegacyProvider()+ }+ val providers = sourceProviders.map { provider ->+ provider.copy(password = "", // Strip credentials from backup exportstalkerLastBootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,stalkerLastPlaybackMode = null,@@ -198,11 +209,12 @@ class BackupManagerImpl @Inject constructor(stalkerTransportConsentAt = 0L)}- if (providers.size != providerEntities.size) {+ if (sourceProviders.size != providerEntities.size) {return@withContext com.streamvault.domain.model.Result.error("Cannot export backup because one or more providers have no typed configuration snapshot")}+ val providerCredentials = sourceProviders.mapNotNull { it.toBackupCredentials() }val providerSnapshots = providers.map { provider ->val configuration = when (val config = provider.toTypedConfiguration()) {is com.streamvault.domain.model.XtreamConfig -> config.copy(password = "")@@ -239,7 +251,9 @@ class BackupManagerImpl @Inject constructor(val seriesFavs = providerIds.flatMap { providerId ->favoriteDao.getAllByType(providerId, "SERIES").first().map { it.toDomain() }}- val allFavorites = liveFavs + movieFavs + seriesFavs+ val allFavorites = (liveFavs + movieFavs + seriesFavs).map { favorite ->+ favorite.withPortableIdentity(channelDao, movieDao, seriesDao)+ }// Gather all custom groupsval liveGroups = providerIds.flatMap { providerId ->@@ -254,6 +268,7 @@ class BackupManagerImpl @Inject constructor(val allGroups = liveGroups + movieGroups + seriesGroupsval playbackHistory = playbackHistoryDao.getAllSync().map { it.toDomain() }+ .map { history -> history.withPortableIdentity(channelDao, movieDao, seriesDao, episodeDao) }val multiViewPresets = mapOf("preset_1" to preferencesRepository.getMultiViewPreset(0).first(),"preset_2" to preferencesRepository.getMultiViewPreset(1).first(),@@ -296,18 +311,31 @@ class BackupManagerImpl @Inject constructor(protectedCategories = protectedCategories,scheduledRecordings = scheduledRecordings,portableProviderPreferences = buildPortableProviderPreferences(providers),+ providerCredentials = providerCredentials.takeIf { it.isNotEmpty() },epgSources = epgSourceDao?.getAllSync()?.map { it.toDomain() })// Compute checksum over the data without checksum fieldval backupWithChecksum = backupData.copy(checksum = buildSha256Checksum(backupData))- // 2. Serialize and write to URI- openBackupOutputStream(uriString)?.use { outputStream ->- OutputStreamWriter(outputStream).use { writer ->- writeBackupDataJson(writer, backupWithChecksum)+ // 2. Serialize and write to URI with the same admission limit used+ // by restore. This prevents the app from producing a backup that+ // its own importer must reject.+ val outputStream = openBackupOutputStream(uriString)+ ?: return@withContext com.streamvault.domain.model.Result.error("Failed to open output stream")+ try {+ BoundedOutputStream(outputStream, MAX_BACKUP_BYTES).use { boundedOutput ->+ OutputStreamWriter(boundedOutput, Charsets.UTF_8).use { writer ->+ writeBackupDataJson(writer, backupWithChecksum)+ }}- } ?: return@withContext com.streamvault.domain.model.Result.error("Failed to open output stream")+ } catch (tooLarge: BackupOutputTooLargeException) {+ deleteFileUriTarget(uriString)+ return@withContext com.streamvault.domain.model.Result.error(+ "Backup exceeds the maximum supported size of $MAX_BACKUP_BYTES bytes",+ tooLarge+ )+ }com.streamvault.domain.model.Result.success(Unit)} catch (e: Exception) {@@ -317,15 +345,16 @@ class BackupManagerImpl @Inject constructor(override suspend fun inspectBackup(uriString: String): Result<BackupPreview> = withContext(Dispatchers.IO) {try {- val rawBackupData = readBackupData(uriString)+ val parsedBackup = readBackupData(uriString)?: return@withContext Result.error("Failed to open input stream")+ val rawBackupData = parsedBackup.dataif (rawBackupData.version > CURRENT_BACKUP_VERSION) {return@withContext Result.error("Unsupported backup version")}if (rawBackupData.isStructurallyEmpty()) {return@withContext Result.error("Backup file does not contain any importable data")}- if (!verifyChecksum(rawBackupData)) {+ if (!verifyChecksum(parsedBackup)) {return@withContext Result.error("Backup file is corrupted (checksum mismatch)")}val backupData = rawBackupData.withLegacyProviderProjection()@@ -356,19 +385,60 @@ class BackupManagerImpl @Inject constructor(.filter { it.status == RecordingStatus.SCHEDULED }val providersByIdentity = existingProviders.associateBy { it.backupIdentity() }- val groupKeys = existingGroups.mapTo(hashSetOf()) { it.name.lowercase() to it.contentType }- val favoriteKeys = existingFavorites.mapTo(hashSetOf()) { Triple(it.contentId, it.contentType, it.groupId) }- val historyKeys = existingHistory.mapTo(hashSetOf()) { Triple(it.contentId, it.contentType, it.providerId) }+ val backupProviderIdMap = backupData.providers.orEmpty().mapNotNull { provider ->+ providersByIdentity[provider.backupIdentity()]?.let { stored ->+ provider.id to stored.id+ }+ }.toMap()+ val groupKeys = existingGroups.mapTo(hashSetOf()) {+ SavedGroupConflictKey(it.providerId, it.name.lowercase(), it.contentType)+ }+ val groupNameById = existingGroups.associate { group ->+ group.id to SavedGroupConflictKey(group.providerId, group.name.lowercase(), group.contentType)+ }+ val favoriteKeys = existingFavorites.map { favorite ->+ val domainFavorite = favorite.toDomain().withPortableIdentity(channelDao, movieDao, seriesDao)+ SavedFavoriteConflictKey(+ providerId = favorite.providerId,+ contentType = favorite.contentType,+ remoteContentId = domainFavorite.remoteContentId ?: "legacy:${favorite.contentId}",+ group = favorite.groupId?.let { groupNameById[it]?.name }+ )+ }.toHashSet()+ val historyKeys = existingHistory.map { history ->+ val domainHistory = history.toDomain().withPortableIdentity(channelDao, movieDao, seriesDao, episodeDao)+ SavedHistoryConflictKey(+ providerId = history.providerId,+ contentType = history.contentType,+ remoteContentId = domainHistory.remoteContentId ?: "legacy:${history.contentId}"+ )+ }.toHashSet()val protectedCategoryKeys = existingProtectedCategories.mapTo(hashSetOf()) { (provider, name, type) ->Triple(provider.id, name, type)}val providerConflicts = backupData.providers.orEmpty().count { it.backupIdentity() in providersByIdentity }- val groupConflicts = backupData.virtualGroups.orEmpty().count { (it.name.lowercase() to it.contentType) in groupKeys }+ val groupConflicts = backupData.virtualGroups.orEmpty().count { group ->+ val targetProviderId = backupProviderIdMap[group.providerId] ?: return@count false+ SavedGroupConflictKey(targetProviderId, group.name.lowercase(), group.contentType) in groupKeys+ }val favoriteConflicts = backupData.favorites.orEmpty().count {- Triple(it.contentId, it.contentType, it.groupId) in favoriteKeys+ val targetProviderId = backupProviderIdMap[it.providerId] ?: return@count false+ SavedFavoriteConflictKey(+ providerId = targetProviderId,+ contentType = it.contentType,+ remoteContentId = it.remoteContentId ?: "legacy:${it.contentId}",+ group = it.groupId?.let { groupId ->+ backupData.virtualGroups.orEmpty().firstOrNull { group -> group.id == groupId }?.name?.lowercase()+ }+ ) in favoriteKeys}val historyConflicts = backupData.playbackHistory.orEmpty().count {- Triple(it.contentId, it.contentType, it.providerId) in historyKeys+ val targetProviderId = backupProviderIdMap[it.providerId] ?: return@count false+ SavedHistoryConflictKey(+ providerId = targetProviderId,+ contentType = it.contentType,+ remoteContentId = it.remoteContentId ?: "legacy:${it.contentId}"+ ) in historyKeys}val protectedCategoryConflicts = backupData.protectedCategories.orEmpty().count { incoming ->val provider = providersByIdentity[incoming.backupIdentity()] ?: return@count false@@ -411,8 +481,9 @@ class BackupManagerImpl @Inject constructor(plan: BackupImportPlan): com.streamvault.domain.model.Result<BackupImportResult> = withContext(Dispatchers.IO) {try {- val rawBackupData = readBackupData(uriString)+ val parsedBackup = readBackupData(uriString)?: return@withContext com.streamvault.domain.model.Result.error("Failed to open input stream")+ val rawBackupData = parsedBackup.dataif (rawBackupData.version > CURRENT_BACKUP_VERSION) {return@withContext com.streamvault.domain.model.Result.error("Unsupported backup version")@@ -420,7 +491,7 @@ class BackupManagerImpl @Inject constructor(if (rawBackupData.isStructurallyEmpty()) {return@withContext com.streamvault.domain.model.Result.error("Backup file does not contain any importable data")}- if (!verifyChecksum(rawBackupData)) {+ if (!verifyChecksum(parsedBackup)) {return@withContext com.streamvault.domain.model.Result.error("Backup file is corrupted (checksum mismatch)")}val backupData = rawBackupData.withLegacyProviderProjection()@@ -428,9 +499,11 @@ class BackupManagerImpl @Inject constructor(val restoreKey = buildRestoreKey(rawBackupData, plan)var checkpoint = loadOrCreateCheckpoint(restoreKey)if (checkpoint.state == RESTORE_STATE_COMPLETE) {- return@withContext com.streamvault.domain.model.Result.success(- checkpoint.toImportResult(plan, backupData)- )+ // A completed restore is a durable crash-recovery boundary, not a one-time+ // consumption marker. The user may intentionally import the same backup again+ // after deleting a provider or other restored data. Reopen the checkpoint so the+ // normal conflict strategy can safely skip or replace the current destination.+ checkpoint = checkpoint.reopenForExplicitReplay()}var storedProviders = loadStoredProviders()@@ -469,6 +542,10 @@ class BackupManagerImpl @Inject constructor(storedProviders = roomRestoreResult.storedProvidersimportedSections += roomRestoreResult.importedSectionsskippedSections += roomRestoreResult.skippedSections+ unresolvedReferences += roomRestoreResult.unresolvedReferences+ if (roomRestoreResult.unresolvedReferences.isNotEmpty()) {+ failedSections += "Saved library/history: ${roomRestoreResult.unresolvedReferences.size} unresolved"+ }checkpoint = roomCheckpoint} else {importedSections += importedRoomSections(backupData, plan)@@ -624,6 +701,32 @@ class BackupManagerImpl @Inject constructor(return dao.get(restoreKey) ?: fresh}+ private suspend fun BackupRestoreCheckpointEntity.reopenForExplicitReplay(): BackupRestoreCheckpointEntity {+ val reopened = copy(+ roomComplete = false,+ preferencesComplete = false,+ presetsComplete = false,+ schedulesComplete = false,+ state = RESTORE_STATE_RUNNING,+ preferenceSnapshotJson = null,+ lastError = null,+ updatedAt = System.currentTimeMillis()+ )+ val dao = backupRestoreCheckpointDao ?: return reopened+ dao.update(+ restoreKey = restoreKey,+ roomComplete = false,+ preferencesComplete = false,+ presetsComplete = false,+ schedulesComplete = false,+ state = RESTORE_STATE_RUNNING,+ lastError = null,+ updatedAt = reopened.updatedAt+ )+ dao.setPreferenceSnapshot(restoreKey, null, reopened.updatedAt)+ return reopened+ }+private suspend fun BackupRestoreCheckpointEntity.persist(clearPreferenceSnapshot: Boolean = false): BackupRestoreCheckpointEntity {@@ -701,44 +804,22 @@ class BackupManagerImpl @Inject constructor(if (!plan.importPlaybackHistory || backupData.playbackHistory == null) add("Playback History")}- private fun BackupRestoreCheckpointEntity.toImportResult(- plan: BackupImportPlan,- backupData: BackupData- ): BackupImportResult {- val imported = buildList {- if (roomComplete) addAll(importedRoomSections(backupData, plan))- if (preferencesComplete) add("Preferences")- if (presetsComplete) add("Split Screen Presets")- if (schedulesComplete) add("Recording Schedules")- }- val skipped = buildList {- if (!roomComplete) addAll(skippedRoomSections(backupData, plan))- if (!plan.importPreferences ||- (backupData.preferences == null && backupData.portableProviderPreferences == null)- ) {- add("Preferences")- }- if (!plan.importMultiViewPresets || backupData.multiViewPresets == null) add("Split Screen Presets")- if (!plan.importRecordingSchedules || backupData.scheduledRecordings == null) add("Recording Schedules")- }- return BackupImportResult(- outcome = when (state) {- RESTORE_STATE_COMPLETE -> BackupRestoreOutcome.COMPLETE- RESTORE_STATE_FAILED_BEFORE_COMMIT -> BackupRestoreOutcome.FAILED_BEFORE_COMMIT- else -> BackupRestoreOutcome.PARTIAL- },- importedSections = imported.distinct(),- skippedSections = skipped.distinct(),- failedSections = lastError?.let(::listOf).orEmpty()- )- }+ private data class ParsedBackup(+ val data: BackupData,+ val rawJson: ByteArray,+ )- private fun verifyChecksum(backupData: BackupData): Boolean {+ private fun verifyChecksum(parsedBackup: ParsedBackup): Boolean {+ val backupData = parsedBackup.dataval storedChecksum = backupData.checksum ?: return true // no checksum = legacy backup, skip verificationval dataWithoutChecksum = backupData.copy(checksum = null)return if (storedChecksum.startsWith(SHA256_PREFIX)) {- buildSha256Checksum(dataWithoutChecksum) == storedChecksum+ // Prefer the exact exported bytes. Release builds previously let R8 rename+ // reflected DTO fields, so parsing and serializing the object again could+ // change its wire representation even though the file itself was intact.+ buildRawSha256Checksum(parsedBackup.rawJson) == storedChecksum ||+ buildSha256Checksum(dataWithoutChecksum) == storedChecksum} else {verifyLegacyCrc32Checksum(dataWithoutChecksum, storedChecksum)}@@ -752,6 +833,19 @@ class BackupManagerImpl @Inject constructor(return SHA256_PREFIX + digest.digest().joinToString(separator = "") { "%02x".format(it) }}+ private fun buildRawSha256Checksum(rawJson: ByteArray): String? {+ val json = rawJson.toString(Charsets.UTF_8)+ val match = RAW_CHECKSUM_FIELD_PATTERN.find(json) ?: return null+ var prefix = json.substring(0, match.range.first)+ val suffix = json.substring(match.range.last + 1)+ if (!match.value.endsWith(",") && prefix.endsWith(',')) {+ prefix = prefix.dropLast(1)+ }+ val payload = (prefix + suffix).toByteArray(Charsets.UTF_8)+ val digest = MessageDigest.getInstance("SHA-256").digest(payload)+ return SHA256_PREFIX + digest.joinToString(separator = "") { "%02x".format(it) }+ }+private fun verifyLegacyCrc32Checksum(backupData: BackupData, checksum: String): Boolean {val crc = CRC32()OutputStreamWriter(Crc32OutputStream(crc), Charsets.UTF_8).use { writer ->@@ -770,6 +864,7 @@ class BackupManagerImpl @Inject constructor(writeNamedJsonField(jsonWriter, "preferences", backupData.preferences, MAP_STRING_STRING_TYPE)writeNamedJsonField(jsonWriter, "providers", backupData.providers, PROVIDER_LIST_TYPE)writeNamedJsonField(jsonWriter, "providerSnapshots", backupData.providerSnapshots, PROVIDER_SNAPSHOT_LIST_TYPE)+ writeNamedJsonField(jsonWriter, "providerCredentials", backupData.providerCredentials, PROVIDER_CREDENTIALS_LIST_TYPE)writeNamedJsonField(jsonWriter, "favorites", backupData.favorites, FAVORITE_LIST_TYPE)writeNamedJsonField(jsonWriter, "virtualGroups", backupData.virtualGroups, VIRTUAL_GROUP_LIST_TYPE)writeNamedJsonField(jsonWriter, "playbackHistory", backupData.playbackHistory, PLAYBACK_HISTORY_LIST_TYPE)@@ -817,38 +912,55 @@ class BackupManagerImpl @Inject constructor(}}- private fun readBackupData(uriString: String): BackupData? {- return openBackupInputStream(uriString)?.use { inputStream ->- BoundedInputStream(inputStream, MAX_BACKUP_BYTES).use { boundedInput ->- AdmissionCheckingReader(- InputStreamReader(boundedInput, Charsets.UTF_8),- MAX_JSON_DEPTH,- MAX_FIELD_CHARS- ).use { admissionReader ->- try {- JsonReader(admissionReader).use { jsonReader ->- readBackupData(jsonReader).also(::validateBackupDataLimits)- }- } catch (cancelled: CancellationException) {- throw cancelled- } catch (admission: BackupAdmissionException) {- throw admission- } catch (error: Exception) {- if (error is MalformedJsonException ||- error is EOFException ||- error is JsonParseException ||- error is IllegalStateException- ) {- throw BackupAdmissionException(- BackupAdmissionReason.MALFORMED,- "Backup JSON is malformed or truncated"- ).also { it.initCause(error) }- }- throw error- }+ private fun readBackupData(uriString: String): ParsedBackup? {+ val rawJson = openBackupInputStream(uriString)?.use(::readBoundedBytes) ?: return null+ val data = try {+ AdmissionCheckingReader(+ InputStreamReader(ByteArrayInputStream(rawJson), Charsets.UTF_8),+ MAX_JSON_DEPTH,+ MAX_FIELD_CHARS+ ).use { admissionReader ->+ JsonReader(admissionReader).use { jsonReader ->+ readBackupData(jsonReader).also(::validateBackupDataLimits)}}+ } catch (cancelled: CancellationException) {+ throw cancelled+ } catch (admission: BackupAdmissionException) {+ throw admission+ } catch (error: Exception) {+ if (error is MalformedJsonException ||+ error is EOFException ||+ error is JsonParseException ||+ error is IllegalStateException+ ) {+ throw BackupAdmissionException(+ BackupAdmissionReason.MALFORMED,+ "Backup JSON is malformed or truncated"+ ).also { it.initCause(error) }+ }+ throw error+ }+ return ParsedBackup(data = data, rawJson = rawJson)+ }++ private fun readBoundedBytes(input: java.io.InputStream): ByteArray {+ val output = ByteArrayOutputStream()+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ var total = 0L+ while (true) {+ val read = input.read(buffer)+ if (read < 0) break+ total += read+ if (total > MAX_BACKUP_BYTES) {+ throw BackupAdmissionException(+ BackupAdmissionReason.BYTE_LIMIT,+ "Backup exceeds the ${MAX_BACKUP_BYTES / (1024 * 1024)} MiB import limit"+ )+ }+ output.write(buffer, 0, read)}+ return output.toByteArray()}private fun readBackupData(reader: JsonReader): BackupData {@@ -857,6 +969,7 @@ class BackupManagerImpl @Inject constructor(var preferences: Map<String, String>? = nullvar providers: List<com.streamvault.domain.model.LegacyProvider>? = nullvar providerSnapshots: List<ProviderBackupSnapshot>? = null+ var providerCredentials: List<ProviderCredentials>? = nullvar favorites: List<com.streamvault.domain.model.Favorite>? = nullvar virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = nullvar playbackHistory: List<com.streamvault.domain.model.PlaybackHistory>? = null@@ -899,6 +1012,8 @@ class BackupManagerImpl @Inject constructor("providers" -> providers = readLimitedArray(reader, PROVIDER_TYPE, MAX_PROVIDERS, "providers")"providerSnapshots" -> providerSnapshots =readLimitedArray(reader, PROVIDER_SNAPSHOT_TYPE, MAX_PROVIDERS, "provider snapshots")+ "providerCredentials" -> providerCredentials =+ readLimitedArray(reader, PROVIDER_CREDENTIALS_TYPE, MAX_PROVIDERS, "provider credentials")"favorites" -> favorites = readLimitedArray(reader, FAVORITE_TYPE, MAX_SECTION_ITEMS, "favorites")"virtualGroups" -> virtualGroups =readLimitedArray(reader, VIRTUAL_GROUP_TYPE, MAX_SECTION_ITEMS, "groups")@@ -936,6 +1051,7 @@ class BackupManagerImpl @Inject constructor(preferences = preferences,providers = providers,providerSnapshots = providerSnapshots,+ providerCredentials = providerCredentials,favorites = favorites,virtualGroups = virtualGroups,playbackHistory = playbackHistory,@@ -966,7 +1082,7 @@ class BackupManagerImpl @Inject constructor("Backup has too many $label")}- val item = gson.fromJson<T>(reader, type)+ val item = readLegacyAwareValue<T>(reader, type)?: throw BackupAdmissionException(BackupAdmissionReason.MALFORMED,"Backup contains a null $label entry"@@ -977,6 +1093,63 @@ class BackupManagerImpl @Inject constructor(return result}+ private fun <T> readLegacyAwareValue(reader: JsonReader, type: Type): T? {+ val element = gson.fromJson<JsonElement>(reader, JsonElement::class.java)+ ?: return null+ if (element.isJsonNull) return null+ return gson.fromJson(normalizeLegacyBackupElement(element, type), type)+ }++ /**+ * Release builds before the backup wire schema was pinned let R8 rename fields in+ * domain.manager DTOs to a, b, c, ... . Accept those files while writing the stable+ * source field names in new builds.+ */+ private fun normalizeLegacyBackupElement(element: JsonElement, type: Type): JsonElement {+ if (!element.isJsonObject) return element+ val fieldNames = when (type) {+ PROVIDER_SNAPSHOT_TYPE -> listOf(+ "provider", "accountRuntime", "xtreamConfig", "m3uConfig", "stalkerConfig", "jellyfinConfig"+ )+ BACKUP_PROVIDER_REFERENCE_TYPE -> listOf("serverUrl", "username", "stalkerMacAddress")+ PORTABLE_CATEGORY_REFERENCE_TYPE -> listOf("provider", "name", "type", "remoteCategoryId")+ PORTABLE_GROUP_REFERENCE_TYPE -> listOf("provider", "name", "contentType")+ PORTABLE_CHANNEL_REFERENCE_TYPE -> listOf("provider", "streamId", "name", "streamUrl")+ PROTECTED_CATEGORY_TYPE -> listOf(+ "providerServerUrl", "providerUsername", "providerStalkerMacAddress",+ "categoryId", "categoryName", "type"+ )+ SCHEDULED_RECORDING_TYPE -> listOf(+ "providerServerUrl", "providerUsername", "providerStalkerMacAddress", "channelId",+ "channelName", "streamUrl", "scheduledStartMs", "scheduledEndMs", "requestedStartMs",+ "requestedEndMs", "paddingBeforeMs", "paddingAfterMs", "programTitle", "recurrence",+ "recurringRuleId"+ )+ else -> return element+ }+ val objectValue = element.asJsonObject+ fieldNames.forEachIndexed { index, fieldName ->+ val legacyName = ('a'.code + index).toChar().toString()+ if (!objectValue.has(fieldName) && objectValue.has(legacyName)) {+ objectValue.add(fieldName, objectValue.remove(legacyName))+ }+ }+ when (type) {+ PORTABLE_CATEGORY_REFERENCE_TYPE,+ PORTABLE_GROUP_REFERENCE_TYPE,+ PORTABLE_CHANNEL_REFERENCE_TYPE -> {+ objectValue.get("provider")?.let { provider ->+ objectValue.add(+ "provider",+ normalizeLegacyBackupElement(provider, BACKUP_PROVIDER_REFERENCE_TYPE)+ )+ }+ }+ else -> Unit+ }+ return objectValue+ }+private fun readStringMap(reader: JsonReader,maxItems: Int,@@ -1069,43 +1242,43 @@ class BackupManagerImpl @Inject constructor()}when (field) {- "providers" -> providers =+ "providers", "a" -> providers =readLimitedArray<BackupProviderReference>(reader,BACKUP_PROVIDER_REFERENCE_TYPE,MAX_PROVIDERS,"portable providers").orEmpty()- "activeProvider" -> activeProvider =- gson.fromJson(reader, BACKUP_PROVIDER_REFERENCE_TYPE)- "guideDefaultCategory" -> guideDefaultCategory =- gson.fromJson(reader, PORTABLE_CATEGORY_REFERENCE_TYPE)- "guideDefaultVirtualCategoryId" -> guideDefaultVirtualCategoryId =+ "activeProvider", "b" -> activeProvider =+ readLegacyAwareValue(reader, BACKUP_PROVIDER_REFERENCE_TYPE)+ "guideDefaultCategory", "c" -> guideDefaultCategory =+ readLegacyAwareValue(reader, PORTABLE_CATEGORY_REFERENCE_TYPE)+ "guideDefaultVirtualCategoryId", "d" -> guideDefaultVirtualCategoryId =reader.nextNullableLong()- "guideDefaultCategorySpecified" -> guideDefaultCategorySpecified =+ "guideDefaultCategorySpecified", "e" -> guideDefaultCategorySpecified =reader.nextBoolean()- "promotedLiveGroups" -> promotedLiveGroups =+ "promotedLiveGroups", "f" -> promotedLiveGroups =readLimitedArray<PortableVirtualGroupReference>(reader,PORTABLE_GROUP_REFERENCE_TYPE,MAX_SECTION_ITEMS,"promoted groups").orEmpty()- "hiddenChannels" -> hiddenChannels =+ "hiddenChannels", "g" -> hiddenChannels =readLimitedArray<PortableChannelReference>(reader,PORTABLE_CHANNEL_REFERENCE_TYPE,MAX_SECTION_ITEMS,"hidden channels").orEmpty()- "hiddenCategories" -> hiddenCategories =+ "hiddenCategories", "h" -> hiddenCategories =readLimitedArray<PortableCategoryReference>(reader,PORTABLE_CATEGORY_REFERENCE_TYPE,MAX_SECTION_ITEMS,"hidden categories").orEmpty()- "unresolvedReferences" -> unresolvedReferences =+ "unresolvedReferences", "i" -> unresolvedReferences =readLimitedArray<String>(reader,STRING_TYPE,@@ -1141,6 +1314,7 @@ class BackupManagerImpl @Inject constructor(require(data.preferences.orEmpty().size <= MAX_PREFERENCES) { "Backup has too many preferences" }require(data.providers.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many providers" }require(data.providerSnapshots.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many provider snapshots" }+ require(data.providerCredentials.orEmpty().size <= MAX_PROVIDERS) { "Backup has too many provider credentials" }data.providerSnapshots.orEmpty().forEach { it.configuration() }require(data.favorites.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many favorites" }require(data.virtualGroups.orEmpty().size <= MAX_SECTION_ITEMS) { "Backup has too many groups" }@@ -1205,7 +1379,10 @@ class BackupManagerImpl @Inject constructor(categoryRepository.getCategories(provider.id).first().filter { it.type == type }}}- val activeProviderId = preferencesRepository.lastActiveProviderId.first()+ // Older app versions persisted -1 when there was no active provider. It is a+ // sentinel, not a provider reference, and must not make an otherwise valid+ // backup partial on restore.+ val activeProviderId = preferencesRepository.lastActiveProviderId.first()?.takeIf { it > 0L }val activeProvider = activeProviderId?.let(referencesById::get).also { reference ->if (activeProviderId != null && reference == null) {unresolved += "Active provider id $activeProviderId was not found during export"@@ -1303,24 +1480,46 @@ class BackupManagerImpl @Inject constructor(* restore code that still expects the compatibility envelope.*/private fun BackupData.withLegacyProviderProjection(): BackupData {- val snapshots = providerSnapshots ?: return this+ val snapshots = providerSnapshots// Treat an explicitly empty legacy projection like an omitted one. This keeps v11's// typed section authoritative while still honoring non-empty v0-10 provider payloads.- if (!providers.isNullOrEmpty()) return this- return copy(- providers = snapshots.map { snapshot ->+ val projectedProviders = if (!providers.isNullOrEmpty()) {+ providers.orEmpty()+ } else if (snapshots != null) {+ snapshots.map { snapshot ->snapshot.configuration().toLegacyProvider(snapshot.provider,snapshot.accountRuntime ?: ProviderAccountRuntime())}- )+ } else {+ return this+ }+ val hydratedProviders = projectedProviders.map { provider ->+ val credentials = providerCredentials.orEmpty().firstOrNull { credential ->+ normalizeProviderServerUrl(credential.serverUrl) == normalizeProviderServerUrl(provider.serverUrl) &&+ credential.username.trim() == provider.username.trim()+ }+ if (credentials == null || provider.password.isNotBlank()) {+ provider+ } else {+ provider.copy(password = credentials.password)+ }+ }+ return copy(providers = hydratedProviders)+ }++ private fun deleteFileUriTarget(uriString: String) {+ if (uriString.isFileUriString()) {+ uriString.toFileUriTarget()?.delete()+ }}private fun BackupData.isStructurallyEmpty(): Boolean =preferences.isNullOrEmpty() &&providers.isNullOrEmpty() &&providerSnapshots.isNullOrEmpty() &&+ providerCredentials.isNullOrEmpty() &&favorites.isNullOrEmpty() &&virtualGroups.isNullOrEmpty() &&playbackHistory.isNullOrEmpty() &&@@ -1412,7 +1611,11 @@ class BackupManagerImpl @Inject constructor(portable: PortableProviderPreferencesBackup,storedProviders: List<Provider>): List<String> {- val unresolved = portable.unresolvedReferences.toMutableList()+ // Backups written by older releases may contain this known false-positive warning.+ // It describes a missing active-provider sentinel, not a broken provider reference.+ val unresolved = portable.unresolvedReferences+ .filterNot { it == LEGACY_NO_ACTIVE_PROVIDER_WARNING }+ .toMutableList()val channels = channelDaofun resolveProvider(reference: BackupProviderReference) =storedProviders.findUnambiguousPortableProvider(reference)@@ -1649,13 +1852,15 @@ class BackupManagerImpl @Inject constructor(add("Providers")add("Saved Library")add("Playback History")- }+ },+ unresolvedReferences = emptyList())}var storedProviders = initialStoredProvidersval importedSections = mutableListOf<String>()val skippedSections = mutableListOf<String>()+ val unresolvedReferences = mutableListOf<String>()transactionRunner.inTransaction {if (plan.importProviders) {@@ -1763,7 +1968,7 @@ class BackupManagerImpl @Inject constructor(}if (plan.importSavedLibrary) {- restoreSavedLibrary(+ unresolvedReferences += restoreSavedLibrary(backupData = backupData,storedProviders = storedProviders,conflictStrategy = plan.conflictStrategy@@ -1775,7 +1980,7 @@ class BackupManagerImpl @Inject constructor(if (plan.importPlaybackHistory) {backupData.playbackHistory?.let { history ->- restorePlaybackHistory(+ unresolvedReferences += restorePlaybackHistory(history = history,storedProviders = storedProviders,backupProviders = backupData.providers.orEmpty(),@@ -1792,7 +1997,8 @@ class BackupManagerImpl @Inject constructor(return RoomRestoreResult(storedProviders = storedProviders,importedSections = importedSections,- skippedSections = skippedSections+ skippedSections = skippedSections,+ unresolvedReferences = unresolvedReferences)}@@ -1800,19 +2006,46 @@ class BackupManagerImpl @Inject constructor(backupData: BackupData,storedProviders: List<Provider>,conflictStrategy: BackupConflictStrategy- ) {+ ): List<String> {+ val unresolvedReferences = mutableListOf<String>()val providerIdMap = resolveProviderIdMap(storedProviders, backupData.providers.orEmpty())val groupIdMap = mutableMapOf<Long, Long>()+ if (conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING) {+ val replaceScopes = buildSet<Pair<Long, ContentType>> {+ backupData.virtualGroups.orEmpty().forEach { group ->+ providerIdMap[group.providerId]?.let { providerId ->+ add(providerId to group.contentType)+ }+ }+ backupData.favorites.orEmpty().forEach { favorite ->+ providerIdMap[favorite.providerId]?.let { providerId ->+ add(providerId to favorite.contentType)+ }+ }+ }+ replaceScopes.forEach { (providerId, contentType) ->+ favoriteDao.deleteByProviderAndType(providerId, contentType.name)+ if (backupData.virtualGroups != null) {+ virtualGroupDao.deleteByProviderAndType(providerId, contentType.name)+ }+ }+ }backupData.virtualGroups?.let { groups ->val existingGroups = buildList {- providerIdMap.values.distinct().forEach { providerId ->- addAll(virtualGroupDao.getByType(providerId, "LIVE").first())- addAll(virtualGroupDao.getByType(providerId, "MOVIE").first())- addAll(virtualGroupDao.getByType(providerId, "SERIES").first())+ if (conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {+ providerIdMap.values.distinct().forEach { providerId ->+ addAll(virtualGroupDao.getByType(providerId, "LIVE").first())+ addAll(virtualGroupDao.getByType(providerId, "MOVIE").first())+ addAll(virtualGroupDao.getByType(providerId, "SERIES").first())+ }}}groups.forEach { group ->- val resolvedProviderId = providerIdMap[group.providerId] ?: return@forEach+ val resolvedProviderId = providerIdMap[group.providerId]+ if (resolvedProviderId == null) {+ unresolvedReferences += "Group ${group.name} provider ${group.providerId} could not be matched"+ return@forEach+ }val conflict = existingGroups.firstOrNull {it.providerId == resolvedProviderId &&it.name.equals(group.name, ignoreCase = true) &&@@ -1831,11 +2064,30 @@ class BackupManagerImpl @Inject constructor(backupData.favorites?.let { favorites ->favorites.forEach { favorite ->- val resolvedProviderId = providerIdMap[favorite.providerId] ?: return@forEach- val resolvedGroupId = favorite.groupId?.let { groupIdMap[it] }+ val resolvedProviderId = providerIdMap[favorite.providerId]+ if (resolvedProviderId == null) {+ unresolvedReferences += "Favorite provider ${favorite.providerId} could not be matched"+ return@forEach+ }+ val resolvedGroupId = favorite.groupId?.let { groupId ->+ groupIdMap[groupId] ?: run {+ unresolvedReferences += "Favorite ${favorite.contentType} refers to missing group $groupId"+ return@forEach+ }+ }+ val resolvedContentId = resolvePortableContentId(+ providerId = resolvedProviderId,+ contentType = favorite.contentType,+ remoteContentId = favorite.remoteContentId,+ legacyContentId = favorite.contentId+ )+ if (resolvedContentId == null) {+ unresolvedReferences += "Favorite ${favorite.contentType} ${favorite.remoteContentId} could not be matched"+ return@forEach+ }val existing = favoriteDao.get(providerId = resolvedProviderId,- contentId = favorite.contentId,+ contentId = resolvedContentId,contentType = favorite.contentType.name,groupId = resolvedGroupId)@@ -1846,6 +2098,7 @@ class BackupManagerImpl @Inject constructor(favorite.copy(id = 0L,providerId = resolvedProviderId,+ contentId = resolvedContentId,groupId = resolvedGroupId).toEntity())@@ -1881,8 +2134,29 @@ class BackupManagerImpl @Inject constructor(isProtected = true)}+ return unresolvedReferences+ }++ private suspend fun resolvePortableContentId(+ providerId: Long,+ contentType: ContentType,+ remoteContentId: String?,+ legacyContentId: Long+ ): Long? {+ if (remoteContentId == null) return legacyContentId+ return when (contentType) {+ ContentType.LIVE -> remoteContentId.toLongOrNull()?.let { channelDao.getByStreamId(providerId, it)?.id }+ ContentType.MOVIE -> remoteContentId.toLongOrNull()?.let { movieDao.getByStreamId(providerId, it)?.id }+ ContentType.SERIES -> resolveSeries(providerId, remoteContentId)?.id+ ContentType.SERIES_EPISODE,+ ContentType.VOD -> null+ }}+ private suspend fun resolveSeries(providerId: Long, remoteSeriesId: String): com.streamvault.data.local.entity.SeriesEntity? =+ seriesDao.getByProviderSeriesId(providerId, remoteSeriesId)+ ?: remoteSeriesId.toLongOrNull()?.let { seriesDao.getBySeriesId(providerId, it) }+private fun resolveProviderIdMap(storedProviders: List<Provider>,backupProviders: List<com.streamvault.domain.model.LegacyProvider>@@ -1901,35 +2175,75 @@ class BackupManagerImpl @Inject constructor(storedProviders: List<Provider>,backupProviders: List<com.streamvault.domain.model.LegacyProvider>,conflictStrategy: BackupConflictStrategy- ) {+ ): List<String> {+ val unresolvedReferences = mutableListOf<String>()val providerIdMap = resolveProviderIdMap(storedProviders, backupProviders)if (providerIdMap.isEmpty()) {- return+ return history.map { "History provider ${it.providerId} could not be matched" }+ }++ val resolvedItems = mutableListOf<ResolvedHistoryItem>()+ val blockedProviderIds = mutableSetOf<Long>()+ history.forEach { item ->+ val resolvedProviderId = providerIdMap[item.providerId]+ if (resolvedProviderId == null) {+ unresolvedReferences += "History provider ${item.providerId} could not be matched"+ return@forEach+ }+ val resolvedIdentity = resolvePortableHistoryIdentity(+ providerId = resolvedProviderId,+ item = item+ )+ if (resolvedIdentity == null) {+ unresolvedReferences += "History ${item.contentType} ${item.remoteContentId} could not be matched"+ blockedProviderIds += resolvedProviderId+ return@forEach+ }+ resolvedItems += ResolvedHistoryItem(+ providerId = resolvedProviderId,+ item = item,+ identity = resolvedIdentity+ )}val providersToResync = when (conflictStrategy) {- BackupConflictStrategy.REPLACE_EXISTING -> providerIdMap.values.toMutableSet()+ BackupConflictStrategy.REPLACE_EXISTING -> providerIdMap.values+ .filterNot { it in blockedProviderIds }+ .toMutableSet()BackupConflictStrategy.KEEP_EXISTING -> linkedSetOf()}if (conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING) {- providerIdMap.values.distinct().forEach { providerId ->+ providersToResync.forEach { providerId ->playbackHistoryDao.deleteByProvider(providerId)}}- history.forEach { item ->- val resolvedProviderId = providerIdMap[item.providerId] ?: return@forEach+ resolvedItems.forEach { resolvedItem ->+ if (conflictStrategy == BackupConflictStrategy.REPLACE_EXISTING &&+ resolvedItem.providerId in blockedProviderIds+ ) {+ return@forEach+ }+ val item = resolvedItem.item+ val resolvedProviderId = resolvedItem.providerId+ val resolvedIdentity = resolvedItem.identityif (conflictStrategy == BackupConflictStrategy.KEEP_EXISTING) {val existing = playbackHistoryDao.get(- contentId = item.contentId,+ contentId = resolvedIdentity.contentId,contentType = item.contentType.name,providerId = resolvedProviderId)if (existing != null) return@forEach}- playbackHistoryDao.insertOrUpdate(item.copy(providerId = resolvedProviderId).toEntity())+ playbackHistoryDao.insertOrUpdate(+ item.copy(+ providerId = resolvedProviderId,+ contentId = resolvedIdentity.contentId,+ seriesId = resolvedIdentity.seriesId+ ).toEntity()+ )providersToResync += resolvedProviderId}@@ -1937,12 +2251,61 @@ class BackupManagerImpl @Inject constructor(movieDao.syncWatchProgressFromHistoryByProvider(providerId)episodeDao.syncWatchProgressFromHistoryByProvider(providerId)}+ return unresolvedReferences+ }++ private data class ResolvedHistoryItem(+ val providerId: Long,+ val item: com.streamvault.domain.model.PlaybackHistory,+ val identity: ResolvedContentIdentity+ )++ private suspend fun resolvePortableHistoryIdentity(+ providerId: Long,+ item: com.streamvault.domain.model.PlaybackHistory+ ): ResolvedContentIdentity? {+ if (item.remoteContentId == null && item.remoteSeriesId == null) {+ return ResolvedContentIdentity(contentId = item.contentId, seriesId = item.seriesId)+ }++ return when (item.contentType) {+ ContentType.LIVE -> item.remoteContentId+ ?.toLongOrNull()+ ?.let { channelDao.getByStreamId(providerId, it)?.id }+ ?.let { ResolvedContentIdentity(contentId = it) }+ ContentType.MOVIE -> item.remoteContentId+ ?.toLongOrNull()+ ?.let { movieDao.getByStreamId(providerId, it)?.id }+ ?.let { ResolvedContentIdentity(contentId = it) }+ ContentType.SERIES -> item.remoteContentId+ ?.let { resolveSeries(providerId, it)?.id }+ ?.let { ResolvedContentIdentity(contentId = it) }+ ContentType.SERIES_EPISODE -> {+ val remoteSeriesId = item.remoteSeriesId ?: return null+ val localSeries = resolveSeries(providerId, remoteSeriesId) ?: return null+ val remoteEpisodeId = item.remoteContentId?.toLongOrNull() ?: return null+ episodeDao.getByProviderSeriesAndEpisodeId(+ providerId = providerId,+ seriesId = localSeries.id,+ episodeId = remoteEpisodeId+ )?.let { episode ->+ ResolvedContentIdentity(contentId = episode.id, seriesId = localSeries.id)+ }+ }+ ContentType.VOD -> null+ }}+ private data class ResolvedContentIdentity(+ val contentId: Long,+ val seriesId: Long? = null+ )+private data class RoomRestoreResult(val storedProviders: List<Provider>,val importedSections: List<String>,- val skippedSections: List<String>+ val skippedSections: List<String>,+ val unresolvedReferences: List<String>)private suspend fun loadStoredProviders(): List<Provider> = providerDao.getAllSync().mapNotNull { entity ->@@ -2034,6 +2397,38 @@ internal fun countScheduledRecordingConflicts(}}+ private class BoundedOutputStream(+ private val delegate: OutputStream,+ private val maxBytes: Long,+ ) : OutputStream() {+ private var bytesWritten = 0L++ override fun write(value: Int) {+ consume(1L)+ delegate.write(value)+ }++ override fun write(buffer: ByteArray, offset: Int, length: Int) {+ consume(length.toLong())+ delegate.write(buffer, offset, length)+ }++ override fun flush() = delegate.flush()++ override fun close() = delegate.close()++ private fun consume(count: Long) {+ if (count < 0L || bytesWritten > maxBytes - count) {+ throw BackupOutputTooLargeException(+ "Backup exceeds the ${maxBytes / (1024 * 1024)} MiB export limit"+ )+ }+ bytesWritten += count+ }+ }++ private class BackupOutputTooLargeException(message: String) : IOException(message)+/*** Rejects hostile JSON structure while characters are still being consumed by Gson.* This keeps deeply nested or overlong values from becoming a large object graph first.@@ -2135,11 +2530,11 @@ internal class BackupAdmissionException() : IOException(message)private fun Provider.backupIdentity(): Triple<String, String, String> =- Triple(serverUrl, username, stalkerMacAddress)+ Triple(normalizeProviderServerUrl(serverUrl), username.trim(), stalkerMacAddress.normalizedIdentity())private fun Provider.toBackupProviderReference() = BackupProviderReference(- serverUrl = serverUrl,- username = username,+ serverUrl = normalizeProviderServerUrl(serverUrl),+ username = username.trim(),stalkerMacAddress = stalkerMacAddress.takeIf { it.isNotBlank() })@@ -2148,12 +2543,40 @@ private fun Iterable<Provider>.findUnambiguousPortableProvider(): Provider? {val normalizedMac = reference.stalkerMacAddress.normalizedIdentity()return filter { provider ->- provider.serverUrl == reference.serverUrl &&- (provider.type == ProviderType.M3U || provider.username == reference.username) &&+ normalizeProviderServerUrl(provider.serverUrl) == normalizeProviderServerUrl(reference.serverUrl) &&+ (provider.type == ProviderType.M3U || provider.username.trim() == reference.username.trim()) &&provider.stalkerMacAddress.normalizedIdentity() == normalizedMac}.singleOrNull()}+/**+ * Provider URLs are identities, not display strings. The setup flow normally stores a+ * canonical value, but backups can cross releases/devices where harmless differences such as+ * a trailing slash, URL scheme/host case, or an explicit default port are present.+ */+private fun normalizeProviderServerUrl(value: String): String {+ val trimmed = value.trim()+ return runCatching {+ val uri = URI(trimmed)+ val scheme = uri.scheme?.lowercase(Locale.ROOT)+ val host = uri.host?.lowercase(Locale.ROOT)+ if (scheme.isNullOrBlank() || host.isNullOrBlank()) {+ return@runCatching trimmed.trimEnd('/').lowercase(Locale.ROOT)+ }+ val port = when {+ uri.port < 0 -> ""+ scheme == "http" && uri.port == 80 -> ""+ scheme == "https" && uri.port == 443 -> ""+ else -> ":${uri.port}"+ }+ val path = uri.rawPath.orEmpty().trimEnd('/')+ val query = uri.rawQuery?.let { "?$it" }.orEmpty()+ "$scheme://$host$port$path$query"+ }.getOrElse {+ trimmed.trimEnd('/').lowercase(Locale.ROOT)+ }+}+private fun List<com.streamvault.domain.model.Category>.resolvePortableCategory(reference: PortableCategoryReference): com.streamvault.domain.model.Category? {@@ -2199,10 +2622,18 @@ private fun PortableChannelReference.unresolvedLabel(kind: String): String =private fun String?.normalizedIdentity(): String = orEmpty().trim().lowercase()private fun ProtectedCategoryBackup.backupIdentity(): Triple<String, String, String> =- Triple(providerServerUrl, providerUsername, providerStalkerMacAddress.orEmpty())+ Triple(+ normalizeProviderServerUrl(providerServerUrl),+ providerUsername.trim(),+ providerStalkerMacAddress.normalizedIdentity()+ )private fun ScheduledRecordingBackup.backupIdentity(): Triple<String, String, String> =- Triple(providerServerUrl, providerUsername, providerStalkerMacAddress.orEmpty())+ Triple(+ normalizeProviderServerUrl(providerServerUrl),+ providerUsername.trim(),+ providerStalkerMacAddress.normalizedIdentity()+ )internal fun com.streamvault.domain.model.RecordingItem.toScheduledRecordingBackup(provider: com.streamvault.domain.model.LegacyProvider,@@ -2379,18 +2810,131 @@ private fun ScheduledRecordingBackup.toImportOutcome(private fun ScheduledRecordingBackup.hasStableRecurringIdentity(): Boolean =recurrence != RecordingRecurrence.NONE && !recurringRuleId.isNullOrBlank()+private suspend fun com.streamvault.domain.model.Favorite.withPortableIdentity(+ channelDao: ChannelDao,+ movieDao: MovieDao,+ seriesDao: SeriesDao+): com.streamvault.domain.model.Favorite =+ copy(+ remoteContentId = remoteContentId ?: resolvePortableContentId(+ channelDao = channelDao,+ movieDao = movieDao,+ seriesDao = seriesDao,+ providerId = providerId,+ contentType = contentType,+ localContentId = contentId+ )+ )++private suspend fun com.streamvault.domain.model.PlaybackHistory.withPortableIdentity(+ channelDao: ChannelDao,+ movieDao: MovieDao,+ seriesDao: SeriesDao,+ episodeDao: EpisodeDao+): com.streamvault.domain.model.PlaybackHistory {+ val episode = if (contentType == ContentType.SERIES_EPISODE) {+ episodeDao.getById(contentId)?.takeIf { it.providerId == providerId }+ } else {+ null+ }+ val series = when {+ episode != null -> seriesDao.getById(episode.seriesId)?.takeIf { it.providerId == providerId }+ else -> seriesId?.let { id -> seriesDao.getById(id)?.takeIf { it.providerId == providerId } }+ }+ return copy(+ remoteContentId = remoteContentId ?: when (contentType) {+ ContentType.LIVE -> channelDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.streamId+ ?.takeIf { it > 0L }+ ?.toString()+ ContentType.MOVIE -> movieDao.getById(contentId)+ ?.takeIf { it.providerId == providerId }+ ?.streamId+ ?.takeIf { it > 0L }+ ?.toString()+ ContentType.SERIES -> series?.remoteKey()+ ContentType.SERIES_EPISODE -> episode?.episodeId+ ?.takeIf { it > 0L }+ ?.toString()+ ContentType.VOD -> null+ },+ remoteSeriesId = remoteSeriesId ?: if (contentType == ContentType.SERIES_EPISODE) {+ series?.remoteKey()+ } else {+ null+ }+ )+}++private suspend fun resolvePortableContentId(+ channelDao: ChannelDao,+ movieDao: MovieDao,+ seriesDao: SeriesDao,+ providerId: Long,+ contentType: ContentType,+ localContentId: Long+): String? = when (contentType) {+ ContentType.LIVE -> channelDao.getById(localContentId)+ ?.takeIf { it.providerId == providerId }+ ?.streamId+ ?.takeIf { it > 0L }+ ?.toString()+ ContentType.MOVIE -> movieDao.getById(localContentId)+ ?.takeIf { it.providerId == providerId }+ ?.streamId+ ?.takeIf { it > 0L }+ ?.toString()+ ContentType.SERIES -> seriesDao.getById(localContentId)+ ?.takeIf { it.providerId == providerId }+ ?.remoteKey()+ ContentType.SERIES_EPISODE,+ ContentType.VOD -> null+}++private fun com.streamvault.data.local.entity.SeriesEntity.remoteKey(): String? =+ providerSeriesId?.takeIf { it.isNotBlank() } ?: seriesId.takeIf { it > 0L }?.toString()++private data class SavedGroupConflictKey(+ val providerId: Long,+ val name: String,+ val contentType: ContentType+)++private data class SavedFavoriteConflictKey(+ val providerId: Long,+ val contentType: ContentType,+ val remoteContentId: String,+ val group: String?+)++private data class SavedHistoryConflictKey(+ val providerId: Long,+ val contentType: ContentType,+ val remoteContentId: String+)+private fun com.streamvault.domain.model.LegacyProvider.toSecureEntityForBackup(credentialCrypto: CredentialCrypto) = copy(password = credentialCrypto.encryptIfNeeded(password)).toEntity()+private fun Provider.toBackupCredentials(): ProviderCredentials? {+ if (username.isBlank() || password.isBlank()) return null+ return ProviderCredentials(+ serverUrl = serverUrl,+ username = username,+ password = password,+ )+}+private fun Iterable<Provider>.findMatchingProvider(serverUrl: String,username: String,stalkerMacAddress: String?): Provider? {val candidates = filter {- it.serverUrl == serverUrl &&- (it.type == ProviderType.M3U || it.username == username)+ normalizeProviderServerUrl(it.serverUrl) == normalizeProviderServerUrl(serverUrl) &&+ (it.type == ProviderType.M3U || it.username.trim() == username.trim())}val normalizedMacAddress = stalkerMacAddress?.trim()@@ -2406,6 +2950,7 @@ private fun Iterable<Provider>.findMatchingProvider(}private const val SHA256_PREFIX = "sha256:"+private val RAW_CHECKSUM_FIELD_PATTERN = Regex("\\\"checksum\\\"\\s*:\\s*\\\"[^\\\"]*\\\"\\s*,?")private fun com.streamvault.domain.model.ProviderConfiguration.toBackupSnapshot(provider: StableProvider,@@ -2425,11 +2970,14 @@ private const val RESTORE_SNAPSHOT_PRESET_1 = "__restore_snapshot_preset_1"private const val RESTORE_SNAPSHOT_PRESET_2 = "__restore_snapshot_preset_2"private const val RESTORE_SNAPSHOT_PRESET_3 = "__restore_snapshot_preset_3"private const val CURRENT_BACKUP_VERSION = 11+private const val LEGACY_NO_ACTIVE_PROVIDER_WARNING =+ "Active provider id -1 was not found during export"private const val FILE_URI_SCHEME = "file"private val PORTABLE_VIRTUAL_CATEGORY_IDS = setOf(-998L, -999L)private val MAP_STRING_STRING_TYPE: Type = object : TypeToken<Map<String, String>>() {}.typeprivate val PROVIDER_TYPE: Type = com.streamvault.domain.model.LegacyProvider::class.javaprivate val PROVIDER_SNAPSHOT_TYPE: Type = ProviderBackupSnapshot::class.java+private val PROVIDER_CREDENTIALS_TYPE: Type = ProviderCredentials::class.javaprivate val FAVORITE_TYPE: Type = com.streamvault.domain.model.Favorite::class.javaprivate val VIRTUAL_GROUP_TYPE: Type = com.streamvault.domain.model.VirtualGroup::class.javaprivate val PLAYBACK_HISTORY_TYPE: Type = com.streamvault.domain.model.PlaybackHistory::class.java@@ -2443,6 +2991,7 @@ private val LONG_TYPE: Type = java.lang.Long::class.javaprivate val STRING_TYPE: Type = String::class.javaprivate val PROVIDER_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.LegacyProvider>>() {}.typeprivate val PROVIDER_SNAPSHOT_LIST_TYPE: Type = object : TypeToken<List<ProviderBackupSnapshot>>() {}.type+private val PROVIDER_CREDENTIALS_LIST_TYPE: Type = object : TypeToken<List<ProviderCredentials>>() {}.typeprivate val EPG_SOURCE_TYPE: Type = com.streamvault.domain.model.EpgSource::class.javaprivate val EPG_SOURCE_LIST_TYPE: Type =object : TypeToken<List<com.streamvault.domain.model.EpgSource>>() {}.typediff --git a/data/src/main/java/com/streamvault/data/manager/GoogleDriveBackupSyncManager.kt b/data/src/main/java/com/streamvault/data/manager/GoogleDriveBackupSyncManager.ktindex e8d0955d..b693fef0 100644--- a/data/src/main/java/com/streamvault/data/manager/GoogleDriveBackupSyncManager.kt+++ b/data/src/main/java/com/streamvault/data/manager/GoogleDriveBackupSyncManager.kt@@ -2,7 +2,6 @@ package com.streamvault.data.managerimport android.content.Contextimport android.util.Log-import androidx.core.net.toUriimport com.google.android.gms.auth.GoogleAuthUtilimport com.google.android.gms.auth.api.signin.GoogleSignInimport com.google.android.gms.auth.api.signin.GoogleSignInAccount@@ -18,6 +17,7 @@ import com.streamvault.domain.manager.BackupManagerimport com.streamvault.domain.manager.DriveAccountimport com.streamvault.domain.manager.DriveAuthStateimport com.streamvault.domain.manager.DriveBackupArtifact+import com.streamvault.domain.manager.DriveBackupSnapshotimport com.streamvault.domain.manager.DriveBackupSyncManagerimport com.streamvault.domain.manager.DriveSignInRequestimport com.streamvault.domain.manager.DriveSyncError@@ -30,6 +30,8 @@ import kotlinx.coroutines.flow.MutableStateFlowimport kotlinx.coroutines.flow.StateFlowimport kotlinx.coroutines.flow.asStateFlowimport kotlinx.coroutines.suspendCancellableCoroutine+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLockimport kotlinx.coroutines.withContextimport kotlin.coroutines.resumeimport kotlin.coroutines.resumeWithException@@ -43,10 +45,31 @@ import org.json.JSONArrayimport org.json.JSONObjectimport java.io.Fileimport java.io.IOException+import java.text.SimpleDateFormat+import java.util.Date+import java.util.Locale+import java.util.TimeZone+import java.util.UUIDimport java.util.concurrent.TimeUnitimport javax.inject.Injectimport javax.inject.Singleton+private const val GOOGLE_DRIVE_API_BASE_URL = "https://www.googleapis.com"++private fun buildDefaultDriveHttpClient(): OkHttpClient = OkHttpClient.Builder()+ .connectTimeout(20, TimeUnit.SECONDS)+ .readTimeout(60, TimeUnit.SECONDS)+ .writeTimeout(60, TimeUnit.SECONDS)+ .build()++private fun buildDefaultGoogleDriveClient(context: Context): GoogleSignInClient {+ val options = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)+ .requestEmail()+ .requestScopes(Scope("https://www.googleapis.com/auth/drive.appdata"))+ .build()+ return GoogleSignIn.getClient(context, options)+}+/*** Implementation backed by Google Sign-In + the Drive REST `appDataFolder` scope.*@@ -55,22 +78,60 @@ import javax.inject.Singleton* the OAuth credentials registered in the Google Cloud Console project. Each* maintainer / signing key must register its own OAuth client (see* `docs/GOOGLE_DRIVE_SETUP.md`).- * - The backup payload is the existing [BackupManager] JSON v5 export — we just- * pipe it through a temp file under [Context.getCacheDir] and upload/download- * via multipart REST. No extra format, no extra schema.- * - Sensitive provider passwords are already stripped by [BackupManager.exportConfig].+ * - New pushes use a timestamped versioned bundle containing the existing+ * [BackupManager] JSON export and matching credentials snapshot. A bounded+ * history lets users restore an older generation without reintroducing the+ * old two-file generation mismatch.+ * - Pulls list snapshots newest-first and accept the bundle plus legacy+ * standalone backup and credentials files for backwards compatibility.*/@Singleton-class GoogleDriveBackupSyncManager @Inject constructor(+class GoogleDriveBackupSyncManager private constructor(@ApplicationContext private val context: Context,private val backupManager: BackupManager,+ private val httpClient: OkHttpClient,+ driveApiBaseUrl: String,+ private val fixedAccessToken: String?,+ private val authClientFactory: () -> GoogleSignInClient,+ private val cachedAccountProvider: () -> GoogleSignInAccount?,+ @Suppress("UNUSED_PARAMETER") constructorMarker: Unit,) : DriveBackupSyncManager {- private val httpClient: OkHttpClient = OkHttpClient.Builder()- .connectTimeout(20, TimeUnit.SECONDS)- .readTimeout(60, TimeUnit.SECONDS)- .writeTimeout(60, TimeUnit.SECONDS)- .build()+ private val driveApiBaseUrl = driveApiBaseUrl.trimEnd('/')++ @Inject+ constructor(+ @ApplicationContext context: Context,+ backupManager: BackupManager,+ ) : this(+ context = context,+ backupManager = backupManager,+ httpClient = buildDefaultDriveHttpClient(),+ driveApiBaseUrl = GOOGLE_DRIVE_API_BASE_URL,+ fixedAccessToken = null,+ authClientFactory = { buildDefaultGoogleDriveClient(context) },+ cachedAccountProvider = { GoogleSignIn.getLastSignedInAccount(context) },+ constructorMarker = Unit,+ )++ internal constructor(+ context: Context,+ backupManager: BackupManager,+ httpClient: OkHttpClient,+ driveApiBaseUrl: String,+ fixedAccessToken: String,+ authClientFactory: (() -> GoogleSignInClient)? = null,+ cachedAccountProvider: (() -> GoogleSignInAccount?)? = null,+ ) : this(+ context = context,+ backupManager = backupManager,+ httpClient = httpClient,+ driveApiBaseUrl = driveApiBaseUrl,+ fixedAccessToken = fixedAccessToken,+ authClientFactory = authClientFactory ?: { buildDefaultGoogleDriveClient(context) },+ cachedAccountProvider = cachedAccountProvider ?: { GoogleSignIn.getLastSignedInAccount(context) },+ constructorMarker = Unit,+ )private val _authState = MutableStateFlow<DriveAuthState>(DriveAuthState.SignedOut)override val authState: StateFlow<DriveAuthState> = _authState.asStateFlow()@@ -78,11 +139,22 @@ class GoogleDriveBackupSyncManager @Inject constructor(private val _syncStatus = MutableStateFlow(DriveSyncStatus())override val syncStatus: StateFlow<DriveSyncStatus> = _syncStatus.asStateFlow()+ /**+ * Serializes operations that share the Drive file identity and auth state.+ * The UI also suppresses duplicate actions, but callers outside that UI+ * must not be able to race two lookup-then-upload sequences.+ */+ private val operationMutex = Mutex()+init {- // Restore last known account silently on cold start.- val cached = GoogleSignIn.getLastSignedInAccount(context)- if (cached != null && hasAppDataScope(cached)) {- _authState.value = DriveAuthState.SignedIn(cached.toDriveAccount())+ if (fixedAccessToken != null) {+ _authState.value = DriveAuthState.SignedIn(DriveAccount("test", "test"))+ } else {+ // Restore last known account silently on cold start.+ val cached = cachedAccountProvider()+ if (cached != null && hasAppDataScope(cached)) {+ _authState.value = DriveAuthState.SignedIn(cached.toDriveAccount())+ }}}@@ -131,12 +203,25 @@ class GoogleDriveBackupSyncManager @Inject constructor(}override suspend fun signOut(): Result<Unit> = withContext(Dispatchers.IO) {- try {- buildClient().signOut().awaitTask()- _authState.value = DriveAuthState.SignedOut- Result.Success(Unit)- } catch (t: Throwable) {- Result.Error(DriveSyncError.AUTH_FAILED, t)+ operationMutex.withLock {+ try {+ val client = buildClient()+ val revokeFailure = runCatching {+ if (cachedAccountProvider() != null) {+ client.revokeAccess().awaitTask()+ }+ }.exceptionOrNull()+ client.signOut().awaitTask()+ _authState.value = DriveAuthState.SignedOut+ if (revokeFailure != null) {+ driveError(DriveSyncError.AUTH_FAILED, revokeFailure)+ } else {+ Result.Success(Unit)+ }+ } catch (t: Throwable) {+ _authState.value = DriveAuthState.SignedOut+ driveError(DriveSyncError.AUTH_FAILED, t)+ }}}@@ -160,75 +245,221 @@ class GoogleDriveBackupSyncManager @Inject constructor(addOnCanceledListener { cont.resume(null) }}- override suspend fun pushBackup(): Result<DriveSyncStatus> = withContext(Dispatchers.IO) {- val account = requireSignedInAccount() ?: return@withContext Result.Error(DriveSyncError.NOT_SIGNED_IN)- val token = fetchAccessToken(account) ?: return@withContext Result.Error(DriveSyncError.AUTH_FAILED)+ override suspend fun pushBackup(+ credentials: List<ProviderCredentials>,+ ): Result<DriveSyncStatus> = withContext(Dispatchers.IO) {+ operationMutex.withLock {+ val accessTokenResult = accessTokenResult()+ if (accessTokenResult is Result.Error) return@withContext accessTokenResult+ val token = (accessTokenResult as Result.Success).data++ val tempFile = File.createTempFile("drive_sync_backup_", ".json", context.cacheDir)+ val bundleFile = File.createTempFile("drive_sync_bundle_", ".json", context.cacheDir)+ val exportUri = tempFile.toURI().toString()++ val exportResult = backupManager.exportConfig(exportUri)+ if (exportResult is Result.Error) {+ return@withContext driveError(DriveSyncError.EXPORT_FAILED, exportResult.exception)+ }+ if (!tempFile.exists() || tempFile.length() == 0L || tempFile.length() > MAX_BACKUP_BYTES) {+ tempFile.delete()+ return@withContext driveError(DriveSyncError.EXPORT_FAILED)+ }- val tempFile = File(context.cacheDir, TEMP_BACKUP_FILE_NAME).apply { delete() }- val exportUri = tempFile.toUri().toString()+ val bundleBuilt = try {+ // Keep the exported backup text unchanged. Re-parsing it into a+ // JSONObject and serializing it again can alter escaping/order and+ // breaks exact-byte checksum compatibility for older releases.+ val backupJson = tempFile.readText(Charsets.UTF_8)+ JSONObject(backupJson)+ val bundle = JSONObject()+ .put("format", DRIVE_BUNDLE_FORMAT)+ .put("backupJson", backupJson)+ .put("credentials", credentials.toJsonArray())+ bundleFile.writeText(bundle.toString(), Charsets.UTF_8)+ bundleFile.length() > 0L && bundleFile.length() <= MAX_DRIVE_FILE_BYTES+ } catch (t: Throwable) {+ Log.e("DriveSync", "pushBackup: failed to build bundle", t)+ false+ }+ if (!bundleBuilt) {+ tempFile.delete()+ bundleFile.delete()+ return@withContext driveError(DriveSyncError.EXPORT_FAILED)+ }- val exportResult = backupManager.exportConfig(exportUri)- if (exportResult is Result.Error) {- return@withContext Result.Error(DriveSyncError.EXPORT_FAILED, exportResult.exception)- }- if (!tempFile.exists() || tempFile.length() == 0L) {- return@withContext Result.Error(DriveSyncError.EXPORT_FAILED)- }+ val bundleFileName = buildBundleFileName()+ val uploadOk = try {+ uploadAppDataFile(+ authToken = token,+ payload = bundleFile,+ fileName = bundleFileName,+ overwriteExisting = false,+ )+ } catch (io: IOException) {+ return@withContext driveHttpError(io)+ } finally {+ tempFile.delete()+ bundleFile.delete()+ }+ if (!uploadOk) {+ return@withContext driveError(DriveSyncError.NETWORK)+ }- val uploadOk = try {- uploadAppDataFile(token, tempFile, BACKUP_FILE_NAME)- } catch (io: IOException) {- return@withContext Result.Error(DriveSyncError.NETWORK, io)- } finally {- tempFile.delete()+ trimRemoteBackups(token)++ val updated = _syncStatus.value.copy(+ lastPushAtMs = System.currentTimeMillis(),+ lastErrorMessage = null,+ )+ _syncStatus.value = updated+ Result.Success(updated)}- if (!uploadOk) {- return@withContext Result.Error(DriveSyncError.NETWORK)+ }++ override suspend fun listBackups(): Result<List<DriveBackupSnapshot>> = withContext(Dispatchers.IO) {+ operationMutex.withLock {+ val accessTokenResult = accessTokenResult()+ if (accessTokenResult is Result.Error) return@withContext accessTokenResult+ val token = (accessTokenResult as Result.Success).data+ try {+ Result.Success(listRemoteBackups(token).map { it.toSnapshot() })+ } catch (io: IOException) {+ driveHttpError(io)+ }}+ }- val updated = _syncStatus.value.copy(- lastPushAtMs = System.currentTimeMillis(),- lastErrorMessage = null,- )- _syncStatus.value = updated- Result.Success(updated)+ override suspend fun deleteBackup(snapshotId: String): Result<Unit> = withContext(Dispatchers.IO) {+ operationMutex.withLock {+ val accessTokenResult = accessTokenResult()+ if (accessTokenResult is Result.Error) return@withContext accessTokenResult+ val token = (accessTokenResult as Result.Success).data+ val selected = try {+ listRemoteBackups(token).firstOrNull { it.id == snapshotId }+ } catch (io: IOException) {+ return@withContext driveHttpError(io)+ }+ if (selected == null) {+ return@withContext driveError(DriveSyncError.NO_REMOTE_BACKUP)+ }+ try {+ deleteRemoteFile(token, selected.id)+ if (!selected.isBundle) {+ // Legacy installs stored credentials in a sibling file.+ // Remove it with the legacy backup so sensitive orphaned+ // credentials are not left behind after user cleanup.+ val legacyCredentialsId = findRemoteFileId(token, CREDENTIALS_FILE_NAME)+ if (legacyCredentialsId != null) {+ runCatching { deleteRemoteFile(token, legacyCredentialsId) }+ .onFailure { error ->+ Log.w("DriveSync", "legacy credentials cleanup failed", error)+ }+ }+ }+ Result.Success(Unit)+ } catch (io: IOException) {+ driveHttpError(io)+ }+ }}- override suspend fun pullBackup(): Result<DriveBackupArtifact> = withContext(Dispatchers.IO) {+ override suspend fun pullBackup(snapshotId: String?): Result<DriveBackupArtifact> = withContext(Dispatchers.IO) {+ operationMutex.withLock {Log.d("DriveSync", "pullBackup: start")- val account = requireSignedInAccount() ?: run {- Log.w("DriveSync", "pullBackup: NOT_SIGNED_IN (account is null)")- return@withContext Result.Error(DriveSyncError.NOT_SIGNED_IN)- }- val token = fetchAccessToken(account) ?: run {- Log.w("DriveSync", "pullBackup: AUTH_FAILED (no token)")- return@withContext Result.Error(DriveSyncError.AUTH_FAILED)- }- Log.d("DriveSync", "pullBackup: token OK, looking up remote backup id")+ val accessTokenResult = accessTokenResult()+ if (accessTokenResult is Result.Error) return@withContext accessTokenResult+ val token = (accessTokenResult as Result.Success).data+ Log.d("DriveSync", "pullBackup: token OK, looking up remote snapshots")- val fileId = try {- findRemoteFileId(token, BACKUP_FILE_NAME)+ val remoteBackups = try {+ listRemoteBackups(token)} catch (io: IOException) {- Log.e("DriveSync", "pullBackup: NETWORK error while finding remote id", io)- return@withContext Result.Error(DriveSyncError.NETWORK, io)+ Log.e("DriveSync", "pullBackup: NETWORK error while finding snapshots", io)+ return@withContext driveHttpError(io)}- if (fileId == null) {- Log.w("DriveSync", "pullBackup: NO_REMOTE_BACKUP (no file found in appDataFolder)")- return@withContext Result.Error(DriveSyncError.NO_REMOTE_BACKUP)+ val selected = if (snapshotId == null) {+ remoteBackups.firstOrNull()+ } else {+ remoteBackups.firstOrNull { it.id == snapshotId }}- Log.d("DriveSync", "pullBackup: remote fileId=$fileId, downloading")+ if (selected == null) {+ Log.w("DriveSync", "pullBackup: NO_REMOTE_BACKUP (no bundle or legacy file found)")+ return@withContext driveError(DriveSyncError.NO_REMOTE_BACKUP)+ }+ val legacyFallback = !selected.isBundle+ val fileId = selected.id+ Log.d("DriveSync", "pullBackup: remote fileId=$fileId, name=${selected.name}, bundle=${selected.isBundle}, downloading")- val target = File(context.cacheDir, TEMP_BACKUP_FILE_NAME).apply { delete() }+ val target = File.createTempFile("drive_sync_backup_", ".json", context.cacheDir).apply { delete() }+ val downloadTarget = if (legacyFallback) {+ target+ } else {+ File.createTempFile("drive_sync_bundle_", ".json", context.cacheDir).apply { delete() }+ }val downloadOk = try {- downloadAppDataFile(token, fileId, target)+ downloadAppDataFile(+ authToken = token,+ fileId = fileId,+ target = downloadTarget,+ maxBytes = if (legacyFallback) MAX_BACKUP_BYTES else MAX_DRIVE_FILE_BYTES,+ )+ } catch (tooLarge: DrivePayloadTooLargeException) {+ downloadTarget.delete()+ return@withContext driveError(DriveSyncError.PAYLOAD_TOO_LARGE, tooLarge)} catch (io: IOException) {Log.e("DriveSync", "pullBackup: NETWORK error during download", io)- return@withContext Result.Error(DriveSyncError.NETWORK, io)+ downloadTarget.delete()+ return@withContext driveHttpError(io)}- if (!downloadOk || !target.exists() || target.length() == 0L) {- Log.w("DriveSync", "pullBackup: download failed or empty file (ok=$downloadOk exists=${target.exists()} size=${target.length()})")+ if (!downloadOk || !downloadTarget.exists() || downloadTarget.length() == 0L) {+ Log.w("DriveSync", "pullBackup: download failed or empty file (ok=$downloadOk exists=${downloadTarget.exists()} size=${downloadTarget.length()})")+ downloadTarget.delete()+ return@withContext driveError(DriveSyncError.NETWORK)+ }++ val credentials: List<ProviderCredentials>?+ if (legacyFallback) {+ credentials = null+ } else {+ try {+ val bundle = JSONObject(downloadTarget.readText(Charsets.UTF_8))+ val format = bundle.optString("format")+ val backupJson = when (format) {+ DRIVE_BUNDLE_FORMAT -> bundle.optString("backupJson", "")+ LEGACY_DRIVE_BUNDLE_FORMAT -> bundle.optJSONObject("backup")?.toString().orEmpty()+ else -> throw IllegalArgumentException("Unsupported Drive backup bundle format")+ }+ if (backupJson.isBlank()) {+ throw IllegalArgumentException("Drive backup bundle is missing backup")+ }+ // Validate that the preserved text is one JSON object, but write+ // the original text rather than JSONObject.toString() so the+ // backup checksum sees the bytes that were exported.+ JSONObject(backupJson)+ val credentialsArray = bundle.optJSONArray("credentials")+ ?: throw IllegalArgumentException("Drive backup bundle is missing credentials")+ if (backupJson.toByteArray(Charsets.UTF_8).size.toLong() > MAX_BACKUP_BYTES) {+ throw DrivePayloadTooLargeException()+ }+ target.writeBytes(backupJson.toByteArray(Charsets.UTF_8))+ credentials = credentialsArray.toProviderCredentials()+ } catch (tooLarge: DrivePayloadTooLargeException) {+ target.delete()+ downloadTarget.delete()+ return@withContext driveError(DriveSyncError.PAYLOAD_TOO_LARGE, tooLarge)+ } catch (t: Throwable) {+ Log.e("DriveSync", "pullBackup: bundle parse error", t)+ target.delete()+ downloadTarget.delete()+ return@withContext driveError(DriveSyncError.IMPORT_FAILED, t)+ } finally {+ downloadTarget.delete()+ }+ }+ if (!target.exists() || target.length() == 0L) {target.delete()- return@withContext Result.Error(DriveSyncError.NETWORK)+ return@withContext driveError(DriveSyncError.IMPORT_FAILED)}Log.d("DriveSync", "pullBackup: downloaded ${target.length()} bytes to ${target.absolutePath}")@@ -236,114 +467,105 @@ class GoogleDriveBackupSyncManager @Inject constructor(lastPullAtMs = System.currentTimeMillis(),lastErrorMessage = null,)- Result.Success(- DriveBackupArtifact(- localUriString = target.toUri().toString(),- sizeBytes = target.length(),- ),- )+ Result.Success(+ DriveBackupArtifact(+ localUriString = target.toURI().toString(),+ sizeBytes = target.length(),+ credentials = credentials,+ ),+ )+ }}override suspend fun pushCredentials(credentials: List<ProviderCredentials>,): Result<Unit> = withContext(Dispatchers.IO) {+ operationMutex.withLock {Log.d("DriveSync", "pushCredentials: start (count=${credentials.size})")- val account = requireSignedInAccount() ?: return@withContext Result.Error(DriveSyncError.NOT_SIGNED_IN)- val token = fetchAccessToken(account) ?: return@withContext Result.Error(DriveSyncError.AUTH_FAILED)-- val json = JSONArray().apply {- credentials.forEach { cred ->- put(- JSONObject().apply {- put("serverUrl", cred.serverUrl)- put("username", cred.username)- put("password", cred.password)- },- )- }- }.toString()+ val accessTokenResult = accessTokenResult()+ if (accessTokenResult is Result.Error) return@withContext accessTokenResult+ val token = (accessTokenResult as Result.Success).data- val tempFile = File(context.cacheDir, TEMP_CREDENTIALS_FILE_NAME).apply { delete() }+ val json = credentials.toJsonArray().toString()++ val tempFile = File.createTempFile("drive_sync_credentials_", ".json", context.cacheDir)tempFile.writeText(json)val uploadOk = try {uploadAppDataFile(token, tempFile, CREDENTIALS_FILE_NAME)} catch (io: IOException) {- return@withContext Result.Error(DriveSyncError.NETWORK, io)+ return@withContext driveHttpError(io)} finally {tempFile.delete()}if (!uploadOk) {Log.w("DriveSync", "pushCredentials: upload failed")- return@withContext Result.Error(DriveSyncError.NETWORK)+ return@withContext driveError(DriveSyncError.NETWORK)}Log.d("DriveSync", "pushCredentials: SUCCESS")- Result.Success(Unit)+ _syncStatus.value = _syncStatus.value.copy(lastErrorMessage = null)+ Result.Success(Unit)+ }}override suspend fun pullCredentials(): Result<List<ProviderCredentials>> = withContext(Dispatchers.IO) {+ operationMutex.withLock {Log.d("DriveSync", "pullCredentials: start")- val account = requireSignedInAccount() ?: return@withContext Result.Error(DriveSyncError.NOT_SIGNED_IN)- val token = fetchAccessToken(account) ?: return@withContext Result.Error(DriveSyncError.AUTH_FAILED)+ val accessTokenResult = accessTokenResult()+ if (accessTokenResult is Result.Error) return@withContext accessTokenResult+ val token = (accessTokenResult as Result.Success).dataval fileId = try {findRemoteFileId(token, CREDENTIALS_FILE_NAME)} catch (io: IOException) {- return@withContext Result.Error(DriveSyncError.NETWORK, io)+ return@withContext driveHttpError(io)}if (fileId == null) {Log.d("DriveSync", "pullCredentials: no remote credentials file (pre-M3 backup), returning empty list")return@withContext Result.Success(emptyList())}- val target = File(context.cacheDir, TEMP_CREDENTIALS_FILE_NAME).apply { delete() }+ val target = File.createTempFile("drive_sync_credentials_", ".json", context.cacheDir).apply { delete() }val downloadOk = try {- downloadAppDataFile(token, fileId, target)+ downloadAppDataFile(token, fileId, target, MAX_DRIVE_FILE_BYTES)+ } catch (tooLarge: DrivePayloadTooLargeException) {+ target.delete()+ return@withContext driveError(DriveSyncError.PAYLOAD_TOO_LARGE, tooLarge)} catch (io: IOException) {target.delete()- return@withContext Result.Error(DriveSyncError.NETWORK, io)+ return@withContext driveHttpError(io)}if (!downloadOk || !target.exists() || target.length() == 0L) {target.delete()- return@withContext Result.Error(DriveSyncError.NETWORK)+ return@withContext driveError(DriveSyncError.NETWORK)}val parsed = try {- val array = JSONArray(target.readText())- (0 until array.length()).map { idx ->- val obj = array.getJSONObject(idx)- ProviderCredentials(- serverUrl = obj.getString("serverUrl"),- username = obj.getString("username"),- password = obj.getString("password"),- )- }+ JSONArray(target.readText(Charsets.UTF_8)).toProviderCredentials()} catch (t: Throwable) {Log.e("DriveSync", "pullCredentials: JSON parse error", t)target.delete()- return@withContext Result.Error(DriveSyncError.IMPORT_FAILED, t)+ return@withContext driveError(DriveSyncError.IMPORT_FAILED, t)} finally {target.delete()}Log.d("DriveSync", "pullCredentials: SUCCESS (count=${parsed.size})")- Result.Success(parsed)+ _syncStatus.value = _syncStatus.value.copy(lastErrorMessage = null)+ Result.Success(parsed)+ }}// ── Internals ─────────────────────────────────────────────────────────────private fun buildClient(): GoogleSignInClient {- val options = GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)- .requestEmail()- .requestScopes(Scope(SCOPE_APP_DATA))- .build()- return GoogleSignIn.getClient(context, options)+ return authClientFactory()}private fun hasAppDataScope(account: GoogleSignInAccount): Boolean =GoogleSignIn.hasPermissions(account, Scope(SCOPE_APP_DATA))private fun requireSignedInAccount(): GoogleSignInAccount? {- val cached = GoogleSignIn.getLastSignedInAccount(context) ?: return null+ val cached = cachedAccountProvider() ?: return nullif (!hasAppDataScope(cached)) return nullreturn cached}@@ -359,10 +581,35 @@ class GoogleDriveBackupSyncManager @Inject constructor(null}+ private fun accessTokenResult(): Result<String> {+ fixedAccessToken?.let { return Result.Success(it) }+ val account = requireSignedInAccount()+ ?: return driveError(DriveSyncError.NOT_SIGNED_IN)+ val token = fetchAccessToken(account)+ ?: return driveError(DriveSyncError.AUTH_FAILED)+ return Result.Success(token)+ }++ private fun driveError(code: String, exception: Throwable? = null): Result.Error {+ _syncStatus.value = _syncStatus.value.copy(lastErrorMessage = code)+ return Result.Error(code, exception)+ }++ private fun driveHttpError(exception: IOException): Result.Error {+ val statusCode = (exception as? DriveHttpException)?.statusCode+ val code = if (statusCode == 401 || statusCode == 403) {+ DriveSyncError.AUTH_FAILED+ } else {+ DriveSyncError.NETWORK+ }+ return driveError(code, exception)+ }+private suspend fun findRemoteFileId(authToken: String, fileName: String): String? {- val url = "https://www.googleapis.com/drive/v3/files" ++ val url = "$driveApiBaseUrl/drive/v3/files" +"?spaces=appDataFolder" +"&q=" + uriEncode("name='$fileName'") ++ "&orderBy=modifiedTime%20desc" +"&fields=files(id,modifiedTime,size)"val request = Request.Builder().url(url)@@ -370,21 +617,33 @@ class GoogleDriveBackupSyncManager @Inject constructor(.get().build()httpClient.newCall(request).useCancellableResponse { response ->- if (!response.isSuccessful) return null+ if (!response.isSuccessful) {+ throw DriveHttpException(response.code, "Drive file lookup failed")+ }val body = response.body?.string().orEmpty()- val files = JSONObject(body).optJSONArray("files") ?: return null+ val files = JSONObject(body).optJSONArray("files")+ ?: throw IOException("Drive file lookup response is missing files")if (files.length() == 0) return nullreturn files.getJSONObject(0).getString("id")}}- private suspend fun uploadAppDataFile(authToken: String, payload: File, fileName: String): Boolean {- val existingId = findRemoteFileId(authToken, fileName)+ private suspend fun uploadAppDataFile(+ authToken: String,+ payload: File,+ fileName: String,+ overwriteExisting: Boolean = true,+ ): Boolean {+ val existingId = if (overwriteExisting) {+ findRemoteFileId(authToken, fileName)+ } else {+ null+ }val boundary = "streamvault-${System.nanoTime()}"val (httpMethod, endpoint) = if (existingId != null) {- "PATCH" to "https://www.googleapis.com/upload/drive/v3/files/$existingId?uploadType=multipart"+ "PATCH" to "$driveApiBaseUrl/upload/drive/v3/files/$existingId?uploadType=multipart"} else {- "POST" to "https://www.googleapis.com/upload/drive/v3/files?uploadType=multipart"+ "POST" to "$driveApiBaseUrl/upload/drive/v3/files?uploadType=multipart"}val metadata = JSONObject().apply {@@ -402,20 +661,149 @@ class GoogleDriveBackupSyncManager @Inject constructor(.build()httpClient.newCall(request).useCancellableResponse { response ->- return response.isSuccessful+ if (!response.isSuccessful) {+ throw DriveHttpException(response.code, "Drive upload failed")+ }+ return true}}- private suspend fun downloadAppDataFile(authToken: String, fileId: String, target: File): Boolean {+ /**+ * Returns the backup files we own in Drive, newest first. The fixed names+ * keep old installs and pre-history backups visible; timestamped bundles+ * are the files created by current pushes.+ */+ private suspend fun listRemoteBackups(authToken: String): List<RemoteBackupFile> {+ val query = "trashed = false and (" ++ "name = '$BUNDLE_FILE_NAME' or " ++ "name contains '$BUNDLE_FILE_PREFIX' or " ++ "name = '$BACKUP_FILE_NAME')"+ val url = "$driveApiBaseUrl/drive/v3/files" ++ "?spaces=appDataFolder" ++ "&q=" + uriEncode(query) ++ "&orderBy=modifiedTime%20desc" ++ "&pageSize=100" ++ "&fields=files(id,name,modifiedTime,size)"val request = Request.Builder()- .url("https://www.googleapis.com/drive/v3/files/$fileId?alt=media")+ .url(url).addHeader("Authorization", "Bearer $authToken").get().build()httpClient.newCall(request).useCancellableResponse { response ->- if (!response.isSuccessful) return false- val source = response.body?.byteStream() ?: return false- target.outputStream().use { sink -> source.copyTo(sink) }+ if (!response.isSuccessful) {+ throw DriveHttpException(response.code, "Drive backup list failed")+ }+ val body = response.body?.string().orEmpty()+ val files = JSONObject(body).optJSONArray("files")+ ?: throw IOException("Drive backup list response is missing files")+ return (0 until files.length())+ .mapNotNull { index ->+ val file = files.optJSONObject(index) ?: return@mapNotNull null+ val id = file.optString("id").takeIf { it.isNotBlank() }+ ?: return@mapNotNull null+ val name = file.optString("name").takeIf { it.isNotBlank() }+ ?: return@mapNotNull null+ RemoteBackupFile(+ id = id,+ name = name,+ modifiedAtMs = parseDriveTimestamp(file.optString("modifiedTime")),+ sizeBytes = file.optLong("size", 0L).coerceAtLeast(0L),+ isBundle = name == BUNDLE_FILE_NAME || name.startsWith(BUNDLE_FILE_PREFIX),+ )+ }+ .sortedWith(+ compareByDescending<RemoteBackupFile> { it.modifiedAtMs ?: Long.MIN_VALUE }+ .thenByDescending { it.id },+ )+ }+ }++ private suspend fun trimRemoteBackups(authToken: String) {+ try {+ val timestamped = listRemoteBackups(authToken)+ .filter { it.isBundle && it.name.startsWith(BUNDLE_FILE_PREFIX) }+ timestamped.drop(MAX_REMOTE_BACKUPS).forEach { remote ->+ runCatching { deleteRemoteFile(authToken, remote.id) }+ .onFailure { error ->+ Log.w("DriveSync", "retention cleanup failed for ${remote.id}", error)+ }+ }+ } catch (io: IOException) {+ // Retention is housekeeping. A successful upload must remain a+ // success even if listing/cleanup is temporarily unavailable.+ Log.w("DriveSync", "retention listing failed", io)+ }+ }++ private suspend fun deleteRemoteFile(authToken: String, fileId: String) {+ val request = Request.Builder()+ .url("$driveApiBaseUrl/drive/v3/files/$fileId")+ .addHeader("Authorization", "Bearer $authToken")+ .delete()+ .build()+ httpClient.newCall(request).useCancellableResponse { response ->+ if (!response.isSuccessful) {+ throw DriveHttpException(response.code, "Drive backup retention delete failed")+ }+ }+ }++ private fun parseDriveTimestamp(value: String): Long? {+ if (value.isBlank()) return null+ val formats = listOf(+ "yyyy-MM-dd'T'HH:mm:ss.SSSX",+ "yyyy-MM-dd'T'HH:mm:ssX",+ )+ return formats.firstNotNullOfOrNull { pattern ->+ runCatching {+ SimpleDateFormat(pattern, Locale.US).apply {+ timeZone = TimeZone.getTimeZone("UTC")+ }.parse(value)?.time+ }.getOrNull()+ }+ }++ private fun buildBundleFileName(): String {+ val timestamp = SimpleDateFormat("yyyyMMdd_HHmmss_SSS", Locale.US).apply {+ timeZone = TimeZone.getTimeZone("UTC")+ }.format(Date())+ return "$BUNDLE_FILE_PREFIX${timestamp}_${UUID.randomUUID().toString().take(8)}.json"+ }++ private suspend fun downloadAppDataFile(+ authToken: String,+ fileId: String,+ target: File,+ maxBytes: Long,+ ): Boolean {+ val request = Request.Builder()+ .url("$driveApiBaseUrl/drive/v3/files/$fileId?alt=media")+ .addHeader("Authorization", "Bearer $authToken")+ .get()+ .build()+ httpClient.newCall(request).useCancellableResponse { response ->+ if (!response.isSuccessful) {+ throw DriveHttpException(response.code, "Drive download failed")+ }+ val body = response.body ?: return false+ if (body.contentLength() > maxBytes) {+ throw DrivePayloadTooLargeException()+ }+ body.byteStream().use { source ->+ target.outputStream().use { sink ->+ val buffer = ByteArray(DEFAULT_BUFFER_SIZE)+ var total = 0L+ while (true) {+ val read = source.read(buffer)+ if (read < 0) break+ total += read+ if (total > maxBytes) {+ throw DrivePayloadTooLargeException()+ }+ sink.write(buffer, 0, read)+ }+ }+ }return true}}@@ -430,10 +818,67 @@ class GoogleDriveBackupSyncManager @Inject constructor(private companion object {const val SCOPE_APP_DATA = "https://www.googleapis.com/auth/drive.appdata"+ const val BUNDLE_FILE_NAME = "streamvault_backup_bundle.json"+ const val BUNDLE_FILE_PREFIX = "streamvault_backup_bundle_"const val BACKUP_FILE_NAME = "streamvault_backup.json"- const val TEMP_BACKUP_FILE_NAME = "drive_sync_backup.json"const val CREDENTIALS_FILE_NAME = "streamvault_credentials.json"- const val TEMP_CREDENTIALS_FILE_NAME = "drive_sync_credentials.json"+ const val DRIVE_BUNDLE_FORMAT = "streamvault-drive-bundle-v2"+ const val LEGACY_DRIVE_BUNDLE_FORMAT = "streamvault-drive-bundle-v1"+ const val MAX_BACKUP_BYTES = 16L * 1024L * 1024L+ // v2 stores the backup as an escaped JSON string, so allow the bundle+ // to be up to roughly twice the standalone backup admission limit.+ const val MAX_DRIVE_FILE_BYTES = 40L * 1024L * 1024L+ const val MAX_REMOTE_BACKUPS = 10+ }+}++private data class RemoteBackupFile(+ val id: String,+ val name: String,+ val modifiedAtMs: Long?,+ val sizeBytes: Long,+ val isBundle: Boolean,+)++private fun RemoteBackupFile.toSnapshot(): DriveBackupSnapshot = DriveBackupSnapshot(+ id = id,+ fileName = name,+ modifiedAtMs = modifiedAtMs,+ sizeBytes = sizeBytes,+ isBundle = isBundle,+)++private class DriveHttpException(+ val statusCode: Int,+ message: String,+) : IOException("$message: HTTP $statusCode")++private class DrivePayloadTooLargeException : IOException("Drive payload exceeds the maximum supported size")+private const val MAX_CREDENTIAL_COUNT = 10_000++private fun List<ProviderCredentials>.toJsonArray(): JSONArray = JSONArray().apply {+ forEach { credential ->+ put(+ JSONObject().apply {+ put("serverUrl", credential.serverUrl)+ put("username", credential.username)+ put("password", credential.password)+ },+ )+ }+}++private fun JSONArray.toProviderCredentials(): List<ProviderCredentials> {+ if (length() > MAX_CREDENTIAL_COUNT) {+ throw IllegalArgumentException("Too many provider credentials in Drive backup")+ }+ return (0 until length()).map { index ->+ val objectValue = getJSONObject(index)+ ProviderCredentials(+ serverUrl = objectValue.getString("serverUrl"),+ username = objectValue.getString("username"),+ password = objectValue.getString("password"),+ )}}diff --git a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.ktindex 6a041fc6..92de6a75 100644--- a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt@@ -16,6 +16,7 @@ import com.streamvault.data.local.dao.ProviderSnapshotDaoimport com.streamvault.data.local.dao.BackupRestoreCheckpointDaoimport com.streamvault.data.local.dao.ChannelDaoimport com.streamvault.data.local.dao.RecordingScheduleDao+import com.streamvault.data.local.dao.SeriesDaoimport com.streamvault.data.local.dao.VirtualGroupDaoimport com.streamvault.data.local.entity.ProviderEntityimport com.streamvault.data.local.entity.ProviderConfigEntity@@ -23,7 +24,10 @@ import com.streamvault.data.provider.ProviderConfigurationCodecimport com.streamvault.data.local.entity.EpgSourceEntityimport com.streamvault.data.local.entity.BackupRestoreCheckpointEntityimport com.streamvault.data.local.entity.ChannelEntity+import com.streamvault.data.local.entity.EpisodeEntity+import com.streamvault.data.local.entity.MovieEntityimport com.streamvault.data.local.entity.RecordingScheduleEntity+import com.streamvault.data.local.entity.SeriesEntityimport com.streamvault.data.local.entity.VirtualGroupEntityimport com.streamvault.data.mapper.toEntityimport com.streamvault.data.provider.toProviderSnapshot@@ -38,6 +42,7 @@ import com.streamvault.domain.manager.PortableCategoryReferenceimport com.streamvault.domain.manager.PortableChannelReferenceimport com.streamvault.domain.manager.PortableProviderPreferencesBackupimport com.streamvault.domain.manager.PortableVirtualGroupReference+import com.streamvault.domain.manager.ProviderCredentialsimport com.streamvault.domain.manager.RecordingManagerimport com.streamvault.domain.manager.RecordingScheduleImportDispositionimport com.streamvault.domain.manager.ScheduledRecordingBackup@@ -65,6 +70,7 @@ import java.io.ByteArrayInputStreamimport java.io.Fileimport java.io.FileOutputStreamimport java.io.InputStream+import java.security.MessageDigestimport kotlinx.coroutines.CancellationExceptionimport kotlinx.coroutines.flow.flowOfimport kotlinx.coroutines.runBlocking@@ -84,6 +90,38 @@ import org.mockito.kotlin.wheneverclass BackupManagerImplTest {+ @Test+ fun `release obfuscated backup fields remain importable`() = runBlocking {+ val payload = """{"version":11,"portableProviderPreferences":{"a":[{"a":"https://example.com","b":"user"}],"e":false,"f":[],"g":[],"h":[],"i":[]}}"""+ val checksum = "sha256:" + MessageDigest.getInstance("SHA-256")+ .digest(payload.toByteArray())+ .joinToString(separator = "") { "%02x".format(it) }+ val json = """{"version":11,"checksum":"$checksum","portableProviderPreferences":{"a":[{"a":"https://example.com","b":"user"}],"e":false,"f":[],"g":[],"h":[],"i":[]}}"""+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val uriString = "content://obfuscated-backup"+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(anyOrNull())).thenReturn(ByteArrayInputStream(json.toByteArray()))++ val manager = backupManagerForValidation(context)+ val readMethod = BackupManagerImpl::class.java+ .getDeclaredMethod("readBackupData", String::class.java)+ .apply { isAccessible = true }+ val parsed = readMethod.invoke(manager, uriString)+ val dataField = parsed!!::class.java.getDeclaredField("data").apply { isAccessible = true }+ val data = dataField.get(parsed) as BackupData++ assertThat(data.portableProviderPreferences?.providers?.single()?.serverUrl)+ .isEqualTo("https://example.com")+ assertThat(data.portableProviderPreferences?.providers?.single()?.username)+ .isEqualTo("user")++ val verifyMethod = BackupManagerImpl::class.java+ .getDeclaredMethod("verifyChecksum", parsed::class.java)+ .apply { isAccessible = true }+ assertThat(verifyMethod.invoke(manager, parsed) as Boolean).isTrue()+ }+@Testfun `importConfig preserves explicit EPG source timezone interpretation`() = runBlocking {val context: Context = mock()@@ -425,6 +463,7 @@ class BackupManagerImplTest {movieDao = mock(),episodeDao = mock(),channelDao = mock(),+ seriesDao = mock(),categoryRepository = mock(),recordingScheduleDao = mock(),recordingManager = mock(),@@ -532,6 +571,7 @@ class BackupManagerImplTest {transactionRunner = transactionRunner,gson = gson,channelDao = mock(),+ seriesDao = mock(),providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L)))@@ -658,6 +698,7 @@ class BackupManagerImplTest {transactionRunner = transactionRunner,gson = gson,channelDao = mock(),+ seriesDao = mock(),providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L)))@@ -680,6 +721,458 @@ class BackupManagerImplTest {verify(playbackHistoryDao).insertOrUpdate(any())}+ @Test+ fun `importConfig resolves saved library and episode history through remote catalog ids`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val providerDao: ProviderDao = mock()+ val favoriteDao: FavoriteDao = mock()+ val playbackHistoryDao: PlaybackHistoryDao = mock()+ val movieDao: MovieDao = mock()+ val episodeDao: EpisodeDao = mock()+ val seriesDao: SeriesDao = mock()+ val gson = Gson()+ val backupProvider = Provider(+ id = 100L,+ name = "Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ val targetMovie = MovieEntity(+ id = 188L,+ streamId = 9001L,+ name = "Movie",+ providerId = 7L+ )+ val targetSeries = SeriesEntity(+ id = 200L,+ seriesId = 3001L,+ providerSeriesId = "series-remote",+ name = "Series",+ providerId = 7L+ )+ val targetEpisode = EpisodeEntity(+ id = 300L,+ episodeId = 7001L,+ title = "Episode",+ episodeNumber = 1,+ seasonNumber = 1,+ seriesId = targetSeries.id,+ providerId = 7L+ )+ val backupData = BackupData(+ providers = listOf(backupProvider),+ favorites = listOf(+ Favorite(+ providerId = backupProvider.id,+ contentId = 88L,+ contentType = ContentType.MOVIE,+ remoteContentId = "9001"+ )+ ),+ playbackHistory = listOf(+ PlaybackHistory(+ contentId = 55L,+ contentType = ContentType.SERIES_EPISODE,+ providerId = backupProvider.id,+ remoteContentId = "7001",+ remoteSeriesId = "series-remote",+ title = "Episode",+ streamUrl = "https://stream.example.test/episode.mp4"+ )+ )+ )+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(Uri.parse("content://remote-id-restore"))).thenReturn(+ ByteArrayInputStream(gson.toJson(backupData).toByteArray())+ )+ whenever(providerDao.getAllSync()).thenReturn(+ listOf(+ ProviderEntity(+ id = 7L,+ name = "Target Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = backupProvider.serverUrl,+ username = backupProvider.username+ )+ )+ )+ whenever(movieDao.getByStreamId(7L, 9001L)).thenReturn(targetMovie)+ whenever(seriesDao.getByProviderSeriesId(7L, "series-remote")).thenReturn(targetSeries)+ whenever(episodeDao.getByProviderSeriesAndEpisodeId(7L, targetSeries.id, 7001L))+ .thenReturn(targetEpisode)+ whenever(favoriteDao.get(any(), any(), any(), any())).thenReturn(null)+ whenever(playbackHistoryDao.get(any(), any(), any())).thenReturn(null)++ val manager = BackupManagerImpl(+ context = context,+ preferencesRepository = mock(),+ credentialCrypto = mock(),+ providerDao = providerDao,+ favoriteDao = favoriteDao,+ virtualGroupDao = mock(),+ playbackHistoryDao = playbackHistoryDao,+ movieDao = movieDao,+ episodeDao = episodeDao,+ categoryRepository = mock(),+ recordingScheduleDao = mock(),+ recordingManager = mock(),+ transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ },+ gson = gson,+ channelDao = mock(),+ seriesDao = seriesDao,+ providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L))+ )++ val result = manager.importConfig(+ uriString = "content://remote-id-restore",+ plan = BackupImportPlan(+ importPreferences = false,+ importProviders = false,+ importSavedLibrary = true,+ importPlaybackHistory = true,+ importMultiViewPresets = false,+ importRecordingSchedules = false,+ conflictStrategy = BackupConflictStrategy.KEEP_EXISTING+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val imported = (result as Result.Success).data+ assertThat(imported.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)+ assertThat(imported.unresolvedReferences).isEmpty()+ verify(favoriteDao).insert(argThat {+ providerId == 7L && contentId == targetMovie.id && contentType.name == ContentType.MOVIE.name+ })+ verify(playbackHistoryDao).insertOrUpdate(argThat {+ providerId == 7L &&+ contentId == targetEpisode.id &&+ seriesId == targetSeries.id &&+ contentType == ContentType.SERIES_EPISODE+ })+ }++ @Test+ fun `replace saved library removes old groups and restores memberships into new groups`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val providerDao: ProviderDao = mock()+ val favoriteDao: FavoriteDao = mock()+ val virtualGroupDao: VirtualGroupDao = mock()+ val movieDao: MovieDao = mock()+ val gson = Gson()+ val backupProvider = Provider(+ id = 100L,+ name = "Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ val targetMovie = MovieEntity(+ id = 188L,+ streamId = 9001L,+ name = "Movie",+ providerId = 7L+ )+ val backupData = BackupData(+ providers = listOf(backupProvider),+ virtualGroups = listOf(+ com.streamvault.domain.model.VirtualGroup(+ id = 10L,+ providerId = backupProvider.id,+ name = "Pinned",+ contentType = ContentType.MOVIE+ )+ ),+ favorites = listOf(+ Favorite(+ providerId = backupProvider.id,+ contentId = 88L,+ contentType = ContentType.MOVIE,+ remoteContentId = "9001",+ groupId = 10L+ )+ )+ )+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(Uri.parse("content://replace-library"))).thenReturn(+ ByteArrayInputStream(gson.toJson(backupData).toByteArray())+ )+ whenever(providerDao.getAllSync()).thenReturn(+ listOf(+ ProviderEntity(+ id = 7L,+ name = "Target Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = backupProvider.serverUrl,+ username = backupProvider.username+ )+ )+ )+ whenever(movieDao.getByStreamId(7L, 9001L)).thenReturn(targetMovie)+ whenever(virtualGroupDao.insert(any())).thenReturn(88L)+ whenever(favoriteDao.get(any(), any(), any(), any())).thenReturn(null)++ val manager = BackupManagerImpl(+ context = context,+ preferencesRepository = mock(),+ credentialCrypto = mock(),+ providerDao = providerDao,+ favoriteDao = favoriteDao,+ virtualGroupDao = virtualGroupDao,+ playbackHistoryDao = mock(),+ movieDao = movieDao,+ episodeDao = mock(),+ categoryRepository = mock(),+ recordingScheduleDao = mock(),+ recordingManager = mock(),+ transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ },+ gson = gson,+ channelDao = mock(),+ seriesDao = mock(),+ providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L))+ )++ val result = manager.importConfig(+ uriString = "content://replace-library",+ plan = BackupImportPlan(+ importPreferences = false,+ importProviders = false,+ importSavedLibrary = true,+ importPlaybackHistory = false,+ importMultiViewPresets = false,+ importRecordingSchedules = false,+ conflictStrategy = BackupConflictStrategy.REPLACE_EXISTING+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat((result as Result.Success).data.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)+ verify(favoriteDao).deleteByProviderAndType(7L, ContentType.MOVIE.name)+ verify(virtualGroupDao).deleteByProviderAndType(7L, ContentType.MOVIE.name)+ verify(virtualGroupDao).insert(argThat {+ id == 0L && providerId == 7L && name == "Pinned" && contentType == ContentType.MOVIE+ })+ verify(favoriteDao).insert(argThat {+ providerId == 7L && contentId == targetMovie.id && groupId == 88L+ })+ }++ @Test+ fun `replace history does not delete a provider when any portable item is unresolved`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val providerDao: ProviderDao = mock()+ val playbackHistoryDao: PlaybackHistoryDao = mock()+ val movieDao: MovieDao = mock()+ val gson = Gson()+ val backupProvider = Provider(+ id = 100L,+ name = "Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ val targetMovie = MovieEntity(+ id = 188L,+ streamId = 9001L,+ name = "Movie",+ providerId = 7L+ )+ val backupData = BackupData(+ providers = listOf(backupProvider),+ playbackHistory = listOf(+ PlaybackHistory(+ contentId = 1L,+ contentType = ContentType.MOVIE,+ providerId = backupProvider.id,+ remoteContentId = "9001",+ title = "Known",+ streamUrl = "https://stream.example.test/known.mp4"+ ),+ PlaybackHistory(+ contentId = 2L,+ contentType = ContentType.MOVIE,+ providerId = backupProvider.id,+ remoteContentId = "9999",+ title = "Missing",+ streamUrl = "https://stream.example.test/missing.mp4"+ )+ )+ )+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(Uri.parse("content://replace-history-safe"))).thenReturn(+ ByteArrayInputStream(gson.toJson(backupData).toByteArray())+ )+ whenever(providerDao.getAllSync()).thenReturn(+ listOf(+ ProviderEntity(+ id = 7L,+ name = "Target Provider",+ type = ProviderType.XTREAM_CODES,+ serverUrl = backupProvider.serverUrl,+ username = backupProvider.username+ )+ )+ )+ whenever(movieDao.getByStreamId(7L, 9001L)).thenReturn(targetMovie)+ whenever(movieDao.getByStreamId(7L, 9999L)).thenReturn(null)++ val manager = BackupManagerImpl(+ context = context,+ preferencesRepository = mock(),+ credentialCrypto = mock(),+ providerDao = providerDao,+ favoriteDao = mock(),+ virtualGroupDao = mock(),+ playbackHistoryDao = playbackHistoryDao,+ movieDao = movieDao,+ episodeDao = mock(),+ categoryRepository = mock(),+ recordingScheduleDao = mock(),+ recordingManager = mock(),+ transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ },+ gson = gson,+ channelDao = mock(),+ seriesDao = mock(),+ providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L))+ )++ val result = manager.importConfig(+ uriString = "content://replace-history-safe",+ plan = BackupImportPlan(+ importPreferences = false,+ importProviders = false,+ importSavedLibrary = false,+ importPlaybackHistory = true,+ importMultiViewPresets = false,+ importRecordingSchedules = false,+ conflictStrategy = BackupConflictStrategy.REPLACE_EXISTING+ )+ )++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val imported = (result as Result.Success).data+ assertThat(imported.outcome).isEqualTo(BackupRestoreOutcome.PARTIAL)+ assertThat(imported.unresolvedReferences).isNotEmpty()+ verify(playbackHistoryDao, never()).deleteByProvider(7L)+ verify(playbackHistoryDao, never()).insertOrUpdate(any())+ }++ @Test+ fun `inspectBackup uses provider and stable content identities for saved conflicts`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val providerDao: ProviderDao = mock()+ val favoriteDao: FavoriteDao = mock()+ val playbackHistoryDao: PlaybackHistoryDao = mock()+ val virtualGroupDao: VirtualGroupDao = mock()+ val categoryRepository: CategoryRepository = mock()+ val recordingManager: RecordingManager = mock()+ val movieDao: MovieDao = mock()+ val sourceProvider = Provider(+ id = 100L,+ name = "Source",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ val targetProvider = sourceProvider.copy(id = 7L, name = "Target")+ val existingGroup = VirtualGroupEntity(+ id = 77L,+ providerId = targetProvider.id,+ name = "Pinned",+ contentType = ContentType.MOVIE+ )+ val existingFavorite = com.streamvault.data.local.entity.FavoriteEntity(+ id = 55L,+ providerId = targetProvider.id,+ contentId = 188L,+ contentType = ContentType.MOVIE,+ groupId = existingGroup.id+ )+ val gson = Gson()+ val backupData = BackupData(+ providers = listOf(sourceProvider),+ virtualGroups = listOf(+ com.streamvault.domain.model.VirtualGroup(+ id = 10L,+ providerId = sourceProvider.id,+ name = "Pinned",+ contentType = ContentType.MOVIE+ )+ ),+ favorites = listOf(+ Favorite(+ providerId = sourceProvider.id,+ contentId = 88L,+ contentType = ContentType.MOVIE,+ remoteContentId = "9001",+ groupId = 10L+ )+ )+ )+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(contentResolver.openInputStream(Uri.parse("content://preview-identities"))).thenReturn(+ ByteArrayInputStream(gson.toJson(backupData).toByteArray())+ )+ whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider.toEntity()))+ whenever(virtualGroupDao.getByType(targetProvider.id, ContentType.LIVE.name))+ .thenReturn(flowOf(emptyList()))+ whenever(virtualGroupDao.getByType(targetProvider.id, ContentType.MOVIE.name))+ .thenReturn(flowOf(listOf(existingGroup)))+ whenever(virtualGroupDao.getByType(targetProvider.id, ContentType.SERIES.name))+ .thenReturn(flowOf(emptyList()))+ whenever(favoriteDao.getAllByType(any(), any())).thenReturn(flowOf(listOf(existingFavorite)))+ whenever(playbackHistoryDao.getAllSync()).thenReturn(emptyList())+ whenever(categoryRepository.getCategories(targetProvider.id)).thenReturn(flowOf(emptyList()))+ whenever(recordingManager.observeRecordingItems()).thenReturn(flowOf(emptyList()))+ whenever(movieDao.getById(existingFavorite.contentId)).thenReturn(+ MovieEntity(+ id = existingFavorite.contentId,+ streamId = 9001L,+ name = "Movie",+ providerId = targetProvider.id+ )+ )++ val manager = BackupManagerImpl(+ context = context,+ preferencesRepository = mock(),+ credentialCrypto = mock(),+ providerDao = providerDao,+ favoriteDao = favoriteDao,+ virtualGroupDao = virtualGroupDao,+ playbackHistoryDao = playbackHistoryDao,+ movieDao = movieDao,+ episodeDao = mock(),+ categoryRepository = categoryRepository,+ recordingScheduleDao = mock(),+ recordingManager = recordingManager,+ transactionRunner = object : DatabaseTransactionRunner {+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()+ },+ gson = gson,+ channelDao = mock(),+ seriesDao = mock(),+ providerSnapshotRepository = snapshotRepositoryFor(targetProvider)+ )++ val result = manager.inspectBackup("content://preview-identities")++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val preview = (result as Result.Success).data+ assertThat(preview.groupConflicts).isEqualTo(1)+ assertThat(preview.favoriteConflicts).isEqualTo(1)+ }+@Testfun `importConfig does not restore preferences before room-backed import succeeds`() = runBlocking {val context: Context = mock()@@ -746,6 +1239,7 @@ class BackupManagerImplTest {},gson = gson,channelDao = mock(),+ seriesDao = mock(),providerSnapshotRepository = snapshotRepositoryFor(backupProvider.copy(id = 7L)))@@ -973,6 +1467,116 @@ class BackupManagerImplTest {assertThat(portable.unresolvedReferences).isEmpty()}+ @Test+ fun `local backup credentials hydrate redacted provider before restore`() {+ val manager = backupManagerForValidation(mock())+ val provider = Provider(+ id = 9L,+ name = "Source",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "http://EXAMPLE.com:80/",+ username = " user ",+ password = "",+ )+ val backup = BackupData(+ providers = listOf(provider),+ providerCredentials = listOf(+ ProviderCredentials(+ serverUrl = "HTTP://example.com",+ username = "user",+ password = "secret",+ )+ )+ )++ val projectionMethod = BackupManagerImpl::class.java+ .getDeclaredMethod("withLegacyProviderProjection", BackupData::class.java)+ .apply { isAccessible = true }+ val hydrated = projectionMethod.invoke(manager, backup) as BackupData++ assertThat(hydrated.providers?.single()?.password).isEqualTo("secret")+ }++ @Test+ fun `portable export ignores the legacy no-active-provider sentinel`() = runBlocking {+ val context: Context = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val categoryRepository: CategoryRepository = mock()+ val provider = Provider(+ id = 2L,+ name = "Source",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "https://example.com",+ username = "user"+ )+ whenever(preferencesRepository.lastActiveProviderId).thenReturn(flowOf(-1L))+ whenever(preferencesRepository.guideDefaultCategoryId).thenReturn(flowOf(null))+ whenever(preferencesRepository.promotedLiveGroupIds).thenReturn(flowOf(emptySet()))+ whenever(preferencesRepository.getHiddenChannelIds(provider.id)).thenReturn(flowOf(emptySet()))+ whenever(preferencesRepository.getHiddenCategoryIds(eq(provider.id), any()))+ .thenReturn(flowOf(emptySet()))+ whenever(categoryRepository.getCategories(provider.id)).thenReturn(flowOf(emptyList()))++ val portable = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ categoryRepository = categoryRepository+ ).buildPortableProviderPreferences(listOf(provider))++ assertThat(portable.activeProvider).isNull()+ assertThat(portable.unresolvedReferences)+ .doesNotContain("Active provider id -1 was not found during export")+ }++ @Test+ fun `portable import matches provider identity across harmless url formatting differences`() = runBlocking {+ val context: Context = mock()+ val contentResolver: ContentResolver = mock()+ val preferencesRepository: PreferencesRepository = mock()+ val providerDao: ProviderDao = mock()+ val categoryRepository: CategoryRepository = mock()+ val reference = BackupProviderReference("http://EXAMPLE.com:80/", " user ")+ val targetProvider = Provider(+ id = 7L,+ name = "Target",+ type = ProviderType.XTREAM_CODES,+ serverUrl = "HTTP://example.COM",+ username = "user"+ )+ whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(listOf(targetProvider.toEntity()))+ whenever(categoryRepository.getCategories(targetProvider.id)).thenReturn(flowOf(emptyList()))+ whenever(contentResolver.openInputStream(Uri.parse("content://portable-normalized-identity")))+ .thenReturn(+ ByteArrayInputStream(+ Gson().toJson(+ BackupData(+ portableProviderPreferences = PortableProviderPreferencesBackup(+ providers = listOf(reference),+ activeProvider = reference,+ unresolvedReferences = listOf(+ "Active provider id -1 was not found during export"+ )+ )+ )+ ).toByteArray()+ )+ )++ val result = backupManagerForValidation(+ context = context,+ preferencesRepository = preferencesRepository,+ providerDao = providerDao,+ categoryRepository = categoryRepository,+ storedProviders = listOf(targetProvider)+ ).importConfig("content://portable-normalized-identity", preferencesOnlyPlan())++ val imported = (result as Result.Success).data+ assertThat(imported.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)+ assertThat(imported.unresolvedReferences).isEmpty()+ verify(preferencesRepository).setLastActiveProviderId(targetProvider.id)+ }+@Testfun `semantic json round trip resolves shifted target ids after room restore`() = runBlocking {val context: Context = mock()@@ -1321,12 +1925,16 @@ class BackupManagerImplTest {}@Test- fun `importConfig retry is a no-op after the same restore checkpoint completed`() = runBlocking {+ fun `importConfig replays a completed restore when the same backup is explicitly imported again`() = runBlocking {val context: Context = mock()val contentResolver: ContentResolver = mock()val providerDao: ProviderDao = mock()val checkpointDao: BackupRestoreCheckpointDao = mock()+ val credentialCrypto: CredentialCrypto = mock()whenever(context.contentResolver).thenReturn(contentResolver)+ whenever(providerDao.getAllSync()).thenReturn(emptyList())+ whenever(providerDao.insert(any())).thenReturn(42L)+ whenever(credentialCrypto.encryptIfNeeded(any())).thenReturn("")whenever(contentResolver.openInputStream(Uri.parse("content://backup-complete-retry"))).thenReturn(ByteArrayInputStream(Gson().toJson(@@ -1356,12 +1964,24 @@ class BackupManagerImplTest {val result = backupManagerForValidation(context = context,providerDao = providerDao,+ credentialCrypto = credentialCrypto,checkpointDao = checkpointDao).importConfig("content://backup-complete-retry")assertThat(result).isInstanceOf(Result.Success::class.java)assertThat((result as Result.Success).data.outcome).isEqualTo(BackupRestoreOutcome.COMPLETE)- verify(providerDao, never()).getAllSync()+ verify(providerDao, org.mockito.kotlin.atLeastOnce()).getAllSync()+ verify(providerDao).insert(any())+ verify(checkpointDao).update(+ any(),+ eq(false),+ eq(false),+ eq(false),+ eq(false),+ eq("RUNNING"),+ anyOrNull(),+ any()+ )Unit}@@ -1402,7 +2022,8 @@ class BackupManagerImplTest {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},gson = gson,- channelDao = mock()+ channelDao = mock(),+ seriesDao = mock())val result = manager.importConfig(@@ -1547,7 +2168,8 @@ class BackupManagerImplTest {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},gson = gson,- channelDao = mock()+ channelDao = mock(),+ seriesDao = mock())val result = manager.importConfig(@@ -1608,7 +2230,8 @@ class BackupManagerImplTest {override suspend fun <T> inTransaction(block: suspend () -> T): T = block()},gson = gson,- channelDao = mock()+ channelDao = mock(),+ seriesDao = mock())val result = manager.importConfig(@@ -2079,6 +2702,7 @@ class BackupManagerImplTest {providerConfigurationCodec = ProviderConfigurationCodec(Gson(), credentialCrypto),backupRestoreCheckpointDao = checkpointDao,channelDao = channelDao,+ seriesDao = mock(),epgSourceDao = epgSourceDao)diff --git a/data/src/test/java/com/streamvault/data/manager/GoogleDriveBackupSyncManagerTest.kt b/data/src/test/java/com/streamvault/data/manager/GoogleDriveBackupSyncManagerTest.ktnew file mode 100644index 00000000..e6164b31--- /dev/null+++ b/data/src/test/java/com/streamvault/data/manager/GoogleDriveBackupSyncManagerTest.kt@@ -0,0 +1,396 @@+package com.streamvault.data.manager++import android.content.Context+import com.google.android.gms.auth.api.signin.GoogleSignInAccount+import com.google.android.gms.auth.api.signin.GoogleSignInClient+import com.google.android.gms.tasks.Tasks+import com.google.common.truth.Truth.assertThat+import com.streamvault.domain.manager.BackupManager+import com.streamvault.domain.manager.DriveAuthState+import com.streamvault.domain.manager.DriveSyncError+import com.streamvault.domain.manager.ProviderCredentials+import com.streamvault.domain.model.Result+import java.io.File+import java.net.URI+import java.nio.file.Files+import java.util.concurrent.CopyOnWriteArrayList+import java.util.concurrent.atomic.AtomicInteger+import kotlinx.coroutines.async+import kotlinx.coroutines.awaitAll+import kotlinx.coroutines.coroutineScope+import kotlinx.coroutines.test.runTest+import okhttp3.mockwebserver.Dispatcher+import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import okhttp3.mockwebserver.RecordedRequest+import android.os.Build+import org.junit.After+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.mockito.kotlin.any+import org.mockito.kotlin.mock+import org.mockito.kotlin.doSuspendableAnswer+import org.mockito.kotlin.verify+import org.mockito.kotlin.whenever+import org.mockito.kotlin.wheneverBlocking+import org.json.JSONArray+import org.json.JSONObject+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++@RunWith(RobolectricTestRunner::class)+@Config(sdk = [Build.VERSION_CODES.O])+class GoogleDriveBackupSyncManagerTest {++ private lateinit var server: MockWebServer+ private lateinit var cacheDir: File+ private val context: Context = mock()+ private val backupManager: BackupManager = mock()++ @Before+ fun setUp() {+ server = MockWebServer()+ server.start()+ cacheDir = Files.createTempDirectory("drive-sync-test").toFile()+ whenever(context.cacheDir).thenReturn(cacheDir)+ wheneverBlocking { backupManager.exportConfig(any()) }.doSuspendableAnswer { invocation ->+ val uri = invocation.getArgument<String>(0)+ File(URI(uri)).writeText("{\"version\":11,\"providers\":[]}")+ Result.Success(Unit)+ }+ }++ @After+ fun tearDown() {+ server.shutdown()+ cacheDir.deleteRecursively()+ }++ @Test+ fun pushBackup_uploadsOneBundleContainingMatchingCredentials() = runTest {+ server.enqueue(MockResponse().setResponseCode(200).setBody("{}"))+ enqueueFileList(emptyList())++ val manager = manager()+ val credentials = listOf(+ ProviderCredentials("https://example.com", "alice", "secret")+ )++ val result = manager.pushBackup(credentials)++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val upload = server.takeRequest()+ assertThat(upload.method).isEqualTo("POST")+ assertThat(upload.path).contains("upload/drive/v3/files")+ val uploadBody = upload.body.readUtf8()+ assertThat(uploadBody).contains("streamvault-drive-bundle-v2")+ assertThat(uploadBody).contains("backupJson")+ assertThat(uploadBody).contains("alice")+ }++ @Test+ fun pullBackup_v2PreservesBackupJsonTextForChecksumVerification() = runTest {+ enqueueFileList(listOf("bundle-id"))+ val backupJson = """{"version":11, "providers":[], "text":"\\u003clegacy\\u003e"}"""+ server.enqueue(+ MockResponse().setResponseCode(200).setBody(+ JSONObject()+ .put("format", "streamvault-drive-bundle-v2")+ .put("backupJson", backupJson)+ .put("credentials", JSONArray())+ .toString()+ )+ )++ val manager = manager()+ val result = manager.pullBackup()++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val artifact = (result as Result.Success).data+ assertThat(File(URI(artifact.localUriString)).readText()).isEqualTo(backupJson)+ File(URI(artifact.localUriString)).delete()+ }++ @Test+ fun pullBackup_extractsBundleCredentialsAndBackupPayload() = runTest {+ enqueueFileList(listOf("bundle-id"))+ server.enqueue(+ MockResponse().setResponseCode(200).setBody(+ """+ {+ "format":"streamvault-drive-bundle-v1",+ "backup":{"version":11,"providers":[]},+ "credentials":[{"serverUrl":"https://example.com","username":"alice","password":"secret"}]+ }+ """.trimIndent()+ )+ )++ val manager = manager()+ val result = manager.pullBackup()++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val artifact = (result as Result.Success).data+ assertThat(artifact.credentials).containsExactly(+ ProviderCredentials("https://example.com", "alice", "secret")+ )+ assertThat(File(URI(artifact.localUriString)).readText()).contains("\"version\":11")+ File(URI(artifact.localUriString)).delete()+ assertThat(manager.syncStatus.value.lastErrorMessage).isNull()+ }++ @Test+ fun malformedBundle_isRejectedAndRecordedAsImportFailure() = runTest {+ enqueueFileList(listOf("bundle-id"))+ server.enqueue(+ MockResponse().setResponseCode(200).setBody(+ """{"format":"unknown","backup":{},"credentials":[]}"""+ )+ )++ val manager = manager()+ val result = manager.pullBackup()++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).isEqualTo(DriveSyncError.IMPORT_FAILED)+ assertThat(manager.syncStatus.value.lastErrorMessage).isEqualTo(DriveSyncError.IMPORT_FAILED)+ }++ @Test+ fun oversizedEmbeddedBackup_isRejectedBeforeStaging() = runTest {+ enqueueFileList(listOf("bundle-id"))+ val oversizedValue = "x".repeat(17 * 1024 * 1024)+ server.enqueue(+ MockResponse().setResponseCode(200).setBody(+ """+ {"format":"streamvault-drive-bundle-v1","backup":{"version":11,"padding":"$oversizedValue"},"credentials":[]}+ """.trimIndent()+ )+ )++ val manager = manager()+ val result = manager.pullBackup()++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).isEqualTo(DriveSyncError.PAYLOAD_TOO_LARGE)+ assertThat(cacheDir.listFiles().orEmpty()).isEmpty()+ }++ @Test+ fun unauthorizedLookup_isClassifiedAsAuthFailureAndRecorded() = runTest {+ server.enqueue(MockResponse().setResponseCode(401).setBody("{}"))++ val manager = manager()+ val result = manager.pullBackup()++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).isEqualTo(DriveSyncError.AUTH_FAILED)+ assertThat(manager.syncStatus.value.lastErrorMessage).isEqualTo(DriveSyncError.AUTH_FAILED)+ }++ @Test+ fun uploadFailure_isClassifiedAsNetworkFailureAndRecorded() = runTest {+ server.enqueue(MockResponse().setResponseCode(500).setBody("{}"))++ val driveManager = manager()+ val result = driveManager.pushBackup(emptyList())++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).isEqualTo(DriveSyncError.NETWORK)+ assertThat(driveManager.syncStatus.value.lastErrorMessage).isEqualTo(DriveSyncError.NETWORK)+ }++ @Test+ fun downloadFailure_isClassifiedAsNetworkFailureAndRecorded() = runTest {+ enqueueFileList(listOf("bundle-id"))+ server.enqueue(MockResponse().setResponseCode(503).setBody("{}"))++ val driveManager = manager()+ val result = driveManager.pullBackup()++ assertThat(result).isInstanceOf(Result.Error::class.java)+ assertThat((result as Result.Error).message).isEqualTo(DriveSyncError.NETWORK)+ assertThat(driveManager.syncStatus.value.lastErrorMessage).isEqualTo(DriveSyncError.NETWORK)+ }++ @Test+ fun signOut_revokesAccessBeforeClearingLocalSession() = runTest {+ val client = mock<GoogleSignInClient>()+ val account = mock<GoogleSignInAccount>()+ whenever(client.revokeAccess()).thenReturn(Tasks.forResult(null))+ whenever(client.signOut()).thenReturn(Tasks.forResult(null))++ val driveManager = GoogleDriveBackupSyncManager(+ context = context,+ backupManager = backupManager,+ httpClient = okhttp3.OkHttpClient(),+ driveApiBaseUrl = server.url("/").toString(),+ fixedAccessToken = "test-token",+ authClientFactory = { client },+ cachedAccountProvider = { account },+ )++ val result = driveManager.signOut()++ assertThat(result).isInstanceOf(Result.Success::class.java)+ verify(client).revokeAccess()+ verify(client).signOut()+ assertThat(driveManager.authState.value).isEqualTo(DriveAuthState.SignedOut)+ }++ @Test+ fun concurrentPushes_areSerializedToOneCreateAndOneUpdate() = runTest {+ val uploadCount = AtomicInteger(0)+ val uploadMethods = CopyOnWriteArrayList<String>()+ server.dispatcher = object : Dispatcher() {+ override fun dispatch(request: RecordedRequest): MockResponse {+ return when {+ request.method == "GET" && request.path.orEmpty().startsWith("/drive/v3/files") -> {+ MockResponse()+ .setResponseCode(200)+ .setBody("{\"files\":[]}")+ }+ request.method == "POST" -> {+ uploadMethods += request.method.orEmpty()+ uploadCount.incrementAndGet()+ MockResponse().setResponseCode(200).setBody("{}")+ }+ else -> MockResponse().setResponseCode(404)+ }+ }+ }++ val driveManager = manager()+ val results = coroutineScope {+ listOf(+ async { driveManager.pushBackup(emptyList()) },+ async { driveManager.pushBackup(emptyList()) },+ ).awaitAll()+ }++ results.forEach { result ->+ assertThat(result).isInstanceOf(Result.Success::class.java)+ }+ assertThat(uploadCount.get()).isEqualTo(2)+ assertThat(uploadMethods).containsExactly("POST", "POST")+ }++ @Test+ fun pushBackup_retainsAtMostTenTimestampedSnapshots() = runTest {+ val deletedPaths = CopyOnWriteArrayList<String>()+ val existingFiles = (0..10).joinToString(",") { index ->+ val minute = index.toString().padStart(2, '0')+ "{\"id\":\"id-$index\",\"name\":\"streamvault_backup_bundle_existing_$index.json\",\"modifiedTime\":\"2026-08-14T10:$minute:00.000Z\",\"size\":\"123\"}"+ }+ server.dispatcher = object : Dispatcher() {+ override fun dispatch(request: RecordedRequest): MockResponse = when {+ request.method == "POST" -> MockResponse().setResponseCode(200).setBody("{}")+ request.method == "GET" -> MockResponse().setResponseCode(200).setBody("{\"files\":[$existingFiles]}")+ request.method == "DELETE" -> {+ deletedPaths += request.path.orEmpty()+ MockResponse().setResponseCode(204)+ }+ else -> MockResponse().setResponseCode(404)+ }+ }++ val result = manager().pushBackup(emptyList())++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(deletedPaths).containsExactly("/drive/v3/files/id-0")+ }++ @Test+ fun listBackups_returnsSnapshotsNewestFirst() = runTest {+ server.enqueue(+ MockResponse().setResponseCode(200).setBody(+ """+ {"files":[+ {"id":"older","name":"streamvault_backup_bundle_older.json","modifiedTime":"2026-08-13T10:00:00.000Z","size":"200"},+ {"id":"newer","name":"streamvault_backup_bundle_newer.json","modifiedTime":"2026-08-14T10:00:00.000Z","size":"300"}+ ]}+ """.trimIndent(),+ ),+ )++ val result = manager().listBackups()++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val snapshots = (result as Result.Success).data+ assertThat(snapshots.map { it.id }).containsExactly("newer", "older").inOrder()+ assertThat(snapshots.first().sizeBytes).isEqualTo(300L)+ }++ @Test+ fun pullBackup_downloadsTheExplicitlySelectedSnapshot() = runTest {+ enqueueFileList(listOf("newer", "older"))+ server.enqueue(+ MockResponse().setResponseCode(200).setBody(+ """{"format":"streamvault-drive-bundle-v2","backupJson":"{\"version\":11,\"providers\":[]}","credentials":[]}""",+ ),+ )++ val result = manager().pullBackup("older")++ assertThat(result).isInstanceOf(Result.Success::class.java)+ val listRequest = server.takeRequest()+ val downloadRequest = server.takeRequest()+ assertThat(listRequest.method).isEqualTo("GET")+ assertThat(downloadRequest.path).contains("/drive/v3/files/older")+ File(URI((result as Result.Success).data.localUriString)).delete()+ }++ @Test+ fun deleteBackup_deletesTheSelectedSnapshot() = runTest {+ enqueueFileList(listOf("newer", "older"))+ server.enqueue(MockResponse().setResponseCode(204))++ val result = manager().deleteBackup("older")++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(server.takeRequest().method).isEqualTo("GET")+ val deleteRequest = server.takeRequest()+ assertThat(deleteRequest.method).isEqualTo("DELETE")+ assertThat(deleteRequest.path).contains("/drive/v3/files/older")+ }++ @Test+ fun deleteBackup_removesLegacyCredentialsCompanionToo() = runTest {+ server.enqueue(+ MockResponse().setResponseCode(200).setBody(+ """{"files":[{"id":"legacy","name":"streamvault_backup.json","modifiedTime":"2026-08-14T10:00:00.000Z","size":"123"}]}""",+ ),+ )+ server.enqueue(MockResponse().setResponseCode(204))+ server.enqueue(+ MockResponse().setResponseCode(200).setBody("{\"files\":[{\"id\":\"credentials\"}]}")+ )+ server.enqueue(MockResponse().setResponseCode(204))++ val result = manager().deleteBackup("legacy")++ assertThat(result).isInstanceOf(Result.Success::class.java)+ assertThat(server.takeRequest().method).isEqualTo("GET")+ assertThat(server.takeRequest().method).isEqualTo("DELETE")+ assertThat(server.takeRequest().path).contains("name%3D%27streamvault_credentials.json%27")+ assertThat(server.takeRequest().method).isEqualTo("DELETE")+ }++ private fun manager(): GoogleDriveBackupSyncManager = GoogleDriveBackupSyncManager(+ context = context,+ backupManager = backupManager,+ httpClient = okhttp3.OkHttpClient(),+ driveApiBaseUrl = server.url("/").toString(),+ fixedAccessToken = "test-token",+ )++ private fun enqueueFileList(ids: List<String>) {+ val files = ids.mapIndexed { index, id ->+ "{\"id\":\"$id\",\"name\":\"streamvault_backup_bundle_20260814_100000_00$index.json\",\"modifiedTime\":\"2026-08-14T10:00:0$index.000Z\",\"size\":\"123\"}"+ }.joinToString(",")+ server.enqueue(+ MockResponse().setResponseCode(200).setBody("{\"files\":[$files]}")+ )+ }+}diff --git a/docs/BACKUP_REVIEW.md b/docs/BACKUP_REVIEW.mdnew file mode 100644index 00000000..3ee0c64e--- /dev/null+++ b/docs/BACKUP_REVIEW.md@@ -0,0 +1,81 @@+# Backup and Restore Review++Reviewed: 2026-08-14++This is the living review of the normal file-backup flow and the Google Drive flow. A status is marked resolved only when the implementation and focused regression coverage support it.++## Current status++- **Resolved:** current `Replace Existing` restore replaces affected provider/type scopes, rebuilds group memberships, and previews conflicts using provider and stable content identity.+- **Resolved:** pending Drive credentials are isolated to the matching restore and cleared on unrelated imports, dismissals, sign-out, pull failures, and completed restores.+- **Resolved:** normal exports, Drive downloads, and external import staging enforce bounded I/O with cleanup of rejected partial files.+- **Resolved:** Drive lookup, upload, and download failures classify authorization versus network errors and persist the result in `syncStatus`.+- **Resolved:** Drive sign-out attempts access revocation before clearing the local session and has direct unit coverage.+- **Resolved:** Drive transport operations are serialized to prevent concurrent lookup-then-upload races and duplicate backup files.+- **Resolved:** new Drive bundles preserve the exact exported backup JSON for checksum verification; pulls accept the new v2 bundle, existing v1 bundles, and legacy standalone files.+- **Resolved:** Google Drive retains a bounded history of timestamped v2 bundles, lists snapshots newest-first, and lets the user choose which snapshot enters the existing preview/import flow. The previous fixed-name v2 bundle and legacy standalone files remain readable.+- **Resolved:** Android TV Export Data and Restore Data no longer launch a system document picker; they use the app-managed local path directly. Export publishes to `Downloads/StreamVault` when available, and common TV file-manager MIME types are accepted when opening backups.+- **Resolved:** local backup management lists only files StreamVault created or successfully registered after a SAF export, supports app-managed Downloads, app-private, registered SAF, and Fire TV USB locations, and requires confirmation before deletion. Arbitrary JSON files selected from elsewhere are intentionally left to the user's file manager.+- **Resolved:** Google Drive backup management lists the available snapshots, requires confirmation, validates the selected Drive file before deleting it, refreshes the list afterward, and removes the legacy standalone credentials companion when deleting a legacy standalone backup.+- **Resolved:** release-built backup DTOs now have stable wire field names; imports also accept the obfuscated `a`/`b`/`c` aliases produced by earlier releases, and SHA-256 verification uses the exact exported bytes to avoid false checksum failures.+- **Resolved:** completed restore checkpoints are reusable. A new explicit import reopens the checkpoint and reapplies the selected Keep Existing or Replace Existing behavior, so deleting a provider and importing the same local or Drive backup works again.+- **Still open:** legacy backups containing only local Room IDs cannot be made fully portable because the missing stable metadata was never exported.+- **Partially addressed:** legacy standalone Drive files remain a compatibility fallback whose backup/credentials generation pairing cannot be proven; new v2 bundles are paired.+- **Open:** real Google Play Services integration testing, preference-scope decisions, atomic normal SAF export semantics, and the cleartext-credentials threat-model decision.++## Supported flows++### Normal backup++The normal export contains provider snapshots, selected preferences, favorites/groups, playback history, split-screen presets, protected categories, scheduled recordings, EPG sources, and portable provider-scoped references. It is checksummed and bounded before import. On television devices, Export Data writes through the app-managed local path without invoking a document picker; it uses the public `Downloads/StreamVault` folder when available, and Restore lists visible local JSON backups inside StreamVault. The release DTO wire names are pinned so R8 obfuscation cannot change the backup schema.++Restore uses the existing inspect/preview/import flow with selectable sections and conflict strategy. New local backups include a matching provider-credentials snapshot so a restored provider can sync immediately. Older backups without that field still restore providers without passwords and require the user to re-enter them.++### Google Drive backup++New pushes create timestamped v2 bundles such as `streamvault_backup_bundle_20260814_120000_123_a1b2c3d4.json`. Each contains the exact backup JSON text and matching provider-credentials snapshot, and uploads it to the private Drive `appDataFolder`. The app keeps the ten newest timestamped bundles, lists them newest-first, and lets the user select one before the existing preview/import flow. The original fixed-name v2 bundle, existing v1 bundles, and legacy standalone backup files remain readable for migration.++Google Drive is optional; local backup does not require a Google account or Google Drive.++### Backup management and deletion++Settings provides separate management actions for local and Google Drive backups.+Local management shows only app-owned exports: files in the app-managed+`Downloads/StreamVault` folder, the app-private backup directory, registered+SAF export destinations, and the supported Fire TV USB backup directory. Each+delete requires confirmation. Files that the user merely picked for import, or+files created outside StreamVault, are not offered for deletion.++Drive management lists the same snapshots available to restore. Deletion is+performed by the Drive file ID after the manager revalidates that the ID is+still one of StreamVault's backup files. Deleting a legacy standalone backup+also removes its legacy `streamvault_credentials.json` companion when present;+new v2 bundles already contain their matching credentials in the same artifact.++## Remaining limitations++- The backup is currently a selected-settings backup, not a complete export of every preference.+- Legacy ID-only favorites/history remain compatibility-limited across devices with different catalog IDs.+- Legacy Drive sibling files may represent different generations.+- Real Google Play Services sign-in/revocation still needs device/account validation.+- New local and Drive backup artifacts contain cleartext provider credentials so they can restore and sync across devices. This requires an explicit threat-model decision before release.+- Normal SAF destinations still write directly rather than using a provider-specific atomic rename strategy.++## Verification performed++Focused suites passed:++```text+./gradlew.bat :data:testDebugUnitTest --tests com.streamvault.data.manager.BackupManagerImplTest --tests com.streamvault.data.manager.GoogleDriveBackupSyncManagerTest --no-daemon+./gradlew.bat :app:testDebugUnitTest --tests com.streamvault.app.ui.screens.settings.SettingsBackupActionsTest --tests com.streamvault.app.ui.screens.settings.SettingsDriveBackupActionsTest --tests com.streamvault.app.ui.screens.provider.ProviderSetupViewModelTest --tests com.streamvault.app.backup.BackupFileBridgeTest --no-daemon+```++The Drive tests cover v2 exact-text preservation, v1 bundle compatibility, malformed and oversized payloads, snapshot listing and explicit selection, upload/download failures, revoke-before-clear behavior, and concurrent pushes. The app tests cover settings state transitions, multi-snapshot selection, provider onboarding, bounded external-import staging, and compatibility with the pre-fix obfuscated backup fields. On the connected Android TV emulator, the corrected release APK opened the existing 2,309-byte backup in the import preview without a checksum error.++## Real-device test checklist++1. Export locally on Android TV with and without a system document picker; confirm the file appears under `Downloads/StreamVault` when the picker is absent.+2. Open that JSON from a TV file manager with StreamVault and restore it after deleting the provider.+3. Push to Google Drive, delete the provider, pull the Drive backup, and restore it.+4. Repeat on a fresh install/different catalog and verify favorites/history behavior.+5. Validate Google sign-in, sign-out, revoke, network failure, and retry behavior with a real Google account.diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.mdindex 5d7ca059..8d48086b 100644--- a/docs/CHANGELOG.md+++ b/docs/CHANGELOG.md@@ -6,6 +6,14 @@ All notable product changes are recorded in this document.### Added+- Added picker-free Android TV local backup export and restore, publishing exports to `Downloads/StreamVault` when available and falling back to app-managed storage when a system document picker is unavailable.+- Added provider credential snapshots to new local backup exports so restored providers can sync without manual password re-entry.+- Added local backup management with confirmation-based deletion for StreamVault-created Downloads, app-private, registered SAF, and supported Fire TV USB exports.+- Added timestamped Google Drive backup bundles containing the exact exported JSON and its matching provider credentials, with newest-first snapshot selection, ten-backup retention, and compatibility with legacy Drive backup formats.+- Added Google Drive snapshot management and deletion in Settings, plus multi-snapshot selection in both Settings and provider onboarding before the normal import preview.+- Added portable provider and catalog identities for favorites and playback history, including series and episode relationships, so restores can resolve records after local database IDs change.+- Added Android TV DPAD-aware scrolling, scroll guidance, initial focus, and footer-to-form focus routing for the backup import preview.+- Added the living backup/restore review and expanded Google Drive setup documentation covering supported flows, compatibility, privacy, and remaining limitations.- Added generic Stalker/Ministra compatibility discovery across portal endpoints, authentication modes, and device profiles.- Added Stalker portal transport controls for custom headers, API/player User-Agents, HTTP proxies, request rules, and TLS handling.- Added Stalker catalog readiness tracking, persisted portal capability state, diagnostics, and playback recovery telemetry.@@ -26,6 +34,11 @@ All notable product changes are recorded in this document.### Changed+- Changed local backup naming to include milliseconds and collision handling, and changed successful SAF exports to be tracked as app-managed backups for later cleanup.+- Changed Drive push, pull, listing, and deletion operations to serialize access, classify authorization/network/payload failures, and keep pending credentials tied to the selected backup snapshot.+- Changed backup import/export admission to enforce bounded byte, JSON, and credential limits while removing rejected partial staging files and failed picker-free export targets.+- Changed backup checksum validation to prefer the exact exported JSON bytes while retaining compatibility with legacy parsed-object checksums.+- Changed backup restore conflict detection and replacement scopes to use provider identity, stable content identity, and group names instead of relying only on local Room IDs.- Improved Stalker bulk live synchronization to tolerate slow large catalogs, detect stalled transfers, retry transient failures, and fall back to category loading when needed.- Improved Stalker playback resolution with content capability detection and direct-media fallback for portals that return non-standard playback responses.- Improved provider ingestion with bounded M3U, XMLTV, and Jellyfin processing that preserves the last committed catalog when a refresh fails or exceeds limits.@@ -40,6 +53,15 @@ All notable product changes are recorded in this document.### Fixed+- Fixed checksum-mismatch failures in release-built and Google Drive-round-tripped backups by pinning serialized backup DTO fields, accepting earlier obfuscated field aliases, and preserving the original exported JSON text.+- Fixed repeated imports of the same backup after a provider or restored data was deleted by reopening completed restore checkpoints and applying the selected conflict strategy again.+- Fixed portable favorites, groups, and playback-history restoration across changed provider/catalog IDs, including unresolved-reference reporting, provider resynchronization, and safe replacement of affected provider/type scopes.+- Fixed stale Google Drive credentials and snapshot state leaking into normal imports, failed pulls, dismissals, sign-out, and incomplete restores; credentials are now applied only after a complete restore, and sign-out revokes Drive access before clearing the local session.+- Fixed partial restore handling so the selected source and import plan remain available for retry while credentials and completion state are cleared only after a complete restore.+- Fixed Google Drive backup races and mismatched backup/credential generations by bundling the matching snapshots, validating selected file IDs before deletion, and cleaning up legacy credential companions when required.+- Fixed oversized, malformed, and failed backup transfers so they are rejected with classified errors and do not leave partial local, cache, or Drive staging files behind.+- Fixed Android TV backup actions that previously depended on an unavailable document-picker app, and broadened file-manager intent handling for generic JSON MIME types.+- Fixed backup preview focus trapping on Cancel/Import by moving initial focus into the dialog body and routing DPAD Up back to the scrollable form.- Fixed Stalker VOD loading for very large catalogs by paging within safe limits instead of aborting the catalog.- Fixed Stalker poster, backdrop, and channel artwork loading when portals return relative image paths.- Fixed Stalker Series loading for portals that expose series through VOD endpoints, with improved category mapping and fallback behavior.diff --git a/docs/GOOGLE_DRIVE_SETUP.md b/docs/GOOGLE_DRIVE_SETUP.mdindex 15d053e4..d4f2d2a3 100644--- a/docs/GOOGLE_DRIVE_SETUP.md+++ b/docs/GOOGLE_DRIVE_SETUP.md@@ -129,21 +129,45 @@ Notes:## Privacy notes-- The backup payload reuses the existing `BackupManager` JSON v5 export. Provider- passwords are already stripped (`BackupManagerImpl.exportConfig`, see the- `password = ""` line).+- New pushes use timestamped v2 artifacts named like+ `streamvault_backup_bundle_20260814_120000_123_a1b2c3d4.json`. Each contains the+ exact current `BackupManager` JSON export text and the matching+ provider-credentials snapshot. The app keeps the ten newest timestamped+ bundles and lets the user choose a snapshot before preview/import. Pull also+ accepts the original fixed-name v2 bundle, existing v1 bundles, and older+ standalone backup/credentials files as read-only migration fallbacks.+ Preserving the exported text keeps checksum verification compatible with+ backups produced by older release builds. New local and Drive exports carry+ the matching credentials field so a restored provider can sync immediately;+ older backups without that field still require password re-entry.- Auth tokens fetched via `GoogleAuthUtil.getToken` are never logged.- The scope `drive.appdata` cannot read files outside the app's private folder.+## Managing saved Drive backups++Open **Settings → Backup & Restore → Manage Drive backups** to see the saved+snapshots in newest-first order. The app asks for confirmation before deleting+one. It validates the selected snapshot against the current `appDataFolder`+listing, then refreshes the list after deletion. This prevents a stale screen+from deleting an unrelated Drive file.++For older installations that have a legacy standalone+`streamvault_backup.json`, deleting that backup also attempts to remove its+legacy `streamvault_credentials.json` companion. Current timestamped v2 bundles+are self-contained, so only the selected bundle is deleted.+## Credentials storage (fork extension, M3)-`drive-backup.json` carries the configuration *minus* passwords. The fork-ships a **second sibling file** in the same `appDataFolder`:+Each timestamped `streamvault_backup_bundle_*.json` carries the configuration plus+its matching credentials snapshot in one versioned artifact. The current bundle+stores the backup JSON text unchanged so the main backup checksum remains+verifiable after Drive round-tripping. Older installations may still+have a **second sibling file** in the same `appDataFolder`:- **`streamvault_credentials.json`** — `[{serverUrl, username, password}]`,cleartext.-Why cleartext on Drive:+Why cleartext in the bundle on Drive:- The file is invisible to the OS and to the standard Drive UI (the`drive.appdata` scope is the only path that can read it).@@ -158,16 +182,16 @@ Why cleartext on Drive:model above.The local DB still stores credentials encrypted via-`AndroidKeystoreCredentialCrypto`. Cleartext only exists inside the-Drive `appDataFolder` and inside the in-memory pull result up to the-moment of import confirm.--Matching at pull time is by `(serverUrl, username)` so the provider-ids reshuffled by the SAF import do not break the restore. Providers-present locally but absent from the credentials file are left-untouched.--Pre-M3 backups (no `streamvault_credentials.json` in `appDataFolder`)-are handled gracefully: `pullCredentials` returns an empty list and-the import path falls back to the master behavior (providers-restored without passwords, user must re-enter them manually).+`AndroidKeystoreCredentialCrypto`. Cleartext also exists in new local backup+files and in the Drive `appDataFolder`; during import it is applied to the+restored provider and then kept only in the encrypted local DB.++Matching is by `(serverUrl, username)` so provider IDs reshuffled by the SAF+import do not break the restore. Providers present locally but absent from a+credential snapshot are left untouched.++Pre-bundle backups (no v2 bundle in `appDataFolder`) are handled gracefully: the+pull path lists and falls back to the legacy standalone backup file;+`pullCredentials` returns an empty list when no legacy credentials file exists, and+the import path restores providers without passwords so the user can re-enter them+manually.diff --git a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.ktindex fdaab616..36a301a2 100644--- a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt@@ -20,6 +20,8 @@ data class BackupData(val providers: List<Provider>? = null,/** v11 authoritative provider payload; v0-10 continue to use [providers]. */val providerSnapshots: List<ProviderBackupSnapshot>? = null,+ /** Credentials paired with provider snapshots so local restores can sync immediately. */+ val providerCredentials: List<ProviderCredentials>? = null,val favorites: List<com.streamvault.domain.model.Favorite>? = null,val virtualGroups: List<com.streamvault.domain.model.VirtualGroup>? = null,val playbackHistory: List<PlaybackHistory>? = null,diff --git a/domain/src/main/java/com/streamvault/domain/manager/DriveBackupSyncManager.kt b/domain/src/main/java/com/streamvault/domain/manager/DriveBackupSyncManager.ktindex 0ef8e949..55d8eb9e 100644--- a/domain/src/main/java/com/streamvault/domain/manager/DriveBackupSyncManager.kt+++ b/domain/src/main/java/com/streamvault/domain/manager/DriveBackupSyncManager.kt@@ -43,27 +43,37 @@ interface DriveBackupSyncManager {suspend fun signOut(): Result<Unit>/**- * Exports the current configuration to a temporary local file, uploads it- * to Drive `appDataFolder` (overwriting the previous backup if any).+ * Exports the current configuration and its matching credentials snapshot+ * into one versioned Drive artifact. Keeping both payloads in one file+ * prevents a backup and credentials upload from representing different+ * local states.*/- suspend fun pushBackup(): Result<DriveSyncStatus>+ suspend fun pushBackup(+ credentials: List<ProviderCredentials> = emptyList(),+ ): Result<DriveSyncStatus>++ /** Lists available Drive snapshots, newest first, for user selection. */+ suspend fun listBackups(): Result<List<DriveBackupSnapshot>>++ /** Deletes one backup snapshot after the caller has confirmed the action. */+ suspend fun deleteBackup(snapshotId: String): Result<Unit>/**- * Downloads the latest backup from Drive `appDataFolder` to a temporary+ * Downloads a selected backup from Drive `appDataFolder` to a temporary* local file, then hands the URI back to the caller — typically wired into* the existing [BackupManager.inspectBackup] flow so the preview + conflict* resolution UI is reused unchanged.*+ * If [snapshotId] is omitted, the newest available snapshot is selected.* Returns [Result.Error] with code [DriveSyncError.NO_REMOTE_BACKUP] if- * nothing has been pushed yet.+ * nothing has been pushed yet or the requested snapshot no longer exists.*/- suspend fun pullBackup(): Result<DriveBackupArtifact>+ suspend fun pullBackup(snapshotId: String? = null): Result<DriveBackupArtifact>/**- * Uploads the provider credentials list to a private sibling file- * (`streamvault_credentials.json`) in the same Drive `appDataFolder`.- * Companion to [pushBackup] — credentials are stripped from the main- * backup JSON by design, so this restores the round-trip.+ * Legacy compatibility upload for the provider credentials list. New UI+ * pushes pass credentials to [pushBackup] so they are bundled with the+ * matching backup snapshot; this method remains only for older callers.** Pure overwrite (last-write-wins). Matching at pull time uses* `(serverUrl, username)` so provider id reshuffling on import does@@ -72,18 +82,18 @@ interface DriveBackupSyncManager {suspend fun pushCredentials(credentials: List<ProviderCredentials>): Result<Unit>/**- * Downloads `streamvault_credentials.json` from Drive `appDataFolder`.- * Returns an empty list if the file is absent (graceful backwards- * compatibility with backups produced before M3).+ * Legacy compatibility download for `streamvault_credentials.json` from+ * Drive `appDataFolder`. New bundle pulls expose credentials through+ * [DriveBackupArtifact.credentials]. Returns an empty list if the legacy+ * file is absent.*/suspend fun pullCredentials(): Result<List<ProviderCredentials>>}/*** Cleartext credentials for a single provider, transported alongside the main- * backup JSON. Storage relies on the `drive.appdata` scope + Google account- * ACL for confidentiality — the file is invisible to the OS and purged on- * uninstall. Matching on pull uses `(serverUrl, username)`.+ * backup JSON. Drive storage relies on the `drive.appdata` scope + Google+ * account ACL for confidentiality. Matching uses `(serverUrl, username)`.*/data class ProviderCredentials(val serverUrl: String,@@ -115,11 +125,22 @@ data class DriveSyncStatus(/** Carries the intent the UI must launch. Kept opaque (`Any?`) for platform independence. */data class DriveSignInRequest(val intent: Any?)+/** A user-visible backup snapshot stored in Drive `appDataFolder`. */+data class DriveBackupSnapshot(+ val id: String,+ val fileName: String,+ val modifiedAtMs: Long? = null,+ val sizeBytes: Long = 0L,+ val isBundle: Boolean = true,+)+/** Local artifact produced by [DriveBackupSyncManager.pullBackup]. */data class DriveBackupArtifact(/** SAF-compatible `file://` URI string the existing [BackupManager.inspectBackup] can read. */val localUriString: String,val sizeBytes: Long,+ /** Credentials embedded in the versioned bundle; null means a legacy backup file. */+ val credentials: List<ProviderCredentials>? = null,)/** Stable identifiers UI may match against to localize messages. */@@ -131,4 +152,5 @@ object DriveSyncError {const val AUTH_FAILED = "drive_auth_failed"const val EXPORT_FAILED = "drive_export_failed"const val IMPORT_FAILED = "drive_import_failed"+ const val PAYLOAD_TOO_LARGE = "drive_payload_too_large"}diff --git a/domain/src/main/java/com/streamvault/domain/model/Favorite.kt b/domain/src/main/java/com/streamvault/domain/model/Favorite.ktindex f065310c..5ccbc5c9 100644--- a/domain/src/main/java/com/streamvault/domain/model/Favorite.kt+++ b/domain/src/main/java/com/streamvault/domain/model/Favorite.kt@@ -5,6 +5,8 @@ data class Favorite(val providerId: Long,val contentId: Long,val contentType: ContentType,+ /** Provider/catalog identity used by backup restore; not persisted in the favorites table. */+ val remoteContentId: String? = null,val position: Int = 0,val groupId: Long? = null,val addedAt: Long = System.currentTimeMillis()diff --git a/domain/src/main/java/com/streamvault/domain/model/PlaybackHistory.kt b/domain/src/main/java/com/streamvault/domain/model/PlaybackHistory.ktindex 685c68ef..25ab7ed0 100644--- a/domain/src/main/java/com/streamvault/domain/model/PlaybackHistory.kt+++ b/domain/src/main/java/com/streamvault/domain/model/PlaybackHistory.kt@@ -5,6 +5,10 @@ data class PlaybackHistory(val contentId: Long,val contentType: ContentType,val providerId: Long,+ /** Provider/catalog identity used by backup restore; not persisted in playback history. */+ val remoteContentId: String? = null,+ /** Stable provider/catalog identity of the parent series for episode history. */+ val remoteSeriesId: String? = null,val title: String,val posterUrl: String? = null,val streamUrl: String,