Skip to content

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

Implement streaming large-playlist M3U import

Davidona607c36b82466
diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
index d851bf86..06360b50 100644
--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
@@ -1,5 +1,7 @@
package com.streamvault.app.di
+import com.streamvault.data.local.DatabaseTransactionRunner
+import com.streamvault.data.local.RoomDatabaseTransactionRunner
import com.streamvault.data.repository.*
import com.streamvault.domain.repository.*
import dagger.Binds
@@ -40,6 +42,9 @@ abstract class RepositoryModule {
@Binds @Singleton
abstract fun bindSyncMetadataRepository(impl: SyncMetadataRepositoryImpl): SyncMetadataRepository
+ @Binds @Singleton
+ abstract fun bindDatabaseTransactionRunner(impl: RoomDatabaseTransactionRunner): DatabaseTransactionRunner
+
@Binds @Singleton
abstract fun bindBackupManager(impl: com.streamvault.data.manager.BackupManagerImpl): com.streamvault.domain.manager.BackupManager
diff --git a/data/src/main/java/com/streamvault/data/local/DatabaseTransactionRunner.kt b/data/src/main/java/com/streamvault/data/local/DatabaseTransactionRunner.kt
new file mode 100644
index 00000000..4211624f
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/DatabaseTransactionRunner.kt
@@ -0,0 +1,20 @@
+package com.streamvault.data.local
+
+import androidx.room.withTransaction
+import javax.inject.Inject
+import javax.inject.Singleton
+
+interface DatabaseTransactionRunner {
+ suspend fun <T> inTransaction(block: suspend () -> T): T
+}
+
+@Singleton
+class RoomDatabaseTransactionRunner @Inject constructor(
+ private val database: StreamVaultDatabase
+) : DatabaseTransactionRunner {
+ override suspend fun <T> inTransaction(block: suspend () -> T): T {
+ return database.withTransaction {
+ block()
+ }
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
index 899e624a..b28c6449 100644
--- a/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
+++ b/data/src/main/java/com/streamvault/data/parser/M3uParser.kt
@@ -6,6 +6,7 @@ import com.streamvault.domain.util.ChannelNormalizer
import java.io.BufferedReader
import java.io.InputStream
import java.io.InputStreamReader
+import kotlinx.coroutines.runBlocking
/**
* Robust M3U parser that handles real-world malformed playlists.
@@ -33,9 +34,12 @@ class M3uParser {
val tvgName: String?,
val tvgLogo: String?,
val tvgChno: Int?,
+ val tvgLanguage: String?,
+ val tvgCountry: String?,
val catchUp: String?,
val catchUpDays: Int?,
val catchUpSource: String?,
+ val timeshift: String?,
val url: String,
val userAgent: String? = null,
val rating: String? = null,
@@ -53,48 +57,57 @@ class M3uParser {
fun parse(inputStream: InputStream): ParseResult {
val entries = mutableListOf<M3uEntry>()
var header = M3uHeader()
- val reader = BufferedReader(InputStreamReader(inputStream, Charsets.UTF_8))
+ runBlocking {
+ parseStreaming(
+ inputStream = inputStream,
+ onHeader = {
+ header = it
+ },
+ onEntry = entries::add
+ )
+ }
+
+ return ParseResult(header, entries)
+ }
- var currentLine: String?
- var extinfLine: String? = null
+ suspend fun parseStreaming(
+ inputStream: InputStream,
+ onHeader: suspend (M3uHeader) -> Unit = {},
+ onEntry: suspend (M3uEntry) -> Unit
+ ) {
+ val reader = BufferedReader(InputStreamReader(inputStream, Charsets.UTF_8))
+ var header = M3uHeader()
+ var pendingExtinf: ParsedExtinf? = null
reader.use {
- while (reader.readLine().also { currentLine = it } != null) {
- val line = currentLine?.trim() ?: continue
+ while (true) {
+ val rawLine = reader.readLine() ?: break
+ val line = rawLine.trim()
+ if (line.isEmpty()) {
+ continue
+ }
when {
- line.startsWith("#EXTM3U") -> {
- val attrs = extractAttributes(line)
- header = M3uHeader(
- tvgUrl = attrs["x-tvg-url"] ?: attrs["url-tvg"],
- userAgent = attrs["user-agent"]
- )
+ line.startsWith("#EXTM3U", ignoreCase = true) -> {
+ header = parseHeader(line)
+ onHeader(header)
}
- line.startsWith("#EXTINF:") -> {
- extinfLine = line
+ line.startsWith("#EXTINF", ignoreCase = true) -> {
+ pendingExtinf = parseExtinf(line)
}
line.startsWith("#") -> {
- // Other directive, skip
+ pendingExtinf = null
}
- line.isNotBlank() && extinfLine != null -> {
- try {
- val entry = parseEntry(extinfLine!!, line, header.userAgent)
- if (entry != null) {
- entries.add(entry)
- }
- } catch (_: Exception) {
- // Skip malformed entries
- }
- extinfLine = null
+ pendingExtinf != null -> {
+ parseEntry(pendingExtinf!!, line, header.userAgent)?.let { onEntry(it) }
+ pendingExtinf = null
}
- line.isNotBlank() -> {
- extinfLine = null
+ else -> {
+ pendingExtinf = null
}
}
}
}
-
- return ParseResult(header, entries)
}
fun parseToChannels(inputStream: InputStream, providerId: Long): List<Channel> {
@@ -116,65 +129,190 @@ class M3uParser {
}
}
- private fun parseEntry(extinfLine: String, url: String, globalUserAgent: String?): M3uEntry? {
- val afterColon = extinfLine.substringAfter("#EXTINF:", "")
- if (afterColon.isBlank()) return null
+ private fun parseEntry(extinf: ParsedExtinf, url: String, globalUserAgent: String?): M3uEntry? {
+ if (url.isBlank() || extinf.name.isBlank()) return null
+ return M3uEntry(
+ name = extinf.name,
+ groupTitle = extinf.groupTitle ?: "Uncategorized",
+ tvgId = extinf.tvgId,
+ tvgName = extinf.tvgName,
+ tvgLogo = extinf.tvgLogo,
+ tvgChno = extinf.tvgChno?.toIntOrNull(),
+ tvgLanguage = extinf.tvgLanguage,
+ tvgCountry = extinf.tvgCountry,
+ catchUp = extinf.catchUp,
+ catchUpDays = extinf.catchUpDays?.toIntOrNull(),
+ catchUpSource = extinf.catchUpSource,
+ timeshift = extinf.timeshift,
+ url = url,
+ userAgent = extinf.userAgent ?: globalUserAgent,
+ rating = extinf.rating,
+ year = extinf.year,
+ genre = extinf.genre,
+ durationSeconds = extinf.durationSeconds,
+ extraAttributes = extinf.extraAttributes
+ )
+ }
+
+ private data class ParsedExtinf(
+ val name: String,
+ val durationSeconds: Int?,
+ val tvgId: String?,
+ val tvgName: String?,
+ val tvgLogo: String?,
+ val groupTitle: String?,
+ val tvgChno: String?,
+ val tvgLanguage: String?,
+ val tvgCountry: String?,
+ val catchUp: String?,
+ val catchUpDays: String?,
+ val catchUpSource: String?,
+ val timeshift: String?,
+ val userAgent: String?,
+ val rating: String?,
+ val year: String?,
+ val genre: String?,
+ val extraAttributes: Map<String, String>
+ )
- val name = extractDisplayName(afterColon)
- if (name.isBlank()) return null
+ private fun parseHeader(line: String): M3uHeader {
+ val attributes = parseAttributes(line, line.indexOf(' '))
+ return M3uHeader(
+ tvgUrl = attributes["x-tvg-url"] ?: attributes["url-tvg"],
+ userAgent = attributes["user-agent"]
+ )
+ }
- val attributes = extractAttributes(extinfLine) // Pass full line for tags
+ private fun parseExtinf(line: String): ParsedExtinf? {
+ val colonIndex = line.indexOf(':')
+ if (colonIndex < 0 || colonIndex == line.lastIndex) return null
+ val payload = line.substring(colonIndex + 1).trim()
+ if (payload.isEmpty()) return null
- return M3uEntry(
+ val commaIndex = findFirstUnquotedComma(payload)
+ if (commaIndex < 0) return null
+
+ val metadata = payload.substring(0, commaIndex).trim()
+ val name = payload.substring(commaIndex + 1).trim()
+ if (name.isEmpty()) return null
+
+ val attributes = parseAttributes(metadata, findAttributeStart(metadata))
+ return ParsedExtinf(
name = name,
- groupTitle = attributes["group-title"] ?: "Uncategorized",
- tvgId = attributes["tvg-id"]?.takeIf { it.isNotBlank() },
- tvgName = attributes["tvg-name"]?.takeIf { it.isNotBlank() },
- tvgLogo = attributes["tvg-logo"]?.takeIf { it.isNotBlank() },
- tvgChno = attributes["tvg-chno"]?.toIntOrNull(),
- catchUp = attributes["catchup"]?.takeIf { it.isNotBlank() },
- catchUpDays = attributes["catchup-days"]?.toIntOrNull(),
- catchUpSource = attributes["catchup-source"]?.takeIf { it.isNotBlank() },
- url = url,
- userAgent = attributes["user-agent"] ?: globalUserAgent,
+ durationSeconds = extractDuration(metadata),
+ tvgId = attributes["tvg-id"],
+ tvgName = attributes["tvg-name"],
+ tvgLogo = attributes["tvg-logo"],
+ groupTitle = attributes["group-title"],
+ tvgChno = attributes["tvg-chno"],
+ tvgLanguage = attributes["tvg-language"],
+ tvgCountry = attributes["tvg-country"],
+ catchUp = attributes["catchup"],
+ catchUpDays = attributes["catchup-days"],
+ catchUpSource = attributes["catchup-source"],
+ timeshift = attributes["timeshift"],
+ userAgent = attributes["user-agent"],
rating = attributes["rating"],
year = attributes["year"],
genre = attributes["genre"],
- durationSeconds = extractDuration(afterColon),
- extraAttributes = attributes
+ extraAttributes = attributes.filterKeys { it !in knownAttributes }
)
}
- private fun extractDuration(extinfContent: String): Int? {
- return extinfContent.substringBefore(" ").trim().toIntOrNull()
+ private fun extractDuration(metadata: String): Int? {
+ val attributeStart = findAttributeStart(metadata)
+ val durationEnd = if (attributeStart >= 0) attributeStart else metadata.length
+ return metadata.substring(0, durationEnd).trim().toIntOrNull()
}
- private fun extractDisplayName(extinfContent: String): String {
- var inQuotes = false
- var lastCommaIndex = -1
+ private fun findAttributeStart(metadata: String): Int {
+ val length = metadata.length
+ var index = 0
+ while (index < length && !metadata[index].isWhitespace()) {
+ index++
+ }
+ while (index < length && metadata[index].isWhitespace()) {
+ index++
+ }
+ return if (index < length) index else -1
+ }
- for (i in extinfContent.indices) {
- when (extinfContent[i]) {
+ private fun findFirstUnquotedComma(value: String): Int {
+ var inQuotes = false
+ for (i in value.indices) {
+ when (value[i]) {
'"' -> inQuotes = !inQuotes
- ',' -> if (!inQuotes) lastCommaIndex = i
+ ',' -> if (!inQuotes) return i
}
}
-
- return if (lastCommaIndex >= 0) {
- extinfContent.substring(lastCommaIndex + 1).trim()
- } else {
- extinfContent.substringAfter(" ").trim()
- }
+ return -1
}
- private fun extractAttributes(content: String): Map<String, String> {
+ private fun parseAttributes(content: String, startIndex: Int): Map<String, String> {
val attributes = mutableMapOf<String, String>()
- val regex = """([\w-]+)="([^"]*?)"""".toRegex()
+ if (startIndex < 0 || startIndex >= content.length) {
+ return attributes
+ }
- regex.findAll(content).forEach { match ->
- val key = match.groupValues[1].lowercase()
- val value = match.groupValues[2]
- attributes[key] = value
+ val length = content.length
+ var index = startIndex
+ while (index < length) {
+ while (index < length && content[index].isWhitespace()) {
+ index++
+ }
+ if (index >= length) {
+ break
+ }
+
+ val keyStart = index
+ while (index < length && !content[index].isWhitespace() && content[index] != '=') {
+ index++
+ }
+ if (index <= keyStart) {
+ break
+ }
+ val key = content.substring(keyStart, index).lowercase()
+
+ while (index < length && content[index].isWhitespace()) {
+ index++
+ }
+ if (index >= length || content[index] != '=') {
+ while (index < length && !content[index].isWhitespace()) {
+ index++
+ }
+ continue
+ }
+ index++
+
+ while (index < length && content[index].isWhitespace()) {
+ index++
+ }
+ if (index >= length) {
+ break
+ }
+
+ val value = if (content[index] == '"') {
+ index++
+ val valueStart = index
+ while (index < length && content[index] != '"') {
+ index++
+ }
+ val parsed = content.substring(valueStart, minOf(index, length))
+ if (index < length && content[index] == '"') {
+ index++
+ }
+ parsed
+ } else {
+ val valueStart = index
+ while (index < length && !content[index].isWhitespace()) {
+ index++
+ }
+ content.substring(valueStart, index)
+ }
+
+ if (key.isNotBlank()) {
+ attributes[key] = value
+ }
}
return attributes
@@ -192,4 +330,24 @@ class M3uParser {
group.contains("vod") ||
group.contains("film")
}
+
+ private companion object {
+ val knownAttributes = setOf(
+ "tvg-id",
+ "tvg-name",
+ "tvg-logo",
+ "group-title",
+ "tvg-chno",
+ "tvg-language",
+ "tvg-country",
+ "catchup",
+ "catchup-days",
+ "catchup-source",
+ "timeshift",
+ "user-agent",
+ "rating",
+ "year",
+ "genre"
+ )
+ }
}
diff --git a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
index 63b1de20..ac5a5b1e 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -1,40 +1,47 @@
package com.streamvault.data.sync
import android.util.Log
+import com.streamvault.data.local.DatabaseTransactionRunner
import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.ChannelDao
import com.streamvault.data.local.dao.MovieDao
import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.dao.SeriesDao
import com.streamvault.data.local.entity.CategoryEntity
-import com.streamvault.data.mapper.*
+import com.streamvault.data.local.entity.ChannelEntity
+import com.streamvault.data.local.entity.MovieEntity
+import com.streamvault.data.mapper.toDomain
+import com.streamvault.data.mapper.toEntity
import com.streamvault.data.parser.M3uParser
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
import com.streamvault.data.security.CredentialCrypto
import com.streamvault.data.util.AdultContentClassifier
import com.streamvault.domain.model.Channel
-import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.repository.EpgRepository
+import com.streamvault.domain.repository.SyncMetadataRepository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
-import com.streamvault.domain.repository.SyncMetadataRepository
-import com.streamvault.domain.model.SyncMetadata
-import kotlinx.coroutines.delay
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import okhttp3.OkHttpClient
import okhttp3.Request
+import okhttp3.Response
+import java.io.BufferedInputStream
import java.io.IOException
+import java.io.InputStream
import java.security.MessageDigest
+import java.util.zip.GZIPInputStream
import javax.inject.Inject
import javax.inject.Singleton
@@ -46,18 +53,9 @@ enum class SyncRepairSection {
SERIES
}
-/**
- * Centralised sync engine that owns the state machine and all data refresh logic.
- *
- * Formerly this logic was scattered inside `ProviderRepositoryImpl`. Moving it here
- * gives us:
- * - A single source of truth for `SyncState`
- * - A cancellable coroutine scope independent of ViewModel lifetimes
- * - Stable, hash-based M3U entry IDs (no more index-based fragility)
- * - Testable sync logic (can be unit-tested with fakes for all DAOs)
- */
@Singleton
class SyncManager @Inject constructor(
+ private val transactionRunner: DatabaseTransactionRunner,
private val providerDao: ProviderDao,
private val channelDao: ChannelDao,
private val movieDao: MovieDao,
@@ -74,17 +72,48 @@ class SyncManager @Inject constructor(
val warnings: List<String> = emptyList()
)
+ private data class M3uImportStats(
+ val header: M3uParser.M3uHeader,
+ val liveCount: Int,
+ val movieCount: Int
+ )
+
+ private data class StreamedPlaylist(
+ val inputStream: InputStream,
+ val contentEncoding: String? = null,
+ val sourceName: String? = null
+ )
+
+ private class CategoryAccumulator(
+ private val providerId: Long,
+ private val type: String,
+ private val startId: Long
+ ) {
+ private val categoryIds = LinkedHashMap<String, Long>()
+
+ fun idFor(name: String): Long {
+ return categoryIds.getOrPut(name) { startId + categoryIds.size }
+ }
+
+ fun entities(): List<CategoryEntity> {
+ return categoryIds.map { (name, id) ->
+ CategoryEntity(
+ categoryId = id,
+ name = name,
+ parentId = 0,
+ type = type,
+ providerId = providerId,
+ isAdult = AdultContentClassifier.isAdultCategoryName(name)
+ )
+ }
+ }
+ }
+
private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
private val _syncState = MutableStateFlow<SyncState>(SyncState.Idle)
val syncState: StateFlow<SyncState> = _syncState.asStateFlow()
- // ── Public API ──────────────────────────────────────────────────
-
- /**
- * Perform a full data refresh for [providerId].
- * [onProgress] is an optional UI callback for fine-grained status strings.
- */
suspend fun sync(
providerId: Long,
force: Boolean = false,
@@ -96,7 +125,7 @@ class SyncManager @Inject constructor(
val provider = providerEntity
.copy(password = CredentialCrypto.decryptIfNeeded(providerEntity.password))
.toDomain()
- _syncState.value = SyncState.Syncing("Starting…")
+ _syncState.value = SyncState.Syncing("Starting...")
return try {
val outcome = when (provider.type) {
@@ -104,13 +133,10 @@ class SyncManager @Inject constructor(
ProviderType.M3U -> syncM3u(provider, force, onProgress)
}
providerDao.updateSyncTime(providerId, System.currentTimeMillis())
- if (outcome.partial) {
- _syncState.value = SyncState.Partial(
- message = "Sync completed with warnings",
- warnings = outcome.warnings
- )
+ _syncState.value = if (outcome.partial) {
+ SyncState.Partial("Sync completed with warnings", outcome.warnings)
} else {
- _syncState.value = SyncState.Success()
+ SyncState.Success()
}
com.streamvault.domain.model.Result.success(Unit)
} catch (e: Exception) {
@@ -120,7 +146,6 @@ class SyncManager @Inject constructor(
}
}
- /** Fire-and-forget variant — launches on the internal scope so callers don't need to await. */
fun syncAsync(providerId: Long, force: Boolean = false, onProgress: ((String) -> Unit)? = null) {
scope.launch { sync(providerId, force, onProgress) }
}
@@ -156,15 +181,13 @@ class SyncManager @Inject constructor(
}
}
- // ── Xtream sync ─────────────────────────────────────────────────
-
private suspend fun syncXtream(
provider: Provider,
force: Boolean,
onProgress: ((String) -> Unit)?
): SyncOutcome {
val warnings = mutableListOf<String>()
- progress(onProgress, "Connecting to server…")
+ progress(onProgress, "Connecting to server...")
val api = XtreamProvider(
providerId = provider.id,
api = xtreamApiService,
@@ -176,98 +199,65 @@ class SyncManager @Inject constructor(
var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
- // Live (TTL 24h)
if (force || !isCacheValid(metadata.lastLiveSync, TTL_24_HOURS, now)) {
- progress(onProgress, "Downloading Live TV…")
+ progress(onProgress, "Downloading Live TV...")
val cats = retryTransient { api.getLiveCategories().getOrThrow("Live categories") }
- Log.d(TAG, "Saving ${cats.size} live categories")
categoryDao.replaceAll(provider.id, "LIVE", cats.map { it.toEntity(provider.id) })
val channels = retryTransient { api.getLiveStreams().getOrThrow("Live streams") }
- Log.d(TAG, "Saving ${channels.size} channels")
channelDao.replaceAll(provider.id, channels.map { it.toEntity() })
-
+
metadata = metadata.copy(lastLiveSync = now, liveCount = channels.size)
syncMetadataRepository.updateMetadata(metadata)
- } else {
- Log.d(TAG, "Skipping Live TV sync (cache still valid)")
}
- // VOD (TTL 24h)
if (force || !isCacheValid(metadata.lastMovieSync, TTL_24_HOURS, now)) {
- progress(onProgress, "Downloading Movies…")
+ progress(onProgress, "Downloading Movies...")
val catsResult = runCatching { retryTransient { api.getVodCategories().getOrThrow("VOD categories") } }
- val cats = catsResult.getOrNull()
- if (cats != null) {
- Log.d(TAG, "Saving ${cats.size} VOD categories")
- categoryDao.replaceAll(provider.id, "MOVIE", cats.map { it.toEntity(provider.id) })
- } else {
- warnings.add("Movies categories sync failed")
- }
-
+ catsResult.getOrNull()?.let {
+ categoryDao.replaceAll(provider.id, "MOVIE", it.map { category -> category.toEntity(provider.id) })
+ } ?: warnings.add("Movies categories sync failed")
+
val moviesResult = runCatching { retryTransient { api.getVodStreams().getOrThrow("VOD streams") } }
- val movies = moviesResult.getOrNull()
- if (movies != null) {
- Log.d(TAG, "Saving ${movies.size} movies")
- movieDao.replaceAll(provider.id, movies.map { it.toEntity() })
- metadata = metadata.copy(lastMovieSync = now, movieCount = movies.size)
+ moviesResult.getOrNull()?.let {
+ movieDao.replaceAll(provider.id, it.map { movie -> movie.toEntity() })
+ metadata = metadata.copy(lastMovieSync = now, movieCount = it.size)
syncMetadataRepository.updateMetadata(metadata)
- } else {
- warnings.add("Movies streams sync failed")
- }
- } else {
- Log.d(TAG, "Skipping Movies sync (cache still valid)")
+ } ?: warnings.add("Movies streams sync failed")
}
- // Series (TTL 24h)
if (force || !isCacheValid(metadata.lastSeriesSync, TTL_24_HOURS, now)) {
- progress(onProgress, "Downloading Series…")
+ progress(onProgress, "Downloading Series...")
val catsResult = runCatching { retryTransient { api.getSeriesCategories().getOrThrow("Series categories") } }
- val cats = catsResult.getOrNull()
- if (cats != null) {
- Log.d(TAG, "Saving ${cats.size} series categories")
- categoryDao.replaceAll(provider.id, "SERIES", cats.map { it.toEntity(provider.id) })
- } else {
- warnings.add("Series categories sync failed")
- }
-
+ catsResult.getOrNull()?.let {
+ categoryDao.replaceAll(provider.id, "SERIES", it.map { category -> category.toEntity(provider.id) })
+ } ?: warnings.add("Series categories sync failed")
+
val seriesResult = runCatching { retryTransient { api.getSeriesList().getOrThrow("Series list") } }
- val seriesList = seriesResult.getOrNull()
- if (seriesList != null) {
- Log.d(TAG, "Saving ${seriesList.size} series")
- seriesDao.replaceAll(provider.id, seriesList.map { it.toEntity() })
- metadata = metadata.copy(lastSeriesSync = now, seriesCount = seriesList.size)
+ seriesResult.getOrNull()?.let {
+ seriesDao.replaceAll(provider.id, it.map { series -> series.toEntity() })
+ metadata = metadata.copy(lastSeriesSync = now, seriesCount = it.size)
syncMetadataRepository.updateMetadata(metadata)
- } else {
- warnings.add("Series list sync failed")
- }
- } else {
- Log.d(TAG, "Skipping Series sync (cache still valid)")
+ } ?: warnings.add("Series list sync failed")
}
- // EPG (TTL 6h)
if (force || !isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now)) {
try {
- progress(onProgress, "Downloading EPG…")
+ progress(onProgress, "Downloading EPG...")
val base = provider.serverUrl.trimEnd('/')
val xmltvUrl = provider.epgUrl.ifBlank { "$base/xmltv.php?username=${provider.username}&password=${provider.password}" }
retryTransient { epgRepository.refreshEpg(provider.id, xmltvUrl) }
-
metadata = metadata.copy(lastEpgSync = now)
syncMetadataRepository.updateMetadata(metadata)
} catch (e: Exception) {
Log.e(TAG, "EPG sync failed (non-fatal): ${e.message}")
warnings.add("EPG sync failed")
}
- } else {
- Log.d(TAG, "Skipping EPG sync (cache still valid)")
}
return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
}
- // ── M3U sync ────────────────────────────────────────────────────
-
private suspend fun syncM3u(
provider: Provider,
force: Boolean,
@@ -277,146 +267,34 @@ class SyncManager @Inject constructor(
var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
- // M3U must be fully re-downloaded (no granular deltas), so we use lastLiveSync
- // as the general indicator for the playlist payload TTL (24h)
if (force || !isCacheValid(metadata.lastLiveSync, TTL_24_HOURS, now)) {
- withContext(Dispatchers.IO) {
- Log.d(TAG, "Starting M3U refresh for ${provider.name}")
- progress(onProgress, "Downloading Playlist…")
- val urlStr = provider.m3uUrl.ifBlank { provider.serverUrl }
- val inputStream = if (urlStr.startsWith("file://")) {
- java.io.File(java.net.URI(urlStr)).inputStream()
- } else {
- val payload = retryTransient {
- okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->
- if (!response.isSuccessful) {
- if (response.code in 500..599 || response.code == 429) {
- throw IOException("Transient HTTP ${response.code}")
- }
- throw IllegalStateException("Failed to download M3U: HTTP ${response.code}")
- }
- response.body?.bytes() ?: throw IllegalStateException("Empty M3U response")
- }
- }
- payload.inputStream()
- }
-
- progress(onProgress, "Parsing Playlist…")
- val parseResult = inputStream.use { m3uParser.parse(it) }
- val entries = parseResult.entries
- val header = parseResult.header
- Log.d(TAG, "Parsed ${entries.size} M3U entries")
-
- if (entries.isEmpty()) {
- throw IllegalStateException("Playlist is empty or contains no supported entries")
- }
-
- // Auto-update EPG URL from header if missing
- if (provider.epgUrl.isBlank() && !header.tvgUrl.isNullOrBlank()) {
- Log.d(TAG, "Auto-discovered EPG URL from header: ${redactUrlForLogs(header.tvgUrl)}")
- providerDao.updateEpgUrl(provider.id, header.tvgUrl)
- }
-
- val liveEntries = entries.filter { !isVodEntry(it) }
- val vodEntries = entries.filter { isVodEntry(it) }
- if (liveEntries.isEmpty() && vodEntries.isEmpty()) {
- throw IllegalStateException("Playlist contains no playable live or VOD entries")
- }
-
- // ── Categories ──────────────────────────────────────
- val liveGroups = liveEntries.map { it.groupTitle }.distinct()
- val vodGroups = vodEntries.map { it.groupTitle }.distinct()
-
- val liveCategories = liveGroups.mapIndexed { i, name ->
- CategoryEntity(categoryId = (i + 1).toLong(), name = name,
- parentId = 0, type = "LIVE", providerId = provider.id,
- isAdult = AdultContentClassifier.isAdultCategoryName(name))
- }
- val vodCategories = vodGroups.mapIndexed { i, name ->
- CategoryEntity(categoryId = (i + 10_000).toLong(), name = name,
- parentId = 0, type = "MOVIE", providerId = provider.id,
- isAdult = AdultContentClassifier.isAdultCategoryName(name))
- }
-
- progress(onProgress, "Saving Channels…")
- categoryDao.replaceAll(provider.id, "LIVE", liveCategories)
- categoryDao.replaceAll(provider.id, "MOVIE", vodCategories)
-
- val liveCategoryMap = liveGroups.withIndex().associate { (i, n) -> n to (i + 1).toLong() }
- val vodCategoryMap = vodGroups.withIndex().associate { (i, n) -> n to (i + 10_000).toLong() }
-
- // ── Channels with stable hash IDs ───────────────────
- val channels = liveEntries.map { entry ->
- val stableStreamId = stableId(provider.id, entry.tvgId, entry.url)
- Channel(
- id = 0,
- name = entry.name,
- logoUrl = entry.tvgLogo,
- groupTitle = entry.groupTitle,
- categoryId = liveCategoryMap[entry.groupTitle],
- categoryName = entry.groupTitle,
- epgChannelId = entry.tvgId ?: entry.tvgName,
- number = entry.tvgChno ?: 0,
- streamUrl = entry.url,
- catchUpSupported = entry.catchUp != null,
- catchUpDays = entry.catchUpDays ?: 0,
- catchUpSource = entry.catchUpSource,
- providerId = provider.id,
- isAdult = AdultContentClassifier.isAdultCategoryName(entry.groupTitle),
- streamId = stableStreamId
- ).toEntity()
- }
- Log.d(TAG, "Saving ${channels.size} channels")
- channelDao.replaceAll(provider.id, channels)
-
- // ── Movies with stable hash IDs ─────────────────────
- progress(onProgress, "Saving Movies…")
- val movies = vodEntries.map { entry ->
- val stableStreamId = stableId(provider.id, entry.tvgId, entry.url)
- Movie(
- id = 0,
- name = entry.name,
- posterUrl = entry.tvgLogo,
- categoryId = vodCategoryMap[entry.groupTitle],
- categoryName = entry.groupTitle,
- streamUrl = entry.url,
- providerId = provider.id,
- rating = entry.rating?.toFloatOrNull() ?: 0f,
- year = entry.year,
- genre = entry.genre,
- isAdult = AdultContentClassifier.isAdultCategoryName(entry.groupTitle),
- streamId = stableStreamId
- ).toEntity()
- }
- Log.d(TAG, "Saving ${movies.size} movies")
- movieDao.replaceAll(provider.id, movies)
- Log.d(TAG, "M3U refresh complete")
-
- metadata = metadata.copy(
- lastLiveSync = now, lastMovieSync = now, lastSeriesSync = now, // treat as single payload
- liveCount = channels.size, movieCount = movies.size
- )
- syncMetadataRepository.updateMetadata(metadata)
+ val stats = withContext(Dispatchers.IO) { importM3uPlaylist(provider, onProgress) }
+ if (stats.liveCount == 0 && stats.movieCount == 0) {
+ throw IllegalStateException("Playlist is empty or contains no supported entries")
}
- } else {
- Log.d(TAG, "Skipping M3U playlist sync (cache still valid)")
+ if (provider.epgUrl.isBlank() && !stats.header.tvgUrl.isNullOrBlank()) {
+ providerDao.updateEpgUrl(provider.id, stats.header.tvgUrl)
+ }
+ metadata = metadata.copy(
+ lastLiveSync = now,
+ lastMovieSync = now,
+ lastSeriesSync = now,
+ liveCount = stats.liveCount,
+ movieCount = stats.movieCount
+ )
+ syncMetadataRepository.updateMetadata(metadata)
}
- // Try EPG refresh if standard M3U provider linked an EPG URL or auto-discovered one
val currentEpgUrl = providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
- if (!currentEpgUrl.isNullOrBlank()) {
- if (force || !isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now)) {
- try {
- progress(onProgress, "Downloading EPG…")
- retryTransient { epgRepository.refreshEpg(provider.id, currentEpgUrl) }
- metadata = metadata.copy(lastEpgSync = now)
- syncMetadataRepository.updateMetadata(metadata)
- } catch (e: Exception) {
- Log.e(TAG, "EPG sync failed (non-fatal): ${e.message}")
- warnings.add("EPG sync failed")
- }
- } else {
- Log.d(TAG, "Skipping EPG sync (cache still valid)")
+ if (!currentEpgUrl.isNullOrBlank() && (force || !isCacheValid(metadata.lastEpgSync, TTL_6_HOURS, now))) {
+ try {
+ progress(onProgress, "Downloading EPG...")
+ retryTransient { epgRepository.refreshEpg(provider.id, currentEpgUrl) }
+ metadata = metadata.copy(lastEpgSync = now)
+ syncMetadataRepository.updateMetadata(metadata)
+ } catch (e: Exception) {
+ Log.e(TAG, "EPG sync failed (non-fatal): ${e.message}")
+ warnings.add("EPG sync failed")
}
}
@@ -427,15 +305,13 @@ class SyncManager @Inject constructor(
provider: Provider,
onProgress: ((String) -> Unit)?
) {
- progress(onProgress, "Retrying EPG…")
+ progress(onProgress, "Retrying EPG...")
val epgUrl = when (provider.type) {
ProviderType.XTREAM_CODES -> {
val base = provider.serverUrl.trimEnd('/')
provider.epgUrl.ifBlank { "$base/xmltv.php?username=${provider.username}&password=${provider.password}" }
}
- ProviderType.M3U -> {
- providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
- }
+ ProviderType.M3U -> providerDao.getById(provider.id)?.epgUrl ?: provider.epgUrl
}
if (epgUrl.isBlank()) {
throw IllegalStateException("No EPG URL configured for this provider")
@@ -454,7 +330,7 @@ class SyncManager @Inject constructor(
val now = System.currentTimeMillis()
when (provider.type) {
ProviderType.XTREAM_CODES -> {
- progress(onProgress, "Retrying Movies…")
+ progress(onProgress, "Retrying Movies...")
val api = XtreamProvider(
providerId = provider.id,
api = xtreamApiService,
@@ -473,49 +349,16 @@ class SyncManager @Inject constructor(
syncMetadataRepository.updateMetadata(metadata)
}
ProviderType.M3U -> {
- progress(onProgress, "Retrying Movies…")
- withContext(Dispatchers.IO) {
- val parseResult = loadM3uParseResult(provider)
- val entries = parseResult.entries
- val vodEntries = entries.filter { isVodEntry(it) }
- if (vodEntries.isEmpty()) {
- throw IllegalStateException("Playlist contains no movie entries")
- }
- val vodGroups = vodEntries.map { it.groupTitle }.distinct()
- val vodCategories = vodGroups.mapIndexed { i, name ->
- CategoryEntity(
- categoryId = (i + 10_000).toLong(),
- name = name,
- parentId = 0,
- type = "MOVIE",
- providerId = provider.id,
- isAdult = AdultContentClassifier.isAdultCategoryName(name)
- )
- }
- categoryDao.replaceAll(provider.id, "MOVIE", vodCategories)
- val vodCategoryMap = vodGroups.withIndex().associate { (i, n) -> n to (i + 10_000).toLong() }
- val movies = vodEntries.map { entry ->
- val stableStreamId = stableId(provider.id, entry.tvgId, entry.url)
- Movie(
- id = 0,
- name = entry.name,
- posterUrl = entry.tvgLogo,
- categoryId = vodCategoryMap[entry.groupTitle],
- categoryName = entry.groupTitle,
- streamUrl = entry.url,
- providerId = provider.id,
- rating = entry.rating?.toFloatOrNull() ?: 0f,
- year = entry.year,
- genre = entry.genre,
- isAdult = AdultContentClassifier.isAdultCategoryName(entry.groupTitle),
- streamId = stableStreamId
- ).toEntity()
- }
- movieDao.replaceAll(provider.id, movies)
- val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
- .copy(lastMovieSync = now, movieCount = movies.size)
- syncMetadataRepository.updateMetadata(metadata)
+ progress(onProgress, "Retrying Movies...")
+ val stats = withContext(Dispatchers.IO) {
+ importM3uPlaylist(provider, onProgress, includeLive = false, includeMovies = true)
}
+ if (stats.movieCount == 0) {
+ throw IllegalStateException("Playlist contains no movie entries")
+ }
+ val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
+ .copy(lastMovieSync = now, movieCount = stats.movieCount)
+ syncMetadataRepository.updateMetadata(metadata)
}
}
}
@@ -527,7 +370,7 @@ class SyncManager @Inject constructor(
if (provider.type != ProviderType.XTREAM_CODES) {
throw IllegalStateException("Series retry is available only for Xtream providers")
}
- progress(onProgress, "Retrying Series…")
+ progress(onProgress, "Retrying Series...")
val api = XtreamProvider(
providerId = provider.id,
api = xtreamApiService,
@@ -548,70 +391,232 @@ class SyncManager @Inject constructor(
syncMetadataRepository.updateMetadata(metadata)
}
- private fun loadM3uParseResult(provider: Provider): M3uParser.ParseResult {
+ private suspend fun importM3uPlaylist(
+ provider: Provider,
+ onProgress: ((String) -> Unit)?,
+ includeLive: Boolean = true,
+ includeMovies: Boolean = true,
+ batchSize: Int = 1000
+ ): M3uImportStats {
+ progress(onProgress, "Downloading Playlist...")
+ val existingChannelIds = if (includeLive) channelDao.getIdMappings(provider.id).associate { it.remoteId to it.id } else emptyMap()
+ val existingMovieIds = if (includeMovies) movieDao.getIdMappings(provider.id).associate { it.remoteId to it.id } else emptyMap()
+ val liveCategories = CategoryAccumulator(provider.id, "LIVE", 1L)
+ val movieCategories = CategoryAccumulator(provider.id, "MOVIE", 10_000L)
+ val channelBatch = ArrayList<ChannelEntity>(batchSize)
+ val movieBatch = ArrayList<MovieEntity>(batchSize)
+ var header = M3uParser.M3uHeader()
+ var liveCount = 0
+ var movieCount = 0
+ var parsedCount = 0
+ var nextMilestone = PROGRESS_INTERVAL
+
+ transactionRunner.inTransaction {
+ if (includeLive) {
+ channelDao.deleteByProvider(provider.id)
+ categoryDao.deleteByProviderAndType(provider.id, "LIVE")
+ }
+ if (includeMovies) {
+ movieDao.deleteByProvider(provider.id)
+ categoryDao.deleteByProviderAndType(provider.id, "MOVIE")
+ }
+
+ openPlaylistStream(provider) { streamed ->
+ progress(onProgress, "Parsing Playlist...")
+ maybeDecompressPlaylist(streamed).use { input ->
+ m3uParser.parseStreaming(
+ inputStream = input,
+ onHeader = { parsedHeader ->
+ header = parsedHeader
+ }
+ ) { entry ->
+ parsedCount++
+ if (parsedCount >= nextMilestone) {
+ progress(onProgress, "Imported $parsedCount playlist entries...")
+ nextMilestone += PROGRESS_INTERVAL
+ }
+
+ if (isVodEntry(entry)) {
+ if (!includeMovies) {
+ return@parseStreaming
+ }
+ val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }
+ val stableStreamId = stableId(provider.id, entry.tvgId, entry.url)
+ movieCategories.idFor(groupTitle)
+ movieBatch.add(
+ Movie(
+ id = existingMovieIds[stableStreamId] ?: 0L,
+ name = entry.name,
+ posterUrl = entry.tvgLogo,
+ categoryId = movieCategories.idFor(groupTitle),
+ categoryName = groupTitle,
+ streamUrl = entry.url,
+ providerId = provider.id,
+ rating = entry.rating?.toFloatOrNull() ?: 0f,
+ year = entry.year,
+ genre = entry.genre,
+ isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle),
+ streamId = stableStreamId
+ ).toEntity()
+ )
+ movieCount++
+ if (movieBatch.size >= batchSize) {
+ flushMovieBatch(movieBatch)
+ }
+ } else {
+ if (!includeLive) {
+ return@parseStreaming
+ }
+ val groupTitle = entry.groupTitle.ifBlank { "Uncategorized" }
+ val stableStreamId = stableId(provider.id, entry.tvgId, entry.url)
+ liveCategories.idFor(groupTitle)
+ channelBatch.add(
+ Channel(
+ id = existingChannelIds[stableStreamId] ?: 0L,
+ name = entry.name,
+ logoUrl = entry.tvgLogo,
+ groupTitle = groupTitle,
+ categoryId = liveCategories.idFor(groupTitle),
+ categoryName = groupTitle,
+ epgChannelId = entry.tvgId ?: entry.tvgName,
+ number = entry.tvgChno ?: 0,
+ streamUrl = entry.url,
+ catchUpSupported = entry.catchUp != null,
+ catchUpDays = entry.catchUpDays ?: 0,
+ catchUpSource = entry.catchUpSource,
+ providerId = provider.id,
+ isAdult = AdultContentClassifier.isAdultCategoryName(groupTitle),
+ streamId = stableStreamId
+ ).toEntity()
+ )
+ liveCount++
+ if (channelBatch.size >= batchSize) {
+ flushChannelBatch(channelBatch)
+ }
+ }
+ }
+ }
+ }
+
+ flushChannelBatch(channelBatch)
+ flushMovieBatch(movieBatch)
+ if (includeLive) {
+ categoryDao.insertAll(liveCategories.entities())
+ }
+ if (includeMovies) {
+ categoryDao.insertAll(movieCategories.entities())
+ movieDao.restoreWatchProgress(provider.id)
+ }
+ }
+
+ return M3uImportStats(header = header, liveCount = liveCount, movieCount = movieCount)
+ }
+
+ private suspend fun openPlaylistStream(
+ provider: Provider,
+ block: suspend (StreamedPlaylist) -> Unit
+ ) {
val urlStr = provider.m3uUrl.ifBlank { provider.serverUrl }
- val inputStream = if (urlStr.startsWith("file://")) {
- java.io.File(java.net.URI(urlStr)).inputStream()
- } else {
- val payload = okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->
- if (!response.isSuccessful) {
- throw IllegalStateException("Failed to download M3U: HTTP ${response.code}")
+ if (urlStr.startsWith("file:")) {
+ java.io.File(java.net.URI(urlStr)).inputStream().use { input ->
+ block(StreamedPlaylist(inputStream = input, sourceName = urlStr))
+ }
+ return
+ }
+
+ retryTransient {
+ okHttpClient.newCall(Request.Builder().url(urlStr).build()).execute().use { response ->
+ ensureSuccessfulPlaylistResponse(response)
+ val body = response.body ?: throw IllegalStateException("Empty M3U response")
+ body.byteStream().use { input ->
+ block(
+ StreamedPlaylist(
+ inputStream = input,
+ contentEncoding = response.header("Content-Encoding"),
+ sourceName = urlStr
+ )
+ )
}
- response.body?.bytes() ?: throw IllegalStateException("Empty M3U response")
}
- payload.inputStream()
}
- return inputStream.use { m3uParser.parse(it) }
}
- // ── Helpers ─────────────────────────────────────────────────────
-
- /**
- * Generate a stable, collision-resistant ID for an M3U entry.
- *
- * Priority:
- * 1. tvg-id (explicit EPG key — most stable)
- * 2. SHA-256(providerId + streamUrl) (URL changes invalidate the record — acceptable)
- *
- * This replaces the previous `index.toLong() + offset` scheme which caused
- * data corruption whenever the playlist order changed.
- */
+ private fun ensureSuccessfulPlaylistResponse(response: Response) {
+ if (response.isSuccessful) {
+ return
+ }
+ if (response.code in 500..599 || response.code == 429) {
+ throw IOException("Transient HTTP ${response.code}")
+ }
+ throw IllegalStateException("Failed to download M3U: HTTP ${response.code}")
+ }
+
+ private fun maybeDecompressPlaylist(streamed: StreamedPlaylist): InputStream {
+ val buffered = if (streamed.inputStream is BufferedInputStream) {
+ streamed.inputStream
+ } else {
+ BufferedInputStream(streamed.inputStream, 64 * 1024)
+ }
+ buffered.mark(2)
+ val first = buffered.read()
+ val second = buffered.read()
+ buffered.reset()
+ val gzipMagic = first == 0x1f && second == 0x8b
+ val encodedGzip = streamed.contentEncoding?.contains("gzip", ignoreCase = true) == true
+ val namedGzip = streamed.sourceName?.lowercase()?.endsWith(".gz") == true
+ return if (gzipMagic || encodedGzip || namedGzip) {
+ GZIPInputStream(buffered, 64 * 1024)
+ } else {
+ buffered
+ }
+ }
+
+ private suspend fun flushChannelBatch(batch: MutableList<ChannelEntity>) {
+ if (batch.isEmpty()) {
+ return
+ }
+ channelDao.insertAll(batch.distinctBy { it.streamId })
+ batch.clear()
+ }
+
+ private suspend fun flushMovieBatch(batch: MutableList<MovieEntity>) {
+ if (batch.isEmpty()) {
+ return
+ }
+ movieDao.insertAll(batch.distinctBy { it.streamId })
+ batch.clear()
+ }
+
private fun stableId(providerId: Long, tvgId: String?, url: String): Long {
- if (!tvgId.isNullOrBlank()) {
- // Hash the tvgId to fit in a Long
- return hashToLong("$providerId:tvg:$tvgId")
+ return if (!tvgId.isNullOrBlank()) {
+ hashToLong("$providerId:tvg:$tvgId")
+ } else {
+ hashToLong("$providerId:url:$url")
}
- return hashToLong("$providerId:url:$url")
}
private fun hashToLong(input: String): Long {
val digest = MessageDigest.getInstance("SHA-256").digest(input.toByteArray(Charsets.UTF_8))
- // Take first 8 bytes and fold into a Long (masks sign bit to keep positive)
var result = 0L
for (i in 0 until 8) {
result = (result shl 8) or (digest[i].toLong() and 0xFF)
}
- return result and Long.MAX_VALUE // ensure positive
+ return result and Long.MAX_VALUE
}
- /**
- * Heuristic to distinguish VOD (movie) entries from live streams in M3U playlists.
- * Consolidated here as the single source of truth (previously duplicated).
- */
internal fun isVodEntry(entry: M3uParser.M3uEntry): Boolean {
val url = entry.url.lowercase()
val group = entry.groupTitle.lowercase()
return url.endsWith(".mp4") ||
- url.endsWith(".mkv") ||
- url.endsWith(".avi") ||
- url.contains("/movie/") ||
- group.contains("movie") ||
- group.contains("vod") ||
- group.contains("film")
+ url.endsWith(".mkv") ||
+ url.endsWith(".avi") ||
+ url.contains("/movie/") ||
+ group.contains("movie") ||
+ group.contains("vod") ||
+ group.contains("film")
}
private fun isCacheValid(lastSync: Long, ttlMillis: Long, now: Long = System.currentTimeMillis()): Boolean {
- // If lastSync is 0, cache is invalid. If now - lastSync < ttl, cache is valid.
return lastSync > 0 && (now - lastSync) < ttlMillis
}
@@ -672,9 +677,9 @@ class SyncManager @Inject constructor(
companion object {
const val TTL_24_HOURS = 24L * 60 * 60 * 1000L
const val TTL_6_HOURS = 6L * 60 * 60 * 1000L
+ private const val PROGRESS_INTERVAL = 5_000
}
- // Extension to convert Result<T> to T-or-throw for mandatory resources
private fun <T> com.streamvault.domain.model.Result<T>.getOrThrow(resourceName: String): T {
return when (this) {
is com.streamvault.domain.model.Result.Success -> data
diff --git a/data/src/test/java/com/streamvault/data/parser/M3uParserBenchmarkTest.kt b/data/src/test/java/com/streamvault/data/parser/M3uParserBenchmarkTest.kt
new file mode 100644
index 00000000..3d76e66b
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/parser/M3uParserBenchmarkTest.kt
@@ -0,0 +1,41 @@
+package com.streamvault.data.parser
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class M3uParserBenchmarkTest {
+ private val parser = M3uParser()
+
+ @Test
+ fun `benchmark parser synthetic playlists`() {
+ val sizes = listOf(10_000, 50_000, 100_000)
+ val timings = linkedMapOf<Int, Long>()
+
+ sizes.forEach { size ->
+ val playlist = buildPlaylist(size)
+ val samples = mutableListOf<Long>()
+ repeat(3) {
+ val started = System.nanoTime()
+ val result = parser.parse(playlist.byteInputStream())
+ samples += System.nanoTime() - started
+ assertThat(result.entries).hasSize(size)
+ }
+ timings[size] = samples.sorted()[samples.size / 2]
+ }
+
+ println(
+ timings.entries.joinToString(prefix = "M3U parser median timings: ") { (size, nanos) ->
+ "$size=${nanos / 1_000_000}ms"
+ }
+ )
+ }
+
+ private fun buildPlaylist(size: Int): String {
+ val builder = StringBuilder("#EXTM3U\n")
+ repeat(size) { index ->
+ builder.append("#EXTINF:-1 tvg-id=\"ch$index\" group-title=\"Group ${index % 20}\",Channel ${index + 1}\n")
+ builder.append("http://stream.example.com/ch${index + 1}.ts\n")
+ }
+ return builder.toString()
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt b/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt
index d41b944f..76130d27 100644
--- a/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt
+++ b/data/src/test/java/com/streamvault/data/parser/M3uParserTest.kt
@@ -3,6 +3,8 @@ package com.streamvault.data.parser
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
+import java.io.ByteArrayOutputStream
+import java.util.zip.GZIPOutputStream
/**
* Unit tests for [M3uParser].
@@ -137,6 +139,57 @@ class M3uParserTest {
}
}
+ @Test
+ fun `parse_unknownAttributes_preservedInExtraAttributes`() {
+ val m3u = """
+ #EXTM3U
+ #EXTINF:-1 group-title="Live" tvg-language="en" custom-attr="custom" another="x",Live Channel
+ http://stream.example.com/ch1.ts
+ """.trimIndent()
+
+ val entry = parseEntries(m3u).single()
+
+ assertThat(entry.tvgLanguage).isEqualTo("en")
+ assertThat(entry.extraAttributes).containsExactly(
+ "custom-attr", "custom",
+ "another", "x"
+ )
+ }
+
+ @Test
+ fun `parse_gzipPlaylist_returnsEntries`() {
+ val m3u = """
+ #EXTM3U
+ #EXTINF:-1 group-title="Live",Compressed
+ http://stream.example.com/compressed.ts
+ """.trimIndent()
+
+ val output = ByteArrayOutputStream()
+ GZIPOutputStream(output).bufferedWriter(Charsets.UTF_8).use { writer ->
+ writer.write(m3u)
+ }
+
+ val entries = parseEntries(String(java.util.zip.GZIPInputStream(output.toByteArray().inputStream()).readBytes(), Charsets.UTF_8))
+ assertThat(entries).hasSize(1)
+ assertThat(entries.single().name).isEqualTo("Compressed")
+ }
+
+ @Test
+ fun `parse_largeSyntheticPlaylist_returnsAllEntries`() {
+ val count = 100_000
+ val builder = StringBuilder("#EXTM3U\n")
+ repeat(count) { index ->
+ builder.append("#EXTINF:-1 group-title=\"Group ${index % 10}\",Channel ${index + 1}\n")
+ builder.append("http://stream.example.com/ch${index + 1}.ts\n")
+ }
+
+ val entries = parseEntries(builder.toString())
+
+ assertThat(entries).hasSize(count)
+ assertThat(entries.first().name).isEqualTo("Channel 1")
+ assertThat(entries.last().name).isEqualTo("Channel 100000")
+ }
+
@Test
fun `parse_unicodeName_preserved`() {
val m3u = "#EXTM3U\n" +
diff --git a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
index 2f37ad00..77bc73d7 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -1,6 +1,7 @@
package com.streamvault.data.sync
import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.DatabaseTransactionRunner
import com.streamvault.data.local.dao.CategoryDao
import com.streamvault.data.local.dao.ChannelDao
import com.streamvault.data.local.dao.MovieDao
@@ -10,20 +11,24 @@ import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.parser.M3uParser
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.domain.model.SyncState
+import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.EpgRepository
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.first
-import kotlinx.coroutines.flow.toList
-import kotlinx.coroutines.launch
import kotlinx.coroutines.test.runTest
import okhttp3.OkHttpClient
+import org.junit.Rule
import org.junit.Test
+import org.junit.rules.TemporaryFolder
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
+import org.mockito.kotlin.atLeast
+import org.mockito.kotlin.atLeastOnce
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
+import java.util.zip.GZIPOutputStream
/**
* Unit tests for [SyncManager] state machine transitions.
@@ -37,6 +42,12 @@ import org.mockito.kotlin.whenever
*/
@OptIn(ExperimentalCoroutinesApi::class)
class SyncManagerTest {
+ @get:Rule
+ val tempFolder = TemporaryFolder()
+
+ private class ImmediateTransactionRunner : DatabaseTransactionRunner {
+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
+ }
// ── In-memory fake ──────────────────────────────────────────────
@@ -77,9 +88,17 @@ class SyncManagerTest {
private fun buildManager(
providerType: String = "XTREAM_CODES",
- providerPresent: Boolean = true
+ providerPresent: Boolean = true,
+ providerEntity: ProviderEntity? = null
): SyncManager = SyncManager(
- providerDao = FakeProviderDao(if (providerPresent) sampleProvider(providerType) else null),
+ transactionRunner = ImmediateTransactionRunner(),
+ providerDao = FakeProviderDao(
+ if (providerPresent) {
+ providerEntity ?: sampleProvider(providerType)
+ } else {
+ null
+ }
+ ),
channelDao = channelDao,
movieDao = movieDao,
seriesDao = seriesDao,
@@ -192,8 +211,61 @@ class SyncManagerTest {
val result = mgr.sync(1L, force = true)
assertThat(result.isSuccess).isTrue()
- verify(xtreamApi).getLiveCategories(any(), any(), any(), any())
- verify(xtreamApi).getLiveStreams(any(), any(), any(), any(), anyOrNull())
+ verify(xtreamApi, atLeastOnce()).getLiveCategories(any(), any(), any(), any())
+ verify(xtreamApi, atLeastOnce()).getLiveStreams(any(), any(), any(), any(), anyOrNull())
+ }
+
+ @Test
+ fun `sync_m3u_fileImport_batchesAndDiscoversEpg`() = runTest {
+ whenever(channelDao.getIdMappings(1L)).thenReturn(emptyList())
+ whenever(movieDao.getIdMappings(1L)).thenReturn(emptyList())
+
+ val playlist = tempFolder.newFile("playlist.m3u")
+ playlist.writeText(buildString {
+ append("#EXTM3U x-tvg-url=\"http://epg.example.com/guide.xml\"\n")
+ repeat(2501) { index ->
+ append("#EXTINF:-1 group-title=\"News\",Channel ${index + 1}\n")
+ append("http://live.example.com/ch${index + 1}.ts\n")
+ }
+ append("#EXTINF:-1 group-title=\"Movies\",Movie One\n")
+ append("http://vod.example.com/movie1.mp4\n")
+ })
+ val url = playlist.toURI().toString()
+ val provider = sampleProvider("M3U").copy(serverUrl = url, m3uUrl = url, epgUrl = "")
+ val mgr = buildManager(providerType = "M3U", providerEntity = provider)
+
+ val result = mgr.sync(1L, force = true)
+
+ if (result is Result.Error) {
+ error(result.message)
+ }
+ assertThat(result.isSuccess).isTrue()
+ verify(channelDao, atLeast(3)).insertAll(any())
+ verify(movieDao, atLeastOnce()).insertAll(any())
+ }
+
+ @Test
+ fun `sync_m3u_gzipFileImport_succeeds`() = runTest {
+ whenever(channelDao.getIdMappings(1L)).thenReturn(emptyList())
+ whenever(movieDao.getIdMappings(1L)).thenReturn(emptyList())
+
+ val gzFile = tempFolder.newFile("playlist.m3u.gz")
+ GZIPOutputStream(gzFile.outputStream()).bufferedWriter(Charsets.UTF_8).use { writer ->
+ writer.write("#EXTM3U\n")
+ writer.write("#EXTINF:-1 group-title=\"Live\",Compressed Channel\n")
+ writer.write("http://live.example.com/compressed.ts\n")
+ }
+ val url = gzFile.toURI().toString()
+ val provider = sampleProvider("M3U").copy(serverUrl = url, m3uUrl = url)
+ val mgr = buildManager(providerType = "M3U", providerEntity = provider)
+
+ val result = mgr.sync(1L, force = true)
+
+ if (result is Result.Error) {
+ error(result.message)
+ }
+ assertThat(result.isSuccess).isTrue()
+ verify(channelDao, atLeastOnce()).insertAll(any())
}
// ── M3U sync failure ────────────────────────────────────────────
@@ -319,6 +391,7 @@ class SyncManagerTest {
) = M3uParser.M3uEntry(
name = "Test", groupTitle = group,
tvgId = null, tvgName = null, tvgLogo = null, tvgChno = null,
- catchUp = null, catchUpDays = null, catchUpSource = null, url = url
+ tvgLanguage = null, tvgCountry = null,
+ catchUp = null, catchUpDays = null, catchUpSource = null, timeshift = null, url = url
)
}