Skip to content

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

Fix empty TV backup imports

David Nashash8bf8ec52122a
diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
index cfa18247..895e1aa6 100644
--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
@@ -43,6 +43,9 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.withContext
import java.io.OutputStream
+import java.io.File
+import java.io.FileInputStream
+import java.io.FileOutputStream
import java.io.InputStreamReader
import java.io.OutputStreamWriter
import java.io.Writer
@@ -72,7 +75,6 @@ class BackupManagerImpl @Inject constructor(
override suspend fun exportConfig(uriString: String): com.streamvault.domain.model.Result<Unit> = withContext(Dispatchers.IO) {
try {
- val uri = Uri.parse(uriString)
val parentalPinBackup = preferencesRepository.exportParentalPinBackup()
val providerEntities = providerDao.getAll().first()
@@ -202,7 +204,7 @@ class BackupManagerImpl @Inject constructor(
val backupWithChecksum = backupData.copy(checksum = buildSha256Checksum(backupData))
// 2. Serialize and write to URI
- context.contentResolver.openOutputStream(uri)?.use { outputStream ->
+ openBackupOutputStream(uriString)?.use { outputStream ->
OutputStreamWriter(outputStream).use { writer ->
writeBackupDataJson(writer, backupWithChecksum)
}
@@ -221,6 +223,9 @@ class BackupManagerImpl @Inject constructor(
if (backupData.version > CURRENT_BACKUP_VERSION) {
return@withContext Result.error("Unsupported backup version")
}
+ if (backupData.isStructurallyEmpty()) {
+ return@withContext Result.error("Backup file does not contain any importable data")
+ }
if (!verifyChecksum(backupData)) {
return@withContext Result.error("Backup file is corrupted (checksum mismatch)")
}
@@ -334,6 +339,9 @@ class BackupManagerImpl @Inject constructor(
if (backupData.version > CURRENT_BACKUP_VERSION) {
return@withContext com.streamvault.domain.model.Result.error("Unsupported backup version")
}
+ if (backupData.isStructurallyEmpty()) {
+ return@withContext com.streamvault.domain.model.Result.error("Backup file does not contain any importable data")
+ }
if (!verifyChecksum(backupData)) {
return@withContext com.streamvault.domain.model.Result.error("Backup file is corrupted (checksum mismatch)")
}
@@ -490,14 +498,50 @@ class BackupManagerImpl @Inject constructor(
}
private fun readBackupData(uriString: String): BackupData? {
- val uri = Uri.parse(uriString)
- return context.contentResolver.openInputStream(uri)?.use { inputStream ->
+ return openBackupInputStream(uriString)?.use { inputStream ->
InputStreamReader(inputStream).use { reader ->
gson.fromJson(reader, BackupData::class.java)
}
}
}
+ private fun openBackupOutputStream(uriString: String): OutputStream? {
+ return if (uriString.isFileUriString()) {
+ val target = uriString.toFileUriTarget() ?: return null
+ target.parentFile?.mkdirs()
+ FileOutputStream(target, false)
+ } else {
+ val uri = Uri.parse(uriString)
+ context.contentResolver.openOutputStream(uri, "wt")
+ ?: context.contentResolver.openOutputStream(uri)
+ }
+ }
+
+ private fun openBackupInputStream(uriString: String) =
+ if (uriString.isFileUriString()) {
+ uriString.toFileUriTarget()?.takeIf { it.isFile }?.let(::FileInputStream)
+ } else {
+ val uri = Uri.parse(uriString)
+ context.contentResolver.openInputStream(uri)
+ }
+
+ private fun String.isFileUriString(): Boolean =
+ startsWith("$FILE_URI_SCHEME:", ignoreCase = true)
+
+ private fun String.toFileUriTarget(): File? =
+ runCatching { File(java.net.URI(this)) }.getOrNull()
+ ?: Uri.parse(this).path?.let(::File)
+
+ private fun BackupData.isStructurallyEmpty(): Boolean =
+ preferences.isNullOrEmpty() &&
+ providers.isNullOrEmpty() &&
+ favorites.isNullOrEmpty() &&
+ virtualGroups.isNullOrEmpty() &&
+ playbackHistory.isNullOrEmpty() &&
+ multiViewPresets.orEmpty().all { it.value.isEmpty() } &&
+ protectedCategories.isNullOrEmpty() &&
+ scheduledRecordings.isNullOrEmpty()
+
private suspend fun restorePreferences(prefs: Map<String, String>) {
prefs["parentalControlLevel"]?.toIntOrNull()?.let {
preferencesRepository.setParentalControlLevel(it)
@@ -1031,6 +1075,7 @@ private fun Iterable<ProviderEntity>.findMatchingProvider(
private const val SHA256_PREFIX = "sha256:"
private const val CURRENT_BACKUP_VERSION = 7
+private const val FILE_URI_SCHEME = "file"
private val MAP_STRING_STRING_TYPE: Type = object : TypeToken<Map<String, String>>() {}.type
private val PROVIDER_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.Provider>>() {}.type
private val FAVORITE_LIST_TYPE: Type = object : TypeToken<List<com.streamvault.domain.model.Favorite>>() {}.type
diff --git a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
index 3c07bbb4..b83700b9 100644
--- a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
@@ -46,6 +46,45 @@ import org.mockito.kotlin.whenever
class BackupManagerImplTest {
+ @Test
+ fun `inspectBackup rejects structurally empty json instead of previewing version zero`() = runBlocking {
+ val context: Context = mock()
+ val contentResolver: ContentResolver = mock()
+ whenever(context.contentResolver).thenReturn(contentResolver)
+ whenever(contentResolver.openInputStream(Uri.parse("content://empty-backup"))).thenReturn(
+ ByteArrayInputStream("{}".toByteArray())
+ )
+
+ val manager = backupManagerForValidation(context = context)
+
+ val result = manager.inspectBackup("content://empty-backup")
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat((result as Result.Error).message).contains("does not contain any importable data")
+ }
+
+ @Test
+ fun `importConfig rejects structurally empty json before mutating data`() = runBlocking {
+ val context: Context = mock()
+ val contentResolver: ContentResolver = mock()
+ val preferencesRepository: PreferencesRepository = mock()
+ whenever(context.contentResolver).thenReturn(contentResolver)
+ whenever(contentResolver.openInputStream(Uri.parse("content://empty-backup-import"))).thenReturn(
+ ByteArrayInputStream("{}".toByteArray())
+ )
+
+ val manager = backupManagerForValidation(
+ context = context,
+ preferencesRepository = preferencesRepository
+ )
+
+ val result = manager.importConfig("content://empty-backup-import")
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat((result as Result.Error).message).contains("does not contain any importable data")
+ verify(preferencesRepository, never()).setParentalControlLevel(any())
+ }
+
@Test
fun `importConfig replace history only deletes imported providers and resyncs them in transaction`() = runBlocking {
val context: Context = mock()
@@ -700,4 +739,26 @@ class BackupManagerImplTest {
}
}
}
+
+ private fun backupManagerForValidation(
+ context: Context,
+ preferencesRepository: PreferencesRepository = mock(),
+ ): BackupManagerImpl = BackupManagerImpl(
+ context = context,
+ preferencesRepository = preferencesRepository,
+ credentialCrypto = mock<CredentialCrypto>(),
+ providerDao = mock<ProviderDao>(),
+ favoriteDao = mock<FavoriteDao>(),
+ virtualGroupDao = mock<VirtualGroupDao>(),
+ playbackHistoryDao = mock<PlaybackHistoryDao>(),
+ movieDao = mock<MovieDao>(),
+ episodeDao = mock<EpisodeDao>(),
+ categoryRepository = mock<CategoryRepository>(),
+ recordingScheduleDao = mock<RecordingScheduleDao>(),
+ recordingManager = mock<RecordingManager>(),
+ transactionRunner = object : DatabaseTransactionRunner {
+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
+ },
+ gson = Gson()
+ )
}
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 672eb9d6..09c52e22 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -22,6 +22,7 @@ All notable product changes are recorded in this document.
### Fixed
+- Attempted to fix Android TV backup export/import creating empty backup JSON or showing version `0` with `0` items on restore. Needs testing.
- Fixed provider delete confirmation staying open when a follow-up TV integration refresh failed after the provider had already been deleted.
- Fixed the bundled FFmpeg Media3 artifact so MPEG Layer II audio (`audio/mpeg-L2`) maps to the bundled `mp2` decoder and release builds pass FFmpeg verification again.
- Fixed a broken player content-resolution merge that could leave the app failing to compile.