Skip to content

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

stalker overhaul

David Nashash0f3282644fcf
diff --git a/AGENTS.md b/AGENTS.md
index 37db04e4..7c51642b 100644
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -8,39 +8,6 @@ Rules:
- For cross-module "how does X relate to Y" questions, prefer `graphify query "<question>"`, `graphify path "<A>" "<B>"`, or `graphify explain "<concept>"` over grep — these traverse the graph's EXTRACTED + INFERRED edges instead of scanning files
- After modifying code files in this session, run `graphify update .` to keep the graph current (AST-only, no API cost)
-## StreamVault emulator orientation
-
-When starting the emulator with StreamVault, always ensure the visible device frame
-and the app orientation are aligned before playback debugging. The known-good
-orientation from the debugging session is the emulator in landscape with the app
-upright at Android `ROTATION_270`.
-
-Use:
-
-```bash
-adb shell cmd window set-ignore-orientation-request true
-adb shell cmd window user-rotation lock 3
-```
-
-Verify with:
-
-```bash
-adb shell dumpsys window displays | rg "cur=|mRotation=|mUserRotationMode|mUserRotation=|mCurrentRotation|mDisplayRotation|ignoreOrientationRequest"
-```
-
-Expected state:
-- `cur=2340x1080 app=2340x1080`
-- `mDisplayRotation=ROTATION_270`
-- `mRotation=3`
-- `mUserRotationMode=USER_ROTATION_LOCKED`
-- `mUserRotation=ROTATION_270`
-- `ignoreOrientationRequest=true`
-
-Do not treat `cur=2340x1080 app=2340x1080` alone as sufficient; the app can
-still be sideways or upside down if the emulator frame and Android rotation are
-not aligned. If the phone frame is portrait while the app is upright, rotate the
-emulator frame with `adb emu rotate`, then reapply the `ROTATION_270` lock above.
-
## Live TV playback validation
For live TV playback bugs, do not validate with a single screenshot, a short
diff --git a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
index 8d5ecdf4..da20a4d3 100644
--- a/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
+++ b/app/src/main/java/com/streamvault/app/StreamVaultApp.kt
@@ -31,6 +31,7 @@ import androidx.work.WorkManager
import com.streamvault.data.manager.recording.RecordingReconcileWorker
import com.streamvault.data.sync.ProviderSyncWorker
import com.streamvault.data.sync.XtreamIndexWorker
+import com.streamvault.data.sync.SyncManager
import com.streamvault.player.timeshift.TimeshiftDiskManager
import javax.inject.Inject
import okhttp3.OkHttpClient
@@ -52,6 +53,9 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {
@Inject
lateinit var jellyfinImageAuthInterceptor: JellyfinImageAuthInterceptor
+ @Inject
+ lateinit var syncManager: SyncManager
+
private val imageOkHttpClient: OkHttpClient by lazy {
okHttpClient.newBuilder()
.addInterceptor(jellyfinImageAuthInterceptor)
@@ -70,6 +74,9 @@ class StreamVaultApp : Application(), SingletonImageLoader.Factory {
applicationScope.launch {
refreshCachedAppUpdateIfNeeded()
}
+ applicationScope.launch {
+ syncManager.reconcileStalkerIndexWorkAtStartup()
+ }
// Schedule daily data maintenance: EPG pruning, stale-favorite cleanup, and DB compaction checks.
// BLD-H02: Require network + device idle so the worker doesn't drain battery.
diff --git a/app/src/main/java/com/streamvault/app/cast/CastMediaRequestFactory.kt b/app/src/main/java/com/streamvault/app/cast/CastMediaRequestFactory.kt
index ad8930c0..0fcad361 100644
--- a/app/src/main/java/com/streamvault/app/cast/CastMediaRequestFactory.kt
+++ b/app/src/main/java/com/streamvault/app/cast/CastMediaRequestFactory.kt
@@ -47,6 +47,7 @@ class CastMediaRequestFactory @Inject constructor() {
rewriteRequiredReason = streamInfo.castRewriteRequiredReason(resolvedUrl),
headers = streamInfo.headers,
userAgent = streamInfo.userAgent,
+ playbackTransportPolicy = streamInfo.playbackTransportPolicy,
allowInvalidSsl = streamInfo.allowInvalidSsl,
proxyHost = streamInfo.proxyHost,
proxyPort = streamInfo.proxyPort
@@ -134,6 +135,9 @@ private fun StreamInfo.castRewriteRequiredReason(url: String): CastRewriteRequir
if (proxyHost.isNotBlank() || proxyPort != null) {
return CastRewriteRequiredReason.PROXY
}
+ if (playbackTransportPolicy != null) {
+ return CastRewriteRequiredReason.SCOPED_TRANSPORT
+ }
if (allowInvalidSsl) {
return CastRewriteRequiredReason.INVALID_SSL
}
diff --git a/app/src/main/java/com/streamvault/app/cast/CastModels.kt b/app/src/main/java/com/streamvault/app/cast/CastModels.kt
index dd46e683..016fadd5 100644
--- a/app/src/main/java/com/streamvault/app/cast/CastModels.kt
+++ b/app/src/main/java/com/streamvault/app/cast/CastModels.kt
@@ -1,5 +1,7 @@
package com.streamvault.app.cast
+import com.streamvault.domain.model.PlaybackTransportPolicy
+
/**
* Media payload sent to a Chromecast receiver.
*
@@ -20,6 +22,7 @@ data class CastMediaRequest(
val rewriteRequiredReason: CastRewriteRequiredReason? = null,
val headers: Map<String, String> = emptyMap(),
val userAgent: String? = null,
+ val playbackTransportPolicy: PlaybackTransportPolicy? = null,
val allowInvalidSsl: Boolean = false,
val proxyHost: String = "",
val proxyPort: Int? = null
@@ -33,7 +36,8 @@ enum class CastRewriteRequiredReason {
CUSTOM_HEADERS,
CUSTOM_USER_AGENT,
PROXY,
- INVALID_SSL
+ INVALID_SSL,
+ SCOPED_TRANSPORT
}
enum class CastConnectionState {
diff --git a/app/src/main/java/com/streamvault/app/cast/CastUiMessages.kt b/app/src/main/java/com/streamvault/app/cast/CastUiMessages.kt
index 508d0993..ec29b3ce 100644
--- a/app/src/main/java/com/streamvault/app/cast/CastUiMessages.kt
+++ b/app/src/main/java/com/streamvault/app/cast/CastUiMessages.kt
@@ -14,7 +14,8 @@ fun CastMediaRequest.toCastUnsupportedMessageRes(): Int = when (rewriteRequiredR
CastRewriteRequiredReason.CUSTOM_HEADERS -> R.string.cast_headers_unsupported
CastRewriteRequiredReason.CUSTOM_USER_AGENT -> R.string.cast_user_agent_unsupported
CastRewriteRequiredReason.PROXY -> R.string.cast_proxy_unsupported
- CastRewriteRequiredReason.INVALID_SSL -> R.string.cast_invalid_ssl_unsupported
+ CastRewriteRequiredReason.INVALID_SSL,
+ CastRewriteRequiredReason.SCOPED_TRANSPORT -> R.string.cast_invalid_ssl_unsupported
null -> R.string.cast_stream_unsupported
}
diff --git a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
index a4648ccb..903a2511 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -102,7 +102,10 @@ object DatabaseModule {
StreamVaultDatabase.MIGRATION_58_59,
StreamVaultDatabase.MIGRATION_59_60,
StreamVaultDatabase.MIGRATION_60_61,
- StreamVaultDatabase.MIGRATION_61_62
+ StreamVaultDatabase.MIGRATION_61_62,
+ StreamVaultDatabase.MIGRATION_62_63,
+ StreamVaultDatabase.MIGRATION_63_64,
+ StreamVaultDatabase.MIGRATION_64_65
)
// NOTE: fallbackToDestructiveMigration() intentionally removed.
// All future schema changes MUST add a corresponding Migration in StreamVaultDatabase.
@@ -144,5 +147,9 @@ object DatabaseModule {
@Provides fun provideXtreamContentIndexDao(db: StreamVaultDatabase): XtreamContentIndexDao = db.xtreamContentIndexDao()
@Provides fun provideXtreamIndexJobDao(db: StreamVaultDatabase): XtreamIndexJobDao = db.xtreamIndexJobDao()
@Provides fun provideXtreamLiveOnboardingDao(db: StreamVaultDatabase): XtreamLiveOnboardingDao = db.xtreamLiveOnboardingDao()
+ @Provides fun provideStalkerIndexJobDao(db: StreamVaultDatabase): StalkerIndexJobDao = db.stalkerIndexJobDao()
+ @Provides fun provideStalkerPortalStateDao(db: StreamVaultDatabase): StalkerPortalStateDao = db.stalkerPortalStateDao()
+ @Provides fun provideStalkerRemoteIdentityDao(db: StreamVaultDatabase): StalkerRemoteIdentityDao = db.stalkerRemoteIdentityDao()
+ @Provides fun provideStalkerDiscoveryStageDao(db: StreamVaultDatabase): StalkerDiscoveryStageDao = db.stalkerDiscoveryStageDao()
@Provides fun provideDownloadDao(db: StreamVaultDatabase): DownloadDao = db.downloadDao()
}
diff --git a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
index a5cafc7d..379227a6 100644
--- a/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/NetworkModule.kt
@@ -30,12 +30,7 @@ import okhttp3.Cache
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import java.io.File
-import java.security.SecureRandom
-import java.security.cert.X509Certificate
import java.util.concurrent.TimeUnit.SECONDS
-import javax.net.ssl.HostnameVerifier
-import javax.net.ssl.SSLContext
-import javax.net.ssl.X509TrustManager
import javax.inject.Singleton
@Module
@@ -95,7 +90,7 @@ object NetworkModule {
@Provides
@Singleton
fun provideStalkerApiService(okHttpClient: OkHttpClient, xtreamJson: Json): StalkerApiService =
- OkHttpStalkerApiService(okHttpClient.newBuilder().applyUnsafeTlsBypass().build(), xtreamJson)
+ OkHttpStalkerApiService(okHttpClient, xtreamJson)
@Provides
@Singleton
@@ -106,19 +101,6 @@ object NetworkModule {
coerceInputValues = true
}
- private fun OkHttpClient.Builder.applyUnsafeTlsBypass(): OkHttpClient.Builder {
- val trustAllManager = object : X509TrustManager {
- override fun checkClientTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
- override fun checkServerTrusted(chain: Array<out X509Certificate>?, authType: String?) = Unit
- override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
- }
- val sslContext = SSLContext.getInstance("TLS").apply {
- init(null, arrayOf(trustAllManager), SecureRandom())
- }
- return sslSocketFactory(sslContext.socketFactory, trustAllManager)
- .hostnameVerifier(HostnameVerifier { _, _ -> true })
- }
-
@Provides
@Singleton
fun provideXmltvParser(): XmltvParser = XmltvParser()
diff --git a/app/src/main/java/com/streamvault/app/pairing/ProviderQrPairingManager.kt b/app/src/main/java/com/streamvault/app/pairing/ProviderQrPairingManager.kt
index b60dc682..dcc1e958 100644
--- a/app/src/main/java/com/streamvault/app/pairing/ProviderQrPairingManager.kt
+++ b/app/src/main/java/com/streamvault/app/pairing/ProviderQrPairingManager.kt
@@ -287,6 +287,14 @@ class ProviderQrPairingManager @Inject constructor(
ProviderPairingSubmitResult.Success(result.provider.name)
is ValidateAndAddProviderResult.ValidationError ->
ProviderPairingSubmitResult.Error(result.message)
+ is ValidateAndAddProviderResult.TransportConsentRequired ->
+ ProviderPairingSubmitResult.Error(
+ "Open StreamVault on the TV to review this provider's connection warning."
+ )
+ is ValidateAndAddProviderResult.VerificationInconclusive ->
+ ProviderPairingSubmitResult.Error(
+ "Open StreamVault on the TV to decide whether to save this provider with verification pending."
+ )
is ValidateAndAddProviderResult.Error ->
ProviderPairingSubmitResult.Error(result.message)
}
diff --git a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginContract.kt b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginContract.kt
index f3885a05..5f6693c6 100644
--- a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginContract.kt
+++ b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginContract.kt
@@ -43,6 +43,9 @@ object StreamVaultPluginContract {
const val KEY_USER_AGENT = "user_agent"
const val KEY_DRM_JSON = "drm_json"
const val KEY_ALLOW_INVALID_SSL = "allow_invalid_ssl"
+ const val KEY_TRANSPORT_MODE = "transport_mode"
+ const val KEY_TRANSPORT_ORIGIN = "transport_origin"
+ const val KEY_TRANSPORT_SPKI_SHA256 = "transport_spki_sha256"
const val KEY_PROXY_HOST = "proxy_host"
const val KEY_PROXY_PORT = "proxy_port"
const val KEY_CAST_REWRITE_REASON = "cast_rewrite_reason"
diff --git a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt
index 59fd55e5..2e54f9c6 100644
--- a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt
+++ b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt
@@ -349,6 +349,14 @@ class StreamVaultPluginManager @Inject constructor(
putString(StreamVaultPluginContract.KEY_HEADERS_JSON, headers.toHeadersJson())
putString(StreamVaultPluginContract.KEY_USER_AGENT, userAgent.orEmpty())
putBoolean(StreamVaultPluginContract.KEY_ALLOW_INVALID_SSL, allowInvalidSsl)
+ playbackTransportPolicy?.let { policy ->
+ putString(StreamVaultPluginContract.KEY_TRANSPORT_MODE, policy.mode.name)
+ putString(StreamVaultPluginContract.KEY_TRANSPORT_ORIGIN, policy.origin.authority)
+ putString(
+ StreamVaultPluginContract.KEY_TRANSPORT_SPKI_SHA256,
+ policy.spkiSha256.orEmpty()
+ )
+ }
putString(StreamVaultPluginContract.KEY_PROXY_HOST, proxyHost)
proxyPort?.let { putInt(StreamVaultPluginContract.KEY_PROXY_PORT, it) }
putString(StreamVaultPluginContract.KEY_CAST_REWRITE_REASON, rewriteRequiredReason?.name.orEmpty())
diff --git a/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt b/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt
index dd99edaf..b33f3cb2 100644
--- a/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt
+++ b/app/src/main/java/com/streamvault/app/tvinput/StreamVaultTvInputService.kt
@@ -25,6 +25,7 @@ import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.StreamType
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.player.playback.applyUnsafeTlsBypass
+import com.streamvault.player.playback.applyPlaybackTransportPolicy
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
@@ -184,10 +185,14 @@ class StreamVaultTvInputService : TvInputService() {
private fun OkHttpClient.forPlayback(streamInfo: StreamInfo): OkHttpClient {
val proxy = streamInfo.httpProxy()
- if (!streamInfo.allowInvalidSsl && proxy == null) {
+ if (streamInfo.playbackTransportPolicy == null &&
+ !streamInfo.allowInvalidSsl &&
+ proxy == null
+ ) {
return this
}
val key = PlaybackClientKey(
+ transportPolicy = streamInfo.playbackTransportPolicy,
allowInvalidSsl = streamInfo.allowInvalidSsl,
proxyHost = streamInfo.proxyHost.trim(),
proxyPort = streamInfo.proxyPort
@@ -195,7 +200,10 @@ class StreamVaultTvInputService : TvInputService() {
return playbackClients.computeIfAbsent(key) {
newBuilder()
.apply {
- if (streamInfo.allowInvalidSsl) {
+ val transportPolicy = streamInfo.playbackTransportPolicy
+ if (transportPolicy != null) {
+ applyPlaybackTransportPolicy(transportPolicy)
+ } else if (streamInfo.allowInvalidSsl) {
applyUnsafeTlsBypass()
}
proxy?.let { proxy(it) }
@@ -211,6 +219,7 @@ class StreamVaultTvInputService : TvInputService() {
}
private data class PlaybackClientKey(
+ val transportPolicy: com.streamvault.domain.model.PlaybackTransportPolicy?,
val allowInvalidSsl: Boolean,
val proxyHost: String,
val proxyPort: Int?
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
index dc6391ac..5f176e46 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesScreen.kt
@@ -735,7 +735,7 @@ private fun MoviesVodContent(
val modernGridState = androidx.compose.foundation.lazy.grid.rememberLazyGridState()
InfiniteScrollEffect(
gridState = modernGridState,
- enabled = !uiState.isReorderMode,
+ enabled = uiState.vodInfiniteScroll && !uiState.isReorderMode,
canLoadMore = uiState.canLoadMoreSelectedCategory,
isLoading = uiState.isLoadingSelectedCategory,
onLoadMore = onLoadMore
@@ -895,6 +895,21 @@ private fun MoviesVodContent(
)
}
}
+ if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory &&
+ !uiState.vodInfiniteScroll && !uiState.isReorderMode
+ ) {
+ item(key = "load_next_movie_batch", span = { GridItemSpan(maxLineSpan) }) {
+ LoadMoreCard(
+ label = stringResource(
+ R.string.library_load_more,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ onClick = onLoadMore,
+ modifier = Modifier.padding(vertical = 12.dp)
+ )
+ }
+ }
}
}
@@ -1156,7 +1171,7 @@ private fun MoviesVodClassicContent(
val classicGridState = androidx.compose.foundation.lazy.grid.rememberLazyGridState()
InfiniteScrollEffect(
gridState = classicGridState,
- enabled = !uiState.isReorderMode,
+ enabled = uiState.vodInfiniteScroll && !uiState.isReorderMode,
canLoadMore = uiState.canLoadMoreSelectedCategory,
isLoading = uiState.isLoadingSelectedCategory,
onLoadMore = onLoadMore
@@ -1226,6 +1241,21 @@ private fun MoviesVodClassicContent(
)
}
}
+ if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory &&
+ !uiState.vodInfiniteScroll && !uiState.isReorderMode
+ ) {
+ item(key = "load_next_movie_batch_classic", span = { GridItemSpan(maxLineSpan) }) {
+ LoadMoreCard(
+ label = stringResource(
+ R.string.library_load_more,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ onClick = onLoadMore,
+ modifier = Modifier.padding(vertical = 12.dp)
+ )
+ }
+ }
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
index 5130b88a..64907761 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/movies/MoviesViewModel.kt
@@ -212,7 +212,11 @@ class MoviesViewModel @Inject constructor(
categoryIds = categoryIds,
limitPerCategory = VodBrowseDefaults.PREVIEW_ROW_LIMIT
).map { providerPreviews ->
- val isLoading = categoryIds.all { id -> providerPreviews[id].isNullOrEmpty() }
+ // The repository includes an entry for every category whose
+ // preview query is active. An empty list is a valid result (and
+ // can also be populated later by Room); it must not keep the
+ // category paginator permanently locked in its loading state.
+ val isLoading = categoryIds.none(providerPreviews::containsKey)
val hasMore = params.providerCategories.size > batchSize
PreviewLoadResult(buildPreviewCatalog(params, providerPreviews), isLoading, hasMore)
}
@@ -298,6 +302,31 @@ class MoviesViewModel @Inject constructor(
}
}
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .flatMapLatest { provider ->
+ combine(
+ movieRepository.getCategoryItemCounts(provider.id),
+ movieRepository.getLibraryCount(provider.id),
+ movieRepository.getCategories(provider.id)
+ ) { counts, libraryCount, categories ->
+ Triple(counts, libraryCount, categories)
+ }
+ }
+ .collectLatest { (counts, libraryCount, categories) ->
+ val countsByName = categories.associate { category ->
+ category.name to (counts[category.id] ?: 0)
+ }
+ _uiState.update { state ->
+ state.copy(
+ categoryCounts = state.categoryCounts + countsByName,
+ libraryCount = libraryCount
+ )
+ }
+ }
+ }
+
viewModelScope.launch {
providerRepository.getActiveProvider()
.filterNotNull()
@@ -306,14 +335,16 @@ class MoviesViewModel @Inject constructor(
favoriteRepository.getAllFavorites(provider.id, ContentType.MOVIE),
getCustomCategories(provider.id, ContentType.MOVIE),
movieRepository.getCategories(provider.id),
+ movieRepository.getCategoryItemCounts(provider.id),
preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.MOVIE),
preferencesRepository.getCategorySortMode(provider.id, ContentType.MOVIE)
) { values ->
val allFavorites = values[0] as List<com.streamvault.domain.model.Favorite>
val customCategories = values[1] as List<Category>
val providerCategories = values[2] as List<Category>
- val hiddenCategoryIds = values[3] as Set<Long>
- val sortMode = values[4] as CategorySortMode
+ val providerCategoryCounts = values[3] as Map<Long, Int>
+ val hiddenCategoryIds = values[4] as Set<Long>
+ val sortMode = values[5] as CategorySortMode
MovieCategorySelectionDependencies(
allFavorites = allFavorites,
customCategories = customCategories,
@@ -322,6 +353,7 @@ class MoviesViewModel @Inject constructor(
hiddenCategoryIds = hiddenCategoryIds,
sortMode = sortMode
),
+ providerCategoryCounts = providerCategoryCounts,
hiddenCategoryIds = hiddenCategoryIds
)
}.combine(
@@ -351,10 +383,16 @@ class MoviesViewModel @Inject constructor(
allFavorites = dependencies.allFavorites,
customCategories = dependencies.customCategories,
providerCategories = dependencies.providerCategories,
+ selectedProviderCategoryHasItems = dependencies.providerCategories
+ .firstOrNull { it.name == selection.selectedCategory }
+ ?.id
+ ?.let { categoryId -> (dependencies.providerCategoryCounts[categoryId] ?: 0) > 0 }
+ ?: false,
hiddenCategoryIds = dependencies.hiddenCategoryIds
)
}
}
+ .distinctUntilChanged()
.flatMapLatest { request ->
flow {
emit(loadSelectedCategoryItems(request))
@@ -1235,6 +1273,7 @@ private data class MovieCategorySelectionDependencies(
val allFavorites: List<com.streamvault.domain.model.Favorite>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
+ val providerCategoryCounts: Map<Long, Int>,
val hiddenCategoryIds: Set<Long>
)
@@ -1248,6 +1287,7 @@ private data class SelectedMovieCategoryRequest(
val allFavorites: List<com.streamvault.domain.model.Favorite>,
val customCategories: List<Category>,
val providerCategories: List<Category>,
+ val selectedProviderCategoryHasItems: Boolean,
val hiddenCategoryIds: Set<Long>
)
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCastStreamInfoSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCastStreamInfoSupport.kt
index 159f8b6f..375c11df 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCastStreamInfoSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerCastStreamInfoSupport.kt
@@ -27,6 +27,7 @@ private fun StreamInfo.castContextScore(): Int {
if (headers.any { (name, value) -> name.isNotBlank() && value.isNotBlank() }) score += 4
if (!userAgent.isNullOrBlank()) score += 2
if (proxyHost.isNotBlank() || proxyPort != null) score += 2
+ if (playbackTransportPolicy != null) score += 2
if (allowInvalidSsl) score += 2
if (drmInfo != null) score += 2
if (streamType != StreamType.UNKNOWN) score += 1
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
index b663ffdb..785caa23 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerContentResolutionSupport.kt
@@ -174,6 +174,7 @@ internal suspend fun resolvePlayerPlaybackStreamInfo(
title = currentTitle,
headers = resolved.headers,
userAgent = resolved.userAgent,
+ playbackTransportPolicy = resolved.playbackTransportPolicy,
allowInvalidSsl = resolved.allowInvalidSsl,
proxyHost = resolved.proxyHost,
proxyPort = resolved.proxyPort,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
index 0cc78ad7..86983a65 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModel.kt
@@ -66,6 +66,7 @@ import com.streamvault.player.timeshift.LiveTimeshiftState
import com.streamvault.player.timeshift.LiveTimeshiftStatus
import com.streamvault.player.timeshift.TimeshiftConfig
import com.streamvault.player.playback.applyUnsafeTlsBypass
+import com.streamvault.player.playback.applyPlaybackTransportPolicy
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -1372,10 +1373,17 @@ class PlayerViewModel @Inject constructor(
}
}
.build()
- val probeClient = if (streamInfo.allowInvalidSsl || streamInfo.proxyHost.isNotBlank()) {
+ val probeClient = if (
+ streamInfo.playbackTransportPolicy != null ||
+ streamInfo.allowInvalidSsl ||
+ streamInfo.proxyHost.isNotBlank()
+ ) {
okHttpClient.newBuilder()
.apply {
- if (streamInfo.allowInvalidSsl) {
+ val transportPolicy = streamInfo.playbackTransportPolicy
+ if (transportPolicy != null) {
+ applyPlaybackTransportPolicy(transportPolicy)
+ } else if (streamInfo.allowInvalidSsl) {
applyUnsafeTlsBypass()
}
streamInfo.httpProxy()?.let { proxy(it) }
@@ -1511,7 +1519,11 @@ class PlayerViewModel @Inject constructor(
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
if (streamInfo == null) {
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
- showPlayerNotice(message = "No playable stream URL was available.", recoveryType = PlayerRecoveryType.SOURCE)
+ showPlayerNotice(
+ message = lastResolutionFailureMessage?.takeIf { it.isNotBlank() }
+ ?: "No playable stream URL was available.",
+ recoveryType = PlayerRecoveryType.SOURCE
+ )
return@launch
}
currentStreamUrl = playbackLogicalUrl
@@ -1730,6 +1742,8 @@ class PlayerViewModel @Inject constructor(
}
}
+ private var lastResolutionFailureMessage: String? = null
+
internal suspend fun resolvePlaybackStreamInfo(
logicalUrl: String,
internalContentId: Long,
@@ -1749,9 +1763,11 @@ class PlayerViewModel @Inject constructor(
seriesRepository = seriesRepository,
xtreamStreamUrlResolver = xtreamStreamUrlResolver
)
- resolution.credentialFailureMessage?.let { message ->
- setLastFailureReason(message)
- showPlayerNotice(message = message, recoveryType = PlayerRecoveryType.SOURCE)
+ val credentialMessage = resolution.credentialFailureMessage
+ lastResolutionFailureMessage = credentialMessage
+ ?: resolution.resolutionFailureMessage?.takeIf { it.isNotBlank() }
+ if (credentialMessage != null) {
+ setLastFailureReason(credentialMessage)
return null
}
return resolution.streamInfo
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt
index 1110ca03..a46213d9 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/player/PlayerViewModelActions.kt
@@ -332,7 +332,8 @@ private fun PlayerViewModel.toPlayerCastUnsupportedMessage(request: CastMediaReq
CastRewriteRequiredReason.CUSTOM_HEADERS -> R.string.cast_headers_unsupported
CastRewriteRequiredReason.CUSTOM_USER_AGENT -> R.string.cast_user_agent_unsupported
CastRewriteRequiredReason.PROXY -> R.string.cast_proxy_unsupported
- CastRewriteRequiredReason.INVALID_SSL -> R.string.cast_invalid_ssl_unsupported
+ CastRewriteRequiredReason.INVALID_SSL,
+ CastRewriteRequiredReason.SCOPED_TRANSPORT -> R.string.cast_invalid_ssl_unsupported
null -> R.string.cast_stream_unsupported
}
)
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.kt
index a8399947..bc6f06f2 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
@@ -87,6 +87,12 @@ import com.streamvault.data.remote.stalker.StalkerAdvancedOptions
import com.streamvault.data.remote.stalker.StalkerAdvancedOptionsCodec
import com.streamvault.data.remote.stalker.StalkerParamOverride
import com.streamvault.data.remote.stalker.StalkerRequestRule
+import com.streamvault.data.remote.stalker.StalkerCompatibilityRegistry
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProfileVerification
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportChallengeReason
import com.google.zxing.qrcode.QRCodeWriter
import com.google.zxing.BarcodeFormat
import android.graphics.Bitmap
@@ -116,6 +122,96 @@ private data class StalkerRequestRuleUiState(
val paramsText: String = ""
)
+@Composable
+private fun StalkerCompatibilitySelector(
+ protocol: StalkerProtocolPreference,
+ profileId: String,
+ onProtocolSelected: (StalkerProtocolPreference) -> Unit,
+ onProfileSelected: (String) -> Unit
+) {
+ var showProtocols by rememberSaveable { mutableStateOf(false) }
+ var showProfiles by rememberSaveable { mutableStateOf(false) }
+ val selectedProfile = StalkerCompatibilityRegistry.find(profileId)
+
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text("Compatibility", style = MaterialTheme.typography.titleSmall, color = OnBackground)
+ SmallActionButton(
+ text = "Protocol: ${protocol.name.replace('_', ' ')}",
+ onClick = { showProtocols = !showProtocols }
+ )
+ AnimatedVisibility(showProtocols) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ StalkerProtocolPreference.entries
+ .filterNot { it == StalkerProtocolPreference.MINISTRA_API_V3 }
+ .forEach { option ->
+ SmallActionButton(
+ text = if (option == protocol) "✓ ${option.name.replace('_', ' ')}" else option.name.replace('_', ' '),
+ onClick = {
+ onProtocolSelected(option)
+ onProfileSelected(StalkerCompatibilityProfileIds.AUTO)
+ showProtocols = false
+ }
+ )
+ }
+ }
+ }
+ SmallActionButton(
+ text = "Model: ${selectedProfile?.displayName ?: "Automatic"}",
+ onClick = { showProfiles = !showProfiles }
+ )
+ AnimatedVisibility(showProfiles) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ SmallActionButton(
+ text = if (profileId == StalkerCompatibilityProfileIds.AUTO) "✓ Automatic" else "Automatic",
+ onClick = {
+ onProfileSelected(StalkerCompatibilityProfileIds.AUTO)
+ showProfiles = false
+ }
+ )
+ val family = if (protocol == StalkerProtocolPreference.MINISTRA_API_V3) {
+ com.streamvault.domain.model.StalkerProtocolFamily.MINISTRA_API_V3
+ } else {
+ com.streamvault.domain.model.StalkerProtocolFamily.CLASSIC_MAG
+ }
+ StalkerCompatibilityRegistry.profiles
+ .filter { it.protocolFamily == family }
+ .groupBy { it.generation }
+ .forEach { (generation, profiles) ->
+ Text(generation, style = MaterialTheme.typography.labelMedium, color = OnBackground.copy(alpha = 0.72f))
+ profiles.forEach { option ->
+ val experimental = option.verification == StalkerProfileVerification.EXPERIMENTAL
+ SmallActionButton(
+ text = buildString {
+ if (option.id == profileId) append("✓ ")
+ append(option.displayName)
+ if (experimental) append(" — EXPERIMENTAL")
+ },
+ onClick = {
+ onProfileSelected(option.id)
+ showProfiles = false
+ }
+ )
+ }
+ }
+ if (family == com.streamvault.domain.model.StalkerProtocolFamily.CLASSIC_MAG) {
+ Text(
+ "Experimental profiles require captured/manual identity fields and are excluded from automatic discovery.",
+ style = MaterialTheme.typography.bodySmall,
+ color = AccentAmber
+ )
+ SmallActionButton(
+ text = if (profileId == StalkerCompatibilityProfileIds.CUSTOM) "✓ Custom profile" else "Custom profile",
+ onClick = {
+ onProfileSelected(StalkerCompatibilityProfileIds.CUSTOM)
+ showProfiles = false
+ }
+ )
+ }
+ }
+ }
+ }
+}
+
private fun StalkerRequestRuleUiState.toRule(): StalkerRequestRule =
StalkerRequestRule(
action = action.trim(),
@@ -485,7 +581,8 @@ fun ProviderSetupScreen(
fileImportError = fileImportError,
onFilePick = { filePickerLauncher.launch(arrayOf("*/*")) },
onLoginXtream = { viewModel.loginXtream(serverUrl, username, password, name, httpUserAgent, httpHeaders) },
- onLoginStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, stalkerAuthMode, username, password, name, "", httpHeaders, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale, stalkerSerialNumber, stalkerDeviceId, stalkerDeviceId2, stalkerSignature, buildStalkerAdvancedOptionsJson()) },
+ onLoginStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, stalkerAuthMode, username, password, name, "", httpHeaders, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale, stalkerSerialNumber, stalkerDeviceId, stalkerDeviceId2, stalkerSignature, buildStalkerAdvancedOptionsJson(), uiState.stalkerProtocolPreference, uiState.stalkerRequestedProfileId) },
+ onRepairStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, stalkerAuthMode, username, password, name, "", httpHeaders, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale, stalkerSerialNumber, stalkerDeviceId, stalkerDeviceId2, stalkerSignature, buildStalkerAdvancedOptionsJson(), uiState.stalkerProtocolPreference, uiState.stalkerRequestedProfileId, repairConnection = true) },
onAddM3u = { viewModel.addM3u(m3uUrl, name, httpUserAgent, httpHeaders) },
onLoginJellyfin = { viewModel.loginJellyfin(serverUrl, username, password, name) },
quickConnectCode = uiState.jellyfinQuickConnectCode,
@@ -494,6 +591,9 @@ fun ProviderSetupScreen(
onStopPhonePairing = viewModel::stopPhonePairing,
onToggleM3uVodClassification = { viewModel.updateM3uVodClassificationEnabled(!uiState.m3uVodClassificationEnabled) },
onSelectEpgSyncMode = viewModel::updateEpgSyncMode,
+ onSelectStalkerCatalogMode = viewModel::updateStalkerCatalogMode,
+ onSelectStalkerProtocolPreference = viewModel::updateStalkerProtocolPreference,
+ onSelectStalkerProfile = viewModel::updateStalkerRequestedProfile,
onSelectXtreamLiveSyncMode = viewModel::updateXtreamLiveSyncMode,
onSelectGuideSourcePolicy = viewModel::updateGuideSourcePolicy,
onSelectChannelLogoSourcePolicy = viewModel::updateChannelLogoSourcePolicy,
@@ -546,7 +646,8 @@ fun ProviderSetupScreen(
fileImportError = fileImportError,
onFilePick = { filePickerLauncher.launch(arrayOf("*/*")) },
onLoginXtream = { viewModel.loginXtream(serverUrl, username, password, name, httpUserAgent, httpHeaders) },
- onLoginStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, stalkerAuthMode, username, password, name, "", httpHeaders, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale, stalkerSerialNumber, stalkerDeviceId, stalkerDeviceId2, stalkerSignature, buildStalkerAdvancedOptionsJson()) },
+ onLoginStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, stalkerAuthMode, username, password, name, "", httpHeaders, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale, stalkerSerialNumber, stalkerDeviceId, stalkerDeviceId2, stalkerSignature, buildStalkerAdvancedOptionsJson(), uiState.stalkerProtocolPreference, uiState.stalkerRequestedProfileId) },
+ onRepairStalker = { viewModel.loginStalker(serverUrl, stalkerMacAddress, stalkerAuthMode, username, password, name, "", httpHeaders, stalkerDeviceProfile, stalkerDeviceTimezone, stalkerDeviceLocale, stalkerSerialNumber, stalkerDeviceId, stalkerDeviceId2, stalkerSignature, buildStalkerAdvancedOptionsJson(), uiState.stalkerProtocolPreference, uiState.stalkerRequestedProfileId, repairConnection = true) },
onAddM3u = { viewModel.addM3u(m3uUrl, name, httpUserAgent, httpHeaders) },
onLoginJellyfin = { viewModel.loginJellyfin(serverUrl, username, password, name) },
quickConnectCode = uiState.jellyfinQuickConnectCode,
@@ -555,6 +656,9 @@ fun ProviderSetupScreen(
onStopPhonePairing = viewModel::stopPhonePairing,
onToggleM3uVodClassification = { viewModel.updateM3uVodClassificationEnabled(!uiState.m3uVodClassificationEnabled) },
onSelectEpgSyncMode = viewModel::updateEpgSyncMode,
+ onSelectStalkerCatalogMode = viewModel::updateStalkerCatalogMode,
+ onSelectStalkerProtocolPreference = viewModel::updateStalkerProtocolPreference,
+ onSelectStalkerProfile = viewModel::updateStalkerRequestedProfile,
onSelectXtreamLiveSyncMode = viewModel::updateXtreamLiveSyncMode,
onSelectGuideSourcePolicy = viewModel::updateGuideSourcePolicy,
onSelectChannelLogoSourcePolicy = viewModel::updateChannelLogoSourcePolicy,
@@ -581,7 +685,13 @@ fun ProviderSetupScreen(
message = uiState.syncProgress!!,
quickConnectCode = if (uiState.jellyfinQuickConnectCode.isNotBlank()) uiState.jellyfinQuickConnectCode else null,
serverUrl = serverUrl,
- onCancel = if (uiState.jellyfinQuickConnectCode.isNotBlank()) ({ viewModel.cancelJellyfinQuickConnect() }) else null
+ onCancel = when {
+ uiState.jellyfinQuickConnectCode.isNotBlank() ->
+ ({ viewModel.cancelJellyfinQuickConnect() })
+ uiState.selectedTab == 1 && uiState.isLoading ->
+ ({ viewModel.cancelStalkerSetup() })
+ else -> null
+ }
)
}
@@ -603,6 +713,66 @@ fun ProviderSetupScreen(
)
}
+uiState.stalkerTransportChallenge?.let { challenge ->
+ val (title, body) = when (challenge.reason) {
+ StalkerTransportChallengeReason.INVALID_TLS ->
+ stringResource(R.string.stalker_transport_invalid_tls_title) to
+ stringResource(
+ R.string.stalker_transport_invalid_tls_body,
+ challenge.displayHost
+ )
+ StalkerTransportChallengeReason.CLEARTEXT_HTTP ->
+ stringResource(R.string.stalker_transport_http_title) to
+ stringResource(
+ R.string.stalker_transport_http_body,
+ challenge.displayHost
+ )
+ StalkerTransportChallengeReason.ORIGIN_CHANGED ->
+ stringResource(R.string.stalker_transport_origin_changed_title) to
+ stringResource(
+ R.string.stalker_transport_origin_changed_body,
+ challenge.displayHost
+ )
+ }
+ PremiumDialog(
+ title = title,
+ subtitle = body,
+ onDismissRequest = viewModel::dismissStalkerTransportChallenge,
+ content = {},
+ footer = {
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.stalker_transport_go_back),
+ onClick = viewModel::dismissStalkerTransportChallenge
+ )
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.stalker_transport_connect_anyway),
+ onClick = viewModel::acceptStalkerTransportChallenge,
+ emphasized = true
+ )
+ }
+ )
+ }
+
+ uiState.stalkerVerificationInconclusive?.let {
+ PremiumDialog(
+ title = stringResource(R.string.stalker_verification_inconclusive_title),
+ subtitle = stringResource(R.string.stalker_verification_inconclusive_body),
+ onDismissRequest = viewModel::dismissStalkerVerificationInconclusive,
+ content = {},
+ footer = {
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.stalker_transport_go_back),
+ onClick = viewModel::dismissStalkerVerificationInconclusive
+ )
+ PremiumDialogFooterButton(
+ label = stringResource(R.string.stalker_save_without_verification),
+ onClick = viewModel::saveStalkerWithoutVerification,
+ emphasized = true
+ )
+ }
+ )
+ }
+
if (showDiscardDraftDialog) {
PremiumDialog(
title = stringResource(R.string.setup_discard_draft_title),
@@ -688,30 +858,23 @@ fun ProviderSetupScreen(
}
if (uiState.pendingCombinedAttachProfileId != null) {
- androidx.compose.material3.AlertDialog(
+ PremiumDialog(
+ title = "Add Playlist To Combined M3U?",
+ subtitle = "Add ${uiState.createdProviderName ?: "this playlist"} to " +
+ "${uiState.pendingCombinedAttachProfileName ?: "the active combined source"} " +
+ "and keep that combined source active for Live TV?",
onDismissRequest = onSkipCreatedProviderCombinedAttach,
- title = { Text("Add Playlist To Combined M3U?") },
- text = {
- Text(
- buildString {
- append("Add ")
- append(uiState.createdProviderName ?: "this playlist")
- append(" to ")
- append(uiState.pendingCombinedAttachProfileName ?: "the active combined source")
- append(" and keep that combined source active for Live TV?")
- },
- color = OnSurface
+ content = {},
+ footer = {
+ PremiumDialogFooterButton(
+ label = "Not Now",
+ onClick = onSkipCreatedProviderCombinedAttach
+ )
+ PremiumDialogFooterButton(
+ label = "Add To Combined",
+ onClick = onAttachCreatedProvider,
+ emphasized = true
)
- },
- confirmButton = {
- TextButton(onClick = onAttachCreatedProvider) {
- Text("Add To Combined", color = Primary)
- }
- },
- dismissButton = {
- TextButton(onClick = onSkipCreatedProviderCombinedAttach) {
- Text("Not Now", color = OnSurface)
- }
}
)
}
@@ -891,6 +1054,7 @@ private fun ProviderFormContent(
onFilePick: () -> Unit,
onLoginXtream: () -> Unit,
onLoginStalker: () -> Unit,
+ onRepairStalker: () -> Unit,
onAddM3u: () -> Unit,
onLoginJellyfin: () -> Unit,
quickConnectCode: String,
@@ -899,6 +1063,9 @@ private fun ProviderFormContent(
onStopPhonePairing: () -> Unit,
onToggleM3uVodClassification: () -> Unit,
onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,
+ onSelectStalkerCatalogMode: (StalkerCatalogMode) -> Unit,
+ onSelectStalkerProtocolPreference: (StalkerProtocolPreference) -> Unit,
+ onSelectStalkerProfile: (String) -> Unit,
onSelectXtreamLiveSyncMode: (ProviderXtreamLiveSyncMode) -> Unit,
onSelectGuideSourcePolicy: (GuideSourcePolicy) -> Unit,
onSelectChannelLogoSourcePolicy: (ChannelLogoSourcePolicy) -> Unit,
@@ -980,6 +1147,7 @@ private fun ProviderFormContent(
onHttpHeadersChange = onHttpHeadersChange,
onToggleM3uVodClassification = onToggleM3uVodClassification,
onSelectEpgSyncMode = onSelectEpgSyncMode,
+ onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,
onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,
onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,
onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,
@@ -1062,6 +1230,12 @@ private fun ProviderFormContent(
imeAction = ImeAction.Next
)
)
+ StalkerCompatibilitySelector(
+ protocol = uiState.stalkerProtocolPreference,
+ profileId = uiState.stalkerRequestedProfileId,
+ onProtocolSelected = onSelectStalkerProtocolPreference,
+ onProfileSelected = onSelectStalkerProfile
+ )
AdvancedProviderOptionsSection(
sourceType = sourceType,
uiState = uiState,
@@ -1071,6 +1245,7 @@ private fun ProviderFormContent(
onHttpHeadersChange = onHttpHeadersChange,
onToggleM3uVodClassification = onToggleM3uVodClassification,
onSelectEpgSyncMode = onSelectEpgSyncMode,
+ onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,
onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,
onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,
onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,
@@ -1126,6 +1301,13 @@ private fun ProviderFormContent(
isLoading = uiState.isLoading,
onClick = onLoginStalker
)
+ if (uiState.isEditing) {
+ SmallActionButton(
+ text = androidx.compose.ui.res.stringResource(R.string.stalker_repair_connection),
+ isLoading = uiState.isLoading,
+ onClick = onRepairStalker
+ )
+ }
}
SourceType.M3U_URL -> {
@@ -1143,6 +1325,7 @@ private fun ProviderFormContent(
onHttpHeadersChange = onHttpHeadersChange,
onToggleM3uVodClassification = onToggleM3uVodClassification,
onSelectEpgSyncMode = onSelectEpgSyncMode,
+ onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,
onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,
onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,
onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,
@@ -1200,6 +1383,7 @@ private fun ProviderFormContent(
onHttpHeadersChange = onHttpHeadersChange,
onToggleM3uVodClassification = onToggleM3uVodClassification,
onSelectEpgSyncMode = onSelectEpgSyncMode,
+ onSelectStalkerCatalogMode = onSelectStalkerCatalogMode,
onSelectXtreamLiveSyncMode = onSelectXtreamLiveSyncMode,
onSelectGuideSourcePolicy = onSelectGuideSourcePolicy,
onSelectChannelLogoSourcePolicy = onSelectChannelLogoSourcePolicy,
@@ -1278,6 +1462,7 @@ private fun AdvancedProviderOptionsSection(
onHttpHeadersChange: (String) -> Unit,
onToggleM3uVodClassification: () -> Unit,
onSelectEpgSyncMode: (ProviderEpgSyncMode) -> Unit,
+ onSelectStalkerCatalogMode: (StalkerCatalogMode) -> Unit,
onSelectXtreamLiveSyncMode: (ProviderXtreamLiveSyncMode) -> Unit,
onSelectGuideSourcePolicy: (GuideSourcePolicy) -> Unit,
onSelectChannelLogoSourcePolicy: (ChannelLogoSourcePolicy) -> Unit,
@@ -1332,8 +1517,9 @@ private fun AdvancedProviderOptionsSection(
SourceType.JELLYFIN -> ProviderEpgSyncMode.UPFRONT
}
- LaunchedEffect(uiState.isEditing, uiState.epgSyncMode, uiState.xtreamLiveSyncMode, uiState.guideSourcePolicy, uiState.channelLogoSourcePolicy, sourceType) {
+ LaunchedEffect(uiState.isEditing, uiState.epgSyncMode, uiState.stalkerCatalogMode, uiState.xtreamLiveSyncMode, uiState.guideSourcePolicy, uiState.channelLogoSourcePolicy, sourceType) {
val hasNonDefaultSelection = ((sourceType == SourceType.XTREAM || sourceType == SourceType.STALKER) && uiState.epgSyncMode != defaultEpgSyncMode) ||
+ (sourceType == SourceType.STALKER && uiState.stalkerCatalogMode != StalkerCatalogMode.ON_DEMAND) ||
(sourceType == SourceType.XTREAM && uiState.xtreamLiveSyncMode != ProviderXtreamLiveSyncMode.AUTO) ||
(supportsGuideAndLogoPolicy(sourceType) && uiState.guideSourcePolicy != GuideSourcePolicy.AUTO) ||
(supportsGuideAndLogoPolicy(sourceType) && uiState.channelLogoSourcePolicy != ChannelLogoSourcePolicy.SUPPLIER_PREFERRED) ||
@@ -1624,6 +1810,38 @@ private fun AdvancedProviderOptionsSection(
}
if (sourceType == SourceType.STALKER) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(Surface, RoundedCornerShape(12.dp))
+ .border(1.dp, SurfaceHighlight, RoundedCornerShape(12.dp))
+ .padding(horizontal = 16.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Text(
+ text = "Movie and series catalog",
+ style = MaterialTheme.typography.titleSmall,
+ color = TextPrimary
+ )
+ Text(
+ text = "This is separate from EPG loading. On demand makes the provider ready after categories load; background indexing downloads the complete catalog later.",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ PolicyOptionRow(
+ title = "On demand (recommended)",
+ description = "Load visible shelves and opened categories as needed. Existing cached items are kept.",
+ selected = uiState.stalkerCatalogMode == StalkerCatalogMode.ON_DEMAND,
+ onSelect = { onSelectStalkerCatalogMode(StalkerCatalogMode.ON_DEMAND) }
+ )
+ PolicyOptionRow(
+ title = "Complete background index",
+ description = "Make the provider ready first, then maintain a complete searchable catalog in the background.",
+ selected = uiState.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX,
+ onSelect = { onSelectStalkerCatalogMode(StalkerCatalogMode.BACKGROUND_INDEX) }
+ )
+ }
+
Column(
modifier = Modifier
.fillMaxWidth()
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.kt
index 7314255e..7039096f 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
@@ -24,6 +24,11 @@ import com.streamvault.domain.model.ProviderEpgSyncMode
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportChallenge
+import com.streamvault.domain.model.StalkerTransportChallengeReason
import com.streamvault.domain.repository.CombinedM3uRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.usecase.ImportBackup
@@ -84,6 +89,8 @@ class ProviderSetupViewModel @Inject constructor(
val knownLocalM3uUrls: StateFlow<Set<String>> = _knownLocalM3uUrls.asStateFlow()
val pairingState: StateFlow<ProviderQrPairingState> = providerQrPairingManager.state
private var jellyfinQuickConnectJob: kotlinx.coroutines.Job? = null
+ private var stalkerSetupJob: kotlinx.coroutines.Job? = null
+ private var pendingStalkerCommand: StalkerProviderSetupCommand? = null
init {
viewModelScope.launch {
@@ -228,7 +235,12 @@ class ProviderSetupViewModel @Inject constructor(
stalkerDeviceId2 = provider.stalkerDeviceId2,
stalkerSignature = provider.stalkerSignature,
stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,
+ stalkerProtocolPreference = provider.stalkerProtocolPreference
+ .takeUnless { it == StalkerProtocolPreference.MINISTRA_API_V3 }
+ ?: StalkerProtocolPreference.CLASSIC_MAG,
+ stalkerRequestedProfileId = provider.stalkerRequestedProfileId,
epgSyncMode = provider.epgSyncMode,
+ stalkerCatalogMode = provider.stalkerCatalogMode,
xtreamLiveSyncMode = provider.xtreamLiveSyncMode,
guideSourcePolicy = provider.guideSourcePolicy,
channelLogoSourcePolicy = provider.channelLogoSourcePolicy,
@@ -259,6 +271,19 @@ class ProviderSetupViewModel @Inject constructor(
_uiState.update { it.copy(epgSyncMode = mode, hasCustomizedEpgSyncMode = true) }
}
+ fun updateStalkerCatalogMode(mode: StalkerCatalogMode) {
+ _uiState.update { it.copy(stalkerCatalogMode = mode) }
+ }
+
+ fun updateStalkerProtocolPreference(preference: StalkerProtocolPreference) {
+ if (preference == StalkerProtocolPreference.MINISTRA_API_V3) return
+ _uiState.update { it.copy(stalkerProtocolPreference = preference) }
+ }
+
+ fun updateStalkerRequestedProfile(profileId: String) {
+ _uiState.update { it.copy(stalkerRequestedProfileId = profileId) }
+ }
+
fun updateXtreamLiveSyncMode(mode: ProviderXtreamLiveSyncMode) {
_uiState.update { it.copy(xtreamLiveSyncMode = mode) }
}
@@ -299,48 +324,128 @@ class ProviderSetupViewModel @Inject constructor(
deviceId: String = "",
deviceId2: String = "",
signature: String = "",
- stalkerAdvancedOptionsJson: String = ""
+ stalkerAdvancedOptionsJson: String = "",
+ protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
+ repairConnection: Boolean = false
) {
+ val current = _uiState.value
+ submitStalker(
+ StalkerProviderSetupCommand(
+ portalUrl = portalUrl,
+ macAddress = macAddress,
+ authMode = authMode,
+ username = username,
+ password = password,
+ name = name,
+ httpUserAgent = httpUserAgent,
+ httpHeaders = httpHeaders,
+ deviceProfile = deviceProfile,
+ timezone = timezone,
+ locale = locale,
+ serialNumber = serialNumber,
+ deviceId = deviceId,
+ deviceId2 = deviceId2,
+ signature = signature,
+ stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,
+ protocolPreference = protocolPreference,
+ repairConnection = repairConnection,
+ requestedProfileId = requestedProfileId,
+ epgSyncMode = current.epgSyncMode,
+ catalogMode = current.stalkerCatalogMode,
+ guideSourcePolicy = current.guideSourcePolicy,
+ channelLogoSourcePolicy = current.channelLogoSourcePolicy,
+ existingProviderId = current.existingProviderId.takeIf { current.isEditing }
+ )
+ )
+ }
+
+ fun acceptStalkerTransportChallenge() {
+ val challenge = _uiState.value.stalkerTransportChallenge ?: return
+ val command = pendingStalkerCommand ?: return
+ if (challenge.reason == StalkerTransportChallengeReason.INVALID_TLS &&
+ challenge.proposedSpkiSha256.isNullOrBlank()
+ ) {
+ _uiState.update {
+ it.copy(
+ stalkerTransportChallenge = null,
+ error = "The provider certificate could not be read safely. Check the address and try again."
+ )
+ }
+ pendingStalkerCommand = null
+ return
+ }
+ _uiState.update { it.copy(stalkerTransportChallenge = null) }
+ pendingStalkerCommand = null
+ submitStalker(command.copy(transportGrant = challenge.acceptedGrant()))
+ }
+
+ fun dismissStalkerTransportChallenge() {
+ pendingStalkerCommand = null
+ _uiState.update {
+ it.copy(
+ stalkerTransportChallenge = null,
+ isLoading = false,
+ syncProgress = null
+ )
+ }
+ }
+
+ fun saveStalkerWithoutVerification() {
+ val command = pendingStalkerCommand ?: return
+ pendingStalkerCommand = null
+ _uiState.update { it.copy(stalkerVerificationInconclusive = null) }
+ submitStalker(command.copy(saveWithoutVerification = true))
+ }
+
+ fun dismissStalkerVerificationInconclusive() {
+ pendingStalkerCommand = null
+ _uiState.update {
+ it.copy(
+ stalkerVerificationInconclusive = null,
+ isLoading = false,
+ syncProgress = null
+ )
+ }
+ }
+
+ fun cancelStalkerSetup() {
+ stalkerSetupJob?.cancel()
+ stalkerSetupJob = null
+ pendingStalkerCommand = null
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ syncProgress = null,
+ stalkerTransportChallenge = null,
+ stalkerVerificationInconclusive = null
+ )
+ }
+ }
+
+ private fun submitStalker(command: StalkerProviderSetupCommand) {
_uiState.update {
it.copy(
validationError = null,
error = null,
completionWarning = null,
onboardingCompletion = OnboardingCompletion.NONE,
- loginSuccess = false
+ loginSuccess = false,
+ stalkerTransportChallenge = null,
+ stalkerVerificationInconclusive = null
)
}
-
- viewModelScope.launch {
- _uiState.update { it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...") }
- val existingId = if (_uiState.value.isEditing) _uiState.value.existingProviderId else null
-
+ stalkerSetupJob?.cancel()
+ stalkerSetupJob = viewModelScope.launch {
+ _uiState.update {
+ it.copy(isLoading = true, validationError = null, syncProgress = "Connecting...")
+ }
when (val result = validateAndAddProvider.loginStalker(
- StalkerProviderSetupCommand(
- portalUrl = portalUrl,
- macAddress = macAddress,
- authMode = authMode,
- username = username,
- password = password,
- name = name,
- httpUserAgent = httpUserAgent,
- httpHeaders = httpHeaders,
- deviceProfile = deviceProfile,
- timezone = timezone,
- locale = locale,
- serialNumber = serialNumber,
- deviceId = deviceId,
- deviceId2 = deviceId2,
- signature = signature,
- stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,
- epgSyncMode = _uiState.value.epgSyncMode,
- guideSourcePolicy = _uiState.value.guideSourcePolicy,
- channelLogoSourcePolicy = _uiState.value.channelLogoSourcePolicy,
- existingProviderId = existingId
- ),
+ command,
onProgress = { msg -> _uiState.update { it.copy(syncProgress = msg) } }
)) {
is ValidateAndAddProviderResult.Success -> {
+ pendingStalkerCommand = null
_uiState.update {
it.copy(
isLoading = false,
@@ -354,6 +459,7 @@ class ProviderSetupViewModel @Inject constructor(
}
}
is ValidateAndAddProviderResult.SavedWithWarning -> {
+ pendingStalkerCommand = null
_uiState.update {
it.copy(
isLoading = false,
@@ -368,11 +474,37 @@ class ProviderSetupViewModel @Inject constructor(
}
}
is ValidateAndAddProviderResult.ValidationError -> {
+ pendingStalkerCommand = null
_uiState.update {
it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)
}
}
+ is ValidateAndAddProviderResult.TransportConsentRequired -> {
+ pendingStalkerCommand = command
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ syncProgress = null,
+ error = null,
+ validationError = null,
+ stalkerTransportChallenge = result.challenge
+ )
+ }
+ }
+ is ValidateAndAddProviderResult.VerificationInconclusive -> {
+ pendingStalkerCommand = command
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ syncProgress = null,
+ error = null,
+ validationError = null,
+ stalkerVerificationInconclusive = result.message
+ )
+ }
+ }
is ValidateAndAddProviderResult.Error -> {
+ pendingStalkerCommand = null
_uiState.update {
it.copy(
isLoading = false,
@@ -457,6 +589,17 @@ class ProviderSetupViewModel @Inject constructor(
it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)
}
}
+ is ValidateAndAddProviderResult.TransportConsentRequired,
+ is ValidateAndAddProviderResult.VerificationInconclusive -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ error = "A transport warning was returned for a non-Stalker provider.",
+ validationError = null,
+ syncProgress = null
+ )
+ }
+ }
is ValidateAndAddProviderResult.Error -> {
_uiState.update {
it.copy(
@@ -567,6 +710,17 @@ class ProviderSetupViewModel @Inject constructor(
it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)
}
}
+ is ValidateAndAddProviderResult.TransportConsentRequired,
+ is ValidateAndAddProviderResult.VerificationInconclusive -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ error = "A transport warning was returned for a non-Stalker provider.",
+ validationError = null,
+ syncProgress = null
+ )
+ }
+ }
is ValidateAndAddProviderResult.Error -> {
_uiState.update {
it.copy(
@@ -643,6 +797,17 @@ class ProviderSetupViewModel @Inject constructor(
it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)
}
}
+ is ValidateAndAddProviderResult.TransportConsentRequired,
+ is ValidateAndAddProviderResult.VerificationInconclusive -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ error = "A transport warning was returned for a non-Stalker provider.",
+ validationError = null,
+ syncProgress = null
+ )
+ }
+ }
is ValidateAndAddProviderResult.Error -> {
_uiState.update {
it.copy(
@@ -721,6 +886,17 @@ class ProviderSetupViewModel @Inject constructor(
it.copy(isLoading = false, validationError = result.message, error = null, syncProgress = null)
}
}
+ is ValidateAndAddProviderResult.TransportConsentRequired,
+ is ValidateAndAddProviderResult.VerificationInconclusive -> {
+ _uiState.update {
+ it.copy(
+ isLoading = false,
+ error = "A transport warning was returned for a non-Stalker provider.",
+ validationError = null,
+ syncProgress = null
+ )
+ }
+ }
is ValidateAndAddProviderResult.Error -> {
_uiState.update {
it.copy(
@@ -1084,6 +1260,10 @@ data class ProviderSetupState(
val stalkerDeviceId2: String = "",
val stalkerSignature: String = "",
val stalkerAdvancedOptionsJson: String = "",
+ val stalkerProtocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ val stalkerTransportChallenge: StalkerTransportChallenge? = null,
+ val stalkerVerificationInconclusive: String? = null,
+ val stalkerRequestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
val jellyfinQuickConnectCode: String = "",
val createdProviderId: Long? = null,
val createdProviderName: String? = null,
@@ -1096,6 +1276,7 @@ data class ProviderSetupState(
val pendingDriveCredentials: List<ProviderCredentials>? = null,
val driveSignedIn: Boolean = false,
val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,
+ val stalkerCatalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,
val xtreamLiveSyncMode: ProviderXtreamLiveSyncMode = ProviderXtreamLiveSyncMode.AUTO,
val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,
val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
index 2d32ae5c..aee0c4b3 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/search/SearchScreen.kt
@@ -57,6 +57,7 @@ import com.streamvault.app.ui.interaction.mouseClickable
import com.streamvault.app.ui.theme.*
import com.streamvault.domain.manager.ParentalControlManager
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.CatalogCompleteness
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.SearchHistoryScope
@@ -191,7 +192,9 @@ class SearchViewModel @Inject constructor(
else results.series,
isLoading = false,
hasSearched = true,
- hasSearchError = results.isPartialResult,
+ hasSearchError = results.isPartialResult &&
+ results.catalogCompleteness == CatalogCompleteness.COMPLETE,
+ catalogCompleteness = results.catalogCompleteness,
parentalControlLevel = level,
hasActiveProvider = true,
queryLength = trimmedQueryLength,
@@ -243,6 +246,13 @@ class SearchViewModel @Inject constructor(
onSearchSubmitted()
}
+ fun buildCompleteStalkerSearchIndex() {
+ val providerId = _activeProviderId.value ?: return
+ viewModelScope.launch {
+ providerRepository.buildStalkerSearchIndexOnce(providerId)
+ }
+ }
+
fun clearRecentQueries() {
viewModelScope.launch {
preferencesRepository.clearRecentSearchQueries(
@@ -343,7 +353,8 @@ data class SearchUiState(
val parentalControlLevel: Int = 0,
val hasActiveProvider: Boolean = false,
val queryLength: Int = 0,
- val unlockedCategoryIds: Set<Long> = emptySet()
+ val unlockedCategoryIds: Set<Long> = emptySet(),
+ val catalogCompleteness: CatalogCompleteness = CatalogCompleteness.COMPLETE
) {
val isEmpty: Boolean get() = hasSearched && channels.isEmpty() && movies.isEmpty() && series.isEmpty()
val totalResults: Int get() = channels.size + movies.size + series.size
@@ -608,7 +619,8 @@ fun SearchScreen(
else -> {
item {
SearchResultsSummaryRow(
- uiState = uiState
+ uiState = uiState,
+ onBuildCompleteIndex = viewModel::buildCompleteStalkerSearchIndex
)
}
@@ -1114,7 +1126,8 @@ fun SectionHeader(title: String) {
@OptIn(ExperimentalTvMaterial3Api::class)
@Composable
private fun SearchResultsSummaryRow(
- uiState: SearchUiState
+ uiState: SearchUiState,
+ onBuildCompleteIndex: () -> Unit
) {
val countsSummary = listOf(
stringResource(R.string.search_results_count, stringResource(R.string.search_live_tv), uiState.channels.size),
@@ -1140,6 +1153,27 @@ private fun SearchResultsSummaryRow(
maxLines = 1,
overflow = TextOverflow.Ellipsis
)
+ if (uiState.catalogCompleteness != CatalogCompleteness.COMPLETE) {
+ Text(
+ text = stringResource(
+ when (uiState.catalogCompleteness) {
+ CatalogCompleteness.INDEXING -> R.string.search_catalog_indexing
+ CatalogCompleteness.TRUNCATED -> R.string.search_catalog_truncated
+ CatalogCompleteness.PARTIAL -> R.string.search_catalog_downloaded_only
+ CatalogCompleteness.COMPLETE -> R.string.search_catalog_complete
+ }
+ ),
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.Warning
+ )
+ if (uiState.catalogCompleteness == CatalogCompleteness.PARTIAL ||
+ uiState.catalogCompleteness == CatalogCompleteness.TRUNCATED
+ ) {
+ Button(onClick = onBuildCompleteIndex) {
+ Text(stringResource(R.string.search_build_complete_index))
+ }
+ }
+ }
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
index a768804f..eda23d11 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesScreen.kt
@@ -742,7 +742,7 @@ private fun SeriesVodContent(
val modernGridState = androidx.compose.foundation.lazy.grid.rememberLazyGridState()
InfiniteScrollEffect(
gridState = modernGridState,
- enabled = !uiState.isReorderMode,
+ enabled = uiState.vodInfiniteScroll && !uiState.isReorderMode,
canLoadMore = uiState.canLoadMoreSelectedCategory,
isLoading = uiState.isLoadingSelectedCategory,
onLoadMore = onLoadMore
@@ -902,6 +902,21 @@ private fun SeriesVodContent(
)
}
}
+ if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory &&
+ !uiState.vodInfiniteScroll && !uiState.isReorderMode
+ ) {
+ item(key = "load_next_series_batch", span = { GridItemSpan(maxLineSpan) }) {
+ LoadMoreCard(
+ label = stringResource(
+ R.string.library_load_more,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ onClick = onLoadMore,
+ modifier = Modifier.padding(vertical = 12.dp)
+ )
+ }
+ }
}
}
@@ -1164,7 +1179,7 @@ private fun SeriesVodClassicContent(
val classicGridState = androidx.compose.foundation.lazy.grid.rememberLazyGridState()
InfiniteScrollEffect(
gridState = classicGridState,
- enabled = !uiState.isReorderMode,
+ enabled = uiState.vodInfiniteScroll && !uiState.isReorderMode,
canLoadMore = uiState.canLoadMoreSelectedCategory,
isLoading = uiState.isLoadingSelectedCategory,
onLoadMore = onLoadMore
@@ -1234,6 +1249,21 @@ private fun SeriesVodClassicContent(
)
}
}
+ if (uiState.canLoadMoreSelectedCategory && !uiState.isLoadingSelectedCategory &&
+ !uiState.vodInfiniteScroll && !uiState.isReorderMode
+ ) {
+ item(key = "load_next_series_batch_classic", span = { GridItemSpan(maxLineSpan) }) {
+ LoadMoreCard(
+ label = stringResource(
+ R.string.library_load_more,
+ uiState.selectedCategoryLoadedCount,
+ uiState.selectedCategoryTotalCount
+ ),
+ onClick = onLoadMore,
+ modifier = Modifier.padding(vertical = 12.dp)
+ )
+ }
+ }
}
}
}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
index 7b861f7f..8979742d 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/series/SeriesViewModel.kt
@@ -298,6 +298,31 @@ class SeriesViewModel @Inject constructor(
}
}
+ viewModelScope.launch {
+ providerRepository.getActiveProvider()
+ .filterNotNull()
+ .flatMapLatest { provider ->
+ combine(
+ seriesRepository.getCategoryItemCounts(provider.id),
+ seriesRepository.getLibraryCount(provider.id),
+ seriesRepository.getCategories(provider.id)
+ ) { counts, libraryCount, categories ->
+ Triple(counts, libraryCount, categories)
+ }
+ }
+ .collectLatest { (counts, libraryCount, categories) ->
+ val countsByName = categories.associate { category ->
+ category.name to (counts[category.id] ?: 0)
+ }
+ _uiState.update { state ->
+ state.copy(
+ categoryCounts = state.categoryCounts + countsByName,
+ libraryCount = libraryCount
+ )
+ }
+ }
+ }
+
viewModelScope.launch {
providerRepository.getActiveProvider()
.filterNotNull()
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt
index df199ae8..acd3e561 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderComponents.kt
@@ -118,7 +118,13 @@ internal fun ProviderSettingsCard(
color = OnSurface
)
}
- ProviderStatusBadge(status = provider.status)
+ ProviderStatusBadge(
+ status = provider.status,
+ requiresAttention = provider.type == ProviderType.STALKER_PORTAL &&
+ provider.status == ProviderStatus.PARTIAL &&
+ provider.stalkerTransportMode ==
+ com.streamvault.domain.model.StalkerTransportMode.AUTO_STRICT
+ )
if (isActive) {
Text(
text = stringResource(R.string.settings_active),
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.kt
index 45d834c4..46575e5a 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderDiagnosticsPanel.kt
@@ -60,6 +60,81 @@ internal fun ProviderDiagnosticsPanel(
style = MaterialTheme.typography.bodySmall,
color = OnSurfaceDim
)
+ if (provider.type == ProviderType.STALKER_PORTAL) {
+ Text(
+ text = buildString {
+ append("Protocol: ")
+ append(provider.stalkerProtocolFamily.name.replace('_', ' '))
+ append(" • Requested: ")
+ append(provider.stalkerRequestedProfileId)
+ append(" • Winner: ")
+ append(provider.stalkerLearnedProfileId.ifBlank { "not validated" })
+ append(" • Endpoint: ")
+ append(provider.stalkerEndpointPreference.name.replace('_', ' '))
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurface
+ )
+ Text(
+ text = buildString {
+ append("Catalog: ")
+ append(if (provider.stalkerLearnedProfileId.isBlank()) "not validated" else "validated")
+ append(" • Identity: ")
+ append(
+ if (provider.stalkerSerialNumber.isNotBlank() || provider.stalkerDeviceId.isNotBlank()) {
+ "manual fields"
+ } else {
+ "MAC first"
+ }
+ )
+ append(" • Verification: ")
+ append(provider.stalkerProfileVerification.name)
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ Text(
+ text = buildString {
+ append("Transport: ")
+ append(provider.stalkerTransportMode.name.replace('_', ' '))
+ provider.stalkerTransportOrigin.takeIf(String::isNotBlank)?.let { origin ->
+ append(" • Origin: ")
+ append(origin)
+ }
+ if (provider.stalkerTransportConsentAt > 0L) {
+ append(" • User approved")
+ }
+ append(" • Generation: ")
+ append(provider.stalkerConfigurationGeneration)
+ if (provider.lastSyncedAt > 0L) {
+ append(" | Last verification: ")
+ append(
+ DateFormat.getDateTimeInstance(
+ DateFormat.MEDIUM,
+ DateFormat.SHORT,
+ Locale.getDefault()
+ ).format(java.util.Date(provider.lastSyncedAt))
+ )
+ }
+ },
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ provider.stalkerCapabilitiesJson.takeIf(String::isNotBlank)?.let { states ->
+ Text(
+ text = "Capabilities: $states",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ provider.stalkerDiscoverySummary.takeIf(String::isNotBlank)?.let { summary ->
+ Text(
+ text = "Last discovery: $summary",
+ style = MaterialTheme.typography.bodySmall,
+ color = OnSurfaceDim
+ )
+ }
+ }
Text(
text = stringResource(R.string.settings_diagnostic_status, diagnostics.lastSyncStatus),
style = MaterialTheme.typography.labelSmall,
@@ -225,4 +300,4 @@ private fun formatMaintenanceCount(value: Long): String = when {
value >= 1_000_000L -> String.format(Locale.US, "%.1fM", value / 1_000_000.0)
value >= 1_000L -> String.format(Locale.US, "%.1fk", value / 1_000.0)
else -> value.toString()
-}
\ No newline at end of file
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.kt b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.kt
index e331fcec..dcc6ebb7 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/settings/SettingsProviderUiComponents.kt
@@ -168,10 +168,19 @@ internal fun ProviderCatalogCountUiModel.shouldShowCatalogStatusTag(): Boolean =
status != ProviderCatalogCountStatus.PENDING && status != ProviderCatalogCountStatus.READY
@Composable
-internal fun ProviderStatusBadge(status: ProviderStatus) {
+internal fun ProviderStatusBadge(
+ status: ProviderStatus,
+ requiresAttention: Boolean = false
+) {
val (label, color) = when (status) {
ProviderStatus.ACTIVE -> stringResource(R.string.settings_status_active) to Primary
- ProviderStatus.PARTIAL -> stringResource(R.string.settings_status_partial) to Secondary
+ ProviderStatus.PARTIAL -> stringResource(
+ if (requiresAttention) {
+ R.string.settings_status_requires_attention
+ } else {
+ R.string.settings_status_partial
+ }
+ ) to Secondary
ProviderStatus.ERROR -> stringResource(R.string.settings_status_error) to ErrorColor
ProviderStatus.EXPIRED -> stringResource(R.string.settings_status_expired) to ErrorColor
ProviderStatus.DISABLED -> stringResource(R.string.settings_status_disabled) to OnSurfaceDim
@@ -187,4 +196,4 @@ internal fun ProviderStatusBadge(status: ProviderStatus) {
.background(color.copy(alpha = 0.16f), RoundedCornerShape(4.dp))
.padding(horizontal = 8.dp, vertical = 4.dp)
)
-}
\ No newline at end of file
+}
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 4d10e0af..61f13653 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -801,6 +801,7 @@
<string name="settings_retry_series">Retry Series</string>
<string name="settings_status_active">Active</string>
<string name="settings_status_partial">Partial</string>
+ <string name="settings_status_requires_attention">Requires attention</string>
<string name="settings_status_error">Error</string>
<string name="settings_status_expired">Expired</string>
<string name="settings_status_disabled">Disabled</string>
@@ -988,6 +989,11 @@
<string name="search_no_provider_title">No active provider</string>
<string name="search_no_provider_subtitle">Add or activate a provider before searching the library.</string>
<string name="search_results_title">%1$d results</string>
+ <string name="search_catalog_downloaded_only">Downloaded items only. Build the complete search index to search the full portal catalog.</string>
+ <string name="search_catalog_indexing">The complete search index is being built. Results are still partial.</string>
+ <string name="search_catalog_truncated">The portal catalog was truncated. Results may be incomplete.</string>
+ <string name="search_catalog_complete">Complete catalog index</string>
+ <string name="search_build_complete_index">Build complete search index once</string>
<string name="search_results_count">%1$s %2$d</string>
<string name="search_live_tv">Live TV</string>
<string name="search_all">All</string>
@@ -1781,4 +1787,16 @@
<string name="settings_remote_selection_global_default">Use global default: %1$s</string>
<string name="settings_remote_dialog_title">%1$s action</string>
<string name="settings_remote_dialog_subtitle">Choose what this colored button should do in %1$s.</string>
+ <string name="stalker_transport_invalid_tls_title" translatable="false">This provider\'s security certificate can\'t be verified</string>
+ <string name="stalker_transport_invalid_tls_body" translatable="false">The connection to %1$s may still be encrypted, but the app can\'t confirm it is really this provider. Someone on the network could read your login or stream details.</string>
+ <string name="stalker_transport_http_title" translatable="false">This provider uses an unencrypted connection</string>
+ <string name="stalker_transport_http_body" translatable="false">Your login and viewing requests to %1$s can be read or changed by someone on the network.</string>
+ <string name="stalker_transport_origin_changed_title" translatable="false">This provider wants to use a different address</string>
+ <string name="stalker_transport_origin_changed_body" translatable="false">The provider redirected the connection to %1$s. Continue only if you recognize this address.</string>
+ <string name="stalker_transport_go_back" translatable="false">Go back</string>
+ <string name="stalker_transport_connect_anyway" translatable="false">Connect anyway</string>
+ <string name="stalker_verification_inconclusive_title" translatable="false">Live TV could not be verified</string>
+ <string name="stalker_verification_inconclusive_body" translatable="false">The provider accepted your login, but the Live TV check did not finish. You can save it with verification pending; it will remain inactive until a sync confirms playable Live TV.</string>
+ <string name="stalker_save_without_verification" translatable="false">Save without verification</string>
+ <string name="stalker_repair_connection" translatable="false">Repair connection</string>
</resources>
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.kt
index 09016fb6..5b6bd033 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
@@ -9,6 +9,10 @@ import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderEpgSyncMode
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.model.StalkerTransportChallenge
+import com.streamvault.domain.model.StalkerTransportChallengeReason
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
import com.streamvault.domain.repository.CombinedM3uRepository
import com.streamvault.domain.repository.ProviderRepository
import com.streamvault.domain.manager.BackupImportPlan
@@ -32,6 +36,7 @@ import org.junit.After
import org.junit.Before
import org.junit.Test
import org.mockito.kotlin.any
+import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
@@ -424,4 +429,154 @@ class ProviderSetupViewModelTest {
assertThat(error).doesNotContain("initial sync failed. The provider was saved")
assertThat(error).contains("sync failed")
}
+
+ @Test
+ fun `accepting HTTP warning resubmits same Stalker setup with scoped grant`() = runTest {
+ val challenge = StalkerTransportChallenge(
+ reason = StalkerTransportChallengeReason.CLEARTEXT_HTTP,
+ origin = StalkerTransportOrigin("http", "portal.example.com", 80),
+ displayHost = "portal.example.com"
+ )
+ val provider = Provider(
+ id = 22L,
+ name = "MAG",
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = "http://portal.example.com"
+ )
+ whenever(validateAndAddProvider.loginStalker(any(), any()))
+ .thenReturn(
+ ValidateAndAddProviderResult.TransportConsentRequired(challenge),
+ ValidateAndAddProviderResult.Success(provider)
+ )
+ val viewModel = ProviderSetupViewModel(
+ providerRepository = providerRepository,
+ combinedM3uRepository = combinedM3uRepository,
+ validateAndAddProvider = validateAndAddProvider,
+ importBackup = importBackup,
+ driveBackupSyncManager = driveBackupSyncManager,
+ providerQrPairingManager = providerQrPairingManager,
+ )
+
+ viewModel.loginStalker(
+ portalUrl = "http://portal.example.com",
+ macAddress = "00:1A:79:12:34:56",
+ authMode = StalkerAuthMode.AUTO,
+ username = "",
+ password = "secret",
+ name = "MAG",
+ httpUserAgent = "",
+ httpHeaders = "",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ advanceUntilIdle()
+
+ assertThat(viewModel.uiState.value.stalkerTransportChallenge).isEqualTo(challenge)
+ assertThat(viewModel.uiState.value.loginSuccess).isFalse()
+
+ viewModel.acceptStalkerTransportChallenge()
+ advanceUntilIdle()
+
+ val commands = argumentCaptor<com.streamvault.domain.usecase.StalkerProviderSetupCommand>()
+ verify(validateAndAddProvider, org.mockito.kotlin.times(2))
+ .loginStalker(commands.capture(), any())
+ assertThat(commands.secondValue.transportGrant?.mode)
+ .isEqualTo(StalkerTransportMode.USER_ACCEPTED_HTTP)
+ assertThat(commands.secondValue.transportGrant?.origin).isEqualTo(challenge.origin)
+ assertThat(viewModel.uiState.value.loginSuccess).isTrue()
+ assertThat(viewModel.uiState.value.stalkerTransportChallenge).isNull()
+ }
+
+ @Test
+ fun `save without verification is offered only after inconclusive result and resubmits command`() = runTest {
+ val provider = Provider(
+ id = 23L,
+ name = "MAG",
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = "https://portal.example.com"
+ )
+ whenever(validateAndAddProvider.loginStalker(any(), any()))
+ .thenReturn(
+ ValidateAndAddProviderResult.VerificationInconclusive(
+ "Authentication succeeded, but Live TV could not be verified."
+ ),
+ ValidateAndAddProviderResult.SavedWithWarning(
+ provider,
+ "Provider saved with Live TV verification pending."
+ )
+ )
+ val viewModel = ProviderSetupViewModel(
+ providerRepository = providerRepository,
+ combinedM3uRepository = combinedM3uRepository,
+ validateAndAddProvider = validateAndAddProvider,
+ importBackup = importBackup,
+ driveBackupSyncManager = driveBackupSyncManager,
+ providerQrPairingManager = providerQrPairingManager,
+ )
+
+ viewModel.loginStalker(
+ portalUrl = "https://portal.example.com",
+ macAddress = "00:1A:79:12:34:56",
+ authMode = StalkerAuthMode.AUTO,
+ username = "",
+ password = "secret",
+ name = "MAG",
+ httpUserAgent = "",
+ httpHeaders = "",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ advanceUntilIdle()
+
+ assertThat(viewModel.uiState.value.stalkerVerificationInconclusive).isNotNull()
+ viewModel.saveStalkerWithoutVerification()
+ advanceUntilIdle()
+
+ val commands = argumentCaptor<com.streamvault.domain.usecase.StalkerProviderSetupCommand>()
+ verify(validateAndAddProvider, org.mockito.kotlin.times(2))
+ .loginStalker(commands.capture(), any())
+ assertThat(commands.firstValue.saveWithoutVerification).isFalse()
+ assertThat(commands.secondValue.saveWithoutVerification).isTrue()
+ assertThat(commands.secondValue.password).isEqualTo("secret")
+ assertThat(viewModel.uiState.value.onboardingCompletion)
+ .isEqualTo(ProviderSetupViewModel.OnboardingCompletion.SAVED_RESUMING)
+ assertThat(viewModel.uiState.value.stalkerVerificationInconclusive).isNull()
+ }
+
+ @Test
+ fun `repair connection submits explicit broad discovery permission`() = runTest {
+ whenever(validateAndAddProvider.loginStalker(any(), any())).thenReturn(
+ ValidateAndAddProviderResult.Error("repair fixture")
+ )
+ val viewModel = ProviderSetupViewModel(
+ providerRepository = providerRepository,
+ combinedM3uRepository = combinedM3uRepository,
+ validateAndAddProvider = validateAndAddProvider,
+ importBackup = importBackup,
+ driveBackupSyncManager = driveBackupSyncManager,
+ providerQrPairingManager = providerQrPairingManager,
+ )
+
+ viewModel.loginStalker(
+ portalUrl = "https://portal.example.com",
+ macAddress = "00:1A:79:12:34:56",
+ authMode = StalkerAuthMode.AUTO,
+ username = "",
+ password = "",
+ name = "MAG",
+ httpUserAgent = "",
+ httpHeaders = "",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ repairConnection = true
+ )
+ advanceUntilIdle()
+
+ val command = argumentCaptor<com.streamvault.domain.usecase.StalkerProviderSetupCommand>()
+ verify(validateAndAddProvider).loginStalker(command.capture(), any())
+ assertThat(command.firstValue.repairConnection).isTrue()
+ }
}
diff --git a/data/build.gradle.kts b/data/build.gradle.kts
index 3c834090..81255e4d 100644
--- a/data/build.gradle.kts
+++ b/data/build.gradle.kts
@@ -91,6 +91,8 @@ dependencies {
testImplementation(libs.junit)
testImplementation(libs.truth)
testImplementation(libs.coroutines.test)
+ testImplementation(libs.okhttp.mockwebserver)
+ testImplementation(libs.okhttp.tls)
// kxml2: JVM XmlPullParser implementation needed for XmltvParser unit tests
// (Android platform provides its own impl; the JVM test runner needs an explicit one)
testImplementation(libs.kxml2)
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/63.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/63.json
new file mode 100644
index 00000000..e5333c7d
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/63.json
@@ -0,0 +1,5704 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 63,
+ "identityHash": "7f6096b23700f2a89efac4d922c05216",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `stalker_catalog_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "httpUserAgent",
+ "columnName": "http_user_agent",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "httpHeaders",
+ "columnName": "http_headers",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMacAddress",
+ "columnName": "stalker_mac_address",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceProfile",
+ "columnName": "stalker_device_profile",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceTimezone",
+ "columnName": "stalker_device_timezone",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceLocale",
+ "columnName": "stalker_device_locale",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerSerialNumber",
+ "columnName": "stalker_serial_number",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceId",
+ "columnName": "stalker_device_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceId2",
+ "columnName": "stalker_device_id2",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerSignature",
+ "columnName": "stalker_signature",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerAdvancedOptionsJson",
+ "columnName": "stalker_advanced_options_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerAuthMode",
+ "columnName": "stalker_auth_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPortalProfile",
+ "columnName": "stalker_portal_profile",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPortalFingerprint",
+ "columnName": "stalker_portal_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMagPreset",
+ "columnName": "stalker_mag_preset",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerLastBootstrapRecipe",
+ "columnName": "stalker_last_bootstrap_recipe",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerEndpointPreference",
+ "columnName": "stalker_endpoint_preference",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerCookieMode",
+ "columnName": "stalker_cookie_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPlaybackBackendHint",
+ "columnName": "stalker_playback_backend_hint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerLastPlaybackMode",
+ "columnName": "stalker_last_playback_mode",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "stalkerCredentialsRequired",
+ "columnName": "stalker_credentials_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMacRequired",
+ "columnName": "stalker_mac_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerUsesTemporaryLinks",
+ "columnName": "stalker_uses_temp_links",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerModuleRestricted",
+ "columnName": "stalker_module_restricted",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerStrictFingerprintRequired",
+ "columnName": "stalker_strict_fingerprint_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerRecipeFallbackUsed",
+ "columnName": "stalker_recipe_fallback_used",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerRecipeRediscoveryAttempts",
+ "columnName": "stalker_recipe_rediscovery_attempts",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "apiVersion",
+ "columnName": "api_version",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "allowedOutputFormatsJson",
+ "columnName": "allowed_output_formats_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSyncMode",
+ "columnName": "epg_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerCatalogMode",
+ "columnName": "stalker_catalog_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "guideSourcePolicy",
+ "columnName": "guide_source_policy",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelLogoSourcePolicy",
+ "columnName": "channel_logo_source_policy",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xtreamFastSyncEnabled",
+ "columnName": "xtream_fast_sync_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xtreamLiveSyncMode",
+ "columnName": "xtream_live_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uVodClassificationEnabled",
+ "columnName": "m3u_vod_classification_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username_stalker_mac_address",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username",
+ "stalker_mac_address"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"
+ }
+ ]
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "qualityOptionsJson",
+ "columnName": "quality_options_json",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "audioVideoOffsetMs",
+ "columnName": "audio_video_offset_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cacheState",
+ "columnName": "cache_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteStaleAt",
+ "columnName": "remote_stale_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_rating_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "rating",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_added_at_release_date_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "added_at",
+ "release_date",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerSeriesId",
+ "columnName": "provider_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cacheState",
+ "columnName": "cache_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteStaleAt",
+ "columnName": "remote_stale_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ },
+ {
+ "name": "index_series_provider_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_rating_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "rating",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_last_modified_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "last_modified",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_last_modified_name_id` ON `${TABLE_NAME}` (`provider_id`, `last_modified`, `name`, `id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channel_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movie_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerSeriesId",
+ "columnName": "provider_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerSeriesKey",
+ "columnName": "provider_series_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "provider_series_key"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "category_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "category_id",
+ "type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_category_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_end_time_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "end_time",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "groupKey",
+ "columnName": "group_key",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_provider_id_content_id_content_type_group_key",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "content_id",
+ "content_type",
+ "group_key"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"
+ },
+ {
+ "name": "index_favorites_provider_id_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_provider_id_content_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"
+ },
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_playback_history_provider_id_content_type_content_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"
+ },
+ {
+ "name": "index_playback_history_provider_id_content_type_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "tmdb_identity",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "canonicalProviderId",
+ "columnName": "canonical_provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "firstSeenAt",
+ "columnName": "first_seen_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "tmdb_id",
+ "content_type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_tmdb_identity_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ },
+ {
+ "name": "index_tmdb_identity_canonical_provider_id",
+ "unique": false,
+ "columnNames": [
+ "canonical_provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "canonical_provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "search_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "query",
+ "columnName": "query",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentScope",
+ "columnName": "content_scope",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "usedAt",
+ "columnName": "used_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "useCount",
+ "columnName": "use_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_search_history_content_scope_provider_id_used_at",
+ "unique": false,
+ "columnNames": [
+ "content_scope",
+ "provider_id",
+ "used_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"
+ },
+ {
+ "name": "index_search_history_used_at",
+ "unique": false,
+ "columnNames": [
+ "used_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"
+ },
+ {
+ "name": "index_search_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_search_history_query_content_scope_provider_id",
+ "unique": true,
+ "columnNames": [
+ "query",
+ "content_scope",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSuccess",
+ "columnName": "last_live_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSuccess",
+ "columnName": "last_series_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSuccess",
+ "columnName": "last_epg_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveAvoidFullUntil",
+ "columnName": "live_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieAvoidFullUntil",
+ "columnName": "movie_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesAvoidFullUntil",
+ "columnName": "series_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveSequentialFailuresRemembered",
+ "columnName": "live_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveHealthySyncStreak",
+ "columnName": "live_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesSequentialFailuresRemembered",
+ "columnName": "series_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesHealthySyncStreak",
+ "columnName": "series_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastLoadedPage",
+ "columnName": "last_loaded_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastAttemptedPage",
+ "columnName": "last_attempted_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessfulPage",
+ "columnName": "last_successful_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalPages",
+ "columnName": "total_pages",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryAfterMs",
+ "columnName": "retry_after_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryBudgetRemaining",
+ "columnName": "retry_budget_remaining",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastPageFingerprint",
+ "columnName": "last_page_fingerprint",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastLoadedPage",
+ "columnName": "last_loaded_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastAttemptedPage",
+ "columnName": "last_attempted_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessfulPage",
+ "columnName": "last_successful_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalPages",
+ "columnName": "total_pages",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryAfterMs",
+ "columnName": "retry_after_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryBudgetRemaining",
+ "columnName": "retry_budget_remaining",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastPageFingerprint",
+ "columnName": "last_page_fingerprint",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_sources",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "url",
+ "columnName": "url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastRefreshAt",
+ "columnName": "last_refresh_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "etag",
+ "columnName": "etag",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModifiedHeader",
+ "columnName": "last_modified_header",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_sources_url",
+ "unique": true,
+ "columnNames": [
+ "url"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"
+ }
+ ]
+ },
+ {
+ "tableName": "provider_epg_sources",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_epg_sources_provider_id_epg_source_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"
+ },
+ {
+ "name": "index_provider_epg_sources_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "display_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "normalizedName",
+ "columnName": "normalized_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconUrl",
+ "columnName": "icon_url",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",
+ "unique": true,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"
+ },
+ {
+ "name": "index_epg_channels_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ },
+ {
+ "name": "index_epg_channels_normalized_name",
+ "unique": false,
+ "columnNames": [
+ "normalized_name"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_programmes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "subtitle",
+ "columnName": "subtitle",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeInfo",
+ "columnName": "episode_info",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_epg_programmes_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ },
+ {
+ "name": "index_epg_programmes_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_epg_mappings",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerChannelId",
+ "columnName": "provider_channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceType",
+ "columnName": "source_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "matchType",
+ "columnName": "match_type",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "confidence",
+ "columnName": "confidence",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "matchedAt",
+ "columnName": "matched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedAttempts",
+ "columnName": "failed_attempts",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "source",
+ "columnName": "source",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isManualOverride",
+ "columnName": "is_manual_override",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "provider_channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"
+ },
+ {
+ "name": "index_channel_epg_mappings_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "combined_m3u_profiles",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ }
+ },
+ {
+ "tableName": "combined_m3u_profile_members",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "profileId",
+ "columnName": "profile_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_combined_m3u_profile_members_profile_id",
+ "unique": false,
+ "columnNames": [
+ "profile_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"
+ },
+ {
+ "name": "index_combined_m3u_profile_members_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",
+ "unique": true,
+ "columnNames": [
+ "profile_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "combined_m3u_profiles",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "profile_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_schedules",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "requestedStartMs",
+ "columnName": "requested_start_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "requestedEndMs",
+ "columnName": "requested_end_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurrence",
+ "columnName": "recurrence",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurringRuleId",
+ "columnName": "recurring_rule_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isManual",
+ "columnName": "is_manual",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_recording_schedules_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_recording_schedules_enabled_requested_start_ms",
+ "unique": false,
+ "columnNames": [
+ "enabled",
+ "requested_start_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"
+ },
+ {
+ "name": "index_recording_schedules_recurring_rule_id",
+ "unique": false,
+ "columnNames": [
+ "recurring_rule_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_runs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "scheduleId",
+ "columnName": "schedule_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "scheduledStartMs",
+ "columnName": "scheduled_start_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "scheduledEndMs",
+ "columnName": "scheduled_end_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurrence",
+ "columnName": "recurrence",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurringRuleId",
+ "columnName": "recurring_rule_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceType",
+ "columnName": "source_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resolvedUrl",
+ "columnName": "resolved_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "headersJson",
+ "columnName": "headers_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userAgent",
+ "columnName": "user_agent",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "expirationTime",
+ "columnName": "expiration_time",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "providerLabel",
+ "columnName": "provider_label",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputUri",
+ "columnName": "output_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDisplayPath",
+ "columnName": "output_display_path",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bytesWritten",
+ "columnName": "bytes_written",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "averageThroughputBytesPerSecond",
+ "columnName": "average_throughput_bps",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryCount",
+ "columnName": "retry_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastProgressAtMs",
+ "columnName": "last_progress_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "failureCategory",
+ "columnName": "failure_category",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failure_reason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "terminalAtMs",
+ "columnName": "terminal_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "startedAtMs",
+ "columnName": "started_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "endedAtMs",
+ "columnName": "ended_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "scheduleEnabled",
+ "columnName": "schedule_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "alarmStartAtMs",
+ "columnName": "alarm_start_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "alarmStopAtMs",
+ "columnName": "alarm_stop_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_recording_runs_schedule_id",
+ "unique": false,
+ "columnNames": [
+ "schedule_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"
+ },
+ {
+ "name": "index_recording_runs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_recording_runs_status_scheduled_start_ms",
+ "unique": false,
+ "columnNames": [
+ "status",
+ "scheduled_start_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"
+ },
+ {
+ "name": "index_recording_runs_alarm_start_at_ms",
+ "unique": false,
+ "columnNames": [
+ "alarm_start_at_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"
+ },
+ {
+ "name": "index_recording_runs_alarm_stop_at_ms",
+ "unique": false,
+ "columnNames": [
+ "alarm_stop_at_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "recording_schedules",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "schedule_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "program_reminders",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programStartTime",
+ "columnName": "program_start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remindAt",
+ "columnName": "remind_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "leadTimeMinutes",
+ "columnName": "lead_time_minutes",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isDismissed",
+ "columnName": "is_dismissed",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "notifiedAt",
+ "columnName": "notified_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_program_reminders_provider_id_remind_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "remind_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"
+ },
+ {
+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",
+ "unique": false,
+ "columnNames": [
+ "is_dismissed",
+ "notified_at",
+ "remind_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"
+ },
+ {
+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "program_start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"
+ },
+ {
+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "program_title",
+ "program_start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_storage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "treeUri",
+ "columnName": "tree_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "display_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDirectory",
+ "columnName": "output_directory",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "availableBytes",
+ "columnName": "available_bytes",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "isWritable",
+ "columnName": "is_writable",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "fileNamePattern",
+ "columnName": "file_name_pattern",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retentionDays",
+ "columnName": "retention_days",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "maxSimultaneousRecordings",
+ "columnName": "max_simultaneous_recordings",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ }
+ },
+ {
+ "tableName": "playback_compatibility_records",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deviceFingerprint",
+ "columnName": "device_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deviceModel",
+ "columnName": "device_model",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "androidSdk",
+ "columnName": "android_sdk",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamType",
+ "columnName": "stream_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "videoMimeType",
+ "columnName": "video_mime_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resolutionBucket",
+ "columnName": "resolution_bucket",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "decoderName",
+ "columnName": "decoder_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "surfaceType",
+ "columnName": "surface_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureType",
+ "columnName": "failure_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastFailedAt",
+ "columnName": "last_failed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSucceededAt",
+ "columnName": "last_succeeded_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "successCount",
+ "columnName": "success_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",
+ "unique": true,
+ "columnNames": [
+ "device_fingerprint",
+ "stream_type",
+ "video_mime_type",
+ "resolution_bucket",
+ "decoder_name",
+ "surface_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",
+ "unique": false,
+ "columnNames": [
+ "device_fingerprint",
+ "stream_type",
+ "video_mime_type",
+ "resolution_bucket"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_last_failed_at",
+ "unique": false,
+ "columnNames": [
+ "last_failed_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_last_succeeded_at",
+ "unique": false,
+ "columnNames": [
+ "last_succeeded_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_content_index",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `remote_id` TEXT NOT NULL, `local_content_id` INTEGER, `name` TEXT NOT NULL, `category_id` INTEGER, `category_name` TEXT, `image_url` TEXT, `container_extension` TEXT, `rating` REAL NOT NULL, `added_at` INTEGER NOT NULL, `remote_updated_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `indexed_at` INTEGER NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `stale_state` TEXT NOT NULL, `error_state` TEXT, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `remote_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteId",
+ "columnName": "remote_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "localContentId",
+ "columnName": "local_content_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteUpdatedAt",
+ "columnName": "remote_updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedAt",
+ "columnName": "indexed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "staleState",
+ "columnName": "stale_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorState",
+ "columnName": "error_state",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "remote_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_content_index_provider_id_content_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_category_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `category_id`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_name",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "name"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_name` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `name`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_local_content_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "local_content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_local_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `local_content_id`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_indexed_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "indexed_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_indexed_at` ON `${TABLE_NAME}` (`provider_id`, `indexed_at`)"
+ },
+ {
+ "name": "index_xtream_content_index_stale_state",
+ "unique": false,
+ "columnNames": [
+ "stale_state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_stale_state` ON `${TABLE_NAME}` (`stale_state`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_index_jobs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `priority_category_id` INTEGER, `priority_requested_at` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "section",
+ "columnName": "section",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalCategories",
+ "columnName": "total_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedCategories",
+ "columnName": "completed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedCategories",
+ "columnName": "failed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedRows",
+ "columnName": "indexed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "skippedMalformedRows",
+ "columnName": "skipped_malformed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedPrunedRows",
+ "columnName": "deleted_pruned_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priorityCategoryId",
+ "columnName": "priority_category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "priorityRequestedAt",
+ "columnName": "priority_requested_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastAttemptAt",
+ "columnName": "last_attempt_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "section"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_index_jobs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_section",
+ "unique": false,
+ "columnNames": [
+ "section"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_section` ON `${TABLE_NAME}` (`section`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_live_onboarding_state",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `provider_type` TEXT NOT NULL, `content_type` TEXT NOT NULL, `phase` TEXT NOT NULL, `staged_session_id` INTEGER, `import_strategy` TEXT, `next_category_index` INTEGER NOT NULL, `accepted_row_count` INTEGER NOT NULL, `staged_flush_count` INTEGER NOT NULL, `sync_profile_tier` TEXT, `sync_profile_batch_size` INTEGER NOT NULL, `sync_profile_strategy` TEXT, `sync_profile_low_memory` INTEGER NOT NULL, `sync_profile_memory_class_mb` INTEGER NOT NULL, `sync_profile_available_mem_mb` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerType",
+ "columnName": "provider_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "phase",
+ "columnName": "phase",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stagedSessionId",
+ "columnName": "staged_session_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "importStrategy",
+ "columnName": "import_strategy",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "acceptedRowCount",
+ "columnName": "accepted_row_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stagedFlushCount",
+ "columnName": "staged_flush_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileTier",
+ "columnName": "sync_profile_tier",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncProfileBatchSize",
+ "columnName": "sync_profile_batch_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileStrategy",
+ "columnName": "sync_profile_strategy",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncProfileLowMemory",
+ "columnName": "sync_profile_low_memory",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileMemoryClassMb",
+ "columnName": "sync_profile_memory_class_mb",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileAvailableMemMb",
+ "columnName": "sync_profile_available_mem_mb",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedAt",
+ "columnName": "completed_at",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_live_onboarding_state_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_phase",
+ "unique": false,
+ "columnNames": [
+ "phase"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_phase` ON `${TABLE_NAME}` (`phase`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_staged_session_id",
+ "unique": false,
+ "columnNames": [
+ "staged_session_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_staged_session_id` ON `${TABLE_NAME}` (`staged_session_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_index_jobs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "section",
+ "columnName": "section",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalCategories",
+ "columnName": "total_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedCategories",
+ "columnName": "completed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedCategories",
+ "columnName": "failed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedRows",
+ "columnName": "indexed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "skippedMalformedRows",
+ "columnName": "skipped_malformed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedPrunedRows",
+ "columnName": "deleted_pruned_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastAttemptAt",
+ "columnName": "last_attempt_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "section"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_index_jobs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_stalker_index_jobs_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_stalker_index_jobs_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_portal_state",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `working_endpoint` TEXT, `bootstrap_recipe` TEXT, `bulk_live_supported` INTEGER, `bulk_live_category_fidelity` INTEGER, `movie_wildcard_supported` INTEGER, `series_wildcard_supported` INTEGER, `epg_supported` INTEGER, `safe_metadata_concurrency` INTEGER NOT NULL, `stress_cooldown_until` INTEGER NOT NULL, `endpoint_health_json` TEXT NOT NULL, `endpoint_failed_until` INTEGER NOT NULL, `validated_at` INTEGER NOT NULL, `schema_version` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "workingEndpoint",
+ "columnName": "working_endpoint",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bootstrapRecipe",
+ "columnName": "bootstrap_recipe",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bulkLiveSupported",
+ "columnName": "bulk_live_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "bulkLiveCategoryFidelity",
+ "columnName": "bulk_live_category_fidelity",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "movieWildcardSupported",
+ "columnName": "movie_wildcard_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seriesWildcardSupported",
+ "columnName": "series_wildcard_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "epgSupported",
+ "columnName": "epg_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "safeMetadataConcurrency",
+ "columnName": "safe_metadata_concurrency",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stressCooldownUntil",
+ "columnName": "stress_cooldown_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endpointHealthJson",
+ "columnName": "endpoint_health_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endpointFailedUntil",
+ "columnName": "endpoint_failed_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "validatedAt",
+ "columnName": "validated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "schemaVersion",
+ "columnName": "schema_version",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_portal_state_provider_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_portal_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_remote_identities",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `raw_id` TEXT NOT NULL, `surrogate_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `raw_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rawId",
+ "columnName": "raw_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "surrogateId",
+ "columnName": "surrogate_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "raw_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_remote_identities_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_stalker_remote_identities_provider_id_content_type_surrogate_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "surrogate_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id_content_type_surrogate_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `surrogate_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "downloads",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentName",
+ "columnName": "content_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceStreamUrl",
+ "columnName": "source_stream_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "sourceStreamId",
+ "columnName": "source_stream_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputUri",
+ "columnName": "output_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDisplayPath",
+ "columnName": "output_display_path",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "bytesWritten",
+ "columnName": "bytes_written",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalBytes",
+ "columnName": "total_bytes",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "supportsResume",
+ "columnName": "supports_resume",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryCount",
+ "columnName": "retry_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedAt",
+ "columnName": "completed_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failure_reason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_downloads_status",
+ "unique": false,
+ "columnNames": [
+ "status"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"
+ },
+ {
+ "name": "index_downloads_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_downloads_content_type_content_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_id`)"
+ }
+ ]
+ }
+ ],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '7f6096b23700f2a89efac4d922c05216')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/64.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/64.json
new file mode 100644
index 00000000..4bb5809f
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/64.json
@@ -0,0 +1,5740 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 64,
+ "identityHash": "5a82a04b0520688d0c19d18238e84d5e",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_protocol_preference` TEXT NOT NULL, `stalker_requested_profile_id` TEXT NOT NULL, `stalker_learned_profile_id` TEXT NOT NULL, `stalker_profile_revision` INTEGER NOT NULL, `stalker_profile_verification` TEXT NOT NULL, `stalker_protocol_family` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `stalker_catalog_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "httpUserAgent",
+ "columnName": "http_user_agent",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "httpHeaders",
+ "columnName": "http_headers",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMacAddress",
+ "columnName": "stalker_mac_address",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceProfile",
+ "columnName": "stalker_device_profile",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceTimezone",
+ "columnName": "stalker_device_timezone",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceLocale",
+ "columnName": "stalker_device_locale",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerSerialNumber",
+ "columnName": "stalker_serial_number",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceId",
+ "columnName": "stalker_device_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceId2",
+ "columnName": "stalker_device_id2",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerSignature",
+ "columnName": "stalker_signature",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerAdvancedOptionsJson",
+ "columnName": "stalker_advanced_options_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerAuthMode",
+ "columnName": "stalker_auth_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPortalProfile",
+ "columnName": "stalker_portal_profile",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPortalFingerprint",
+ "columnName": "stalker_portal_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMagPreset",
+ "columnName": "stalker_mag_preset",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerProtocolPreference",
+ "columnName": "stalker_protocol_preference",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerRequestedProfileId",
+ "columnName": "stalker_requested_profile_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerLearnedProfileId",
+ "columnName": "stalker_learned_profile_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerProfileRevision",
+ "columnName": "stalker_profile_revision",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerProfileVerification",
+ "columnName": "stalker_profile_verification",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerProtocolFamily",
+ "columnName": "stalker_protocol_family",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerLastBootstrapRecipe",
+ "columnName": "stalker_last_bootstrap_recipe",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerEndpointPreference",
+ "columnName": "stalker_endpoint_preference",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerCookieMode",
+ "columnName": "stalker_cookie_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPlaybackBackendHint",
+ "columnName": "stalker_playback_backend_hint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerLastPlaybackMode",
+ "columnName": "stalker_last_playback_mode",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "stalkerCredentialsRequired",
+ "columnName": "stalker_credentials_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMacRequired",
+ "columnName": "stalker_mac_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerUsesTemporaryLinks",
+ "columnName": "stalker_uses_temp_links",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerModuleRestricted",
+ "columnName": "stalker_module_restricted",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerStrictFingerprintRequired",
+ "columnName": "stalker_strict_fingerprint_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerRecipeFallbackUsed",
+ "columnName": "stalker_recipe_fallback_used",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerRecipeRediscoveryAttempts",
+ "columnName": "stalker_recipe_rediscovery_attempts",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "apiVersion",
+ "columnName": "api_version",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "allowedOutputFormatsJson",
+ "columnName": "allowed_output_formats_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSyncMode",
+ "columnName": "epg_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerCatalogMode",
+ "columnName": "stalker_catalog_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "guideSourcePolicy",
+ "columnName": "guide_source_policy",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelLogoSourcePolicy",
+ "columnName": "channel_logo_source_policy",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xtreamFastSyncEnabled",
+ "columnName": "xtream_fast_sync_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xtreamLiveSyncMode",
+ "columnName": "xtream_live_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uVodClassificationEnabled",
+ "columnName": "m3u_vod_classification_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username_stalker_mac_address",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username",
+ "stalker_mac_address"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"
+ }
+ ]
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "qualityOptionsJson",
+ "columnName": "quality_options_json",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "audioVideoOffsetMs",
+ "columnName": "audio_video_offset_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cacheState",
+ "columnName": "cache_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteStaleAt",
+ "columnName": "remote_stale_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_rating_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "rating",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_added_at_release_date_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "added_at",
+ "release_date",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerSeriesId",
+ "columnName": "provider_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cacheState",
+ "columnName": "cache_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteStaleAt",
+ "columnName": "remote_stale_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ },
+ {
+ "name": "index_series_provider_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_rating_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "rating",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_last_modified_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "last_modified",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_last_modified_name_id` ON `${TABLE_NAME}` (`provider_id`, `last_modified`, `name`, `id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channel_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movie_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerSeriesId",
+ "columnName": "provider_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerSeriesKey",
+ "columnName": "provider_series_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "provider_series_key"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "category_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "category_id",
+ "type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_category_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_end_time_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "end_time",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "groupKey",
+ "columnName": "group_key",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_provider_id_content_id_content_type_group_key",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "content_id",
+ "content_type",
+ "group_key"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"
+ },
+ {
+ "name": "index_favorites_provider_id_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_provider_id_content_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"
+ },
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_playback_history_provider_id_content_type_content_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"
+ },
+ {
+ "name": "index_playback_history_provider_id_content_type_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "tmdb_identity",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "canonicalProviderId",
+ "columnName": "canonical_provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "firstSeenAt",
+ "columnName": "first_seen_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "tmdb_id",
+ "content_type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_tmdb_identity_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ },
+ {
+ "name": "index_tmdb_identity_canonical_provider_id",
+ "unique": false,
+ "columnNames": [
+ "canonical_provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "canonical_provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "search_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "query",
+ "columnName": "query",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentScope",
+ "columnName": "content_scope",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "usedAt",
+ "columnName": "used_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "useCount",
+ "columnName": "use_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_search_history_content_scope_provider_id_used_at",
+ "unique": false,
+ "columnNames": [
+ "content_scope",
+ "provider_id",
+ "used_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"
+ },
+ {
+ "name": "index_search_history_used_at",
+ "unique": false,
+ "columnNames": [
+ "used_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"
+ },
+ {
+ "name": "index_search_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_search_history_query_content_scope_provider_id",
+ "unique": true,
+ "columnNames": [
+ "query",
+ "content_scope",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSuccess",
+ "columnName": "last_live_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSuccess",
+ "columnName": "last_series_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSuccess",
+ "columnName": "last_epg_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveAvoidFullUntil",
+ "columnName": "live_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieAvoidFullUntil",
+ "columnName": "movie_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesAvoidFullUntil",
+ "columnName": "series_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveSequentialFailuresRemembered",
+ "columnName": "live_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveHealthySyncStreak",
+ "columnName": "live_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesSequentialFailuresRemembered",
+ "columnName": "series_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesHealthySyncStreak",
+ "columnName": "series_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastLoadedPage",
+ "columnName": "last_loaded_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastAttemptedPage",
+ "columnName": "last_attempted_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessfulPage",
+ "columnName": "last_successful_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalPages",
+ "columnName": "total_pages",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryAfterMs",
+ "columnName": "retry_after_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryBudgetRemaining",
+ "columnName": "retry_budget_remaining",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastPageFingerprint",
+ "columnName": "last_page_fingerprint",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastLoadedPage",
+ "columnName": "last_loaded_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastAttemptedPage",
+ "columnName": "last_attempted_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessfulPage",
+ "columnName": "last_successful_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalPages",
+ "columnName": "total_pages",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryAfterMs",
+ "columnName": "retry_after_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryBudgetRemaining",
+ "columnName": "retry_budget_remaining",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastPageFingerprint",
+ "columnName": "last_page_fingerprint",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_sources",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "url",
+ "columnName": "url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastRefreshAt",
+ "columnName": "last_refresh_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "etag",
+ "columnName": "etag",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModifiedHeader",
+ "columnName": "last_modified_header",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_sources_url",
+ "unique": true,
+ "columnNames": [
+ "url"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"
+ }
+ ]
+ },
+ {
+ "tableName": "provider_epg_sources",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_epg_sources_provider_id_epg_source_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"
+ },
+ {
+ "name": "index_provider_epg_sources_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "display_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "normalizedName",
+ "columnName": "normalized_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconUrl",
+ "columnName": "icon_url",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",
+ "unique": true,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"
+ },
+ {
+ "name": "index_epg_channels_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ },
+ {
+ "name": "index_epg_channels_normalized_name",
+ "unique": false,
+ "columnNames": [
+ "normalized_name"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_programmes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "subtitle",
+ "columnName": "subtitle",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeInfo",
+ "columnName": "episode_info",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_epg_programmes_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ },
+ {
+ "name": "index_epg_programmes_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_epg_mappings",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerChannelId",
+ "columnName": "provider_channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceType",
+ "columnName": "source_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "matchType",
+ "columnName": "match_type",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "confidence",
+ "columnName": "confidence",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "matchedAt",
+ "columnName": "matched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedAttempts",
+ "columnName": "failed_attempts",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "source",
+ "columnName": "source",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isManualOverride",
+ "columnName": "is_manual_override",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "provider_channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"
+ },
+ {
+ "name": "index_channel_epg_mappings_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "combined_m3u_profiles",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ }
+ },
+ {
+ "tableName": "combined_m3u_profile_members",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "profileId",
+ "columnName": "profile_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_combined_m3u_profile_members_profile_id",
+ "unique": false,
+ "columnNames": [
+ "profile_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"
+ },
+ {
+ "name": "index_combined_m3u_profile_members_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",
+ "unique": true,
+ "columnNames": [
+ "profile_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "combined_m3u_profiles",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "profile_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_schedules",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "requestedStartMs",
+ "columnName": "requested_start_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "requestedEndMs",
+ "columnName": "requested_end_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurrence",
+ "columnName": "recurrence",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurringRuleId",
+ "columnName": "recurring_rule_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isManual",
+ "columnName": "is_manual",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_recording_schedules_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_recording_schedules_enabled_requested_start_ms",
+ "unique": false,
+ "columnNames": [
+ "enabled",
+ "requested_start_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"
+ },
+ {
+ "name": "index_recording_schedules_recurring_rule_id",
+ "unique": false,
+ "columnNames": [
+ "recurring_rule_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_runs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "scheduleId",
+ "columnName": "schedule_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "scheduledStartMs",
+ "columnName": "scheduled_start_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "scheduledEndMs",
+ "columnName": "scheduled_end_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurrence",
+ "columnName": "recurrence",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurringRuleId",
+ "columnName": "recurring_rule_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceType",
+ "columnName": "source_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resolvedUrl",
+ "columnName": "resolved_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "headersJson",
+ "columnName": "headers_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userAgent",
+ "columnName": "user_agent",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "expirationTime",
+ "columnName": "expiration_time",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "providerLabel",
+ "columnName": "provider_label",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputUri",
+ "columnName": "output_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDisplayPath",
+ "columnName": "output_display_path",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bytesWritten",
+ "columnName": "bytes_written",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "averageThroughputBytesPerSecond",
+ "columnName": "average_throughput_bps",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryCount",
+ "columnName": "retry_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastProgressAtMs",
+ "columnName": "last_progress_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "failureCategory",
+ "columnName": "failure_category",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failure_reason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "terminalAtMs",
+ "columnName": "terminal_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "startedAtMs",
+ "columnName": "started_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "endedAtMs",
+ "columnName": "ended_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "scheduleEnabled",
+ "columnName": "schedule_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "alarmStartAtMs",
+ "columnName": "alarm_start_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "alarmStopAtMs",
+ "columnName": "alarm_stop_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_recording_runs_schedule_id",
+ "unique": false,
+ "columnNames": [
+ "schedule_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"
+ },
+ {
+ "name": "index_recording_runs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_recording_runs_status_scheduled_start_ms",
+ "unique": false,
+ "columnNames": [
+ "status",
+ "scheduled_start_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"
+ },
+ {
+ "name": "index_recording_runs_alarm_start_at_ms",
+ "unique": false,
+ "columnNames": [
+ "alarm_start_at_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"
+ },
+ {
+ "name": "index_recording_runs_alarm_stop_at_ms",
+ "unique": false,
+ "columnNames": [
+ "alarm_stop_at_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "recording_schedules",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "schedule_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "program_reminders",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programStartTime",
+ "columnName": "program_start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remindAt",
+ "columnName": "remind_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "leadTimeMinutes",
+ "columnName": "lead_time_minutes",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isDismissed",
+ "columnName": "is_dismissed",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "notifiedAt",
+ "columnName": "notified_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_program_reminders_provider_id_remind_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "remind_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"
+ },
+ {
+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",
+ "unique": false,
+ "columnNames": [
+ "is_dismissed",
+ "notified_at",
+ "remind_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"
+ },
+ {
+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "program_start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"
+ },
+ {
+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "program_title",
+ "program_start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_storage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "treeUri",
+ "columnName": "tree_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "display_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDirectory",
+ "columnName": "output_directory",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "availableBytes",
+ "columnName": "available_bytes",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "isWritable",
+ "columnName": "is_writable",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "fileNamePattern",
+ "columnName": "file_name_pattern",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retentionDays",
+ "columnName": "retention_days",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "maxSimultaneousRecordings",
+ "columnName": "max_simultaneous_recordings",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ }
+ },
+ {
+ "tableName": "playback_compatibility_records",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deviceFingerprint",
+ "columnName": "device_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deviceModel",
+ "columnName": "device_model",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "androidSdk",
+ "columnName": "android_sdk",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamType",
+ "columnName": "stream_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "videoMimeType",
+ "columnName": "video_mime_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resolutionBucket",
+ "columnName": "resolution_bucket",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "decoderName",
+ "columnName": "decoder_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "surfaceType",
+ "columnName": "surface_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureType",
+ "columnName": "failure_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastFailedAt",
+ "columnName": "last_failed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSucceededAt",
+ "columnName": "last_succeeded_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "successCount",
+ "columnName": "success_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",
+ "unique": true,
+ "columnNames": [
+ "device_fingerprint",
+ "stream_type",
+ "video_mime_type",
+ "resolution_bucket",
+ "decoder_name",
+ "surface_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",
+ "unique": false,
+ "columnNames": [
+ "device_fingerprint",
+ "stream_type",
+ "video_mime_type",
+ "resolution_bucket"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_last_failed_at",
+ "unique": false,
+ "columnNames": [
+ "last_failed_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_last_succeeded_at",
+ "unique": false,
+ "columnNames": [
+ "last_succeeded_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_content_index",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `remote_id` TEXT NOT NULL, `local_content_id` INTEGER, `name` TEXT NOT NULL, `category_id` INTEGER, `category_name` TEXT, `image_url` TEXT, `container_extension` TEXT, `rating` REAL NOT NULL, `added_at` INTEGER NOT NULL, `remote_updated_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `indexed_at` INTEGER NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `stale_state` TEXT NOT NULL, `error_state` TEXT, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `remote_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteId",
+ "columnName": "remote_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "localContentId",
+ "columnName": "local_content_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteUpdatedAt",
+ "columnName": "remote_updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedAt",
+ "columnName": "indexed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "staleState",
+ "columnName": "stale_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorState",
+ "columnName": "error_state",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "remote_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_content_index_provider_id_content_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_category_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `category_id`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_name",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "name"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_name` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `name`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_local_content_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "local_content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_local_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `local_content_id`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_indexed_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "indexed_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_indexed_at` ON `${TABLE_NAME}` (`provider_id`, `indexed_at`)"
+ },
+ {
+ "name": "index_xtream_content_index_stale_state",
+ "unique": false,
+ "columnNames": [
+ "stale_state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_stale_state` ON `${TABLE_NAME}` (`stale_state`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_index_jobs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `priority_category_id` INTEGER, `priority_requested_at` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "section",
+ "columnName": "section",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalCategories",
+ "columnName": "total_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedCategories",
+ "columnName": "completed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedCategories",
+ "columnName": "failed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedRows",
+ "columnName": "indexed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "skippedMalformedRows",
+ "columnName": "skipped_malformed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedPrunedRows",
+ "columnName": "deleted_pruned_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priorityCategoryId",
+ "columnName": "priority_category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "priorityRequestedAt",
+ "columnName": "priority_requested_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastAttemptAt",
+ "columnName": "last_attempt_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "section"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_index_jobs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_section",
+ "unique": false,
+ "columnNames": [
+ "section"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_section` ON `${TABLE_NAME}` (`section`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_live_onboarding_state",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `provider_type` TEXT NOT NULL, `content_type` TEXT NOT NULL, `phase` TEXT NOT NULL, `staged_session_id` INTEGER, `import_strategy` TEXT, `next_category_index` INTEGER NOT NULL, `accepted_row_count` INTEGER NOT NULL, `staged_flush_count` INTEGER NOT NULL, `sync_profile_tier` TEXT, `sync_profile_batch_size` INTEGER NOT NULL, `sync_profile_strategy` TEXT, `sync_profile_low_memory` INTEGER NOT NULL, `sync_profile_memory_class_mb` INTEGER NOT NULL, `sync_profile_available_mem_mb` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerType",
+ "columnName": "provider_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "phase",
+ "columnName": "phase",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stagedSessionId",
+ "columnName": "staged_session_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "importStrategy",
+ "columnName": "import_strategy",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "acceptedRowCount",
+ "columnName": "accepted_row_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stagedFlushCount",
+ "columnName": "staged_flush_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileTier",
+ "columnName": "sync_profile_tier",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncProfileBatchSize",
+ "columnName": "sync_profile_batch_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileStrategy",
+ "columnName": "sync_profile_strategy",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncProfileLowMemory",
+ "columnName": "sync_profile_low_memory",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileMemoryClassMb",
+ "columnName": "sync_profile_memory_class_mb",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileAvailableMemMb",
+ "columnName": "sync_profile_available_mem_mb",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedAt",
+ "columnName": "completed_at",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_live_onboarding_state_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_phase",
+ "unique": false,
+ "columnNames": [
+ "phase"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_phase` ON `${TABLE_NAME}` (`phase`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_staged_session_id",
+ "unique": false,
+ "columnNames": [
+ "staged_session_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_staged_session_id` ON `${TABLE_NAME}` (`staged_session_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_index_jobs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "section",
+ "columnName": "section",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalCategories",
+ "columnName": "total_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedCategories",
+ "columnName": "completed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedCategories",
+ "columnName": "failed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedRows",
+ "columnName": "indexed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "skippedMalformedRows",
+ "columnName": "skipped_malformed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedPrunedRows",
+ "columnName": "deleted_pruned_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastAttemptAt",
+ "columnName": "last_attempt_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "section"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_index_jobs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_stalker_index_jobs_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_stalker_index_jobs_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_portal_state",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `working_endpoint` TEXT, `bootstrap_recipe` TEXT, `bulk_live_supported` INTEGER, `bulk_live_category_fidelity` INTEGER, `movie_wildcard_supported` INTEGER, `series_wildcard_supported` INTEGER, `epg_supported` INTEGER, `safe_metadata_concurrency` INTEGER NOT NULL, `stress_cooldown_until` INTEGER NOT NULL, `endpoint_health_json` TEXT NOT NULL, `endpoint_failed_until` INTEGER NOT NULL, `validated_at` INTEGER NOT NULL, `schema_version` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "workingEndpoint",
+ "columnName": "working_endpoint",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bootstrapRecipe",
+ "columnName": "bootstrap_recipe",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bulkLiveSupported",
+ "columnName": "bulk_live_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "bulkLiveCategoryFidelity",
+ "columnName": "bulk_live_category_fidelity",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "movieWildcardSupported",
+ "columnName": "movie_wildcard_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seriesWildcardSupported",
+ "columnName": "series_wildcard_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "epgSupported",
+ "columnName": "epg_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "safeMetadataConcurrency",
+ "columnName": "safe_metadata_concurrency",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stressCooldownUntil",
+ "columnName": "stress_cooldown_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endpointHealthJson",
+ "columnName": "endpoint_health_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endpointFailedUntil",
+ "columnName": "endpoint_failed_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "validatedAt",
+ "columnName": "validated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "schemaVersion",
+ "columnName": "schema_version",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_portal_state_provider_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_portal_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_remote_identities",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `raw_id` TEXT NOT NULL, `surrogate_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `raw_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rawId",
+ "columnName": "raw_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "surrogateId",
+ "columnName": "surrogate_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "raw_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_remote_identities_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_stalker_remote_identities_provider_id_content_type_surrogate_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "surrogate_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id_content_type_surrogate_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `surrogate_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "downloads",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentName",
+ "columnName": "content_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceStreamUrl",
+ "columnName": "source_stream_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "sourceStreamId",
+ "columnName": "source_stream_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputUri",
+ "columnName": "output_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDisplayPath",
+ "columnName": "output_display_path",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "bytesWritten",
+ "columnName": "bytes_written",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalBytes",
+ "columnName": "total_bytes",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "supportsResume",
+ "columnName": "supports_resume",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryCount",
+ "columnName": "retry_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedAt",
+ "columnName": "completed_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failure_reason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_downloads_status",
+ "unique": false,
+ "columnNames": [
+ "status"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"
+ },
+ {
+ "name": "index_downloads_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_downloads_content_type_content_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_id`)"
+ }
+ ]
+ }
+ ],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '5a82a04b0520688d0c19d18238e84d5e')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/65.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/65.json
new file mode 100644
index 00000000..2d57ce29
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/65.json
@@ -0,0 +1,5855 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 65,
+ "identityHash": "1ba430e69c6bbe2b7e0459d6202ea8a6",
+ "entities": [
+ {
+ "tableName": "providers",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `type` TEXT NOT NULL, `server_url` TEXT NOT NULL, `username` TEXT NOT NULL, `password` TEXT NOT NULL, `m3u_url` TEXT NOT NULL, `epg_url` TEXT NOT NULL, `http_user_agent` TEXT NOT NULL, `http_headers` TEXT NOT NULL, `stalker_mac_address` TEXT NOT NULL, `stalker_device_profile` TEXT NOT NULL, `stalker_device_timezone` TEXT NOT NULL, `stalker_device_locale` TEXT NOT NULL, `stalker_serial_number` TEXT NOT NULL, `stalker_device_id` TEXT NOT NULL, `stalker_device_id2` TEXT NOT NULL, `stalker_signature` TEXT NOT NULL, `stalker_advanced_options_json` TEXT NOT NULL, `stalker_auth_mode` TEXT NOT NULL, `stalker_portal_profile` TEXT NOT NULL, `stalker_portal_fingerprint` TEXT NOT NULL, `stalker_mag_preset` TEXT NOT NULL, `stalker_protocol_preference` TEXT NOT NULL, `stalker_transport_mode` TEXT NOT NULL, `stalker_transport_origin` TEXT NOT NULL, `stalker_tls_spki_sha256` TEXT NOT NULL, `stalker_transport_consent_at` INTEGER NOT NULL, `stalker_configuration_generation` INTEGER NOT NULL, `stalker_discovery_summary` TEXT NOT NULL, `stalker_capabilities_json` TEXT NOT NULL, `stalker_requested_profile_id` TEXT NOT NULL, `stalker_learned_profile_id` TEXT NOT NULL, `stalker_profile_revision` INTEGER NOT NULL, `stalker_profile_verification` TEXT NOT NULL, `stalker_protocol_family` TEXT NOT NULL, `stalker_last_bootstrap_recipe` TEXT NOT NULL, `stalker_endpoint_preference` TEXT NOT NULL, `stalker_cookie_mode` TEXT NOT NULL, `stalker_playback_backend_hint` TEXT NOT NULL, `stalker_last_playback_mode` TEXT, `stalker_credentials_required` INTEGER NOT NULL, `stalker_mac_required` INTEGER NOT NULL, `stalker_uses_temp_links` INTEGER NOT NULL, `stalker_module_restricted` INTEGER NOT NULL, `stalker_strict_fingerprint_required` INTEGER NOT NULL, `stalker_recipe_fallback_used` INTEGER NOT NULL, `stalker_recipe_rediscovery_attempts` INTEGER NOT NULL, `is_active` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `epg_sync_mode` TEXT NOT NULL, `stalker_catalog_mode` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `xtream_fast_sync_enabled` INTEGER NOT NULL, `xtream_live_sync_mode` TEXT NOT NULL, `m3u_vod_classification_enabled` INTEGER NOT NULL, `status` TEXT NOT NULL, `last_synced_at` INTEGER NOT NULL, `created_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serverUrl",
+ "columnName": "server_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "username",
+ "columnName": "username",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "password",
+ "columnName": "password",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uUrl",
+ "columnName": "m3u_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgUrl",
+ "columnName": "epg_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "httpUserAgent",
+ "columnName": "http_user_agent",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "httpHeaders",
+ "columnName": "http_headers",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMacAddress",
+ "columnName": "stalker_mac_address",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceProfile",
+ "columnName": "stalker_device_profile",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceTimezone",
+ "columnName": "stalker_device_timezone",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceLocale",
+ "columnName": "stalker_device_locale",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerSerialNumber",
+ "columnName": "stalker_serial_number",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceId",
+ "columnName": "stalker_device_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDeviceId2",
+ "columnName": "stalker_device_id2",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerSignature",
+ "columnName": "stalker_signature",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerAdvancedOptionsJson",
+ "columnName": "stalker_advanced_options_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerAuthMode",
+ "columnName": "stalker_auth_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPortalProfile",
+ "columnName": "stalker_portal_profile",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPortalFingerprint",
+ "columnName": "stalker_portal_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMagPreset",
+ "columnName": "stalker_mag_preset",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerProtocolPreference",
+ "columnName": "stalker_protocol_preference",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerTransportMode",
+ "columnName": "stalker_transport_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerTransportOrigin",
+ "columnName": "stalker_transport_origin",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerTlsSpkiSha256",
+ "columnName": "stalker_tls_spki_sha256",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerTransportConsentAt",
+ "columnName": "stalker_transport_consent_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerConfigurationGeneration",
+ "columnName": "stalker_configuration_generation",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerDiscoverySummary",
+ "columnName": "stalker_discovery_summary",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerCapabilitiesJson",
+ "columnName": "stalker_capabilities_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerRequestedProfileId",
+ "columnName": "stalker_requested_profile_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerLearnedProfileId",
+ "columnName": "stalker_learned_profile_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerProfileRevision",
+ "columnName": "stalker_profile_revision",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerProfileVerification",
+ "columnName": "stalker_profile_verification",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerProtocolFamily",
+ "columnName": "stalker_protocol_family",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerLastBootstrapRecipe",
+ "columnName": "stalker_last_bootstrap_recipe",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerEndpointPreference",
+ "columnName": "stalker_endpoint_preference",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerCookieMode",
+ "columnName": "stalker_cookie_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerPlaybackBackendHint",
+ "columnName": "stalker_playback_backend_hint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerLastPlaybackMode",
+ "columnName": "stalker_last_playback_mode",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "stalkerCredentialsRequired",
+ "columnName": "stalker_credentials_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerMacRequired",
+ "columnName": "stalker_mac_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerUsesTemporaryLinks",
+ "columnName": "stalker_uses_temp_links",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerModuleRestricted",
+ "columnName": "stalker_module_restricted",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerStrictFingerprintRequired",
+ "columnName": "stalker_strict_fingerprint_required",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerRecipeFallbackUsed",
+ "columnName": "stalker_recipe_fallback_used",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerRecipeRediscoveryAttempts",
+ "columnName": "stalker_recipe_rediscovery_attempts",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isActive",
+ "columnName": "is_active",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "maxConnections",
+ "columnName": "max_connections",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "expirationDate",
+ "columnName": "expiration_date",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "apiVersion",
+ "columnName": "api_version",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "allowedOutputFormatsJson",
+ "columnName": "allowed_output_formats_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSyncMode",
+ "columnName": "epg_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stalkerCatalogMode",
+ "columnName": "stalker_catalog_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "guideSourcePolicy",
+ "columnName": "guide_source_policy",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelLogoSourcePolicy",
+ "columnName": "channel_logo_source_policy",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xtreamFastSyncEnabled",
+ "columnName": "xtream_fast_sync_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xtreamLiveSyncMode",
+ "columnName": "xtream_live_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "m3uVodClassificationEnabled",
+ "columnName": "m3u_vod_classification_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncedAt",
+ "columnName": "last_synced_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_providers_server_url_username_stalker_mac_address",
+ "unique": true,
+ "columnNames": [
+ "server_url",
+ "username",
+ "stalker_mac_address"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_providers_server_url_username_stalker_mac_address` ON `${TABLE_NAME}` (`server_url`, `username`, `stalker_mac_address`)"
+ }
+ ]
+ },
+ {
+ "tableName": "channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `quality_options_json` TEXT, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "qualityOptionsJson",
+ "columnName": "quality_options_json",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channels_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channels_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_channels_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_logical_group_id` ON `${TABLE_NAME}` (`logical_group_id`)"
+ },
+ {
+ "name": "index_channels_provider_id_category_id_logical_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "logical_group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channels_provider_id_category_id_logical_group_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `logical_group_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_preferences",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `channel_id` INTEGER NOT NULL, `aspect_ratio` TEXT, `audio_video_offset_ms` INTEGER, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`channel_id`) REFERENCES `channels`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "aspectRatio",
+ "columnName": "aspect_ratio",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "audioVideoOffsetMs",
+ "columnName": "audio_video_offset_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_preferences_channel_id",
+ "unique": true,
+ "columnNames": [
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_preferences_channel_id` ON `${TABLE_NAME}` (`channel_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "channels",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "channel_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channels_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`channels`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "channels",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_UPDATE BEFORE UPDATE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_BEFORE_DELETE BEFORE DELETE ON `channels` BEGIN DELETE FROM `channels_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_UPDATE AFTER UPDATE ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_channels_fts_AFTER_INSERT AFTER INSERT ON `channels` BEGIN INSERT INTO `channels_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "movies",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cacheState",
+ "columnName": "cache_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteStaleAt",
+ "columnName": "remote_stale_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movies_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_stream_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "stream_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_movies_provider_id_stream_id` ON `${TABLE_NAME}` (`provider_id`, `stream_id`)"
+ },
+ {
+ "name": "index_movies_provider_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_category_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_rating_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "rating",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"
+ },
+ {
+ "name": "index_movies_provider_id_added_at_release_date_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "added_at",
+ "release_date",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movies_provider_id_added_at_release_date_name_id` ON `${TABLE_NAME}` (`provider_id`, `added_at`, `release_date`, `name`, `id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movies_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`movies`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "movies",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_UPDATE BEFORE UPDATE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_BEFORE_DELETE BEFORE DELETE ON `movies` BEGIN DELETE FROM `movies_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_UPDATE AFTER UPDATE ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_movies_fts_AFTER_INSERT AFTER INSERT ON `movies` BEGIN INSERT INTO `movies_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "series",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `cache_state` TEXT NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `remote_stale_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerSeriesId",
+ "columnName": "provider_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "cacheState",
+ "columnName": "cache_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteStaleAt",
+ "columnName": "remote_stale_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`)"
+ },
+ {
+ "name": "index_series_provider_id_series_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_series_provider_id_series_id` ON `${TABLE_NAME}` (`provider_id`, `series_id`)"
+ },
+ {
+ "name": "index_series_provider_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_category_id_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_category_id_name_id` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_rating_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "rating",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_rating_name_id` ON `${TABLE_NAME}` (`provider_id`, `rating`, `name`, `id`)"
+ },
+ {
+ "name": "index_series_provider_id_last_modified_name_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "last_modified",
+ "name",
+ "id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_provider_id_last_modified_name_id` ON `${TABLE_NAME}` (`provider_id`, `last_modified`, `name`, `id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_fts",
+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`name` TEXT NOT NULL, content=`series`)",
+ "fields": [
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": []
+ },
+ "ftsVersion": "FTS4",
+ "ftsOptions": {
+ "tokenizer": "simple",
+ "tokenizerArgs": [],
+ "contentTable": "series",
+ "languageIdColumnName": "",
+ "matchInfo": "FTS4",
+ "notIndexedColumns": [],
+ "prefixSizes": [],
+ "preferredOrder": "ASC"
+ },
+ "contentSyncTriggers": [
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_UPDATE BEFORE UPDATE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_BEFORE_DELETE BEFORE DELETE ON `series` BEGIN DELETE FROM `series_fts` WHERE `docid`=OLD.`rowid`; END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_UPDATE AFTER UPDATE ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END",
+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_series_fts_AFTER_INSERT AFTER INSERT ON `series` BEGIN INSERT INTO `series_fts`(`docid`, `name`) VALUES (NEW.`rowid`, NEW.`name`); END"
+ ]
+ },
+ {
+ "tableName": "episodes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `episode_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `episode_number` INTEGER NOT NULL, `season_number` INTEGER NOT NULL, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `cover_url` TEXT, `plot` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `release_date` TEXT, `series_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `watch_progress` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`series_id`) REFERENCES `series`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeId",
+ "columnName": "episode_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "coverUrl",
+ "columnName": "cover_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchProgress",
+ "columnName": "watch_progress",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_episodes_series_id",
+ "unique": false,
+ "columnNames": [
+ "series_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_series_id` ON `${TABLE_NAME}` (`series_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_episodes_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_episodes_provider_id_episode_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "episode_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_episodes_provider_id_episode_id` ON `${TABLE_NAME}` (`provider_id`, `episode_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "series",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "series_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "categories",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `is_user_protected` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isUserProtected",
+ "columnName": "is_user_protected",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_categories_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_categories_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_categories_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ },
+ {
+ "name": "index_categories_provider_id_category_id_type",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_categories_provider_id_category_id_type` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `logo_url` TEXT, `group_title` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `epg_channel_id` TEXT, `number` INTEGER NOT NULL, `catch_up_supported` INTEGER NOT NULL, `catch_up_days` INTEGER NOT NULL, `catchUpSource` TEXT, `is_adult` INTEGER NOT NULL, `logical_group_id` TEXT NOT NULL, `error_count` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logoUrl",
+ "columnName": "logo_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "groupTitle",
+ "columnName": "group_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgChannelId",
+ "columnName": "epg_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "number",
+ "columnName": "number",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSupported",
+ "columnName": "catch_up_supported",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpDays",
+ "columnName": "catch_up_days",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catchUpSource",
+ "columnName": "catchUpSource",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "logicalGroupId",
+ "columnName": "logical_group_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorCount",
+ "columnName": "error_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_channel_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `stream_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `stream_url` TEXT NOT NULL, `container_extension` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `duration` TEXT, `duration_seconds` INTEGER NOT NULL, `rating` REAL NOT NULL, `year` TEXT, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, `added_at` INTEGER NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `stream_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "duration",
+ "columnName": "duration",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "durationSeconds",
+ "columnName": "duration_seconds",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "year",
+ "columnName": "year",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "stream_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_movie_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `series_id` INTEGER NOT NULL, `provider_series_id` TEXT, `provider_series_key` TEXT NOT NULL, `name` TEXT NOT NULL, `poster_url` TEXT, `backdrop_url` TEXT, `category_id` INTEGER, `category_name` TEXT, `plot` TEXT, `cast` TEXT, `director` TEXT, `genre` TEXT, `release_date` TEXT, `rating` REAL NOT NULL, `tmdb_id` INTEGER, `youtube_trailer` TEXT, `episode_run_time` TEXT, `last_modified` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `provider_series_key`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerSeriesId",
+ "columnName": "provider_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "providerSeriesKey",
+ "columnName": "provider_series_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "backdropUrl",
+ "columnName": "backdrop_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "plot",
+ "columnName": "plot",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "cast",
+ "columnName": "cast",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "director",
+ "columnName": "director",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "releaseDate",
+ "columnName": "release_date",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "youtubeTrailer",
+ "columnName": "youtube_trailer",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeRunTime",
+ "columnName": "episode_run_time",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModified",
+ "columnName": "last_modified",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "provider_series_key"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_series_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "category_import_stage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`session_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `parent_id` INTEGER, `type` TEXT NOT NULL, `is_adult` INTEGER NOT NULL, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`session_id`, `provider_id`, `category_id`, `type`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "sessionId",
+ "columnName": "session_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentId",
+ "columnName": "parent_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "session_id",
+ "provider_id",
+ "category_id",
+ "type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_category_import_stage_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_session_id_provider_id",
+ "unique": false,
+ "columnNames": [
+ "session_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_session_id_provider_id` ON `${TABLE_NAME}` (`session_id`, `provider_id`)"
+ },
+ {
+ "name": "index_category_import_stage_provider_id_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_category_import_stage_provider_id_type` ON `${TABLE_NAME}` (`provider_id`, `type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "programs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `title` TEXT NOT NULL, `description` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `genre` TEXT, `category` TEXT, `has_archive` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "genre",
+ "columnName": "genre",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "hasArchive",
+ "columnName": "has_archive",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_programs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id` ON `${TABLE_NAME}` (`provider_id`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_end_time_channel_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "end_time",
+ "channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_end_time_channel_id` ON `${TABLE_NAME}` (`provider_id`, `end_time`, `channel_id`)"
+ },
+ {
+ "name": "index_programs_provider_id_start_time_end_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_programs_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_programs_provider_id_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_programs_provider_id_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `start_time`, `end_time`)"
+ }
+ ]
+ },
+ {
+ "tableName": "favorites",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `position` INTEGER NOT NULL, `group_id` INTEGER, `group_key` INTEGER NOT NULL, `added_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`group_id`) REFERENCES `virtual_groups`(`id`) ON UPDATE NO ACTION ON DELETE SET NULL )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupId",
+ "columnName": "group_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "groupKey",
+ "columnName": "group_key",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_favorites_provider_id_content_id_content_type_group_key",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "content_id",
+ "content_type",
+ "group_key"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_favorites_provider_id_content_id_content_type_group_key` ON `${TABLE_NAME}` (`provider_id`, `content_id`, `content_type`, `group_key`)"
+ },
+ {
+ "name": "index_favorites_provider_id_content_type_group_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "group_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_provider_id_content_type_group_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `group_id`)"
+ },
+ {
+ "name": "index_favorites_group_id_position",
+ "unique": false,
+ "columnNames": [
+ "group_id",
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_favorites_group_id_position` ON `${TABLE_NAME}` (`group_id`, `position`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "virtual_groups",
+ "onDelete": "SET NULL",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "group_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "virtual_groups",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `name` TEXT NOT NULL, `icon_emoji` TEXT, `position` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `content_type` TEXT NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconEmoji",
+ "columnName": "icon_emoji",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "position",
+ "columnName": "position",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_virtual_groups_provider_id_content_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"
+ },
+ {
+ "name": "index_virtual_groups_position",
+ "unique": false,
+ "columnNames": [
+ "position"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_position` ON `${TABLE_NAME}` (`position`)"
+ },
+ {
+ "name": "index_virtual_groups_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_virtual_groups_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `content_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `title` TEXT NOT NULL, `poster_url` TEXT, `stream_url` TEXT NOT NULL, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `watch_count` INTEGER NOT NULL, `watched_status` TEXT NOT NULL, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchCount",
+ "columnName": "watch_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "watchedStatus",
+ "columnName": "watched_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_history_content_id_content_type_provider_id",
+ "unique": true,
+ "columnNames": [
+ "content_id",
+ "content_type",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_history_content_id_content_type_provider_id` ON `${TABLE_NAME}` (`content_id`, `content_type`, `provider_id`)"
+ },
+ {
+ "name": "index_playback_history_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_last_watched_at` ON `${TABLE_NAME}` (`last_watched_at`)"
+ },
+ {
+ "name": "index_playback_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_playback_history_provider_id_content_type_content_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `content_id`)"
+ },
+ {
+ "name": "index_playback_history_provider_id_content_type_last_watched_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "last_watched_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_history_provider_id_content_type_last_watched_at` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `last_watched_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "tmdb_identity",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`tmdb_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `canonical_provider_id` INTEGER NOT NULL, `first_seen_at` INTEGER NOT NULL, PRIMARY KEY(`tmdb_id`, `content_type`), FOREIGN KEY(`canonical_provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "tmdbId",
+ "columnName": "tmdb_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "canonicalProviderId",
+ "columnName": "canonical_provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "firstSeenAt",
+ "columnName": "first_seen_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "tmdb_id",
+ "content_type"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_tmdb_identity_content_type",
+ "unique": false,
+ "columnNames": [
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_content_type` ON `${TABLE_NAME}` (`content_type`)"
+ },
+ {
+ "name": "index_tmdb_identity_canonical_provider_id",
+ "unique": false,
+ "columnNames": [
+ "canonical_provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_tmdb_identity_canonical_provider_id` ON `${TABLE_NAME}` (`canonical_provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "canonical_provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "search_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `query` TEXT NOT NULL, `content_scope` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `used_at` INTEGER NOT NULL, `use_count` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "query",
+ "columnName": "query",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentScope",
+ "columnName": "content_scope",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "usedAt",
+ "columnName": "used_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "useCount",
+ "columnName": "use_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_search_history_content_scope_provider_id_used_at",
+ "unique": false,
+ "columnNames": [
+ "content_scope",
+ "provider_id",
+ "used_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_content_scope_provider_id_used_at` ON `${TABLE_NAME}` (`content_scope`, `provider_id`, `used_at`)"
+ },
+ {
+ "name": "index_search_history_used_at",
+ "unique": false,
+ "columnNames": [
+ "used_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_used_at` ON `${TABLE_NAME}` (`used_at`)"
+ },
+ {
+ "name": "index_search_history_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_search_history_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_search_history_query_content_scope_provider_id",
+ "unique": true,
+ "columnNames": [
+ "query",
+ "content_scope",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_search_history_query_content_scope_provider_id` ON `${TABLE_NAME}` (`query`, `content_scope`, `provider_id`)"
+ }
+ ]
+ },
+ {
+ "tableName": "sync_metadata",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `last_live_sync` INTEGER NOT NULL, `last_live_success` INTEGER NOT NULL, `last_movie_sync` INTEGER NOT NULL, `last_series_sync` INTEGER NOT NULL, `last_series_success` INTEGER NOT NULL, `last_epg_sync` INTEGER NOT NULL, `last_epg_success` INTEGER NOT NULL, `last_movie_attempt` INTEGER NOT NULL, `last_movie_success` INTEGER NOT NULL, `last_movie_partial` INTEGER NOT NULL, `live_count` INTEGER NOT NULL, `movie_count` INTEGER NOT NULL, `series_count` INTEGER NOT NULL, `epg_count` INTEGER NOT NULL, `last_sync_status` TEXT NOT NULL, `movie_sync_mode` TEXT NOT NULL, `movie_warnings_count` INTEGER NOT NULL, `movie_catalog_stale` INTEGER NOT NULL, `live_avoid_full_until` INTEGER NOT NULL, `movie_avoid_full_until` INTEGER NOT NULL, `series_avoid_full_until` INTEGER NOT NULL, `live_sequential_failures_remembered` INTEGER NOT NULL, `live_healthy_sync_streak` INTEGER NOT NULL, `movie_parallel_failures_remembered` INTEGER NOT NULL, `movie_healthy_sync_streak` INTEGER NOT NULL, `series_sequential_failures_remembered` INTEGER NOT NULL, `series_healthy_sync_streak` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSync",
+ "columnName": "last_live_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastLiveSuccess",
+ "columnName": "last_live_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSync",
+ "columnName": "last_movie_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSync",
+ "columnName": "last_series_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSeriesSuccess",
+ "columnName": "last_series_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSync",
+ "columnName": "last_epg_sync",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastEpgSuccess",
+ "columnName": "last_epg_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieAttempt",
+ "columnName": "last_movie_attempt",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMovieSuccess",
+ "columnName": "last_movie_success",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastMoviePartial",
+ "columnName": "last_movie_partial",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveCount",
+ "columnName": "live_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCount",
+ "columnName": "movie_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesCount",
+ "columnName": "series_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgCount",
+ "columnName": "epg_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSyncStatus",
+ "columnName": "last_sync_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieSyncMode",
+ "columnName": "movie_sync_mode",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieWarningsCount",
+ "columnName": "movie_warnings_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieCatalogStale",
+ "columnName": "movie_catalog_stale",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveAvoidFullUntil",
+ "columnName": "live_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieAvoidFullUntil",
+ "columnName": "movie_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesAvoidFullUntil",
+ "columnName": "series_avoid_full_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveSequentialFailuresRemembered",
+ "columnName": "live_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "liveHealthySyncStreak",
+ "columnName": "live_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieParallelFailuresRemembered",
+ "columnName": "movie_parallel_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "movieHealthySyncStreak",
+ "columnName": "movie_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesSequentialFailuresRemembered",
+ "columnName": "series_sequential_failures_remembered",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesHealthySyncStreak",
+ "columnName": "series_healthy_sync_streak",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "movie_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastLoadedPage",
+ "columnName": "last_loaded_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastAttemptedPage",
+ "columnName": "last_attempted_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessfulPage",
+ "columnName": "last_successful_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalPages",
+ "columnName": "total_pages",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryAfterMs",
+ "columnName": "retry_after_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryBudgetRemaining",
+ "columnName": "retry_budget_remaining",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastPageFingerprint",
+ "columnName": "last_page_fingerprint",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_movie_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_movie_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "series_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `page_size` INTEGER NOT NULL, `retry_after_ms` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `retry_budget_remaining` INTEGER NOT NULL, `last_page_fingerprint` TEXT, PRIMARY KEY(`provider_id`, `category_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastLoadedPage",
+ "columnName": "last_loaded_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastAttemptedPage",
+ "columnName": "last_attempted_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessfulPage",
+ "columnName": "last_successful_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalPages",
+ "columnName": "total_pages",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryAfterMs",
+ "columnName": "retry_after_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryBudgetRemaining",
+ "columnName": "retry_budget_remaining",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastPageFingerprint",
+ "columnName": "last_page_fingerprint",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_series_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_series_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_sources",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `url` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `last_refresh_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `last_error` TEXT, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `etag` TEXT, `last_modified_header` TEXT)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "url",
+ "columnName": "url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastRefreshAt",
+ "columnName": "last_refresh_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "etag",
+ "columnName": "etag",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastModifiedHeader",
+ "columnName": "last_modified_header",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_sources_url",
+ "unique": true,
+ "columnNames": [
+ "url"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_sources_url` ON `${TABLE_NAME}` (`url`)"
+ }
+ ]
+ },
+ {
+ "tableName": "provider_epg_sources",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `epg_source_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_epg_sources_provider_id_epg_source_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_epg_sources_provider_id_epg_source_id` ON `${TABLE_NAME}` (`provider_id`, `epg_source_id`)"
+ },
+ {
+ "name": "index_provider_epg_sources_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_epg_sources_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_channels",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `display_name` TEXT NOT NULL, `normalized_name` TEXT NOT NULL, `icon_url` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "display_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "normalizedName",
+ "columnName": "normalized_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "iconUrl",
+ "columnName": "icon_url",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_channels_epg_source_id_xmltv_channel_id",
+ "unique": true,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id_xmltv_channel_id` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`)"
+ },
+ {
+ "name": "index_epg_channels_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ },
+ {
+ "name": "index_epg_channels_normalized_name",
+ "unique": false,
+ "columnNames": [
+ "normalized_name"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_channels_normalized_name` ON `${TABLE_NAME}` (`normalized_name`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "epg_programmes",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `epg_source_id` INTEGER NOT NULL, `xmltv_channel_id` TEXT NOT NULL, `start_time` INTEGER NOT NULL, `end_time` INTEGER NOT NULL, `title` TEXT NOT NULL, `subtitle` TEXT, `description` TEXT NOT NULL, `category` TEXT, `lang` TEXT NOT NULL, `rating` TEXT, `image_url` TEXT, `episode_info` TEXT, FOREIGN KEY(`epg_source_id`) REFERENCES `epg_sources`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "startTime",
+ "columnName": "start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endTime",
+ "columnName": "end_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "subtitle",
+ "columnName": "subtitle",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "description",
+ "columnName": "description",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "category",
+ "columnName": "category",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lang",
+ "columnName": "lang",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "episodeInfo",
+ "columnName": "episode_info",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id",
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`)"
+ },
+ {
+ "name": "index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time",
+ "unique": true,
+ "columnNames": [
+ "epg_source_id",
+ "xmltv_channel_id",
+ "start_time",
+ "end_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id_xmltv_channel_id_start_time_end_time` ON `${TABLE_NAME}` (`epg_source_id`, `xmltv_channel_id`, `start_time`, `end_time`)"
+ },
+ {
+ "name": "index_epg_programmes_epg_source_id",
+ "unique": false,
+ "columnNames": [
+ "epg_source_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_epg_source_id` ON `${TABLE_NAME}` (`epg_source_id`)"
+ },
+ {
+ "name": "index_epg_programmes_start_time",
+ "unique": false,
+ "columnNames": [
+ "start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_epg_programmes_start_time` ON `${TABLE_NAME}` (`start_time`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "epg_sources",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "epg_source_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "channel_epg_mappings",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_channel_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `source_type` TEXT NOT NULL, `epg_source_id` INTEGER, `xmltv_channel_id` TEXT, `match_type` TEXT, `confidence` REAL NOT NULL, `matched_at` INTEGER NOT NULL, `failed_attempts` INTEGER NOT NULL, `source` TEXT, `is_manual_override` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerChannelId",
+ "columnName": "provider_channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceType",
+ "columnName": "source_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "epgSourceId",
+ "columnName": "epg_source_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "xmltvChannelId",
+ "columnName": "xmltv_channel_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "matchType",
+ "columnName": "match_type",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "confidence",
+ "columnName": "confidence",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "matchedAt",
+ "columnName": "matched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedAttempts",
+ "columnName": "failed_attempts",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "source",
+ "columnName": "source",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "isManualOverride",
+ "columnName": "is_manual_override",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_channel_epg_mappings_provider_id_provider_channel_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "provider_channel_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id_provider_channel_id` ON `${TABLE_NAME}` (`provider_id`, `provider_channel_id`)"
+ },
+ {
+ "name": "index_channel_epg_mappings_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_channel_epg_mappings_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "combined_m3u_profiles",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `name` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ }
+ },
+ {
+ "tableName": "combined_m3u_profile_members",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `profile_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `enabled` INTEGER NOT NULL, FOREIGN KEY(`profile_id`) REFERENCES `combined_m3u_profiles`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "profileId",
+ "columnName": "profile_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_combined_m3u_profile_members_profile_id",
+ "unique": false,
+ "columnNames": [
+ "profile_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id` ON `${TABLE_NAME}` (`profile_id`)"
+ },
+ {
+ "name": "index_combined_m3u_profile_members_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_combined_m3u_profile_members_profile_id_provider_id",
+ "unique": true,
+ "columnNames": [
+ "profile_id",
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_combined_m3u_profile_members_profile_id_provider_id` ON `${TABLE_NAME}` (`profile_id`, `provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "combined_m3u_profiles",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "profile_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_schedules",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `requested_start_ms` INTEGER NOT NULL, `requested_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `enabled` INTEGER NOT NULL, `is_manual` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "requestedStartMs",
+ "columnName": "requested_start_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "requestedEndMs",
+ "columnName": "requested_end_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurrence",
+ "columnName": "recurrence",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurringRuleId",
+ "columnName": "recurring_rule_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isManual",
+ "columnName": "is_manual",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_recording_schedules_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_recording_schedules_enabled_requested_start_ms",
+ "unique": false,
+ "columnNames": [
+ "enabled",
+ "requested_start_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_enabled_requested_start_ms` ON `${TABLE_NAME}` (`enabled`, `requested_start_ms`)"
+ },
+ {
+ "name": "index_recording_schedules_recurring_rule_id",
+ "unique": false,
+ "columnNames": [
+ "recurring_rule_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_schedules_recurring_rule_id` ON `${TABLE_NAME}` (`recurring_rule_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_runs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `schedule_id` INTEGER NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` INTEGER NOT NULL, `channel_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `program_title` TEXT, `scheduled_start_ms` INTEGER NOT NULL, `scheduled_end_ms` INTEGER NOT NULL, `recurrence` TEXT NOT NULL, `recurring_rule_id` TEXT, `status` TEXT NOT NULL, `source_type` TEXT NOT NULL, `resolved_url` TEXT, `headers_json` TEXT NOT NULL, `user_agent` TEXT, `expiration_time` INTEGER, `provider_label` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `bytes_written` INTEGER NOT NULL, `average_throughput_bps` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `last_progress_at_ms` INTEGER, `failure_category` TEXT NOT NULL, `failure_reason` TEXT, `terminal_at_ms` INTEGER, `started_at_ms` INTEGER, `ended_at_ms` INTEGER, `schedule_enabled` INTEGER NOT NULL, `priority` INTEGER NOT NULL, `alarm_start_at_ms` INTEGER, `alarm_stop_at_ms` INTEGER, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`), FOREIGN KEY(`schedule_id`) REFERENCES `recording_schedules`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE , FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "scheduleId",
+ "columnName": "schedule_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "scheduledStartMs",
+ "columnName": "scheduled_start_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "scheduledEndMs",
+ "columnName": "scheduled_end_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurrence",
+ "columnName": "recurrence",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "recurringRuleId",
+ "columnName": "recurring_rule_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceType",
+ "columnName": "source_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resolvedUrl",
+ "columnName": "resolved_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "headersJson",
+ "columnName": "headers_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "userAgent",
+ "columnName": "user_agent",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "expirationTime",
+ "columnName": "expiration_time",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "providerLabel",
+ "columnName": "provider_label",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputUri",
+ "columnName": "output_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDisplayPath",
+ "columnName": "output_display_path",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bytesWritten",
+ "columnName": "bytes_written",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "averageThroughputBytesPerSecond",
+ "columnName": "average_throughput_bps",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryCount",
+ "columnName": "retry_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastProgressAtMs",
+ "columnName": "last_progress_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "failureCategory",
+ "columnName": "failure_category",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failure_reason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "terminalAtMs",
+ "columnName": "terminal_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "startedAtMs",
+ "columnName": "started_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "endedAtMs",
+ "columnName": "ended_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "scheduleEnabled",
+ "columnName": "schedule_enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "alarmStartAtMs",
+ "columnName": "alarm_start_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "alarmStopAtMs",
+ "columnName": "alarm_stop_at_ms",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_recording_runs_schedule_id",
+ "unique": false,
+ "columnNames": [
+ "schedule_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_schedule_id` ON `${TABLE_NAME}` (`schedule_id`)"
+ },
+ {
+ "name": "index_recording_runs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_recording_runs_status_scheduled_start_ms",
+ "unique": false,
+ "columnNames": [
+ "status",
+ "scheduled_start_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_status_scheduled_start_ms` ON `${TABLE_NAME}` (`status`, `scheduled_start_ms`)"
+ },
+ {
+ "name": "index_recording_runs_alarm_start_at_ms",
+ "unique": false,
+ "columnNames": [
+ "alarm_start_at_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_start_at_ms` ON `${TABLE_NAME}` (`alarm_start_at_ms`)"
+ },
+ {
+ "name": "index_recording_runs_alarm_stop_at_ms",
+ "unique": false,
+ "columnNames": [
+ "alarm_stop_at_ms"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_recording_runs_alarm_stop_at_ms` ON `${TABLE_NAME}` (`alarm_stop_at_ms`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "recording_schedules",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "schedule_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ },
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "program_reminders",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `channel_id` TEXT NOT NULL, `channel_name` TEXT NOT NULL, `program_title` TEXT NOT NULL, `program_start_time` INTEGER NOT NULL, `remind_at` INTEGER NOT NULL, `lead_time_minutes` INTEGER NOT NULL, `is_dismissed` INTEGER NOT NULL, `notified_at` INTEGER, `created_at` INTEGER NOT NULL, FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelId",
+ "columnName": "channel_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelName",
+ "columnName": "channel_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programTitle",
+ "columnName": "program_title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "programStartTime",
+ "columnName": "program_start_time",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remindAt",
+ "columnName": "remind_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "leadTimeMinutes",
+ "columnName": "lead_time_minutes",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isDismissed",
+ "columnName": "is_dismissed",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "notifiedAt",
+ "columnName": "notified_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_program_reminders_provider_id_remind_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "remind_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_remind_at` ON `${TABLE_NAME}` (`provider_id`, `remind_at`)"
+ },
+ {
+ "name": "index_program_reminders_is_dismissed_notified_at_remind_at",
+ "unique": false,
+ "columnNames": [
+ "is_dismissed",
+ "notified_at",
+ "remind_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_is_dismissed_notified_at_remind_at` ON `${TABLE_NAME}` (`is_dismissed`, `notified_at`, `remind_at`)"
+ },
+ {
+ "name": "index_program_reminders_provider_id_channel_id_program_start_time",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "program_start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_start_time`)"
+ },
+ {
+ "name": "index_program_reminders_provider_id_channel_id_program_title_program_start_time",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "channel_id",
+ "program_title",
+ "program_start_time"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_program_reminders_provider_id_channel_id_program_title_program_start_time` ON `${TABLE_NAME}` (`provider_id`, `channel_id`, `program_title`, `program_start_time`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "recording_storage",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER NOT NULL, `tree_uri` TEXT, `display_name` TEXT, `output_directory` TEXT, `available_bytes` INTEGER, `is_writable` INTEGER NOT NULL, `file_name_pattern` TEXT NOT NULL, `retention_days` INTEGER, `max_simultaneous_recordings` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "treeUri",
+ "columnName": "tree_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "displayName",
+ "columnName": "display_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDirectory",
+ "columnName": "output_directory",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "availableBytes",
+ "columnName": "available_bytes",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "isWritable",
+ "columnName": "is_writable",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "fileNamePattern",
+ "columnName": "file_name_pattern",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retentionDays",
+ "columnName": "retention_days",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "maxSimultaneousRecordings",
+ "columnName": "max_simultaneous_recordings",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ }
+ },
+ {
+ "tableName": "playback_compatibility_records",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `device_fingerprint` TEXT NOT NULL, `device_model` TEXT NOT NULL, `android_sdk` INTEGER NOT NULL, `stream_type` TEXT NOT NULL, `video_mime_type` TEXT NOT NULL, `resolution_bucket` TEXT NOT NULL, `decoder_name` TEXT NOT NULL, `surface_type` TEXT NOT NULL, `failure_type` TEXT NOT NULL, `last_failed_at` INTEGER NOT NULL, `last_succeeded_at` INTEGER NOT NULL, `failure_count` INTEGER NOT NULL, `success_count` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deviceFingerprint",
+ "columnName": "device_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deviceModel",
+ "columnName": "device_model",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "androidSdk",
+ "columnName": "android_sdk",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamType",
+ "columnName": "stream_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "videoMimeType",
+ "columnName": "video_mime_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "resolutionBucket",
+ "columnName": "resolution_bucket",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "decoderName",
+ "columnName": "decoder_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "surfaceType",
+ "columnName": "surface_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureType",
+ "columnName": "failure_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastFailedAt",
+ "columnName": "last_failed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSucceededAt",
+ "columnName": "last_succeeded_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failureCount",
+ "columnName": "failure_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "successCount",
+ "columnName": "success_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type",
+ "unique": true,
+ "columnNames": [
+ "device_fingerprint",
+ "stream_type",
+ "video_mime_type",
+ "resolution_bucket",
+ "decoder_name",
+ "surface_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket_decoder_name_surface_type` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`, `decoder_name`, `surface_type`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket",
+ "unique": false,
+ "columnNames": [
+ "device_fingerprint",
+ "stream_type",
+ "video_mime_type",
+ "resolution_bucket"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_device_fingerprint_stream_type_video_mime_type_resolution_bucket` ON `${TABLE_NAME}` (`device_fingerprint`, `stream_type`, `video_mime_type`, `resolution_bucket`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_last_failed_at",
+ "unique": false,
+ "columnNames": [
+ "last_failed_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_failed_at` ON `${TABLE_NAME}` (`last_failed_at`)"
+ },
+ {
+ "name": "index_playback_compatibility_records_last_succeeded_at",
+ "unique": false,
+ "columnNames": [
+ "last_succeeded_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_playback_compatibility_records_last_succeeded_at` ON `${TABLE_NAME}` (`last_succeeded_at`)"
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_content_index",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `remote_id` TEXT NOT NULL, `local_content_id` INTEGER, `name` TEXT NOT NULL, `category_id` INTEGER, `category_name` TEXT, `image_url` TEXT, `container_extension` TEXT, `rating` REAL NOT NULL, `added_at` INTEGER NOT NULL, `remote_updated_at` INTEGER NOT NULL, `is_adult` INTEGER NOT NULL, `indexed_at` INTEGER NOT NULL, `detail_hydrated_at` INTEGER NOT NULL, `stale_state` TEXT NOT NULL, `error_state` TEXT, `sync_fingerprint` TEXT NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `remote_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteId",
+ "columnName": "remote_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "localContentId",
+ "columnName": "local_content_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoryId",
+ "columnName": "category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "categoryName",
+ "columnName": "category_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "imageUrl",
+ "columnName": "image_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "rating",
+ "columnName": "rating",
+ "affinity": "REAL",
+ "notNull": true
+ },
+ {
+ "fieldPath": "addedAt",
+ "columnName": "added_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "remoteUpdatedAt",
+ "columnName": "remote_updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isAdult",
+ "columnName": "is_adult",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedAt",
+ "columnName": "indexed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "detailHydratedAt",
+ "columnName": "detail_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "staleState",
+ "columnName": "stale_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "errorState",
+ "columnName": "error_state",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncFingerprint",
+ "columnName": "sync_fingerprint",
+ "affinity": "TEXT",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "remote_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_content_index_provider_id_content_type",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type` ON `${TABLE_NAME}` (`provider_id`, `content_type`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_category_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "category_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_category_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `category_id`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_name",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "name"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_name` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `name`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_content_type_local_content_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "local_content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_content_type_local_content_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `local_content_id`)"
+ },
+ {
+ "name": "index_xtream_content_index_provider_id_indexed_at",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "indexed_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_provider_id_indexed_at` ON `${TABLE_NAME}` (`provider_id`, `indexed_at`)"
+ },
+ {
+ "name": "index_xtream_content_index_stale_state",
+ "unique": false,
+ "columnNames": [
+ "stale_state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_content_index_stale_state` ON `${TABLE_NAME}` (`stale_state`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_index_jobs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `priority_category_id` INTEGER, `priority_requested_at` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "section",
+ "columnName": "section",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalCategories",
+ "columnName": "total_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedCategories",
+ "columnName": "completed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedCategories",
+ "columnName": "failed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedRows",
+ "columnName": "indexed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "skippedMalformedRows",
+ "columnName": "skipped_malformed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedPrunedRows",
+ "columnName": "deleted_pruned_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priorityCategoryId",
+ "columnName": "priority_category_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "priorityRequestedAt",
+ "columnName": "priority_requested_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastAttemptAt",
+ "columnName": "last_attempt_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "section"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_index_jobs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_section",
+ "unique": false,
+ "columnNames": [
+ "section"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_section` ON `${TABLE_NAME}` (`section`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_xtream_index_jobs_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "xtream_live_onboarding_state",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `provider_type` TEXT NOT NULL, `content_type` TEXT NOT NULL, `phase` TEXT NOT NULL, `staged_session_id` INTEGER, `import_strategy` TEXT, `next_category_index` INTEGER NOT NULL, `accepted_row_count` INTEGER NOT NULL, `staged_flush_count` INTEGER NOT NULL, `sync_profile_tier` TEXT, `sync_profile_batch_size` INTEGER NOT NULL, `sync_profile_strategy` TEXT, `sync_profile_low_memory` INTEGER NOT NULL, `sync_profile_memory_class_mb` INTEGER NOT NULL, `sync_profile_available_mem_mb` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerType",
+ "columnName": "provider_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "phase",
+ "columnName": "phase",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stagedSessionId",
+ "columnName": "staged_session_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "importStrategy",
+ "columnName": "import_strategy",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "acceptedRowCount",
+ "columnName": "accepted_row_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stagedFlushCount",
+ "columnName": "staged_flush_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileTier",
+ "columnName": "sync_profile_tier",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncProfileBatchSize",
+ "columnName": "sync_profile_batch_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileStrategy",
+ "columnName": "sync_profile_strategy",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "syncProfileLowMemory",
+ "columnName": "sync_profile_low_memory",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileMemoryClassMb",
+ "columnName": "sync_profile_memory_class_mb",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "syncProfileAvailableMemMb",
+ "columnName": "sync_profile_available_mem_mb",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedAt",
+ "columnName": "completed_at",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_xtream_live_onboarding_state_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_phase",
+ "unique": false,
+ "columnNames": [
+ "phase"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_phase` ON `${TABLE_NAME}` (`phase`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ },
+ {
+ "name": "index_xtream_live_onboarding_state_staged_session_id",
+ "unique": false,
+ "columnNames": [
+ "staged_session_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_xtream_live_onboarding_state_staged_session_id` ON `${TABLE_NAME}` (`staged_session_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_index_jobs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `section` TEXT NOT NULL, `state` TEXT NOT NULL, `total_categories` INTEGER NOT NULL, `completed_categories` INTEGER NOT NULL, `next_category_index` INTEGER NOT NULL, `failed_categories` INTEGER NOT NULL, `indexed_rows` INTEGER NOT NULL, `skipped_malformed_rows` INTEGER NOT NULL, `deleted_pruned_rows` INTEGER NOT NULL, `last_error` TEXT, `last_attempt_at` INTEGER NOT NULL, `last_success_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `section`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "section",
+ "columnName": "section",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalCategories",
+ "columnName": "total_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedCategories",
+ "columnName": "completed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "nextCategoryIndex",
+ "columnName": "next_category_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedCategories",
+ "columnName": "failed_categories",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "indexedRows",
+ "columnName": "indexed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "skippedMalformedRows",
+ "columnName": "skipped_malformed_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deletedPrunedRows",
+ "columnName": "deleted_pruned_rows",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastAttemptAt",
+ "columnName": "last_attempt_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastSuccessAt",
+ "columnName": "last_success_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "section"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_index_jobs_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_stalker_index_jobs_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_stalker_index_jobs_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_index_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_portal_state",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `working_endpoint` TEXT, `bootstrap_recipe` TEXT, `bulk_live_supported` INTEGER, `bulk_live_category_fidelity` INTEGER, `movie_wildcard_supported` INTEGER, `series_wildcard_supported` INTEGER, `epg_supported` INTEGER, `safe_metadata_concurrency` INTEGER NOT NULL, `stress_cooldown_until` INTEGER NOT NULL, `endpoint_health_json` TEXT NOT NULL, `endpoint_failed_until` INTEGER NOT NULL, `validated_at` INTEGER NOT NULL, `schema_version` INTEGER NOT NULL, PRIMARY KEY(`provider_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "workingEndpoint",
+ "columnName": "working_endpoint",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bootstrapRecipe",
+ "columnName": "bootstrap_recipe",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "bulkLiveSupported",
+ "columnName": "bulk_live_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "bulkLiveCategoryFidelity",
+ "columnName": "bulk_live_category_fidelity",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "movieWildcardSupported",
+ "columnName": "movie_wildcard_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seriesWildcardSupported",
+ "columnName": "series_wildcard_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "epgSupported",
+ "columnName": "epg_supported",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "safeMetadataConcurrency",
+ "columnName": "safe_metadata_concurrency",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "stressCooldownUntil",
+ "columnName": "stress_cooldown_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endpointHealthJson",
+ "columnName": "endpoint_health_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "endpointFailedUntil",
+ "columnName": "endpoint_failed_until",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "validatedAt",
+ "columnName": "validated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "schemaVersion",
+ "columnName": "schema_version",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_portal_state_provider_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_portal_state_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_remote_identities",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `raw_id` TEXT NOT NULL, `surrogate_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `content_type`, `raw_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rawId",
+ "columnName": "raw_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "surrogateId",
+ "columnName": "surrogate_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "raw_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_remote_identities_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_stalker_remote_identities_provider_id_content_type_surrogate_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "content_type",
+ "surrogate_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stalker_remote_identities_provider_id_content_type_surrogate_id` ON `${TABLE_NAME}` (`provider_id`, `content_type`, `surrogate_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stalker_discovery_staging",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`discovery_id` TEXT NOT NULL, `provider_id` INTEGER, `configuration_generation` INTEGER NOT NULL, `sanitized_summary` TEXT NOT NULL, `categories_json` TEXT NOT NULL, `channels_json` TEXT NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`discovery_id`))",
+ "fields": [
+ {
+ "fieldPath": "discoveryId",
+ "columnName": "discovery_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "configurationGeneration",
+ "columnName": "configuration_generation",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sanitizedSummary",
+ "columnName": "sanitized_summary",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "categoriesJson",
+ "columnName": "categories_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "channelsJson",
+ "columnName": "channels_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "discovery_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_stalker_discovery_staging_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_discovery_staging_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_stalker_discovery_staging_created_at",
+ "unique": false,
+ "columnNames": [
+ "created_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_stalker_discovery_staging_created_at` ON `${TABLE_NAME}` (`created_at`)"
+ }
+ ]
+ },
+ {
+ "tableName": "downloads",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `content_type` TEXT NOT NULL, `content_id` INTEGER NOT NULL, `content_name` TEXT NOT NULL, `stream_url` TEXT NOT NULL, `source_stream_url` TEXT, `source_stream_id` INTEGER, `container_extension` TEXT, `poster_url` TEXT, `output_uri` TEXT, `output_display_path` TEXT, `status` TEXT NOT NULL, `bytes_written` INTEGER NOT NULL, `total_bytes` INTEGER, `supports_resume` INTEGER NOT NULL, `retry_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `completed_at` INTEGER, `failure_reason` TEXT, `series_id` INTEGER, `season_number` INTEGER, `episode_number` INTEGER, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentId",
+ "columnName": "content_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentName",
+ "columnName": "content_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamUrl",
+ "columnName": "stream_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sourceStreamUrl",
+ "columnName": "source_stream_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "sourceStreamId",
+ "columnName": "source_stream_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "containerExtension",
+ "columnName": "container_extension",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputUri",
+ "columnName": "output_uri",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "outputDisplayPath",
+ "columnName": "output_display_path",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "bytesWritten",
+ "columnName": "bytes_written",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalBytes",
+ "columnName": "total_bytes",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "supportsResume",
+ "columnName": "supports_resume",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "retryCount",
+ "columnName": "retry_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "completedAt",
+ "columnName": "completed_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "failureReason",
+ "columnName": "failure_reason",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesId",
+ "columnName": "series_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_downloads_status",
+ "unique": false,
+ "columnNames": [
+ "status"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_status` ON `${TABLE_NAME}` (`status`)"
+ },
+ {
+ "name": "index_downloads_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_downloads_content_type_content_id",
+ "unique": false,
+ "columnNames": [
+ "content_type",
+ "content_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_downloads_content_type_content_id` ON `${TABLE_NAME}` (`content_type`, `content_id`)"
+ }
+ ]
+ }
+ ],
+ "setupQueries": [
+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",
+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '1ba430e69c6bbe2b7e0459d6202ea8a6')"
+ ]
+ }
+}
\ No newline at end of file
diff --git a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
index 24f18635..14fa0383 100644
--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
@@ -1286,6 +1286,157 @@ class StreamVaultDatabaseMigrationTest {
migratedDb.close()
}
+ @Test
+ fun migrate62To64_addsStalkerStateAndStableCompatibilityProfile() {
+ migrationTestHelper.createDatabase("streamvault-62-64-test", 62).apply {
+ execSQL(
+ """
+ INSERT INTO providers (
+ id, name, type, server_url, username, password, m3u_url, epg_url,
+ http_user_agent, http_headers, stalker_mac_address, stalker_device_profile,
+ stalker_device_timezone, stalker_device_locale, stalker_serial_number,
+ stalker_device_id, stalker_device_id2, stalker_signature, stalker_advanced_options_json,
+ stalker_auth_mode, stalker_portal_profile, stalker_portal_fingerprint,
+ stalker_mag_preset, stalker_last_bootstrap_recipe, stalker_endpoint_preference,
+ stalker_cookie_mode, stalker_playback_backend_hint, stalker_last_playback_mode,
+ stalker_credentials_required, stalker_mac_required, stalker_uses_temp_links,
+ stalker_module_restricted, stalker_strict_fingerprint_required,
+ stalker_recipe_fallback_used, stalker_recipe_rediscovery_attempts,
+ is_active, max_connections, expiration_date, api_version,
+ allowed_output_formats_json, epg_sync_mode, guide_source_policy,
+ channel_logo_source_policy, xtream_fast_sync_enabled, xtream_live_sync_mode,
+ m3u_vod_classification_enabled, status, last_synced_at, created_at
+ ) VALUES (
+ 1, 'Migrated Stalker', 'STALKER_PORTAL', 'https://portal.invalid', '', '', '', '',
+ '', '', '00:1A:79:00:00:01', 'MAG250', 'Asia/Jerusalem', 'en', '', '', '', '', '',
+ 'AUTO', 'MAG_BASIC', 'BASIC_MAC', 'GENERIC_SAFE', 'GENERIC_SAFE', 'AUTO',
+ 'NONE', 'AUTO', NULL, 0, 1, 0, 0, 0, 0, 0,
+ 1, 1, NULL, NULL, '[]', 'BACKGROUND', 'AUTO', 'SUPPLIER_PREFERRED',
+ 0, 'AUTO', 0, 'ACTIVE', 1234, 5678
+ )
+ """.trimIndent()
+ )
+ execSQL("INSERT INTO categories (category_id, name, parent_id, type, provider_id, is_adult, is_user_protected, sync_fingerprint) VALUES (10, 'Movies', NULL, 'MOVIE', 1, 0, 0, 'cat')")
+ execSQL(
+ """
+ INSERT INTO movies (
+ stream_id, name, stream_url, duration_seconds, rating, provider_id,
+ watch_progress, watch_count, last_watched_at, is_adult, is_user_protected,
+ sync_fingerprint, added_at, cache_state, detail_hydrated_at, remote_stale_at
+ ) VALUES (99, 'Cached Movie', 'stalker://cached', 7200, 8.0, 1, 321, 2, 999, 0, 0, 'movie', 1, 'HYDRATED', 2, 0)
+ """.trimIndent()
+ )
+ execSQL("INSERT INTO favorites (provider_id, content_id, content_type, position, group_id, group_key, added_at) VALUES (1, 99, 'MOVIE', 0, NULL, 0, 100)")
+ execSQL(
+ """
+ INSERT INTO movie_category_hydration (
+ provider_id, category_id, last_hydrated_at, item_count, last_status,
+ last_error, last_loaded_page, last_attempted_page, last_successful_page,
+ total_pages, is_complete, page_size, retry_after_ms, failure_count,
+ retry_budget_remaining, last_page_fingerprint
+ ) VALUES (1, 10, 1000, 1, 'SUCCESS', NULL, 1, 1, 1, 3, 0, 18, 0, 0, 3, 'page-one')
+ """.trimIndent()
+ )
+ close()
+ }
+
+ val migratedDb = migrationTestHelper.runMigrationsAndValidate(
+ "streamvault-62-64-test",
+ 64,
+ true,
+ StreamVaultDatabase.MIGRATION_62_63,
+ StreamVaultDatabase.MIGRATION_63_64
+ )
+
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('providers') WHERE name = 'stalker_catalog_mode'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'stalker_index_jobs'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'stalker_portal_state'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'stalker_remote_identities'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('stalker_index_jobs') WHERE name = 'skipped_malformed_rows'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('stalker_portal_state') WHERE name = 'endpoint_health_json'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM providers WHERE id = 1 AND stalker_catalog_mode = 'ON_DEMAND'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM categories WHERE provider_id = 1 AND category_id = 10"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM movies WHERE provider_id = 1 AND stream_id = 99 AND watch_progress = 321 AND watch_count = 2"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM favorites WHERE provider_id = 1 AND content_id = 99"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM movie_category_hydration WHERE provider_id = 1 AND category_id = 10 AND last_loaded_page = 1"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM providers WHERE id = 1 AND stalker_requested_profile_id = 'classic.mag250.generic'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM providers WHERE id = 1 AND stalker_learned_profile_id = 'classic.mag250.generic' AND stalker_profile_revision = 1"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM providers WHERE id = 1 AND stalker_profile_verification = 'VERIFIED' AND stalker_protocol_family = 'CLASSIC_MAG'"))
+
+ migratedDb.close()
+ }
+
+ @Test
+ fun migrate64To65_addsScopedTransportAndResetsLegacyStalkerToStrict() {
+ migrationTestHelper.createDatabase("streamvault-64-65-test", 64).apply {
+ execSQL(
+ """
+ INSERT INTO providers (
+ id, name, type, server_url, username, password, m3u_url, epg_url,
+ http_user_agent, http_headers, stalker_mac_address, stalker_device_profile,
+ stalker_device_timezone, stalker_device_locale, stalker_serial_number,
+ stalker_device_id, stalker_device_id2, stalker_signature,
+ stalker_advanced_options_json, stalker_auth_mode, stalker_portal_profile,
+ stalker_portal_fingerprint, stalker_mag_preset, stalker_protocol_preference,
+ stalker_requested_profile_id, stalker_learned_profile_id,
+ stalker_profile_revision, stalker_profile_verification,
+ stalker_protocol_family, stalker_last_bootstrap_recipe,
+ stalker_endpoint_preference, stalker_cookie_mode,
+ stalker_playback_backend_hint, stalker_last_playback_mode,
+ stalker_credentials_required, stalker_mac_required,
+ stalker_uses_temp_links, stalker_module_restricted,
+ stalker_strict_fingerprint_required, stalker_recipe_fallback_used,
+ stalker_recipe_rediscovery_attempts, is_active, max_connections,
+ expiration_date, api_version, allowed_output_formats_json, epg_sync_mode,
+ stalker_catalog_mode, guide_source_policy, channel_logo_source_policy,
+ xtream_fast_sync_enabled, xtream_live_sync_mode,
+ m3u_vod_classification_enabled, status, last_synced_at, created_at
+ ) VALUES (
+ 1, 'Legacy HTTP Stalker', 'STALKER_PORTAL', 'http://portal.invalid', '', '', '', '',
+ '', '', '00:1A:79:00:00:01', 'MAG250', 'UTC', 'en', '', '', '', '',
+ '', 'AUTO', 'MAG_BASIC', 'BASIC_MAC', 'GENERIC_SAFE', 'CLASSIC_MAG',
+ 'classic.mag250.generic', 'classic.mag250.generic', 1, 'VERIFIED',
+ 'CLASSIC_MAG', 'GENERIC_SAFE', 'AUTO', 'NONE', 'AUTO', NULL,
+ 0, 1, 0, 0, 0, 0, 0, 1, 1,
+ NULL, NULL, '[]', 'BACKGROUND', 'ON_DEMAND', 'AUTO',
+ 'SUPPLIER_PREFERRED', 0, 'AUTO', 0, 'ACTIVE', 1234, 5678
+ )
+ """.trimIndent()
+ )
+ close()
+ }
+
+ val migratedDb = migrationTestHelper.runMigrationsAndValidate(
+ "streamvault-64-65-test",
+ 65,
+ true,
+ StreamVaultDatabase.MIGRATION_64_65
+ )
+
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('providers') WHERE name = 'stalker_transport_mode'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('providers') WHERE name = 'stalker_tls_spki_sha256'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM pragma_table_info('providers') WHERE name = 'stalker_configuration_generation'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'table' AND name = 'stalker_discovery_staging'"))
+ assertEquals(1, countRows(migratedDb, "SELECT COUNT(*) FROM sqlite_master WHERE type = 'index' AND name = 'index_stalker_discovery_staging_created_at'"))
+ assertEquals(
+ 1,
+ countRows(
+ migratedDb,
+ """
+ SELECT COUNT(*) FROM providers
+ WHERE id = 1
+ AND stalker_transport_mode = 'AUTO_STRICT'
+ AND stalker_transport_origin = ''
+ AND stalker_tls_spki_sha256 = ''
+ AND stalker_transport_consent_at = 0
+ AND status = 'PARTIAL'
+ AND is_active = 0
+ """.trimIndent()
+ )
+ )
+ migratedDb.close()
+ }
+
private fun countRows(db: androidx.sqlite.db.SupportSQLiteDatabase, sql: String): Int {
db.query(sql).use { cursor ->
if (!cursor.moveToFirst()) return 0
diff --git a/data/src/main/AndroidManifest.xml b/data/src/main/AndroidManifest.xml
index e0a7c31b..ec8d8efc 100644
--- a/data/src/main/AndroidManifest.xml
+++ b/data/src/main/AndroidManifest.xml
@@ -1,5 +1,8 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
+ <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
+ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
+
<application>
<service
android:name="com.streamvault.data.manager.recording.RecordingForegroundService"
diff --git a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt
index c7d5697a..7ccad946 100644
--- a/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt
+++ b/data/src/main/java/com/streamvault/data/local/RoomEnumConverters.kt
@@ -9,6 +9,7 @@ import com.streamvault.domain.model.ProviderStatus
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.model.StalkerCatalogMode
import com.streamvault.domain.model.StalkerBootstrapRecipe
import com.streamvault.domain.model.StalkerCookieMode
import com.streamvault.domain.model.StalkerEndpointPreference
@@ -16,6 +17,10 @@ import com.streamvault.domain.model.StalkerMagPreset
import com.streamvault.domain.model.StalkerPlaybackBackendHint
import com.streamvault.domain.model.StalkerPortalFingerprint
import com.streamvault.domain.model.StalkerPortalProfile
+import com.streamvault.domain.model.StalkerProfileVerification
+import com.streamvault.domain.model.StalkerProtocolFamily
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportMode
import java.util.logging.Logger
class RoomEnumConverters {
@@ -43,6 +48,13 @@ class RoomEnumConverters {
fun toProviderEpgSyncMode(value: String?): ProviderEpgSyncMode? =
enumValueOrDefault(value, ProviderEpgSyncMode.SKIP, providerEpgSyncModeAliases())
+ @TypeConverter
+ fun fromStalkerCatalogMode(value: StalkerCatalogMode?): String? = value?.name
+
+ @TypeConverter
+ fun toStalkerCatalogMode(value: String?): StalkerCatalogMode? =
+ enumValueOrDefault(value, StalkerCatalogMode.ON_DEMAND)
+
@TypeConverter
fun fromGuideSourcePolicy(value: GuideSourcePolicy?): String? = value?.name
@@ -92,6 +104,34 @@ class RoomEnumConverters {
fun toStalkerMagPreset(value: String?): StalkerMagPreset? =
enumValueOrDefault(value, StalkerMagPreset.GENERIC_SAFE)
+ @TypeConverter
+ fun fromStalkerProtocolPreference(value: StalkerProtocolPreference?): String? = value?.name
+
+ @TypeConverter
+ fun toStalkerProtocolPreference(value: String?): StalkerProtocolPreference? =
+ enumValueOrDefault(value, StalkerProtocolPreference.AUTO)
+
+ @TypeConverter
+ fun fromStalkerTransportMode(value: StalkerTransportMode?): String? = value?.name
+
+ @TypeConverter
+ fun toStalkerTransportMode(value: String?): StalkerTransportMode? =
+ enumValueOrDefault(value, StalkerTransportMode.AUTO_STRICT)
+
+ @TypeConverter
+ fun fromStalkerProfileVerification(value: StalkerProfileVerification?): String? = value?.name
+
+ @TypeConverter
+ fun toStalkerProfileVerification(value: String?): StalkerProfileVerification? =
+ enumValueOrDefault(value, StalkerProfileVerification.UNVERIFIED)
+
+ @TypeConverter
+ fun fromStalkerProtocolFamily(value: StalkerProtocolFamily?): String? = value?.name
+
+ @TypeConverter
+ fun toStalkerProtocolFamily(value: String?): StalkerProtocolFamily? =
+ enumValueOrDefault(value, StalkerProtocolFamily.CLASSIC_MAG)
+
@TypeConverter
fun fromStalkerBootstrapRecipe(value: StalkerBootstrapRecipe?): String? = value?.name
diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
index 9dacbd6f..a9ad832b 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
@@ -48,9 +48,13 @@ import com.streamvault.data.local.entity.*
XtreamContentIndexEntity::class,
XtreamIndexJobEntity::class,
XtreamLiveOnboardingStateEntity::class,
+ StalkerIndexJobEntity::class,
+ StalkerPortalStateEntity::class,
+ StalkerRemoteIdentityEntity::class,
+ StalkerDiscoveryStageEntity::class,
DownloadEntity::class
],
- version = 62,
+ version = 65,
exportSchema = true // ← was false; schema JSON now tracked in version control
)
@TypeConverters(RoomEnumConverters::class)
@@ -88,6 +92,10 @@ abstract class StreamVaultDatabase : RoomDatabase() {
abstract fun xtreamContentIndexDao(): XtreamContentIndexDao
abstract fun xtreamIndexJobDao(): XtreamIndexJobDao
abstract fun xtreamLiveOnboardingDao(): XtreamLiveOnboardingDao
+ abstract fun stalkerIndexJobDao(): StalkerIndexJobDao
+ abstract fun stalkerPortalStateDao(): StalkerPortalStateDao
+ abstract fun stalkerRemoteIdentityDao(): StalkerRemoteIdentityDao
+ abstract fun stalkerDiscoveryStageDao(): StalkerDiscoveryStageDao
abstract fun downloadDao(): DownloadDao
companion object {
@@ -2702,6 +2710,222 @@ abstract class StreamVaultDatabase : RoomDatabase() {
}
}
+ val MIGRATION_62_63 = object : Migration(62, 63) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ addColumnIfMissing(
+ database,
+ tableName = "providers",
+ columnName = "stalker_catalog_mode",
+ columnDefinition = "TEXT NOT NULL DEFAULT 'ON_DEMAND'"
+ )
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS stalker_index_jobs (
+ provider_id INTEGER NOT NULL,
+ section TEXT NOT NULL,
+ state TEXT NOT NULL DEFAULT 'DISABLED',
+ total_categories INTEGER NOT NULL DEFAULT 0,
+ completed_categories INTEGER NOT NULL DEFAULT 0,
+ next_category_index INTEGER NOT NULL DEFAULT 0,
+ failed_categories INTEGER NOT NULL DEFAULT 0,
+ indexed_rows INTEGER NOT NULL DEFAULT 0,
+ skipped_malformed_rows INTEGER NOT NULL DEFAULT 0,
+ deleted_pruned_rows INTEGER NOT NULL DEFAULT 0,
+ last_error TEXT,
+ last_attempt_at INTEGER NOT NULL DEFAULT 0,
+ last_success_at INTEGER NOT NULL DEFAULT 0,
+ updated_at INTEGER NOT NULL DEFAULT 0,
+ PRIMARY KEY(provider_id, section),
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_provider_id ON stalker_index_jobs(provider_id)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_state ON stalker_index_jobs(state)")
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_index_jobs_updated_at ON stalker_index_jobs(updated_at)")
+ database.execSQL(
+ """
+ INSERT OR REPLACE INTO stalker_index_jobs (
+ provider_id, section, state, total_categories, completed_categories,
+ next_category_index, failed_categories, indexed_rows, skipped_malformed_rows,
+ deleted_pruned_rows, last_error,
+ last_attempt_at, last_success_at, updated_at
+ )
+ SELECT j.provider_id, j.section, 'DISABLED', j.total_categories, j.completed_categories,
+ j.next_category_index, j.failed_categories, j.indexed_rows, j.skipped_malformed_rows,
+ j.deleted_pruned_rows, j.last_error,
+ j.last_attempt_at, j.last_success_at, j.updated_at
+ FROM xtream_index_jobs j
+ INNER JOIN providers p ON p.id = j.provider_id
+ WHERE p.type = 'STALKER_PORTAL' AND j.section IN ('MOVIE', 'SERIES')
+ """.trimIndent()
+ )
+ database.execSQL(
+ "DELETE FROM xtream_index_jobs WHERE provider_id IN (SELECT id FROM providers WHERE type = 'STALKER_PORTAL')"
+ )
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS stalker_portal_state (
+ provider_id INTEGER NOT NULL,
+ working_endpoint TEXT,
+ bootstrap_recipe TEXT,
+ bulk_live_supported INTEGER,
+ bulk_live_category_fidelity INTEGER,
+ movie_wildcard_supported INTEGER,
+ series_wildcard_supported INTEGER,
+ epg_supported INTEGER,
+ safe_metadata_concurrency INTEGER NOT NULL DEFAULT 2,
+ stress_cooldown_until INTEGER NOT NULL DEFAULT 0,
+ endpoint_health_json TEXT NOT NULL DEFAULT '{}',
+ endpoint_failed_until INTEGER NOT NULL DEFAULT 0,
+ validated_at INTEGER NOT NULL DEFAULT 0,
+ schema_version INTEGER NOT NULL DEFAULT 1,
+ PRIMARY KEY(provider_id),
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_stalker_portal_state_provider_id ON stalker_portal_state(provider_id)")
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS stalker_remote_identities (
+ provider_id INTEGER NOT NULL,
+ content_type TEXT NOT NULL,
+ raw_id TEXT NOT NULL,
+ surrogate_id INTEGER NOT NULL,
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ PRIMARY KEY(provider_id, content_type, raw_id),
+ FOREIGN KEY(provider_id) REFERENCES providers(id) ON UPDATE NO ACTION ON DELETE CASCADE
+ )
+ """.trimIndent()
+ )
+ database.execSQL("CREATE INDEX IF NOT EXISTS index_stalker_remote_identities_provider_id ON stalker_remote_identities(provider_id)")
+ database.execSQL("CREATE UNIQUE INDEX IF NOT EXISTS index_stalker_remote_identities_provider_id_content_type_surrogate_id ON stalker_remote_identities(provider_id, content_type, surrogate_id)")
+ validateForeignKeys(database, "providers", "stalker_index_jobs", "stalker_portal_state", "stalker_remote_identities")
+ }
+ }
+
+ val MIGRATION_63_64 = object : Migration(63, 64) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ addColumnIfMissing(database, "providers", "stalker_protocol_preference", "TEXT NOT NULL DEFAULT 'AUTO'")
+ addColumnIfMissing(database, "providers", "stalker_requested_profile_id", "TEXT NOT NULL DEFAULT 'auto'")
+ addColumnIfMissing(database, "providers", "stalker_learned_profile_id", "TEXT NOT NULL DEFAULT ''")
+ addColumnIfMissing(database, "providers", "stalker_profile_revision", "INTEGER NOT NULL DEFAULT 0")
+ addColumnIfMissing(database, "providers", "stalker_profile_verification", "TEXT NOT NULL DEFAULT 'UNVERIFIED'")
+ addColumnIfMissing(database, "providers", "stalker_protocol_family", "TEXT NOT NULL DEFAULT 'CLASSIC_MAG'")
+ database.execSQL(
+ """
+ UPDATE providers SET stalker_requested_profile_id = CASE stalker_mag_preset
+ WHEN 'MAG250_LEGACY' THEN 'classic.mag250.legacy'
+ WHEN 'MAG254_STRICT' THEN 'classic.mag254.strict'
+ WHEN 'MINISTRA_MODERN' THEN 'classic.mag322.modern'
+ ELSE 'classic.mag250.generic'
+ END,
+ stalker_learned_profile_id = CASE stalker_mag_preset
+ WHEN 'MAG250_LEGACY' THEN 'classic.mag250.legacy'
+ WHEN 'MAG254_STRICT' THEN 'classic.mag254.strict'
+ WHEN 'MINISTRA_MODERN' THEN 'classic.mag322.modern'
+ ELSE 'classic.mag250.generic'
+ END,
+ stalker_profile_revision = 1,
+ stalker_profile_verification = 'VERIFIED'
+ WHERE type = 'STALKER_PORTAL'
+ """.trimIndent()
+ )
+ validateForeignKeys(database, "providers")
+ }
+ }
+
+ val MIGRATION_64_65 = object : Migration(64, 65) {
+ override fun migrate(database: SupportSQLiteDatabase) {
+ addColumnIfMissing(
+ database,
+ "providers",
+ "stalker_transport_mode",
+ "TEXT NOT NULL DEFAULT 'AUTO_STRICT'"
+ )
+ addColumnIfMissing(
+ database,
+ "providers",
+ "stalker_transport_origin",
+ "TEXT NOT NULL DEFAULT ''"
+ )
+ addColumnIfMissing(
+ database,
+ "providers",
+ "stalker_tls_spki_sha256",
+ "TEXT NOT NULL DEFAULT ''"
+ )
+ addColumnIfMissing(
+ database,
+ "providers",
+ "stalker_transport_consent_at",
+ "INTEGER NOT NULL DEFAULT 0"
+ )
+ addColumnIfMissing(
+ database,
+ "providers",
+ "stalker_configuration_generation",
+ "INTEGER NOT NULL DEFAULT 0"
+ )
+ addColumnIfMissing(
+ database,
+ "providers",
+ "stalker_discovery_summary",
+ "TEXT NOT NULL DEFAULT ''"
+ )
+ addColumnIfMissing(
+ database,
+ "providers",
+ "stalker_capabilities_json",
+ "TEXT NOT NULL DEFAULT ''"
+ )
+ database.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS stalker_discovery_staging (
+ discovery_id TEXT NOT NULL PRIMARY KEY,
+ provider_id INTEGER,
+ configuration_generation INTEGER NOT NULL,
+ sanitized_summary TEXT NOT NULL,
+ categories_json TEXT NOT NULL,
+ channels_json TEXT NOT NULL,
+ created_at INTEGER NOT NULL
+ )
+ """.trimIndent()
+ )
+ database.execSQL(
+ "CREATE INDEX IF NOT EXISTS index_stalker_discovery_staging_provider_id ON stalker_discovery_staging(provider_id)"
+ )
+ database.execSQL(
+ "CREATE INDEX IF NOT EXISTS index_stalker_discovery_staging_created_at ON stalker_discovery_staging(created_at)"
+ )
+ // Existing installs used a global trust-all client. They deliberately migrate to
+ // strict verification and must consent in the foreground if their portal needs
+ // HTTP or invalid TLS.
+ database.execSQL(
+ """
+ UPDATE providers
+ SET stalker_transport_mode = 'AUTO_STRICT',
+ stalker_transport_origin = '',
+ stalker_tls_spki_sha256 = '',
+ stalker_transport_consent_at = 0
+ WHERE type = 'STALKER_PORTAL'
+ """.trimIndent()
+ )
+ database.execSQL(
+ """
+ UPDATE providers
+ SET status = 'PARTIAL',
+ is_active = 0
+ WHERE type = 'STALKER_PORTAL'
+ AND lower(server_url) LIKE 'http://%'
+ """.trimIndent()
+ )
+ validateForeignKeys(database, "providers")
+ }
+ }
+
val MIGRATION_52_53 = object : Migration(52, 53) {
override fun migrate(database: SupportSQLiteDatabase) {
addStalkerHardeningColumns(database, "movie_category_hydration")
diff --git a/data/src/main/java/com/streamvault/data/local/dao/StalkerSyncDaos.kt b/data/src/main/java/com/streamvault/data/local/dao/StalkerSyncDaos.kt
new file mode 100644
index 00000000..c428df77
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/dao/StalkerSyncDaos.kt
@@ -0,0 +1,77 @@
+package com.streamvault.data.local.dao
+
+import androidx.room.Dao
+import androidx.room.Insert
+import androidx.room.OnConflictStrategy
+import androidx.room.Query
+import com.streamvault.data.local.entity.StalkerIndexJobEntity
+import com.streamvault.data.local.entity.StalkerPortalStateEntity
+import com.streamvault.data.local.entity.StalkerRemoteIdentityEntity
+import com.streamvault.data.local.entity.StalkerDiscoveryStageEntity
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+interface StalkerIndexJobDao {
+ @Query("SELECT * FROM stalker_index_jobs WHERE provider_id = :providerId ORDER BY updated_at ASC, section ASC")
+ fun observeForProvider(providerId: Long): Flow<List<StalkerIndexJobEntity>>
+
+ @Query("SELECT * FROM stalker_index_jobs WHERE provider_id = :providerId AND section = :section LIMIT 1")
+ suspend fun get(providerId: Long, section: String): StalkerIndexJobEntity?
+
+ @Query("SELECT * FROM stalker_index_jobs WHERE provider_id = :providerId AND state IN ('QUEUED','RETRY_WAIT','PARTIAL') ORDER BY updated_at ASC LIMIT 1")
+ suspend fun getNextPending(providerId: Long): StalkerIndexJobEntity?
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(entity: StalkerIndexJobEntity)
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsertAll(entities: List<StalkerIndexJobEntity>)
+
+ @Query("UPDATE stalker_index_jobs SET state = 'DISABLED', updated_at = :updatedAt WHERE provider_id = :providerId")
+ suspend fun disableForProvider(providerId: Long, updatedAt: Long): Int
+
+ @Query("DELETE FROM stalker_index_jobs WHERE provider_id = :providerId")
+ suspend fun deleteByProvider(providerId: Long): Int
+}
+
+@Dao
+interface StalkerPortalStateDao {
+ @Query("SELECT * FROM stalker_portal_state WHERE provider_id = :providerId LIMIT 1")
+ suspend fun get(providerId: Long): StalkerPortalStateEntity?
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(entity: StalkerPortalStateEntity)
+
+ @Query("DELETE FROM stalker_portal_state WHERE provider_id = :providerId")
+ suspend fun invalidate(providerId: Long): Int
+}
+
+@Dao
+interface StalkerRemoteIdentityDao {
+ @Query("SELECT * FROM stalker_remote_identities WHERE provider_id = :providerId AND content_type = :contentType AND raw_id = :rawId LIMIT 1")
+ suspend fun getByRawId(providerId: Long, contentType: String, rawId: String): StalkerRemoteIdentityEntity?
+
+ @Query("SELECT * FROM stalker_remote_identities WHERE provider_id = :providerId AND content_type = :contentType AND surrogate_id = :surrogateId LIMIT 1")
+ suspend fun getBySurrogateId(providerId: Long, contentType: String, surrogateId: Long): StalkerRemoteIdentityEntity?
+
+ @Query("SELECT MAX(surrogate_id) FROM stalker_remote_identities WHERE provider_id = :providerId AND content_type = :contentType AND surrogate_id >= :floor")
+ suspend fun maxAllocatedSurrogate(providerId: Long, contentType: String, floor: Long): Long?
+
+ @Insert(onConflict = OnConflictStrategy.ABORT)
+ suspend fun insert(entity: StalkerRemoteIdentityEntity)
+}
+
+@Dao
+interface StalkerDiscoveryStageDao {
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(entity: StalkerDiscoveryStageEntity)
+
+ @Query("SELECT * FROM stalker_discovery_staging WHERE discovery_id = :discoveryId LIMIT 1")
+ suspend fun get(discoveryId: String): StalkerDiscoveryStageEntity?
+
+ @Query("DELETE FROM stalker_discovery_staging WHERE discovery_id = :discoveryId")
+ suspend fun delete(discoveryId: String): Int
+
+ @Query("DELETE FROM stalker_discovery_staging WHERE created_at < :cutoff")
+ suspend fun deleteOlderThan(cutoff: Long): Int
+}
diff --git a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
index d5ba355d..61e58f4d 100644
--- a/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
+++ b/data/src/main/java/com/streamvault/data/local/entity/Entities.kt
@@ -21,6 +21,12 @@ import com.streamvault.domain.model.StalkerPlaybackBackendHint
import com.streamvault.domain.model.StalkerPortalFingerprint
import com.streamvault.domain.model.StalkerPortalProfile
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProfileVerification
+import com.streamvault.domain.model.StalkerProtocolFamily
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportMode
@Entity(
tableName = "providers",
@@ -51,6 +57,19 @@ data class ProviderEntity(
@ColumnInfo(name = "stalker_portal_profile") val stalkerPortalProfile: StalkerPortalProfile = StalkerPortalProfile.MAG_BASIC,
@ColumnInfo(name = "stalker_portal_fingerprint") val stalkerPortalFingerprint: StalkerPortalFingerprint = StalkerPortalFingerprint.BASIC_MAC,
@ColumnInfo(name = "stalker_mag_preset") val stalkerMagPreset: StalkerMagPreset = StalkerMagPreset.GENERIC_SAFE,
+ @ColumnInfo(name = "stalker_protocol_preference") val stalkerProtocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ @ColumnInfo(name = "stalker_transport_mode") val stalkerTransportMode: StalkerTransportMode = StalkerTransportMode.AUTO_STRICT,
+ @ColumnInfo(name = "stalker_transport_origin") val stalkerTransportOrigin: String = "",
+ @ColumnInfo(name = "stalker_tls_spki_sha256") val stalkerTlsSpkiSha256: String = "",
+ @ColumnInfo(name = "stalker_transport_consent_at") val stalkerTransportConsentAt: Long = 0L,
+ @ColumnInfo(name = "stalker_configuration_generation") val stalkerConfigurationGeneration: Long = 0L,
+ @ColumnInfo(name = "stalker_discovery_summary") val stalkerDiscoverySummary: String = "",
+ @ColumnInfo(name = "stalker_capabilities_json") val stalkerCapabilitiesJson: String = "",
+ @ColumnInfo(name = "stalker_requested_profile_id") val stalkerRequestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
+ @ColumnInfo(name = "stalker_learned_profile_id") val stalkerLearnedProfileId: String = "",
+ @ColumnInfo(name = "stalker_profile_revision") val stalkerProfileRevision: Int = 0,
+ @ColumnInfo(name = "stalker_profile_verification") val stalkerProfileVerification: StalkerProfileVerification = StalkerProfileVerification.UNVERIFIED,
+ @ColumnInfo(name = "stalker_protocol_family") val stalkerProtocolFamily: StalkerProtocolFamily = StalkerProtocolFamily.CLASSIC_MAG,
@ColumnInfo(name = "stalker_last_bootstrap_recipe") val stalkerLastBootstrapRecipe: StalkerBootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,
@ColumnInfo(name = "stalker_endpoint_preference") val stalkerEndpointPreference: StalkerEndpointPreference = StalkerEndpointPreference.AUTO,
@ColumnInfo(name = "stalker_cookie_mode") val stalkerCookieMode: StalkerCookieMode = StalkerCookieMode.NONE,
@@ -69,6 +88,7 @@ data class ProviderEntity(
@ColumnInfo(name = "api_version") val apiVersion: String? = null,
@ColumnInfo(name = "allowed_output_formats_json") val allowedOutputFormatsJson: String = "[]",
@ColumnInfo(name = "epg_sync_mode") val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,
+ @ColumnInfo(name = "stalker_catalog_mode") val stalkerCatalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,
@ColumnInfo(name = "guide_source_policy") val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,
@ColumnInfo(name = "channel_logo_source_policy") val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,
@ColumnInfo(name = "xtream_fast_sync_enabled") val xtreamFastSyncEnabled: Boolean = false,
diff --git a/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt b/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt
new file mode 100644
index 00000000..6499aaaa
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/entity/StalkerSyncEntities.kt
@@ -0,0 +1,111 @@
+package com.streamvault.data.local.entity
+
+import androidx.room.ColumnInfo
+import androidx.room.Entity
+import androidx.room.ForeignKey
+import androidx.room.Index
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.StalkerIndexState
+
+@Entity(
+ tableName = "stalker_index_jobs",
+ primaryKeys = ["provider_id", "section"],
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id"]),
+ Index(value = ["state"]),
+ Index(value = ["updated_at"])
+ ]
+)
+data class StalkerIndexJobEntity(
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ val section: ContentType,
+ val state: StalkerIndexState = StalkerIndexState.DISABLED,
+ @ColumnInfo(name = "total_categories") val totalCategories: Int = 0,
+ @ColumnInfo(name = "completed_categories") val completedCategories: Int = 0,
+ @ColumnInfo(name = "next_category_index") val nextCategoryIndex: Int = 0,
+ @ColumnInfo(name = "failed_categories") val failedCategories: Int = 0,
+ @ColumnInfo(name = "indexed_rows") val indexedRows: Int = 0,
+ @ColumnInfo(name = "skipped_malformed_rows") val skippedMalformedRows: Int = 0,
+ @ColumnInfo(name = "deleted_pruned_rows") val deletedPrunedRows: Int = 0,
+ @ColumnInfo(name = "last_error") val lastError: String? = null,
+ @ColumnInfo(name = "last_attempt_at") val lastAttemptAt: Long = 0L,
+ @ColumnInfo(name = "last_success_at") val lastSuccessAt: Long = 0L,
+ @ColumnInfo(name = "updated_at") val updatedAt: Long = 0L
+)
+
+@Entity(
+ tableName = "stalker_portal_state",
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [Index(value = ["provider_id"], unique = true)]
+)
+data class StalkerPortalStateEntity(
+ @androidx.room.PrimaryKey
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "working_endpoint") val workingEndpoint: String? = null,
+ @ColumnInfo(name = "bootstrap_recipe") val bootstrapRecipe: String? = null,
+ @ColumnInfo(name = "bulk_live_supported") val bulkLiveSupported: Boolean? = null,
+ @ColumnInfo(name = "bulk_live_category_fidelity") val bulkLiveCategoryFidelity: Boolean? = null,
+ @ColumnInfo(name = "movie_wildcard_supported") val movieWildcardSupported: Boolean? = null,
+ @ColumnInfo(name = "series_wildcard_supported") val seriesWildcardSupported: Boolean? = null,
+ @ColumnInfo(name = "epg_supported") val epgSupported: Boolean? = null,
+ @ColumnInfo(name = "safe_metadata_concurrency") val safeMetadataConcurrency: Int = 2,
+ @ColumnInfo(name = "stress_cooldown_until") val stressCooldownUntil: Long = 0L,
+ /** JSON map of SHA-256 endpoint/recipe keys to cooldown expiry; never stores raw values. */
+ @ColumnInfo(name = "endpoint_health_json") val endpointHealthJson: String = "{}",
+ @ColumnInfo(name = "endpoint_failed_until") val endpointFailedUntil: Long = 0L,
+ @ColumnInfo(name = "validated_at") val validatedAt: Long = 0L,
+ @ColumnInfo(name = "schema_version") val schemaVersion: Int = 1
+)
+
+@Entity(
+ tableName = "stalker_remote_identities",
+ primaryKeys = ["provider_id", "content_type", "raw_id"],
+ foreignKeys = [ForeignKey(
+ entity = ProviderEntity::class,
+ parentColumns = ["id"],
+ childColumns = ["provider_id"],
+ onDelete = ForeignKey.CASCADE
+ )],
+ indices = [
+ Index(value = ["provider_id"]),
+ Index(value = ["provider_id", "content_type", "surrogate_id"], unique = true)
+ ]
+)
+data class StalkerRemoteIdentityEntity(
+ @ColumnInfo(name = "provider_id") val providerId: Long,
+ @ColumnInfo(name = "content_type") val contentType: ContentType,
+ @ColumnInfo(name = "raw_id") val rawId: String,
+ @ColumnInfo(name = "surrogate_id") val surrogateId: Long,
+ @ColumnInfo(name = "created_at") val createdAt: Long,
+ @ColumnInfo(name = "updated_at") val updatedAt: Long
+)
+
+@Entity(
+ tableName = "stalker_discovery_staging",
+ indices = [
+ Index(value = ["provider_id"]),
+ Index(value = ["created_at"])
+ ]
+)
+data class StalkerDiscoveryStageEntity(
+ @androidx.room.PrimaryKey
+ @ColumnInfo(name = "discovery_id") val discoveryId: String,
+ @ColumnInfo(name = "provider_id") val providerId: Long?,
+ @ColumnInfo(name = "configuration_generation") val configurationGeneration: Long,
+ /** Sanitized summary only; no credentials, cookies, tokens, bodies, or stream URLs. */
+ @ColumnInfo(name = "sanitized_summary") val sanitizedSummary: String,
+ @ColumnInfo(name = "categories_json") val categoriesJson: String = "[]",
+ @ColumnInfo(name = "channels_json") val channelsJson: String = "[]",
+ @ColumnInfo(name = "created_at") val createdAt: Long
+)
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 fac5c50f..c6203283 100644
--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
@@ -20,6 +20,7 @@ import com.streamvault.data.mapper.toEntity
import com.streamvault.data.preferences.ParentalPinBackupData
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.security.CredentialCrypto
+import com.streamvault.data.remote.stalker.StalkerCompatibilityRegistry
import com.streamvault.domain.manager.BackupData
import com.streamvault.domain.manager.BackupConflictStrategy
import com.streamvault.domain.manager.BackupImportPlan
@@ -39,6 +40,14 @@ import com.streamvault.domain.model.RecordingRecurrence
import com.streamvault.domain.model.RecordingRequest
import com.streamvault.domain.model.RecordingStatus
import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.StalkerBootstrapRecipe
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerProfileVerification
+import com.streamvault.domain.model.StalkerProtocolFamily
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportMode
import com.streamvault.domain.repository.CategoryRepository
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.Dispatchers
@@ -140,7 +149,14 @@ class BackupManagerImpl @Inject constructor(
val providers = providerEntities.map { entity ->
entity.toDomain().copy(
password = "", // Strip credentials from backup export
- username = entity.toDomain().username // Keep username for provider identification
+ username = entity.toDomain().username, // Keep username for provider identification
+ stalkerLastBootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,
+ stalkerLastPlaybackMode = null,
+ // Transport consent is device-local. A restore must verify or ask again.
+ stalkerTransportMode = StalkerTransportMode.AUTO_STRICT,
+ stalkerTransportOrigin = "",
+ stalkerTlsSpkiSha256 = "",
+ stalkerTransportConsentAt = 0L
)
}
val providerIds = providerEntities.map { it.id }
@@ -724,7 +740,52 @@ class BackupManagerImpl @Inject constructor(
return@forEach
}
val entity = provider.copy(
- id = existing?.id ?: 0L
+ id = existing?.id ?: 0L,
+ stalkerCatalogMode = if (backupData.version < 9) {
+ StalkerCatalogMode.ON_DEMAND
+ } else {
+ provider.stalkerCatalogMode
+ },
+ stalkerProtocolPreference = if (backupData.version < 10) {
+ StalkerProtocolPreference.AUTO
+ } else provider.stalkerProtocolPreference,
+ stalkerRequestedProfileId = if (backupData.version < 10) {
+ StalkerCompatibilityRegistry.idForLegacyPreset(provider.stalkerMagPreset)
+ } else provider.stalkerRequestedProfileId,
+ stalkerLearnedProfileId = if (backupData.version < 10) {
+ StalkerCompatibilityRegistry.idForLegacyPreset(provider.stalkerMagPreset)
+ } else provider.stalkerLearnedProfileId,
+ stalkerProfileRevision = if (backupData.version < 10) {
+ StalkerCompatibilityRegistry.REVISION
+ } else provider.stalkerProfileRevision,
+ stalkerProfileVerification = if (backupData.version < 10) {
+ StalkerProfileVerification.VERIFIED
+ } else provider.stalkerProfileVerification,
+ stalkerProtocolFamily = if (backupData.version < 10) {
+ StalkerProtocolFamily.CLASSIC_MAG
+ } else provider.stalkerProtocolFamily,
+ stalkerLastBootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,
+ stalkerLastPlaybackMode = null,
+ stalkerTransportMode = StalkerTransportMode.AUTO_STRICT,
+ stalkerTransportOrigin = "",
+ stalkerTlsSpkiSha256 = "",
+ stalkerTransportConsentAt = 0L,
+ isActive = if (
+ provider.type == ProviderType.STALKER_PORTAL &&
+ provider.serverUrl.startsWith("http://", ignoreCase = true)
+ ) {
+ false
+ } else {
+ provider.isActive
+ },
+ status = if (
+ provider.type == ProviderType.STALKER_PORTAL &&
+ provider.serverUrl.startsWith("http://", ignoreCase = true)
+ ) {
+ ProviderStatus.PARTIAL
+ } else {
+ provider.status
+ }
).toSecureEntityForBackup(credentialCrypto)
providerDao.insert(entity)
}
@@ -1126,7 +1187,7 @@ private fun Iterable<ProviderEntity>.findMatchingProvider(
}
private const val SHA256_PREFIX = "sha256:"
-private const val CURRENT_BACKUP_VERSION = 8
+private const val CURRENT_BACKUP_VERSION = 10
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
diff --git a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt
index 804120b5..9f7912d1 100644
--- a/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt
+++ b/data/src/main/java/com/streamvault/data/manager/reminder/ProgramReminderNotifier.kt
@@ -1,12 +1,15 @@
package com.streamvault.data.manager.reminder
+import android.Manifest
import android.app.NotificationChannel
import android.app.NotificationManager
import android.app.PendingIntent
import android.content.Context
+import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
+import androidx.core.content.ContextCompat
import com.streamvault.data.local.entity.ProgramReminderEntity
import dagger.hilt.android.qualifiers.ApplicationContext
import javax.inject.Inject
@@ -19,6 +22,12 @@ class ProgramReminderNotifier @Inject constructor(
fun showReminder(reminder: ProgramReminderEntity) {
createChannelIfNeeded()
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU &&
+ ContextCompat.checkSelfPermission(context, Manifest.permission.POST_NOTIFICATIONS) !=
+ PackageManager.PERMISSION_GRANTED
+ ) {
+ return
+ }
val now = System.currentTimeMillis()
val minutesUntilStart = ((reminder.programStartTime - now) / 60000L).coerceAtLeast(0L)
val contentText = if (minutesUntilStart <= 0L) {
diff --git a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
index 6a56ddf5..2c8e9c6f 100644
--- a/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
+++ b/data/src/main/java/com/streamvault/data/mapper/EntityMappers.kt
@@ -39,6 +39,19 @@ fun ProviderEntity.toDomain() = Provider(
stalkerPortalProfile = stalkerPortalProfile,
stalkerPortalFingerprint = stalkerPortalFingerprint,
stalkerMagPreset = stalkerMagPreset,
+ stalkerProtocolPreference = stalkerProtocolPreference,
+ stalkerTransportMode = stalkerTransportMode,
+ stalkerTransportOrigin = stalkerTransportOrigin,
+ stalkerTlsSpkiSha256 = stalkerTlsSpkiSha256,
+ stalkerTransportConsentAt = stalkerTransportConsentAt,
+ stalkerConfigurationGeneration = stalkerConfigurationGeneration,
+ stalkerDiscoverySummary = stalkerDiscoverySummary,
+ stalkerCapabilitiesJson = stalkerCapabilitiesJson,
+ stalkerRequestedProfileId = stalkerRequestedProfileId,
+ stalkerLearnedProfileId = stalkerLearnedProfileId,
+ stalkerProfileRevision = stalkerProfileRevision,
+ stalkerProfileVerification = stalkerProfileVerification,
+ stalkerProtocolFamily = stalkerProtocolFamily,
stalkerLastBootstrapRecipe = stalkerLastBootstrapRecipe,
stalkerEndpointPreference = stalkerEndpointPreference,
stalkerCookieMode = stalkerCookieMode,
@@ -57,6 +70,7 @@ fun ProviderEntity.toDomain() = Provider(
apiVersion = apiVersion,
allowedOutputFormats = decodeAllowedOutputFormats(allowedOutputFormatsJson),
epgSyncMode = epgSyncMode,
+ stalkerCatalogMode = stalkerCatalogMode,
guideSourcePolicy = guideSourcePolicy,
channelLogoSourcePolicy = channelLogoSourcePolicy,
xtreamFastSyncEnabled = xtreamFastSyncEnabled,
@@ -91,6 +105,19 @@ fun Provider.toEntity() = ProviderEntity(
stalkerPortalProfile = stalkerPortalProfile,
stalkerPortalFingerprint = stalkerPortalFingerprint,
stalkerMagPreset = stalkerMagPreset,
+ stalkerProtocolPreference = stalkerProtocolPreference,
+ stalkerTransportMode = stalkerTransportMode,
+ stalkerTransportOrigin = stalkerTransportOrigin,
+ stalkerTlsSpkiSha256 = stalkerTlsSpkiSha256,
+ stalkerTransportConsentAt = stalkerTransportConsentAt,
+ stalkerConfigurationGeneration = stalkerConfigurationGeneration,
+ stalkerDiscoverySummary = stalkerDiscoverySummary,
+ stalkerCapabilitiesJson = stalkerCapabilitiesJson,
+ stalkerRequestedProfileId = stalkerRequestedProfileId,
+ stalkerLearnedProfileId = stalkerLearnedProfileId,
+ stalkerProfileRevision = stalkerProfileRevision,
+ stalkerProfileVerification = stalkerProfileVerification,
+ stalkerProtocolFamily = stalkerProtocolFamily,
stalkerLastBootstrapRecipe = stalkerLastBootstrapRecipe,
stalkerEndpointPreference = stalkerEndpointPreference,
stalkerCookieMode = stalkerCookieMode,
@@ -109,6 +136,7 @@ fun Provider.toEntity() = ProviderEntity(
apiVersion = apiVersion,
allowedOutputFormatsJson = encodeAllowedOutputFormats(allowedOutputFormats),
epgSyncMode = epgSyncMode,
+ stalkerCatalogMode = stalkerCatalogMode,
guideSourcePolicy = guideSourcePolicy,
channelLogoSourcePolicy = channelLogoSourcePolicy,
xtreamFastSyncEnabled = xtreamFastSyncEnabled,
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/MinistraApiV3Provider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/MinistraApiV3Provider.kt
new file mode 100644
index 00000000..8e469876
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/MinistraApiV3Provider.kt
@@ -0,0 +1,175 @@
+package com.streamvault.data.remote.stalker
+
+import android.content.Context
+import com.streamvault.data.security.CredentialCrypto
+import com.streamvault.domain.model.Category
+import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.Program
+import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.Series
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProfileVerification
+import com.streamvault.domain.model.StalkerProtocolFamily
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.provider.IptvProvider
+import java.io.IOException
+import dagger.hilt.android.qualifiers.ApplicationContext
+import javax.inject.Inject
+import javax.inject.Singleton
+
+data class MinistraApiV3Credentials(
+ val portalUrl: String,
+ val login: String,
+ val password: String,
+ val macAddress: String = "",
+ val serialNumber: String = "",
+ val activationCode: String = ""
+)
+
+data class MinistraApiV3Token(
+ val accessToken: String,
+ val refreshToken: String = "",
+ val expiresAt: Long
+) {
+ fun isUsable(now: Long = System.currentTimeMillis()): Boolean =
+ accessToken.isNotBlank() && expiresAt > now + 30_000L
+}
+
+/** Implementations must encrypt values at rest; tokens never belong in Provider or backups. */
+interface MinistraApiV3TokenStore {
+ suspend fun read(providerId: Long): MinistraApiV3Token?
+ suspend fun write(providerId: Long, token: MinistraApiV3Token)
+ suspend fun clear(providerId: Long)
+}
+
+@Singleton
+class EncryptedMinistraApiV3TokenStore @Inject constructor(
+ @ApplicationContext context: Context,
+ private val credentialCrypto: CredentialCrypto
+) : MinistraApiV3TokenStore {
+ private val preferences = context.getSharedPreferences("ministra_api_v3_tokens", Context.MODE_PRIVATE)
+
+ override suspend fun read(providerId: Long): MinistraApiV3Token? {
+ val access = preferences.getString("$providerId.access", null) ?: return null
+ return runCatching {
+ MinistraApiV3Token(
+ accessToken = credentialCrypto.decryptIfNeeded(access),
+ refreshToken = preferences.getString("$providerId.refresh", "").orEmpty()
+ .let(credentialCrypto::decryptIfNeeded),
+ expiresAt = preferences.getString("$providerId.expiry", "").orEmpty()
+ .let(credentialCrypto::decryptIfNeeded).toLong()
+ )
+ }.getOrNull()
+ }
+
+ override suspend fun write(providerId: Long, token: MinistraApiV3Token) {
+ preferences.edit()
+ .putString("$providerId.access", credentialCrypto.encryptIfNeeded(token.accessToken))
+ .putString("$providerId.refresh", credentialCrypto.encryptIfNeeded(token.refreshToken))
+ .putString("$providerId.expiry", credentialCrypto.encryptIfNeeded(token.expiresAt.toString()))
+ .apply()
+ }
+
+ override suspend fun clear(providerId: Long) {
+ preferences.edit()
+ .remove("$providerId.access")
+ .remove("$providerId.refresh")
+ .remove("$providerId.expiry")
+ .apply()
+ Unit
+ }
+}
+
+/** Transport contract for a provider-documented API-v3 deployment. */
+interface MinistraApiV3Client {
+ suspend fun authenticate(credentials: MinistraApiV3Credentials): MinistraApiV3Token
+ suspend fun refresh(refreshToken: String): MinistraApiV3Token
+ suspend fun liveCategories(token: String): List<Category>
+ suspend fun live(token: String, categoryId: Long?): List<Channel>
+ suspend fun vodCategories(token: String): List<Category>
+ suspend fun vod(token: String, categoryId: Long?): List<Movie>
+ suspend fun vodInfo(token: String, id: Long): Movie
+ suspend fun seriesCategories(token: String): List<Category>
+ suspend fun series(token: String, categoryId: Long?): List<Series>
+ suspend fun seriesInfo(token: String, id: Long): Series
+ suspend fun epg(token: String, channelId: String, limit: Int?): List<Program>
+ suspend fun playback(token: String, type: ContentType, id: Long): String
+ suspend fun catchUp(token: String, id: Long, start: Long, end: Long): String?
+}
+
+class MinistraLicenseRequiredException(message: String) : IOException(message)
+class MinistraApiV3CompatibilityException(message: String, cause: Throwable? = null) : IOException(message, cause)
+
+/**
+ * Android MAG support. This class cannot share classic cookies, tokens, fingerprints, or identity
+ * generation. A concrete client is enabled only for a provider-documented API-v3 contract.
+ */
+class MinistraApiV3Provider(
+ override val providerId: Long,
+ private val credentials: MinistraApiV3Credentials,
+ private val requestedProfileId: String,
+ private val client: MinistraApiV3Client,
+ private val tokenStore: MinistraApiV3TokenStore
+) : IptvProvider {
+ private var memoryToken: MinistraApiV3Token? = null
+
+ override suspend fun authenticate(): Result<Provider> = apiCall("Ministra API-v3 authentication failed") {
+ token(forceLogin = true)
+ Provider(
+ id = providerId,
+ name = credentials.login.ifBlank { "Ministra API v3" },
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = credentials.portalUrl,
+ username = credentials.login,
+ password = credentials.password,
+ stalkerMacAddress = credentials.macAddress,
+ stalkerSerialNumber = credentials.serialNumber,
+ stalkerProtocolPreference = StalkerProtocolPreference.MINISTRA_API_V3,
+ stalkerRequestedProfileId = requestedProfileId.ifBlank { StalkerCompatibilityProfileIds.AUTO },
+ stalkerLearnedProfileId = requestedProfileId,
+ stalkerProfileRevision = StalkerCompatibilityRegistry.REVISION,
+ stalkerProfileVerification = StalkerCompatibilityRegistry.find(requestedProfileId)?.verification
+ ?: StalkerProfileVerification.UNVERIFIED,
+ stalkerProtocolFamily = StalkerProtocolFamily.MINISTRA_API_V3,
+ apiVersion = "Ministra API v3",
+ status = ProviderStatus.PARTIAL
+ )
+ }
+
+ override suspend fun getLiveCategories() = apiCall("Failed to load API-v3 live categories") { client.liveCategories(token().accessToken) }
+ override suspend fun getLiveStreams(categoryId: Long?) = apiCall("Failed to load API-v3 live channels") { client.live(token().accessToken, categoryId) }
+ override suspend fun getVodCategories() = apiCall("Failed to load API-v3 VOD categories") { client.vodCategories(token().accessToken) }
+ override suspend fun getVodStreams(categoryId: Long?) = apiCall("Failed to load API-v3 VOD") { client.vod(token().accessToken, categoryId) }
+ override suspend fun getVodInfo(vodId: Long) = apiCall("Failed to load API-v3 VOD details") { client.vodInfo(token().accessToken, vodId) }
+ override suspend fun getSeriesCategories() = apiCall("Failed to load API-v3 series categories") { client.seriesCategories(token().accessToken) }
+ override suspend fun getSeriesList(categoryId: Long?) = apiCall("Failed to load API-v3 series") { client.series(token().accessToken, categoryId) }
+ override suspend fun getSeriesInfo(seriesId: Long) = apiCall("Failed to load API-v3 series details") { client.seriesInfo(token().accessToken, seriesId) }
+ override suspend fun getEpg(channelId: String) = apiCall("Failed to load API-v3 EPG") { client.epg(token().accessToken, channelId, null) }
+ override suspend fun getShortEpg(channelId: String, limit: Int) = apiCall("Failed to load API-v3 EPG") { client.epg(token().accessToken, channelId, limit) }
+ override suspend fun buildStreamUrl(streamId: Long, containerExtension: String?): String = client.playback(token().accessToken, ContentType.LIVE, streamId)
+ override suspend fun buildCatchUpUrl(streamId: Long, start: Long, end: Long): String? = client.catchUp(token().accessToken, streamId, start, end)
+
+ private suspend fun token(forceLogin: Boolean = false): MinistraApiV3Token {
+ val cached = memoryToken ?: tokenStore.read(providerId)
+ if (!forceLogin && cached?.isUsable() == true) return cached.also { memoryToken = it }
+ val renewed = if (!forceLogin && !cached?.refreshToken.isNullOrBlank()) {
+ runCatching { client.refresh(cached!!.refreshToken) }.getOrNull()
+ } else null
+ val resolved = renewed ?: client.authenticate(credentials)
+ if (!resolved.isUsable()) throw MinistraApiV3CompatibilityException("API-v3 returned an invalid or expired token.")
+ memoryToken = resolved
+ tokenStore.write(providerId, resolved)
+ return resolved
+ }
+
+ private suspend fun <T> apiCall(message: String, block: suspend () -> T): Result<T> = try {
+ Result.success(block())
+ } catch (error: Exception) {
+ Result.error(error.message ?: message, error)
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt
index ee53b98c..6fa8e193 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiService.kt
@@ -14,6 +14,10 @@ import com.streamvault.domain.model.StalkerMagPreset
import com.streamvault.domain.model.StalkerPlaybackBackendHint
import com.streamvault.domain.model.StalkerPortalFingerprint
import com.streamvault.domain.model.StalkerPortalProfile
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.DiscoveryBudget
import com.streamvault.domain.util.StreamEntryUrlPolicy
import java.io.ByteArrayOutputStream
import java.io.IOException
@@ -23,20 +27,29 @@ import java.net.URI
import java.net.InetSocketAddress
import java.net.Proxy
import java.net.URLEncoder
+import java.security.MessageDigest
import java.time.Instant
import java.time.LocalDate
import java.time.LocalDateTime
import java.time.OffsetDateTime
+import java.time.ZoneId
import java.time.ZoneOffset
import java.time.format.DateTimeFormatter
import java.time.format.DateTimeFormatterBuilder
import java.time.format.ResolverStyle
import java.util.Base64
+import java.util.ArrayDeque
import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.TimeUnit
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
@@ -51,6 +64,8 @@ import kotlinx.serialization.json.jsonObject
import kotlinx.serialization.json.longOrNull
import okhttp3.Cookie
import okhttp3.CookieJar
+import okhttp3.Call
+import okhttp3.Callback
import okhttp3.Headers
import okhttp3.HttpUrl
import okhttp3.OkHttpClient
@@ -59,99 +74,173 @@ import okhttp3.Request
import okhttp3.RequestBody.Companion.toRequestBody
import okhttp3.Response
import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+import kotlin.coroutines.resume
+import kotlin.coroutines.resumeWithException
@Singleton
class OkHttpStalkerApiService @Inject constructor(
private val okHttpClient: OkHttpClient,
- private val json: Json
+ private val json: Json,
+ private val transportFactory: StalkerTransportFactory = StalkerTransportFactory(okHttpClient)
) : StalkerApiService {
- private val cookieJar = InMemoryStalkerCookieJar()
+ private data class SessionScope(
+ val cookieJar: InMemoryStalkerCookieJar = InMemoryStalkerCookieJar(),
+ @Volatile var lastAccessAt: Long = System.currentTimeMillis()
+ )
+
+ private val sessionScopes = ConcurrentHashMap<String, SessionScope>()
private val stalkerHttpClients = ConcurrentHashMap<String, OkHttpClient>()
+ private val resolvedLoadUrls = ConcurrentHashMap<String, String>()
override suspend fun authenticate(profile: StalkerDeviceProfile): Result<Pair<StalkerSession, StalkerProviderProfile>> {
+ profile.discoveryRuntime.begin()
+ return try {
+ // Each network call is capped by the remaining wall-time and consumeRequest checks
+ // elapsed time before dispatch. Avoid a second coroutine timer here: virtual-time
+ // dispatchers can otherwise race an already-completed OkHttp callback.
+ authenticateWithinBudget(profile)
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: StalkerApiError) {
+ Result.error(error.message.orEmpty(), error)
+ } catch (error: IOException) {
+ Result.error(error.message ?: "Failed to connect to portal.", error)
+ } finally {
+ profile.discoveryRuntime.end()
+ }
+ }
+
+ private suspend fun authenticateWithinBudget(
+ profile: StalkerDeviceProfile
+ ): Result<Pair<StalkerSession, StalkerProviderProfile>> {
var lastError: Throwable? = null
- var lockedLoadUrl: String? = null
- val failedHandshakeLoadUrls = mutableSetOf<String>()
- val bootstrapSessions = mutableMapOf<String, StalkerBootstrapSession>()
+ val failedHandshakeAttempts = mutableSetOf<String>()
+ val hintedLoadUrls = probePortalBaseHintCandidates(profile)
val authModes = candidateAuthModes(profile)
for (effectiveAuthMode in authModes) {
- for (attempt in candidateAuthAttempts(profile, effectiveAuthMode)) {
+ val attempts = ArrayDeque(candidateAuthAttempts(profile, effectiveAuthMode, hintedLoadUrls))
+ val retriedPartialAuthorization = mutableSetOf<String>()
+ while (attempts.isNotEmpty()) {
+ val attempt = attempts.removeFirst()
val recipeIndex = attempt.recipeIndex
val recipe = attempt.recipe
- val loadUrl = attempt.loadUrl
- if (lockedLoadUrl != null && lockedLoadUrl != loadUrl) {
- continue
- }
- if (lockedLoadUrl == null && loadUrl in failedHandshakeLoadUrls) {
+ var loadUrl = attempt.loadUrl
+ var endpointFamily = endpointPreferenceFor(loadUrl).name
+ val profileLabel = StalkerCompatibilityRegistry.find(recipe.compatibilityProfileId)
+ ?.displayName ?: recipe.compatibilityProfileId
+ profile.onProgress?.invoke("Trying $profileLabel")
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "HANDSHAKE",
+ "STARTED"
+ )
+ val handshakeAttemptKey = listOf(
+ loadUrl,
+ effectiveAuthMode.name,
+ recipe.recipe.name,
+ recipe.compatibilityProfileId,
+ profile.cookieMode.name,
+ profile.endpointPreference.name,
+ hashDiscoveryHeaderPolicy(profile),
+ profile.transportGrant?.origin?.authority.orEmpty(),
+ profile.transportGrant?.spkiSha256.orEmpty(),
+ profile.transportGrant?.consentedAt?.toString().orEmpty()
+ ).joinToString("|")
+ if (handshakeAttemptKey in failedHandshakeAttempts) {
continue
}
- cookieJar.clear()
- val referer = StalkerUrlFactory.portalReferer(loadUrl)
+ var referer = StalkerUrlFactory.portalReferer(loadUrl)
val evidence = mutableListOf<String>()
val recipeEvidence = mutableListOf("recipe:${recipe.recipe.name}", "preset:${recipe.magPreset.name}")
val attemptProfile = profile.withRecipe(recipe, effectiveAuthMode)
- val bootstrapSessionKey = "${effectiveAuthMode.name}|$loadUrl"
- var bootstrapSession = bootstrapSessions[bootstrapSessionKey]
- val token = bootstrapSession?.token ?: run {
- val handshakePayload = runCatching {
- requestJson(
- url = loadUrl,
- profile = attemptProfile,
- referer = referer,
- query = mapOf(
- "type" to "stb",
- "action" to "handshake",
- "token" to "",
- "JsHttpRequest" to "1-xml"
- )
+ val cookieJar = cookieJarFor(attemptProfile)
+ cookieJar.clear()
+ val handshakePayload = runCatching {
+ requestJson(
+ url = loadUrl,
+ profile = attemptProfile,
+ referer = referer,
+ query = mapOf(
+ "type" to "stb",
+ "action" to "handshake",
+ "token" to "",
+ "JsHttpRequest" to "1-xml"
)
- }.getOrElse { error ->
- failedHandshakeLoadUrls += loadUrl
- lastError = error
+ )
+ }.getOrElse { error ->
+ if (error is CancellationException) throw error
+ failedHandshakeAttempts += handshakeAttemptKey
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "HANDSHAKE",
+ authenticationFailureOutcome(error)
+ )
+ if (error.isTerminalStalkerDiscoveryFailure()) return Result.error(error.message.orEmpty(), error)
+ lastError = preferredAuthenticationFailure(lastError, error)
+ continue
+ }
+ val token = handshakePayload.findString("token")
+ ?.takeIf { it.isNotBlank() }
+ ?: run {
+ lastError = IOException("Portal handshake did not return a token.")
continue
}
- handshakePayload.findString("token")
- ?.takeIf { it.isNotBlank() }
- ?: run {
- lastError = IOException("Portal handshake did not return a token.")
- continue
- }
+ val handshakeRandom = handshakePayload.findString("random").orEmpty()
+ resolvedLoadUrl(loadUrl, attemptProfile)?.let { redirectedLoadUrl ->
+ loadUrl = redirectedLoadUrl
+ referer = StalkerUrlFactory.portalReferer(redirectedLoadUrl)
+ endpointFamily = endpointPreferenceFor(redirectedLoadUrl).name
+ evidence += "endpoint_redirect"
}
evidence += "handshake"
- lockedLoadUrl = loadUrl
- if (bootstrapSession == null) {
- bootstrapSession = StalkerBootstrapSession(token)
- bootstrapSessions[bootstrapSessionKey] = bootstrapSession
- }
+ profile.onProgress?.invoke("Handshake accepted")
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "HANDSHAKE",
+ "ACCEPTED"
+ )
if (recipe.authMode.requiresCredentials()) {
- if (!bootstrapSession.credentialAuthenticated) {
- if (attemptProfile.username.isBlank()) {
- lastError = IOException("Portal requires account credentials for this connection.")
- continue
- }
- val authPayload = runCatching {
- requestCredentialAuth(
- url = loadUrl,
- profile = attemptProfile,
- referer = referer,
- token = token,
- allowAlternateEndpointRetry = false
- )
- }.getOrElse { error ->
- lastError = error
- continue
- }
- authPayload.ensureNoPortalError()
- bootstrapSession.credentialAuthenticated = true
+ if (attemptProfile.username.isBlank()) {
+ lastError = IOException("Portal requires account credentials for this connection.")
+ continue
}
+ val authPayload = runCatching {
+ requestCredentialAuth(
+ url = loadUrl,
+ profile = attemptProfile,
+ referer = referer,
+ token = token,
+ allowAlternateEndpointRetry = false
+ )
+ }.getOrElse { error ->
+ if (error is CancellationException) throw error
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "CREDENTIALS",
+ authenticationFailureOutcome(error)
+ )
+ if (error.isTerminalStalkerDiscoveryFailure()) return Result.error(error.message.orEmpty(), error)
+ lastError = preferredAuthenticationFailure(lastError, error)
+ continue
+ }
+ authPayload.ensureNoPortalError()
evidence += "do_auth"
}
var session = StalkerSession(
loadUrl = loadUrl,
portalReferer = referer,
- token = token
+ token = token,
+ sessionScopeKey = sessionScopeKey(attemptProfile)
)
if (recipe.preferLocalizationBeforeProfile) {
runCatching {
@@ -166,7 +255,7 @@ class OkHttpStalkerApiService @Inject constructor(
"JsHttpRequest" to "1-xml"
)
)
- }.getOrNull()?.let {
+ }.getOrNullPreservingCancellation()?.let {
evidence += "get_localization"
}
}
@@ -176,16 +265,42 @@ class OkHttpStalkerApiService @Inject constructor(
profile = attemptProfile,
referer = referer,
token = token,
- query = buildProfileQuery(attemptProfile)
+ query = buildProfileQuery(
+ profile = attemptProfile,
+ handshakeRandom = handshakeRandom
+ )
)
}.getOrElse { error ->
- lastError = error
+ if (error is CancellationException) throw error
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "PROFILE",
+ authenticationFailureOutcome(error)
+ )
+ if (error.isTerminalStalkerDiscoveryFailure()) return Result.error(error.message.orEmpty(), error)
+ lastError = preferredAuthenticationFailure(lastError, error)
continue
}
profilePayload.ensureNoPortalError()
evidence += "get_profile"
+ profile.onProgress?.invoke(
+ if (profile.requireCatalogValidation) {
+ "Profile accepted; checking catalog"
+ } else {
+ "Profile accepted"
+ }
+ )
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "PROFILE",
+ "ACCEPTED"
+ )
- var providerProfile = profilePayload.toProviderProfile()
+ var providerProfile = profilePayload.toProviderProfile(profile.timezone)
var bootstrapStrategy = when (recipe.recipe) {
StalkerBootstrapRecipe.GENERIC_SAFE -> StalkerBootstrapStrategy.AUTO
StalkerBootstrapRecipe.LEGACY_MAG -> StalkerBootstrapStrategy.MAC_ONLY
@@ -209,8 +324,8 @@ class OkHttpStalkerApiService @Inject constructor(
"JsHttpRequest" to "1-xml"
)
)
- }.getOrNull()?.let { accountInfoPayload ->
- providerProfile = providerProfile.merge(accountInfoPayload.toProviderProfile())
+ }.getOrNullPreservingCancellation()?.let { accountInfoPayload ->
+ providerProfile = providerProfile.merge(accountInfoPayload.toProviderProfile(profile.timezone))
bootstrapStrategy = StalkerBootstrapStrategy.MAC_WITH_ACCOUNT_INFO
evidence += "get_account_info"
}
@@ -228,7 +343,7 @@ class OkHttpStalkerApiService @Inject constructor(
"JsHttpRequest" to "1-xml"
)
)
- }.getOrNull()?.let {
+ }.getOrNullPreservingCancellation()?.let {
evidence += "get_localization"
}
}
@@ -245,7 +360,7 @@ class OkHttpStalkerApiService @Inject constructor(
"JsHttpRequest" to "1-xml"
)
)
- }.getOrNull()?.let { modulesPayload ->
+ }.getOrNullPreservingCancellation()?.let { modulesPayload ->
val modules = modulesPayload.toModuleNames()
if (modules.isNotEmpty()) {
bootstrapStrategy = StalkerBootstrapStrategy.MAC_WITH_MODULES
@@ -269,11 +384,105 @@ class OkHttpStalkerApiService @Inject constructor(
"JsHttpRequest" to "1-xml"
)
)
- }.getOrNull()?.let {
+ }.getOrNullPreservingCancellation()?.let {
evidence += "get_events"
}
}
+ if (profile.requireCatalogValidation) {
+ val catalogEvidence = runCatching {
+ validateCatalogAcceptance(session, attemptProfile)
+ }.getOrElse { error ->
+ if (error is CancellationException) throw error
+ if (error is StalkerApiError.PartialAuthorization) {
+ val retryKey = "${effectiveAuthMode.name}|${attempt.recipe.compatibilityProfileId}|$loadUrl"
+ val reportedProfile = StalkerCompatibilityRegistry.findVerifiedByModelSignal(
+ providerProfile.reportedStbType
+ )
+ if (profile.allowCompatibilityDiscovery &&
+ reportedProfile != null &&
+ reportedProfile.id != recipe.compatibilityProfileId
+ ) {
+ promoteCompatibilityAttempt(
+ attempts = attempts,
+ compatibilityProfileId = reportedProfile.id,
+ loadUrl = attempt.loadUrl
+ )
+ profile.onProgress?.invoke(
+ "Portal reports ${reportedProfile.displayName}; validating that profile"
+ )
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "CATALOG",
+ "MODEL_SIGNAL"
+ )
+ lastError = preferredAuthenticationFailure(lastError, error)
+ continue
+ }
+ if (error.requiresFreshSessionRetry() &&
+ retriedPartialAuthorization.add(retryKey)
+ ) {
+ attempts.addFirst(attempt)
+ profile.onProgress?.invoke("Catalog authorization rejected; retrying fresh session")
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "CATALOG",
+ "FRESH_SESSION_RETRY"
+ )
+ lastError = preferredAuthenticationFailure(lastError, error)
+ continue
+ }
+ Log.w(
+ TAG,
+ "Stalker partial authorization host=${runCatching { URI(loadUrl).host }.getOrNull().orEmpty()} " +
+ "profile=${attempt.recipe.compatibilityProfileId}; fresh-session retry rejected"
+ )
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "CATALOG",
+ "PARTIAL_AUTHORIZATION"
+ )
+ lastError = preferredAuthenticationFailure(lastError, error)
+ if (profile.allowCompatibilityDiscovery) {
+ profile.onProgress?.invoke(
+ "Catalog rejected $profileLabel; trying another compatibility profile"
+ )
+ continue
+ }
+ return Result.error(error.message.orEmpty(), error)
+ }
+ if (error.isInconclusiveLiveReadinessFailure()) {
+ val inconclusive = StalkerApiError.ReadinessInconclusive(
+ evidenceCode = error.liveReadinessEvidenceCode(),
+ cause = error
+ )
+ return Result.error(inconclusive.message.orEmpty(), inconclusive)
+ }
+ if (error.isDefinitiveLiveReadinessFailure()) {
+ return Result.error(error.message.orEmpty(), error)
+ }
+ if (error.isTerminalStalkerDiscoveryFailure()) {
+ return Result.error(error.message.orEmpty(), error)
+ }
+ lastError = preferredAuthenticationFailure(lastError, error)
+ continue
+ }
+ evidence += catalogEvidence
+ StalkerTelemetry.authenticationAttempt(
+ profile.providerId,
+ recipe.compatibilityProfileId,
+ endpointFamily,
+ "CATALOG",
+ "ACCEPTED"
+ )
+ }
+
val fingerprint = detectPortalFingerprint(
profile = providerProfile,
effectiveAuthMode = effectiveAuthMode,
@@ -351,7 +560,12 @@ class OkHttpStalkerApiService @Inject constructor(
moduleRestricted = providerProfile.moduleNames.isNotEmpty(),
ambiguousAccountState = ambiguousState
),
- ambiguousState = ambiguousState
+ ambiguousState = ambiguousState,
+ compatibilityProfileId = recipe.compatibilityProfileId,
+ profileRevision = StalkerCompatibilityRegistry.REVISION,
+ profileVerification = StalkerCompatibilityRegistry.find(recipe.compatibilityProfileId)
+ ?.verification ?: com.streamvault.domain.model.StalkerProfileVerification.UNVERIFIED,
+ protocolFamily = com.streamvault.domain.model.StalkerProtocolFamily.CLASSIC_MAG
)
session = session.copy(
serverCookieHeader = cookieJar.cookieHeaderFor(loadUrl),
@@ -363,7 +577,8 @@ class OkHttpStalkerApiService @Inject constructor(
fingerprintEvidence = fingerprintEvidence,
bootstrapEvidence = evidence.toList(),
recipeEvidence = recipeEvidence.toList(),
- rediscoveryAttempted = rediscoveryAttempted
+ rediscoveryAttempted = rediscoveryAttempted,
+ compatibilityProfileId = recipe.compatibilityProfileId
)
Log.i(
TAG,
@@ -672,7 +887,7 @@ class OkHttpStalkerApiService @Inject constructor(
"ch_id" to channelId,
"size" to limit.coerceAtLeast(1).toString()
)
- ).toProgramRecords(channelId)
+ ).toProgramRecords(channelId, profile.timezone)
}
override suspend fun getEpg(
@@ -840,7 +1055,12 @@ class OkHttpStalkerApiService @Inject constructor(
}
override fun currentCookieHeader(session: StalkerSession): String =
- cookieJar.cookieHeaderFor(session.loadUrl).ifBlank { session.serverCookieHeader }
+ sessionScopes[session.sessionScopeKey]
+ ?.also { scope -> scope.lastAccessAt = System.currentTimeMillis() }
+ ?.cookieJar
+ ?.cookieHeaderFor(session.loadUrl)
+ .orEmpty()
+ .ifBlank { session.serverCookieHeader }
private suspend fun fetchPagedItems(
session: StalkerSession,
@@ -856,7 +1076,14 @@ class OkHttpStalkerApiService @Inject constructor(
)
val items = mutableListOf<StalkerItemRecord>()
items += firstPage.toItemRecords()
- val totalPages = firstPage.totalPages()
+ val advertisedTotalPages = firstPage.advertisedTotalPages()
+ if (advertisedTotalPages != null && advertisedTotalPages > MAX_PAGE_COUNT) {
+ throw StalkerApiError.CatalogTruncated(
+ advertisedTotalPages = advertisedTotalPages,
+ pageLimit = MAX_PAGE_COUNT
+ )
+ }
+ val totalPages = advertisedTotalPages ?: 1
for (page in 2..totalPages) {
val pagePayload = requestJson(
url = session.loadUrl,
@@ -885,11 +1112,18 @@ class OkHttpStalkerApiService @Inject constructor(
query = baseQuery + ("p" to safePage.toString())
)
val items = payload.toItemRecords()
+ val pageSize = payload.pageSize(items.size)
+ val advertisedTotalItems = payload.advertisedTotalItems()
+ val advertisedTotalPages = payload.advertisedTotalPages()
return StalkerPagedItems(
items = items,
page = safePage,
totalPages = payload.totalPages(),
- pageSize = payload.pageSize(items.size)
+ pageSize = pageSize,
+ advertisedTotalItems = advertisedTotalItems,
+ advertisedTotalPages = advertisedTotalPages,
+ isTruncated = advertisedTotalPages?.let { it > MAX_PAGE_COUNT } == true,
+ terminationReason = "page_limit".takeIf { advertisedTotalPages?.let { it > MAX_PAGE_COUNT } == true }
)
}
@@ -910,6 +1144,7 @@ class OkHttpStalkerApiService @Inject constructor(
)
).toItemRecords()
}.onFailure { error ->
+ if (error is CancellationException) throw error
Log.w(TAG, "Stalker get_all_channels failed; falling back to paged live catalog", error)
}.getOrNull()?.takeIf { it.isNotEmpty() }
}
@@ -949,6 +1184,7 @@ class OkHttpStalkerApiService @Inject constructor(
runCatching {
executeJsonRequest(request, action, profile)
}.recoverCatching { error ->
+ if (error is CancellationException) throw error
if (!allowAlternateEndpointRetry) throw error
val alternateUrl = siblingLoadUrl(url)
?.takeIf { it != url }
@@ -971,15 +1207,33 @@ class OkHttpStalkerApiService @Inject constructor(
}.getOrElse { throw it }
}
- private fun executeJsonRequest(request: Request, action: String?, profile: StalkerDeviceProfile): JsonElement {
- return stalkerHttpClientFor(profile).newCall(request).execute().use { response ->
- captureResponseCookies(response)
+ private suspend fun executeJsonRequest(request: Request, action: String?, profile: StalkerDeviceProfile): JsonElement {
+ profile.discoveryRuntime.consumeRequest()
+ val startedAt = System.currentTimeMillis()
+ return withTransportAwareStalkerCall(request, profile) { response ->
+ recordResolvedLoadUrl(request, response, profile)
+ captureResponseCookies(response, profile)
if (!response.isSuccessful) {
+ StalkerTelemetry.httpResponse(
+ providerId = profile.providerId,
+ endpointFamily = endpointFamily(request),
+ action = action,
+ durationMillis = System.currentTimeMillis() - startedAt,
+ responseBytes = response.body?.contentLength()?.coerceAtLeast(0L) ?: 0L,
+ status = response.code,
+ outcome = "HTTP_ERROR"
+ )
+ // A 401/403 served as an HTML page comes from an edge/WAF (e.g. Cloudflare)
+ // or a misconfigured endpoint, not from the portal's JSON auth layer; do not
+ // classify it as a portal authorization verdict.
+ val htmlErrorPage = runCatching {
+ looksLikeHtml(response.peekBody(HTML_ERROR_SNIFF_BYTES).string())
+ }.getOrDefault(false)
response.body?.close()
- throw IOException("Portal request failed with HTTP ${response.code}.")
+ throw response.toStalkerHttpError(htmlErrorPage)
}
val responseBody = response.body
- ?: throw IOException("Portal returned an empty response${actionSuffix(action)}.")
+ ?: throw StalkerApiError.Malformed("Portal returned an empty response${actionSuffix(action)}.")
val charset = responseBody.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8
val raw = readBodyBounded(
stream = responseBody.byteStream(),
@@ -988,10 +1242,19 @@ class OkHttpStalkerApiService @Inject constructor(
action = action
)
if (raw.isBlank()) {
- throw IOException("Portal returned an empty response${actionSuffix(action)}.")
+ throw StalkerApiError.Malformed("Portal returned an empty response${actionSuffix(action)}.")
}
val parsed = parsePortalJson(raw, action)
parsed.ensureNoPortalError()
+ StalkerTelemetry.httpResponse(
+ providerId = profile.providerId,
+ endpointFamily = endpointFamily(request),
+ action = action,
+ durationMillis = System.currentTimeMillis() - startedAt,
+ responseBytes = raw.toByteArray(charset).size.toLong(),
+ status = response.code,
+ outcome = "SUCCESS"
+ )
parsed
}
}
@@ -1015,7 +1278,7 @@ class OkHttpStalkerApiService @Inject constructor(
totalRead += n
if (totalRead > maxBytes) {
val limitKb = maxBytes / 1024
- throw IOException(
+ throw StalkerApiError.ResponseTooLarge(
"Portal response for '${action ?: "request"}' exceeded the ${limitKb}KB limit; " +
"portal may be misbehaving."
)
@@ -1079,17 +1342,29 @@ class OkHttpStalkerApiService @Inject constructor(
profile: StalkerDeviceProfile,
onItem: suspend (StalkerItemRecord) -> Unit
): Int {
- return stalkerHttpClientFor(profile).newCall(request).execute().use { response ->
- captureResponseCookies(response)
+ profile.discoveryRuntime.consumeRequest()
+ val startedAt = System.currentTimeMillis()
+ return withTransportAwareStalkerCall(request, profile) { response ->
+ captureResponseCookies(response, profile)
if (!response.isSuccessful) {
- throw IOException("Portal request failed with HTTP ${response.code}.")
+ throw response.toStalkerHttpError()
}
- val body = response.body ?: throw IOException("Portal returned an empty response${actionSuffix(action)}.")
+ val body = response.body ?: throw StalkerApiError.Malformed("Portal returned an empty response${actionSuffix(action)}.")
val charset = body.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8
val reader = JsonReader(InputStreamReader(body.byteStream(), charset))
reader.isLenient = true
try {
- streamStalkerItems(reader, onItem)
+ streamStalkerItems(reader, onItem).also { itemCount ->
+ StalkerTelemetry.httpResponse(
+ providerId = profile.providerId,
+ endpointFamily = endpointFamily(request),
+ action = action,
+ durationMillis = System.currentTimeMillis() - startedAt,
+ responseBytes = body.contentLength().coerceAtLeast(0L),
+ status = response.code,
+ outcome = if (itemCount > 0) "SUCCESS" else "EMPTY"
+ )
+ }
} catch (error: IllegalStateException) {
throw IOException("Portal returned unreadable JSON${actionSuffix(action)}.", error)
}
@@ -1124,11 +1399,12 @@ class OkHttpStalkerApiService @Inject constructor(
when (reader.nextName()) {
"error" -> {
val error = reader.nextStringOrSkip()
- // Use the same placeholder filter as ensureNoPortalError so that
- // "null", "0", "false", and "ok" from loose portals are not treated
- // as real errors in the streamed item path either.
- if (!error.isNullOrBlank() && !isPlaceholderErrorValue(error)) {
- throw IOException(error)
+ error?.let(::portalError)?.let { throw it }
+ }
+ "not_valid_token" -> {
+ val marker = reader.nextStringOrSkip()
+ if (marker != null && !isPlaceholderErrorValue(marker)) {
+ throw invalidTokenError()
}
}
"js", "data", "items" -> count += streamStalkerItems(reader, onItem)
@@ -1218,12 +1494,13 @@ class OkHttpStalkerApiService @Inject constructor(
channelIdOverride: String?,
onProgram: suspend (StalkerProgramRecord) -> Unit
): Int {
- return stalkerHttpClientFor(profile).newCall(request).execute().use { response ->
- captureResponseCookies(response)
+ profile.discoveryRuntime.consumeRequest()
+ return withTransportAwareStalkerCall(request, profile) { response ->
+ captureResponseCookies(response, profile)
if (!response.isSuccessful) {
- throw IOException("Portal request failed with HTTP ${response.code}.")
+ throw response.toStalkerHttpError()
}
- val body = response.body ?: throw IOException("Portal returned an empty response${actionSuffix(action)}.")
+ val body = response.body ?: throw StalkerApiError.Malformed("Portal returned an empty response${actionSuffix(action)}.")
val charset = body.contentType()?.charset(Charsets.UTF_8) ?: Charsets.UTF_8
val limited = ByteSizeLimitInputStream(
delegate = body.byteStream(),
@@ -1235,7 +1512,7 @@ class OkHttpStalkerApiService @Inject constructor(
val reader = JsonReader(InputStreamReader(limited, charset))
reader.isLenient = true
try {
- streamStalkerPrograms(reader, channelIdOverride, onProgram)
+ streamStalkerPrograms(reader, channelIdOverride, profile.timezone.toPortalZoneId(), onProgram)
} catch (error: IllegalStateException) {
throw IOException("Portal returned unreadable JSON${actionSuffix(action)}.", error)
}
@@ -1245,11 +1522,12 @@ class OkHttpStalkerApiService @Inject constructor(
private suspend fun streamStalkerPrograms(
reader: JsonReader,
channelIdOverride: String?,
+ zoneId: ZoneId,
onProgram: suspend (StalkerProgramRecord) -> Unit
): Int {
return when (reader.peek()) {
- JsonToken.BEGIN_ARRAY -> streamProgramArray(reader, channelIdOverride, onProgram)
- JsonToken.BEGIN_OBJECT -> streamProgramObject(reader, channelIdOverride, onProgram)
+ JsonToken.BEGIN_ARRAY -> streamProgramArray(reader, channelIdOverride, zoneId, onProgram)
+ JsonToken.BEGIN_OBJECT -> streamProgramObject(reader, channelIdOverride, zoneId, onProgram)
JsonToken.NULL -> {
reader.nextNull()
0
@@ -1264,6 +1542,7 @@ class OkHttpStalkerApiService @Inject constructor(
private suspend fun streamProgramObject(
reader: JsonReader,
channelIdOverride: String?,
+ zoneId: ZoneId,
onProgram: suspend (StalkerProgramRecord) -> Unit
): Int {
var count = 0
@@ -1274,13 +1553,17 @@ class OkHttpStalkerApiService @Inject constructor(
when (name) {
"error" -> {
val error = reader.nextStringOrSkip()
- if (!error.isNullOrBlank() && !error.equals("null", ignoreCase = true)) {
- throw IOException(error)
+ error?.let(::portalError)?.let { throw it }
+ }
+ "not_valid_token" -> {
+ val marker = reader.nextStringOrSkip()
+ if (marker != null && !isPlaceholderErrorValue(marker)) {
+ throw invalidTokenError()
}
}
"js", "data", "items" -> {
sawEnvelope = true
- count += streamStalkerPrograms(reader, channelIdOverride, onProgram)
+ count += streamStalkerPrograms(reader, channelIdOverride, zoneId, onProgram)
}
else -> {
// Some portals return the bulk EPG as an object whose keys are channel IDs
@@ -1288,7 +1571,7 @@ class OkHttpStalkerApiService @Inject constructor(
// into an envelope key and there is no caller-supplied override, treat the
// key as the channel ID and walk the array.
if (!sawEnvelope && channelIdOverride == null && reader.peek() == JsonToken.BEGIN_ARRAY) {
- count += streamProgramArray(reader, name, onProgram)
+ count += streamProgramArray(reader, name, zoneId, onProgram)
} else {
reader.skipValue()
}
@@ -1302,6 +1585,7 @@ class OkHttpStalkerApiService @Inject constructor(
private suspend fun streamProgramArray(
reader: JsonReader,
channelIdOverride: String?,
+ zoneId: ZoneId,
onProgram: suspend (StalkerProgramRecord) -> Unit
): Int {
var count = 0
@@ -1309,20 +1593,20 @@ class OkHttpStalkerApiService @Inject constructor(
while (reader.hasNext()) {
if (reader.peek() == JsonToken.BEGIN_OBJECT) {
val element = JsonParser.parseReader(reader)
- val program = element.asJsonObjectOrNull()?.toProgramRecord(channelIdOverride)
+ val program = element.asJsonObjectOrNull()?.toProgramRecord(channelIdOverride, zoneId)
if (program != null) {
onProgram(program)
count++
}
} else {
- count += streamStalkerPrograms(reader, channelIdOverride, onProgram)
+ count += streamStalkerPrograms(reader, channelIdOverride, zoneId, onProgram)
}
}
reader.endArray()
return count
}
- private fun GsonJsonObject.toProgramRecord(channelIdOverride: String?): StalkerProgramRecord? {
+ private fun GsonJsonObject.toProgramRecord(channelIdOverride: String?, zoneId: ZoneId): StalkerProgramRecord? {
val resolvedChannelId = channelIdOverride
?: findString("ch_id")
?: findString("channel_id")
@@ -1331,10 +1615,10 @@ class OkHttpStalkerApiService @Inject constructor(
?: findString("epg_id")
?: return null
val startMillis = findString("start_timestamp")?.toLongOrNull()?.times(1000L)
- ?: findString("time")?.let(::parseDateTime)
+ ?: findString("time")?.let { parseDateTime(it, zoneId) }
?: return null
val endMillis = findString("stop_timestamp")?.toLongOrNull()?.times(1000L)
- ?: findString("time_to")?.let(::parseDateTime)
+ ?: findString("time_to")?.let { parseDateTime(it, zoneId) }
?: (startMillis + (findString("duration")?.toLongOrNull()?.times(60_000L) ?: DEFAULT_PROGRAM_DURATION_MILLIS))
val title = findString("name") ?: findString("title") ?: return null
return StalkerProgramRecord(
@@ -1368,10 +1652,15 @@ class OkHttpStalkerApiService @Inject constructor(
if (looksLikeHtml(normalized)) {
val lower = normalized.lowercase(Locale.ROOT)
if (lower.contains("access denied") || lower.contains("forbidden")) {
- throw IOException("Portal denied the request${actionSuffix(action)}.")
+ throw StalkerApiError.Authorization(
+ message = "Portal denied the request${actionSuffix(action)}.",
+ portalReason = "access denied"
+ )
}
}
+ authorizationMessage(normalized)?.let { throw it }
+
extractEmbeddedJson(normalized)?.let { candidate ->
runCatching { json.parseToJsonElement(candidate) }
.getOrNull()
@@ -1380,18 +1669,297 @@ class OkHttpStalkerApiService @Inject constructor(
throw runCatching { json.parseToJsonElement(normalized) }
.fold(
- onSuccess = { IOException("Portal returned unreadable JSON${actionSuffix(action)}.") },
- onFailure = { error -> IOException("Portal returned unreadable JSON${actionSuffix(action)}.", error) }
+ onSuccess = { StalkerApiError.Malformed("Portal returned unreadable JSON${actionSuffix(action)}.") },
+ onFailure = { error -> StalkerApiError.Malformed("Portal returned unreadable JSON${actionSuffix(action)}.", error) }
)
}
private fun JsonElement.ensureNoPortalError() {
+ if (findBoolean("not_valid_token") == true) {
+ throw invalidTokenError()
+ }
val raw = rootObjectOrNull()?.findString("error")
?: findString("error")
- ?: return
- // Ignore well-known placeholder values that some portals emit even on success.
- if (raw.isBlank() || isPlaceholderErrorValue(raw)) return
- throw IOException(raw)
+ raw?.let { portalError(it)?.let { error -> throw error } }
+
+ statusEnvelopeError()?.let { throw it }
+
+ val message = rootObjectOrNull()?.findString("msg")
+ ?: findString("msg")
+ message?.let { authorizationMessage(it)?.let { error -> throw error } }
+ }
+
+ /**
+ * Ministra reports workflow failures as HTTP 200 with a `status`/`msg`/`block_msg`
+ * envelope instead of an HTTP error or an `error` field. Well-known examples:
+ * `status:1` + "Device conflict - device_id mismatch" (MAC locked to another device
+ * identity), `status:1` + "Time out of sync" (device clock outside tolerance) and
+ * `status:2` + "Authentication request" (device not registered; launcher auth required).
+ * These must never be treated as accepted payloads.
+ */
+ private fun JsonElement.statusEnvelopeError(): StalkerApiError? {
+ val payload = payloadObjectOrNull() ?: return null
+ val status = payload.findInt("status") ?: return null
+ if (status == 0) return null
+ val msg = payload.findString("msg")
+ val blockMsg = payload.findString("block_msg")?.let(::stripPortalHtml)
+ if (msg == null && blockMsg == null) return null
+ val detail = listOfNotNull(msg, blockMsg)
+ .flatMap { it.lineSequence() }
+ .map { it.trim() }
+ .filter { it.isNotEmpty() }
+ .joinToString(" ")
+ val normalizedMsg = (msg ?: "").lowercase(Locale.ROOT)
+ return when {
+ status == 2 -> StalkerApiError.DeviceNotRegistered(
+ message = "Portal does not recognize this device (registration is required). " +
+ "Portal message: $detail",
+ reason = msg
+ )
+ normalizedMsg.contains("device conflict") ||
+ normalizedMsg.contains("device_id mismatch") ||
+ normalizedMsg.contains("device id mismatch") ->
+ StalkerApiError.DeviceConflict(
+ message = "Portal reports \"$detail\". This MAC is locked to a different " +
+ "device identity; enter the registered serial number, device IDs and " +
+ "signature, or ask your provider to reset the device binding.",
+ reason = msg
+ )
+ normalizedMsg.contains("time out of sync") ||
+ normalizedMsg.contains("not synchronized") ->
+ StalkerApiError.ClockSkew(
+ message = "Portal rejected the login because this device's clock is out of " +
+ "sync. Correct the device date/time and retry. Portal message: $detail",
+ reason = msg
+ )
+ normalizedMsg.contains("not valid mac") || normalizedMsg.contains("invalid mac") ->
+ StalkerApiError.InvalidMac(
+ detail.ifBlank { "Portal reported an invalid MAC address." },
+ msg
+ )
+ normalizedMsg.contains("not_valid_token") ||
+ normalizedMsg.contains("invalid token") ||
+ normalizedMsg.contains("empty token") ->
+ StalkerApiError.TokenRejected(detail, msg)
+ normalizedMsg.contains("blocked") ||
+ normalizedMsg.contains("disabled") ||
+ normalizedMsg.contains("banned") ||
+ normalizedMsg.contains("not allowed") ->
+ StalkerApiError.AccountBlocked(detail, msg)
+ else -> StalkerApiError.Authorization(
+ message = "Portal rejected the device profile: $detail",
+ portalReason = msg
+ )
+ }
+ }
+
+ private fun stripPortalHtml(raw: String): String {
+ val withBreaks = raw.replace(Regex("<\\s*br\\s*/?\\s*>", RegexOption.IGNORE_CASE), " ")
+ val withoutTags = withBreaks.replace(Regex("<[^>]*>"), " ")
+ val decoded = withoutTags
+ .replace("&lt;", "<")
+ .replace("&gt;", ">")
+ .replace("&quot;", "\"")
+ .replace("&#39;", "'")
+ .replace("&nbsp;", " ")
+ .replace("&amp;", "&")
+ return decoded.replace(Regex("\\s+"), " ").trim()
+ }
+
+ /**
+ * A handshake/profile HTTP 200 is not acceptance. Add-provider discovery requires the
+ * minimum workflow the app actually needs: live genres, a non-empty channel page, and either
+ * an already resolved stream URL or a successful create_link response.
+ */
+ private suspend fun validateCatalogAcceptance(
+ session: StalkerSession,
+ profile: StalkerDeviceProfile
+ ): List<String> {
+ profile.onProgress?.invoke("Validating Live TV categories")
+ val categoriesPayload = runCatching {
+ requestJson(
+ url = session.loadUrl,
+ profile = profile,
+ referer = session.portalReferer,
+ token = session.token,
+ query = mapOf(
+ "type" to "itv",
+ "action" to "get_genres",
+ "JsHttpRequest" to "1-xml"
+ )
+ ).also { payload ->
+ payload.ensureNoPortalError()
+ if (!payload.isRecognizedCatalogPayload()) {
+ throw StalkerApiError.Malformed(
+ "Portal returned a malformed live category wrapper."
+ )
+ }
+ }
+ }.getOrElse { error ->
+ if (error is CancellationException) throw error
+ throwCatalogValidationFailure(error)
+ }
+ val categories = categoriesPayload.toCategoryRecords()
+ if (categories.isEmpty()) {
+ throw IOException("Portal accepted the profile but returned no live channel categories.")
+ }
+
+ profile.onProgress?.invoke("Validating Live TV channel list")
+ var lastPageFailure: Throwable? = null
+ var channels = emptyList<StalkerItemRecord>()
+ val categoryStrategies = buildList<String?> {
+ add(null) // Bulk list without a category filter.
+ add("*") // Common Ministra wildcard accepted by some classic portals.
+ addAll(
+ sampleLiveDiscoveryCategories(categories, MAX_DISCOVERY_CATEGORY_PROBES)
+ .map(StalkerCategoryRecord::id)
+ )
+ }.distinct()
+ for (categoryId in categoryStrategies) {
+ val pagePayload = runCatching {
+ val query = linkedMapOf(
+ "type" to "itv",
+ "action" to "get_ordered_list",
+ "p" to "1",
+ "JsHttpRequest" to "1-xml"
+ )
+ categoryId?.let { query["genre"] = it }
+ requestJson(
+ url = session.loadUrl,
+ profile = profile,
+ referer = session.portalReferer,
+ token = session.token,
+ query = query
+ ).also { payload ->
+ payload.ensureNoPortalError()
+ if (!payload.isRecognizedCatalogPayload()) {
+ throw StalkerApiError.Malformed(
+ "Portal returned a malformed live channel page."
+ )
+ }
+ }
+ }.getOrElse { error ->
+ if (error is CancellationException) throw error
+ if (error.isStalkerAuthorizationFailure()) throwCatalogValidationFailure(error)
+ lastPageFailure = error
+ continue
+ }
+ channels = pagePayload.toItemRecords()
+ if (channels.isNotEmpty()) break
+ }
+ if (channels.isEmpty()) {
+ throw IOException(
+ "Portal accepted the profile but returned no live channels in the validation pages.",
+ lastPageFailure
+ )
+ }
+
+ val playable = channels.firstOrNull { channel ->
+ channel.cmd?.isNotBlank() == true ||
+ channel.streamUrl?.isNotBlank() == true ||
+ channel.commandVariants.any { it.cmd.isNotBlank() }
+ } ?: throw IOException("Portal returned live channels without a playback command.")
+ val command = playable.cmd
+ ?.takeIf(String::isNotBlank)
+ ?: playable.commandVariants.firstOrNull { it.cmd.isNotBlank() }?.cmd
+ ?: playable.streamUrl.orEmpty()
+
+ profile.onProgress?.invoke("Validating Live TV playback link")
+ val playbackEvidence = if (command.isResolvedPlaybackUrl()) {
+ "playback:live:direct"
+ } else {
+ when (
+ val result = createLink(
+ session = session,
+ profile = profile,
+ kind = StalkerStreamKind.LIVE,
+ cmd = command
+ )
+ ) {
+ is Result.Success -> "playback:live:create_link"
+ is Result.Error -> {
+ val cause = result.exception ?: IOException(result.message)
+ if (cause.isStalkerAuthorizationFailure()) throwCatalogValidationFailure(cause)
+ throw IOException("Portal returned channels but could not resolve a live playback link.", cause)
+ }
+ is Result.Loading -> throw IOException("Unexpected loading state while validating playback.")
+ }
+ }
+
+ return listOf(
+ "catalog:itv:categories_valid",
+ "catalog:itv:page_valid",
+ playbackEvidence
+ )
+ }
+
+ private fun throwCatalogValidationFailure(cause: Throwable): Nothing {
+ if (cause.isStalkerAuthorizationFailure()) {
+ throw StalkerApiError.PartialAuthorization(
+ cause = cause,
+ reason = (cause as? StalkerApiError)?.portalReason
+ )
+ }
+ throw cause
+ }
+
+ private fun String.isResolvedPlaybackUrl(): Boolean {
+ val candidate = trim().substringAfter(' ', missingDelimiterValue = trim()).trim()
+ if (!StreamEntryUrlPolicy.isAllowed(candidate)) return false
+ val uri = runCatching { URI(candidate) }.getOrNull() ?: return false
+ val host = uri.host.orEmpty().lowercase(Locale.ROOT)
+ if (host in setOf("", "localhost", "127.0.0.1", "::1")) return false
+ return !uri.path.orEmpty().contains("/ch/")
+ }
+
+ private fun authorizationMessage(raw: String): StalkerApiError.Authorization? {
+ val normalized = raw.trim().lowercase(Locale.ROOT)
+ val isAuthorizationFailure = listOf(
+ "authorization failed",
+ "unauthorized",
+ "not valid mac",
+ "invalid mac",
+ "not_valid_token",
+ "invalid token",
+ "empty token",
+ "access denied",
+ "permission denied"
+ ).any(normalized::contains)
+ return if (isAuthorizationFailure) {
+ val message = raw.trim().ifBlank { "Portal authorization failed." }
+ val reason = raw.trim().takeIf(String::isNotBlank)
+ when {
+ normalized.contains("mac") -> StalkerApiError.InvalidMac(message, reason)
+ normalized.contains("token") -> StalkerApiError.TokenRejected(message, reason)
+ else -> StalkerApiError.Authorization(message = message, portalReason = reason)
+ }
+ } else {
+ null
+ }
+ }
+
+ private fun invalidTokenError(): StalkerApiError.Authorization =
+ StalkerApiError.TokenRejected(
+ message = "Portal token is invalid.",
+ reason = "not_valid_token"
+ )
+
+ private fun portalError(raw: String): StalkerApiError? {
+ if (raw.isBlank() || isPlaceholderErrorValue(raw)) return null
+ val normalized = raw.lowercase(Locale.ROOT)
+ return when {
+ listOf("not valid mac", "invalid mac").any(normalized::contains) ->
+ StalkerApiError.InvalidMac(raw, raw)
+ listOf("not_valid_token", "invalid token", "empty token").any(normalized::contains) ->
+ StalkerApiError.TokenRejected(raw, raw)
+ listOf("unsupported model", "invalid model", "device rejected", "stb type").any(normalized::contains) ->
+ StalkerApiError.ModelRejected(raw, raw)
+ listOf("access denied", "authorization", "unauthorized").any(normalized::contains) ->
+ StalkerApiError.Authorization(message = raw, portalReason = raw)
+ listOf("blocked", "disabled", "banned", "not allowed").any(normalized::contains) ->
+ StalkerApiError.AccountBlocked(message = raw, portalReason = raw)
+ else -> StalkerApiError.Server(message = raw, portalReason = raw)
+ }
}
/**
@@ -1408,10 +1976,147 @@ class OkHttpStalkerApiService @Inject constructor(
private suspend inline fun <T> runApiCall(
message: String,
crossinline block: suspend () -> T
- ): Result<T> = try {
- Result.success(block())
- } catch (error: Exception) {
- Result.error(error.message ?: message, error)
+ ): Result<T> {
+ var attempt = 0
+ while (true) {
+ try {
+ return Result.success(block())
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: Exception) {
+ val typed = when (error) {
+ is StalkerApiError -> error
+ is IOException -> StalkerApiError.Transport(error.message ?: message, error)
+ else -> error
+ }
+ attempt += 1
+ val retryable = typed is StalkerApiError.RateLimited ||
+ typed is StalkerApiError.Transport ||
+ (typed is StalkerApiError.Server && (typed.httpStatus ?: 500) >= 500)
+ if (!retryable || attempt >= MAX_OPERATION_ATTEMPTS) {
+ return Result.error(typed.message ?: message, typed)
+ }
+ val retryAfter = (typed as? StalkerApiError.RateLimited)?.retryAfterMillis
+ val exponential = 250L shl (attempt - 1)
+ val jitter = kotlin.random.Random.nextLong(100L, 401L)
+ delay((retryAfter ?: (exponential + jitter)).coerceIn(100L, MAX_RETRY_DELAY_MILLIS))
+ }
+ }
+ }
+
+ private fun Throwable.isTerminalStalkerDiscoveryFailure(): Boolean =
+ this is StalkerApiError.AccountBlocked ||
+ this is StalkerApiError.InvalidMac ||
+ this is StalkerApiError.DeviceConflict ||
+ this is StalkerApiError.DeviceNotRegistered ||
+ this is StalkerApiError.ClockSkew ||
+ this is StalkerApiError.RateLimited ||
+ this is StalkerApiError.TransportConsentRequired ||
+ this is StalkerApiError.DiscoveryBudgetExceeded
+
+ private fun Throwable.isInconclusiveLiveReadinessFailure(): Boolean {
+ val chain = generateSequence<Throwable>(this) { it.cause }.toList()
+ if (chain.any {
+ it is StalkerApiError.Authorization ||
+ it is StalkerApiError.AccountBlocked ||
+ it is StalkerApiError.ModelRejected ||
+ it is StalkerApiError.BlockedOrConfiguration ||
+ it is StalkerApiError.TransportConsentRequired ||
+ it is StalkerApiError.RateLimited
+ }
+ ) {
+ return false
+ }
+ val normalizedMessage = chain.joinToString(" ") { it.message.orEmpty() }.lowercase()
+ val definitiveEmptyEvidence = listOf(
+ "returned no live channel categories",
+ "returned no live channels",
+ "live channels without a playback command"
+ ).any(normalizedMessage::contains)
+ return !definitiveEmptyEvidence && chain.any {
+ it is IOException ||
+ it is StalkerApiError.Server ||
+ it is StalkerApiError.Malformed ||
+ it is StalkerApiError.ResponseTooLarge ||
+ it is StalkerApiError.DiscoveryBudgetExceeded
+ }
+ }
+
+ private fun Throwable.isDefinitiveLiveReadinessFailure(): Boolean {
+ val normalizedMessage = generateSequence<Throwable>(this) { it.cause }
+ .joinToString(" ") { it.message.orEmpty() }
+ .lowercase()
+ return listOf(
+ "returned no live channel categories",
+ "returned no live channels",
+ "live channels without a playback command"
+ ).any(normalizedMessage::contains)
+ }
+
+ private fun Throwable.liveReadinessEvidenceCode(): String {
+ val chain = generateSequence<Throwable>(this) { it.cause }.toList()
+ return when {
+ chain.any { it is StalkerApiError.DiscoveryBudgetExceeded } -> "LIVE_BUDGET_EXHAUSTED"
+ chain.any { it is StalkerApiError.ResponseTooLarge } -> "LIVE_RESPONSE_TOO_LARGE"
+ chain.any { it is StalkerApiError.Malformed } -> "LIVE_MALFORMED_RESPONSE"
+ chain.any { it is StalkerApiError.Server } -> "LIVE_SERVER_ERROR"
+ chain.any { it is StalkerApiError.Transport } -> "LIVE_TRANSPORT_ERROR"
+ else -> "LIVE_INCONCLUSIVE"
+ }
+ }
+
+ private fun StalkerApiError.PartialAuthorization.requiresFreshSessionRetry(): Boolean =
+ generateSequence<Throwable>(this) { it.cause }
+ .any { cause ->
+ cause is StalkerApiError.TokenRejected ||
+ cause.message.orEmpty().contains("token", ignoreCase = true)
+ }
+
+ private fun preferredAuthenticationFailure(current: Throwable?, candidate: Throwable): Throwable =
+ if (current == null || authenticationFailureRank(candidate) > authenticationFailureRank(current)) {
+ candidate
+ } else {
+ current
+ }
+
+ private fun authenticationFailureRank(error: Throwable): Int = when (error) {
+ is StalkerApiError.DeviceConflict -> 115
+ is StalkerApiError.DeviceNotRegistered -> 110
+ is StalkerApiError.ClockSkew -> 105
+ is StalkerApiError.PartialAuthorization -> 100
+ is StalkerApiError.AccountBlocked -> 95
+ is StalkerApiError.RateLimited -> 90
+ is StalkerApiError.TokenRejected -> 85
+ is StalkerApiError.InvalidMac -> 80
+ is StalkerApiError.Authorization -> 75
+ is StalkerApiError.ModelRejected -> 60
+ is StalkerApiError.Server -> 50
+ is StalkerApiError.Transport -> 40
+ is StalkerApiError.Malformed -> 30
+ else -> 20
+ }
+
+ private fun authenticationFailureOutcome(error: Throwable): String = when (error) {
+ is StalkerApiError.DeviceConflict -> "DEVICE_CONFLICT"
+ is StalkerApiError.DeviceNotRegistered -> "DEVICE_NOT_REGISTERED"
+ is StalkerApiError.ClockSkew -> "CLOCK_SKEW"
+ is StalkerApiError.PartialAuthorization -> "PARTIAL_AUTHORIZATION"
+ is StalkerApiError.AccountBlocked -> "ACCOUNT_BLOCKED"
+ is StalkerApiError.RateLimited -> "RATE_LIMITED"
+ is StalkerApiError.TokenRejected -> "TOKEN_REJECTED"
+ is StalkerApiError.InvalidMac -> "INVALID_MAC"
+ is StalkerApiError.Authorization -> "AUTHORIZATION_REJECTED"
+ is StalkerApiError.ModelRejected -> "MODEL_REJECTED"
+ is StalkerApiError.Server -> "SERVER_ERROR"
+ is StalkerApiError.Transport -> "TRANSPORT_ERROR"
+ is StalkerApiError.Malformed -> "MALFORMED_RESPONSE"
+ else -> "FAILED"
+ }
+
+ private fun endpointFamily(request: Request): String = when {
+ request.url.encodedPath.endsWith("/portal.php", ignoreCase = true) -> "PORTAL_PHP"
+ request.url.encodedPath.endsWith("/server/load.php", ignoreCase = true) -> "SERVER_LOAD"
+ else -> "OTHER"
}
private fun buildUrl(baseUrl: String, query: Map<String, String>): String {
@@ -1452,12 +2157,47 @@ class OkHttpStalkerApiService @Inject constructor(
return prepared
}
- private fun stalkerHttpClientFor(profile: StalkerDeviceProfile): OkHttpClient {
+ private suspend fun <T> withTransportAwareStalkerCall(
+ request: Request,
+ profile: StalkerDeviceProfile,
+ block: suspend (Response) -> T
+ ): T {
+ return try {
+ val baseClient = stalkerHttpClientFor(profile, request.url.toString())
+ val remainingMillis = profile.discoveryRuntime.remainingMillis()
+ val client = if (remainingMillis == Long.MAX_VALUE) {
+ baseClient
+ } else {
+ baseClient.newBuilder()
+ .callTimeout(remainingMillis, TimeUnit.MILLISECONDS)
+ .build()
+ }
+ withCancellableStalkerCall(client.newCall(request), block)
+ } catch (error: CancellationException) {
+ throw error
+ } catch (error: Throwable) {
+ if (error is StalkerApiError.TransportConsentRequired) throw error
+ transportFactory.challengeForTlsFailure(request.url.toString(), error)?.let { challenge ->
+ throw StalkerApiError.TransportConsentRequired(challenge)
+ }
+ throw error
+ }
+ }
+
+ private fun stalkerHttpClientFor(profile: StalkerDeviceProfile, url: String): OkHttpClient {
val proxy = profile.advancedOptions.proxy
- val key = proxy?.let { "${it.host}:${it.port}" } ?: "<direct>"
+ val scopeKey = sessionScopeKey(profile)
+ val grantKey = profile.transportGrant?.let { grant ->
+ "${grant.mode}:${grant.origin.authority}:${grant.spkiSha256.orEmpty()}"
+ } ?: "AUTO_STRICT"
+ val key = "$scopeKey|$grantKey|${proxy?.let { "${it.host}:${it.port}" } ?: "<direct>"}"
+ val transportClient = transportFactory.clientFor(url, profile.transportGrant)
return stalkerHttpClients.computeIfAbsent(key) {
- okHttpClient.newBuilder()
- .cookieJar(cookieJar)
+ transportClient.newBuilder()
+ // Stalker requests need one deterministic Cookie header containing both
+ // durable MAG identity cookies and server-issued affinity/session cookies.
+ // OkHttp's automatic cookie bridge would replace that merged header.
+ .cookieJar(CookieJar.NO_COOKIES)
.apply {
if (proxy != null) {
proxy(Proxy(Proxy.Type.HTTP, InetSocketAddress(proxy.host, proxy.port)))
@@ -1467,10 +2207,13 @@ class OkHttpStalkerApiService @Inject constructor(
}
}
- private fun buildProfileQuery(profile: StalkerDeviceProfile): Map<String, String> {
+ private fun buildProfileQuery(
+ profile: StalkerDeviceProfile,
+ handshakeRandom: String
+ ): Map<String, String> {
val timestamp = (System.currentTimeMillis() / 1000L).toString()
val preset = stalkerMagPresetSpec(profile.magPreset)
- val metrics = buildMetricsJson(profile, preset)
+ val metrics = buildMetricsJson(profile, handshakeRandom)
val hwVersion = profile.advancedOptions.hwVersion.trim().ifBlank { preset.hwVersion }
return linkedMapOf(
"type" to "stb",
@@ -1485,11 +2228,13 @@ class OkHttpStalkerApiService @Inject constructor(
"device_id" to profile.deviceId,
"device_id2" to profile.deviceId2,
"signature" to profile.signature,
- "auth_second_step" to "1",
+ "auth_second_step" to if (profile.authMode.requiresCredentials()) "1" else "0",
"hw_version" to hwVersion,
"not_valid_token" to "0",
"metrics" to metrics,
- "hw_version_2" to hwVersion,
+ // Real MAG hardware computes this with gSTB.GetHashVersion1(metrics, random).
+ // An empty value is truthful; substituting the hardware version is not a valid hash.
+ "hw_version_2" to "",
"timestamp" to timestamp,
"api_signature" to preset.apiSignature,
"prehash" to "false",
@@ -1506,7 +2251,7 @@ class OkHttpStalkerApiService @Inject constructor(
profile.macAddress.takeIf { it.isNotBlank() }?.let { cookies["mac"] = encode(it) }
profile.locale.takeIf { it.isNotBlank() }?.let { cookies["stb_lang"] = encode(it) }
profile.timezone.takeIf { it.isNotBlank() }?.let { cookies["timezone"] = encode(it) }
- cookieJar.cookieHeaderFor(url).split(';')
+ cookieJarFor(profile).cookieHeaderFor(url).split(';')
.mapNotNull { part ->
val key = part.substringBefore('=', missingDelimiterValue = "").trim()
val value = part.substringAfter('=', missingDelimiterValue = "").trim()
@@ -1561,38 +2306,152 @@ class OkHttpStalkerApiService @Inject constructor(
private fun buildMetricsJson(
profile: StalkerDeviceProfile,
- preset: StalkerMagPresetSpec
- ): String {
- if (preset.metricsJson != "{}") {
- return preset.metricsJson
+ handshakeRandom: String
+ ): String = JsonObject(
+ linkedMapOf(
+ "mac" to JsonPrimitive(profile.macAddress),
+ "sn" to JsonPrimitive(profile.serialNumber),
+ "model" to JsonPrimitive(profile.deviceProfile),
+ "type" to JsonPrimitive("STB"),
+ "uid" to JsonPrimitive(profile.deviceId2),
+ "random" to JsonPrimitive(handshakeRandom)
+ )
+ ).toString()
+
+ private fun captureResponseCookies(response: Response, profile: StalkerDeviceProfile) {
+ val cookies = Cookie.parseAll(response.request.url, response.headers)
+ if (cookies.isNotEmpty()) {
+ cookieJarFor(profile).saveFromResponse(response.request.url, cookies)
}
- return buildString {
- append('{')
- append("\"mac\":\"").append(profile.macAddress).append("\",")
- append("\"sn\":\"").append(profile.serialNumber).append("\",")
- append("\"model\":\"").append(profile.deviceProfile).append("\",")
- append("\"type\":\"STB\",")
- append("\"uid\":\"").append(profile.deviceId2.take(16)).append("\",")
- append("\"random\":\"").append(profile.deviceId2.take(16)).append('"')
- append('}')
+ }
+
+ private fun recordResolvedLoadUrl(request: Request, response: Response, profile: StalkerDeviceProfile) {
+ val requested = request.url.newBuilder().query(null).fragment(null).build().toString()
+ val resolved = response.request.url.newBuilder().query(null).fragment(null).build().toString()
+ if (requested == resolved) return
+ resolvedLoadUrls[resolvedLoadUrlKey(requested, profile)] = resolved
+ if (resolvedLoadUrls.size > MAX_RESOLVED_LOAD_URLS) {
+ resolvedLoadUrls.keys.firstOrNull()?.let(resolvedLoadUrls::remove)
}
}
- private fun captureResponseCookies(response: Response) {
- val cookies = Cookie.parseAll(response.request.url, response.headers)
- if (cookies.isNotEmpty()) {
- cookieJar.saveFromResponse(response.request.url, cookies)
+ private fun resolvedLoadUrl(loadUrl: String, profile: StalkerDeviceProfile): String? =
+ resolvedLoadUrls[resolvedLoadUrlKey(loadUrl, profile)]
+
+ private fun resolvedLoadUrlKey(loadUrl: String, profile: StalkerDeviceProfile): String =
+ "${sessionScopeKey(profile)}|${StalkerUrlFactory.normalizePortalUrl(loadUrl)}"
+
+ private fun Response.toStalkerHttpError(htmlErrorPage: Boolean = false): StalkerApiError {
+ val retryAfterMillis = header("Retry-After")
+ ?.trim()
+ ?.toLongOrNull()
+ ?.coerceAtLeast(0L)
+ ?.times(1000L)
+ return when (code) {
+ 401, 403 -> if (htmlErrorPage) {
+ StalkerApiError.BlockedOrConfiguration(
+ message = "Portal request was blocked with HTTP $code.",
+ portalReason = "html_error_page"
+ )
+ } else {
+ StalkerApiError.Authorization(
+ message = "Portal authorization failed with HTTP $code.",
+ httpStatus = code
+ )
+ }
+ 429 -> StalkerApiError.RateLimited(
+ httpStatus = code,
+ retryAfterMillis = retryAfterMillis
+ )
+ in 500..599 -> StalkerApiError.Server(
+ message = "Portal request failed with HTTP $code.",
+ httpStatus = code
+ )
+ else -> StalkerApiError.BlockedOrConfiguration(
+ message = "Portal request failed with HTTP $code."
+ )
}
}
+ private fun cookieJarFor(profile: StalkerDeviceProfile): InMemoryStalkerCookieJar {
+ val now = System.currentTimeMillis()
+ val key = sessionScopeKey(profile)
+ val scope = sessionScopes.computeIfAbsent(key) { SessionScope(lastAccessAt = now) }
+ scope.lastAccessAt = now
+ if (sessionScopes.size > MAX_SESSION_SCOPES) {
+ val excess = sessionScopes.size - MAX_SESSION_SCOPES
+ sessionScopes.entries
+ .filter { it.key != key }
+ .sortedWith(
+ compareBy<Map.Entry<String, SessionScope>>(
+ { now - it.value.lastAccessAt <= SESSION_SCOPE_IDLE_MILLIS },
+ { it.value.lastAccessAt }
+ )
+ )
+ .take(excess)
+ .forEach { (staleKey, _) ->
+ sessionScopes.remove(staleKey)
+ stalkerHttpClients.keys.removeIf { clientKey -> clientKey.startsWith("$staleKey|") }
+ }
+ }
+ return scope.cookieJar
+ }
+
+ private fun sessionScopeKey(profile: StalkerDeviceProfile): String {
+ val normalized = listOf(
+ StalkerUrlFactory.normalizePortalUrl(profile.portalUrl),
+ profile.macAddress.trim().uppercase(Locale.ROOT),
+ profile.username.trim(),
+ profile.password,
+ profile.deviceProfile.trim(),
+ profile.deviceId.trim(),
+ profile.deviceId2.trim(),
+ profile.serialNumber.trim(),
+ profile.compatibilityProfileId,
+ profile.advancedOptions.proxy?.let { "${it.host}:${it.port}" }.orEmpty()
+ ).joinToString("\u001f")
+ return MessageDigest.getInstance("SHA-256")
+ .digest(normalized.toByteArray(Charsets.UTF_8))
+ .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
+ }
+
+ private fun hashDiscoveryHeaderPolicy(profile: StalkerDeviceProfile): String {
+ val policy = buildString {
+ append(profile.httpUserAgent)
+ append('\u001f')
+ append(profile.httpHeaders)
+ append('\u001f')
+ profile.headerOverrides.toSortedMap(String.CASE_INSENSITIVE_ORDER)
+ .forEach { (name, value) ->
+ append(name.lowercase(Locale.ROOT))
+ append('=')
+ append(value.orEmpty())
+ append('\u001e')
+ }
+ }
+ return MessageDigest.getInstance("SHA-256")
+ .digest(policy.toByteArray(Charsets.UTF_8))
+ .take(12)
+ .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
+ }
+
private fun JsonElement.totalPages(): Int {
- val payload = payloadObjectOrNull() ?: return 1
- val totalItems = payload["total_items"]?.primitiveContentOrNull()?.toIntOrNull() ?: return 1
- val pageSize = pageSize(payload["data"]?.jsonArrayOrNull()?.size ?: 0).takeIf { it > 0 }
- ?: return 1
- return ((totalItems + pageSize - 1) / pageSize).coerceAtLeast(1).coerceAtMost(MAX_PAGE_COUNT)
+ return (advertisedTotalPages() ?: 1).coerceAtMost(MAX_PAGE_COUNT)
+ }
+
+ private fun JsonElement.advertisedTotalPages(): Int? {
+ val totalItems = advertisedTotalItems() ?: return null
+ val fallbackSize = payloadObjectOrNull()?.get("data")?.jsonArrayOrNull()?.size ?: 0
+ val pageSize = pageSize(fallbackSize).takeIf { it > 0 } ?: return null
+ return ((totalItems + pageSize - 1) / pageSize).coerceAtLeast(1)
}
+ private fun JsonElement.advertisedTotalItems(): Int? = payloadObjectOrNull()
+ ?.get("total_items")
+ ?.primitiveContentOrNull()
+ ?.toIntOrNull()
+ ?.takeIf { it >= 0 }
+
private fun JsonElement.pageSize(fallback: Int): Int {
val payload = payloadObjectOrNull() ?: return fallback
return payload["max_page_items"]?.primitiveContentOrNull()?.toIntOrNull()
@@ -1601,7 +2460,7 @@ class OkHttpStalkerApiService @Inject constructor(
?: fallback
}
- private fun JsonElement.toProviderProfile(): StalkerProviderProfile {
+ private fun JsonElement.toProviderProfile(timezone: String): StalkerProviderProfile {
val payload = payloadObjectOrNull()
return StalkerProviderProfile(
accountId = payload?.findString("id"),
@@ -1612,10 +2471,13 @@ class OkHttpStalkerApiService @Inject constructor(
?.toIntOrNull()
?: payload?.findString("max_connections")?.toIntOrNull(),
expirationDate = payload?.findString("expire_billing_date")
- ?.let(::parseExpirationDate)
- ?: payload?.findString("end_date")?.let(::parseExpirationDate),
+ ?.let { parseExpirationDate(it, timezone.toPortalZoneId()) }
+ ?: payload?.findString("end_date")?.let { parseExpirationDate(it, timezone.toPortalZoneId()) },
statusLabel = payload?.findString("status"),
- authAccess = payload?.findBoolean("auth_access")
+ authAccess = payload?.findBoolean("auth_access"),
+ reportedStbType = payload?.findString("stb_type")
+ ?: payload?.findString("device_model")
+ ?: payload?.findString("model")
)
}
@@ -1627,6 +2489,7 @@ class OkHttpStalkerApiService @Inject constructor(
expirationDate = other.expirationDate ?: expirationDate,
statusLabel = other.statusLabel ?: statusLabel,
authAccess = other.authAccess ?: authAccess,
+ reportedStbType = other.reportedStbType ?: reportedStbType,
moduleNames = if (other.moduleNames.isNotEmpty()) other.moduleNames else moduleNames,
bootstrapStrategy = if (other.bootstrapStrategy != StalkerBootstrapStrategy.AUTO) {
other.bootstrapStrategy
@@ -1714,7 +2577,10 @@ class OkHttpStalkerApiService @Inject constructor(
StalkerCategoryRecord(
id = id,
name = name,
- alias = entry.findString("alias")
+ alias = entry.findString("alias"),
+ advertisedItemCount = entry.findString("count")?.toIntOrNull()
+ ?: entry.findString("items")?.toIntOrNull()
+ ?: entry.findString("total")?.toIntOrNull()
)
}
}
@@ -2074,14 +2940,15 @@ class OkHttpStalkerApiService @Inject constructor(
}.getOrNull()
}
- private fun JsonElement.toProgramRecords(channelId: String? = null): List<StalkerProgramRecord> {
+ private fun JsonElement.toProgramRecords(channelId: String? = null, timezone: String): List<StalkerProgramRecord> {
+ val zoneId = timezone.toPortalZoneId()
return extractListElements().mapNotNull { entry ->
val resolvedChannelId = channelId ?: entry.findProgramChannelId() ?: return@mapNotNull null
val startMillis = entry.findString("start_timestamp")?.toLongOrNull()?.times(1000L)
- ?: entry.findString("time")?.let(::parseDateTime)
+ ?: entry.findString("time")?.let { parseDateTime(it, zoneId) }
?: return@mapNotNull null
val endMillis = entry.findString("stop_timestamp")?.toLongOrNull()?.times(1000L)
- ?: entry.findString("time_to")?.let(::parseDateTime)
+ ?: entry.findString("time_to")?.let { parseDateTime(it, zoneId) }
?: startMillis + (entry.findString("duration")?.toLongOrNull()?.times(60_000L) ?: DEFAULT_PROGRAM_DURATION_MILLIS)
StalkerProgramRecord(
id = entry.findString("id") ?: "$resolvedChannelId:$startMillis",
@@ -2122,6 +2989,15 @@ class OkHttpStalkerApiService @Inject constructor(
}
}
+ private fun JsonElement.isRecognizedCatalogPayload(): Boolean {
+ if (this is JsonArray) return true
+ val js = rootObjectOrNull()?.get("js") ?: return false
+ if (js is JsonArray) return true
+ val wrapper = js.jsonObjectOrNull() ?: return false
+ return wrapper["data"] is JsonArray || wrapper["data"] is JsonObject ||
+ wrapper["items"] is JsonArray || wrapper["items"] is JsonObject
+ }
+
private fun JsonElement.findString(key: String): String? {
val payload = payloadObjectOrNull()
return payload?.findString(key)
@@ -2158,6 +3034,11 @@ class OkHttpStalkerApiService @Inject constructor(
}
}
+ private fun JsonObject.findInt(key: String): Int? {
+ val element = this[key] as? JsonPrimitive ?: return null
+ return element.contentOrNull?.trim()?.toIntOrNull()
+ }
+
private fun GsonJsonObject.findString(key: String): String? {
val element = get(key) ?: return null
if (!element.isJsonPrimitive) return null
@@ -2259,8 +3140,8 @@ class OkHttpStalkerApiService @Inject constructor(
StalkerAuthMode.AUTO -> buildList {
val hasMac = profile.macAddress.isNotBlank()
val hasCredentials = profile.username.isNotBlank()
- if (hasMac && hasCredentials) add(StalkerAuthMode.MAC_PLUS_CREDENTIALS)
if (hasMac) add(StalkerAuthMode.MAC_ONLY)
+ if (hasMac && hasCredentials) add(StalkerAuthMode.MAC_PLUS_CREDENTIALS)
if (hasCredentials) add(StalkerAuthMode.CREDENTIALS_ONLY)
if (isEmpty()) add(StalkerAuthMode.MAC_ONLY)
}
@@ -2272,6 +3153,49 @@ class OkHttpStalkerApiService @Inject constructor(
profile: StalkerDeviceProfile,
effectiveAuthMode: StalkerAuthMode
): List<StalkerRecipeSpec> {
+ val requestedProfile = StalkerCompatibilityRegistry.find(profile.requestedProfileId)
+ val manuallySelected = profile.requestedProfileId != StalkerCompatibilityProfileIds.AUTO
+ if (manuallySelected && requestedProfile != null) {
+ val base = StalkerCompatibilityRegistry.baseFingerprint(requestedProfile)
+ val preset = base.preset ?: profile.magPreset
+ val captured = fallbackRecipesFor(effectiveAuthMode).firstOrNull {
+ it.recipe == base.bootstrapRecipe && it.magPreset == preset
+ }
+ return listOf(
+ (captured ?: defaultRecipeFor(effectiveAuthMode, profile.portalFingerprint, preset)).copy(
+ recipe = base.bootstrapRecipe ?: profile.bootstrapRecipe,
+ magPreset = preset,
+ compatibilityProfileId = requestedProfile.id
+ )
+ )
+ }
+ if (!profile.allowCompatibilityDiscovery) {
+ val learnedProfile = StalkerCompatibilityRegistry.find(profile.compatibilityProfileId)
+ ?: StalkerCompatibilityRegistry.find(
+ StalkerCompatibilityRegistry.idForLegacyPreset(profile.magPreset)
+ )
+ learnedProfile?.let { learned ->
+ val base = StalkerCompatibilityRegistry.baseFingerprint(learned)
+ val preset = base.preset ?: profile.magPreset
+ val captured = fallbackRecipesFor(effectiveAuthMode).firstOrNull {
+ it.recipe == base.bootstrapRecipe && it.magPreset == preset
+ }
+ return listOf(
+ (captured ?: defaultRecipeFor(effectiveAuthMode, profile.portalFingerprint, preset)).copy(
+ recipe = base.bootstrapRecipe ?: profile.bootstrapRecipe,
+ magPreset = preset,
+ compatibilityProfileId = learned.id
+ )
+ )
+ }
+ return listOf(
+ defaultRecipeFor(effectiveAuthMode, profile.portalFingerprint, profile.magPreset).copy(
+ recipe = profile.bootstrapRecipe,
+ magPreset = profile.magPreset,
+ compatibilityProfileId = profile.compatibilityProfileId
+ )
+ )
+ }
val defaultRecipe = defaultRecipeFor(
authMode = effectiveAuthMode,
fingerprintHint = profile.portalFingerprint,
@@ -2290,26 +3214,75 @@ class OkHttpStalkerApiService @Inject constructor(
presetHint = profile.magPreset
).magPreset
)
- return (listOf(defaultRecipe) + fallbackRecipesFor(effectiveAuthMode))
- .distinctBy { "${it.recipe}:${it.magPreset}:${it.authMode}" }
+ if (effectiveAuthMode != StalkerAuthMode.MAC_ONLY) {
+ return (listOf(defaultRecipe) + fallbackRecipesFor(effectiveAuthMode))
+ .distinctBy { "${it.recipe}:${it.magPreset}:${it.authMode}" }
+ .take(StalkerCompatibilityRegistry.MAX_AUTOMATIC_ATTEMPTS)
+ }
+ val preferred = when {
+ profile.portalFingerprint != StalkerPortalFingerprint.BASIC_MAC ->
+ StalkerCompatibilityRegistry.idForLegacyPreset(defaultRecipe.magPreset)
+ profile.compatibilityProfileId == StalkerCompatibilityProfileIds.AUTO -> null
+ profile.compatibilityProfileId == StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC &&
+ profile.magPreset != StalkerMagPreset.GENERIC_SAFE ->
+ StalkerCompatibilityRegistry.idForLegacyPreset(profile.magPreset)
+ else -> profile.compatibilityProfileId
+ }
+ return StalkerCompatibilityRegistry.classicAutomaticOrder(preferred).map { candidate ->
+ val base = StalkerCompatibilityRegistry.baseFingerprint(candidate)
+ val preset = base.preset ?: profile.magPreset
+ val capturedRecipe = fallbackRecipesFor(effectiveAuthMode).firstOrNull {
+ it.recipe == base.bootstrapRecipe && it.magPreset == preset
+ } ?: defaultRecipeFor(effectiveAuthMode, profile.portalFingerprint, preset).copy(
+ recipe = base.bootstrapRecipe ?: defaultRecipe.recipe,
+ magPreset = preset
+ )
+ val selectedRecipe = if (candidate.id == preferred &&
+ (profile.portalFingerprint != StalkerPortalFingerprint.BASIC_MAC ||
+ profile.bootstrapRecipe != StalkerBootstrapRecipe.GENERIC_SAFE ||
+ defaultRecipe.recipe != StalkerBootstrapRecipe.GENERIC_SAFE)
+ ) {
+ defaultRecipe
+ } else {
+ capturedRecipe
+ }
+ selectedRecipe.copy(
+ compatibilityProfileId = candidate.id
+ )
+ }.ifEmpty { listOf(defaultRecipe) }
+ .distinctBy { it.compatibilityProfileId }
+ .take(StalkerCompatibilityRegistry.MAX_AUTOMATIC_ATTEMPTS)
}
private fun candidateAuthAttempts(
profile: StalkerDeviceProfile,
- effectiveAuthMode: StalkerAuthMode
+ effectiveAuthMode: StalkerAuthMode,
+ hintedLoadUrls: List<String> = emptyList()
): List<StalkerAuthAttempt> {
val recipes = candidateRecipes(profile, effectiveAuthMode)
+ .take(profile.discoveryBudget.maxIdentityProfiles)
val defaultRecipe = recipes.firstOrNull() ?: return emptyList()
+ if (!profile.allowCompatibilityDiscovery) {
+ val loadUrl = orderedLoadUrlCandidates(profile, defaultRecipe, hintedLoadUrls).firstOrNull()
+ ?: return emptyList()
+ return recipes.mapIndexed { recipeIndex, recipe ->
+ StalkerAuthAttempt(recipeIndex, recipe, loadUrl)
+ }
+ }
val hasLearnedEndpointPreference = profile.endpointPreference != StalkerEndpointPreference.AUTO ||
defaultRecipe.endpointPreference != StalkerEndpointPreference.AUTO
return if (hasLearnedEndpointPreference) {
recipes.flatMapIndexed { recipeIndex, recipe ->
- orderedLoadUrlCandidates(profile, recipe).map { loadUrl ->
+ orderedLoadUrlCandidates(profile, recipe, hintedLoadUrls)
+ .take(profile.discoveryBudget.maxEndpointCandidates)
+ .map { loadUrl ->
StalkerAuthAttempt(recipeIndex, recipe, loadUrl)
}
}
} else {
- orderedLoadUrlCandidates(profile, defaultRecipe).flatMap { loadUrl ->
+ orderedLoadUrlCandidates(profile, defaultRecipe, hintedLoadUrls)
+ .take(profile.discoveryBudget.maxEndpointCandidates)
+ .flatMap { loadUrl ->
recipes.mapIndexed { recipeIndex, recipe ->
StalkerAuthAttempt(recipeIndex, recipe, loadUrl)
}
@@ -2317,11 +3290,88 @@ class OkHttpStalkerApiService @Inject constructor(
}
}
+ private fun promoteCompatibilityAttempt(
+ attempts: ArrayDeque<StalkerAuthAttempt>,
+ compatibilityProfileId: String,
+ loadUrl: String
+ ) {
+ val queued = attempts.toList()
+ val promoted = queued.firstOrNull { candidate ->
+ candidate.recipe.compatibilityProfileId == compatibilityProfileId &&
+ candidate.loadUrl == loadUrl
+ } ?: return
+ attempts.clear()
+ attempts.addLast(promoted)
+ queued.filterNot { it === promoted }.forEach(attempts::addLast)
+ }
+
+ /**
+ * Best-effort discovery of the portal's install path. Many portals serve the API from a
+ * non-root base (e.g. `/stalker_portal/`); for those, a bare `GET /` typically redirects
+ * to `<base>/c/`. Following that redirect once (same-origin only, enforced by the
+ * transport layer) reveals the base path and lets discovery try the correct
+ * `server/load.php` first instead of burning the request budget on 404/403 probes.
+ *
+ * Sends no MAC/cookies/identity headers and never throws: any failure simply yields no
+ * hint. Runs only for compatibility discovery (add-provider / repair), where endpoint
+ * order matters; saved providers reuse their learned endpoint.
+ */
+ private suspend fun probePortalBaseHintCandidates(profile: StalkerDeviceProfile): List<String> {
+ if (!profile.allowCompatibilityDiscovery) return emptyList()
+ if (!StalkerUrlFactory.isBarePortalBase(profile.portalUrl)) return emptyList()
+ val normalized = StalkerUrlFactory.normalizePortalUrl(profile.portalUrl)
+ val baseUrl = "$normalized/"
+ return runCatching {
+ val remaining = profile.discoveryRuntime.remainingMillis()
+ val timeoutMillis = minOf(PORTAL_BASE_HINT_TIMEOUT_MILLIS, remaining)
+ if (timeoutMillis <= 0L) return emptyList()
+ val client = transportFactory.clientFor(baseUrl, profile.transportGrant)
+ .newBuilder()
+ .callTimeout(timeoutMillis, TimeUnit.MILLISECONDS)
+ .build()
+ val request = Request.Builder()
+ .url(baseUrl)
+ .header("User-Agent", profile.userAgent)
+ .header("Accept", "*/*")
+ .build()
+ withCancellableStalkerCall(client.newCall(request)) { response ->
+ response.use {
+ val finalUrl = response.request.url
+ val path = finalUrl.encodedPath.trimEnd('/')
+ if (!path.endsWith("/c", ignoreCase = true)) return@withCancellableStalkerCall emptyList()
+ val portalBase = path.dropLast(2)
+ if (portalBase.isNotEmpty() &&
+ (!portalBase.startsWith("/") || portalBase.substringAfterLast('/').isEmpty())
+ ) {
+ return@withCancellableStalkerCall emptyList()
+ }
+ val origin = "${finalUrl.scheme}://${finalUrl.host}" +
+ if (finalUrl.port != defaultPortForScheme(finalUrl.scheme)) ":${finalUrl.port}" else ""
+ listOf(
+ "$origin$portalBase/server/load.php",
+ "$origin$portalBase/portal.php"
+ )
+ }
+ }
+ }.getOrElse { error ->
+ if (error is CancellationException) throw error
+ emptyList()
+ }.also { hinted ->
+ if (hinted.isNotEmpty()) {
+ Log.d(TAG, "Stalker portal base hint ${runCatching { URI(baseUrl).host }.getOrNull().orEmpty()} resolved=${hinted.first()}")
+ }
+ }
+ }
+
+ private fun defaultPortForScheme(scheme: String): Int =
+ if (scheme.equals("https", ignoreCase = true)) 443 else 80
+
private fun orderedLoadUrlCandidates(
profile: StalkerDeviceProfile,
- recipe: StalkerRecipeSpec
+ recipe: StalkerRecipeSpec,
+ hintedLoadUrls: List<String> = emptyList()
): List<String> {
- val baseCandidates = StalkerUrlFactory.loadUrlCandidates(profile.portalUrl)
+ val baseCandidates = (hintedLoadUrls + StalkerUrlFactory.loadUrlCandidates(profile.portalUrl)).distinct()
when (profile.endpointPreference) {
StalkerEndpointPreference.PORTAL -> {
return baseCandidates.filter { candidate ->
@@ -2352,11 +3402,6 @@ class OkHttpStalkerApiService @Inject constructor(
val loadUrl: String
)
- private data class StalkerBootstrapSession(
- val token: String,
- var credentialAuthenticated: Boolean = false
- )
-
private fun endpointPreferenceFor(loadUrl: String): StalkerEndpointPreference =
when {
loadUrl.lowercase(Locale.ROOT).endsWith("/portal.php") -> StalkerEndpointPreference.PORTAL
@@ -2453,6 +3498,14 @@ class OkHttpStalkerApiService @Inject constructor(
companion object {
private const val TAG = "OkHttpStalkerApi"
private const val MAX_PAGE_COUNT = 200
+ private const val MAX_DISCOVERY_CATEGORY_PROBES = 8
+ private const val MAX_RESOLVED_LOAD_URLS = 64
+ private const val MAX_SESSION_SCOPES = 16
+ private const val MAX_OPERATION_ATTEMPTS = 3
+ private const val MAX_RETRY_DELAY_MILLIS = 30_000L
+ private const val HTML_ERROR_SNIFF_BYTES = 2_048L
+ private const val PORTAL_BASE_HINT_TIMEOUT_MILLIS = 8_000L
+ private const val SESSION_SCOPE_IDLE_MILLIS = 30 * 60_000L
private const val DEFAULT_PROGRAM_DURATION_MILLIS = 30 * 60_000L
/** Hard ceiling for the streamed `get_epg_info` body; anything larger is treated as a portal fault. */
private const val MAX_EPG_BYTES = 64L * 1024L * 1024L
@@ -2464,6 +3517,62 @@ class OkHttpStalkerApiService @Inject constructor(
}
}
+internal fun <T> sampleDiscoveryCategories(categories: List<T>, limit: Int): List<T> {
+ if (limit <= 0 || categories.isEmpty()) return emptyList()
+ if (categories.size <= limit) return categories
+ if (limit == 1) return listOf(categories.first())
+ val lastIndex = categories.lastIndex
+ return (0 until limit)
+ .map { sampleIndex -> (sampleIndex * lastIndex) / (limit - 1) }
+ .distinct()
+ .map(categories::get)
+}
+
+internal fun sampleLiveDiscoveryCategories(
+ categories: List<StalkerCategoryRecord>,
+ limit: Int
+): List<StalkerCategoryRecord> {
+ if (limit <= 0 || categories.isEmpty()) return emptyList()
+ if (categories.size <= limit) {
+ return categories.sortedWith(
+ compareByDescending<StalkerCategoryRecord> { it.advertisedItemCount ?: -1 }
+ .thenBy { categories.indexOf(it) }
+ )
+ }
+ val prioritized = categories.withIndex()
+ .filter { (_, category) -> (category.advertisedItemCount ?: 0) > 0 }
+ .sortedWith(
+ compareByDescending<IndexedValue<StalkerCategoryRecord>> {
+ it.value.advertisedItemCount ?: 0
+ }.thenBy(IndexedValue<StalkerCategoryRecord>::index)
+ )
+ .map(IndexedValue<StalkerCategoryRecord>::value)
+ return buildList {
+ prioritized.forEach { category ->
+ if (size < limit && category !in this) add(category)
+ }
+ // Preserve coverage at both ends even when high-confidence categories consume part of
+ // the sample budget.
+ listOf(categories.first(), categories.last()).forEach { category ->
+ if (size < limit && category !in this) add(category)
+ }
+ sampleDiscoveryCategories(categories, limit).forEach { category ->
+ if (size < limit && category !in this) add(category)
+ }
+ categories.forEach { category ->
+ if (size < limit && category !in this) add(category)
+ }
+ }
+}
+
+private fun <T> kotlin.Result<T>.getOrNullPreservingCancellation(): T? = fold(
+ onSuccess = { it },
+ onFailure = { error ->
+ if (error is CancellationException) throw error
+ null
+ }
+)
+
internal fun buildStalkerDeviceProfile(
portalUrl: String,
macAddress: String,
@@ -2485,12 +3594,30 @@ internal fun buildStalkerDeviceProfile(
deviceIdOverride: String = "",
deviceId2Override: String = "",
signatureOverride: String = "",
- stalkerAdvancedOptionsJson: String = ""
+ stalkerAdvancedOptionsJson: String = "",
+ protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ transportGrant: StalkerTransportGrant? = null,
+ requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
+ learnedProfileId: String = "",
+ requireCatalogValidation: Boolean = false,
+ allowCompatibilityDiscovery: Boolean = true,
+ discoveryBudget: DiscoveryBudget = DiscoveryBudget(),
+ discoveryRuntime: StalkerDiscoveryRuntime = StalkerDiscoveryRuntime(discoveryBudget),
+ onProgress: ((String) -> Unit)? = null
): StalkerDeviceProfile {
val advancedOptions = StalkerAdvancedOptionsCodec.decode(stalkerAdvancedOptionsJson)
- val preset = stalkerMagPresetSpec(magPresetHint)
+ val requestedCompatibilityProfile = StalkerCompatibilityRegistry.find(requestedProfileId)
+ val selectedCompatibilityProfile = requestedCompatibilityProfile
+ ?: StalkerCompatibilityRegistry.find(learnedProfileId)
+ val activeCompatibilityProfile = selectedCompatibilityProfile
+ ?: StalkerCompatibilityRegistry.find(StalkerCompatibilityRegistry.idForLegacyPreset(magPresetHint))
+ val baseFingerprint = activeCompatibilityProfile?.let(StalkerCompatibilityRegistry::baseFingerprint)
+ val effectivePreset = baseFingerprint?.preset ?: magPresetHint
+ val preset = stalkerMagPresetSpec(effectivePreset)
val normalizedInputProfile = deviceProfile.trim()
val normalizedProfile = when {
+ selectedCompatibilityProfile != null && requestedProfileId != StalkerCompatibilityProfileIds.CUSTOM ->
+ selectedCompatibilityProfile.model
normalizedInputProfile.isBlank() -> preset.defaultDeviceProfile
magPresetHint != StalkerMagPreset.GENERIC_SAFE && normalizedInputProfile.equals("MAG250", ignoreCase = true) ->
preset.defaultDeviceProfile
@@ -2522,7 +3649,7 @@ internal fun buildStalkerDeviceProfile(
portalUrl = portalUrl,
macAddress = normalizedMac,
authMode = effectiveAuthMode,
- magPreset = magPresetHint,
+ magPreset = effectivePreset,
portalFingerprint = portalFingerprintHint,
bootstrapRecipe = bootstrapRecipeHint,
endpointPreference = endpointPreferenceHint,
@@ -2543,7 +3670,17 @@ internal fun buildStalkerDeviceProfile(
httpUserAgent = normalizedHttpUserAgent,
httpHeaders = normalizedHttpHeaders,
headerOverrides = headerOverrides,
- advancedOptions = advancedOptions
+ advancedOptions = advancedOptions,
+ protocolPreference = protocolPreference,
+ transportGrant = transportGrant,
+ requestedProfileId = requestedProfileId,
+ compatibilityProfileId = activeCompatibilityProfile?.id
+ ?: StalkerCompatibilityRegistry.idForLegacyPreset(effectivePreset),
+ requireCatalogValidation = requireCatalogValidation,
+ allowCompatibilityDiscovery = allowCompatibilityDiscovery,
+ discoveryBudget = discoveryBudget,
+ discoveryRuntime = discoveryRuntime,
+ onProgress = onProgress
)
}
@@ -2606,7 +3743,16 @@ private fun StalkerDeviceProfile.withRecipe(
deviceIdOverride = deviceId,
deviceId2Override = deviceId2,
signatureOverride = signature,
- stalkerAdvancedOptionsJson = StalkerAdvancedOptionsCodec.encode(advancedOptions)
+ stalkerAdvancedOptionsJson = StalkerAdvancedOptionsCodec.encode(advancedOptions),
+ protocolPreference = protocolPreference,
+ transportGrant = transportGrant,
+ requestedProfileId = recipe.compatibilityProfileId,
+ learnedProfileId = recipe.compatibilityProfileId,
+ requireCatalogValidation = requireCatalogValidation,
+ allowCompatibilityDiscovery = allowCompatibilityDiscovery,
+ discoveryBudget = discoveryBudget,
+ discoveryRuntime = discoveryRuntime,
+ onProgress = onProgress
)
}
@@ -2637,7 +3783,7 @@ private fun Request.Builder.applyStalkerHeaderOverrides(
}
}
-internal fun parseExpirationDate(raw: String?): Long? {
+internal fun parseExpirationDate(raw: String?, zoneId: ZoneId = ZoneOffset.UTC): Long? {
val value = raw?.trim()?.takeIf { it.isNotEmpty() } ?: return null
value.toLongOrNull()?.let { numeric ->
return if (numeric >= 1_000_000_000_000L) numeric else numeric * 1000L
@@ -2646,22 +3792,25 @@ internal fun parseExpirationDate(raw: String?): Long? {
runCatching { OffsetDateTime.parse(value).toInstant().toEpochMilli() }.getOrNull()?.let { return it }
STALKER_DATE_TIME_FORMATTERS.forEach { formatter ->
runCatching {
- LocalDateTime.parse(value, formatter).toInstant(ZoneOffset.UTC).toEpochMilli()
+ LocalDateTime.parse(value, formatter).atZone(zoneId).toInstant().toEpochMilli()
}.getOrNull()?.let { return it }
}
STALKER_DATE_FORMATTERS.forEach { formatter ->
runCatching {
- LocalDate.parse(value, formatter).atStartOfDay().toInstant(ZoneOffset.UTC).toEpochMilli()
+ LocalDate.parse(value, formatter).atStartOfDay(zoneId).toInstant().toEpochMilli()
}.getOrNull()?.let { return it }
}
return null
}
-private fun parseDateTime(raw: String?): Long? {
+private fun parseDateTime(raw: String?, zoneId: ZoneId = ZoneOffset.UTC): Long? {
val value = raw?.trim()?.takeIf { it.isNotEmpty() } ?: return null
- return parseExpirationDate(value)
+ return parseExpirationDate(value, zoneId)
}
+private fun String.toPortalZoneId(): ZoneId =
+ runCatching { ZoneId.of(trim()) }.getOrDefault(ZoneOffset.UTC)
+
private val STALKER_DATE_TIME_FORMATTERS: List<DateTimeFormatter> = listOf(
"yyyy-MM-dd HH:mm:ss",
"yyyy-MM-dd HH:mm",
@@ -2720,39 +3869,69 @@ private class ByteSizeLimitInputStream(
private fun checkLimit() {
if (bytesRead > maxBytes) {
- throw IOException(onOverflow())
+ throw StalkerApiError.ResponseTooLarge(onOverflow())
}
}
}
-private class InMemoryStalkerCookieJar : CookieJar {
- private val store = ConcurrentHashMap<String, MutableList<Cookie>>()
+internal suspend fun <T> withCancellableStalkerCall(
+ call: Call,
+ block: suspend (Response) -> T
+): T = coroutineScope {
+ suspendCancellableCoroutine { continuation ->
+ continuation.invokeOnCancellation { call.cancel() }
+ call.enqueue(object : Callback {
+ override fun onFailure(call: Call, e: IOException) {
+ if (continuation.isActive) continuation.resumeWithException(e)
+ }
+
+ override fun onResponse(call: Call, response: Response) {
+ if (!continuation.isActive) {
+ response.close()
+ return
+ }
+ launch {
+ try {
+ val result = response.use { received -> block(received) }
+ if (continuation.isActive) continuation.resume(result)
+ } catch (error: Throwable) {
+ if (continuation.isActive) continuation.resumeWithException(error)
+ }
+ }
+ }
+ })
+ }
+}
+
+internal class InMemoryStalkerCookieJar : CookieJar {
+ private val store = ConcurrentHashMap<String, List<Cookie>>()
override fun saveFromResponse(url: HttpUrl, cookies: List<Cookie>) {
if (cookies.isEmpty()) return
val key = url.topPrivateDomain() ?: url.host
- val existing = store.getOrPut(key) { mutableListOf() }
- cookies.forEach { incoming ->
- existing.removeAll { current ->
- current.name == incoming.name &&
- current.domain == incoming.domain &&
- current.path == incoming.path
+ val now = System.currentTimeMillis()
+ store.compute(key) { _, current ->
+ val updated = current.orEmpty().filterTo(mutableListOf()) { existing ->
+ cookies.none { incoming ->
+ existing.name == incoming.name &&
+ existing.domain == incoming.domain &&
+ existing.path == incoming.path
+ } && existing.expiresAt > now
}
- if (!incoming.expiresAt.let { it > 0L } || incoming.expiresAt > System.currentTimeMillis()) {
- existing += incoming
+ cookies.forEach { incoming ->
+ if (incoming.expiresAt > now) updated += incoming
}
+ updated.takeIf { it.isNotEmpty() }
}
}
override fun loadForRequest(url: HttpUrl): List<Cookie> {
val key = url.topPrivateDomain() ?: url.host
- val existing = store[key].orEmpty()
val now = System.currentTimeMillis()
- val valid = existing.filter { cookie -> cookie.expiresAt > now && cookie.matches(url) }
- if (valid.size != existing.size) {
- store[key] = valid.toMutableList()
- }
- return valid
+ val current = store.computeIfPresent(key) { _, existing ->
+ existing.filter { cookie -> cookie.expiresAt > now }.takeIf { it.isNotEmpty() }
+ }.orEmpty()
+ return current.filter { cookie -> cookie.matches(url) }
}
fun cookieHeaderFor(url: String): String {
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiError.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiError.kt
new file mode 100644
index 00000000..3713cbad
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiError.kt
@@ -0,0 +1,132 @@
+package com.streamvault.data.remote.stalker
+
+import java.io.IOException
+import com.streamvault.domain.model.StalkerTransportChallenge
+
+sealed class StalkerApiError(
+ message: String,
+ cause: Throwable? = null,
+ open val httpStatus: Int? = null,
+ open val portalReason: String? = null,
+ open val retryAfterMillis: Long? = null
+) : IOException(message, cause) {
+ open class Authorization(
+ message: String = "Portal authorization failed.",
+ cause: Throwable? = null,
+ override val httpStatus: Int? = null,
+ override val portalReason: String? = null
+ ) : StalkerApiError(message, cause, httpStatus = httpStatus, portalReason = portalReason)
+
+ class PartialAuthorization(
+ message: String = "Portal accepted the device profile but denied catalog access.",
+ cause: Throwable? = null,
+ reason: String? = null
+ ) : Authorization(message, cause = cause, portalReason = reason)
+
+ class InvalidMac(message: String, reason: String? = null) :
+ Authorization(message, portalReason = reason)
+
+ class TokenRejected(message: String, reason: String? = null) :
+ Authorization(message, portalReason = reason)
+
+ /**
+ * The portal knows this MAC but has a different device identity (device_id/signature)
+ * bound to it. Retrying with another recipe or endpoint cannot help; the user must
+ * supply the registered device identity or ask the provider to unbind the device.
+ */
+ class DeviceConflict(message: String, reason: String? = null) :
+ Authorization(message, portalReason = reason)
+
+ /**
+ * The portal answered with the Ministra `status:2` envelope: the device is not
+ * registered/provisioned and must authenticate through the portal launcher first.
+ */
+ class DeviceNotRegistered(message: String, reason: String? = null) :
+ Authorization(message, portalReason = reason)
+
+ /**
+ * The portal rejected the profile because the device clock is outside its tolerance.
+ * Retrying is pointless until the device date/time is corrected.
+ */
+ class ClockSkew(message: String, reason: String? = null) :
+ Authorization(message, portalReason = reason)
+
+ class ModelRejected(message: String, override val portalReason: String? = null) :
+ StalkerApiError(message, portalReason = portalReason)
+
+ class AccountBlocked(message: String, override val portalReason: String? = null) :
+ StalkerApiError(message, portalReason = portalReason)
+
+ class RateLimited(
+ message: String = "Portal rate limit reached.",
+ override val httpStatus: Int? = 429,
+ override val retryAfterMillis: Long? = null
+ ) : StalkerApiError(message, httpStatus = httpStatus, retryAfterMillis = retryAfterMillis)
+
+ class Server(
+ message: String,
+ override val httpStatus: Int? = null,
+ override val portalReason: String? = null
+ ) : StalkerApiError(message, httpStatus = httpStatus, portalReason = portalReason)
+
+ class Transport(message: String, cause: Throwable? = null) : StalkerApiError(message, cause)
+ class TransportConsentRequired(
+ val challenge: StalkerTransportChallenge
+ ) : StalkerApiError("Transport consent is required for ${challenge.displayHost}.")
+ class Malformed(message: String, cause: Throwable? = null) : StalkerApiError(message, cause)
+ class ResponseTooLarge(message: String) : StalkerApiError(message)
+ class DiscoveryBudgetExceeded(message: String) : StalkerApiError(message)
+ class ReadinessInconclusive(
+ val evidenceCode: String,
+ cause: Throwable
+ ) : StalkerApiError(
+ "Authentication succeeded, but Live TV readiness could not be verified.",
+ cause
+ )
+ class CatalogTruncated(
+ val advertisedTotalPages: Int,
+ val pageLimit: Int,
+ message: String = "Portal catalog exceeds the $pageLimit-page aggregate safety limit."
+ ) : StalkerApiError(message)
+ class BlockedOrConfiguration(message: String, override val portalReason: String? = null) :
+ StalkerApiError(message, portalReason = portalReason)
+}
+
+internal fun Throwable.isStalkerAuthorizationFailure(): Boolean {
+ if (this is StalkerApiError.Authorization) return true
+ val value = generateSequence(this) { it.cause }
+ .mapNotNull { it.message }
+ .joinToString(" ")
+ .lowercase()
+ return listOf(
+ "authorization failed",
+ "not_valid_token",
+ "invalid token",
+ "empty token",
+ "unauthorized",
+ "not valid mac",
+ "invalid mac",
+ "access denied",
+ "permission denied",
+ "http 401",
+ "http 403"
+ ).any(value::contains)
+}
+
+internal fun isStalkerAuthorizationFailure(message: String, error: Throwable?): Boolean {
+ if (error?.isStalkerAuthorizationFailure() == true) return true
+ val normalized = message.lowercase()
+ return listOf(
+ "authorization failed",
+ "not_valid_token",
+ "invalid token",
+ "empty token",
+ "unauthorized",
+ "not valid mac",
+ "invalid mac",
+ "access denied",
+ "permission denied",
+ "http 401",
+ "http 403"
+ ).any(normalized::contains)
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt
index 98d626ec..78d453f2 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerApiService.kt
@@ -9,6 +9,14 @@ import com.streamvault.domain.model.StalkerMagPreset
import com.streamvault.domain.model.StalkerPlaybackBackendHint
import com.streamvault.domain.model.StalkerPortalFingerprint
import com.streamvault.domain.model.StalkerPortalProfile
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProfileVerification
+import com.streamvault.domain.model.StalkerProtocolFamily
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.DiscoveryBudget
+import java.util.concurrent.atomic.AtomicBoolean
+import java.util.concurrent.atomic.AtomicInteger
data class StalkerDeviceProfile(
val portalUrl: String,
@@ -35,13 +43,68 @@ data class StalkerDeviceProfile(
val httpUserAgent: String = "",
val httpHeaders: String = "",
val headerOverrides: Map<String, String?> = emptyMap(),
- val advancedOptions: StalkerAdvancedOptions = StalkerAdvancedOptions()
+ val advancedOptions: StalkerAdvancedOptions = StalkerAdvancedOptions(),
+ val providerId: Long = 0L,
+ val protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ val transportGrant: StalkerTransportGrant? = null,
+ val requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
+ val compatibilityProfileId: String = StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC,
+ val requireCatalogValidation: Boolean = false,
+ /** Broad profile/endpoint discovery is reserved for explicit Add/Edit/Connect operations. */
+ val allowCompatibilityDiscovery: Boolean = true,
+ val discoveryBudget: DiscoveryBudget = DiscoveryBudget(),
+ val discoveryRuntime: StalkerDiscoveryRuntime = StalkerDiscoveryRuntime(discoveryBudget),
+ val onProgress: ((String) -> Unit)? = null
)
+class StalkerDiscoveryRuntime(
+ private val budget: DiscoveryBudget
+) {
+ private val active = AtomicBoolean(false)
+ private val requests = AtomicInteger(0)
+ @Volatile private var startedAtNanos: Long = 0L
+
+ fun begin() {
+ requests.set(0)
+ startedAtNanos = System.nanoTime()
+ active.set(true)
+ }
+
+ fun end() {
+ active.set(false)
+ }
+
+ fun consumeRequest() {
+ if (!active.get()) return
+ val request = requests.incrementAndGet()
+ if (request > budget.maxRequests) {
+ throw StalkerApiError.DiscoveryBudgetExceeded(
+ "Portal discovery stopped after ${budget.maxRequests} network requests."
+ )
+ }
+ val elapsedMillis = (System.nanoTime() - startedAtNanos) / 1_000_000L
+ if (elapsedMillis > budget.maxElapsedMillis) {
+ throw StalkerApiError.DiscoveryBudgetExceeded(
+ "Portal discovery stopped after ${budget.maxElapsedMillis / 1_000L} seconds."
+ )
+ }
+ }
+
+ val requestCount: Int
+ get() = requests.get()
+
+ fun remainingMillis(): Long {
+ if (!active.get()) return Long.MAX_VALUE
+ val elapsedMillis = (System.nanoTime() - startedAtNanos) / 1_000_000L
+ return (budget.maxElapsedMillis - elapsedMillis).coerceAtLeast(1L)
+ }
+}
+
data class StalkerSession(
val loadUrl: String,
val portalReferer: String,
val token: String,
+ val sessionScopeKey: String = "",
val serverCookieHeader: String = "",
val effectiveAuthMode: StalkerAuthMode = StalkerAuthMode.AUTO,
val portalProfile: StalkerPortalProfile = StalkerPortalProfile.MAG_BASIC,
@@ -51,7 +114,8 @@ data class StalkerSession(
val fingerprintEvidence: StalkerFingerprintEvidence = StalkerFingerprintEvidence(),
val bootstrapEvidence: List<String> = emptyList(),
val recipeEvidence: List<String> = emptyList(),
- val rediscoveryAttempted: Boolean = false
+ val rediscoveryAttempted: Boolean = false,
+ val compatibilityProfileId: String = StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC
)
data class StalkerFingerprintEvidence(
@@ -77,6 +141,8 @@ data class StalkerProviderProfile(
val expirationDate: Long? = null,
val statusLabel: String? = null,
val authAccess: Boolean? = null,
+ /** Model reported by the portal for the bound account, when middleware exposes it. */
+ val reportedStbType: String? = null,
val moduleNames: List<String> = emptyList(),
val bootstrapStrategy: StalkerBootstrapStrategy = StalkerBootstrapStrategy.AUTO,
val effectiveAuthMode: StalkerAuthMode = StalkerAuthMode.AUTO,
@@ -93,13 +159,18 @@ data class StalkerProviderProfile(
val strictFingerprintRequired: Boolean = false,
val fallbackRecipeUsed: Boolean = false,
val rediscoveryAttempted: Boolean = false,
- val ambiguousState: Boolean = false
+ val ambiguousState: Boolean = false,
+ val compatibilityProfileId: String = StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC,
+ val profileRevision: Int = StalkerCompatibilityRegistry.REVISION,
+ val profileVerification: StalkerProfileVerification = StalkerProfileVerification.UNVERIFIED,
+ val protocolFamily: StalkerProtocolFamily = StalkerProtocolFamily.CLASSIC_MAG
)
data class StalkerCategoryRecord(
val id: String,
val name: String,
- val alias: String? = null
+ val alias: String? = null,
+ val advertisedItemCount: Int? = null
)
data class StalkerItemRecord(
@@ -144,9 +215,13 @@ data class StalkerPagedItems(
val items: List<StalkerItemRecord>,
val page: Int,
val totalPages: Int,
- val pageSize: Int
+ val pageSize: Int,
+ val advertisedTotalItems: Int? = null,
+ val advertisedTotalPages: Int? = null,
+ val isTruncated: Boolean = false,
+ val terminationReason: String? = null
) {
- val isComplete: Boolean get() = page >= totalPages
+ val isComplete: Boolean get() = !isTruncated && page >= totalPages
}
data class StalkerSeriesDetails(
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerCompatibilityRegistry.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerCompatibilityRegistry.kt
new file mode 100644
index 00000000..d31747c1
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerCompatibilityRegistry.kt
@@ -0,0 +1,161 @@
+package com.streamvault.data.remote.stalker
+
+import com.streamvault.domain.model.StalkerBootstrapRecipe
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerMagPreset
+import com.streamvault.domain.model.StalkerProfileVerification
+import com.streamvault.domain.model.StalkerProtocolFamily
+import java.util.Locale
+
+enum class StalkerBrowserEngine { QT_WEBKIT, EKIOH, ANDROID }
+enum class StalkerIdentityStrategy { MAC_ONLY, MANUAL_FIELDS_REQUIRED, API_V3_CREDENTIALS }
+
+/**
+ * A registry entry is an indivisible portal fingerprint. Experimental siblings intentionally
+ * inherit a captured family fingerprint as a unit; individual firmware/metrics fields are never
+ * mixed. They remain manual-only until a trace fixture promotes them to VERIFIED.
+ */
+data class StalkerCompatibilityProfile(
+ val id: String,
+ val revision: Int,
+ val displayName: String,
+ val generation: String,
+ val model: String,
+ val aliases: Set<String>,
+ val protocolFamily: StalkerProtocolFamily,
+ val verification: StalkerProfileVerification,
+ val browserEngine: StalkerBrowserEngine,
+ val identityStrategy: StalkerIdentityStrategy,
+ val automaticRepresentative: Boolean,
+ val baseFingerprintId: String? = null,
+ val preset: StalkerMagPreset? = null,
+ val bootstrapRecipe: StalkerBootstrapRecipe? = null
+)
+
+object StalkerCompatibilityRegistry {
+ const val REVISION = 1
+ const val MAX_AUTOMATIC_ATTEMPTS = 6
+
+ private fun verified(
+ id: String,
+ name: String,
+ generation: String,
+ model: String,
+ aliases: Set<String>,
+ preset: StalkerMagPreset,
+ recipe: StalkerBootstrapRecipe,
+ automatic: Boolean = true
+ ) = StalkerCompatibilityProfile(
+ id, REVISION, name, generation, model, aliases,
+ StalkerProtocolFamily.CLASSIC_MAG, StalkerProfileVerification.VERIFIED,
+ StalkerBrowserEngine.QT_WEBKIT, StalkerIdentityStrategy.MAC_ONLY,
+ automatic, preset = preset, bootstrapRecipe = recipe
+ )
+
+ private fun experimental(
+ model: String,
+ generation: String,
+ base: String,
+ aliases: Set<String> = emptySet(),
+ engine: StalkerBrowserEngine = StalkerBrowserEngine.QT_WEBKIT
+ ) = StalkerCompatibilityProfile(
+ id = "classic.${model.lowercase()}",
+ revision = REVISION,
+ displayName = model,
+ generation = generation,
+ model = model,
+ aliases = aliases,
+ protocolFamily = StalkerProtocolFamily.CLASSIC_MAG,
+ verification = StalkerProfileVerification.EXPERIMENTAL,
+ browserEngine = engine,
+ identityStrategy = StalkerIdentityStrategy.MANUAL_FIELDS_REQUIRED,
+ automaticRepresentative = false,
+ baseFingerprintId = base
+ )
+
+ private fun android(model: String, aliases: Set<String> = emptySet()) = StalkerCompatibilityProfile(
+ id = "api-v3.${model.lowercase()}",
+ revision = REVISION,
+ displayName = "$model (Ministra API v3)",
+ generation = "Android MAG",
+ model = model,
+ aliases = aliases,
+ protocolFamily = StalkerProtocolFamily.MINISTRA_API_V3,
+ verification = StalkerProfileVerification.EXPERIMENTAL,
+ browserEngine = StalkerBrowserEngine.ANDROID,
+ identityStrategy = StalkerIdentityStrategy.API_V3_CREDENTIALS,
+ automaticRepresentative = false
+ )
+
+ val profiles: List<StalkerCompatibilityProfile> = listOf(
+ verified(StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC, "MAG250 (Generic)", "MAG2xx", "MAG250", setOf("MAG245"), StalkerMagPreset.GENERIC_SAFE, StalkerBootstrapRecipe.GENERIC_SAFE),
+ verified(StalkerCompatibilityProfileIds.CLASSIC_MAG250_LEGACY, "MAG250 (Legacy)", "MAG2xx", "MAG250", setOf("MAG245"), StalkerMagPreset.MAG250_LEGACY, StalkerBootstrapRecipe.LEGACY_MAG),
+ verified(StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT, "MAG254 (Strict)", "MAG2xx", "MAG254", setOf("MAG255"), StalkerMagPreset.MAG254_STRICT, StalkerBootstrapRecipe.STRICT_MAG),
+ verified(StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN, "MAG322 (Modern)", "MAG3xx", "MAG322", setOf("MAG323"), StalkerMagPreset.MINISTRA_MODERN, StalkerBootstrapRecipe.LOCALIZATION_STRICT),
+
+ experimental("MAG200", "MAG2xx", StalkerCompatibilityProfileIds.CLASSIC_MAG250_LEGACY),
+ experimental("MAG245", "MAG2xx", StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC),
+ experimental("MAG255", "MAG2xx", StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT),
+ experimental("MAG256", "MAG2xx", StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT, setOf("MAG257")),
+ experimental("MAG257", "MAG2xx", StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT),
+ experimental("MAG270", "MAG2xx", StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT, setOf("MAG275")),
+ experimental("MAG275", "MAG2xx", StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT),
+ experimental("MAG323", "MAG3xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN),
+ experimental("MAG324", "MAG3xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN, setOf("MAG325")),
+ experimental("MAG325", "MAG3xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN),
+ experimental("MAG349", "MAG3xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN, setOf("MAG351")),
+ experimental("MAG351", "MAG3xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN),
+ experimental("MAG420", "MAG4xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN, setOf("MAG424")),
+ experimental("MAG424", "MAG4xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN),
+ experimental("MAG520", "MAG5xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN, setOf("MAG522", "MAG524")),
+ experimental("MAG522", "MAG5xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN),
+ experimental("MAG524", "MAG5xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN),
+ experimental("MAG540", "MAG5xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN, setOf("MAG544")),
+ experimental("MAG544", "MAG5xx", StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN),
+ experimental("MAG250-EKIOH", "MAG2xx Ekioh", StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC, engine = StalkerBrowserEngine.EKIOH),
+ experimental("MAG255-EKIOH", "MAG2xx Ekioh", StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT, engine = StalkerBrowserEngine.EKIOH),
+
+ android("MAG260"), android("MAG410"), android("MAG424A"), android("MAG425A"), android("MAG500A")
+ )
+
+ private val byId = profiles.associateBy { it.id }
+
+ fun find(id: String?): StalkerCompatibilityProfile? = id?.trim()?.let(byId::get)
+
+ fun findVerifiedByModelSignal(value: String?): StalkerCompatibilityProfile? {
+ val normalized = value?.normalizeModelSignal()?.takeIf { it.isNotBlank() } ?: return null
+ return profiles
+ .asSequence()
+ .filter {
+ it.protocolFamily == StalkerProtocolFamily.CLASSIC_MAG &&
+ it.verification == StalkerProfileVerification.VERIFIED
+ }
+ .firstOrNull { profile ->
+ profile.model.normalizeModelSignal() == normalized ||
+ profile.aliases.any { alias -> alias.normalizeModelSignal() == normalized }
+ }
+ }
+
+ fun baseFingerprint(profile: StalkerCompatibilityProfile): StalkerCompatibilityProfile =
+ profile.baseFingerprintId?.let(byId::get) ?: profile
+
+ fun idForLegacyPreset(preset: StalkerMagPreset): String = when (preset) {
+ StalkerMagPreset.GENERIC_SAFE -> StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC
+ StalkerMagPreset.MAG250_LEGACY -> StalkerCompatibilityProfileIds.CLASSIC_MAG250_LEGACY
+ StalkerMagPreset.MAG254_STRICT -> StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT
+ StalkerMagPreset.MINISTRA_MODERN -> StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN
+ }
+
+ fun classicAutomaticOrder(preferredId: String?): List<StalkerCompatibilityProfile> = buildList {
+ find(preferredId)?.takeIf { it.protocolFamily == StalkerProtocolFamily.CLASSIC_MAG }?.let(::add)
+ listOf(
+ StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC,
+ StalkerCompatibilityProfileIds.CLASSIC_MAG250_LEGACY,
+ StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT,
+ StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN
+ ).mapNotNull(::find).forEach(::add)
+ }.distinctBy { it.id }.take(MAX_AUTOMATIC_ATTEMPTS)
+
+ private fun String.normalizeModelSignal(): String =
+ trim().uppercase(Locale.ROOT).filter(Char::isLetterOrDigit)
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerDiscoveryCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerDiscoveryCoordinator.kt
new file mode 100644
index 00000000..5ec91d9b
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerDiscoveryCoordinator.kt
@@ -0,0 +1,45 @@
+package com.streamvault.data.remote.stalker
+
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.StalkerDiscoveryProgress
+import com.streamvault.domain.model.StalkerDiscoveryStage
+
+/**
+ * Foreground boundary for bounded classic-MAG discovery.
+ *
+ * The RPC service still owns wire decoding and compatibility recipes; callers no longer need to
+ * know that authentication also performs the Live readiness gate. This boundary is intentionally
+ * small so endpoint planning can continue moving out of [OkHttpStalkerApiService] incrementally.
+ */
+class StalkerDiscoveryCoordinator(
+ private val api: StalkerApiService
+) {
+ suspend fun authenticate(
+ profile: StalkerDeviceProfile,
+ onProgress: ((StalkerDiscoveryProgress) -> Unit)? = null
+ ): Result<Pair<StalkerSession, StalkerProviderProfile>> {
+ val startedAt = System.currentTimeMillis()
+ onProgress?.invoke(
+ StalkerDiscoveryProgress(
+ stage = StalkerDiscoveryStage.AUTHENTICATION,
+ attempt = 1,
+ limit = profile.discoveryBudget.maxRequests,
+ elapsedMillis = 0L
+ )
+ )
+ val result = api.authenticate(profile)
+ onProgress?.invoke(
+ StalkerDiscoveryProgress(
+ stage = if (result is Result.Success) {
+ StalkerDiscoveryStage.LIVE_READINESS
+ } else {
+ StalkerDiscoveryStage.AUTHENTICATION
+ },
+ attempt = profile.discoveryRuntime.requestCount,
+ limit = profile.discoveryBudget.maxRequests,
+ elapsedMillis = System.currentTimeMillis() - startedAt
+ )
+ )
+ return result
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalRecipes.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalRecipes.kt
index 7c088ce0..ca39bfa3 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalRecipes.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalRecipes.kt
@@ -15,7 +15,6 @@ internal data class StalkerMagPresetSpec(
val imageVersion: String,
val hwVersion: String,
val apiSignature: String,
- val metricsJson: String,
val localization: String,
val requireStrictIdentity: Boolean = false
)
@@ -31,7 +30,8 @@ internal data class StalkerRecipeSpec(
val endpointPreference: StalkerEndpointPreference = StalkerEndpointPreference.AUTO,
val preferLocalizationBeforeProfile: Boolean = false,
val cookieMode: StalkerCookieMode = StalkerCookieMode.NONE,
- val playbackBackendHint: StalkerPlaybackBackendHint = StalkerPlaybackBackendHint.AUTO
+ val playbackBackendHint: StalkerPlaybackBackendHint = StalkerPlaybackBackendHint.AUTO,
+ val compatibilityProfileId: String = StalkerCompatibilityRegistry.idForLegacyPreset(magPreset)
)
internal fun stalkerMagPresetSpec(preset: StalkerMagPreset): StalkerMagPresetSpec = when (preset) {
@@ -41,7 +41,6 @@ internal fun stalkerMagPresetSpec(preset: StalkerMagPreset): StalkerMagPresetSpe
imageVersion = "218",
hwVersion = "1.7-BD-00",
apiSignature = "262",
- metricsJson = "{}",
localization = "en_US.utf8"
)
@@ -51,17 +50,15 @@ internal fun stalkerMagPresetSpec(preset: StalkerMagPreset): StalkerMagPresetSpe
imageVersion = "216",
hwVersion = "1.7-BD-00",
apiSignature = "254",
- metricsJson = """{"mac":"legacy","sn":"legacy"}""",
localization = "en_GB.utf8"
)
StalkerMagPreset.MAG254_STRICT -> StalkerMagPresetSpec(
defaultDeviceProfile = "MAG254",
versionString = "ImageDescription: 0.2.18-r23-254; ImageDate: Thu Nov 1 11:14:12 EET 2018; PORTAL version: 5.6.8; API Version: JS API version: 343; STB API version: 146; Player Engine version: 0x58c",
- imageVersion = "254",
+ imageVersion = "218",
hwVersion = "2.6-IB-00",
apiSignature = "263",
- metricsJson = """{"hw":"strict","video_out":"hdmi"}""",
localization = "en_US.utf8",
requireStrictIdentity = true
)
@@ -72,7 +69,6 @@ internal fun stalkerMagPresetSpec(preset: StalkerMagPreset): StalkerMagPresetSpe
imageVersion = "221",
hwVersion = "2.6-IB-00",
apiSignature = "270",
- metricsJson = """{"platform":"ministra","video_out":"hdmi","num_banks":2}""",
localization = "en_US.utf8",
requireStrictIdentity = true
)
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt
new file mode 100644
index 00000000..d4c4c166
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerPortalStateStore.kt
@@ -0,0 +1,238 @@
+package com.streamvault.data.remote.stalker
+
+import com.streamvault.data.local.dao.StalkerPortalStateDao
+import com.streamvault.data.local.entity.StalkerPortalStateEntity
+import com.streamvault.domain.model.ContentType
+import java.security.MessageDigest
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.serialization.encodeToString
+import kotlinx.serialization.json.Json
+
+@Singleton
+class StalkerPortalStateStore @Inject constructor(
+ private val dao: StalkerPortalStateDao
+) {
+ private val json = Json { ignoreUnknownKeys = true }
+
+ suspend fun getValidated(providerId: Long, now: Long = System.currentTimeMillis()): StalkerPortalStateEntity? =
+ dao.get(providerId)?.takeIf { state ->
+ state.validatedAt > 0L && now - state.validatedAt <= VALIDATION_TTL_MILLIS
+ }
+
+ suspend fun get(providerId: Long): StalkerPortalStateEntity? = dao.get(providerId)
+
+ suspend fun recordAuthentication(
+ providerId: Long,
+ session: StalkerSession,
+ profile: StalkerProviderProfile,
+ now: Long = System.currentTimeMillis()
+ ) {
+ if (providerId <= 0L) return
+ val existing = dao.get(providerId)
+ dao.upsert(
+ (existing ?: StalkerPortalStateEntity(providerId)).copy(
+ workingEndpoint = session.loadUrl,
+ bootstrapRecipe = profile.bootstrapRecipe.name,
+ epgSupported = true.takeIf { profile.moduleNames.any { module ->
+ module.contains("epg", ignoreCase = true) || module.contains("itv", ignoreCase = true)
+ } } ?: existing?.epgSupported,
+ endpointHealthJson = clearHealthFailures(
+ existing?.endpointHealthJson,
+ endpointKey(session.loadUrl),
+ recipeKey(profile.bootstrapRecipe.name)
+ ),
+ endpointFailedUntil = 0L,
+ validatedAt = now
+ )
+ )
+ StalkerTelemetry.capabilityChanged(providerId, "AUTH_RECIPE", "VALIDATED")
+ }
+
+ suspend fun recordBulkLive(
+ providerId: Long,
+ supported: Boolean,
+ categoryFidelity: Boolean? = null,
+ now: Long = System.currentTimeMillis()
+ ) = update(providerId) { state ->
+ state.copy(
+ bulkLiveSupported = supported,
+ bulkLiveCategoryFidelity = categoryFidelity ?: state.bulkLiveCategoryFidelity,
+ validatedAt = now
+ )
+ }.also {
+ StalkerTelemetry.capabilityChanged(providerId, "BULK_LIVE", if (supported) "SUPPORTED" else "UNSUPPORTED")
+ }
+
+ suspend fun recordWildcard(
+ providerId: Long,
+ contentType: ContentType,
+ supported: Boolean,
+ now: Long = System.currentTimeMillis()
+ ) = update(providerId) { state ->
+ when (contentType) {
+ ContentType.MOVIE -> state.copy(movieWildcardSupported = supported, validatedAt = now)
+ ContentType.SERIES -> state.copy(seriesWildcardSupported = supported, validatedAt = now)
+ else -> state
+ }
+ }.also {
+ StalkerTelemetry.capabilityChanged(
+ providerId,
+ "${contentType.name}_WILDCARD",
+ if (supported) "SUPPORTED" else "UNSUPPORTED"
+ )
+ }
+
+ suspend fun recordEpg(
+ providerId: Long,
+ supported: Boolean,
+ now: Long = System.currentTimeMillis()
+ ) = update(providerId) { state ->
+ state.copy(epgSupported = supported, validatedAt = now)
+ }.also {
+ StalkerTelemetry.capabilityChanged(providerId, "EPG", if (supported) "SUPPORTED" else "UNSUPPORTED")
+ }
+
+ suspend fun recordStressCooldown(
+ providerId: Long,
+ cooldownUntil: Long,
+ now: Long = System.currentTimeMillis()
+ ) = update(providerId) { state ->
+ state.copy(
+ safeMetadataConcurrency = 1,
+ stressCooldownUntil = cooldownUntil.coerceAtLeast(now),
+ validatedAt = state.validatedAt.takeIf { it > 0L } ?: now
+ )
+ }.also {
+ StalkerTelemetry.capabilityChanged(providerId, "METADATA_CONCURRENCY", "DOWNGRADED")
+ }
+
+ suspend fun recordHealthyMetadataProbe(
+ providerId: Long,
+ now: Long = System.currentTimeMillis()
+ ) {
+ val state = dao.get(providerId) ?: return
+ if (state.safeMetadataConcurrency == 1 && state.stressCooldownUntil in 1..now) {
+ dao.upsert(state.copy(safeMetadataConcurrency = 2, stressCooldownUntil = 0L))
+ StalkerTelemetry.capabilityChanged(providerId, "METADATA_CONCURRENCY", "RESTORED")
+ }
+ }
+
+ suspend fun markEndpointUnhealthy(
+ providerId: Long,
+ endpoint: String,
+ now: Long = System.currentTimeMillis()
+ ) {
+ if (providerId <= 0L || endpoint.isBlank()) return
+ val until = now + ENDPOINT_COOLDOWN_MILLIS
+ update(providerId) { state ->
+ val health = decodeEndpointHealth(state.endpointHealthJson)
+ .filterValues { expiry -> expiry > now }
+ .toMutableMap()
+ health[endpointKey(endpoint)] = until
+ val bounded = health.entries.sortedByDescending { it.value }.take(MAX_ENDPOINT_HEALTH_ENTRIES)
+ .associate { it.key to it.value }
+ state.copy(
+ endpointHealthJson = json.encodeToString(bounded),
+ endpointFailedUntil = bounded.values.maxOrNull() ?: 0L
+ )
+ }
+ StalkerTelemetry.capabilityChanged(providerId, "ENDPOINT", "COOLDOWN")
+ }
+
+ fun isEndpointHealthy(
+ state: StalkerPortalStateEntity,
+ endpoint: String,
+ now: Long = System.currentTimeMillis()
+ ): Boolean = decodeEndpointHealth(state.endpointHealthJson)[endpointKey(endpoint)]?.let { it <= now } ?: true
+
+ suspend fun markRecipeUnhealthy(
+ providerId: Long,
+ recipe: String,
+ now: Long = System.currentTimeMillis()
+ ) {
+ if (providerId <= 0L || recipe.isBlank()) return
+ val until = now + RECIPE_COOLDOWN_MILLIS
+ update(providerId) { state ->
+ val health = decodeEndpointHealth(state.endpointHealthJson)
+ .filterValues { expiry -> expiry > now }
+ .toMutableMap()
+ health[recipeKey(recipe)] = until
+ state.copy(
+ endpointHealthJson = json.encodeToString(
+ health.entries.sortedByDescending { it.value }.take(MAX_ENDPOINT_HEALTH_ENTRIES)
+ .associate { it.key to it.value }
+ )
+ )
+ }
+ StalkerTelemetry.capabilityChanged(providerId, "AUTH_RECIPE", "COOLDOWN")
+ }
+
+ fun isRecipeHealthy(
+ state: StalkerPortalStateEntity,
+ recipe: String,
+ now: Long = System.currentTimeMillis()
+ ): Boolean = decodeEndpointHealth(state.endpointHealthJson)[recipeKey(recipe)]?.let { it <= now } ?: true
+
+ suspend fun invalidateAuthentication(providerId: Long) = update(providerId) { state ->
+ state.copy(workingEndpoint = null, bootstrapRecipe = null, validatedAt = 0L)
+ }
+
+ suspend fun invalidateCapabilities(providerId: Long) = update(providerId) { state ->
+ state.copy(
+ bulkLiveSupported = null,
+ bulkLiveCategoryFidelity = null,
+ movieWildcardSupported = null,
+ seriesWildcardSupported = null,
+ epgSupported = null,
+ validatedAt = 0L
+ )
+ }
+
+ suspend fun invalidate(providerId: Long) {
+ if (providerId > 0L) dao.invalidate(providerId)
+ }
+
+ suspend fun restore(providerId: Long, state: StalkerPortalStateEntity?) {
+ if (providerId <= 0L) return
+ if (state == null) {
+ dao.invalidate(providerId)
+ } else {
+ dao.upsert(state.copy(providerId = providerId))
+ }
+ }
+
+ private suspend fun update(
+ providerId: Long,
+ transform: (StalkerPortalStateEntity) -> StalkerPortalStateEntity
+ ) {
+ if (providerId <= 0L) return
+ dao.upsert(transform(dao.get(providerId) ?: StalkerPortalStateEntity(providerId)))
+ }
+
+ private fun clearHealthFailures(jsonValue: String?, vararg keys: String): String {
+ val health = decodeEndpointHealth(jsonValue).toMutableMap()
+ keys.forEach(health::remove)
+ return json.encodeToString(health)
+ }
+
+ private fun decodeEndpointHealth(value: String?): Map<String, Long> = runCatching {
+ json.decodeFromString<Map<String, Long>>(value.orEmpty().ifBlank { "{}" })
+ }.getOrDefault(emptyMap())
+
+ private fun endpointKey(endpoint: String): String = healthKey("endpoint", StalkerUrlFactory.normalizePortalUrl(endpoint))
+
+ private fun recipeKey(recipe: String): String = healthKey("recipe", recipe.uppercase())
+
+ private fun healthKey(kind: String, value: String): String = MessageDigest.getInstance("SHA-256")
+ .digest("$kind:$value".toByteArray(Charsets.UTF_8))
+ .take(12)
+ .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
+
+ private companion object {
+ const val VALIDATION_TTL_MILLIS = 7L * 24L * 60L * 60L * 1000L
+ const val ENDPOINT_COOLDOWN_MILLIS = 10L * 60L * 1000L
+ const val RECIPE_COOLDOWN_MILLIS = 10L * 60L * 1000L
+ const val MAX_ENDPOINT_HEALTH_ENTRIES = 8
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
index 153d6041..3205a3b9 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerProvider.kt
@@ -8,6 +8,8 @@ import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Episode
import com.streamvault.domain.model.Movie
+import com.streamvault.domain.model.PlaybackTransportMode
+import com.streamvault.domain.model.PlaybackTransportPolicy
import com.streamvault.domain.model.Program
import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderStatus
@@ -23,11 +25,20 @@ import com.streamvault.domain.model.StalkerMagPreset
import com.streamvault.domain.model.StalkerPlaybackBackendHint
import com.streamvault.domain.model.StalkerPortalFingerprint
import com.streamvault.domain.model.StalkerPortalProfile
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportChallenge
+import com.streamvault.domain.model.StalkerTransportChallengeReason
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
import com.streamvault.domain.provider.IptvProvider
import com.streamvault.domain.util.ChannelNormalizer
+import com.streamvault.data.remote.xtream.extractStreamExpirationTime
import java.io.IOException
import java.net.URI
import java.net.URLEncoder
+import java.security.MessageDigest
import java.util.Base64
import java.util.Locale
import java.util.concurrent.ConcurrentHashMap
@@ -38,6 +49,7 @@ data class StalkerPlaybackInfo(
val url: String,
val headers: Map<String, String> = emptyMap(),
val userAgent: String? = null,
+ val transportPolicy: PlaybackTransportPolicy? = null,
val allowInvalidSsl: Boolean = false,
val proxyHost: String = "",
val proxyPort: Int? = null,
@@ -51,9 +63,13 @@ data class StalkerPagedResult<T>(
val items: List<T>,
val page: Int,
val totalPages: Int,
- val pageSize: Int
+ val pageSize: Int,
+ val advertisedTotalItems: Int? = null,
+ val advertisedTotalPages: Int? = null,
+ val isTruncated: Boolean = false,
+ val terminationReason: String? = null
) {
- val isComplete: Boolean get() = page >= totalPages
+ val isComplete: Boolean get() = !isTruncated && page >= totalPages
}
class StalkerProvider(
@@ -81,16 +97,35 @@ class StalkerProvider(
private val deviceId: String = "",
private val deviceId2: String = "",
private val signature: String = "",
- private val stalkerAdvancedOptionsJson: String = ""
+ private val stalkerAdvancedOptionsJson: String = "",
+ private val protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ private val transportGrant: StalkerTransportGrant? = null,
+ private val requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
+ private val learnedProfileId: String = "",
+ private val requireCatalogValidation: Boolean = true,
+ private val identityResolver: StalkerRemoteIdentityResolver? = null,
+ private val portalStateStore: StalkerPortalStateStore? = null,
+ private val discoveryCoordinator: StalkerDiscoveryCoordinator =
+ StalkerDiscoveryCoordinator(api),
+ private val onProgress: ((String) -> Unit)? = null
) : IptvProvider {
- internal companion object {
+internal companion object {
private const val TAG = "StalkerProvider"
private const val DEFAULT_PLAYER_USER_AGENT = "Lavf53.32.100"
+ private const val LIVE_IDENTITY_BATCH_SIZE = 500
+ private const val RESOLVED_URL_CACHE_SOFT_TTL_MILLIS = 60_000L
+ private const val RESOLVED_URL_CACHE_MIN_TTL_MILLIS = 5_000L
+ private const val RESOLVED_URL_CACHE_MAX_TTL_MILLIS = 300_000L
private val sharedAuthCache = ConcurrentHashMap<String, CachedAuth>()
+ private val resolvedStreamUrlCache = ConcurrentHashMap<String, CachedResolvedUrl>()
fun clearSharedAuthCacheForTests() {
sharedAuthCache.clear()
}
+
+ fun clearResolvedStreamUrlCacheForTests() {
+ resolvedStreamUrlCache.clear()
+ }
}
private data class CachedAuth(
@@ -98,6 +133,11 @@ class StalkerProvider(
val profile: StalkerProviderProfile
)
+ private data class CachedResolvedUrl(
+ val url: String,
+ val expiresAt: Long
+ )
+
private data class CategorySeed(
val id: Long,
val rawId: String,
@@ -108,6 +148,7 @@ class StalkerProvider(
private var sessionCache: StalkerSession? = null
private var accountProfileCache: StalkerProviderProfile? = null
private val categoryCache = mutableMapOf<ContentType, List<CategorySeed>>()
+ private val remoteIdentityCache = ConcurrentHashMap<Pair<ContentType, String>, Long>()
suspend fun invalidateAuthentication() {
authMutex.withLock {
@@ -115,9 +156,38 @@ class StalkerProvider(
accountProfileCache = null
categoryCache.clear()
sharedAuthCache.remove(authCacheKey())
+ clearResolvedStreamUrlCache()
}
}
+ private fun resolvedStreamUrlCacheKey(kind: StalkerStreamKind, cmd: String): String =
+ "$providerId|${kind.name}|$cmd"
+
+ private fun consultResolvedStreamUrlCache(kind: StalkerStreamKind, cmd: String): String? {
+ val key = resolvedStreamUrlCacheKey(kind, cmd)
+ val entry = resolvedStreamUrlCache[key] ?: return null
+ if (System.currentTimeMillis() >= entry.expiresAt) {
+ resolvedStreamUrlCache.remove(key, entry)
+ return null
+ }
+ return entry.url
+ }
+
+ private fun storeResolvedStreamUrl(kind: StalkerStreamKind, cmd: String, url: String) {
+ val now = System.currentTimeMillis()
+ val expiry = extractStreamExpirationTime(url)
+ ?.takeIf { it > now }
+ ?.coerceIn(now + RESOLVED_URL_CACHE_MIN_TTL_MILLIS, now + RESOLVED_URL_CACHE_MAX_TTL_MILLIS)
+ ?: (now + RESOLVED_URL_CACHE_SOFT_TTL_MILLIS)
+ resolvedStreamUrlCache[resolvedStreamUrlCacheKey(kind, cmd)] =
+ CachedResolvedUrl(url = url, expiresAt = expiry)
+ }
+
+ private fun clearResolvedStreamUrlCache() {
+ val prefix = "$providerId|"
+ resolvedStreamUrlCache.keys.removeAll { it.startsWith(prefix) }
+ }
+
override suspend fun authenticate(): Result<Provider> {
return when (val authResult = ensureAuthenticated()) {
is Result.Success -> {
@@ -148,6 +218,12 @@ class StalkerProvider(
stalkerPortalProfile = profile.portalProfile,
stalkerPortalFingerprint = profile.portalFingerprint,
stalkerMagPreset = profile.magPreset,
+ stalkerProtocolPreference = protocolPreference,
+ stalkerRequestedProfileId = requestedProfileId,
+ stalkerLearnedProfileId = learnedCompatibilityProfileId(profile),
+ stalkerProfileRevision = profile.profileRevision,
+ stalkerProfileVerification = profile.profileVerification,
+ stalkerProtocolFamily = profile.protocolFamily,
stalkerLastBootstrapRecipe = profile.bootstrapRecipe,
stalkerEndpointPreference = profile.fingerprintEvidence.endpointPreference,
stalkerCookieMode = profile.fingerprintEvidence.cookieMode,
@@ -185,19 +261,42 @@ class StalkerProvider(
api.getLiveCategories(session, profile)
}
- override suspend fun getLiveStreams(categoryId: Long?): Result<List<Channel>> =
- mapItems(ContentType.LIVE, categoryId) { session, profile, rawCategoryId ->
+ override suspend fun getLiveStreams(categoryId: Long?): Result<List<Channel>> {
+ val result = mapItems(ContentType.LIVE, categoryId) { session, profile, rawCategoryId ->
api.getLiveStreams(session, profile, rawCategoryId)
- }.mapData { items ->
- items.mapNotNull(::toChannel)
}
+ return mapResolvedItems(ContentType.LIVE, result, ::toChannel)
+ }
+
+ internal fun validatedAuthenticationSnapshot(): Pair<StalkerSession, StalkerProviderProfile>? {
+ val session = sessionCache ?: return null
+ val profile = accountProfileCache ?: return null
+ return session to profile
+ }
suspend fun streamLiveStreams(onChannel: suspend (Channel) -> Unit): Result<Int> {
return runWithAuthorizedSession { session, _ ->
+ val pendingItems = ArrayList<StalkerItemRecord>(LIVE_IDENTITY_BATCH_SIZE)
+
+ suspend fun flushPendingItems() {
+ if (pendingItems.isEmpty()) return
+ bindRemoteIds(ContentType.LIVE, pendingItems.map(StalkerItemRecord::id))
+ pendingItems.forEach { item ->
+ toChannel(item)?.let { channel -> onChannel(channel) }
+ }
+ pendingItems.clear()
+ }
+
when (val result = api.streamLiveStreams(session, currentDeviceProfile()) { item ->
- toChannel(item)?.let { channel -> onChannel(channel) }
+ pendingItems += item
+ if (pendingItems.size >= LIVE_IDENTITY_BATCH_SIZE) {
+ flushPendingItems()
+ }
}) {
- is Result.Success -> Result.success(result.data)
+ is Result.Success -> {
+ flushPendingItems()
+ Result.success(result.data)
+ }
is Result.Error -> Result.error(result.message, result.exception)
is Result.Loading -> Result.error("Unexpected loading state")
}
@@ -209,40 +308,32 @@ class StalkerProvider(
api.getVodCategories(session, profile)
}
- override suspend fun getVodStreams(categoryId: Long?): Result<List<Movie>> =
- mapItems(ContentType.MOVIE, categoryId) { session, profile, rawCategoryId ->
+ override suspend fun getVodStreams(categoryId: Long?): Result<List<Movie>> {
+ val result = mapItems(ContentType.MOVIE, categoryId) { session, profile, rawCategoryId ->
api.getVodStreams(session, profile, rawCategoryId)
- }.mapData { items ->
- items.mapNotNull { item -> toMovie(item, requestedCategoryId = categoryId) }
}
+ return mapResolvedItems(ContentType.MOVIE, result) { item ->
+ toMovie(item, requestedCategoryId = categoryId)
+ }
+ }
suspend fun getVodStreamsPage(categoryId: Long?, page: Int): Result<StalkerPagedResult<Movie>> =
mapPagedItems(ContentType.MOVIE, categoryId) { session, profile, rawCategoryId ->
api.getVodStreamsPage(session, profile, rawCategoryId, page)
- }.mapData { paged ->
- StalkerPagedResult(
- items = paged.items.mapNotNull { item -> toMovie(item, requestedCategoryId = categoryId) },
- page = paged.page,
- totalPages = paged.totalPages,
- pageSize = paged.pageSize
- )
- }
+ }.let { result -> mapResolvedPage(ContentType.MOVIE, result) { item ->
+ toMovie(item, requestedCategoryId = categoryId)
+ } }
suspend fun getVodStreamsPageUsingItemCategories(categoryId: Long?, page: Int): Result<StalkerPagedResult<Movie>> =
mapPagedItems(ContentType.MOVIE, categoryId) { session, profile, rawCategoryId ->
api.getVodStreamsPage(session, profile, rawCategoryId, page)
- }.mapData { paged ->
- StalkerPagedResult(
- items = paged.items.mapNotNull { item -> toMovie(item, requestedCategoryId = null) },
- page = paged.page,
- totalPages = paged.totalPages,
- pageSize = paged.pageSize
- )
- }
+ }.let { result -> mapResolvedPage(ContentType.MOVIE, result) { item ->
+ toMovie(item, requestedCategoryId = null)
+ } }
override suspend fun getVodInfo(vodId: Long): Result<Movie> {
- return when (val moviesResult = getVodStreams(null)) {
- is Result.Success -> moviesResult.data
+ return when (val moviesResult = getVodStreamsPage(categoryId = null, page = 1)) {
+ is Result.Success -> moviesResult.data.items
.firstOrNull { movie ->
movie.streamId == vodId || movie.id == vodId
}?.let { movie -> Result.success(movie) }
@@ -257,24 +348,21 @@ class StalkerProvider(
api.getSeriesCategories(session, profile)
}
- override suspend fun getSeriesList(categoryId: Long?): Result<List<Series>> =
- mapItems(ContentType.SERIES, categoryId) { session, profile, rawCategoryId ->
+ override suspend fun getSeriesList(categoryId: Long?): Result<List<Series>> {
+ val result = mapItems(ContentType.SERIES, categoryId) { session, profile, rawCategoryId ->
api.getSeries(session, profile, rawCategoryId)
- }.mapData { items ->
- items.mapNotNull(::toSeries)
}
+ return mapResolvedItems(ContentType.SERIES, result) { item ->
+ toSeries(item, requestedCategoryId = categoryId)
+ }
+ }
suspend fun getSeriesListPage(categoryId: Long?, page: Int): Result<StalkerPagedResult<Series>> =
mapPagedItems(ContentType.SERIES, categoryId) { session, profile, rawCategoryId ->
api.getSeriesPage(session, profile, rawCategoryId, page)
- }.mapData { paged ->
- StalkerPagedResult(
- items = paged.items.mapNotNull(::toSeries),
- page = paged.page,
- totalPages = paged.totalPages,
- pageSize = paged.pageSize
- )
- }
+ }.let { result -> mapResolvedPage(ContentType.SERIES, result) { item ->
+ toSeries(item, requestedCategoryId = categoryId)
+ } }
suspend fun isWildcardCategory(type: ContentType, categoryId: Long): Boolean {
val normalizedType = when (type) {
@@ -285,12 +373,21 @@ class StalkerProvider(
categoryId == syntheticCategoryId(normalizedType, "*")
}
- override suspend fun getSeriesInfo(seriesId: Long): Result<Series> = getSeriesInfo(seriesId.toString())
+ override suspend fun getSeriesInfo(seriesId: Long): Result<Series> =
+ getSeriesInfo(identityResolver?.reverse(providerId, ContentType.SERIES, seriesId) ?: seriesId.toString())
suspend fun getSeriesInfo(providerSeriesId: String): Result<Series> {
return runWithAuthorizedSession { session, _ ->
when (val detailsResult = api.getSeriesDetails(session, currentDeviceProfile(), providerSeriesId)) {
- is Result.Success -> Result.success(detailsResult.data.toSeries())
+ is Result.Success -> {
+ val details = detailsResult.data
+ bindRemoteIds(ContentType.SERIES, listOf(details.series.id))
+ bindRemoteIds(
+ ContentType.SERIES_EPISODE,
+ details.seasons.flatMap { season -> season.episodes.map(StalkerEpisodeRecord::id) }
+ )
+ Result.success(details.toSeries())
+ }
is Result.Error -> Result.error(detailsResult.message, detailsResult.exception)
is Result.Loading -> Result.error("Unexpected loading state")
}
@@ -439,30 +536,21 @@ class StalkerProvider(
adapter.allowsDirectBypass(variant) &&
shouldBypassCreateLink(kind, candidate)
}
- ?.let { candidate ->
+?.let { candidate ->
Log.d(
TAG,
"Resolved direct Stalker playback provider=$providerId kind=${kind.name} mode=${adapter.adapterMode.name} " +
"candidateMode=${variant.playbackMode.name} endpoint=${effectiveArchiveEndpointPreference(kind, session).name}"
)
return Result.success(
- StalkerPlaybackInfo(
- url = candidate,
- headers = buildPlaybackHeaders(session, profile, candidate),
- userAgent = resolveDirectPlaybackUserAgent(profile),
- allowInvalidSsl = true,
- proxyHost = profile.advancedOptions.proxy?.host.orEmpty(),
- proxyPort = profile.advancedOptions.proxy?.port,
- playbackMode = adapter.adapterMode,
- endpointPreference = effectiveArchiveEndpointPreference(
- kind = kind,
- session = session
- ),
- cookieMode = derivePlaybackCookieMode(
- current = effectiveArchiveCookieMode(kind, session, candidate),
- url = candidate
- ),
- backendHint = detectPlaybackBackendHint(candidate, descriptor.capabilities, adapter)
+ buildResolvedPlaybackInfo(
+ session = session,
+ profile = profile,
+ adapter = adapter,
+ resolvedUrl = candidate,
+ kind = kind,
+ descriptor = descriptor,
+ userAgent = resolveDirectPlaybackUserAgent(profile)
)
)
}
@@ -472,6 +560,25 @@ class StalkerProvider(
return@forEach
}
+ consultResolvedStreamUrlCache(kind, variant.cmd)?.let { cachedResolvedUrl ->
+ Log.d(
+ TAG,
+ "Resolved create_link playback provider=$providerId kind=${kind.name} mode=${adapter.adapterMode.name} " +
+ "cache=hit endpoint=${effectiveArchiveEndpointPreference(kind, session).name}"
+ )
+ return Result.success(
+ buildResolvedPlaybackInfo(
+ session = session,
+ profile = profile,
+ adapter = adapter,
+ resolvedUrl = cachedResolvedUrl,
+ kind = kind,
+ descriptor = descriptor,
+ userAgent = resolvePlaybackUserAgent(profile)
+ )
+ )
+ }
+
when (
val linkResult = api.createLink(
session = session,
@@ -483,7 +590,7 @@ class StalkerProvider(
archiveEndSeconds = archiveEndSeconds
)
) {
- is Result.Success -> {
+is Result.Success -> {
val resolvedUrl = repairCreateLinkUrl(
kind = kind,
resolvedUrl = linkResult.data,
@@ -491,6 +598,7 @@ class StalkerProvider(
archiveStartSeconds = archiveStartSeconds,
archiveEndSeconds = archiveEndSeconds
)
+ storeResolvedStreamUrl(kind, variant.cmd, resolvedUrl)
Log.d(
TAG,
"Resolved create_link playback provider=$providerId kind=${kind.name} mode=${adapter.adapterMode.name} " +
@@ -499,23 +607,14 @@ class StalkerProvider(
"liveTarget=${livePlaybackTargetSummary(directUrl, resolvedUrl)}"
)
return Result.success(
- StalkerPlaybackInfo(
- url = resolvedUrl,
- headers = buildPlaybackHeaders(session, profile, resolvedUrl),
- userAgent = resolvePlaybackUserAgent(profile),
- allowInvalidSsl = true,
- proxyHost = profile.advancedOptions.proxy?.host.orEmpty(),
- proxyPort = profile.advancedOptions.proxy?.port,
- playbackMode = adapter.adapterMode,
- endpointPreference = effectiveArchiveEndpointPreference(
- kind = kind,
- session = session
- ),
- cookieMode = derivePlaybackCookieMode(
- current = effectiveArchiveCookieMode(kind, session, resolvedUrl),
- url = resolvedUrl
- ),
- backendHint = detectPlaybackBackendHint(resolvedUrl, descriptor.capabilities, adapter)
+ buildResolvedPlaybackInfo(
+ session = session,
+ profile = profile,
+ adapter = adapter,
+ resolvedUrl = resolvedUrl,
+ kind = kind,
+ descriptor = descriptor,
+ userAgent = resolvePlaybackUserAgent(profile)
)
)
}
@@ -692,6 +791,7 @@ class StalkerProvider(
else -> emptyList()
}
}
+ bindCategoryRemoteIds(type, categoryRecords)
val categories = categoryRecords.map { record ->
val id = syntheticCategoryId(type, record.id.ifBlank { record.name })
CategorySeed(
@@ -740,6 +840,72 @@ class StalkerProvider(
}
}
+ private suspend fun <T> mapResolvedItems(
+ type: ContentType,
+ result: Result<List<StalkerItemRecord>>,
+ mapper: (StalkerItemRecord) -> T?
+ ): Result<List<T>> = when (result) {
+ is Result.Success -> {
+ bindRemoteIds(type, result.data.map(StalkerItemRecord::id))
+ Result.success(result.data.mapNotNull(mapper))
+ }
+ is Result.Error -> Result.error(result.message, result.exception)
+ is Result.Loading -> Result.error("Unexpected loading state")
+ }
+
+ private suspend fun <T> mapResolvedPage(
+ type: ContentType,
+ result: Result<StalkerPagedItems>,
+ mapper: (StalkerItemRecord) -> T?
+ ): Result<StalkerPagedResult<T>> = when (result) {
+ is Result.Success -> {
+ val paged = result.data
+ bindRemoteIds(type, paged.items.map(StalkerItemRecord::id))
+ Result.success(
+ StalkerPagedResult(
+ items = paged.items.mapNotNull(mapper),
+ page = paged.page,
+ totalPages = paged.totalPages,
+ pageSize = paged.pageSize,
+ advertisedTotalItems = paged.advertisedTotalItems,
+ advertisedTotalPages = paged.advertisedTotalPages,
+ isTruncated = paged.isTruncated,
+ terminationReason = paged.terminationReason
+ )
+ )
+ }
+ is Result.Error -> Result.error(result.message, result.exception)
+ is Result.Loading -> Result.error("Unexpected loading state")
+ }
+
+ private suspend fun bindRemoteIds(type: ContentType, rawIds: Iterable<String>) {
+ val ids = rawIds.map(String::trim).filter(String::isNotEmpty).distinct()
+ if (ids.isEmpty()) return
+ val resolved = identityResolver?.resolveAll(providerId, type, ids)
+ ?: ids.associateWith { rawId ->
+ rawId.toLongOrNull()?.takeIf { it > 0L } ?: legacyStableId(type, rawId)
+ }
+ resolved.forEach { (rawId, surrogateId) ->
+ remoteIdentityCache[type to rawId] = surrogateId
+ }
+ }
+
+ private suspend fun bindCategoryRemoteIds(type: ContentType, records: List<StalkerCategoryRecord>) {
+ val resolved = identityResolver?.resolveCategories(
+ providerId = providerId,
+ contentType = type,
+ categories = records.map { record -> (record.id.ifBlank { record.name }) to record.name }
+ )
+ if (resolved == null) {
+ records.forEach { record ->
+ val rawId = record.id.ifBlank { record.name }.trim()
+ remoteIdentityCache[type to rawId] = legacyStableId(type, rawId)
+ }
+ } else {
+ resolved.forEach { (rawId, surrogateId) -> remoteIdentityCache[type to rawId] = surrogateId }
+ }
+ }
+
private suspend fun <T> runWithAuthorizedSession(
retryOnAuthorizationFailure: Boolean = true,
block: suspend (StalkerSession, StalkerProviderProfile) -> Result<T>
@@ -776,14 +942,42 @@ class StalkerProvider(
return@withLock Result.success(cachedAuth.session to cachedAuth.profile)
}
+ val persistedState = portalStateStore?.getValidated(providerId)
+ val rawPersistedRecipe = persistedState?.bootstrapRecipe
+ ?.let { value -> runCatching { StalkerBootstrapRecipe.valueOf(value) }.getOrNull() }
+ val persistedRecipe = rawPersistedRecipe?.takeIf { recipe ->
+ portalStateStore?.isRecipeHealthy(persistedState, recipe.name) != false
+ }
+ val persistedEndpointUrl = persistedState?.workingEndpoint?.takeIf { endpoint ->
+ portalStateStore?.isEndpointHealthy(persistedState, endpoint) != false
+ }
+ val persistedEndpoint = persistedEndpointUrl?.let { endpoint ->
+ if (endpoint.contains("server/load.php", ignoreCase = true)) {
+ StalkerEndpointPreference.SERVER_LOAD
+ } else {
+ StalkerEndpointPreference.PORTAL
+ }
+ }
+ if (persistedState?.workingEndpoint != null && persistedEndpointUrl == null) {
+ StalkerTelemetry.strategySelected(providerId, "AUTH_ENDPOINT_AUTO", "ENDPOINT_COOLDOWN")
+ } else if (persistedEndpoint != null) {
+ StalkerTelemetry.strategySelected(providerId, persistedEndpoint.name, "VALIDATED_CACHE")
+ }
+ if (rawPersistedRecipe != null && persistedRecipe == null) {
+ StalkerTelemetry.strategySelected(providerId, "AUTH_RECIPE_DISCOVERY", "RECIPE_COOLDOWN")
+ }
val profile = buildStalkerDeviceProfile(
- portalUrl = portalUrl,
+ // Preserve the complete validated endpoint (scheme, custom path, and script), not
+ // just its SERVER_LOAD/PORTAL family. loadUrlCandidates accepts a direct script URL.
+ portalUrl = persistedEndpointUrl ?: portalUrl,
macAddress = normalizedMacAddress(),
authMode = authMode,
magPresetHint = magPresetHint,
portalFingerprintHint = portalFingerprintHint,
- bootstrapRecipeHint = bootstrapRecipeHint,
- endpointPreferenceHint = endpointPreferenceHint,
+ bootstrapRecipeHint = persistedRecipe
+ ?: bootstrapRecipeHint.takeIf { rawPersistedRecipe == null }
+ ?: StalkerBootstrapRecipe.GENERIC_SAFE,
+ endpointPreferenceHint = persistedEndpoint ?: endpointPreferenceHint,
cookieModeHint = cookieModeHint,
playbackBackendHint = playbackBackendHint,
username = normalizedUsername(),
@@ -797,9 +991,35 @@ class StalkerProvider(
deviceIdOverride = normalizedDeviceId(),
deviceId2Override = normalizedDeviceId2(),
signatureOverride = normalizedSignature(),
- stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson
- )
- when (val authResult = api.authenticate(profile)) {
+ stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,
+ protocolPreference = protocolPreference,
+ transportGrant = transportGrant,
+ requestedProfileId = requestedProfileId,
+ learnedProfileId = learnedProfileId,
+ requireCatalogValidation = requireCatalogValidation,
+ allowCompatibilityDiscovery = providerId <= 0L,
+ onProgress = onProgress
+ ).copy(providerId = providerId)
+ val initialAuthResult = discoveryCoordinator.authenticate(profile)
+ val finalAuthResult = if (
+ initialAuthResult is Result.Error &&
+ persistedEndpointUrl != null
+ ) {
+ portalStateStore?.markEndpointUnhealthy(providerId, persistedEndpointUrl)
+ StalkerTelemetry.strategySelected(providerId, "AUTH_ENDPOINT_AUTO", "CACHED_ENDPOINT_FAILED")
+ discoveryCoordinator.authenticate(
+ profile.copy(
+ portalUrl = portalUrl,
+ endpointPreference = StalkerEndpointPreference.AUTO,
+ // Endpoint repair must retain the learned identity. Broad profile rotation
+ // is reserved for an explicit foreground Repair connection action.
+ allowCompatibilityDiscovery = false
+ )
+ )
+ } else {
+ initialAuthResult
+ }
+ when (val authResult = finalAuthResult) {
is Result.Success -> {
sessionCache = authResult.data.first
accountProfileCache = authResult.data.second
@@ -807,14 +1027,40 @@ class StalkerProvider(
session = authResult.data.first,
profile = authResult.data.second
)
+ portalStateStore?.recordAuthentication(
+ providerId = providerId,
+ session = authResult.data.first,
+ profile = authResult.data.second
+ )
Result.success(authResult.data)
}
- is Result.Error -> Result.error(authResult.message, authResult.exception)
+ is Result.Error -> {
+ rawPersistedRecipe?.let { failedRecipe ->
+ portalStateStore?.markRecipeUnhealthy(providerId, failedRecipe.name)
+ }
+ Result.error(authResult.message, authResult.exception)
+ }
is Result.Loading -> Result.error("Unexpected loading state")
}
}
+ suspend fun validatedPortalState(): com.streamvault.data.local.entity.StalkerPortalStateEntity? =
+ portalStateStore?.getValidated(providerId)
+
+ suspend fun recordBulkLiveCapability(supported: Boolean, categoryFidelity: Boolean? = null) {
+ portalStateStore?.recordBulkLive(providerId, supported, categoryFidelity)
+ }
+
+ suspend fun recordWildcardCapability(contentType: ContentType, supported: Boolean) {
+ portalStateStore?.recordWildcard(providerId, contentType, supported)
+ }
+
+ suspend fun recordEpgCapability(supported: Boolean) {
+ portalStateStore?.recordEpg(providerId, supported)
+ }
+
private fun currentDeviceProfile(): StalkerDeviceProfile {
+ accountProfileCache?.let { learned -> return buildLearnedDeviceProfile(learned) }
return buildStalkerDeviceProfile(
portalUrl = portalUrl,
macAddress = normalizedMacAddress(),
@@ -836,11 +1082,19 @@ class StalkerProvider(
deviceIdOverride = normalizedDeviceId(),
deviceId2Override = normalizedDeviceId2(),
signatureOverride = normalizedSignature(),
- stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson
- )
+ stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,
+ protocolPreference = protocolPreference,
+ transportGrant = transportGrant,
+ requestedProfileId = requestedProfileId,
+ learnedProfileId = learnedProfileId,
+ requireCatalogValidation = requireCatalogValidation,
+ allowCompatibilityDiscovery = providerId <= 0L,
+ onProgress = onProgress
+ ).copy(providerId = providerId)
}
private fun buildLearnedDeviceProfile(profile: StalkerProviderProfile): StalkerDeviceProfile {
+ val learnedCompatibilityProfileId = learnedCompatibilityProfileId(profile)
return buildStalkerDeviceProfile(
portalUrl = portalUrl,
macAddress = normalizedMacAddress(),
@@ -862,10 +1116,26 @@ class StalkerProvider(
deviceIdOverride = normalizedDeviceId(),
deviceId2Override = normalizedDeviceId2(),
signatureOverride = normalizedSignature(),
- stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson
- )
+ stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,
+ protocolPreference = protocolPreference,
+ transportGrant = transportGrant,
+ requestedProfileId = learnedCompatibilityProfileId,
+ learnedProfileId = learnedCompatibilityProfileId,
+ requireCatalogValidation = requireCatalogValidation,
+ allowCompatibilityDiscovery = providerId <= 0L,
+ onProgress = onProgress
+ ).copy(providerId = providerId)
}
+ private fun learnedCompatibilityProfileId(profile: StalkerProviderProfile): String =
+ if (profile.compatibilityProfileId == StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC &&
+ profile.magPreset != StalkerMagPreset.GENERIC_SAFE
+ ) {
+ StalkerCompatibilityRegistry.idForLegacyPreset(profile.magPreset)
+ } else {
+ profile.compatibilityProfileId
+ }
+
private fun buildPlaybackHeaders(
session: StalkerSession,
profile: StalkerDeviceProfile,
@@ -906,6 +1176,76 @@ class StalkerProvider(
}
}
+ private fun playbackTransportPolicyFor(url: String): PlaybackTransportPolicy? {
+ val grant = transportGrant ?: return null
+ val normalizedUrl = url.trim().substringAfter(' ', url.trim())
+ val uri = runCatching { URI(normalizedUrl) }.getOrNull() ?: return null
+ val scheme = uri.scheme?.lowercase(Locale.ROOT) ?: return null
+ val host = uri.host?.lowercase(Locale.ROOT) ?: return null
+ val port = when {
+ uri.port != -1 -> uri.port
+ scheme == "https" -> 443
+ scheme == "http" -> 80
+ else -> return null
+ }
+ if (!grant.origin.scheme.equals(scheme, ignoreCase = true) ||
+ !grant.origin.host.equals(host, ignoreCase = true) ||
+ grant.origin.port != port
+ ) {
+ return null
+ }
+ return when (grant.mode) {
+ StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS ->
+ PlaybackTransportPolicy(
+ mode = PlaybackTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS,
+ origin = grant.origin,
+ spkiSha256 = grant.spkiSha256
+ )
+ StalkerTransportMode.USER_ACCEPTED_HTTP ->
+ PlaybackTransportPolicy(
+ mode = PlaybackTransportMode.USER_ACCEPTED_HTTP,
+ origin = grant.origin
+ )
+ StalkerTransportMode.AUTO_STRICT,
+ StalkerTransportMode.VERIFIED_HTTPS -> null
+ }
+ }
+
+private fun playbackTransportChallengeFor(url: String): StalkerTransportChallenge? {
+ // IPTV streams are commonly served over plain HTTP from a different origin than the
+ // (often HTTPS) portal — Flussonic / raw-IP CDNs / high ports are the norm, not the
+ // exception. The portal already authenticated and vouched for the resolved URL via
+ // create_link, so we trust cleartext playback origins instead of gating them behind a
+ // per-origin consent that can never be granted through the UI. The portal-origin
+ // transport consent (StalkerTransportFactory) is unchanged.
+ return null
+ }
+
+ private fun buildResolvedPlaybackInfo(
+ session: StalkerSession,
+ profile: StalkerDeviceProfile,
+ adapter: StalkerPlaybackAdapter,
+ resolvedUrl: String,
+ kind: StalkerStreamKind,
+ descriptor: StalkerPlaybackDescriptor,
+ userAgent: String?
+ ): StalkerPlaybackInfo = StalkerPlaybackInfo(
+ url = resolvedUrl,
+ headers = buildPlaybackHeaders(session, profile, resolvedUrl),
+ userAgent = userAgent,
+ transportPolicy = playbackTransportPolicyFor(resolvedUrl),
+ allowInvalidSsl = false,
+ proxyHost = profile.advancedOptions.proxy?.host.orEmpty(),
+ proxyPort = profile.advancedOptions.proxy?.port,
+ playbackMode = adapter.adapterMode,
+ endpointPreference = effectiveArchiveEndpointPreference(kind, session),
+ cookieMode = derivePlaybackCookieMode(
+ current = effectiveArchiveCookieMode(kind, session, resolvedUrl),
+ url = resolvedUrl
+ ),
+ backendHint = detectPlaybackBackendHint(resolvedUrl, descriptor.capabilities, adapter)
+ )
+
private fun resolvePlaybackUserAgent(profile: StalkerDeviceProfile): String? {
profile.advancedOptions.playerUserAgent.trim().takeIf { it.isNotBlank() }?.let { return it }
parseStalkerHeaderOverrides(profile.advancedOptions.playerHeaders).entries.firstOrNull { (name, _) ->
@@ -1225,6 +1565,7 @@ class StalkerProvider(
if (cached != null) {
return cached.firstOrNull { it.id == targetId }?.rawId
}
+ identityResolver?.reverse(providerId, normalizedType, targetId)?.let { return it }
when (val categoriesResult = when (normalizedType) {
ContentType.LIVE -> getLiveCategories()
ContentType.MOVIE -> getVodCategories()
@@ -1282,7 +1623,11 @@ class StalkerProvider(
private fun toMovie(item: StalkerItemRecord, requestedCategoryId: Long? = null): Movie? {
val numericId = stableItemId(ContentType.MOVIE, item.id)
- val category = requestedCategorySeed(ContentType.MOVIE, requestedCategoryId)
+ val category = requestedCategorySeed(
+ type = ContentType.MOVIE,
+ categoryId = requestedCategoryId,
+ fallbackName = item.categoryName
+ )
?: resolveCategory(ContentType.MOVIE, item.categoryId, item.categoryName)
val directStreamUrl = item.streamUrl
?.substringAfter(' ', missingDelimiterValue = item.streamUrl)
@@ -1324,7 +1669,11 @@ class StalkerProvider(
)
}
- private fun requestedCategorySeed(type: ContentType, categoryId: Long?): CategorySeed? {
+ private fun requestedCategorySeed(
+ type: ContentType,
+ categoryId: Long?,
+ fallbackName: String? = null
+ ): CategorySeed? {
val targetId = categoryId ?: return null
val normalizedType = when (type) {
ContentType.SERIES_EPISODE -> ContentType.SERIES
@@ -1332,12 +1681,20 @@ class StalkerProvider(
}
return categoryCache[normalizedType]?.firstOrNull { category ->
category.id == targetId || category.rawId.toLongOrNull() == targetId
- }
+ } ?: CategorySeed(
+ id = targetId,
+ rawId = targetId.toString(),
+ name = fallbackName?.trim().takeUnless { it.isNullOrBlank() } ?: "Category $targetId"
+ )
}
- private fun toSeries(item: StalkerItemRecord): Series? {
+ private fun toSeries(item: StalkerItemRecord, requestedCategoryId: Long? = null): Series? {
val numericId = stableItemId(ContentType.SERIES, item.id)
- val category = resolveCategory(ContentType.SERIES, item.categoryId, item.categoryName)
+ val category = requestedCategorySeed(
+ type = ContentType.SERIES,
+ categoryId = requestedCategoryId,
+ fallbackName = item.categoryName
+ ) ?: resolveCategory(ContentType.SERIES, item.categoryId, item.categoryName)
return Series(
id = 0L,
name = item.name.ifBlank { "Series $numericId" },
@@ -1493,9 +1850,16 @@ class StalkerProvider(
}
private fun stableItemId(type: ContentType, rawId: String): Long =
- rawId.trim().toLongOrNull()?.takeIf { it > 0 } ?: syntheticCategoryId(type, rawId)
+ remoteIdentityCache[type to rawId.trim()]
+ ?: rawId.trim().toLongOrNull()?.takeIf { it > 0L }
+ ?: legacyStableId(type, rawId)
private fun syntheticCategoryId(type: ContentType, seed: String): Long {
+ remoteIdentityCache[type to seed.trim()]?.let { return it }
+ return legacyStableId(type, seed)
+ }
+
+ private fun legacyStableId(type: ContentType, seed: String): Long {
val normalized = "$providerId/${type.name}/${seed.trim().lowercase(Locale.ROOT)}"
return (normalized.hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)
}
@@ -1530,33 +1894,38 @@ class StalkerProvider(
private fun normalizedSignature(): String =
signature.trim().uppercase(Locale.ROOT)
- private fun authCacheKey(): String = listOf(
- System.identityHashCode(api).toString(),
- providerId.toString(),
- StalkerUrlFactory.normalizePortalUrl(portalUrl),
- normalizedMacAddress(),
- authMode.name,
- normalizedUsername(),
- normalizedPassword(),
- httpUserAgent.trim(),
- httpHeaders,
- portalFingerprintHint.name,
- magPresetHint.name,
- bootstrapRecipeHint.name,
- endpointPreferenceHint.name,
- cookieModeHint.name,
- playbackBackendHint.name,
- portalProfileHint.name,
- preferredPlaybackMode?.name.orEmpty(),
- normalizedDeviceProfile(),
- normalizedTimezone(),
- normalizedLocale(),
- normalizedSerialNumber(),
- normalizedDeviceId(),
- normalizedDeviceId2(),
- normalizedSignature(),
- stalkerAdvancedOptionsJson
- ).joinToString(separator = "\u001f")
+ private fun authCacheKey(): String {
+ val normalized = listOf(
+ System.identityHashCode(api).toString(),
+ providerId.toString(),
+ StalkerUrlFactory.normalizePortalUrl(portalUrl),
+ normalizedMacAddress(),
+ authMode.name,
+ normalizedUsername(),
+ normalizedPassword(),
+ httpUserAgent.trim(),
+ httpHeaders,
+ portalFingerprintHint.name,
+ magPresetHint.name,
+ bootstrapRecipeHint.name,
+ endpointPreferenceHint.name,
+ cookieModeHint.name,
+ playbackBackendHint.name,
+ portalProfileHint.name,
+ preferredPlaybackMode?.name.orEmpty(),
+ normalizedDeviceProfile(),
+ normalizedTimezone(),
+ normalizedLocale(),
+ normalizedSerialNumber(),
+ normalizedDeviceId(),
+ normalizedDeviceId2(),
+ normalizedSignature(),
+ stalkerAdvancedOptionsJson
+ ).joinToString(separator = "\u001f")
+ return MessageDigest.getInstance("SHA-256")
+ .digest(normalized.toByteArray(Charsets.UTF_8))
+ .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
+ }
private fun resolveProviderStatus(profile: StalkerProviderProfile): ProviderStatus {
val normalizedStatus = profile.statusLabel?.trim()?.lowercase(Locale.ROOT).orEmpty()
@@ -1577,10 +1946,7 @@ class StalkerProvider(
}
private fun isAuthorizationFailure(message: String, exception: Throwable?): Boolean {
- val normalizedMessage = message.lowercase(Locale.ROOT)
- val exceptionMessage = exception?.message?.lowercase(Locale.ROOT).orEmpty()
- return normalizedMessage.contains("authorization failed") ||
- exceptionMessage.contains("authorization failed")
+ return com.streamvault.data.remote.stalker.isStalkerAuthorizationFailure(message, exception)
}
private fun validateArchiveWindow(
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt
new file mode 100644
index 00000000..286e62d0
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolver.kt
@@ -0,0 +1,131 @@
+package com.streamvault.data.remote.stalker
+
+import android.database.sqlite.SQLiteConstraintException
+import com.streamvault.data.local.DatabaseTransactionRunner
+import com.streamvault.data.local.dao.StalkerRemoteIdentityDao
+import com.streamvault.data.local.dao.CategoryDao
+import com.streamvault.data.local.entity.StalkerRemoteIdentityEntity
+import com.streamvault.domain.model.ContentType
+import java.util.Locale
+import java.util.concurrent.ConcurrentHashMap
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+
+/** Collision-safe, persistent translation between portal IDs and local Long IDs. */
+@Singleton
+class StalkerRemoteIdentityResolver private constructor(
+ private val dao: StalkerRemoteIdentityDao,
+ private val transactionRunner: DatabaseTransactionRunner,
+ private val categoryDao: CategoryDao?,
+ @Suppress("UNUSED_PARAMETER") constructorMarker: Unit
+) {
+ @Inject
+ constructor(
+ dao: StalkerRemoteIdentityDao,
+ transactionRunner: DatabaseTransactionRunner,
+ categoryDao: CategoryDao
+ ) : this(dao, transactionRunner, categoryDao, Unit)
+
+ internal constructor(
+ dao: StalkerRemoteIdentityDao,
+ transactionRunner: DatabaseTransactionRunner
+ ) : this(dao, transactionRunner, null, Unit)
+
+ private val locks = ConcurrentHashMap<String, Mutex>()
+
+ suspend fun resolveAll(
+ providerId: Long,
+ contentType: ContentType,
+ rawIds: Iterable<String>
+ ): Map<String, Long> {
+ val normalizedIds = rawIds.map(String::trim).filter(String::isNotEmpty).distinct().sorted()
+ if (normalizedIds.isEmpty()) return emptyMap()
+ val key = "$providerId/${contentType.name}"
+ return locks.computeIfAbsent(key) { Mutex() }.withLock {
+ transactionRunner.inTransaction {
+ normalizedIds.associateWith { rawId -> resolveLocked(providerId, contentType, rawId) }
+ }
+ }
+ }
+
+ suspend fun reverse(providerId: Long, contentType: ContentType, surrogateId: Long): String? =
+ dao.getBySurrogateId(providerId, contentType.name, surrogateId)?.rawId
+
+ suspend fun resolveCategories(
+ providerId: Long,
+ contentType: ContentType,
+ categories: Iterable<Pair<String, String>>
+ ): Map<String, Long> {
+ val normalized = categories
+ .map { (rawId, name) -> rawId.trim() to name.trim() }
+ .filter { (rawId, _) -> rawId.isNotEmpty() }
+ .distinctBy { it.first }
+ .sortedBy { it.first }
+ if (normalized.isEmpty()) return emptyMap()
+ val existingByName = categoryDao
+ ?.getByProviderAndTypeSync(providerId, contentType.name)
+ ?.associateBy { category -> category.name.trim().lowercase(Locale.ROOT) }
+ .orEmpty()
+ val preferred = normalized.associate { (rawId, name) ->
+ rawId to existingByName[name.lowercase(Locale.ROOT)]?.categoryId
+ }
+ val key = "$providerId/${contentType.name}"
+ return locks.computeIfAbsent(key) { Mutex() }.withLock {
+ transactionRunner.inTransaction {
+ normalized.associate { (rawId, _) ->
+ rawId to resolveLocked(providerId, contentType, rawId, preferred[rawId])
+ }
+ }
+ }
+ }
+
+ private suspend fun resolveLocked(
+ providerId: Long,
+ contentType: ContentType,
+ rawId: String,
+ preferredSurrogate: Long? = null
+ ): Long {
+ dao.getByRawId(providerId, contentType.name, rawId)?.let { return it.surrogateId }
+ val numericCandidate = rawId.toLongOrNull()?.takeIf { it > 0L }
+ val legacyCandidate = legacyId(providerId, contentType, rawId)
+ var candidate = listOfNotNull(preferredSurrogate?.takeIf { it > 0L }, numericCandidate, legacyCandidate)
+ .firstOrNull { proposed ->
+ dao.getBySurrogateId(providerId, contentType.name, proposed) == null
+ }
+ ?: nextHighSurrogate(providerId, contentType)
+ while (true) {
+ val now = System.currentTimeMillis()
+ try {
+ dao.insert(
+ StalkerRemoteIdentityEntity(
+ providerId = providerId,
+ contentType = contentType,
+ rawId = rawId,
+ surrogateId = candidate,
+ createdAt = now,
+ updatedAt = now
+ )
+ )
+ return candidate
+ } catch (_: SQLiteConstraintException) {
+ dao.getByRawId(providerId, contentType.name, rawId)?.let { return it.surrogateId }
+ candidate = nextHighSurrogate(providerId, contentType)
+ }
+ }
+ }
+
+ private suspend fun nextHighSurrogate(providerId: Long, contentType: ContentType): Long =
+ ((dao.maxAllocatedSurrogate(providerId, contentType.name, HIGH_SURROGATE_FLOOR)
+ ?: (HIGH_SURROGATE_FLOOR - 1L)) + 1L).coerceAtMost(Long.MAX_VALUE - 1L)
+
+ private fun legacyId(providerId: Long, contentType: ContentType, rawId: String): Long {
+ val normalized = "$providerId/${contentType.name}/${rawId.trim().lowercase(Locale.ROOT)}"
+ return (normalized.hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)
+ }
+
+ private companion object {
+ const val HIGH_SURROGATE_FLOOR = 4_000_000_000L
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt
new file mode 100644
index 00000000..3db32856
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinator.kt
@@ -0,0 +1,247 @@
+package com.streamvault.data.remote.stalker
+
+import com.streamvault.domain.model.StalkerRequestPriority
+import java.net.SocketTimeoutException
+import java.util.concurrent.ConcurrentHashMap
+import java.util.concurrent.atomic.AtomicLong
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.sync.Mutex
+import kotlinx.coroutines.sync.withLock
+
+data class StalkerRequestSnapshot(
+ val active: Int,
+ val queued: Int,
+ val concurrencyLimit: Int,
+ val stressCooldownUntil: Long
+)
+
+data class StalkerRequestDescriptor(
+ val contentType: String,
+ val action: String,
+ val categoryKey: String? = null,
+ val itemKey: String? = null,
+ val page: Int? = null,
+ val workId: String? = null
+) {
+ internal fun dedupeKey(): String = listOf(
+ contentType,
+ action,
+ categoryKey.orEmpty(),
+ itemKey.orEmpty(),
+ page?.toString().orEmpty()
+ ).joinToString("\u001f")
+}
+
+data class StalkerResponseMetrics(
+ val items: Int? = null,
+ val pages: Int? = null,
+ val advertisedTotal: Int? = null,
+ val truncated: Boolean? = null,
+ val terminationReason: String? = null
+)
+
+/** Provider-scoped priority, deduplication, and adaptive metadata admission. */
+@Singleton
+class StalkerRequestCoordinator @Inject constructor(
+ private val portalStateStore: StalkerPortalStateStore?
+) {
+ /** Isolated constructor for pure unit tests; production uses the injected state store. */
+ constructor() : this(null)
+
+ private data class Waiter(
+ val ticket: Long,
+ val priority: StalkerRequestPriority
+ )
+
+ private class ProviderState {
+ val mutex = Mutex()
+ val waiters = mutableListOf<Waiter>()
+ val inFlight = mutableMapOf<String, CompletableDeferred<Any?>>()
+ var active = 0
+ var activeBackground = 0
+ var safeMetadataConcurrency = NORMAL_METADATA_CONCURRENCY
+ var stressCooldownUntil = 0L
+ var persistedStateLoaded = false
+ }
+
+ private val states = ConcurrentHashMap<Long, ProviderState>()
+ private val tickets = AtomicLong()
+
+ suspend fun <T> execute(
+ providerId: Long,
+ priority: StalkerRequestPriority,
+ descriptor: StalkerRequestDescriptor,
+ metricsOf: (T) -> StalkerResponseMetrics = { StalkerResponseMetrics() },
+ block: suspend () -> T
+ ): T {
+ require(providerId > 0L)
+ val state = states.computeIfAbsent(providerId) { ProviderState() }
+ hydratePersistedState(providerId, state)
+ val requestKey = descriptor.dedupeKey()
+ val deferred = CompletableDeferred<Any?>()
+ var owner = false
+ val shared = state.mutex.withLock {
+ state.inFlight[requestKey]?.also { return@withLock it }
+ state.inFlight[requestKey] = deferred
+ owner = true
+ deferred
+ }
+ if (!owner) {
+ @Suppress("UNCHECKED_CAST")
+ return shared.await() as T
+ }
+
+ val waiter = Waiter(tickets.incrementAndGet(), priority)
+ var acquired = false
+ var responseMetrics = StalkerResponseMetrics()
+ val startedAt = System.currentTimeMillis()
+ var outcome = "success"
+ try {
+ state.mutex.withLock { state.waiters += waiter }
+ while (!acquired) {
+ acquired = state.mutex.withLock {
+ val now = System.currentTimeMillis()
+ val limit = state.currentLimit(now)
+ val first = state.waiters.minWithOrNull(
+ compareBy<Waiter>({ it.priority.ordinal }, { it.ticket })
+ )
+ val backgroundAllowed = priority != StalkerRequestPriority.BACKGROUND_INDEX ||
+ state.activeBackground == 0
+ if (first == waiter && state.active < limit && backgroundAllowed) {
+ state.waiters.remove(waiter)
+ state.active += 1
+ if (priority == StalkerRequestPriority.BACKGROUND_INDEX) state.activeBackground += 1
+ true
+ } else {
+ false
+ }
+ }
+ if (!acquired) delay(ADMISSION_POLL_MILLIS)
+ }
+ val result = block()
+ responseMetrics = metricsOf(result)
+ val probeNow = System.currentTimeMillis()
+ val restored = state.mutex.withLock {
+ if (state.safeMetadataConcurrency == 1 && state.stressCooldownUntil in 1..probeNow) {
+ state.safeMetadataConcurrency = NORMAL_METADATA_CONCURRENCY
+ state.stressCooldownUntil = 0L
+ true
+ } else {
+ false
+ }
+ }
+ if (restored) portalStateStore?.recordHealthyMetadataProbe(providerId, probeNow)
+ deferred.complete(result)
+ return result
+ } catch (cancelled: CancellationException) {
+ outcome = "cancelled"
+ deferred.cancel(cancelled)
+ throw cancelled
+ } catch (error: Throwable) {
+ outcome = error.telemetryOutcome()
+ if (error.isProviderStressSignal()) {
+ val cooldownUntil = System.currentTimeMillis() + STRESS_COOLDOWN_MILLIS
+ state.mutex.withLock {
+ state.safeMetadataConcurrency = 1
+ state.stressCooldownUntil = cooldownUntil
+ }
+ portalStateStore?.recordStressCooldown(providerId, cooldownUntil)
+ }
+ deferred.completeExceptionally(error)
+ throw error
+ } finally {
+ val finalSnapshot = state.mutex.withLock {
+ state.waiters.remove(waiter)
+ if (acquired) {
+ state.active = (state.active - 1).coerceAtLeast(0)
+ if (priority == StalkerRequestPriority.BACKGROUND_INDEX) {
+ state.activeBackground = (state.activeBackground - 1).coerceAtLeast(0)
+ }
+ }
+ if (state.inFlight[requestKey] === deferred) state.inFlight.remove(requestKey)
+ val limit = state.currentLimit(System.currentTimeMillis())
+ StalkerRequestSnapshot(state.active, state.waiters.size, limit, state.stressCooldownUntil)
+ }
+ StalkerTelemetry.requestCompleted(
+ providerId = providerId,
+ priority = priority,
+ descriptor = descriptor,
+ responseMetrics = responseMetrics,
+ durationMillis = System.currentTimeMillis() - startedAt,
+ active = finalSnapshot.active,
+ queued = finalSnapshot.queued,
+ concurrencyLimit = finalSnapshot.concurrencyLimit,
+ stressCooldownUntil = finalSnapshot.stressCooldownUntil,
+ outcome = outcome
+ )
+ }
+ }
+
+ suspend fun snapshot(providerId: Long): StalkerRequestSnapshot {
+ val state = states[providerId] ?: return StalkerRequestSnapshot(0, 0, 2, 0L)
+ return state.mutex.withLock {
+ val limit = state.currentLimit(System.currentTimeMillis())
+ StalkerRequestSnapshot(state.active, state.waiters.size, limit, state.stressCooldownUntil)
+ }
+ }
+
+ suspend fun recordFailure(providerId: Long, error: Throwable?) {
+ if (providerId <= 0L || error?.isProviderStressSignal() != true) return
+ val state = states.computeIfAbsent(providerId) { ProviderState() }
+ hydratePersistedState(providerId, state)
+ val cooldownUntil = System.currentTimeMillis() + STRESS_COOLDOWN_MILLIS
+ state.mutex.withLock {
+ state.safeMetadataConcurrency = 1
+ state.stressCooldownUntil = cooldownUntil
+ }
+ portalStateStore?.recordStressCooldown(providerId, cooldownUntil)
+ }
+
+ private suspend fun hydratePersistedState(providerId: Long, state: ProviderState) {
+ if (state.mutex.withLock { state.persistedStateLoaded }) return
+ val persisted = portalStateStore?.get(providerId)
+ state.mutex.withLock {
+ if (!state.persistedStateLoaded) {
+ state.safeMetadataConcurrency = persisted?.safeMetadataConcurrency
+ ?.coerceIn(1, NORMAL_METADATA_CONCURRENCY)
+ ?: NORMAL_METADATA_CONCURRENCY
+ state.stressCooldownUntil = persisted?.stressCooldownUntil ?: 0L
+ state.persistedStateLoaded = true
+ }
+ }
+ }
+
+ private fun ProviderState.currentLimit(now: Long): Int =
+ if (safeMetadataConcurrency <= 1 || stressCooldownUntil > now) 1 else NORMAL_METADATA_CONCURRENCY
+
+ private fun Throwable.isProviderStressSignal(): Boolean = when (this) {
+ is StalkerApiError.RateLimited -> true
+ is StalkerApiError.Server -> httpStatus == 503
+ is StalkerApiError.Transport -> cause is SocketTimeoutException ||
+ message.orEmpty().contains("timeout", ignoreCase = true) ||
+ message.orEmpty().contains("reset", ignoreCase = true)
+ is SocketTimeoutException -> true
+ else -> cause?.isProviderStressSignal() == true
+ }
+
+ private fun Throwable.telemetryOutcome(): String = when (this) {
+ is StalkerApiError.Authorization -> "authorization"
+ is StalkerApiError.RateLimited -> "rate_limited"
+ is StalkerApiError.Server -> "server"
+ is StalkerApiError.Transport -> "transport"
+ is StalkerApiError.Malformed -> "malformed"
+ is StalkerApiError.ResponseTooLarge -> "oversized"
+ is StalkerApiError.BlockedOrConfiguration -> "blocked_configuration"
+ else -> "failed"
+ }
+
+ private companion object {
+ const val NORMAL_METADATA_CONCURRENCY = 2
+ const val ADMISSION_POLL_MILLIS = 20L
+ const val STRESS_COOLDOWN_MILLIS = 5L * 60L * 1000L
+ }
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTelemetry.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTelemetry.kt
new file mode 100644
index 00000000..e4b27278
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTelemetry.kt
@@ -0,0 +1,202 @@
+package com.streamvault.data.remote.stalker
+
+import android.util.Log
+import com.streamvault.domain.model.StalkerRequestPriority
+import com.streamvault.domain.model.StalkerReadinessSnapshot
+import java.security.MessageDigest
+
+/** Sanitized structured diagnostics. Values accepted here must never contain portal secrets or URLs. */
+internal object StalkerTelemetry {
+ fun capabilityChanged(providerId: Long, capability: String, outcome: String) {
+ val event = buildString {
+ append("event=capability_state")
+ append(" provider=").append(providerHash(providerId))
+ append(" capability=").append(safeLabel(capability))
+ append(" outcome=").append(safeLabel(outcome))
+ }
+ runCatching { Log.i(TAG, event) }
+ }
+
+ fun strategySelected(providerId: Long, strategy: String, reason: String) {
+ val event = buildString {
+ append("event=strategy_selected")
+ append(" provider=").append(providerHash(providerId))
+ append(" strategy=").append(safeLabel(strategy))
+ append(" reason=").append(safeLabel(reason))
+ }
+ runCatching { Log.i(TAG, event) }
+ }
+
+ fun authenticationAttempt(
+ providerId: Long,
+ profileId: String,
+ endpointFamily: String,
+ stage: String,
+ outcome: String
+ ) {
+ val event = buildString {
+ append("event=authentication_attempt")
+ append(" provider=").append(providerHash(providerId))
+ append(" profile=").append(safeLabel(profileId))
+ append(" endpoint_family=").append(safeLabel(endpointFamily))
+ append(" stage=").append(safeLabel(stage))
+ append(" outcome=").append(safeLabel(outcome))
+ }
+ runCatching { Log.i(TAG, event) }
+ }
+
+ fun httpResponse(
+ providerId: Long,
+ endpointFamily: String,
+ action: String?,
+ durationMillis: Long,
+ responseBytes: Long,
+ status: Int,
+ outcome: String
+ ) {
+ val event = buildString {
+ append("event=http_response")
+ append(" provider=").append(providerHash(providerId))
+ append(" endpoint_family=").append(safeLabel(endpointFamily))
+ append(" action=").append(safeLabel(action.orEmpty()))
+ append(" duration_ms=").append(durationMillis.coerceAtLeast(0L))
+ append(" bytes=").append(responseBytes.coerceAtLeast(0L))
+ append(" status=").append(status.coerceAtLeast(0))
+ append(" outcome=").append(safeLabel(outcome))
+ }
+ runCatching { Log.i(TAG, event) }
+ }
+
+ fun indexProgress(
+ providerId: Long,
+ workId: String,
+ section: String,
+ state: String,
+ completedCategories: Int,
+ totalCategories: Int,
+ indexedRows: Int
+ ) {
+ val event = buildString {
+ append("event=index_checkpoint")
+ append(" provider=").append(providerHash(providerId))
+ append(" work_id=").append(hashOpaque(workId))
+ append(" section=").append(safeLabel(section))
+ append(" state=").append(safeLabel(state))
+ append(" completed_categories=").append(completedCategories.coerceAtLeast(0))
+ append(" total_categories=").append(totalCategories.coerceAtLeast(0))
+ append(" indexed_rows=").append(indexedRows.coerceAtLeast(0))
+ }
+ runCatching { Log.i(TAG, event) }
+ }
+
+ fun readinessMilestone(snapshot: StalkerReadinessSnapshot) {
+ val event = buildString {
+ append("event=readiness_milestone")
+ append(" provider=").append(providerHash(snapshot.providerId))
+ append(" state=").append(snapshot.state.name)
+ append(" elapsed_ms=").append(
+ (milestoneTime(snapshot) - snapshot.syncStartedAt).coerceAtLeast(0L)
+ )
+ append(" warning_count=").append(snapshot.warningCount.coerceAtLeast(0))
+ }
+ runCatching { Log.i(TAG, event) }
+ }
+
+ fun requestCompleted(
+ providerId: Long,
+ priority: StalkerRequestPriority,
+ descriptor: StalkerRequestDescriptor,
+ responseMetrics: StalkerResponseMetrics,
+ durationMillis: Long,
+ active: Int,
+ queued: Int,
+ concurrencyLimit: Int,
+ stressCooldownUntil: Long,
+ outcome: String
+ ) {
+ val event = buildRequestEvent(
+ providerId = providerId,
+ priority = priority,
+ descriptor = descriptor,
+ responseMetrics = responseMetrics,
+ durationMillis = durationMillis,
+ active = active,
+ queued = queued,
+ concurrencyLimit = concurrencyLimit,
+ stressCooldownUntil = stressCooldownUntil,
+ outcome = outcome
+ )
+ runCatching { Log.i(TAG, event) }
+ }
+
+ internal fun buildRequestEvent(
+ providerId: Long,
+ priority: StalkerRequestPriority,
+ descriptor: StalkerRequestDescriptor,
+ responseMetrics: StalkerResponseMetrics,
+ durationMillis: Long,
+ active: Int,
+ queued: Int,
+ concurrencyLimit: Int,
+ stressCooldownUntil: Long,
+ outcome: String,
+ now: Long = System.currentTimeMillis()
+ ): String {
+ val cooldownRemaining = (stressCooldownUntil - now).coerceAtLeast(0L)
+ return buildString {
+ append("event=metadata_request")
+ append(" provider=").append(providerHash(providerId))
+ append(" priority=").append(priority.name)
+ append(" content=").append(safeLabel(descriptor.contentType))
+ append(" action=").append(safeLabel(descriptor.action))
+ descriptor.page?.let { append(" page=").append(it.coerceAtLeast(1)) }
+ descriptor.workId?.let { append(" work_id=").append(hashOpaque(it)) }
+ responseMetrics.items?.let { append(" items=").append(it.coerceAtLeast(0)) }
+ responseMetrics.pages?.let { append(" pages=").append(it.coerceAtLeast(0)) }
+ responseMetrics.advertisedTotal?.let { append(" advertised_total=").append(it.coerceAtLeast(0)) }
+ responseMetrics.truncated?.let { append(" truncated=").append(it) }
+ responseMetrics.terminationReason?.let { append(" termination=").append(safeTerminationReason(it)) }
+ append(" duration_ms=").append(durationMillis.coerceAtLeast(0L))
+ append(" active=").append(active.coerceAtLeast(0))
+ append(" queued=").append(queued.coerceAtLeast(0))
+ append(" concurrency_limit=").append(concurrencyLimit.coerceIn(1, 2))
+ append(" cooldown_remaining_ms=").append(cooldownRemaining)
+ append(" outcome=").append(safeLabel(outcome))
+ }
+ }
+
+ private fun providerHash(providerId: Long): String = MessageDigest.getInstance("SHA-256")
+ .digest("streamvault/stalker/provider/$providerId".toByteArray(Charsets.UTF_8))
+ .take(8)
+ .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
+
+ private fun hashOpaque(value: String): String = MessageDigest.getInstance("SHA-256")
+ .digest(value.toByteArray(Charsets.UTF_8))
+ .take(8)
+ .joinToString("") { byte -> "%02x".format(byte.toInt() and 0xff) }
+
+ private fun safeLabel(value: String): String = value
+ .uppercase()
+ .filter { it in 'A'..'Z' || it in '0'..'9' || it == '_' || it == '-' }
+ .take(40)
+ .ifBlank { "UNKNOWN" }
+
+ private fun safeTerminationReason(value: String): String = when (safeLabel(value)) {
+ "PAGE_LIMIT" -> "PAGE_LIMIT"
+ "REPEATED_PAGE" -> "REPEATED_PAGE"
+ "WRONG_PAGE" -> "WRONG_PAGE"
+ "EARLY_EMPTY_PAGE" -> "EARLY_EMPTY_PAGE"
+ "MALFORMED_PAGE" -> "MALFORMED_PAGE"
+ else -> "OTHER"
+ }
+
+ private fun milestoneTime(snapshot: StalkerReadinessSnapshot): Long = when (snapshot.state) {
+ com.streamvault.domain.model.StalkerReadiness.AUTHENTICATING -> snapshot.syncStartedAt
+ com.streamvault.domain.model.StalkerReadiness.LIVE_READY -> snapshot.liveReadyAt
+ com.streamvault.domain.model.StalkerReadiness.CATEGORIES_READY -> snapshot.categoriesReadyAt
+ com.streamvault.domain.model.StalkerReadiness.READY,
+ com.streamvault.domain.model.StalkerReadiness.READY_WITH_WARNINGS -> snapshot.readyAt
+ } ?: System.currentTimeMillis()
+
+ private const val TAG = "StalkerTelemetry"
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
index e7ee9cb4..7e20148a 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinator.kt
@@ -3,7 +3,8 @@ package com.streamvault.data.remote.stalker
import java.util.concurrent.ConcurrentHashMap
internal object StalkerTrafficCoordinator {
- private const val ACTIVE_PLAYBACK_RECHECK_MILLIS = 3_000L
+ private const val NORMAL_BACKGROUND_PAGE_DELAY_MILLIS = 1_000L
+ private const val PLAYBACK_BACKGROUND_PAGE_DELAY_MILLIS = 2_000L
private val activePlaybackCountsByProvider = ConcurrentHashMap<Long, Int>()
fun notePlaybackStarted(providerId: Long) {
@@ -23,16 +24,18 @@ internal object StalkerTrafficCoordinator {
}
}
- fun shouldDeferCatalogFetch(providerId: Long, now: Long = System.currentTimeMillis()): Boolean =
- deferCatalogFetchMillis(providerId, now) > 0L
+ fun isPlaybackActive(providerId: Long): Boolean =
+ providerId > 0L && (activePlaybackCountsByProvider[providerId] ?: 0) > 0
- fun deferCatalogFetchMillis(providerId: Long, now: Long = System.currentTimeMillis()): Long {
- if (providerId <= 0L) return 0L
- if ((activePlaybackCountsByProvider[providerId] ?: 0) <= 0) return 0L
- return ACTIVE_PLAYBACK_RECHECK_MILLIS
- }
+ /** Playback never blocks interactive requests; only maintenance slows between pages. */
+ fun backgroundInterPageDelayMillis(providerId: Long): Long =
+ if (isPlaybackActive(providerId)) {
+ PLAYBACK_BACKGROUND_PAGE_DELAY_MILLIS
+ } else {
+ NORMAL_BACKGROUND_PAGE_DELAY_MILLIS
+ }
internal fun resetForTests() {
activePlaybackCountsByProvider.clear()
}
-}
\ No newline at end of file
+}
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTransport.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTransport.kt
new file mode 100644
index 00000000..9213b583
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerTransport.kt
@@ -0,0 +1,318 @@
+package com.streamvault.data.remote.stalker
+
+import com.streamvault.domain.model.StalkerTransportChallenge
+import com.streamvault.domain.model.StalkerTransportChallengeReason
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
+import java.net.InetSocketAddress
+import java.io.IOException
+import java.net.Socket
+import java.security.MessageDigest
+import java.security.SecureRandom
+import java.security.cert.CertificateException
+import java.security.cert.X509Certificate
+import java.util.Base64
+import java.util.Locale
+import java.util.concurrent.ConcurrentHashMap
+import javax.net.ssl.SSLContext
+import javax.net.ssl.SSLHandshakeException
+import javax.net.ssl.SSLPeerUnverifiedException
+import javax.net.ssl.SSLSocket
+import javax.net.ssl.X509TrustManager
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.withContext
+import okhttp3.HttpUrl
+import okhttp3.Interceptor
+import okhttp3.OkHttpClient
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+
+/**
+ * Produces Stalker clients without weakening the application-wide OkHttp client.
+ *
+ * The only relaxed client this class can create is bound to one normalized origin and one
+ * user-approved public key. The public-key check is repeated by both the trust manager and
+ * hostname verifier before any HTTP bytes are sent.
+ */
+class StalkerTransportFactory(
+ private val strictClient: OkHttpClient
+) {
+ private val approvedClients = ConcurrentHashMap<String, OkHttpClient>()
+ private val strictStalkerClient: OkHttpClient by lazy {
+ buildRedirectScopedClient(strictClient, null)
+ }
+
+ fun clientFor(url: String, grant: StalkerTransportGrant?): OkHttpClient {
+ val httpUrl = url.toHttpUrlOrNull()
+ ?: throw StalkerApiError.TransportConsentRequired(
+ invalidOriginChallenge(url)
+ )
+ val origin = httpUrl.toTransportOrigin()
+ if (httpUrl.isHttps) {
+ if (grant?.mode != StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS) {
+ if (grant == null) return strictStalkerClient
+ val key = "strict|${grant.mode}|${grant.origin.authority}|${grant.spkiSha256.orEmpty()}"
+ return approvedClients.computeIfAbsent(key) {
+ buildRedirectScopedClient(strictClient, grant)
+ }
+ }
+ requireMatchingGrant(origin, grant)
+ val expectedPin = grant.spkiSha256?.takeIf { it.isNotBlank() }
+ ?: throw StalkerApiError.TransportConsentRequired(
+ tlsChallenge(origin, null, "MISSING_APPROVED_KEY")
+ )
+ val key = "${origin.authority}|$expectedPin"
+ return approvedClients.computeIfAbsent(key) {
+ buildPinnedUnverifiedClient(origin, expectedPin)
+ }
+ }
+
+ if (grant?.mode != StalkerTransportMode.USER_ACCEPTED_HTTP) {
+ throw StalkerApiError.TransportConsentRequired(
+ StalkerTransportChallenge(
+ reason = StalkerTransportChallengeReason.CLEARTEXT_HTTP,
+ origin = origin,
+ displayHost = origin.displayHost(),
+ detailCode = "CLEARTEXT_REQUIRES_CONSENT"
+ )
+ )
+ }
+ requireMatchingGrant(origin, grant)
+ val key = "http|${origin.authority}"
+ return approvedClients.computeIfAbsent(key) {
+ buildRedirectScopedClient(strictClient, grant)
+ }
+ }
+
+ suspend fun challengeForTlsFailure(url: String, error: Throwable): StalkerTransportChallenge? {
+ if (!error.isTlsIdentityFailure()) return null
+ val httpUrl = url.toHttpUrlOrNull()?.takeIf(HttpUrl::isHttps) ?: return null
+ val origin = httpUrl.toTransportOrigin()
+ val pin = probeSpki(origin)
+ return tlsChallenge(
+ origin = origin,
+ spkiSha256 = pin,
+ detailCode = when (error) {
+ is SSLPeerUnverifiedException -> "HOSTNAME_OR_PEER_UNVERIFIED"
+ else -> "CERTIFICATE_CHAIN_UNVERIFIED"
+ }
+ )
+ }
+
+ private fun requireMatchingGrant(
+ origin: StalkerTransportOrigin,
+ grant: StalkerTransportGrant
+ ) {
+ if (grant.origin.normalized() != origin.normalized()) {
+ throw StalkerApiError.TransportConsentRequired(
+ StalkerTransportChallenge(
+ reason = StalkerTransportChallengeReason.ORIGIN_CHANGED,
+ origin = origin,
+ displayHost = origin.displayHost(),
+ detailCode = "TRANSPORT_ORIGIN_CHANGED"
+ )
+ )
+ }
+ }
+
+ private fun buildPinnedUnverifiedClient(
+ origin: StalkerTransportOrigin,
+ expectedPin: String
+ ): OkHttpClient {
+ val trustManager = object : X509TrustManager {
+ override fun checkClientTrusted(
+ chain: Array<out X509Certificate>?,
+ authType: String?
+ ) = Unit
+
+ override fun checkServerTrusted(
+ chain: Array<out X509Certificate>?,
+ authType: String?
+ ) {
+ val leaf = chain?.firstOrNull()
+ ?: throw CertificateException("Portal did not present a certificate.")
+ if (leaf.spkiSha256() != expectedPin) {
+ throw CertificateException("Portal certificate public key changed.")
+ }
+ }
+
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
+ }
+ val sslContext = SSLContext.getInstance("TLS").apply {
+ init(null, arrayOf(trustManager), SecureRandom())
+ }
+ val pinnedClient = strictClient.newBuilder()
+ .sslSocketFactory(sslContext.socketFactory, trustManager)
+ .hostnameVerifier { hostname, session ->
+ if (!hostname.equals(origin.host, ignoreCase = true)) {
+ false
+ } else {
+ runCatching {
+ (session.peerCertificates.firstOrNull() as? X509Certificate)
+ ?.spkiSha256() == expectedPin
+ }.getOrDefault(false)
+ }
+ }
+ .build()
+ return buildRedirectScopedClient(pinnedClient, null)
+ }
+
+ private fun buildRedirectScopedClient(
+ base: OkHttpClient,
+ acceptedRedirectGrant: StalkerTransportGrant?
+ ): OkHttpClient = base.newBuilder()
+ .followRedirects(false)
+ .followSslRedirects(false)
+ .addInterceptor(StalkerRedirectInterceptor(acceptedRedirectGrant))
+ .build()
+
+ /**
+ * Performs TLS only, with no HTTP request and therefore no MAC, credentials, cookies, or
+ * custom headers. The returned key is public certificate material used to populate the
+ * foreground consent challenge.
+ */
+ private suspend fun probeSpki(origin: StalkerTransportOrigin): String? =
+ withContext(Dispatchers.IO) {
+ runCatching {
+ val captureManager = object : X509TrustManager {
+ override fun checkClientTrusted(
+ chain: Array<out X509Certificate>?,
+ authType: String?
+ ) = Unit
+
+ override fun checkServerTrusted(
+ chain: Array<out X509Certificate>?,
+ authType: String?
+ ) = Unit
+
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
+ }
+ val sslContext = SSLContext.getInstance("TLS").apply {
+ init(null, arrayOf(captureManager), SecureRandom())
+ }
+ Socket().use { raw ->
+ raw.connect(InetSocketAddress(origin.host, origin.port), PROBE_TIMEOUT_MILLIS)
+ raw.soTimeout = PROBE_TIMEOUT_MILLIS
+ (sslContext.socketFactory.createSocket(
+ raw,
+ origin.host,
+ origin.port,
+ true
+ ) as SSLSocket).use { tls ->
+ tls.startHandshake()
+ (tls.session.peerCertificates.firstOrNull() as? X509Certificate)
+ ?.spkiSha256()
+ }
+ }
+ }.getOrNull()
+ }
+
+ private fun invalidOriginChallenge(raw: String): StalkerTransportChallenge =
+ StalkerTransportChallenge(
+ reason = StalkerTransportChallengeReason.ORIGIN_CHANGED,
+ origin = StalkerTransportOrigin("https", "invalid", 443),
+ displayHost = raw.take(128),
+ detailCode = "INVALID_PORTAL_ORIGIN"
+ )
+
+ private fun tlsChallenge(
+ origin: StalkerTransportOrigin,
+ spkiSha256: String?,
+ detailCode: String
+ ): StalkerTransportChallenge = StalkerTransportChallenge(
+ reason = StalkerTransportChallengeReason.INVALID_TLS,
+ origin = origin,
+ displayHost = origin.displayHost(),
+ proposedSpkiSha256 = spkiSha256,
+ detailCode = detailCode
+ )
+
+ private companion object {
+ const val PROBE_TIMEOUT_MILLIS = 5_000
+ }
+}
+
+private class StalkerRedirectInterceptor(
+ private val acceptedRedirectGrant: StalkerTransportGrant?
+) : Interceptor {
+ override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
+ var request = chain.request()
+ repeat(MAX_REDIRECTS + 1) { hop ->
+ val response = chain.proceed(request)
+ if (response.code !in REDIRECT_CODES) return response
+ if (hop >= MAX_REDIRECTS) {
+ response.close()
+ throw IOException("Stalker redirect limit exceeded.")
+ }
+ val target = response.header("Location")
+ ?.let(request.url::resolve)
+ ?: return response
+ val sourceOrigin = request.url.toTransportOrigin()
+ val targetOrigin = target.toTransportOrigin()
+ val sameOrigin = sourceOrigin.normalized() == targetOrigin.normalized()
+ if (!sameOrigin && acceptedRedirectGrant?.origin?.normalized() != targetOrigin.normalized()) {
+ response.close()
+ throw StalkerApiError.TransportConsentRequired(
+ StalkerTransportChallenge(
+ reason = StalkerTransportChallengeReason.ORIGIN_CHANGED,
+ origin = targetOrigin,
+ displayHost = targetOrigin.displayHost(),
+ detailCode = "CROSS_ORIGIN_REDIRECT"
+ )
+ )
+ }
+ response.close()
+ request = request.newBuilder()
+ .url(target)
+ .apply {
+ if (!sameOrigin) {
+ SENSITIVE_REDIRECT_HEADERS.forEach(::removeHeader)
+ }
+ }
+ .build()
+ }
+ throw IOException("Stalker redirect limit exceeded.")
+ }
+
+ private companion object {
+ const val MAX_REDIRECTS = 5
+ val REDIRECT_CODES = setOf(300, 301, 302, 303, 307, 308)
+ val SENSITIVE_REDIRECT_HEADERS = listOf(
+ "Authorization",
+ "Cookie",
+ "X-User-Agent",
+ "X-Device-Id",
+ "X-Signature"
+ )
+ }
+}
+
+internal fun HttpUrl.toTransportOrigin(): StalkerTransportOrigin =
+ StalkerTransportOrigin(
+ scheme = scheme.lowercase(Locale.ROOT),
+ host = host.lowercase(Locale.ROOT),
+ port = port
+ )
+
+internal fun StalkerTransportOrigin.normalized(): StalkerTransportOrigin = copy(
+ scheme = scheme.lowercase(Locale.ROOT),
+ host = host.lowercase(Locale.ROOT)
+)
+
+internal fun StalkerTransportOrigin.displayHost(): String {
+ val defaultPort = (scheme.equals("https", true) && port == 443) ||
+ (scheme.equals("http", true) && port == 80)
+ return if (defaultPort) host else "$host:$port"
+}
+
+internal fun X509Certificate.spkiSha256(): String =
+ "sha256/" + Base64.getEncoder().encodeToString(
+ MessageDigest.getInstance("SHA-256").digest(publicKey.encoded)
+ )
+
+internal fun Throwable.isTlsIdentityFailure(): Boolean =
+ generateSequence(this) { it.cause }.any { cause ->
+ cause is SSLHandshakeException ||
+ cause is SSLPeerUnverifiedException ||
+ cause is CertificateException
+ }
diff --git a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerUrlFactory.kt b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerUrlFactory.kt
index f3c567e6..60301b50 100644
--- a/data/src/main/java/com/streamvault/data/remote/stalker/StalkerUrlFactory.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stalker/StalkerUrlFactory.kt
@@ -29,7 +29,10 @@ object StalkerUrlFactory {
private const val INTERNAL_SCHEME = "stalker"
fun normalizePortalUrl(url: String): String =
- url.trim().trimEnd('/')
+ url.trim()
+ .substringBefore('#')
+ .substringBefore('?')
+ .trimEnd('/')
fun loadUrlCandidates(portalUrl: String): List<String> {
val normalized = normalizePortalUrl(portalUrl)
@@ -40,6 +43,13 @@ object StalkerUrlFactory {
candidates += normalized
}
+ direct.endsWith("/c/index.html") || direct.endsWith("/c/index.htm") -> {
+ val suffix = if (direct.endsWith("/c/index.html")) "/c/index.html" else "/c/index.htm"
+ val base = normalized.dropLast(suffix.length)
+ candidates += "$base/server/load.php"
+ candidates += "$base/portal.php"
+ }
+
direct.endsWith("/c") -> {
val base = normalized.removeSuffix("/c")
candidates += "$base/server/load.php"
@@ -47,15 +57,31 @@ object StalkerUrlFactory {
}
else -> {
+ // Prefer the modern Ministra API family (server/load.php) across the known
+ // install locations before falling back to the legacy portal.php endpoints.
candidates += "$normalized/server/load.php"
- candidates += "$normalized/portal.php"
candidates += "${normalized.trimEnd('/')}/stalker_portal/server/load.php"
+ candidates += "$normalized/portal.php"
candidates += "${normalized.trimEnd('/')}/stalker_portal/portal.php"
}
}
return candidates.toList()
}
+ /**
+ * True when the user supplied only a portal base (host or custom path) rather than an
+ * explicit API script (`server/load.php`, `portal.php`) or launcher client path (`/c…`).
+ * Only bare bases benefit from probing `/` for a redirect that reveals the install path.
+ */
+ fun isBarePortalBase(portalUrl: String): Boolean {
+ val direct = normalizePortalUrl(portalUrl).lowercase(Locale.ROOT)
+ return !direct.endsWith("/server/load.php") &&
+ !direct.endsWith("/portal.php") &&
+ !direct.endsWith("/c") &&
+ !direct.endsWith("/c/index.html") &&
+ !direct.endsWith("/c/index.htm")
+ }
+
fun portalReferer(loadUrl: String): String {
val normalized = normalizePortalUrl(loadUrl)
return when {
diff --git a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
index 2dbea406..ddc54ead 100644
--- a/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
+++ b/data/src/main/java/com/streamvault/data/remote/xtream/XtreamStreamUrlResolver.kt
@@ -17,6 +17,7 @@ import com.streamvault.data.security.CredentialCrypto
import com.streamvault.data.util.UrlSecurityPolicy
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.LiveStreamFormatMode
+import com.streamvault.domain.model.PlaybackTransportPolicy
import com.streamvault.domain.model.StalkerAuthMode
import com.streamvault.domain.model.StalkerBootstrapRecipe
import com.streamvault.domain.model.StalkerCookieMode
@@ -25,6 +26,9 @@ import com.streamvault.domain.model.StalkerMagPreset
import com.streamvault.domain.model.StalkerPlaybackBackendHint
import com.streamvault.domain.model.StalkerPortalFingerprint
import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
import java.net.URI
import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
@@ -37,6 +41,7 @@ data class ResolvedStreamUrl(
val containerExtension: String? = null,
val headers: Map<String, String> = emptyMap(),
val userAgent: String? = null,
+ val playbackTransportPolicy: PlaybackTransportPolicy? = null,
val allowInvalidSsl: Boolean = false,
val proxyHost: String = "",
val proxyPort: Int? = null
@@ -71,6 +76,10 @@ class XtreamStreamUrlResolver @Inject constructor(
val deviceId2: String,
val signature: String,
val stalkerAdvancedOptionsJson: String,
+ val transportMode: StalkerTransportMode,
+ val transportOrigin: String,
+ val tlsSpkiSha256: String,
+ val transportConsentAt: Long,
val provider: StalkerProvider
)
@@ -209,6 +218,7 @@ class XtreamStreamUrlResolver @Inject constructor(
containerExtension = token.containerExtension ?: fallbackContainerExtension,
headers = playbackInfo.headers,
userAgent = playbackInfo.userAgent,
+ playbackTransportPolicy = playbackInfo.transportPolicy,
allowInvalidSsl = playbackInfo.allowInvalidSsl,
proxyHost = playbackInfo.proxyHost,
proxyPort = playbackInfo.proxyPort
@@ -346,6 +356,7 @@ class XtreamStreamUrlResolver @Inject constructor(
containerExtension = fallbackContainerExtension,
headers = playbackInfo.headers,
userAgent = playbackInfo.userAgent,
+ playbackTransportPolicy = playbackInfo.transportPolicy,
allowInvalidSsl = playbackInfo.allowInvalidSsl,
proxyHost = playbackInfo.proxyHost,
proxyPort = playbackInfo.proxyPort
@@ -430,7 +441,11 @@ class XtreamStreamUrlResolver @Inject constructor(
cached.deviceId == provider.stalkerDeviceId &&
cached.deviceId2 == provider.stalkerDeviceId2 &&
cached.signature == provider.stalkerSignature &&
- cached.stalkerAdvancedOptionsJson == provider.stalkerAdvancedOptionsJson
+ cached.stalkerAdvancedOptionsJson == provider.stalkerAdvancedOptionsJson &&
+ cached.transportMode == provider.stalkerTransportMode &&
+ cached.transportOrigin == provider.stalkerTransportOrigin &&
+ cached.tlsSpkiSha256 == provider.stalkerTlsSpkiSha256 &&
+ cached.transportConsentAt == provider.stalkerTransportConsentAt
) {
return cached.provider
}
@@ -462,7 +477,11 @@ class XtreamStreamUrlResolver @Inject constructor(
deviceId = provider.stalkerDeviceId,
deviceId2 = provider.stalkerDeviceId2,
signature = provider.stalkerSignature,
- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson
+ stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,
+ protocolPreference = provider.stalkerProtocolPreference,
+ transportGrant = provider.toStalkerTransportGrant(),
+ requestedProfileId = provider.stalkerRequestedProfileId,
+ learnedProfileId = provider.stalkerLearnedProfileId
)
stalkerProviders[providerId] = CachedStalkerProvider(
serverUrl = provider.serverUrl,
@@ -486,6 +505,10 @@ class XtreamStreamUrlResolver @Inject constructor(
deviceId2 = provider.stalkerDeviceId2,
signature = provider.stalkerSignature,
stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,
+ transportMode = provider.stalkerTransportMode,
+ transportOrigin = provider.stalkerTransportOrigin,
+ tlsSpkiSha256 = provider.stalkerTlsSpkiSha256,
+ transportConsentAt = provider.stalkerTransportConsentAt,
provider = resolvedProvider
)
return resolvedProvider
@@ -508,6 +531,39 @@ class XtreamStreamUrlResolver @Inject constructor(
}
}
+private fun ProviderEntity.toStalkerTransportGrant(): StalkerTransportGrant? {
+ if (stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_HTTP &&
+ stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS &&
+ stalkerTransportMode != StalkerTransportMode.VERIFIED_HTTPS
+ ) {
+ return null
+ }
+ val origin = stalkerTransportOrigin.toStalkerTransportOrigin()
+ ?: serverUrl.toStalkerTransportOrigin()
+ ?: return null
+ val pin = stalkerTlsSpkiSha256.takeIf(String::isNotBlank)
+ if (stalkerTransportMode == StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS && pin == null) {
+ return null
+ }
+ return StalkerTransportGrant(
+ mode = stalkerTransportMode,
+ origin = origin,
+ spkiSha256 = pin,
+ consentedAt = stalkerTransportConsentAt
+ )
+}
+
+private fun String.toStalkerTransportOrigin(): StalkerTransportOrigin? {
+ val normalized = trim()
+ val uri = runCatching { URI(normalized) }.getOrNull()
+ ?.takeIf { it.scheme != null }
+ ?: return null
+ val scheme = uri.scheme?.lowercase()?.takeIf { it == "http" || it == "https" } ?: return null
+ val host = uri.host?.lowercase()?.takeIf(String::isNotBlank) ?: return null
+ val port = uri.port.takeIf { it > 0 } ?: if (scheme == "https") 443 else 80
+ return StalkerTransportOrigin(scheme, host, port)
+}
+
internal fun extractStreamExpirationTime(url: String): Long? {
val query = runCatching { URI(url).rawQuery }.getOrNull()
?: url.substringAfter('?', missingDelimiterValue = "").takeIf { it.isNotBlank() }
diff --git a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
index f13d0e6d..bb6020fc 100644
--- a/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ChannelRepositoryImpl.kt
@@ -259,6 +259,7 @@ class ChannelRepositoryImpl @Inject constructor(
title = channel.name,
headers = resolvedStream.headers,
userAgent = resolvedStream.userAgent,
+ playbackTransportPolicy = resolvedStream.playbackTransportPolicy,
allowInvalidSsl = resolvedStream.allowInvalidSsl,
proxyHost = resolvedStream.proxyHost,
proxyPort = resolvedStream.proxyPort,
diff --git a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
index 129099d8..06a83afd 100644
--- a/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/MovieRepositoryImpl.kt
@@ -22,6 +22,11 @@ import com.streamvault.data.remote.http.toGenericRequestProfile
import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.stalker.StalkerPlaybackMode
import com.streamvault.data.remote.stalker.StalkerProvider
+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver
+import com.streamvault.data.remote.stalker.StalkerRequestCoordinator
+import com.streamvault.data.remote.stalker.StalkerRequestDescriptor
+import com.streamvault.data.remote.stalker.StalkerResponseMetrics
+import com.streamvault.data.remote.stalker.StalkerPortalStateStore
import com.streamvault.data.remote.stalker.StalkerTrafficCoordinator
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamStreamUrlResolver
@@ -47,6 +52,7 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Result.Success
import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.StreamType
+import com.streamvault.domain.model.StalkerRequestPriority
import com.streamvault.domain.model.VodDuplicateConfidence
import com.streamvault.domain.model.VodDuplicateHandlingMode
import com.streamvault.domain.model.VodMovieVariant
@@ -94,7 +100,10 @@ class MovieRepositoryImpl @Inject constructor(
private val xtreamContentIndexDao: XtreamContentIndexDao,
private val xtreamIndexJobDao: XtreamIndexJobDao,
private val syncManager: SyncManager,
- private val transactionRunner: DatabaseTransactionRunner
+ private val transactionRunner: DatabaseTransactionRunner,
+ private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,
+ private val stalkerRequestCoordinator: StalkerRequestCoordinator,
+ private val stalkerPortalStateStore: StalkerPortalStateStore
) : MovieRepository {
private companion object {
const val TAG = "MovieRepository"
@@ -107,6 +116,8 @@ class MovieRepositoryImpl @Inject constructor(
const val CURSOR_BATCH_SIZE = 40
const val STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLD = 24
const val STALKER_PREVIEW_MAX_REMOTE_PAGES = 2
+ const val STALKER_INITIAL_CATEGORY_FILL_COUNT = 40
+ const val STALKER_INITIAL_CATEGORY_MAX_REMOTE_PAGES = 4
const val DETAIL_REFRESH_TTL_MILLIS = 14L * 24L * 60L * 60L * 1000L
const val CACHE_STATE_SUMMARY_ONLY = "SUMMARY_ONLY"
const val CACHE_STATE_DETAIL_HYDRATED = "DETAIL_HYDRATED"
@@ -183,7 +194,13 @@ class MovieRepositoryImpl @Inject constructor(
limit: Int,
offset: Int
): Flow<List<Movie>> = flow {
- ensureXtreamCategoryLoaded(providerId, categoryId, fetchIfMissing = true, refreshStaleInBackground = true)
+ ensureXtreamCategoryLoaded(
+ providerId,
+ categoryId,
+ fetchIfMissing = true,
+ refreshStaleInBackground = true,
+ requiredCount = offset + limit
+ )
emitAll(
combine(
movieDao.getByCategoryPage(providerId, categoryId, limit, offset),
@@ -203,7 +220,13 @@ class MovieRepositoryImpl @Inject constructor(
override fun getMoviesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Movie>> =
flow {
- ensureXtreamCategoryLoaded(providerId, categoryId, fetchIfMissing = true, refreshStaleInBackground = true)
+ ensureXtreamCategoryLoaded(
+ providerId,
+ categoryId,
+ fetchIfMissing = true,
+ refreshStaleInBackground = true,
+ requiredCount = limit
+ )
emitAll(
combine(
movieDao.getByCategoryPreview(providerId, categoryId, limit),
@@ -247,16 +270,14 @@ class MovieRepositoryImpl @Inject constructor(
return@channelFlow
}
previewCategories.forEach { category ->
- launch(Dispatchers.IO) {
- ensureXtreamCategoryLoaded(
- providerId = providerId,
- categoryId = category.categoryId,
- fetchIfMissing = true,
- refreshStaleInBackground = false,
- requiredCount = limitPerCategory,
- allowStalkerWildcard = false
- )
- }
+ triggerXtreamCategoryHydration(
+ providerId = providerId,
+ categoryId = category.categoryId,
+ fetchIfMissing = true,
+ refreshStaleInBackground = false,
+ requiredCount = limitPerCategory,
+ allowStalkerWildcard = false
+ )
}
// SQL LIMIT applied per-category — avoids loading the full catalog into memory
val categoryGroupFlows: List<Flow<Pair<Long?, List<Movie>>>> = previewCategories.map { cat ->
@@ -384,7 +405,8 @@ class MovieRepositoryImpl @Inject constructor(
it,
fetchIfMissing = true,
refreshStaleInBackground = true,
- requiredCount = browseFetchLimit(query)
+ requiredCount = browseFetchLimit(query),
+ loadStalkerCategoryCompletely = true
)
}
emit(fetchMovieBrowseResult(query))
@@ -528,6 +550,7 @@ class MovieRepositoryImpl @Inject constructor(
title = movie.name,
headers = resolvedStream.headers,
userAgent = resolvedStream.userAgent,
+ playbackTransportPolicy = resolvedStream.playbackTransportPolicy,
allowInvalidSsl = resolvedStream.allowInvalidSsl,
proxyHost = resolvedStream.proxyHost,
proxyPort = resolvedStream.proxyPort,
@@ -1441,7 +1464,8 @@ class MovieRepositoryImpl @Inject constructor(
refreshStaleInBackground: Boolean = false,
forceRefresh: Boolean = false,
requiredCount: Int = SEARCH_RESULT_LIMIT,
- allowStalkerWildcard: Boolean = true
+ allowStalkerWildcard: Boolean = true,
+ loadStalkerCategoryCompletely: Boolean = false
) {
val key = "$providerId:$categoryId"
val provider = providerDao.getById(providerId) ?: return
@@ -1458,10 +1482,13 @@ class MovieRepositoryImpl @Inject constructor(
return
}
if (provider.type == ProviderType.STALKER_PORTAL) {
- if (localCount <= 0) {
- syncManager.prioritizeStalkerIndexCategory(providerId, ContentType.MOVIE, categoryId)
- }
- if (!shouldUseStalkerLazyFallback(providerId, hydration, localCount)) {
+ if (!shouldUseStalkerLazyFallback(
+ hydration = hydration,
+ localCount = localCount,
+ requiredCount = requiredCount,
+ loadCompletely = loadStalkerCategoryCompletely
+ )
+ ) {
return
}
hydrateStalkerMovieCategoryToCount(
@@ -1471,7 +1498,8 @@ class MovieRepositoryImpl @Inject constructor(
requiredCount = requiredCount,
localCount = localCount,
hydration = hydration,
- allowWildcard = allowStalkerWildcard
+ allowWildcard = allowStalkerWildcard,
+ loadCompletely = loadStalkerCategoryCompletely
)
return
}
@@ -1499,10 +1527,7 @@ class MovieRepositoryImpl @Inject constructor(
val localCount = movieDao.getCountByCategory(providerId, categoryId).first()
val hydration = movieCategoryHydrationDao.get(providerId, categoryId)
if (provider.type == ProviderType.STALKER_PORTAL) {
- if (localCount <= 0) {
- syncManager.prioritizeStalkerIndexCategory(providerId, ContentType.MOVIE, categoryId)
- }
- if (!shouldUseStalkerLazyFallback(providerId, hydration, localCount)) {
+ if (!shouldUseStalkerLazyFallback(hydration, localCount, requiredCount)) {
return@launch
}
hydrateStalkerMovieCategoryToCount(
@@ -1522,20 +1547,23 @@ class MovieRepositoryImpl @Inject constructor(
}
}
- private suspend fun shouldUseStalkerLazyFallback(
- providerId: Long,
+ private fun shouldUseStalkerLazyFallback(
hydration: MovieCategoryHydrationEntity?,
- localCount: Int
+ localCount: Int,
+ requiredCount: Int,
+ loadCompletely: Boolean = false
): Boolean {
val now = System.currentTimeMillis()
- if (localCount > 0) return false
+ val hasEmptySuccessfulCheckpoint = localCount == 0 &&
+ (hydration?.lastSuccessfulPage ?: hydration?.lastLoadedPage ?: 0) > 0
+ if (hasEmptySuccessfulCheckpoint) return true
if (hydration?.isComplete == true) return false
+ if (hydration?.lastStatus == "TRUNCATED" && !loadCompletely) return false
+ if (loadCompletely) return true
+ if (localCount >= requiredCount) return false
if (hydration?.lastStatus in setOf("FAILED_PERMANENT", "FAILED_BUDGET_EXHAUSTED")) return true
if (hydration?.retryBudgetRemaining == 0 && hydration.retryAfterMs <= now) return true
- return when (xtreamIndexJobDao.get(providerId, ContentType.MOVIE.name)?.state) {
- null, "FAILED_PERMANENT" -> true
- else -> false
- }
+ return true
}
private suspend fun hydrateStalkerMovieCategoryToCount(
@@ -1545,7 +1573,8 @@ class MovieRepositoryImpl @Inject constructor(
requiredCount: Int,
localCount: Int? = null,
hydration: MovieCategoryHydrationEntity? = null,
- allowWildcard: Boolean = true
+ allowWildcard: Boolean = true,
+ loadCompletely: Boolean = false
) {
val key = "$providerId:$categoryId"
val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }
@@ -1554,27 +1583,75 @@ class MovieRepositoryImpl @Inject constructor(
if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.MOVIE, categoryId)) return
var currentCount = localCount ?: movieDao.getCountByCategory(providerId, categoryId).first()
var currentHydration = hydration ?: movieCategoryHydrationDao.get(providerId, categoryId)
- if (currentHydration?.isComplete == true || currentCount >= requiredCount) return
+ if ((currentHydration?.isComplete == true && currentCount > 0) ||
+ (!loadCompletely && currentCount >= requiredCount)
+ ) return
if (currentCount == 0 && currentHydration?.isEmptyRetryCoolingDown() == true) return
val isPreviewLoad = requiredCount <= STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLD
- var nextPage = when (currentHydration?.lastStatus) {
- "FAILED_RETRYABLE", "COOLDOWN", "ANOMALY" -> currentHydration?.lastAttemptedPage?.coerceAtLeast(1) ?: 1
- else -> ((currentHydration?.lastSuccessfulPage ?: currentHydration?.lastLoadedPage ?: 0) + 1).coerceAtLeast(1)
+ val isInitialCategoryFill = !isPreviewLoad && currentCount < STALKER_INITIAL_CATEGORY_FILL_COUNT
+ val targetCount = when {
+ loadCompletely -> Int.MAX_VALUE
+ isInitialCategoryFill -> minOf(requiredCount, STALKER_INITIAL_CATEGORY_FILL_COUNT)
+ else -> requiredCount
+ }
+ val maxRemotePages = when {
+ loadCompletely -> Int.MAX_VALUE
+ isPreviewLoad -> STALKER_PREVIEW_MAX_REMOTE_PAGES
+ isInitialCategoryFill -> STALKER_INITIAL_CATEGORY_MAX_REMOTE_PAGES
+ else -> 1
+ }
+ var nextPage = when {
+ currentCount == 0 && (currentHydration?.lastSuccessfulPage ?: 0) > 0 -> 1
+ currentHydration?.lastStatus in setOf("FAILED_RETRYABLE", "COOLDOWN", "ANOMALY") ->
+ currentHydration?.lastAttemptedPage?.coerceAtLeast(1) ?: 1
+ else ->
+ ((currentHydration?.lastSuccessfulPage ?: currentHydration?.lastLoadedPage ?: 0) + 1)
+ .coerceAtLeast(1)
}
// The cached totalPages can under-report when the preview hydrate stored
// it from a partial response. Skip the pre-fetch guard on the first
// iteration so we always perform at least one real fetch that refreshes
// totalPages; subsequent iterations use the in-loop updated value.
var firstIteration = true
- while (currentCount < requiredCount) {
- if (StalkerTrafficCoordinator.shouldDeferCatalogFetch(providerId)) break
+ var remotePagesRequested = 0
+ while (currentCount < targetCount) {
val attemptStartedAt = System.currentTimeMillis()
if (isPreviewLoad && nextPage > STALKER_PREVIEW_MAX_REMOTE_PAGES) break
+ if (remotePagesRequested >= maxRemotePages) break
val totalPages = currentHydration?.totalPages ?: 0
if (!firstIteration && totalPages > 0 && nextPage > totalPages) break
firstIteration = false
- when (val result = stalkerProvider.getVodStreamsPage(categoryId, nextPage)) {
+ remotePagesRequested += 1
+ val requestPriority = if (isPreviewLoad) {
+ StalkerRequestPriority.VISIBLE_PREVIEW
+ } else {
+ StalkerRequestPriority.OPEN_CATEGORY
+ }
+ val coordinatedResult = stalkerRequestCoordinator.execute(
+ providerId = providerId,
+ priority = requestPriority,
+ descriptor = StalkerRequestDescriptor(
+ contentType = "MOVIE",
+ action = "CATEGORY_PAGE",
+ categoryKey = categoryId.toString(),
+ page = nextPage
+ ),
+ metricsOf = { result ->
+ val page = (result as? Success)?.data
+ StalkerResponseMetrics(
+ items = page?.items?.size,
+ pages = page?.page,
+ advertisedTotal = page?.advertisedTotalItems,
+ truncated = page?.isTruncated,
+ terminationReason = page?.terminationReason
+ )
+ }
+ ) { stalkerProvider.getVodStreamsPage(categoryId, nextPage) }
+ if (coordinatedResult is Result.Error) {
+ stalkerRequestCoordinator.recordFailure(providerId, coordinatedResult.exception)
+ }
+ when (val result = coordinatedResult) {
is Success -> {
val entities = result.data.items.map { movie -> movie.toEntity() }
val pageComplete = result.data.isComplete || entities.isEmpty()
@@ -1587,7 +1664,7 @@ class MovieRepositoryImpl @Inject constructor(
categoryId = categoryId,
lastHydratedAt = attemptStartedAt,
itemCount = updatedCount,
- lastStatus = "SUCCESS",
+ lastStatus = if (result.data.isTruncated) "TRUNCATED" else "SUCCESS",
lastError = null,
lastLoadedPage = result.data.page,
lastAttemptedPage = result.data.page,
@@ -1739,7 +1816,12 @@ class MovieRepositoryImpl @Inject constructor(
deviceId = provider.stalkerDeviceId,
deviceId2 = provider.stalkerDeviceId2,
signature = provider.stalkerSignature,
- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson
+ stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,
+ protocolPreference = provider.stalkerProtocolPreference,
+ requestedProfileId = provider.stalkerRequestedProfileId,
+ learnedProfileId = provider.stalkerLearnedProfileId,
+ identityResolver = stalkerRemoteIdentityResolver,
+ portalStateStore = stalkerPortalStateStore
)
}
diff --git a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
index b434d173..67d2200d 100644
--- a/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/ProviderRepositoryImpl.kt
@@ -3,6 +3,8 @@ package com.streamvault.data.repository
import com.streamvault.data.local.DatabaseTransactionRunner
import com.streamvault.data.local.dao.*
import com.streamvault.data.local.entity.ProviderEntity
+import com.streamvault.data.local.entity.StalkerDiscoveryStageEntity
+import com.streamvault.data.local.entity.StalkerIndexJobEntity
import com.streamvault.data.manager.recording.RecordingAlarmScheduler
import com.streamvault.data.manager.reminder.ProgramReminderAlarmScheduler
import com.streamvault.data.mapper.*
@@ -12,6 +14,10 @@ import com.streamvault.data.remote.jellyfin.JellyfinProvider
import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.stalker.StalkerPlaybackMode
import com.streamvault.data.remote.stalker.StalkerProvider
+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver
+import com.streamvault.data.remote.stalker.StalkerPortalStateStore
+import com.streamvault.data.remote.stalker.StalkerCompatibilityRegistry
+import com.streamvault.data.remote.stalker.StalkerApiError
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
import com.streamvault.data.security.CredentialCrypto
@@ -38,6 +44,9 @@ import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
+import java.io.IOException
+import java.net.URI
+import java.util.UUID
import java.util.logging.Logger
import javax.inject.Inject
import javax.inject.Singleton
@@ -61,7 +70,13 @@ class ProviderRepositoryImpl @Inject constructor(
private val transactionRunner: DatabaseTransactionRunner,
private val recordingAlarmScheduler: RecordingAlarmScheduler,
private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler,
- private val jellyfinProvider: JellyfinProvider
+ private val jellyfinProvider: JellyfinProvider,
+ private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,
+ private val stalkerIndexJobDao: StalkerIndexJobDao,
+ private val stalkerPortalStateStore: StalkerPortalStateStore,
+ private val movieCategoryHydrationDao: MovieCategoryHydrationDao,
+ private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao,
+ private val stalkerDiscoveryStageDao: StalkerDiscoveryStageDao? = null
) : ProviderRepository {
private companion object {
const val XTREAM_GUIDE_BATCH_CONCURRENCY = 4
@@ -71,7 +86,9 @@ class ProviderRepositoryImpl @Inject constructor(
const val ALARM_STEP_WEIGHT = 5
const val PROVIDER_ROW_STEP_WEIGHT = 200
const val FINALIZE_STEP_WEIGHT = 200
+ const val STALKER_DISCOVERY_STAGE_TTL_MILLIS = 60L * 60L * 1000L
val logger: Logger = Logger.getLogger(ProviderRepositoryImpl::class.java.name)
+ val STALKER_URL_SCHEME_REGEX = Regex("^[a-zA-Z][a-zA-Z0-9+.-]*://")
}
private val repositoryScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
@@ -94,11 +111,52 @@ class ProviderRepositoryImpl @Inject constructor(
override suspend fun updateProvider(provider: Provider): Result<Unit> = try {
providerDao.update(provider.toSecureEntity())
+ if (provider.type == ProviderType.STALKER_PORTAL) {
+ stalkerPortalStateStore.invalidate(provider.id)
+ }
+ if (provider.type == ProviderType.STALKER_PORTAL &&
+ provider.stalkerCatalogMode == StalkerCatalogMode.ON_DEMAND
+ ) {
+ stalkerIndexJobDao.disableForProvider(provider.id, System.currentTimeMillis())
+ syncManager.cancelStalkerIndexSync(provider.id)
+ }
Result.success(Unit)
} catch (e: Exception) {
Result.error("Failed to update provider: ${e.message}", e)
}
+ override suspend fun buildStalkerSearchIndexOnce(providerId: Long): Result<Unit> {
+ return try {
+ val provider = providerDao.getById(providerId)
+ ?: return Result.error("Provider not found")
+ if (provider.type != ProviderType.STALKER_PORTAL) {
+ return Result.error("Complete search indexing is only available for Stalker providers")
+ }
+ val now = System.currentTimeMillis()
+ transactionRunner.inTransaction {
+ // A manual rebuild is an explicit retry of every category, including rows
+ // previously marked COMPLETE, TRUNCATED, or terminally failed. Keep the
+ // current searchable content visible while resetting only crawl progress.
+ movieCategoryHydrationDao.deleteByProvider(providerId)
+ seriesCategoryHydrationDao.deleteByProvider(providerId)
+ listOf(ContentType.MOVIE, ContentType.SERIES).forEach { section ->
+ stalkerIndexJobDao.upsert(
+ StalkerIndexJobEntity(
+ providerId = providerId,
+ section = section,
+ state = StalkerIndexState.QUEUED,
+ updatedAt = now
+ )
+ )
+ }
+ }
+ syncManager.scheduleStalkerIndexSync(providerId, force = false)
+ Result.success(Unit)
+ } catch (error: Exception) {
+ Result.error("Failed to queue the complete Stalker search index", error)
+ }
+ }
+
override suspend fun getAllProviderCredentials(): List<ProviderCredentials> {
return providerDao.getAllSync()
.map { entity ->
@@ -125,6 +183,9 @@ class ProviderRepositoryImpl @Inject constructor(
} ?: return false
val encrypted = credentialCrypto.encryptIfNeeded(cleartextPassword)
providerDao.update(entity.copy(password = encrypted))
+ if (entity.type == ProviderType.STALKER_PORTAL) {
+ stalkerPortalStateStore.invalidate(entity.id)
+ }
return true
}
@@ -283,6 +344,7 @@ class ProviderRepositoryImpl @Inject constructor(
)
return when (val authResult = provider.authenticate()) {
is Result.Success -> {
+ onProgress?.invoke("Profile accepted; catalog validated")
val providerData = if (existingProvider != null) {
onProgress?.invoke("Updating existing provider...")
val updated = authResult.data.copy(
@@ -304,6 +366,7 @@ class ProviderRepositoryImpl @Inject constructor(
createdAt = existingProvider.createdAt
)
providerDao.update(updated.toSecureEntity())
+ stalkerPortalStateStore.invalidate(existingProvider.id)
updated.copy(password = "")
} else {
val newData = authResult.data.copy(
@@ -322,6 +385,11 @@ class ProviderRepositoryImpl @Inject constructor(
newData.copy(id = newId).copy(password = "")
}
+ if (providerData.stalkerCatalogMode == StalkerCatalogMode.ON_DEMAND) {
+ stalkerIndexJobDao.disableForProvider(providerData.id, System.currentTimeMillis())
+ syncManager.cancelStalkerIndexSync(providerData.id)
+ }
+
handleInitialOnboardingSync(
providerData = providerData,
syncResult = syncManager.sync(
@@ -559,7 +627,13 @@ class ProviderRepositoryImpl @Inject constructor(
deviceId2: String,
signature: String,
stalkerAdvancedOptionsJson: String,
+ protocolPreference: StalkerProtocolPreference,
+ transportGrant: StalkerTransportGrant?,
+ saveWithoutVerification: Boolean,
+ repairConnection: Boolean,
+ requestedProfileId: String,
epgSyncMode: ProviderEpgSyncMode,
+ catalogMode: StalkerCatalogMode,
guideSourcePolicy: GuideSourcePolicy,
channelLogoSourcePolicy: ChannelLogoSourcePolicy,
onProgress: ((String) -> Unit)?,
@@ -569,7 +643,13 @@ class ProviderRepositoryImpl @Inject constructor(
val normalizedMacAddress = ProviderInputSanitizer.normalizeMacAddress(macAddress)
val normalizedName = ProviderInputSanitizer.normalizeProviderName(name)
val normalizedUsername = ProviderInputSanitizer.normalizeUsername(username)
- val resolvedPortalUrl = ProviderInputSanitizer.resolveUrlProtocol(normalizedPortalUrl)
+ val inputHasScheme = STALKER_URL_SCHEME_REGEX.containsMatchIn(normalizedPortalUrl)
+ val resolvedPortalUrl = when {
+ inputHasScheme -> normalizedPortalUrl
+ transportGrant?.mode == StalkerTransportMode.USER_ACCEPTED_HTTP ->
+ "http://$normalizedPortalUrl"
+ else -> "https://$normalizedPortalUrl"
+ }
val normalizedDeviceProfile = ProviderInputSanitizer.normalizeDeviceProfile(deviceProfile)
val normalizedTimezone = ProviderInputSanitizer.normalizeTimezone(timezone)
val normalizedLocale = ProviderInputSanitizer.normalizeLocale(locale)
@@ -579,6 +659,21 @@ class ProviderRepositoryImpl @Inject constructor(
val normalizedSignature = ProviderInputSanitizer.normalizeStalkerSignature(signature)
val normalizedAdvancedOptionsJson = stalkerAdvancedOptionsJson.trim()
+ if (protocolPreference == StalkerProtocolPreference.MINISTRA_API_V3) {
+ return Result.error(
+ "This portal requires the licensed Ministra API-v3 flow. API-v3 activation is isolated from classic MAG and needs provider-issued OAuth/license configuration."
+ )
+ }
+ val requestedCompatibility = StalkerCompatibilityRegistry.find(requestedProfileId)
+ if (requestedCompatibility?.identityStrategy ==
+ com.streamvault.data.remote.stalker.StalkerIdentityStrategy.MANUAL_FIELDS_REQUIRED &&
+ normalizedSerialNumber.isBlank() && normalizedDeviceId.isBlank() && normalizedSignature.isBlank()
+ ) {
+ return Result.error(
+ "${requestedCompatibility.displayName} is experimental and has no verified hardware UID algorithm. Enter captured serial/device identity fields or use Automatic."
+ )
+ }
+
ProviderInputSanitizer.validateUrl(resolvedPortalUrl)?.let { message ->
return Result.error(message)
}
@@ -591,7 +686,9 @@ class ProviderRepositoryImpl @Inject constructor(
}
}
- onProgress?.invoke("Authenticating...")
+ val requestedProfileLabel = StalkerCompatibilityRegistry.find(requestedProfileId)?.displayName
+ ?: "Automatic MAG compatibility"
+ onProgress?.invoke("Trying $requestedProfileLabel")
val existingProvider = if (id != null) {
// Edit path: check that the new normalized identity does not collide with a
// different provider before we commit the update.
@@ -610,9 +707,25 @@ class ProviderRepositoryImpl @Inject constructor(
} catch (e: CredentialDecryptionException) {
return Result.error(e.message ?: CredentialDecryptionException.MESSAGE, e)
}
+ val effectiveTransportGrant = transportGrant
+ ?: existingProvider?.toStalkerTransportGrant()
+ ?: resolvedPortalUrl.toStalkerOrigin()
+ ?.takeIf { it.scheme == "https" }
+ ?.let { origin ->
+ StalkerTransportGrant(
+ mode = StalkerTransportMode.VERIFIED_HTTPS,
+ origin = origin,
+ consentedAt = 0L
+ )
+ }
+ val previousPortalState = existingProvider?.let {
+ stalkerPortalStateStore.get(it.id)
+ }
- val provider = createStalkerProvider(
- providerId = 0L,
+ fun discoveryProvider(requireLiveReadiness: Boolean) = createStalkerProvider(
+ // Ordinary edits validate with the learned identity. Only a new provider or
+ // the explicit Repair connection action may rotate compatibility profiles.
+ providerId = if (existingProvider == null || repairConnection) 0L else existingProvider.id,
portalUrl = resolvedPortalUrl,
macAddress = normalizedMacAddress,
authMode = authMode,
@@ -627,14 +740,55 @@ class ProviderRepositoryImpl @Inject constructor(
deviceId = normalizedDeviceId,
deviceId2 = normalizedDeviceId2,
signature = normalizedSignature,
- stalkerAdvancedOptionsJson = normalizedAdvancedOptionsJson
+ stalkerAdvancedOptionsJson = normalizedAdvancedOptionsJson,
+ protocolPreference = protocolPreference,
+ transportGrant = effectiveTransportGrant,
+ requestedProfileId = requestedProfileId,
+ requireCatalogValidation = requireLiveReadiness,
+ onProgress = onProgress
)
- return when (val authResult = provider.authenticate()) {
+ var authenticatedProvider = discoveryProvider(requireLiveReadiness = true)
+ var authResult = authenticatedProvider.authenticate()
+ var acceptedWithoutVerification = false
+ val readinessWasInconclusive = (authResult as? Result.Error)?.exception
+ ?.let { failure ->
+ generateSequence(failure) { it.cause }
+ .filterIsInstance<StalkerApiError.ReadinessInconclusive>()
+ .firstOrNull()
+ }
+ if (saveWithoutVerification && readinessWasInconclusive != null) {
+ onProgress?.invoke("Authentication confirmed; saving with Live TV verification pending")
+ authenticatedProvider = discoveryProvider(requireLiveReadiness = false)
+ authResult = authenticatedProvider.authenticate()
+ acceptedWithoutVerification = authResult is Result.Success
+ }
+
+ return when (val finalAuthResult = authResult) {
is Result.Success -> {
+ val validatedSnapshot = authenticatedProvider.validatedAuthenticationSnapshot()
+ val discoverySummary = validatedSnapshot?.toSanitizedDiscoverySummary().orEmpty()
+ val capabilitySummary = validatedSnapshot?.second
+ ?.toSanitizedCapabilitySummary()
+ .orEmpty()
+ val discoveryId = UUID.randomUUID().toString()
+ val stagedAt = System.currentTimeMillis()
+ stalkerDiscoveryStageDao?.deleteOlderThan(
+ stagedAt - STALKER_DISCOVERY_STAGE_TTL_MILLIS
+ )
+ stalkerDiscoveryStageDao?.upsert(
+ StalkerDiscoveryStageEntity(
+ discoveryId = discoveryId,
+ providerId = existingProvider?.id,
+ configurationGeneration =
+ (existingProvider?.stalkerConfigurationGeneration ?: 0L) + 1L,
+ sanitizedSummary = discoverySummary,
+ createdAt = stagedAt
+ )
+ )
val providerData = if (existingProvider != null) {
onProgress?.invoke("Updating existing provider...")
- val updated = authResult.data.copy(
+ val updated = finalAuthResult.data.copy(
id = existingProvider.id,
name = normalizedName.ifBlank { existingProvider.name },
serverUrl = resolvedPortalUrl,
@@ -643,7 +797,7 @@ class ProviderRepositoryImpl @Inject constructor(
httpUserAgent = httpUserAgent,
httpHeaders = httpHeaders,
stalkerMacAddress = normalizedMacAddress,
- stalkerDeviceProfile = normalizedDeviceProfile,
+ stalkerDeviceProfile = finalAuthResult.data.stalkerDeviceProfile,
stalkerDeviceTimezone = normalizedTimezone,
stalkerDeviceLocale = normalizedLocale,
stalkerSerialNumber = normalizedSerialNumber,
@@ -651,8 +805,22 @@ class ProviderRepositoryImpl @Inject constructor(
stalkerDeviceId2 = normalizedDeviceId2,
stalkerSignature = normalizedSignature,
stalkerAdvancedOptionsJson = normalizedAdvancedOptionsJson,
+ stalkerProtocolPreference = protocolPreference,
+ stalkerTransportMode = effectiveTransportGrant?.mode
+ ?: StalkerTransportMode.VERIFIED_HTTPS,
+ stalkerTransportOrigin = effectiveTransportGrant?.origin
+ ?.toPersistenceValue()
+ ?: resolvedPortalUrl.toStalkerOrigin()?.toPersistenceValue().orEmpty(),
+ stalkerTlsSpkiSha256 = effectiveTransportGrant?.spkiSha256.orEmpty(),
+ stalkerTransportConsentAt = effectiveTransportGrant?.consentedAt ?: 0L,
+ stalkerConfigurationGeneration =
+ existingProvider.stalkerConfigurationGeneration + 1L,
+ stalkerDiscoverySummary = discoverySummary,
+ stalkerCapabilitiesJson = capabilitySummary,
+ stalkerRequestedProfileId = requestedProfileId,
epgUrl = existingProvider.epgUrl,
epgSyncMode = epgSyncMode,
+ stalkerCatalogMode = catalogMode,
guideSourcePolicy = guideSourcePolicy,
channelLogoSourcePolicy = channelLogoSourcePolicy,
xtreamFastSyncEnabled = false,
@@ -662,18 +830,28 @@ class ProviderRepositoryImpl @Inject constructor(
lastSyncedAt = 0L,
createdAt = existingProvider.createdAt
)
- providerDao.update(updated.toSecureEntity())
+ transactionRunner.inTransaction {
+ providerDao.update(updated.toSecureEntity())
+ validatedSnapshot?.let { (session, validatedProfile) ->
+ stalkerPortalStateStore.recordAuthentication(
+ providerId = updated.id,
+ session = session,
+ profile = validatedProfile
+ )
+ }
+ stalkerDiscoveryStageDao?.delete(discoveryId)
+ }
updated.copy(password = "")
} else {
- val newData = authResult.data.copy(
- name = normalizedName.ifBlank { authResult.data.name },
+ val newData = finalAuthResult.data.copy(
+ name = normalizedName.ifBlank { finalAuthResult.data.name },
serverUrl = resolvedPortalUrl,
username = normalizedUsername,
password = effectivePassword,
httpUserAgent = httpUserAgent,
httpHeaders = httpHeaders,
stalkerMacAddress = normalizedMacAddress,
- stalkerDeviceProfile = normalizedDeviceProfile,
+ stalkerDeviceProfile = finalAuthResult.data.stalkerDeviceProfile,
stalkerDeviceTimezone = normalizedTimezone,
stalkerDeviceLocale = normalizedLocale,
stalkerSerialNumber = normalizedSerialNumber,
@@ -681,7 +859,20 @@ class ProviderRepositoryImpl @Inject constructor(
stalkerDeviceId2 = normalizedDeviceId2,
stalkerSignature = normalizedSignature,
stalkerAdvancedOptionsJson = normalizedAdvancedOptionsJson,
+ stalkerProtocolPreference = protocolPreference,
+ stalkerTransportMode = effectiveTransportGrant?.mode
+ ?: StalkerTransportMode.VERIFIED_HTTPS,
+ stalkerTransportOrigin = effectiveTransportGrant?.origin
+ ?.toPersistenceValue()
+ ?: resolvedPortalUrl.toStalkerOrigin()?.toPersistenceValue().orEmpty(),
+ stalkerTlsSpkiSha256 = effectiveTransportGrant?.spkiSha256.orEmpty(),
+ stalkerTransportConsentAt = effectiveTransportGrant?.consentedAt ?: 0L,
+ stalkerConfigurationGeneration = 1L,
+ stalkerDiscoverySummary = discoverySummary,
+ stalkerCapabilitiesJson = capabilitySummary,
+ stalkerRequestedProfileId = requestedProfileId,
epgSyncMode = epgSyncMode,
+ stalkerCatalogMode = catalogMode,
guideSourcePolicy = guideSourcePolicy,
channelLogoSourcePolicy = channelLogoSourcePolicy,
xtreamFastSyncEnabled = false,
@@ -689,17 +880,93 @@ class ProviderRepositoryImpl @Inject constructor(
isActive = false,
status = ProviderStatus.PARTIAL
)
- val newId = providerDao.insert(newData.toSecureEntity())
+ val newId = transactionRunner.inTransaction {
+ val insertedId = providerDao.insert(newData.toSecureEntity())
+ validatedSnapshot?.let { (session, validatedProfile) ->
+ stalkerPortalStateStore.recordAuthentication(
+ providerId = insertedId,
+ session = session,
+ profile = validatedProfile
+ )
+ }
+ stalkerDiscoveryStageDao?.delete(discoveryId)
+ insertedId
+ }
newData.copy(id = newId).copy(password = "")
}
- handleInitialOnboardingSync(
- providerData = providerData,
- syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),
- syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings"
- )
+ val onboardingResult = if (acceptedWithoutVerification) {
+ syncManager.scheduleProviderSyncResume(
+ providerData.id,
+ providerData.stalkerConfigurationGeneration
+ )
+ val message =
+ "Provider saved with Live TV verification pending. It needs a successful sync before activation."
+ Result.error(
+ message,
+ ProviderSavedWithSyncErrorException(
+ provider = providerData.copy(
+ status = ProviderStatus.PARTIAL,
+ isActive = false
+ ),
+ message = message
+ )
+ )
+ } else {
+ handleInitialOnboardingSync(
+ providerData = providerData,
+ syncResult = syncManager.sync(providerData.id, force = false, onProgress = onProgress),
+ syncFailurePrefix = "Provider login succeeded, but initial sync failed. The provider was saved and can be retried from Settings"
+ )
+ }
+ if (existingProvider != null && onboardingResult is Result.Error && !acceptedWithoutVerification) {
+ transactionRunner.inTransaction {
+ providerDao.update(existingProvider)
+ stalkerPortalStateStore.restore(existingProvider.id, previousPortalState)
+ }
+ Result.error(
+ "The new Stalker settings were not saved because initial readiness failed. The previous provider configuration is still active.",
+ onboardingResult.exception?.cause ?: onboardingResult.exception
+ )
+ } else {
+ onboardingResult
+ }
+ }
+ is Result.Error -> {
+ val consent = (finalAuthResult.exception as? StalkerApiError.TransportConsentRequired)
+ ?.let { StalkerTransportConsentRequiredException(it.challenge) }
+ if (consent != null) {
+ Result.error(consent.message.orEmpty(), consent)
+ } else if (finalAuthResult.exception is StalkerApiError.ReadinessInconclusive) {
+ val inconclusive = finalAuthResult.exception as StalkerApiError.ReadinessInconclusive
+ val required = StalkerReadinessInconclusiveException(
+ evidenceCode = inconclusive.evidenceCode,
+ message = "Authentication succeeded, but Live TV could not be verified. You can go back or save this provider with verification pending.",
+ cause = inconclusive
+ )
+ Result.error(required.message.orEmpty(), required)
+ } else if (!inputHasScheme && finalAuthResult.exception.isNonTlsTransportFailure()) {
+ val httpOrigin = "http://$normalizedPortalUrl".toStalkerOrigin()
+ if (httpOrigin != null) {
+ val challenge = StalkerTransportChallenge(
+ reason = StalkerTransportChallengeReason.CLEARTEXT_HTTP,
+ origin = httpOrigin,
+ displayHost = if (httpOrigin.port == 80) {
+ httpOrigin.host
+ } else {
+ "${httpOrigin.host}:${httpOrigin.port}"
+ },
+ detailCode = "HTTPS_UNAVAILABLE_HTTP_FALLBACK"
+ )
+ val required = StalkerTransportConsentRequiredException(challenge)
+ Result.error(required.message.orEmpty(), required)
+ } else {
+ Result.error(finalAuthResult.message, finalAuthResult.exception)
+ }
+ } else {
+ Result.error(finalAuthResult.message, finalAuthResult.exception)
+ }
}
- is Result.Error -> Result.error(authResult.message, authResult.exception)
is Result.Loading -> Result.error("Unexpected loading state")
}
}
@@ -728,7 +995,12 @@ class ProviderRepositoryImpl @Inject constructor(
lastSyncedAt = System.currentTimeMillis(),
isActive = false
)
- syncManager.scheduleProviderSyncResume(providerData.id)
+ syncManager.scheduleProviderSyncResume(
+ providerData.id,
+ providerData.stalkerConfigurationGeneration.takeIf {
+ providerData.type == ProviderType.STALKER_PORTAL
+ }
+ )
val message = "$syncFailurePrefix: Sync did not finish with any committed content."
Result.error(
message,
@@ -750,7 +1022,12 @@ class ProviderRepositoryImpl @Inject constructor(
}
is Result.Error -> {
updateProviderSyncStatus(providerData.id, ProviderStatus.PARTIAL, isActive = false)
- syncManager.scheduleProviderSyncResume(providerData.id)
+ syncManager.scheduleProviderSyncResume(
+ providerData.id,
+ providerData.stalkerConfigurationGeneration.takeIf {
+ providerData.type == ProviderType.STALKER_PORTAL
+ }
+ )
val message = "$syncFailurePrefix: ${syncResult.message}"
Result.error(
message,
@@ -774,6 +1051,9 @@ class ProviderRepositoryImpl @Inject constructor(
epgSyncModeOverride: ProviderEpgSyncMode?,
onProgress: ((String) -> Unit)?
): Result<Unit> {
+ if (force && providerDao.getById(providerId)?.type == ProviderType.STALKER_PORTAL) {
+ stalkerPortalStateStore.invalidateCapabilities(providerId)
+ }
return when (
val syncResult = syncManager.sync(
providerId,
@@ -1032,7 +1312,13 @@ class ProviderRepositoryImpl @Inject constructor(
deviceId: String = "",
deviceId2: String = "",
signature: String = "",
- stalkerAdvancedOptionsJson: String = ""
+ stalkerAdvancedOptionsJson: String = "",
+ protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ transportGrant: StalkerTransportGrant? = null,
+ requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
+ learnedProfileId: String = "",
+ requireCatalogValidation: Boolean = true,
+ onProgress: ((String) -> Unit)? = null
): StalkerProvider {
return StalkerProvider(
providerId = providerId,
@@ -1059,7 +1345,15 @@ class ProviderRepositoryImpl @Inject constructor(
deviceId = deviceId,
deviceId2 = deviceId2,
signature = signature,
- stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson
+ stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,
+ protocolPreference = protocolPreference,
+ transportGrant = transportGrant,
+ requestedProfileId = requestedProfileId,
+ learnedProfileId = learnedProfileId,
+ requireCatalogValidation = requireCatalogValidation,
+ identityResolver = stalkerRemoteIdentityResolver,
+ portalStateStore = stalkerPortalStateStore,
+ onProgress = onProgress
)
}
@@ -1093,7 +1387,11 @@ class ProviderRepositoryImpl @Inject constructor(
deviceId = entity.stalkerDeviceId,
deviceId2 = entity.stalkerDeviceId2,
signature = entity.stalkerSignature,
- stalkerAdvancedOptionsJson = entity.stalkerAdvancedOptionsJson
+ stalkerAdvancedOptionsJson = entity.stalkerAdvancedOptionsJson,
+ protocolPreference = entity.stalkerProtocolPreference,
+ transportGrant = entity.toStalkerTransportGrant(),
+ requestedProfileId = entity.stalkerRequestedProfileId,
+ learnedProfileId = entity.stalkerLearnedProfileId
)
}
@@ -1267,6 +1565,92 @@ class ProviderRepositoryImpl @Inject constructor(
}
}
+private fun ProviderEntity.toStalkerTransportGrant(): StalkerTransportGrant? {
+ if (stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_HTTP &&
+ stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS &&
+ stalkerTransportMode != StalkerTransportMode.VERIFIED_HTTPS
+ ) {
+ return null
+ }
+ val origin = stalkerTransportOrigin.toStalkerOrigin()
+ ?: serverUrl.toStalkerOrigin()
+ ?: return null
+ val pin = stalkerTlsSpkiSha256.takeIf(String::isNotBlank)
+ if (stalkerTransportMode == StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS && pin == null) {
+ return null
+ }
+ return StalkerTransportGrant(
+ mode = stalkerTransportMode,
+ origin = origin,
+ spkiSha256 = pin,
+ consentedAt = stalkerTransportConsentAt
+ )
+}
+
+private fun String.toStalkerOrigin(): StalkerTransportOrigin? {
+ val uri = runCatching { URI(trim()) }.getOrNull() ?: return null
+ val scheme = uri.scheme?.lowercase()?.takeIf { it == "http" || it == "https" } ?: return null
+ val host = uri.host?.lowercase()?.takeIf(String::isNotBlank) ?: return null
+ val port = when {
+ uri.port != -1 -> uri.port
+ scheme == "https" -> 443
+ else -> 80
+ }
+ return StalkerTransportOrigin(scheme, host, port)
+}
+
+private fun StalkerTransportOrigin.toPersistenceValue(): String =
+ authority
+
+private fun Throwable?.isNonTlsTransportFailure(): Boolean {
+ val chain = generateSequence(this) { it.cause }.toList()
+ if (chain.any {
+ it is StalkerApiError &&
+ it !is StalkerApiError.Transport &&
+ it !is StalkerApiError.TransportConsentRequired
+ }
+ ) {
+ return false
+ }
+ if (chain.any { it is StalkerApiError.TransportConsentRequired }) return false
+ return chain.any { it is StalkerApiError.Transport || it is IOException }
+}
+
+private fun Pair<
+ com.streamvault.data.remote.stalker.StalkerSession,
+ com.streamvault.data.remote.stalker.StalkerProviderProfile
+>.toSanitizedDiscoverySummary(): String {
+ val session = first
+ val endpoint = when {
+ session.loadUrl.endsWith("/portal.php", ignoreCase = true) -> "PORTAL_PHP"
+ session.loadUrl.endsWith("/server/load.php", ignoreCase = true) -> "SERVER_LOAD"
+ else -> "CUSTOM_RPC"
+ }
+ val profile = session.compatibilityProfileId
+ .uppercase()
+ .filter { it.isLetterOrDigit() || it == '.' || it == '_' || it == '-' }
+ .take(64)
+ .ifBlank { "UNKNOWN" }
+ return "AUTHENTICATED;LIVE=SUPPORTED;ENDPOINT=$endpoint;PROFILE=$profile"
+}
+
+private fun com.streamvault.data.remote.stalker.StalkerProviderProfile
+ .toSanitizedCapabilitySummary(): String {
+ val capabilities = portalCapabilities
+ val archive = if (capabilities.archiveAvailable) "SUPPORTED" else "NOT_PROBED"
+ val modules = if (capabilities.moduleRestricted) "RESTRICTED" else "SUPPORTED"
+ return buildString {
+ append('{')
+ append("\"LIVE\":\"SUPPORTED\",")
+ append("\"VOD\":\"NOT_PROBED\",")
+ append("\"SERIES\":\"NOT_PROBED\",")
+ append("\"ARCHIVE\":\"").append(archive).append("\",")
+ append("\"EPG\":\"NOT_PROBED\",")
+ append("\"ACCOUNT_MODULES\":\"").append(modules).append("\"")
+ append('}')
+ }
+}
+
internal fun buildM3uCatchUpUrls(source: String, start: Long, end: Long): List<String> {
val trimmedSource = source.trim()
if (trimmedSource.isBlank()) return emptyList()
diff --git a/data/src/main/java/com/streamvault/data/repository/SearchRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SearchRepositoryImpl.kt
index 5ef70e4d..da15fecc 100644
--- a/data/src/main/java/com/streamvault/data/repository/SearchRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SearchRepositoryImpl.kt
@@ -3,11 +3,17 @@ package com.streamvault.data.repository
import android.database.sqlite.SQLiteException
import android.util.Log
import com.streamvault.data.local.dao.SearchDao
+import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.data.local.dao.StalkerIndexJobDao
import com.streamvault.data.local.dao.SearchHitEntity
import com.streamvault.data.util.toFtsPrefixQuery
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.CatalogCompleteness
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Series
+import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.StalkerIndexState
import com.streamvault.domain.repository.ChannelRepository
import com.streamvault.domain.repository.MovieRepository
import com.streamvault.domain.repository.SearchRepository
@@ -30,7 +36,9 @@ class SearchRepositoryImpl @Inject constructor(
private val searchDao: SearchDao,
private val channelRepository: ChannelRepository,
private val movieRepository: MovieRepository,
- private val seriesRepository: SeriesRepository
+ private val seriesRepository: SeriesRepository,
+ private val providerDao: ProviderDao,
+ private val stalkerIndexJobDao: StalkerIndexJobDao
) : SearchRepository {
override fun searchContent(
providerId: Long,
@@ -134,6 +142,37 @@ class SearchRepositoryImpl @Inject constructor(
}
}
}
+ .map { result ->
+ result.copy(
+ catalogCompleteness = catalogCompleteness(
+ providerId = providerId,
+ includeMovies = includeMovies,
+ includeSeries = includeSeries
+ )
+ )
+ }
+ }
+
+ private suspend fun catalogCompleteness(
+ providerId: Long,
+ includeMovies: Boolean,
+ includeSeries: Boolean
+ ): CatalogCompleteness {
+ if (!includeMovies && !includeSeries) return CatalogCompleteness.COMPLETE
+ val provider = providerDao.getById(providerId) ?: return CatalogCompleteness.PARTIAL
+ if (provider.type != ProviderType.STALKER_PORTAL) return CatalogCompleteness.COMPLETE
+ val sections = buildList {
+ if (includeMovies) add(ContentType.MOVIE)
+ if (includeSeries) add(ContentType.SERIES)
+ }
+ val states = sections.map { section -> stalkerIndexJobDao.get(providerId, section.name)?.state }
+ return when {
+ states.any { it == StalkerIndexState.TRUNCATED } -> CatalogCompleteness.TRUNCATED
+ states.any { it in setOf(StalkerIndexState.QUEUED, StalkerIndexState.RUNNING, StalkerIndexState.RETRY_WAIT) } ->
+ CatalogCompleteness.INDEXING
+ states.isNotEmpty() && states.all { it == StalkerIndexState.COMPLETE } -> CatalogCompleteness.COMPLETE
+ else -> CatalogCompleteness.PARTIAL
+ }
}
override fun searchChannels(providerId: Long, query: String): Flow<List<Channel>> =
diff --git a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
index f9069324..5e6185c6 100644
--- a/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/SeriesRepositoryImpl.kt
@@ -10,6 +10,11 @@ import com.streamvault.data.remote.http.toGenericRequestProfile
import com.streamvault.data.remote.stalker.StalkerApiService
import com.streamvault.data.remote.stalker.StalkerPlaybackMode
import com.streamvault.data.remote.stalker.StalkerProvider
+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver
+import com.streamvault.data.remote.stalker.StalkerRequestCoordinator
+import com.streamvault.data.remote.stalker.StalkerRequestDescriptor
+import com.streamvault.data.remote.stalker.StalkerResponseMetrics
+import com.streamvault.data.remote.stalker.StalkerPortalStateStore
import com.streamvault.data.remote.stalker.StalkerTrafficCoordinator
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.xtream.XtreamProvider
@@ -68,7 +73,10 @@ class SeriesRepositoryImpl @Inject constructor(
private val xtreamIndexJobDao: XtreamIndexJobDao,
private val syncManager: SyncManager,
private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao,
- private val jellyfinProvider: JellyfinProvider
+ private val jellyfinProvider: JellyfinProvider,
+ private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,
+ private val stalkerRequestCoordinator: StalkerRequestCoordinator,
+ private val stalkerPortalStateStore: StalkerPortalStateStore
) : SeriesRepository {
private companion object {
const val TAG = "SeriesRepository"
@@ -81,6 +89,8 @@ class SeriesRepositoryImpl @Inject constructor(
const val CURSOR_BATCH_SIZE = 40
const val STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLD = 24
const val STALKER_PREVIEW_MAX_REMOTE_PAGES = 2
+ const val STALKER_INITIAL_CATEGORY_FILL_COUNT = 40
+ const val STALKER_INITIAL_CATEGORY_MAX_REMOTE_PAGES = 4
const val DETAIL_REFRESH_TTL_MILLIS = 14L * 24L * 60L * 60L * 1000L
const val XTREAM_DETAIL_HYDRATION_TIMEOUT_MILLIS = 8_000L
const val CACHE_STATE_SUMMARY_ONLY = "SUMMARY_ONLY"
@@ -172,7 +182,7 @@ class SeriesRepositoryImpl @Inject constructor(
limit: Int,
offset: Int
): Flow<List<Series>> = flow {
- ensureXtreamCategoryLoaded(providerId, categoryId)
+ ensureXtreamCategoryLoaded(providerId, categoryId, requiredCount = offset + limit)
emitAll(
combine(
seriesDao.getByCategoryPage(providerId, categoryId, limit, offset),
@@ -192,7 +202,7 @@ class SeriesRepositoryImpl @Inject constructor(
override fun getSeriesByCategoryPreview(providerId: Long, categoryId: Long, limit: Int): Flow<List<Series>> =
flow {
- ensureXtreamCategoryLoaded(providerId, categoryId)
+ ensureXtreamCategoryLoaded(providerId, categoryId, requiredCount = limit)
emitAll(
combine(
seriesDao.getByCategoryPreview(providerId, categoryId, limit),
@@ -239,15 +249,13 @@ class SeriesRepositoryImpl @Inject constructor(
(provider.type == ProviderType.XTREAM_CODES || provider.type == ProviderType.STALKER_PORTAL)
) {
previewCategories.forEach { category ->
- launch(Dispatchers.IO) {
- ensureXtreamCategoryLoaded(
- providerId = providerId,
- categoryId = category.categoryId,
- requiredCount = limitPerCategory,
- refreshStaleInBackground = false,
- allowStalkerWildcard = false
- )
- }
+ triggerSeriesCategoryHydration(
+ providerId = providerId,
+ categoryId = category.categoryId,
+ provider = provider,
+ requiredCount = limitPerCategory,
+ allowStalkerWildcard = false
+ )
}
}
val categoryGroupFlows: List<Flow<Pair<Long?, List<Series>>>> = previewCategories.map { cat ->
@@ -329,7 +337,14 @@ class SeriesRepositoryImpl @Inject constructor(
val normalizedSearch = query.searchQuery.trim()
query.categoryId
?.takeIf { normalizedSearch.length < MIN_SEARCH_QUERY_LENGTH }
- ?.let { ensureXtreamCategoryLoaded(query.providerId, it, browseFetchLimit(query)) }
+ ?.let {
+ ensureXtreamCategoryLoaded(
+ providerId = query.providerId,
+ categoryId = it,
+ requiredCount = browseFetchLimit(query),
+ loadStalkerCategoryCompletely = true
+ )
+ }
emit(fetchSeriesBrowseResult(query))
}.flowOn(Dispatchers.IO)
}
@@ -609,6 +624,7 @@ class SeriesRepositoryImpl @Inject constructor(
title = episode.title,
headers = resolvedStream.headers,
userAgent = resolvedStream.userAgent,
+ playbackTransportPolicy = resolvedStream.playbackTransportPolicy,
allowInvalidSsl = resolvedStream.allowInvalidSsl,
proxyHost = resolvedStream.proxyHost,
proxyPort = resolvedStream.proxyPort,
@@ -1434,7 +1450,8 @@ class SeriesRepositoryImpl @Inject constructor(
categoryId: Long,
requiredCount: Int = SEARCH_RESULT_LIMIT,
refreshStaleInBackground: Boolean = true,
- allowStalkerWildcard: Boolean = true
+ allowStalkerWildcard: Boolean = true,
+ loadStalkerCategoryCompletely: Boolean = false
) {
val key = "$providerId:$categoryId"
val provider = providerDao.getById(providerId) ?: return
@@ -1451,10 +1468,13 @@ class SeriesRepositoryImpl @Inject constructor(
return
}
if (provider.type == ProviderType.STALKER_PORTAL) {
- if (localCount <= 0) {
- syncManager.prioritizeStalkerIndexCategory(providerId, ContentType.SERIES, categoryId)
- }
- if (!shouldUseStalkerLazyFallback(providerId, hydration, localCount)) {
+ if (!shouldUseStalkerLazyFallback(
+ hydration = hydration,
+ localCount = localCount,
+ requiredCount = requiredCount,
+ loadCompletely = loadStalkerCategoryCompletely
+ )
+ ) {
return
}
hydrateStalkerSeriesCategoryToCount(
@@ -1464,7 +1484,8 @@ class SeriesRepositoryImpl @Inject constructor(
requiredCount = requiredCount,
localCount = localCount,
hydration = hydration,
- allowWildcard = allowStalkerWildcard
+ allowWildcard = allowStalkerWildcard,
+ loadCompletely = loadStalkerCategoryCompletely
)
return
}
@@ -1488,10 +1509,7 @@ class SeriesRepositoryImpl @Inject constructor(
val hydration = seriesCategoryHydrationDao.get(providerId, categoryId)
if (localCount == 0 && hydration?.isEmptyRetryCoolingDown() == true) return@launch
if (provider.type == ProviderType.STALKER_PORTAL) {
- if (localCount <= 0) {
- syncManager.prioritizeStalkerIndexCategory(providerId, ContentType.SERIES, categoryId)
- }
- if (!shouldUseStalkerLazyFallback(providerId, hydration, localCount)) {
+ if (!shouldUseStalkerLazyFallback(hydration, localCount, requiredCount)) {
return@launch
}
hydrateStalkerSeriesCategoryToCount(
@@ -1510,20 +1528,23 @@ class SeriesRepositoryImpl @Inject constructor(
}
}
- private suspend fun shouldUseStalkerLazyFallback(
- providerId: Long,
+ private fun shouldUseStalkerLazyFallback(
hydration: SeriesCategoryHydrationEntity?,
- localCount: Int
+ localCount: Int,
+ requiredCount: Int,
+ loadCompletely: Boolean = false
): Boolean {
val now = System.currentTimeMillis()
- if (localCount > 0) return false
+ val hasEmptySuccessfulCheckpoint = localCount == 0 &&
+ (hydration?.lastSuccessfulPage ?: hydration?.lastLoadedPage ?: 0) > 0
+ if (hasEmptySuccessfulCheckpoint) return true
if (hydration?.isComplete == true) return false
+ if (hydration?.lastStatus == "TRUNCATED" && !loadCompletely) return false
+ if (loadCompletely) return true
+ if (localCount >= requiredCount) return false
if (hydration?.lastStatus in setOf("FAILED_PERMANENT", "FAILED_BUDGET_EXHAUSTED")) return true
if (hydration?.retryBudgetRemaining == 0 && hydration.retryAfterMs <= now) return true
- return when (xtreamIndexJobDao.get(providerId, ContentType.SERIES.name)?.state) {
- null, "FAILED_PERMANENT" -> true
- else -> false
- }
+ return true
}
private suspend fun hydrateStalkerSeriesCategoryToCount(
@@ -1533,7 +1554,8 @@ class SeriesRepositoryImpl @Inject constructor(
requiredCount: Int,
localCount: Int? = null,
hydration: SeriesCategoryHydrationEntity? = null,
- allowWildcard: Boolean = true
+ allowWildcard: Boolean = true,
+ loadCompletely: Boolean = false
) {
val key = "$providerId:$categoryId"
val lock = xtreamCategoryLoadLocks.getOrPut(key) { Mutex() }
@@ -1542,27 +1564,75 @@ class SeriesRepositoryImpl @Inject constructor(
if (!allowWildcard && stalkerProvider.isWildcardCategory(ContentType.SERIES, categoryId)) return
var currentCount = localCount ?: seriesDao.getCountByCategory(providerId, categoryId).first()
var currentHydration = hydration ?: seriesCategoryHydrationDao.get(providerId, categoryId)
- if (currentHydration?.isComplete == true || currentCount >= requiredCount) return
+ if ((currentHydration?.isComplete == true && currentCount > 0) ||
+ (!loadCompletely && currentCount >= requiredCount)
+ ) return
if (currentCount == 0 && currentHydration?.isEmptyRetryCoolingDown() == true) return
val isPreviewLoad = requiredCount <= STALKER_PREVIEW_REQUIRED_COUNT_THRESHOLD
- var nextPage = when (currentHydration?.lastStatus) {
- "FAILED_RETRYABLE", "COOLDOWN", "ANOMALY" -> currentHydration?.lastAttemptedPage?.coerceAtLeast(1) ?: 1
- else -> ((currentHydration?.lastSuccessfulPage ?: currentHydration?.lastLoadedPage ?: 0) + 1).coerceAtLeast(1)
+ val isInitialCategoryFill = !isPreviewLoad && currentCount < STALKER_INITIAL_CATEGORY_FILL_COUNT
+ val targetCount = when {
+ loadCompletely -> Int.MAX_VALUE
+ isInitialCategoryFill -> minOf(requiredCount, STALKER_INITIAL_CATEGORY_FILL_COUNT)
+ else -> requiredCount
+ }
+ val maxRemotePages = when {
+ loadCompletely -> Int.MAX_VALUE
+ isPreviewLoad -> STALKER_PREVIEW_MAX_REMOTE_PAGES
+ isInitialCategoryFill -> STALKER_INITIAL_CATEGORY_MAX_REMOTE_PAGES
+ else -> 1
+ }
+ var nextPage = when {
+ currentCount == 0 && (currentHydration?.lastSuccessfulPage ?: 0) > 0 -> 1
+ currentHydration?.lastStatus in setOf("FAILED_RETRYABLE", "COOLDOWN", "ANOMALY") ->
+ currentHydration?.lastAttemptedPage?.coerceAtLeast(1) ?: 1
+ else ->
+ ((currentHydration?.lastSuccessfulPage ?: currentHydration?.lastLoadedPage ?: 0) + 1)
+ .coerceAtLeast(1)
}
// The cached totalPages can under-report when the preview hydrate stored
// it from a partial response. Skip the pre-fetch guard on the first
// iteration so we always perform at least one real fetch that refreshes
// totalPages; subsequent iterations use the in-loop updated value.
var firstIteration = true
- while (currentCount < requiredCount) {
- if (StalkerTrafficCoordinator.shouldDeferCatalogFetch(providerId)) break
+ var remotePagesRequested = 0
+ while (currentCount < targetCount) {
val attemptStartedAt = System.currentTimeMillis()
if (isPreviewLoad && nextPage > STALKER_PREVIEW_MAX_REMOTE_PAGES) break
+ if (remotePagesRequested >= maxRemotePages) break
val totalPages = currentHydration?.totalPages ?: 0
if (!firstIteration && totalPages > 0 && nextPage > totalPages) break
firstIteration = false
- when (val result = stalkerProvider.getSeriesListPage(categoryId, nextPage)) {
+ remotePagesRequested += 1
+ val requestPriority = if (isPreviewLoad) {
+ StalkerRequestPriority.VISIBLE_PREVIEW
+ } else {
+ StalkerRequestPriority.OPEN_CATEGORY
+ }
+ val coordinatedResult = stalkerRequestCoordinator.execute(
+ providerId = providerId,
+ priority = requestPriority,
+ descriptor = StalkerRequestDescriptor(
+ contentType = "SERIES",
+ action = "CATEGORY_PAGE",
+ categoryKey = categoryId.toString(),
+ page = nextPage
+ ),
+ metricsOf = { result ->
+ val page = (result as? Success)?.data
+ StalkerResponseMetrics(
+ items = page?.items?.size,
+ pages = page?.page,
+ advertisedTotal = page?.advertisedTotalItems,
+ truncated = page?.isTruncated,
+ terminationReason = page?.terminationReason
+ )
+ }
+ ) { stalkerProvider.getSeriesListPage(categoryId, nextPage) }
+ if (coordinatedResult is Result.Error) {
+ stalkerRequestCoordinator.recordFailure(providerId, coordinatedResult.exception)
+ }
+ when (val result = coordinatedResult) {
is Success -> {
val entities = result.data.items.map { series -> series.toEntity() }
val pageComplete = result.data.isComplete || entities.isEmpty()
@@ -1573,7 +1643,7 @@ class SeriesRepositoryImpl @Inject constructor(
categoryId = categoryId,
lastHydratedAt = attemptStartedAt,
itemCount = currentCount,
- lastStatus = "SUCCESS",
+ lastStatus = if (result.data.isTruncated) "TRUNCATED" else "SUCCESS",
lastError = null,
lastLoadedPage = result.data.page,
lastAttemptedPage = result.data.page,
@@ -1719,7 +1789,12 @@ class SeriesRepositoryImpl @Inject constructor(
deviceId = provider.stalkerDeviceId,
deviceId2 = provider.stalkerDeviceId2,
signature = provider.stalkerSignature,
- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson
+ stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,
+ protocolPreference = provider.stalkerProtocolPreference,
+ requestedProfileId = provider.stalkerRequestedProfileId,
+ learnedProfileId = provider.stalkerLearnedProfileId,
+ identityResolver = stalkerRemoteIdentityResolver,
+ portalStateStore = stalkerPortalStateStore
)
}
}
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt
index 2b3e4371..8bfa3b69 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncStateReaderImpl.kt
@@ -1,25 +1,47 @@
package com.streamvault.data.sync
import com.streamvault.data.local.dao.XtreamIndexJobDao
+import com.streamvault.data.local.dao.StalkerIndexJobDao
import com.streamvault.domain.manager.ProviderSyncStateReader
+import com.streamvault.domain.model.StalkerIndexState
+import com.streamvault.domain.model.StalkerReadinessSnapshot
import com.streamvault.domain.model.SyncState
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.map
@Singleton
class ProviderSyncStateReaderImpl @Inject constructor(
private val syncManager: SyncManager,
- private val xtreamIndexJobDao: XtreamIndexJobDao
+ private val readinessTracker: StalkerReadinessTracker,
+ private val xtreamIndexJobDao: XtreamIndexJobDao,
+ private val stalkerIndexJobDao: StalkerIndexJobDao
) : ProviderSyncStateReader {
override fun currentSyncState(providerId: Long): SyncState = syncManager.currentSyncState(providerId)
+ override fun currentStalkerReadiness(providerId: Long): StalkerReadinessSnapshot? =
+ readinessTracker.current(providerId)
+
+ override fun observeStalkerReadiness(providerId: Long): Flow<StalkerReadinessSnapshot?> =
+ readinessTracker.observe(providerId)
+
override fun observeBackgroundIndexingActive(providerId: Long): Flow<Boolean> =
- xtreamIndexJobDao.observeForProvider(providerId).map { jobs ->
- jobs.any { job ->
+ combine(
+ xtreamIndexJobDao.observeForProvider(providerId),
+ stalkerIndexJobDao.observeForProvider(providerId)
+ ) { xtreamJobs, stalkerJobs ->
+ xtreamJobs.any { job ->
job.section in setOf("MOVIE", "SERIES") &&
job.state in setOf("QUEUED", "RUNNING", "PARTIAL", "STALE", "FAILED_RETRYABLE")
+ } || stalkerJobs.any { job ->
+ job.state in setOf(
+ StalkerIndexState.QUEUED,
+ StalkerIndexState.RUNNING,
+ StalkerIndexState.RETRY_WAIT,
+ StalkerIndexState.PARTIAL
+ )
}
}
}
diff --git a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
index 94f4e556..c525f162 100644
--- a/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/ProviderSyncWorker.kt
@@ -23,9 +23,11 @@ import com.streamvault.data.local.dao.XtreamLiveOnboardingDao
import com.streamvault.domain.model.ProviderStatus
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.ProviderEpgSyncMode
+import com.streamvault.domain.model.StalkerCatalogMode
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.repository.SyncMetadataRepository
+import com.streamvault.data.remote.stalker.StalkerApiError
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
@@ -74,8 +76,14 @@ internal suspend fun reconcileTargetedProviderStatus(
)
}
is com.streamvault.domain.model.Result.Error -> {
- if (provider.status != ProviderStatus.PARTIAL) {
- providerDao.update(provider.copy(isActive = false, status = ProviderStatus.ERROR))
+ val consentRequired = result.exception.hasTransportConsentChallenge()
+ if (consentRequired || provider.status != ProviderStatus.PARTIAL) {
+ providerDao.update(
+ provider.copy(
+ isActive = false,
+ status = if (consentRequired) ProviderStatus.PARTIAL else ProviderStatus.ERROR
+ )
+ )
}
}
is com.streamvault.domain.model.Result.Loading -> Unit
@@ -112,6 +120,10 @@ class ProviderSyncWorker(
ProviderSyncWorkerEntryPoint::class.java
)
val requestedProviderId = inputData.getLong(KEY_PROVIDER_ID, INVALID_PROVIDER_ID)
+ val requestedGeneration = inputData.getLong(
+ KEY_CONFIGURATION_GENERATION,
+ INVALID_CONFIGURATION_GENERATION
+ )
val providers = if (requestedProviderId != INVALID_PROVIDER_ID) {
entryPoint.providerDao().getById(requestedProviderId)?.let(::listOf).orEmpty()
} else {
@@ -123,6 +135,17 @@ class ProviderSyncWorker(
var sawRetryableFailure = false
providers.forEach { provider ->
+ if (requestedProviderId == provider.id &&
+ requestedGeneration != INVALID_CONFIGURATION_GENERATION &&
+ provider.type == ProviderType.STALKER_PORTAL &&
+ provider.stalkerConfigurationGeneration != requestedGeneration
+ ) {
+ Log.i(
+ TAG,
+ "Discarding stale Stalker sync request for provider ${provider.id}."
+ )
+ return@forEach
+ }
val trackInitialLiveOnboarding = shouldTrackInitialLiveOnboarding(
provider = provider,
onboardingDao = entryPoint.xtreamLiveOnboardingDao()
@@ -162,6 +185,7 @@ class ProviderSyncWorker(
}
private fun shouldRetry(error: Throwable?): Boolean {
+ if (error.hasTransportConsentChallenge()) return false
return when (error) {
is java.io.IOException -> true
is SQLiteException -> error.message.orEmpty().contains("locked", ignoreCase = true) ||
@@ -178,6 +202,8 @@ class ProviderSyncWorker(
private const val UNIQUE_PROVIDER_WORK_PREFIX = "provider-sync-provider-"
private const val KEY_PROVIDER_ID = "provider_id"
private const val INVALID_PROVIDER_ID = -1L
+ private const val KEY_CONFIGURATION_GENERATION = "configuration_generation"
+ private const val INVALID_CONFIGURATION_GENERATION = -1L
fun enqueuePeriodic(context: Context) {
val request = PeriodicWorkRequestBuilder<ProviderSyncWorker>(6, TimeUnit.HOURS)
@@ -224,9 +250,19 @@ class ProviderSyncWorker(
)
}
- fun enqueueProvider(context: Context, providerId: Long) {
+ fun enqueueProvider(
+ context: Context,
+ providerId: Long,
+ configurationGeneration: Long? = null
+ ) {
val request = OneTimeWorkRequestBuilder<ProviderSyncWorker>()
- .setInputData(workDataOf(KEY_PROVIDER_ID to providerId))
+ .setInputData(
+ workDataOf(
+ KEY_PROVIDER_ID to providerId,
+ KEY_CONFIGURATION_GENERATION to
+ (configurationGeneration ?: INVALID_CONFIGURATION_GENERATION)
+ )
+ )
.setConstraints(
Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
@@ -333,8 +369,9 @@ class ProviderSyncWorker(
ContentCachePolicy.EPG_TTL_MILLIS,
now
)
- val movieIndexDue = shouldRunIndexJob(entryPoint, provider.id, ContentType.MOVIE, now)
- val seriesIndexDue = shouldRunIndexJob(entryPoint, provider.id, ContentType.SERIES, now)
+ val maintainCompleteIndex = provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX
+ val movieIndexDue = maintainCompleteIndex && shouldRunIndexJob(entryPoint, provider.id, ContentType.MOVIE, now)
+ val seriesIndexDue = maintainCompleteIndex && shouldRunIndexJob(entryPoint, provider.id, ContentType.SERIES, now)
if (!provider.isActive) {
return com.streamvault.domain.model.Result.success(Unit)
@@ -374,3 +411,7 @@ class ProviderSyncWorker(
)
}
}
+
+private fun Throwable?.hasTransportConsentChallenge(): Boolean =
+ generateSequence(this) { it.cause }
+ .any { it is StalkerApiError.TransportConsentRequired }
diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt b/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt
index 9bb07cb5..8881ea84 100644
--- a/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerIndexWorker.kt
@@ -14,14 +14,24 @@ import androidx.work.WorkManager
import androidx.work.WorkRequest
import androidx.work.WorkerParameters
import com.streamvault.data.local.dao.ProviderDao
+import com.streamvault.data.local.dao.StalkerIndexJobDao
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.data.remote.stalker.StalkerTelemetry
import dagger.hilt.EntryPoint
import dagger.hilt.InstallIn
import dagger.hilt.android.EntryPointAccessors
import dagger.hilt.components.SingletonComponent
import java.io.IOException
import java.util.concurrent.TimeUnit
+import kotlinx.coroutines.CancellationException
+
+internal fun stalkerIndexExistingWorkPolicy(force: Boolean, appendSuccessor: Boolean): ExistingWorkPolicy = when {
+ force -> ExistingWorkPolicy.REPLACE
+ appendSuccessor -> ExistingWorkPolicy.APPEND_OR_REPLACE
+ else -> ExistingWorkPolicy.KEEP
+}
class StalkerIndexWorker(
appContext: Context,
@@ -32,6 +42,7 @@ class StalkerIndexWorker(
@InstallIn(SingletonComponent::class)
interface StalkerIndexWorkerEntryPoint {
fun providerDao(): ProviderDao
+ fun stalkerIndexJobDao(): StalkerIndexJobDao
fun syncManager(): SyncManager
}
@@ -54,13 +65,27 @@ class StalkerIndexWorker(
entryPoint.providerDao().getById(requestedProviderId)?.let(::listOf).orEmpty()
} else {
entryPoint.providerDao().getAllSync()
- .filter { provider -> provider.isActive && provider.type == ProviderType.STALKER_PORTAL }
+ .filter { provider ->
+ provider.isActive &&
+ provider.type == ProviderType.STALKER_PORTAL
+ }
}
var sawRetryableFailure = false
providers
.filter { provider -> provider.type == ProviderType.STALKER_PORTAL }
.forEach { provider ->
+ val pendingOneTime = listOf(ContentType.MOVIE, ContentType.SERIES).any { contentType ->
+ entryPoint.stalkerIndexJobDao().get(provider.id, contentType.name)?.state in setOf(
+ com.streamvault.domain.model.StalkerIndexState.QUEUED,
+ com.streamvault.domain.model.StalkerIndexState.RUNNING,
+ com.streamvault.domain.model.StalkerIndexState.RETRY_WAIT,
+ com.streamvault.domain.model.StalkerIndexState.PARTIAL
+ )
+ }
+ if (provider.stalkerCatalogMode != StalkerCatalogMode.BACKGROUND_INDEX && !pendingOneTime) {
+ return@forEach
+ }
when (val result = entryPoint.syncManager().processQueuedStalkerIndexJobs(
providerId = provider.id,
section = requestedSection,
@@ -75,9 +100,24 @@ class StalkerIndexWorker(
}
else -> Unit
}
+ listOf(ContentType.MOVIE, ContentType.SERIES).forEach { contentType ->
+ entryPoint.stalkerIndexJobDao().get(provider.id, contentType.name)?.let { job ->
+ StalkerTelemetry.indexProgress(
+ providerId = provider.id,
+ workId = id.toString(),
+ section = contentType.name,
+ state = job.state.name,
+ completedCategories = job.completedCategories,
+ totalCategories = job.totalCategories,
+ indexedRows = job.indexedRows
+ )
+ }
+ }
}
if (sawRetryableFailure) Result.retry() else Result.success()
+ } catch (cancelled: CancellationException) {
+ throw cancelled
} catch (error: Exception) {
Log.e(TAG, "Stalker index worker failed", error)
if (shouldRetry(error)) Result.retry() else Result.failure()
@@ -107,7 +147,8 @@ class StalkerIndexWorker(
providerId: Long,
section: String? = null,
force: Boolean = false,
- initialDelaySeconds: Long = 0L
+ initialDelaySeconds: Long = 0L,
+ appendSuccessor: Boolean = false
) {
if (providerId <= 0L) return
val request = OneTimeWorkRequestBuilder<StalkerIndexWorker>()
@@ -130,19 +171,29 @@ class StalkerIndexWorker(
.build()
WorkManager.getInstance(context).enqueueUniqueWork(
- uniqueWorkName(providerId, section),
- if (force) ExistingWorkPolicy.REPLACE else ExistingWorkPolicy.APPEND_OR_REPLACE,
+ uniqueWorkName(providerId),
+ stalkerIndexExistingWorkPolicy(force, appendSuccessor),
request
)
}
+ fun cancel(context: Context, providerId: Long) {
+ if (providerId <= 0L) return
+ val workManager = WorkManager.getInstance(context)
+ workManager.cancelUniqueWork(uniqueWorkName(providerId))
+ // Names used by older builds had a section suffix.
+ workManager.cancelUniqueWork("$UNIQUE_WORK_PREFIX$providerId-")
+ workManager.cancelUniqueWork("$UNIQUE_WORK_PREFIX$providerId-MOVIE")
+ workManager.cancelUniqueWork("$UNIQUE_WORK_PREFIX$providerId-SERIES")
+ }
+
private fun defaultConstraints(): Constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()
- private fun uniqueWorkName(providerId: Long, section: String?): String =
- "$UNIQUE_WORK_PREFIX$providerId-${section.orEmpty()}"
+ private fun uniqueWorkName(providerId: Long): String =
+ "$UNIQUE_WORK_PREFIX$providerId"
private fun String.toContentTypeOrNull(): ContentType? =
runCatching { ContentType.valueOf(this) }.getOrNull()
diff --git a/data/src/main/java/com/streamvault/data/sync/StalkerReadinessTracker.kt b/data/src/main/java/com/streamvault/data/sync/StalkerReadinessTracker.kt
new file mode 100644
index 00000000..7044b772
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/sync/StalkerReadinessTracker.kt
@@ -0,0 +1,89 @@
+package com.streamvault.data.sync
+
+import com.streamvault.data.remote.stalker.StalkerTelemetry
+import com.streamvault.domain.model.StalkerReadiness
+import com.streamvault.domain.model.StalkerReadinessSnapshot
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.map
+import kotlinx.coroutines.flow.update
+
+/** In-memory lifecycle state for the current or most recent Stalker readiness run. */
+@Singleton
+class StalkerReadinessTracker @Inject constructor() {
+ private val snapshots = MutableStateFlow<Map<Long, StalkerReadinessSnapshot>>(emptyMap())
+
+ val all = snapshots.asStateFlow()
+
+ fun current(providerId: Long): StalkerReadinessSnapshot? = snapshots.value[providerId]
+
+ fun observe(providerId: Long): Flow<StalkerReadinessSnapshot?> =
+ snapshots.map { states -> states[providerId] }
+
+ fun start(providerId: Long, now: Long = System.currentTimeMillis()) {
+ publish(
+ StalkerReadinessSnapshot(
+ providerId = providerId,
+ state = StalkerReadiness.AUTHENTICATING,
+ syncStartedAt = now
+ )
+ )
+ }
+
+ fun authenticated(providerId: Long, now: Long = System.currentTimeMillis()) {
+ mutate(providerId) { snapshot -> snapshot.copy(authenticatedAt = now) }
+ }
+
+ fun liveReady(providerId: Long, now: Long = System.currentTimeMillis()) {
+ mutate(providerId) { snapshot ->
+ snapshot.copy(state = StalkerReadiness.LIVE_READY, liveReadyAt = now)
+ }
+ }
+
+ fun categoriesReady(providerId: Long, now: Long = System.currentTimeMillis()) {
+ mutate(providerId) { snapshot ->
+ snapshot.copy(state = StalkerReadiness.CATEGORIES_READY, categoriesReadyAt = now)
+ }
+ }
+
+ fun ready(providerId: Long, warningCount: Int, now: Long = System.currentTimeMillis()) {
+ mutate(providerId) { snapshot ->
+ snapshot.copy(
+ state = if (warningCount > 0) {
+ StalkerReadiness.READY_WITH_WARNINGS
+ } else {
+ StalkerReadiness.READY
+ },
+ readyAt = now,
+ warningCount = warningCount.coerceAtLeast(0)
+ )
+ }
+ }
+
+ fun clear(providerId: Long) {
+ snapshots.update { current -> current - providerId }
+ }
+
+ private fun mutate(
+ providerId: Long,
+ transform: (StalkerReadinessSnapshot) -> StalkerReadinessSnapshot
+ ) {
+ snapshots.update { current ->
+ val snapshot = current[providerId] ?: return@update current
+ current + (providerId to transform(snapshot))
+ }
+ snapshots.value[providerId]?.let(::emitTelemetry)
+ }
+
+ private fun publish(snapshot: StalkerReadinessSnapshot) {
+ snapshots.update { current -> current + (snapshot.providerId to snapshot) }
+ emitTelemetry(snapshot)
+ }
+
+ private fun emitTelemetry(snapshot: StalkerReadinessSnapshot) {
+ StalkerTelemetry.readinessMilestone(snapshot)
+ }
+}
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 b9ed9a4b..fbd9bd1d 100644
--- a/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
+++ b/data/src/main/java/com/streamvault/data/sync/SyncManager.kt
@@ -13,6 +13,7 @@ import com.streamvault.data.local.dao.ProgramDao
import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.dao.SeriesCategoryHydrationDao
import com.streamvault.data.local.dao.SeriesDao
+import com.streamvault.data.local.dao.StalkerIndexJobDao
import com.streamvault.data.local.dao.TmdbIdentityDao
import com.streamvault.data.local.dao.XtreamContentIndexDao
import com.streamvault.data.local.dao.XtreamIndexJobDao
@@ -22,6 +23,7 @@ import com.streamvault.data.local.entity.ChannelEntity
import com.streamvault.data.local.entity.ChannelGuideSyncEntity
import com.streamvault.data.local.entity.MovieEntity
import com.streamvault.data.local.entity.SeriesEntity
+import com.streamvault.data.local.entity.StalkerIndexJobEntity
import com.streamvault.data.local.entity.XtreamContentIndexEntity
import com.streamvault.data.local.entity.XtreamIndexJobEntity
import com.streamvault.data.local.entity.XtreamLiveOnboardingStateEntity
@@ -31,11 +33,18 @@ import com.streamvault.data.parser.M3uParser
import com.streamvault.data.remote.http.buildAppRequestProfile
import com.streamvault.data.remote.http.toGenericRequestProfile
import com.streamvault.data.remote.stalker.StalkerApiService
+import com.streamvault.data.remote.stalker.StalkerApiError
import com.streamvault.data.remote.stalker.StalkerPlaybackMode
import com.streamvault.data.remote.stalker.StalkerProvider
+import com.streamvault.data.remote.stalker.StalkerRemoteIdentityResolver
+import com.streamvault.data.remote.stalker.StalkerRequestCoordinator
+import com.streamvault.data.remote.stalker.StalkerRequestDescriptor
+import com.streamvault.data.remote.stalker.StalkerResponseMetrics
+import com.streamvault.data.remote.stalker.StalkerPortalStateStore
import com.streamvault.data.remote.stalker.StalkerProviderProfile
import com.streamvault.data.remote.jellyfin.JellyfinProvider
import com.streamvault.data.remote.stalker.StalkerTrafficCoordinator
+import com.streamvault.data.remote.stalker.StalkerTelemetry
import com.streamvault.data.remote.dto.XtreamCategory
import com.streamvault.data.remote.dto.XtreamSeriesItem
import com.streamvault.data.remote.dto.XtreamStream
@@ -60,6 +69,12 @@ import com.streamvault.domain.model.Provider
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerIndexState
+import com.streamvault.domain.model.StalkerRequestPriority
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.model.VodSyncMode
@@ -74,15 +89,15 @@ import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.withContext
+import kotlinx.coroutines.withTimeoutOrNull
import kotlinx.coroutines.sync.Mutex
-import kotlinx.coroutines.sync.Semaphore
import kotlinx.coroutines.sync.withLock
-import kotlinx.coroutines.sync.withPermit
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
@@ -102,12 +117,15 @@ private const val TAG = "SyncManager"
private const val XTREAM_FALLBACK_STAGE_BATCH_SIZE = 500
private const val STALKER_INDEX_CATEGORY_SLICE_SIZE = 32
private const val STALKER_WILDCARD_PAGE_SLICE_SIZE = 192
-private const val STALKER_MAX_PARALLEL_CATEGORY_FETCHES = 6
+private const val STALKER_MAX_PARALLEL_CATEGORY_FETCHES = 2
private const val STALKER_MAX_SECTION_RUN_MILLIS = 240_000L
private const val STALKER_CATEGORY_RETRY_BUDGET = 3
private const val STALKER_CATEGORY_RETRY_COOLDOWN_MILLIS = 5 * 60 * 1000L
private const val STALKER_RUNNING_JOB_STALE_MILLIS = 15 * 60 * 1000L
private const val STALKER_MIN_HEALTHY_EPG_PROGRAMS = 3
+// Bulk live is an optimization. Bound the complete attempt so a portal that keeps
+// a response alive without completing cannot block the per-category recovery path.
+private const val STALKER_BULK_LIVE_REQUEST_TIMEOUT_MILLIS = 15_000L
private const val LIVE_CATEGORY_SEQUENTIAL_MODE_WARNING =
"Live category sync downgraded to sequential mode after provider stress signals."
private const val XTREAM_RECOVERY_ABORT_WARNING_SUFFIX =
@@ -181,6 +199,7 @@ class SyncManager @Inject constructor(
private val tmdbIdentityDao: TmdbIdentityDao,
private val xtreamContentIndexDao: XtreamContentIndexDao,
private val xtreamIndexJobDao: XtreamIndexJobDao,
+ private val stalkerIndexJobDao: StalkerIndexJobDao,
private val xtreamLiveOnboardingDao: XtreamLiveOnboardingDao,
private val stalkerApiService: StalkerApiService,
private val episodeDao: EpisodeDao,
@@ -194,7 +213,11 @@ class SyncManager @Inject constructor(
private val syncMetadataRepository: SyncMetadataRepository,
private val transactionRunner: DatabaseTransactionRunner,
private val preferencesRepository: com.streamvault.data.preferences.PreferencesRepository,
- private val syncProgressBus: SyncProgressBus
+ private val syncProgressBus: SyncProgressBus,
+ private val stalkerRemoteIdentityResolver: StalkerRemoteIdentityResolver,
+ private val stalkerRequestCoordinator: StalkerRequestCoordinator,
+ private val stalkerPortalStateStore: StalkerPortalStateStore,
+ private val stalkerReadinessTracker: StalkerReadinessTracker
) {
private val syncStateTracker = SyncStateTracker()
private val syncErrorSanitizer = SyncErrorSanitizer()
@@ -230,7 +253,6 @@ class SyncManager @Inject constructor(
private val providerSyncMutexes = ConcurrentHashMap<Long, Mutex>()
private val providerStalkerSummaryMutexes = ConcurrentHashMap<Long, Mutex>()
private val providerStalkerIndexSectionMutexes = ConcurrentHashMap<String, Mutex>()
- private val providerStalkerFetchSemaphores = ConcurrentHashMap<Long, Semaphore>()
private val providerEpgMutexes = ConcurrentHashMap<Long, Mutex>()
private val syncAdmissionMutex = Mutex()
private val xtreamCatalogHttpService: OkHttpXtreamApiService by lazy {
@@ -353,7 +375,6 @@ class SyncManager @Inject constructor(
private suspend fun <T> withStalkerSummaryLock(
providerId: Long,
section: ContentType?,
- providerMaxConnections: Int,
block: suspend () -> T
): T = when (section) {
ContentType.MOVIE,
@@ -361,16 +382,22 @@ class SyncManager @Inject constructor(
else -> withProviderLock(providerId, block)
}
- private suspend fun <T> withStalkerFetchPermit(provider: Provider, block: suspend () -> T): T {
- val permitCount = minOf(
- provider.maxConnections.coerceAtLeast(1),
- STALKER_MAX_PARALLEL_CATEGORY_FETCHES
- ).coerceAtLeast(1)
- val semaphore = syncAdmissionMutex.withLock {
- providerStalkerFetchSemaphores.computeIfAbsent(provider.id) { Semaphore(permitCount) }
- }
- return semaphore.withPermit { block() }
- }
+ private suspend fun <T> withStalkerFetchPermit(
+ provider: Provider,
+ contentType: ContentType,
+ categoryId: Long,
+ page: Int,
+ block: suspend () -> T
+ ): T = stalkerRequestCoordinator.execute(
+ providerId = provider.id,
+ priority = StalkerRequestPriority.BACKGROUND_INDEX,
+ descriptor = StalkerRequestDescriptor(
+ contentType = contentType.name,
+ action = "INDEX_PAGE",
+ categoryKey = categoryId.toString(),
+ page = page
+ )
+ ) { block() }
suspend fun runWhenNoSyncActive(block: suspend () -> Boolean): Boolean =
syncAdmissionMutex.withLock {
@@ -382,10 +409,14 @@ class SyncManager @Inject constructor(
}
suspend fun onProviderDeleted(providerId: Long) {
- BackgroundEpgSyncWorker.cancel(applicationContext, providerId)
+ runCatching { BackgroundEpgSyncWorker.cancel(applicationContext, providerId) }
+ .onFailure { error -> Log.w(TAG, "Failed to cancel background EPG work: ${sanitizeThrowableMessage(error)}") }
+ runCatching { StalkerIndexWorker.cancel(applicationContext, providerId) }
+ .onFailure { error -> Log.w(TAG, "Failed to cancel Stalker index work: ${sanitizeThrowableMessage(error)}") }
withProviderLock(providerId) {
withProviderEpgLock(providerId) {
syncStateTracker.reset(providerId)
+ stalkerReadinessTracker.clear(providerId)
xtreamAdaptiveSyncPolicy.forgetProvider(providerId)
syncCatalogStore.clearProviderStaging(providerId)
epgRepository.onProviderDeleted(providerId)
@@ -404,9 +435,16 @@ class SyncManager @Inject constructor(
}
}
- fun scheduleProviderSyncResume(providerId: Long) {
+ fun scheduleProviderSyncResume(
+ providerId: Long,
+ configurationGeneration: Long? = null
+ ) {
runCatching {
- ProviderSyncWorker.enqueueProvider(applicationContext, providerId)
+ ProviderSyncWorker.enqueueProvider(
+ applicationContext,
+ providerId,
+ configurationGeneration
+ )
}.onFailure { error ->
Log.w(TAG, "Failed to schedule provider resume work for provider $providerId: ${sanitizeThrowableMessage(error)}")
}
@@ -429,7 +467,8 @@ class SyncManager @Inject constructor(
providerId: Long,
section: ContentType? = null,
force: Boolean = false,
- initialDelaySeconds: Long = 0L
+ initialDelaySeconds: Long = 0L,
+ appendSuccessor: Boolean = false
) {
val effectiveSection: ContentType? = null
runCatching {
@@ -438,7 +477,8 @@ class SyncManager @Inject constructor(
providerId = providerId,
section = effectiveSection?.name,
force = force,
- initialDelaySeconds = initialDelaySeconds
+ initialDelaySeconds = initialDelaySeconds,
+ appendSuccessor = appendSuccessor
)
}.onFailure { error ->
Log.w(TAG, "Failed to schedule Stalker index work for provider $providerId (${effectiveSection?.name ?: "all"}): ${sanitizeThrowableMessage(error)}")
@@ -485,30 +525,10 @@ class SyncManager @Inject constructor(
section: ContentType,
categoryId: Long
) {
+ // Interactive repositories hydrate the requested category directly. Retained as a
+ // source-compatible no-op while callers migrate to the request coordinator.
+ if (providerId <= 0L || categoryId == Long.MIN_VALUE) return
if (section != ContentType.MOVIE && section != ContentType.SERIES) return
- val now = System.currentTimeMillis()
- val updated = xtreamIndexJobDao.requestCategoryPriority(
- providerId = providerId,
- section = section.name,
- categoryId = categoryId,
- requestedAt = now
- )
- if (updated == 0) {
- upsertXtreamIndexJob(
- providerId = providerId,
- section = section.name,
- state = "QUEUED",
- now = now,
- priorityCategoryId = categoryId,
- priorityRequestedAt = now
- )
- }
- val provider = providerDao.getById(providerId)?.toDomain()
- if (provider != null) {
- scheduleStalkerIndexContinuation(provider, section, force = false)
- } else {
- scheduleStalkerIndexSync(providerId, section, force = false)
- }
}
suspend fun syncEpg(
@@ -542,16 +562,6 @@ class SyncManager @Inject constructor(
.toDomain()
val providerId = provider.id
- if (!force && provider.type == ProviderType.STALKER_PORTAL && hasPendingStalkerCatalogIndex(provider.id)) {
- updateXtreamEpgJobState(
- provider = provider,
- state = "QUEUED",
- now = System.currentTimeMillis(),
- lastError = null
- )
- return com.streamvault.domain.model.Result.success(Unit)
- }
-
val startedAt = System.currentTimeMillis()
updateXtreamEpgJobState(
provider = provider,
@@ -615,7 +625,7 @@ class SyncManager @Inject constructor(
indexedRows = programDao.countByProvider(providerId),
lastError = safeMessage
)
- updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
+ updateSyncStatusMetadata(providerId = providerId, status = syncFailureStatus(provider, e))
publishSyncState(providerId, SyncState.Error(safeMessage, e))
com.streamvault.domain.model.Result.error(safeMessage, e)
}
@@ -633,12 +643,7 @@ class SyncManager @Inject constructor(
lastSuccessAt: Long? = null,
lastError: String? = null
) {
- if (
- provider.type != ProviderType.XTREAM_CODES &&
- provider.type != ProviderType.STALKER_PORTAL
- ) {
- return
- }
+ if (provider.type != ProviderType.XTREAM_CODES) return
if (provider.epgSyncMode == ProviderEpgSyncMode.SKIP) return
upsertXtreamIndexJob(
providerId = provider.id,
@@ -722,7 +727,7 @@ class SyncManager @Inject constructor(
lastError = sanitizeThrowableMessage(e)
)
}
- updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
+ updateSyncStatusMetadata(providerId = providerId, status = syncFailureStatus(provider, e))
publishSyncState(providerId, SyncState.Error(safeMessage, e))
com.streamvault.domain.model.Result.error(safeMessage, e)
}
@@ -835,7 +840,7 @@ class SyncManager @Inject constructor(
} catch (e: Exception) {
val safeMessage = syncErrorSanitizer.userMessage(e, "Index rebuild failed")
Log.e(TAG, "Xtream index rebuild failed for provider $providerId: ${syncErrorSanitizer.throwableMessage(e)}")
- updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
+ updateSyncStatusMetadata(providerId = providerId, status = syncFailureStatus(provider, e))
publishSyncState(providerId, SyncState.Error(safeMessage, e))
com.streamvault.domain.model.Result.error(safeMessage, e)
}
@@ -891,7 +896,7 @@ class SyncManager @Inject constructor(
} catch (e: Exception) {
val safeMessage = syncErrorSanitizer.userMessage(e, "Retry failed")
Log.e(TAG, "Section retry failed for provider $providerId [$section]: ${syncErrorSanitizer.throwableMessage(e)}")
- updateSyncStatusMetadata(providerId = providerId, status = "ERROR")
+ updateSyncStatusMetadata(providerId = providerId, status = syncFailureStatus(provider, e))
publishSyncState(providerId, SyncState.Error(safeMessage, e))
com.streamvault.domain.model.Result.error(safeMessage, e)
} finally {
@@ -1535,6 +1540,54 @@ class SyncManager @Inject constructor(
return ContentCachePolicy.shouldRefresh(job.lastSuccessAt, ContentCachePolicy.CATALOG_TTL_MILLIS)
}
+ fun cancelStalkerIndexSync(providerId: Long) {
+ StalkerIndexWorker.cancel(applicationContext, providerId)
+ }
+
+ suspend fun reconcileStalkerIndexWorkAtStartup() {
+ providerDao.getAllSync()
+ .filter { it.type == ProviderType.STALKER_PORTAL }
+ .forEach { provider ->
+ // v62 and older reused Xtream rows. They are never valid Stalker owners now.
+ xtreamIndexJobDao.deleteByProvider(provider.id)
+ val hasPendingOneTime = listOf(ContentType.MOVIE, ContentType.SERIES).any { section ->
+ stalkerIndexJobDao.get(provider.id, section.name)?.state in setOf(
+ StalkerIndexState.QUEUED,
+ StalkerIndexState.RUNNING,
+ StalkerIndexState.RETRY_WAIT,
+ StalkerIndexState.PARTIAL
+ )
+ }
+ if (provider.stalkerCatalogMode == StalkerCatalogMode.ON_DEMAND && !hasPendingOneTime) {
+ cancelStalkerIndexSync(provider.id)
+ } else if (provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX || hasPendingOneTime) {
+ scheduleStalkerIndexSync(provider.id)
+ }
+ }
+ }
+
+ private fun shouldRunStalkerSummaryIndex(job: StalkerIndexJobEntity?): Boolean {
+ if (job == null) return true
+ if (job.state in setOf(
+ StalkerIndexState.QUEUED,
+ StalkerIndexState.RUNNING,
+ StalkerIndexState.PARTIAL,
+ StalkerIndexState.RETRY_WAIT
+ )) return true
+ return ContentCachePolicy.shouldRefresh(job.lastSuccessAt, ContentCachePolicy.CATALOG_TTL_MILLIS)
+ }
+
+ private fun StalkerIndexState.toLegacyJobState(): String = when (this) {
+ StalkerIndexState.DISABLED -> "DISABLED"
+ StalkerIndexState.QUEUED -> "QUEUED"
+ StalkerIndexState.RUNNING -> "RUNNING"
+ StalkerIndexState.RETRY_WAIT -> "FAILED_RETRYABLE"
+ StalkerIndexState.PARTIAL -> "PARTIAL"
+ StalkerIndexState.COMPLETE -> "SUCCESS"
+ StalkerIndexState.TRUNCATED -> "TRUNCATED"
+ StalkerIndexState.FAILED -> "FAILED_PERMANENT"
+ }
+
suspend fun processQueuedStalkerIndexJobs(
providerId: Long,
section: ContentType? = null,
@@ -1542,19 +1595,7 @@ class SyncManager @Inject constructor(
maxCategoriesPerSection: Int? = null,
onProgress: ((String) -> Unit)? = null
): com.streamvault.domain.model.Result<Unit> {
- val providerMaxConnections = providerDao.getById(providerId)?.maxConnections ?: Int.MAX_VALUE
- return withStalkerSummaryLock(providerId, section, providerMaxConnections) lock@{
- val playbackDelayMillis = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId)
- if (playbackDelayMillis > 0L) {
- Log.i(TAG, "Deferring Stalker catalog work for provider $providerId because playback is active.")
- scheduleStalkerIndexSync(
- providerId = providerId,
- section = null,
- force = force,
- initialDelaySeconds = ((playbackDelayMillis + 999L) / 1000L).coerceAtLeast(1L)
- )
- return@lock com.streamvault.domain.model.Result.success(Unit)
- }
+ return withStalkerSummaryLock(providerId, section) lock@{
val providerEntity = providerDao.getById(providerId)
?: return@lock com.streamvault.domain.model.Result.error("Provider $providerId not found")
@@ -1581,7 +1622,8 @@ class SyncManager @Inject constructor(
providerId = providerId,
section = null,
force = false,
- initialDelaySeconds = decision.retryDelaySeconds
+ initialDelaySeconds = decision.retryDelaySeconds,
+ appendSuccessor = true
)
} else {
scheduleStalkerEpgIfCatalogIdle(provider)
@@ -1643,7 +1685,8 @@ class SyncManager @Inject constructor(
val runnable: Boolean,
val retryDelaySeconds: Long,
val pending: Boolean,
- val jobState: String?
+ val jobState: String?,
+ val updatedAt: Long
)
private suspend fun chooseNextStalkerCatalogSection(
@@ -1654,11 +1697,31 @@ class SyncManager @Inject constructor(
now: Long
): StalkerCatalogDecision {
val movie = stalkerCatalogSectionState(provider, api, ContentType.MOVIE, force, now)
+ val series = stalkerCatalogSectionState(provider, api, ContentType.SERIES, force, now)
+ if (requestedSection == ContentType.MOVIE && movie.runnable) {
+ return StalkerCatalogDecision(
+ ContentType.MOVIE,
+ reason = "explicit movie section is runnable (${movie.jobState ?: "no job"})"
+ )
+ }
+ if (requestedSection == ContentType.SERIES && series.runnable) {
+ return StalkerCatalogDecision(
+ ContentType.SERIES,
+ reason = "explicit series section is runnable (${series.jobState ?: "no job"})"
+ )
+ }
+ if (movie.runnable && series.runnable) {
+ val selected = listOf(movie, series).minWith(
+ compareBy<StalkerCatalogSectionState>({ it.updatedAt }, { it.contentType.ordinal })
+ )
+ return StalkerCatalogDecision(
+ selected.contentType,
+ reason = "oldest pending section is ${selected.contentType.name.lowercase()} (${selected.jobState ?: "no job"})"
+ )
+ }
if (movie.runnable) {
return StalkerCatalogDecision(ContentType.MOVIE, reason = "movies are runnable (${movie.jobState ?: "no job"})")
}
-
- val series = stalkerCatalogSectionState(provider, api, ContentType.SERIES, force, now)
if (series.runnable) {
val reason = if (movie.pending && movie.retryDelaySeconds > 0L) {
"movies are waiting ${movie.retryDelaySeconds}s for retry; series is runnable"
@@ -1692,14 +1755,15 @@ class SyncManager @Inject constructor(
force: Boolean,
now: Long
): StalkerCatalogSectionState {
- val job = xtreamIndexJobDao.get(provider.id, contentType.name)
- if (!force && !shouldRunXtreamSummaryIndex(job)) {
+ val job = stalkerIndexJobDao.get(provider.id, contentType.name)
+ if (!force && !shouldRunStalkerSummaryIndex(job)) {
return StalkerCatalogSectionState(
contentType = contentType,
runnable = false,
retryDelaySeconds = 0L,
pending = false,
- jobState = job?.state
+ jobState = job?.state?.toLegacyJobState(),
+ updatedAt = job?.updatedAt ?: 0L
)
}
@@ -1715,7 +1779,8 @@ class SyncManager @Inject constructor(
runnable = true,
retryDelaySeconds = 0L,
pending = true,
- jobState = job?.state
+ jobState = job?.state?.toLegacyJobState(),
+ updatedAt = job?.updatedAt ?: 0L
)
}
@@ -1728,14 +1793,19 @@ class SyncManager @Inject constructor(
hydration == null ||
(!hydration.isComplete && !hydration.isTerminalFailure && hydration.retryBudgetRemaining > 0)
}
- val needsStateReconciliation = job?.state in setOf("QUEUED", "RUNNING", "STALE", "FAILED_RETRYABLE") &&
+ val needsStateReconciliation = job?.state in setOf(
+ StalkerIndexState.QUEUED,
+ StalkerIndexState.RUNNING,
+ StalkerIndexState.RETRY_WAIT
+ ) &&
!hasUnresolvedWork
return StalkerCatalogSectionState(
contentType = contentType,
runnable = hasAttemptableWork || needsStateReconciliation,
retryDelaySeconds = retryDelaySeconds,
pending = hasUnresolvedWork || needsStateReconciliation,
- jobState = job?.state
+ jobState = job?.state?.toLegacyJobState(),
+ updatedAt = job?.updatedAt ?: 0L
)
}
@@ -1750,7 +1820,12 @@ class SyncManager @Inject constructor(
when {
decision.contentType != null -> {
Log.i(TAG, "Scheduling next Stalker catalog step for provider ${provider.id}: ${decision.contentType.name}")
- scheduleStalkerIndexSync(provider.id, section = null, force = false)
+ scheduleStalkerIndexSync(
+ providerId = provider.id,
+ section = null,
+ force = false,
+ appendSuccessor = true
+ )
}
decision.retryDelaySeconds > 0L -> {
Log.i(TAG, "Scheduling Stalker catalog retry for provider ${provider.id} in ${decision.retryDelaySeconds}s")
@@ -1758,49 +1833,21 @@ class SyncManager @Inject constructor(
providerId = provider.id,
section = null,
force = false,
- initialDelaySeconds = decision.retryDelaySeconds
+ initialDelaySeconds = decision.retryDelaySeconds,
+ appendSuccessor = true
)
}
}
}
private suspend fun scheduleStalkerEpgIfCatalogIdle(provider: Provider) {
- if (provider.type != ProviderType.STALKER_PORTAL || provider.epgSyncMode == ProviderEpgSyncMode.SKIP) return
- if (!hasPendingStalkerCatalogIndex(provider.id)) {
- Log.i(TAG, "Scheduling Stalker EPG for provider ${provider.id}: catalog is idle.")
- scheduleBackgroundEpgSync(provider.id)
- } else {
- Log.i(TAG, "Deferring Stalker EPG for provider ${provider.id}: catalog indexing is still pending.")
- }
- }
-
- private suspend fun hasPendingStalkerCatalogIndex(providerId: Long): Boolean {
- val now = System.currentTimeMillis()
- return listOf(ContentType.MOVIE, ContentType.SERIES).any { contentType ->
- when (xtreamIndexJobDao.get(providerId, contentType.name)?.state) {
- "QUEUED",
- "RUNNING",
- "STALE",
- "FAILED_RETRYABLE" -> true
- "PARTIAL" -> hasRetryableStalkerCategoryWork(providerId, contentType, now)
- else -> false
- }
- }
+ if (provider.type != ProviderType.STALKER_PORTAL ||
+ provider.epgSyncMode != ProviderEpgSyncMode.BACKGROUND
+ ) return
+ Log.i(TAG, "Scheduling Stalker EPG independently of catalog indexing for provider ${provider.id}.")
+ scheduleBackgroundEpgSync(provider.id)
}
- private suspend fun hasRetryableStalkerCategoryWork(
- providerId: Long,
- contentType: ContentType,
- now: Long
- ): Boolean =
- categoryDao.getByProviderAndTypeSync(providerId, contentType.name).any { category ->
- val hydration = getStalkerHydrationSnapshot(providerId, contentType, category.categoryId)
- hydration == null ||
- (!hydration.isComplete &&
- !hydration.isTerminalFailure &&
- hydration.retryBudgetRemaining > 0)
- }
-
private fun scheduleStalkerIndexContinuation(
provider: Provider,
section: ContentType,
@@ -1872,9 +1919,26 @@ class SyncManager @Inject constructor(
return
}
- val initialJob = xtreamIndexJobDao.get(provider.id, contentType.name)
+ val initialJob = stalkerIndexJobDao.get(provider.id, contentType.name)
- if (wildcardCategory != null && visibleCategories.size == 1 && visibleCategories.first().categoryId == wildcardCategory.categoryId) {
+ val learnedWildcardSupport = api.validatedPortalState()?.let { state ->
+ when (contentType) {
+ ContentType.MOVIE -> state.movieWildcardSupported
+ ContentType.SERIES -> state.seriesWildcardSupported
+ else -> null
+ }
+ }
+ if (
+ wildcardCategory != null &&
+ learnedWildcardSupport != false &&
+ visibleCategories.size == 1 &&
+ visibleCategories.first().categoryId == wildcardCategory.categoryId
+ ) {
+ StalkerTelemetry.strategySelected(
+ provider.id,
+ "${contentType.name}_WILDCARD",
+ if (learnedWildcardSupport == true) "VALIDATED_CACHE" else "CAPABILITY_PROBE"
+ )
if (processStalkerWildcardIndexSection(
provider = provider,
api = api,
@@ -1885,11 +1949,13 @@ class SyncManager @Inject constructor(
initialJob = initialJob,
onProgress = onProgress
)) {
+ api.recordWildcardCapability(contentType, supported = true)
return
}
+ } else if (wildcardCategory != null && learnedWildcardSupport == false) {
+ StalkerTelemetry.strategySelected(provider.id, "${contentType.name}_CATEGORY", "WILDCARD_KNOWN_UNSUPPORTED")
}
- val priorityCategoryId = initialJob?.priorityCategoryId
val hydrationByCategory = visibleCategories.associate { category ->
category.categoryId to getStalkerHydrationSnapshot(provider.id, contentType, category.categoryId)
}
@@ -1913,17 +1979,8 @@ class SyncManager @Inject constructor(
try {
val pending = buildList {
- priorityCategoryId
- ?.takeIf { requestedId -> visibleCategories.any { it.categoryId == requestedId } }
- ?.let { requestedId ->
- val hydration = hydrationByCategory[requestedId]
- if (canAttemptStalkerCategory(hydration, now)) {
- visibleCategories.firstOrNull { it.categoryId == requestedId }?.let(::add)
- }
- }
visibleCategories.forEach { category ->
if (size >= maxCategories) return@forEach
- if (any { it.categoryId == category.categoryId }) return@forEach
val hydration = hydrationByCategory[category.categoryId]
if (!canAttemptStalkerCategory(hydration, now)) return@forEach
add(category)
@@ -1949,6 +2006,8 @@ class SyncManager @Inject constructor(
val totalPages: Int,
val pageSize: Int,
val isComplete: Boolean,
+ val isTruncated: Boolean,
+ val terminationReason: String?,
val pageFingerprint: String?
)
@@ -1968,8 +2027,8 @@ class SyncManager @Inject constructor(
var forceSequential = parallelFetchLimit <= 1
val retriedImmediately = mutableSetOf<Long>()
while (pendingQueue.isNotEmpty() && System.currentTimeMillis() < runDeadlineAt) {
- if (StalkerTrafficCoordinator.shouldDeferCatalogFetch(provider.id)) {
- break
+ if (pagesCommitted > 0) {
+ delay(StalkerTrafficCoordinator.backgroundInterPageDelayMillis(provider.id))
}
val windowSize = minOf(
if (forceSequential) 1 else parallelFetchLimit,
@@ -2013,7 +2072,12 @@ class SyncManager @Inject constructor(
async {
StalkerCategoryFetchResult(
attempt = attempt,
- result = withStalkerFetchPermit(provider) {
+ result = withStalkerFetchPermit(
+ provider = provider,
+ contentType = contentType,
+ categoryId = attempt.category.categoryId,
+ page = attempt.nextPage
+ ) {
fetchStalkerSummaryPageWithRecovery(
api = api,
contentType = contentType,
@@ -2032,6 +2096,9 @@ class SyncManager @Inject constructor(
val category = fetched.attempt.category
val hydration = fetched.attempt.hydration
val nextPage = fetched.attempt.nextPage
+ if (fetched.result is Result.Error) {
+ stalkerRequestCoordinator.recordFailure(provider.id, fetched.result.exception)
+ }
when (val result = fetched.result) {
is Result.Success -> {
val pageFingerprint = stalkerPageFingerprint(result.data.items, contentType)
@@ -2082,6 +2149,8 @@ class SyncManager @Inject constructor(
totalPages = result.data.totalPages,
pageSize = result.data.pageSize,
isComplete = result.data.isComplete,
+ isTruncated = result.data.isTruncated,
+ terminationReason = result.data.terminationReason,
pageFingerprint = pageFingerprint
)
}
@@ -2124,9 +2193,6 @@ class SyncManager @Inject constructor(
}
is Result.Loading -> Unit
}
- if (priorityCategoryId == category.categoryId) {
- clearPriority = true
- }
}
if (successfulPages.isNotEmpty()) {
val indexedAt = System.currentTimeMillis()
@@ -2150,8 +2216,10 @@ class SyncManager @Inject constructor(
for (page in successfulPages) {
pagesCommitted += 1
rowsCommitted += page.items.size
- val pageComplete = page.isComplete ||
- (page.items.isEmpty() && page.totalPages in 1..page.requestedPage)
+ val pageComplete = !page.isTruncated && (
+ page.isComplete ||
+ (page.items.isEmpty() && page.totalPages in 1..page.requestedPage)
+ )
val categoryCount = (page.hydration?.itemCount ?: 0) + page.items.size
markStalkerAttemptSucceeded(
providerId = provider.id,
@@ -2164,9 +2232,11 @@ class SyncManager @Inject constructor(
totalPages = page.totalPages,
pageSize = page.pageSize,
pageComplete = pageComplete,
+ truncated = page.isTruncated,
+ terminationReason = page.terminationReason,
pageFingerprint = page.pageFingerprint
)
- if (!pageComplete && System.currentTimeMillis() < runDeadlineAt) {
+ if (!pageComplete && !page.isTruncated && System.currentTimeMillis() < runDeadlineAt) {
pendingQueue.addLast(page.category)
}
}
@@ -2186,6 +2256,7 @@ class SyncManager @Inject constructor(
val finishedAt = System.currentTimeMillis()
val completedCategories = refreshedHydration.values.count { it?.isComplete == true }
val failedCategories = refreshedHydration.values.count { it?.isTerminalFailure == true }
+ val truncatedCategories = refreshedHydration.values.count { it?.isTruncated == true }
val hasMoreCategories = refreshedHydration.values.any { hydration ->
canAttemptStalkerCategory(hydration, finishedAt)
}
@@ -2201,6 +2272,7 @@ class SyncManager @Inject constructor(
}
val finalState = when {
hasMoreCategories -> "QUEUED"
+ truncatedCategories > 0 -> "TRUNCATED"
failedCategories > 0 -> "PARTIAL"
pruneSuppressed -> "PARTIAL"
else -> "SUCCESS"
@@ -2217,29 +2289,18 @@ class SyncManager @Inject constructor(
indexedRows = indexedRows,
skippedMalformedRows = skippedMalformedRows,
deletedPrunedRows = deletedRows,
- clearPriority = clearPriority || finalState == "SUCCESS",
+ clearPriority = clearPriority || finalState in setOf("SUCCESS", "TRUNCATED"),
lastAttemptAt = now,
lastSuccessAt = finishedAt.takeIf { finalState == "SUCCESS" },
- lastError = refreshedHydration.values.firstOrNull { it?.lastStatus == "ERROR" }?.lastError
+ lastError = refreshedHydration.values.firstOrNull {
+ it?.lastStatus in setOf("ERROR", "TRUNCATED")
+ }?.lastError
)
updateStalkerSummaryMetadata(provider.id, contentType, indexedRows, finalState, finishedAt)
Log.i(
TAG,
"Stalker ${contentType.name} indexing finished for provider ${provider.id}: state=$finalState completed=$completedCategories failed=$failedCategories rows=$indexedRows committedPages=$pagesCommitted committedRows=$rowsCommitted throughput=${stalkerThroughputSummary(sectionStartedAt, pagesCommitted, rowsCommitted)} retryDelay=${retryDelaySeconds}s"
)
- when {
- hasMoreCategories -> scheduleStalkerIndexContinuation(provider, contentType, force = false)
- finalState == "PARTIAL" -> {
- if (retryDelaySeconds > 0L) {
- scheduleStalkerIndexContinuation(
- provider = provider,
- section = contentType,
- force = false,
- initialDelaySeconds = retryDelaySeconds
- )
- }
- }
- }
} finally {
if (contentType == ContentType.MOVIE && restoreMovieWatchProgressPending) {
movieDao.restoreWatchProgress(provider.id)
@@ -2253,8 +2314,7 @@ class SyncManager @Inject constructor(
maxCategories: Int
): Int {
val runtimeLimit = runtimeProfile.maxCategoryConcurrency.coerceAtLeast(1)
- val providerLimit = provider.maxConnections.coerceAtLeast(1)
- val effectiveLimit = minOf(runtimeLimit, providerLimit)
+ val effectiveLimit = runtimeLimit
return minOf(
maxCategories.coerceAtLeast(1),
effectiveLimit,
@@ -2280,7 +2340,7 @@ class SyncManager @Inject constructor(
wildcardCategory: CategoryEntity,
visibleCategories: List<CategoryEntity>,
maxPages: Int,
- initialJob: XtreamIndexJobEntity?,
+ initialJob: StalkerIndexJobEntity?,
onProgress: ((String) -> Unit)?
): Boolean {
val now = System.currentTimeMillis()
@@ -2318,7 +2378,9 @@ class SyncManager @Inject constructor(
try {
while (pagesProcessed < maxPages) {
- if (StalkerTrafficCoordinator.shouldDeferCatalogFetch(provider.id)) break
+ if (pagesProcessed > 0) {
+ delay(StalkerTrafficCoordinator.backgroundInterPageDelayMillis(provider.id))
+ }
val currentHydration = getStalkerHydrationSnapshot(provider.id, contentType, wildcardCategory.categoryId)
if (!canAttemptStalkerCategory(currentHydration, System.currentTimeMillis())) break
val nextPage = nextStalkerAttemptPage(currentHydration)
@@ -2331,7 +2393,18 @@ class SyncManager @Inject constructor(
attemptedPage = nextPage,
now = System.currentTimeMillis()
)
- when (val result = fetchStalkerWildcardSummaryPageWithRecovery(api, contentType, wildcardCategory.categoryId, nextPage)) {
+ val coordinatedResult = withStalkerFetchPermit(
+ provider = provider,
+ contentType = contentType,
+ categoryId = wildcardCategory.categoryId,
+ page = nextPage
+ ) {
+ fetchStalkerWildcardSummaryPageWithRecovery(api, contentType, wildcardCategory.categoryId, nextPage)
+ }
+ if (coordinatedResult is Result.Error) {
+ stalkerRequestCoordinator.recordFailure(provider.id, coordinatedResult.exception)
+ }
+ when (val result = coordinatedResult) {
is Result.Success -> {
val indexedAt = System.currentTimeMillis()
val dedupedItems = dedupeStalkerPageItems(result.data.items, contentType)
@@ -2351,6 +2424,7 @@ class SyncManager @Inject constructor(
pageFingerprint = null
)
Log.i(TAG, "$message Falling back to per-category indexing for provider ${provider.id}.")
+ api.recordWildcardCapability(contentType, supported = false)
return false
}
@@ -2362,7 +2436,11 @@ class SyncManager @Inject constructor(
items = visibleItems,
page = result.data.page,
totalPages = result.data.totalPages,
- pageSize = result.data.pageSize
+ pageSize = result.data.pageSize,
+ advertisedTotalItems = result.data.advertisedTotalItems,
+ advertisedTotalPages = result.data.advertisedTotalPages,
+ isTruncated = result.data.isTruncated,
+ terminationReason = result.data.terminationReason
),
pageFingerprint = pageFingerprint
) ?: pageFingerprint
@@ -2382,6 +2460,7 @@ class SyncManager @Inject constructor(
pageFingerprint = pageFingerprint
)
Log.i(TAG, "Stalker wildcard ${contentType.name} indexing disabled for provider ${provider.id}: $anomaly")
+ api.recordWildcardCapability(contentType, supported = false)
return false
}
@@ -2401,8 +2480,10 @@ class SyncManager @Inject constructor(
indexedRowsEstimate += visibleItems.size
rowsCommitted += visibleItems.size
- val pageComplete = result.data.isComplete ||
- (result.data.items.isEmpty() && result.data.totalPages in 1..nextPage)
+ val pageComplete = !result.data.isTruncated && (
+ result.data.isComplete ||
+ (result.data.items.isEmpty() && result.data.totalPages in 1..nextPage)
+ )
markStalkerAttemptSucceeded(
providerId = provider.id,
contentType = contentType,
@@ -2414,10 +2495,12 @@ class SyncManager @Inject constructor(
totalPages = result.data.totalPages,
pageSize = result.data.pageSize,
pageComplete = pageComplete,
+ truncated = result.data.isTruncated,
+ terminationReason = result.data.terminationReason,
pageFingerprint = pageFingerprint
)
pagesProcessed += 1
- if (pageComplete) break
+ if (pageComplete || result.data.isTruncated) break
}
is Result.Error -> {
val failedAt = System.currentTimeMillis()
@@ -2434,6 +2517,7 @@ class SyncManager @Inject constructor(
retryable = retryable,
pageFingerprint = currentHydration?.lastPageFingerprint
)
+ api.recordWildcardCapability(contentType, supported = false)
return false
}
is Result.Loading -> Unit
@@ -2446,6 +2530,7 @@ class SyncManager @Inject constructor(
val indexedRows = currentStalkerIndexedRowCount(provider.id, contentType)
val finalState = when {
hasMorePages -> "QUEUED"
+ refreshedHydration?.isTruncated == true -> "TRUNCATED"
refreshedHydration?.isTerminalFailure == true -> "PARTIAL"
refreshedHydration?.hasPruneSuppressionRisk == true -> "PARTIAL"
else -> "SUCCESS"
@@ -2462,12 +2547,12 @@ class SyncManager @Inject constructor(
now = finishedAt,
totalCategories = visibleCategories.size,
completedCategories = if (finalState == "SUCCESS") visibleCategories.size else 0,
- nextCategoryIndex = if (finalState == "SUCCESS") visibleCategories.size else 0,
+ nextCategoryIndex = if (finalState in setOf("SUCCESS", "TRUNCATED")) visibleCategories.size else 0,
failedCategories = if (finalState == "PARTIAL") 1 else 0,
indexedRows = indexedRows,
skippedMalformedRows = skippedMalformedRows,
deletedPrunedRows = deletedRows,
- clearPriority = finalState == "SUCCESS",
+ clearPriority = finalState in setOf("SUCCESS", "TRUNCATED"),
lastAttemptAt = now,
lastSuccessAt = finishedAt.takeIf { finalState == "SUCCESS" },
lastError = lastError ?: refreshedHydration?.lastError
@@ -2477,20 +2562,6 @@ class SyncManager @Inject constructor(
TAG,
"Stalker wildcard ${contentType.name} indexing finished for provider ${provider.id}: state=$finalState pages=$pagesProcessed rows=$rowsCommitted totalRows=$indexedRows throughput=${stalkerThroughputSummary(sectionStartedAt, pagesProcessed, rowsCommitted)}"
)
- when {
- hasMorePages -> scheduleStalkerIndexContinuation(provider, contentType, force = false)
- finalState == "PARTIAL" -> {
- val delaySeconds = nextRetryDelaySeconds(listOf(refreshedHydration), finishedAt)
- if (delaySeconds > 0L) {
- scheduleStalkerIndexContinuation(
- provider = provider,
- section = contentType,
- force = false,
- initialDelaySeconds = delaySeconds
- )
- }
- }
- }
return true
} finally {
if (contentType == ContentType.MOVIE && restoreMovieWatchProgressPending) {
@@ -2519,8 +2590,11 @@ class SyncManager @Inject constructor(
private val StalkerHydrationSnapshot.isTerminalFailure: Boolean
get() = lastStatus in setOf("FAILED_PERMANENT", "FAILED_BUDGET_EXHAUSTED")
+ private val StalkerHydrationSnapshot.isTruncated: Boolean
+ get() = lastStatus == "TRUNCATED"
+
private val StalkerHydrationSnapshot.hasPruneSuppressionRisk: Boolean
- get() = lastStatus in setOf("ANOMALY", "FAILED_RETRYABLE", "COOLDOWN")
+ get() = lastStatus in setOf("ANOMALY", "FAILED_RETRYABLE", "COOLDOWN", "TRUNCATED")
private suspend fun getStalkerHydrationSnapshot(
providerId: Long,
@@ -2572,6 +2646,7 @@ class SyncManager @Inject constructor(
): Boolean {
if (hydration == null) return true
if (hydration.isComplete) return false
+ if (hydration.isTruncated) return false
if (hydration.isTerminalFailure) return false
if (hydration.retryBudgetRemaining <= 0) return false
if (hydration.retryAfterMs > finishedAt) return false
@@ -2650,8 +2725,11 @@ class SyncManager @Inject constructor(
totalPages: Int,
pageSize: Int,
pageComplete: Boolean,
+ truncated: Boolean = false,
+ terminationReason: String? = null,
pageFingerprint: String?
) {
+ val status = if (truncated) "TRUNCATED" else "SUCCESS"
when (contentType) {
ContentType.MOVIE -> movieCategoryHydrationDao.upsert(
com.streamvault.data.local.entity.MovieCategoryHydrationEntity(
@@ -2659,13 +2737,13 @@ class SyncManager @Inject constructor(
categoryId = categoryId,
lastHydratedAt = now,
itemCount = itemCount,
- lastStatus = "SUCCESS",
- lastError = null,
+ lastStatus = status,
+ lastError = terminationReason,
lastLoadedPage = attemptedPage,
lastAttemptedPage = attemptedPage,
lastSuccessfulPage = attemptedPage,
totalPages = totalPages,
- isComplete = pageComplete,
+ isComplete = pageComplete && !truncated,
pageSize = pageSize,
retryAfterMs = 0L,
failureCount = 0,
@@ -2679,13 +2757,13 @@ class SyncManager @Inject constructor(
categoryId = categoryId,
lastHydratedAt = now,
itemCount = itemCount,
- lastStatus = "SUCCESS",
- lastError = null,
+ lastStatus = status,
+ lastError = terminationReason,
lastLoadedPage = attemptedPage,
lastAttemptedPage = attemptedPage,
lastSuccessfulPage = attemptedPage,
totalPages = totalPages,
- isComplete = pageComplete,
+ isComplete = pageComplete && !truncated,
pageSize = pageSize,
retryAfterMs = 0L,
failureCount = 0,
@@ -2796,6 +2874,19 @@ class SyncManager @Inject constructor(
"Recovered empty paged Stalker ${contentType.name} first page with non-paged fallback for category $categoryId"
)
fallback
+ } else if (fallback is Result.Error && fallback.exception is StalkerApiError.CatalogTruncated) {
+ val truncation = fallback.exception as StalkerApiError.CatalogTruncated
+ Result.success(
+ com.streamvault.data.remote.stalker.StalkerPagedResult(
+ items = emptyList(),
+ page = 1,
+ totalPages = truncation.pageLimit,
+ pageSize = 0,
+ advertisedTotalPages = truncation.advertisedTotalPages,
+ isTruncated = true,
+ terminationReason = "page_limit"
+ )
+ )
} else {
recovered
}
@@ -2921,16 +3012,7 @@ class SyncManager @Inject constructor(
}
private fun isLikelyStalkerAuthFailure(message: String, exception: Throwable?): Boolean {
- val normalizedMessage = message.lowercase()
- val exceptionMessage = exception?.message?.lowercase().orEmpty()
- return normalizedMessage.contains("http 401") ||
- normalizedMessage.contains("http 403") ||
- normalizedMessage.contains("token") ||
- normalizedMessage.contains("authorization") ||
- exceptionMessage.contains("http 401") ||
- exceptionMessage.contains("http 403") ||
- exceptionMessage.contains("token") ||
- exceptionMessage.contains("authorization")
+ return com.streamvault.data.remote.stalker.isStalkerAuthorizationFailure(message, exception)
}
private fun sha1Hex(value: String): String {
@@ -3717,6 +3799,45 @@ class SyncManager @Inject constructor(
lastSuccessAt: Long? = null,
lastError: String? = null
) {
+ val providerType = providerDao.getById(providerId)?.type
+ val stalkerSection = runCatching { ContentType.valueOf(section) }.getOrNull()
+ if (
+ providerType == ProviderType.STALKER_PORTAL &&
+ stalkerSection in setOf(ContentType.MOVIE, ContentType.SERIES)
+ ) {
+ val existing = stalkerIndexJobDao.get(providerId, section)
+ val mappedState = when (state) {
+ "QUEUED", "STALE" -> StalkerIndexState.QUEUED
+ "RUNNING" -> StalkerIndexState.RUNNING
+ "FAILED_RETRYABLE" -> StalkerIndexState.RETRY_WAIT
+ "PARTIAL" -> StalkerIndexState.PARTIAL
+ "SUCCESS", "COMPLETE" -> StalkerIndexState.COMPLETE
+ "TRUNCATED" -> StalkerIndexState.TRUNCATED
+ "FAILED_PERMANENT", "FAILED" -> StalkerIndexState.FAILED
+ "DISABLED", "IDLE" -> StalkerIndexState.DISABLED
+ else -> StalkerIndexState.PARTIAL
+ }
+ stalkerIndexJobDao.upsert(
+ (existing ?: StalkerIndexJobEntity(
+ providerId = providerId,
+ section = requireNotNull(stalkerSection)
+ )).copy(
+ state = mappedState,
+ totalCategories = totalCategories ?: existing?.totalCategories ?: 0,
+ completedCategories = completedCategories ?: existing?.completedCategories ?: 0,
+ nextCategoryIndex = nextCategoryIndex ?: existing?.nextCategoryIndex ?: 0,
+ failedCategories = failedCategories ?: existing?.failedCategories ?: 0,
+ indexedRows = indexedRows ?: existing?.indexedRows ?: 0,
+ skippedMalformedRows = skippedMalformedRows ?: existing?.skippedMalformedRows ?: 0,
+ deletedPrunedRows = deletedPrunedRows ?: existing?.deletedPrunedRows ?: 0,
+ lastError = lastError,
+ lastAttemptAt = lastAttemptAt ?: existing?.lastAttemptAt ?: 0L,
+ lastSuccessAt = lastSuccessAt ?: existing?.lastSuccessAt ?: 0L,
+ updatedAt = now
+ )
+ )
+ return
+ }
val existing = xtreamIndexJobDao.get(providerId, section)
xtreamIndexJobDao.upsert(
(existing ?: XtreamIndexJobEntity(providerId = providerId, section = section)).copy(
@@ -3862,6 +3983,7 @@ class SyncManager @Inject constructor(
onProgress: ((String) -> Unit)?
): SyncOutcome {
val warnings = mutableListOf<String>()
+ stalkerReadinessTracker.start(provider.id)
UrlSecurityPolicy.validateStalkerPortalUrl(provider.serverUrl)?.let { message ->
throw IllegalStateException(message)
}
@@ -3869,6 +3991,7 @@ class SyncManager @Inject constructor(
progress(provider.id, onProgress, "Connecting to portal...")
val api = createStalkerSyncProvider(provider)
requireResult(api.authenticate(), "Failed to authenticate with portal")
+ stalkerReadinessTracker.authenticated(provider.id)
var metadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
val now = System.currentTimeMillis()
@@ -3879,19 +4002,9 @@ class SyncManager @Inject constructor(
var seriesCategoryCount = 0
if (force || ContentCachePolicy.shouldRefresh(metadata.lastLiveSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
- upsertXtreamIndexJob(
- providerId = provider.id,
- section = ContentType.LIVE.name,
- state = "RUNNING",
- now = now,
- lastAttemptAt = now,
- lastError = null
- )
progress(provider.id, onProgress, "Downloading Live TV...")
val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()
val liveCatalogResult = syncStalkerLiveCatalogStaged(api, provider, hiddenLiveCategoryIds, onProgress)
- val liveCategoryCount = categoryDao.getByProviderAndTypeSync(provider.id, ContentType.LIVE.name).size
- val liveFinishedAt = System.currentTimeMillis()
metadata = metadata.copy(
lastLiveSync = now,
lastLiveSuccess = now,
@@ -3903,22 +4016,11 @@ class SyncManager @Inject constructor(
section = Section.LIVE,
itemsIndexed = liveCatalogResult.acceptedCount
)
- upsertXtreamIndexJob(
- providerId = provider.id,
- section = ContentType.LIVE.name,
- state = "SUCCESS",
- now = liveFinishedAt,
- totalCategories = liveCategoryCount,
- completedCategories = liveCategoryCount,
- nextCategoryIndex = liveCategoryCount,
- failedCategories = 0,
- indexedRows = liveCatalogResult.acceptedCount,
- lastAttemptAt = now,
- lastSuccessAt = liveFinishedAt,
- lastError = null
- )
warnings += liveCatalogResult.warnings
}
+ // LIVE_READY is emitted only after either the refreshed catalog transaction has
+ // committed or the previously committed live cache was accepted as fresh.
+ stalkerReadinessTracker.liveReady(provider.id)
if (force || ContentCachePolicy.shouldRefresh(metadata.lastMovieSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
progress(provider.id, onProgress, "Preparing Movies...")
@@ -3969,12 +4071,14 @@ class SyncManager @Inject constructor(
}
)
movieCategoryCount = categories.size
- queueStalkerIndexSection(
- providerId = provider.id,
- contentType = ContentType.MOVIE,
- totalCategories = categories.size,
- now = now
- )
+ if (provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {
+ queueStalkerIndexSection(
+ providerId = provider.id,
+ contentType = ContentType.MOVIE,
+ totalCategories = categories.size,
+ now = now
+ )
+ }
metadata = metadata.copy(
lastMovieSync = now,
lastMovieAttempt = now,
@@ -3984,7 +4088,7 @@ class SyncManager @Inject constructor(
movieCatalogStale = true
)
syncMetadataRepository.updateMetadata(metadata)
- queuedMovieIndex = true
+ queuedMovieIndex = provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX
}
if (force || ContentCachePolicy.shouldRefresh(metadata.lastSeriesSuccess, ContentCachePolicy.CATALOG_TTL_MILLIS, now)) {
@@ -4034,18 +4138,20 @@ class SyncManager @Inject constructor(
}
)
seriesCategoryCount = categories.size
- queueStalkerIndexSection(
- providerId = provider.id,
- contentType = ContentType.SERIES,
- totalCategories = categories.size,
- now = now
- )
+ if (provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX) {
+ queueStalkerIndexSection(
+ providerId = provider.id,
+ contentType = ContentType.SERIES,
+ totalCategories = categories.size,
+ now = now
+ )
+ }
metadata = metadata.copy(
lastSeriesSync = now,
seriesCount = seriesDao.getCount(provider.id).first()
)
syncMetadataRepository.updateMetadata(metadata)
- queuedSeriesIndex = true
+ queuedSeriesIndex = provider.stalkerCatalogMode == StalkerCatalogMode.BACKGROUND_INDEX
}
if (liveCount == 0 && movieCategoryCount == 0 && seriesCategoryCount == 0) {
@@ -4060,29 +4166,32 @@ class SyncManager @Inject constructor(
throw IllegalStateException(diagnostic)
}
}
-
- if (provider.epgSyncMode != ProviderEpgSyncMode.SKIP) {
- upsertXtreamIndexJob(
- providerId = provider.id,
- section = "EPG",
- state = "QUEUED",
- now = now,
- totalCategories = 1,
- completedCategories = 0,
- nextCategoryIndex = 0,
- failedCategories = 0,
- lastAttemptAt = now,
- lastError = null
- )
- }
+ // Both category shells are now committed (or their committed cache is still fresh).
+ stalkerReadinessTracker.categoriesReady(provider.id)
when {
queuedMovieIndex && queuedSeriesIndex -> scheduleStalkerIndexSync(provider.id, force = force)
queuedMovieIndex -> scheduleStalkerIndexContinuation(provider, ContentType.MOVIE, force = force)
queuedSeriesIndex -> scheduleStalkerIndexContinuation(provider, ContentType.SERIES, force = force)
- else -> scheduleStalkerEpgIfCatalogIdle(provider)
}
+ when (provider.epgSyncMode) {
+ ProviderEpgSyncMode.UPFRONT -> {
+ val epgResult = syncProviderEpg(
+ provider = provider,
+ metadata = metadata,
+ now = now,
+ force = force,
+ onProgress = onProgress
+ )
+ warnings += epgResult.warnings
+ }
+ ProviderEpgSyncMode.BACKGROUND -> scheduleBackgroundEpgSync(provider.id)
+ ProviderEpgSyncMode.SKIP -> Unit
+ }
+
+ stalkerReadinessTracker.ready(provider.id, warnings.size)
+
return if (warnings.isEmpty()) SyncOutcome() else SyncOutcome(partial = true, warnings = warnings)
}
@@ -4277,15 +4386,21 @@ class SyncManager @Inject constructor(
if (shouldUseProviderGuide(guidePolicy) &&
(force || ContentCachePolicy.shouldRefresh(updatedMetadata.lastEpgSuccess, ContentCachePolicy.EPG_TTL_MILLIS, now))
) {
- val stalkerEpgWarnings = syncStalkerPreferredEpg(
- provider = provider,
- now = now,
- onProgress = onProgress
- )
- // Any Stalker EPG warning indicates an HTTP request failure, which is
- // typically transient.
- if (stalkerEpgWarnings.isNotEmpty()) hasRetryableFailure = true
- warnings += stalkerEpgWarnings
+ val learnedEpgSupport = stalkerPortalStateStore.getValidated(provider.id)?.epgSupported
+ if (learnedEpgSupport == false && provider.epgUrl.isBlank()) {
+ StalkerTelemetry.strategySelected(provider.id, "EPG_SKIP", "EPG_KNOWN_UNSUPPORTED")
+ warnings += "Stalker portal guide is known to be unsupported; keeping cached guide data."
+ } else {
+ val stalkerEpgWarnings = syncStalkerPreferredEpg(
+ provider = provider,
+ now = now,
+ onProgress = onProgress
+ )
+ // A failed capability probe is retryable only until it is learned;
+ // subsequent syncs skip it for the validation TTL.
+ if (stalkerEpgWarnings.isNotEmpty()) hasRetryableFailure = true
+ warnings += stalkerEpgWarnings
+ }
updatedMetadata = syncMetadataRepository.getMetadata(provider.id) ?: updatedMetadata
}
}
@@ -4534,16 +4649,25 @@ class SyncManager @Inject constructor(
// Stream the bulk EPG payload program-by-program; the previous buffered API
// could materialise >30 MB JSON trees on certain Stalker portals which led to
// OOM crashes when re-entering content screens.
- api.streamBulkEpg(periodHours = 6) { program ->
- val resolvedChannelKey = aliasToChannelKey[program.channelId] ?: return@streamBulkEpg
- if (program.endTime <= program.startTime) return@streamBulkEpg
- bulkCoveredChannelKeys += resolvedChannelKey
- insertBuffer += program.copy(
- providerId = provider.id,
- channelId = resolvedChannelKey
- ).toEntity()
- if (insertBuffer.size >= STALKER_GUIDE_PROGRAM_BATCH_SIZE) {
- flushPrograms()
+ stalkerRequestCoordinator.execute(
+ providerId = provider.id,
+ priority = StalkerRequestPriority.EPG,
+ descriptor = StalkerRequestDescriptor(
+ contentType = "EPG",
+ action = "BULK_GUIDE"
+ )
+ ) {
+ api.streamBulkEpg(periodHours = 6) { program ->
+ val resolvedChannelKey = aliasToChannelKey[program.channelId] ?: return@streamBulkEpg
+ if (program.endTime <= program.startTime) return@streamBulkEpg
+ bulkCoveredChannelKeys += resolvedChannelKey
+ insertBuffer += program.copy(
+ providerId = provider.id,
+ channelId = resolvedChannelKey
+ ).toEntity()
+ if (insertBuffer.size >= STALKER_GUIDE_PROGRAM_BATCH_SIZE) {
+ flushPrograms()
+ }
}
}.let { result ->
if (result is com.streamvault.domain.model.Result.Error) {
@@ -4568,7 +4692,16 @@ class SyncManager @Inject constructor(
runCatching {
var perChannelRecordCount = 0
val foreignChannelIds = HashSet<String>()
- val streamResult = api.streamEpg(request.channelKey) { program ->
+ val streamResult = stalkerRequestCoordinator.execute(
+ providerId = provider.id,
+ priority = StalkerRequestPriority.EPG,
+ descriptor = StalkerRequestDescriptor(
+ contentType = "EPG",
+ action = "CHANNEL_GUIDE",
+ itemKey = request.channelKey
+ )
+ ) {
+ api.streamEpg(request.channelKey) { program ->
if (program.endTime <= program.startTime) return@streamEpg
if (program.channelId != request.channelKey) {
foreignChannelIds += program.channelId
@@ -4587,6 +4720,7 @@ class SyncManager @Inject constructor(
if (insertBuffer.size >= STALKER_GUIDE_PROGRAM_BATCH_SIZE) {
flushPrograms()
}
+ }
}
if (streamResult is com.streamvault.domain.model.Result.Error) {
throw streamResult.exception ?: IllegalStateException(streamResult.message)
@@ -4613,12 +4747,16 @@ class SyncManager @Inject constructor(
flushPrograms()
if (replacedChannelKeys.isEmpty() && failedChannels.isNotEmpty()) {
+ api.recordEpgCapability(supported = false)
return listOf(
"Stalker portal guide sync failed for all ${failedChannels.size} channels; keeping existing guide data."
)
}
val epgCount = programDao.countByProvider(provider.id)
+ if (replacedChannelKeys.isNotEmpty() || bulkCoveredChannelKeys.isNotEmpty()) {
+ api.recordEpgCapability(supported = true)
+ }
val guideLooksHealthy = epgCount >= STALKER_MIN_HEALTHY_EPG_PROGRAMS || previousProgramCount == 0
val existingMetadata = syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id)
syncMetadataRepository.updateMetadata(
@@ -4823,19 +4961,9 @@ class SyncManager @Inject constructor(
ProviderType.STALKER_PORTAL -> {
emitCatalogSyncProgress(section = Section.LIVE)
progress(provider.id, onProgress, "Retrying Live TV...")
- upsertXtreamIndexJob(
- providerId = provider.id,
- section = ContentType.LIVE.name,
- state = "RUNNING",
- now = now,
- lastAttemptAt = now,
- lastError = null
- )
val api = createStalkerSyncProvider(provider)
val hiddenLiveCategoryIds = preferencesRepository.getHiddenCategoryIds(provider.id, ContentType.LIVE).first()
val liveCatalogResult = syncStalkerLiveCatalogStaged(api, provider, hiddenLiveCategoryIds, onProgress)
- val liveCategoryCount = categoryDao.getByProviderAndTypeSync(provider.id, ContentType.LIVE.name).size
- val liveFinishedAt = System.currentTimeMillis()
val metadata = (syncMetadataRepository.getMetadata(provider.id) ?: SyncMetadata(provider.id))
.copy(
lastLiveSync = now,
@@ -4847,20 +4975,6 @@ class SyncManager @Inject constructor(
section = Section.LIVE,
itemsIndexed = liveCatalogResult.acceptedCount
)
- upsertXtreamIndexJob(
- providerId = provider.id,
- section = ContentType.LIVE.name,
- state = "SUCCESS",
- now = liveFinishedAt,
- totalCategories = liveCategoryCount,
- completedCategories = liveCategoryCount,
- nextCategoryIndex = liveCategoryCount,
- failedCategories = 0,
- indexedRows = liveCatalogResult.acceptedCount,
- lastAttemptAt = now,
- lastSuccessAt = liveFinishedAt,
- lastError = null
- )
sectionWarnings += liveCatalogResult.warnings
}
@@ -5135,6 +5249,21 @@ class SyncManager @Inject constructor(
syncMetadataRepository.updateMetadata(metadata)
}
+ private fun syncFailureStatus(provider: Provider, error: Throwable): String {
+ if (provider.type != ProviderType.STALKER_PORTAL) return "ERROR"
+ val causes = generateSequence(error as Throwable?) { it.cause }.toList()
+ return when {
+ causes.any { it is StalkerApiError.PartialAuthorization } -> "PARTIAL_AUTHORIZATION"
+ causes.any { it is StalkerApiError.AccountBlocked } -> "ACCOUNT_BLOCKED"
+ causes.any { it is StalkerApiError.RateLimited } -> "RATE_LIMITED"
+ causes.any { it is StalkerApiError.TokenRejected } -> "SESSION_REJECTED"
+ causes.any { it is StalkerApiError.InvalidMac } -> "INVALID_MAC"
+ causes.any { it is StalkerApiError.ModelRejected } -> "MODEL_REJECTED"
+ causes.any { it is StalkerApiError.Authorization } -> "AUTHORIZATION_REJECTED"
+ else -> "ERROR"
+ }
+ }
+
private fun shouldRememberSequentialPreference(error: Throwable): Boolean {
return xtreamAdaptiveSyncPolicy.isProviderStress(error) ||
error is XtreamAuthenticationException ||
@@ -5512,10 +5641,56 @@ class SyncManager @Inject constructor(
deviceId = provider.stalkerDeviceId,
deviceId2 = provider.stalkerDeviceId2,
signature = provider.stalkerSignature,
- stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson
+ stalkerAdvancedOptionsJson = provider.stalkerAdvancedOptionsJson,
+ protocolPreference = provider.stalkerProtocolPreference,
+ transportGrant = provider.toStalkerTransportGrant(),
+ requestedProfileId = provider.stalkerRequestedProfileId,
+ learnedProfileId = provider.stalkerLearnedProfileId,
+ identityResolver = stalkerRemoteIdentityResolver,
+ portalStateStore = stalkerPortalStateStore
)
}
+ /**
+ * Rebuilds the persisted transport consent for sync-time re-authentication. Without this,
+ * providers on cleartext HTTP (or user-accepted TLS) would fail every background
+ * authentication with a consent challenge even though the user already consented when the
+ * provider was added.
+ */
+ private fun Provider.toStalkerTransportGrant(): StalkerTransportGrant? {
+ if (stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_HTTP &&
+ stalkerTransportMode != StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS &&
+ stalkerTransportMode != StalkerTransportMode.VERIFIED_HTTPS
+ ) {
+ return null
+ }
+ val origin = stalkerTransportOrigin.toStalkerOrigin()
+ ?: serverUrl.toStalkerOrigin()
+ ?: return null
+ val pin = stalkerTlsSpkiSha256.takeIf(String::isNotBlank)
+ if (stalkerTransportMode == StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS && pin == null) {
+ return null
+ }
+ return StalkerTransportGrant(
+ mode = stalkerTransportMode,
+ origin = origin,
+ spkiSha256 = pin,
+ consentedAt = stalkerTransportConsentAt
+ )
+ }
+
+ private fun String.toStalkerOrigin(): StalkerTransportOrigin? {
+ val uri = runCatching { java.net.URI(trim()) }.getOrNull() ?: return null
+ val scheme = uri.scheme?.lowercase()?.takeIf { it == "http" || it == "https" } ?: return null
+ val host = uri.host?.lowercase()?.takeIf(String::isNotBlank) ?: return null
+ val port = when {
+ uri.port != -1 -> uri.port
+ scheme == "https" -> 443
+ else -> 80
+ }
+ return StalkerTransportOrigin(scheme, host, port)
+ }
+
private suspend fun loadStalkerChannelsByCategory(
api: StalkerProvider,
categories: List<com.streamvault.domain.model.Category>,
@@ -5595,6 +5770,7 @@ class SyncManager @Inject constructor(
val batch = ArrayList<Channel>(XTREAM_FALLBACK_STAGE_BATCH_SIZE)
var stagedSessionId: Long? = null
var acceptedCount = 0
+ var bulkRowsWithResolvedCategories = 0
suspend fun flushBatch() {
if (batch.isEmpty()) return
@@ -5630,14 +5806,16 @@ class SyncManager @Inject constructor(
.distinctBy { it.categoryId to it.type }
.takeIf { it.isNotEmpty() }
if (acceptedCount == 0 || sessionId == null) {
- syncCatalogStore.replaceLiveCatalog(
- providerId = provider.id,
- categories = categories,
- channels = emptyList()
- )
+ // An empty discovery result is not proof that a previously working
+ // catalog became empty. Keep the committed generation intact and
+ // discard only rows owned by this attempt.
+ sessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }
return StagedStalkerLiveCatalogResult(
acceptedCount = 0,
- warnings = (warnings + "Live TV provider exposed no live channels; continuing with VOD and series only.").distinct()
+ warnings = (
+ warnings +
+ "Live TV returned no usable channels; keeping the last verified Live catalog."
+ ).distinct()
)
}
syncCatalogStore.applyStagedLiveCatalog(provider.id, sessionId, categories)
@@ -5646,20 +5824,60 @@ class SyncManager @Inject constructor(
try {
var bulkFailure: Exception? = null
- when (val streamResult = api.streamLiveStreams { channel ->
- if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds) {
- return@streamLiveStreams
+ val learnedState = api.validatedPortalState()
+ val shouldTryBulk = (
+ learnedState?.bulkLiveSupported != false &&
+ learnedState?.bulkLiveCategoryFidelity != false
+ ) || preferredCategories.isNullOrEmpty()
+ if (shouldTryBulk) {
+ StalkerTelemetry.strategySelected(
+ provider.id,
+ "BULK_LIVE",
+ if (learnedState?.bulkLiveSupported == true) "VALIDATED_CACHE" else "CAPABILITY_PROBE"
+ )
+ } else {
+ StalkerTelemetry.strategySelected(
+ provider.id,
+ "CATEGORY_LIVE",
+ if (learnedState?.bulkLiveCategoryFidelity == false) {
+ "BULK_CATEGORY_FIDELITY_FAILED"
+ } else {
+ "BULK_KNOWN_UNSUPPORTED"
}
- batch += channel
- if (batch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {
- flushBatch()
+ )
+ }
+ val streamResult = if (shouldTryBulk) {
+ withTimeoutOrNull(STALKER_BULK_LIVE_REQUEST_TIMEOUT_MILLIS) {
+ api.streamLiveStreams { channel ->
+ if (channel.categoryId != null && channel.categoryId in hiddenLiveCategoryIds) {
+ return@streamLiveStreams
+ }
+ if (channel.categoryId != null) bulkRowsWithResolvedCategories += 1
+ batch += channel
+ if (batch.size >= XTREAM_FALLBACK_STAGE_BATCH_SIZE) {
+ flushBatch()
+ progress(
+ provider.id,
+ onProgress,
+ "Loading live channels... $acceptedCount imported"
+ )
+ }
}
- }) {
+ }
+ } else {
+ null
+ }
+ when (streamResult) {
is com.streamvault.domain.model.Result.Success -> {
flushBatch()
+ api.recordBulkLiveCapability(
+ supported = true,
+ categoryFidelity = acceptedCount == 0 || bulkRowsWithResolvedCategories > 0
+ )
return finalizeStagedImport()
}
is com.streamvault.domain.model.Result.Error -> {
+ api.recordBulkLiveCapability(supported = false)
val profileDiagnostic = stalkerCatalogAccessDiagnostic(
api = api,
primaryMessage = categoriesErrorMessage.orEmpty(),
@@ -5677,6 +5895,11 @@ class SyncManager @Inject constructor(
)
}
is com.streamvault.domain.model.Result.Loading -> throw IllegalStateException("Unexpected loading state")
+ null -> if (shouldTryBulk) {
+ api.recordBulkLiveCapability(supported = false)
+ bulkFailure = IOException("Bulk live request timed out; switching to category requests.")
+ progress(provider.id, onProgress, "Bulk live request is slow; loading categories instead...")
+ }
}
stagedSessionId?.let { syncCatalogStore.discardStagedImport(provider.id, it) }
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 b32c0b3a..44e55d6a 100644
--- a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
@@ -30,11 +30,13 @@ import com.streamvault.domain.model.DecoderMode
import com.streamvault.domain.model.Favorite
import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.Provider
+import com.streamvault.domain.model.ProviderStatus
import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.RecordingItem
import com.streamvault.domain.model.RecordingRecurrence
import com.streamvault.domain.model.RecordingStatus
import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.StalkerTransportMode
import com.streamvault.domain.repository.CategoryRepository
import java.io.ByteArrayInputStream
import kotlinx.coroutines.runBlocking
@@ -88,6 +90,81 @@ class BackupManagerImplTest {
verify(preferencesRepository, never()).setParentalControlLevel(any())
}
+ @Test
+ fun `import strips Stalker transport consent and requires attention for HTTP`() = runBlocking {
+ val context: Context = mock()
+ val contentResolver: ContentResolver = mock()
+ val providerDao: ProviderDao = mock()
+ val credentialCrypto: CredentialCrypto = mock()
+ val gson = Gson()
+ val backup = BackupData(
+ providers = listOf(
+ Provider(
+ id = 9L,
+ name = "MAG",
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = "http://portal.example.com/c/",
+ stalkerMacAddress = "00:1A:79:12:34:56",
+ stalkerTransportMode = StalkerTransportMode.USER_ACCEPTED_HTTP,
+ stalkerTransportOrigin = "http://portal.example.com",
+ stalkerTlsSpkiSha256 = "sha256/must-not-survive",
+ stalkerTransportConsentAt = 1234L,
+ isActive = true,
+ status = ProviderStatus.ACTIVE
+ )
+ )
+ )
+ whenever(context.contentResolver).thenReturn(contentResolver)
+ whenever(contentResolver.openInputStream(Uri.parse("content://stalker-backup"))).thenReturn(
+ ByteArrayInputStream(gson.toJson(backup).toByteArray())
+ )
+ whenever(providerDao.getAllSync()).thenReturn(emptyList())
+ whenever(credentialCrypto.encryptIfNeeded(any())).thenAnswer { invocation ->
+ invocation.arguments.first() as String
+ }
+ val manager = BackupManagerImpl(
+ context = context,
+ preferencesRepository = mock(),
+ credentialCrypto = credentialCrypto,
+ providerDao = providerDao,
+ favoriteDao = mock(),
+ virtualGroupDao = mock(),
+ playbackHistoryDao = mock(),
+ movieDao = mock(),
+ episodeDao = mock(),
+ categoryRepository = mock(),
+ recordingScheduleDao = mock(),
+ recordingManager = mock(),
+ transactionRunner = object : DatabaseTransactionRunner {
+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
+ },
+ gson = gson
+ )
+
+ val result = manager.importConfig(
+ uriString = "content://stalker-backup",
+ plan = BackupImportPlan(
+ importPreferences = false,
+ importProviders = true,
+ importSavedLibrary = false,
+ importPlaybackHistory = false,
+ importMultiViewPresets = false,
+ importRecordingSchedules = false
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val inserted = org.mockito.kotlin.argumentCaptor<ProviderEntity>()
+ verify(providerDao).insert(inserted.capture())
+ assertThat(inserted.firstValue.stalkerTransportMode)
+ .isEqualTo(StalkerTransportMode.AUTO_STRICT)
+ assertThat(inserted.firstValue.stalkerTransportOrigin).isEmpty()
+ assertThat(inserted.firstValue.stalkerTlsSpkiSha256).isEmpty()
+ assertThat(inserted.firstValue.stalkerTransportConsentAt).isEqualTo(0L)
+ assertThat(inserted.firstValue.isActive).isFalse()
+ assertThat(inserted.firstValue.status).isEqualTo(ProviderStatus.PARTIAL)
+ }
+
@Test
fun `importConfig replace history only deletes imported providers and resyncs them in transaction`() = runBlocking {
val context: Context = mock()
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt
index 0b9f0442..054f57fc 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/OkHttpStalkerApiServiceTest.kt
@@ -4,27 +4,177 @@ import com.google.common.truth.Truth.assertThat
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.StalkerAuthMode
import com.streamvault.domain.model.StalkerBootstrapRecipe
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
import com.streamvault.domain.model.StalkerEndpointPreference
import com.streamvault.domain.model.StalkerMagPreset
import com.streamvault.domain.model.StalkerPlaybackBackendHint
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.cancelAndJoin
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.test.runCurrent
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
+import okhttp3.Call
+import okhttp3.Callback
+import okhttp3.Cookie
+import okhttp3.HttpUrl.Companion.toHttpUrl
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.OkHttpClient
import okhttp3.Protocol
+import okhttp3.Request
import okhttp3.Response
import okhttp3.ResponseBody.Companion.toResponseBody
+import okio.Timeout
import org.junit.Test
import java.time.LocalDateTime
+import java.time.ZoneId
import java.time.ZoneOffset
+@OptIn(ExperimentalCoroutinesApi::class)
class OkHttpStalkerApiServiceTest {
+ @Test
+ fun authenticate_rejects_profile_msg_that_reports_invalid_mac() = runTest {
+ val service = OkHttpStalkerApiService(
+ okHttpClient = fakeClient(
+ "handshake" to """{"js":{"token":"token-123"}}""",
+ "get_profile" to """{"js":{"status":1,"msg":"Not valid MAC"}}"""
+ ),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(
+ buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(StalkerApiError.Authorization::class.java)
+ assertThat(error.message).contains("Not valid MAC")
+ }
+
+ @Test
+ fun getVodCategories_classifies_plain_text_unauthorized_as_authorization_failure() = runTest {
+ val service = OkHttpStalkerApiService(
+ okHttpClient = fakeClient("get_categories" to "Unauthorized request."),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.getVodCategories(
+ session = StalkerSession(
+ loadUrl = "https://portal.example.com/server/load.php",
+ portalReferer = "https://portal.example.com/c/",
+ token = "token-123"
+ ),
+ profile = buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat((result as Result.Error).exception)
+ .isInstanceOf(StalkerApiError.Authorization::class.java)
+ }
+
+ @Test
+ fun cancellableTransport_cancelsUnderlyingOkHttpCall() = runTest {
+ val call = PendingCall()
+ val job = launch {
+ withCancellableStalkerCall(call) { error("A pending call must not produce a response") }
+ }
+
+ runCurrent()
+ assertThat(call.enqueued).isTrue()
+
+ job.cancelAndJoin()
+
+ assertThat(call.cancelled).isTrue()
+ }
+
+ @Test
+ fun cancellableTransport_keepsCallCancellationActiveWhileResponseIsBeingConsumed() = runTest {
+ val call = PendingCall()
+ var responseConsumptionStarted = false
+ val job = launch {
+ withCancellableStalkerCall(call) {
+ responseConsumptionStarted = true
+ awaitCancellation()
+ }
+ }
+
+ runCurrent()
+ call.respond()
+ runCurrent()
+ assertThat(responseConsumptionStarted).isTrue()
+
+ job.cancelAndJoin()
+
+ assertThat(call.cancelled).isTrue()
+ }
+
+ @Test
+ fun cookieJar_handlesConcurrentUpdatesWithoutLosingProviderSessionCookies() = runTest {
+ val jar = InMemoryStalkerCookieJar()
+ val url = "https://portal.example.com/server/load.php".toHttpUrl()
+
+ coroutineScope {
+ (0 until 100).map { index ->
+ async(Dispatchers.Default) {
+ jar.saveFromResponse(
+ url,
+ listOf(
+ Cookie.Builder()
+ .name("session_$index")
+ .value(index.toString())
+ .hostOnlyDomain(url.host)
+ .path("/")
+ .build()
+ )
+ )
+ }
+ }.awaitAll()
+ }
+
+ assertThat(jar.loadForRequest(url).map { cookie -> cookie.name }.toSet()).hasSize(100)
+ }
+
+ @Test
+ fun offsetlessExpiration_usesDeviceProfileTimezoneIncludingNonHourOffsets() {
+ val zone = ZoneId.of("Asia/Kathmandu")
+
+ val parsed = parseExpirationDate("2026-07-13 12:30:00", zone)
+
+ assertThat(parsed).isEqualTo(LocalDateTime.of(2026, 7, 13, 12, 30).atZone(zone).toInstant().toEpochMilli())
+ }
+
+ @Test
+ fun explicitOffsetExpiration_isNotReinterpretedInPortalTimezone() {
+ val parsed = parseExpirationDate("2026-07-13T12:30:00+03:30", ZoneId.of("America/New_York"))
+
+ assertThat(parsed).isEqualTo(java.time.OffsetDateTime.parse("2026-07-13T12:30:00+03:30").toInstant().toEpochMilli())
+ }
+
@Test
fun authenticate_retries_with_legacy_recipe_and_updates_profile_metadata() = runTest {
val requestedVersions = mutableListOf<String>()
val requestedImages = mutableListOf<String>()
+ var handshakeCount = 0
val service = OkHttpStalkerApiService(
okHttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
@@ -35,7 +185,10 @@ class OkHttpStalkerApiServiceTest {
requestedImages += request.url.queryParameter("image_version").orEmpty()
}
val body = when (action) {
- "handshake" -> """{"js":{"token":"token-123"}}"""
+ "handshake" -> {
+ handshakeCount++
+ """{"js":{"token":"token-$handshakeCount"}}"""
+ }
"get_profile" -> if (request.url.queryParameter("image_version") != "216") {
""
} else {
@@ -76,6 +229,306 @@ class OkHttpStalkerApiServiceTest {
assertThat(success.data.first.recipeEvidence).containsAtLeast("fallback_recipe", "rediscovery_attempted")
assertThat(requestedImages).containsAtLeast("218", "216").inOrder()
assertThat(requestedVersions.last()).contains("0.2.16-r17-250")
+ assertThat(handshakeCount).isEqualTo(2)
+ }
+
+ @Test
+ fun authenticate_auto_triesMacOnlyBeforeCredentialBackedAuth() = runTest {
+ val requestedActions = mutableListOf<String>()
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ requestedActions += action
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token-123"}}"""
+ "get_profile" -> """
+ {"js":{"id":"42","name":"MAC Account","status":"1","auth_access":true}}
+ """.trimIndent()
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(
+ buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ authMode = StalkerAuthMode.AUTO,
+ username = "optional-user",
+ password = "optional-password",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val session = (result as Result.Success).data.first
+ assertThat(session.effectiveAuthMode).isEqualTo(StalkerAuthMode.MAC_ONLY)
+ assertThat(requestedActions).containsExactly("handshake", "get_profile").inOrder()
+ }
+
+ @Test
+ fun authenticate_cached_profile_stops_after_fresh_session_catalog_denial() = runTest {
+ var handshakeCount = 0
+ val requestedImages = mutableListOf<String>()
+ val progress = mutableListOf<String>()
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ if (action == "get_profile") {
+ requestedImages += request.url.queryParameter("image_version").orEmpty()
+ }
+ val body = when (action) {
+ "handshake" -> {
+ handshakeCount++
+ """{"js":{"token":"token-$handshakeCount","random":"random-$handshakeCount"}}"""
+ }
+ "get_profile" -> """{"js":{"id":"42","name":"Accepted Box","status":"1","stb_type":"MAG254"}}"""
+ "get_main_info", "get_modules" -> """{"js":{}}"""
+ "get_genres", "get_categories" -> """{"js":{"not_valid_token":true}}"""
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(
+ buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ requestedProfileId = StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC,
+ requireCatalogValidation = true,
+ allowCompatibilityDiscovery = false,
+ onProgress = progress::add
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(StalkerApiError.PartialAuthorization::class.java)
+ assertThat(error.message).contains("accepted the device profile")
+ assertThat(handshakeCount).isEqualTo(2)
+ assertThat(requestedImages).containsExactly("218", "218")
+ assertThat(progress).containsAtLeast(
+ "Trying MAG250 (Generic)",
+ "Handshake accepted",
+ "Profile accepted; checking catalog",
+ "Validating Live TV categories",
+ "Catalog authorization rejected; retrying fresh session"
+ )
+ }
+
+ @Test
+ fun authenticate_auto_continues_after_profile_scoped_catalog_denial_and_finds_mag254() = runTest {
+ var handshakeCount = 0
+ val requestedModels = mutableListOf<String>()
+ val progress = mutableListOf<String>()
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ val isMag254 = request.header("User-Agent").orEmpty().contains("MAG254")
+ if (action == "get_profile") {
+ requestedModels += request.url.queryParameter("stb_type").orEmpty()
+ }
+ val body = when (action) {
+ "handshake" -> {
+ handshakeCount++
+ """{"js":{"token":"token-$handshakeCount","random":"random-$handshakeCount"}}"""
+ }
+ "get_profile" -> """{"js":{"id":"42","name":"Accepted Box","status":"1","stb_type":"MAG254"}}"""
+ "get_main_info", "get_localization", "get_events" -> """{"js":{}}"""
+ "get_genres" -> if (isMag254) {
+ """{"js":[{"id":"1","title":"News"}]}"""
+ } else {
+ "Not valid MAC"
+ }
+ "get_ordered_list" -> """{"js":{"data":[{"id":"7","name":"News 1","cmd":"ffmpeg http://localhost/ch/7_"}],"total_items":1,"max_page_items":14}}"""
+ "create_link" -> """{"js":{"cmd":"ffmpeg https://cdn.example.com/live/7.m3u8"}}"""
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(
+ buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ requireCatalogValidation = true,
+ onProgress = progress::add
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val success = result as Result.Success
+ assertThat(success.data.first.compatibilityProfileId)
+ .isEqualTo(StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT)
+ assertThat(success.data.first.bootstrapEvidence).containsAtLeast(
+ "catalog:itv:categories_valid",
+ "catalog:itv:page_valid",
+ "playback:live:create_link"
+ )
+ assertThat(requestedModels).containsAtLeast("MAG250", "MAG254").inOrder()
+ assertThat(handshakeCount).isEqualTo(2)
+ assertThat(progress).contains("Portal reports MAG254 (Strict); validating that profile")
+ assertThat(progress).contains("Validating Live TV playback link")
+ }
+
+ @Test
+ fun authenticate_cachedOnly_uses_exact_learned_profile_once() = runTest {
+ var handshakeCount = 0
+ val requestedImages = mutableListOf<String>()
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ val body = when (action) {
+ "handshake" -> {
+ handshakeCount++
+ """{"js":{"token":"token-$handshakeCount"}}"""
+ }
+ "get_profile" -> {
+ requestedImages += request.url.queryParameter("image_version").orEmpty()
+ """{"js":{"status":1,"msg":"Not valid MAC"}}"""
+ }
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val profile = buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ learnedProfileId = StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN,
+ allowCompatibilityDiscovery = false
+ ).copy(providerId = 42L)
+
+ val result = service.authenticate(profile)
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat(handshakeCount).isEqualTo(1)
+ assertThat(requestedImages).containsExactly("221")
+ }
+
+ @Test
+ fun authenticate_reports_higherRanked_primary_failure_instead_of_last_fallback() = runTest {
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token"}}"""
+ "get_profile" -> if (request.url.queryParameter("image_version") == "218") {
+ """{"js":{"status":1,"msg":"Not valid MAC"}}"""
+ } else {
+ ""
+ }
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat((result as Result.Error).message).contains("Not valid MAC")
+ assertThat(result.exception).isInstanceOf(StalkerApiError.InvalidMac::class.java)
+ }
+
+ @Test
+ fun authenticate_accountBlocked_is_terminal_for_discovery() = runTest {
+ var profileRequests = 0
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token"}}"""
+ "get_profile" -> {
+ profileRequests++
+ """{"js":{"error":"Account blocked"}}"""
+ }
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat((result as Result.Error).exception).isInstanceOf(StalkerApiError.AccountBlocked::class.java)
+ assertThat(profileRequests).isEqualTo(1)
}
@Test
@@ -130,7 +583,7 @@ class OkHttpStalkerApiServiceTest {
}
@Test
- fun authenticate_doesNotSwitchEndpointsAfterHandshakeSucceeds() = runTest {
+ fun authenticate_switchesEndpointsWhenHandshakeSucceedsButProfileFails() = runTest {
val requestedPaths = mutableListOf<String>()
val service = OkHttpStalkerApiService(
okHttpClient = OkHttpClient.Builder()
@@ -173,11 +626,66 @@ class OkHttpStalkerApiServiceTest {
)
)
- assertThat(result).isInstanceOf(Result.Error::class.java)
- assertThat(requestedPaths).doesNotContain("/portal.php")
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ assertThat(requestedPaths).contains("/portal.php")
assertThat(requestedPaths).contains("/server/load.php")
}
+ @Test
+ fun authenticate_uses_effective_loadScript_after_http_redirect() = runTest {
+ val requestedPaths = mutableListOf<String>()
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ requestedPaths += request.url.encodedPath
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token-123"}}"""
+ "get_profile" -> """{"js":{"name":"Redirected Portal","status":"1","auth_access":true}}"""
+ else -> """{"js":{}}"""
+ }
+ val effectiveRequest = if (action == "handshake") {
+ request.newBuilder()
+ .url("https://portal.example.com/stalker_portal/server/load.php?type=stb&action=handshake")
+ .build()
+ } else {
+ request
+ }
+ Response.Builder()
+ .request(effectiveRequest)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(
+ buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val session = (result as Result.Success).data.first
+ assertThat(session.loadUrl)
+ .isEqualTo("https://portal.example.com/stalker_portal/server/load.php")
+ // First request is the bare-base hint probe (GET /), then the original candidate,
+ // then every call after the handshake redirect was adopted.
+ assertThat(requestedPaths.first()).isEqualTo("/")
+ assertThat(requestedPaths[1]).isEqualTo("/server/load.php")
+ assertThat(requestedPaths.drop(2).distinct())
+ .containsExactly("/stalker_portal/server/load.php")
+ }
+
@Test
fun authenticate_usesOnlyLearnedServerLoadEndpoint() = runTest {
val requestedPaths = mutableListOf<String>()
@@ -232,7 +740,7 @@ class OkHttpStalkerApiServiceTest {
}
@Test
- fun authenticate_locks_to_first_http200_endpoint_before_full_authentication() = runTest {
+ fun authenticate_scopes_endpoint_handshake_evidence_to_each_identity_profile() = runTest {
val requestedPaths = mutableListOf<String>()
val requestedActions = mutableListOf<String>()
val service = OkHttpStalkerApiService(
@@ -285,13 +793,16 @@ class OkHttpStalkerApiServiceTest {
)
assertThat(result).isInstanceOf(Result.Success::class.java)
- assertThat(requestedPaths.count { it == "/server/load.php" }).isEqualTo(1)
+ assertThat(requestedPaths.count { it == "/server/load.php" }).isEqualTo(4)
assertThat(requestedActions.first()).isEqualTo("/server/load.php:handshake")
- assertThat(requestedActions.drop(1)).containsAtLeast(
+ assertThat(requestedActions).containsAtLeast(
"/portal.php:handshake",
"/portal.php:get_profile"
)
- assertThat(requestedPaths.drop(1).distinct()).containsExactly("/portal.php")
+ assertThat(requestedPaths.distinct()).containsExactly(
+ "/server/load.php",
+ "/portal.php"
+ )
}
@Test
@@ -913,8 +1424,10 @@ class OkHttpStalkerApiServiceTest {
}
@Test
- fun authenticate_uses_device_id2_for_metrics_uid_and_omits_signature_and_video_out() = runTest {
+ fun authenticate_uses_handshake_random_and_truthful_identity_metrics() = runTest {
val requestedMetrics = mutableListOf<String>()
+ val requestedAuthSecondSteps = mutableListOf<String>()
+ val requestedHardwareHashes = mutableListOf<String>()
val service = OkHttpStalkerApiService(
okHttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
@@ -922,9 +1435,11 @@ class OkHttpStalkerApiServiceTest {
val action = request.url.queryParameter("action").orEmpty()
if (action == "get_profile") {
requestedMetrics += request.url.queryParameter("metrics").orEmpty()
+ requestedAuthSecondSteps += request.url.queryParameter("auth_second_step").orEmpty()
+ requestedHardwareHashes += request.url.queryParameter("hw_version_2").orEmpty()
}
val body = when (action) {
- "handshake" -> """{"js":{"token":"token-123"}}"""
+ "handshake" -> """{"js":{"token":"token-123","random":"challenge-456"}}"""
"get_profile" -> """{"js":{"name":"Living Room","status":"1"}}"""
else -> error("Unexpected action '$action'")
}
@@ -956,10 +1471,12 @@ class OkHttpStalkerApiServiceTest {
assertThat(result).isInstanceOf(Result.Success::class.java)
val metrics = requestedMetrics.single()
- assertThat(metrics).contains("\"uid\":\"DEVICEID2ABCDEFG\"")
- assertThat(metrics).contains("\"random\":\"DEVICEID2ABCDEFG\"")
+ assertThat(metrics).contains("\"uid\":\"DEVICEID2ABCDEFGH\"")
+ assertThat(metrics).contains("\"random\":\"challenge-456\"")
assertThat(metrics).doesNotContain("signature")
assertThat(metrics).doesNotContain("video_out")
+ assertThat(requestedAuthSecondSteps).containsExactly("0")
+ assertThat(requestedHardwareHashes).containsExactly("")
}
@Test
@@ -1037,6 +1554,7 @@ class OkHttpStalkerApiServiceTest {
@Test
fun authenticate_retains_server_cookies_for_follow_up_playback_requests() = runTest {
val observedCookies = mutableListOf<String>()
+ val profileCookies = mutableListOf<String>()
val service = OkHttpStalkerApiService(
okHttpClient = OkHttpClient.Builder()
.addInterceptor { chain ->
@@ -1045,6 +1563,9 @@ class OkHttpStalkerApiServiceTest {
if (action == "create_link") {
observedCookies += request.header("Cookie").orEmpty()
}
+ if (action == "get_profile") {
+ profileCookies += request.header("Cookie").orEmpty()
+ }
val body = when (action) {
"handshake" -> """{"js":{"token":"token-123"}}"""
"get_profile" -> """{"js":{"name":"Living Room","status":"1"}}"""
@@ -1097,40 +1618,193 @@ class OkHttpStalkerApiServiceTest {
cmd = "ffmpeg http://localhost/ch/1234_"
)
- assertThat(createLinkResult).isInstanceOf(Result.Success::class.java)
- assertThat(authResult.data.first.serverCookieHeader).contains("PHPSESSID=session-42")
- assertThat(observedCookies.single()).contains("PHPSESSID=session-42")
- assertThat(observedCookies.single()).contains("mac=00%3A1A%3A79%3A12%3A34%3A56")
- assertThat(observedCookies.single()).contains("stb_lang=en%20us")
- assertThat(observedCookies.single()).contains("timezone=Europe%2FAmsterdam")
- assertThat(observedCookies.single()).doesNotContain("sn=")
- assertThat(observedCookies.single()).doesNotContain("device_id=")
- assertThat(observedCookies.single()).doesNotContain("device_id2=")
- assertThat(observedCookies.single()).doesNotContain("signature=")
+ assertThat(createLinkResult).isInstanceOf(Result.Success::class.java)
+ assertThat(authResult.data.first.serverCookieHeader).contains("PHPSESSID=session-42")
+ assertThat(profileCookies.single()).contains("PHPSESSID=session-42")
+ assertThat(profileCookies.single()).contains("mac=00%3A1A%3A79%3A12%3A34%3A56")
+ assertThat(observedCookies.single()).contains("PHPSESSID=session-42")
+ assertThat(observedCookies.single()).contains("mac=00%3A1A%3A79%3A12%3A34%3A56")
+ assertThat(observedCookies.single()).contains("stb_lang=en%20us")
+ assertThat(observedCookies.single()).contains("timezone=Europe%2FAmsterdam")
+ assertThat(observedCookies.single()).doesNotContain("sn=")
+ assertThat(observedCookies.single()).doesNotContain("device_id=")
+ assertThat(observedCookies.single()).doesNotContain("device_id2=")
+ assertThat(observedCookies.single()).doesNotContain("signature=")
+ }
+
+ @Test
+ fun provider_profiles_never_share_cookie_jars() = runTest {
+ val playbackCookies = mutableMapOf<String, String>()
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ val cookie = request.header("Cookie").orEmpty()
+ val profileKey = if (cookie.contains("12%3A34%3A56")) "a" else "b"
+ if (action == "create_link") playbackCookies[profileKey] = cookie
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token-$profileKey"}}"""
+ "get_profile" -> """{"js":{"name":"Profile $profileKey","status":"1"}}"""
+ "create_link" -> """{"js":{"cmd":"ffmpeg http://cdn.example.com/$profileKey.ts"}}"""
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .apply {
+ if (action == "handshake") {
+ addHeader("Set-Cookie", "PHPSESSID=session-$profileKey; Path=/; HttpOnly")
+ }
+ }
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+ val profileA = buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ val profileB = buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:57",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ val sessionA = (service.authenticate(profileA) as Result.Success).data.first
+ val sessionB = (service.authenticate(profileB) as Result.Success).data.first
+
+ service.createLink(sessionA, profileA, StalkerStreamKind.LIVE, "ffmpeg http://localhost/ch/1_")
+ service.createLink(sessionB, profileB, StalkerStreamKind.LIVE, "ffmpeg http://localhost/ch/2_")
+
+ assertThat(playbackCookies.getValue("a")).contains("PHPSESSID=session-a")
+ assertThat(playbackCookies.getValue("a")).doesNotContain("session-b")
+ assertThat(playbackCookies.getValue("b")).contains("PHPSESSID=session-b")
+ assertThat(playbackCookies.getValue("b")).doesNotContain("session-a")
+ }
+
+ @Test
+ fun authenticate_reports_access_denied_html_clearly() = runTest {
+ val service = OkHttpStalkerApiService(
+ okHttpClient = fakeClient(
+ "handshake" to """<!DOCTYPE html><html><body>Access Denied.</body></html>"""
+ ),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(
+ buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ )
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.message).isEqualTo("Portal denied the request for handshake.")
+ }
+
+ @Test
+ fun getLiveCategories_classifies_notValidToken_marker_as_authorization_without_transport_retries() = runTest {
+ var requestCount = 0
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ requestCount++
+ Response.Builder()
+ .request(chain.request())
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body("""{"js":{"not_valid_token":1}}""".toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.getLiveCategories(stalkerSession(), stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(StalkerApiError.Authorization::class.java)
+ assertThat(error.message).isEqualTo("Portal token is invalid.")
+ assertThat(requestCount).isEqualTo(1)
}
@Test
- fun authenticate_reports_access_denied_html_clearly() = runTest {
+ fun getLiveCategories_classifies_http200_denial_html_as_authorization_without_transport_retries() = runTest {
+ var requestCount = 0
val service = OkHttpStalkerApiService(
- okHttpClient = fakeClient(
- "handshake" to """<!DOCTYPE html><html><body>Access Denied.</body></html>"""
- ),
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ requestCount++
+ Response.Builder()
+ .request(chain.request())
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(
+ "<!DOCTYPE html><html><body>Access Denied.</body></html>"
+ .toResponseBody("text/html".toMediaType())
+ )
+ .build()
+ }
+ .build(),
json = Json { ignoreUnknownKeys = true }
)
- val result = service.authenticate(
- buildStalkerDeviceProfile(
- portalUrl = "https://portal.example.com/c",
- macAddress = "00:1A:79:12:34:56",
- deviceProfile = "MAG250",
- timezone = "UTC",
- locale = "en"
- )
+ val result = service.getLiveCategories(stalkerSession(), stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(StalkerApiError.Authorization::class.java)
+ assertThat(error.message).isEqualTo("Portal denied the request for get_genres.")
+ assertThat(requestCount).isEqualTo(1)
+ }
+
+ @Test
+ fun getVodStreams_reports_aggregate_page_limit_before_silently_returning_partial_catalog() = runTest {
+ var requestCount = 0
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ requestCount++
+ Response.Builder()
+ .request(chain.request())
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(
+ """{"js":{"total_items":201,"max_page_items":1,"data":[{"id":"1","name":"Movie","category_id":"42","cmd":"ffmpeg http://example.com/movie.mp4"}]}}"""
+ .toResponseBody("application/json".toMediaType())
+ )
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
)
+ val result = service.getVodStreams(stalkerSession(), stalkerProfile(), categoryId = "42")
+
assertThat(result).isInstanceOf(Result.Error::class.java)
val error = result as Result.Error
- assertThat(error.message).isEqualTo("Portal denied the request for handshake.")
+ assertThat(error.exception).isInstanceOf(StalkerApiError.CatalogTruncated::class.java)
+ val truncation = error.exception as StalkerApiError.CatalogTruncated
+ assertThat(truncation.advertisedTotalPages).isEqualTo(201)
+ assertThat(truncation.pageLimit).isEqualTo(200)
+ assertThat(requestCount).isEqualTo(1)
}
@Test
@@ -1181,6 +1855,8 @@ class OkHttpStalkerApiServiceTest {
val error = result as Result.Error
assertThat(error.message).contains("not found")
assertThat(requestedUrls).containsExactly(
+ "https://portal.example.com/server/load.php?type=itv&action=get_genres&JsHttpRequest=1-xml",
+ "https://portal.example.com/server/load.php?type=itv&action=get_genres&JsHttpRequest=1-xml",
"https://portal.example.com/server/load.php?type=itv&action=get_genres&JsHttpRequest=1-xml"
)
}
@@ -1236,6 +1912,8 @@ class OkHttpStalkerApiServiceTest {
assertThat(error.message).contains("stream endpoint failed")
assertThat(streamed).isEmpty()
assertThat(requestedUrls).containsExactly(
+ "https://portal.example.com/server/load.php?type=itv&action=get_all_channels&JsHttpRequest=1-xml",
+ "https://portal.example.com/server/load.php?type=itv&action=get_all_channels&JsHttpRequest=1-xml",
"https://portal.example.com/server/load.php?type=itv&action=get_all_channels&JsHttpRequest=1-xml"
)
}
@@ -1571,6 +2249,42 @@ class OkHttpStalkerApiServiceTest {
assertThat(success.data.map { it.title }).containsExactly("Morning News", "Live Sports")
}
+ @Test
+ fun getBulkEpg_interpretsOffsetlessProgramTimesInPortalTimezone() = runTest {
+ val service = OkHttpStalkerApiService(
+ okHttpClient = fakeClient(
+ "get_epg_info" to """
+ {"js":[
+ {"id":"p1","ch_id":"100","name":"Evening News","time":"2026-07-13 20:00:00","time_to":"2026-07-13 21:00:00"}
+ ]}
+ """.trimIndent()
+ ),
+ json = Json { ignoreUnknownKeys = true }
+ )
+ val zone = ZoneId.of("Europe/Amsterdam")
+
+ val result = service.getBulkEpg(
+ session = stalkerSession(),
+ profile = buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = zone.id,
+ locale = "en"
+ ),
+ periodHours = 6
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val program = (result as Result.Success).data.single()
+ assertThat(program.startTimeMillis).isEqualTo(
+ LocalDateTime.of(2026, 7, 13, 20, 0).atZone(zone).toInstant().toEpochMilli()
+ )
+ assertThat(program.endTimeMillis).isEqualTo(
+ LocalDateTime.of(2026, 7, 13, 21, 0).atZone(zone).toInstant().toEpochMilli()
+ )
+ }
+
@Test
fun getSeriesDetails_expands_season_shell_rows_into_episode_placeholders() = runTest {
val service = OkHttpStalkerApiService(
@@ -1742,6 +2456,221 @@ class OkHttpStalkerApiServiceTest {
assertThat(success.data.seasons[1].episodes.map { it.episodeNumber }).containsExactly(1, 2, 3).inOrder()
}
+ @Test
+ fun authenticate_classifies_device_conflict_envelope_as_terminal_device_conflict() = runTest {
+ val requestedActions = mutableListOf<String>()
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ requestedActions += action
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token-123","random":"abc"}}"""
+ "get_profile" -> """{"js":{"status":1,"msg":"Device conflict - device_id mismatch","block_msg":"Please contact your provider<br>to register this device."}}"""
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(StalkerApiError.DeviceConflict::class.java)
+ assertThat(error.message).contains("Device conflict")
+ assertThat(error.message).contains("Please contact your provider to register this device.")
+ // Terminal: no bootstrap/catalog call may follow a conflicted profile.
+ assertThat(requestedActions).containsExactly("handshake", "get_profile").inOrder()
+ }
+
+ @Test
+ fun authenticate_classifies_status2_envelope_as_device_not_registered() = runTest {
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token-123"}}"""
+ "get_profile" -> """{"js":{"status":2,"msg":"Authentication request","launcher_profile_url":"http://portal.example.com/stalker_portal/server/api/launcher_profile.php"}}"""
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(StalkerApiError.DeviceNotRegistered::class.java)
+ assertThat(error.message).contains("Authentication request")
+ }
+
+ @Test
+ fun authenticate_classifies_time_out_of_sync_envelope_as_clock_skew() = runTest {
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ val action = request.url.queryParameter("action").orEmpty()
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token-123"}}"""
+ "get_profile" -> """{"js":{"status":1,"msg":"Time out of sync","block_msg":"Time on the device is not synchronized."}}"""
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(StalkerApiError.ClockSkew::class.java)
+ assertThat(error.message).contains("clock")
+ assertThat(error.message).contains("Time out of sync")
+ }
+
+ @Test
+ fun authenticate_accepts_profile_payload_with_numeric_status_and_no_message() = runTest {
+ // Some Ministra builds embed "status":"1" in a fully valid profile payload.
+ val service = OkHttpStalkerApiService(
+ okHttpClient = fakeClient(
+ "handshake" to """{"js":{"token":"token-123"}}""",
+ "get_profile" to """{"js":{"name":"Living Room","status":"1","max_online":"2"}}"""
+ ),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ }
+
+ @Test
+ fun authenticate_classifies_html_403_as_blocked_not_authorization() = runTest {
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(403)
+ .message("Forbidden")
+ .body(
+ (
+ "<!DOCTYPE html><html><head><title>Attention Required</title></head>" +
+ "<body>Blocked by edge WAF</body></html>"
+ ).toResponseBody("text/html".toMediaType())
+ )
+ .build()
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(stalkerProfile())
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(StalkerApiError.BlockedOrConfiguration::class.java)
+ assertThat(error.exception).isNotInstanceOf(StalkerApiError.Authorization::class.java)
+ }
+
+ @Test
+ fun authenticate_prefers_redirect_hinted_portal_base_for_first_handshake() = runTest {
+ val requestedUrls = mutableListOf<String>()
+ val service = OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder()
+ .addInterceptor { chain ->
+ val request = chain.request()
+ requestedUrls += request.url.toString()
+ val action = request.url.queryParameter("action").orEmpty()
+ val path = request.url.encodedPath
+ when {
+ action.isNotEmpty() -> {
+ val body = when (action) {
+ "handshake" -> """{"js":{"token":"token-123"}}"""
+ // Stop discovery right after the profile; only URL order matters here.
+ "get_profile" -> """{"js":{"status":1,"msg":"Device conflict - device_id mismatch"}}"""
+ else -> error("Unexpected action '$action'")
+ }
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(body.toResponseBody("application/json".toMediaType()))
+ .build()
+ }
+ // Test fakes short-circuit the chain before the redirect interceptor,
+ // so simulate the already-followed redirect like authenticate_uses_
+ // effective_loadScript_after_http_redirect does: the response carries
+ // the final effective request URL.
+ path == "/" -> Response.Builder()
+ .request(
+ request.newBuilder()
+ .url("https://portal.example.com/stalker_portal/c/")
+ .build()
+ )
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body("<html>portal</html>".toResponseBody("text/html".toMediaType()))
+ .build()
+ else -> error("Unexpected request ${request.url}")
+ }
+ }
+ .build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+
+ val result = service.authenticate(
+ buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+ )
+
+ // The device-conflict stop is intentional; what matters is request routing.
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat(requestedUrls.first()).isEqualTo("https://portal.example.com/")
+ val firstHandshake = requestedUrls.first { it.contains("action=handshake") }
+ assertThat(firstHandshake)
+ .startsWith("https://portal.example.com/stalker_portal/server/load.php?")
+ }
+
private fun fakeClient(vararg responses: Pair<String, String>): OkHttpClient {
val byAction = responses.toMap()
return OkHttpClient.Builder()
@@ -1759,4 +2688,52 @@ class OkHttpStalkerApiServiceTest {
}
.build()
}
+
+ private fun stalkerSession() = StalkerSession(
+ loadUrl = "https://portal.example.com/server/load.php",
+ portalReferer = "https://portal.example.com/c/",
+ token = "token-123"
+ )
+
+ private fun stalkerProfile() = buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+
+ private class PendingCall : Call {
+ private val request = Request.Builder().url("https://portal.example.com/server/load.php").build()
+ @Volatile private var callback: Callback? = null
+ @Volatile var enqueued = false
+ @Volatile var cancelled = false
+
+ override fun request(): Request = request
+ override fun execute(): Response = error("Synchronous execution must not be used")
+ override fun enqueue(responseCallback: Callback) {
+ enqueued = true
+ callback = responseCallback
+ }
+ override fun cancel() {
+ cancelled = true
+ }
+ override fun isExecuted(): Boolean = enqueued
+ override fun isCanceled(): Boolean = cancelled
+ override fun timeout(): Timeout = Timeout.NONE
+ override fun clone(): Call = PendingCall()
+
+ fun respond() {
+ callback?.onResponse(
+ this,
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body("{}".toResponseBody("application/json".toMediaType()))
+ .build()
+ ) ?: error("Call was not enqueued")
+ }
+ }
}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerCatalogAcceptanceTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerCatalogAcceptanceTest.kt
new file mode 100644
index 00000000..1d705f64
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerCatalogAcceptanceTest.kt
@@ -0,0 +1,74 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Result
+import kotlinx.coroutines.test.runTest
+import kotlinx.serialization.json.Json
+import okhttp3.MediaType.Companion.toMediaType
+import okhttp3.OkHttpClient
+import okhttp3.Protocol
+import okhttp3.Response
+import okhttp3.ResponseBody.Companion.toResponseBody
+import org.junit.Test
+
+class StalkerCatalogAcceptanceTest {
+ @Test
+ fun addConnection_rejectsEmptyLiveCatalog() = runTest {
+ val service = service { action ->
+ when (action) {
+ "handshake" -> """{"js":{"token":"token"}}"""
+ "get_profile" -> """{"js":{"id":"1","name":"Portal","status":"1","auth_access":true}}"""
+ "get_genres" -> """{"js":[]}"""
+ else -> """{"js":[]}"""
+ }
+ }
+
+ val result = service.authenticate(profile(requireCatalog = true))
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat((result as Result.Error).message).contains("no live channel categories")
+ }
+
+ @Test
+ fun addConnection_rejectsProfileWhenEveryCatalogWrapperIsMalformed() = runTest {
+ val service = service { action ->
+ when (action) {
+ "handshake" -> """{"js":{"token":"token"}}"""
+ "get_profile" -> """{"js":{"id":"1","name":"Portal","status":"1","auth_access":true}}"""
+ else -> """{"js":{"unexpected":true}}"""
+ }
+ }
+
+ val result = service.authenticate(profile(requireCatalog = true))
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ assertThat((result as Result.Error).exception)
+ .isInstanceOf(StalkerApiError.ReadinessInconclusive::class.java)
+ assertThat((result.exception as StalkerApiError.ReadinessInconclusive).evidenceCode)
+ .isEqualTo("LIVE_MALFORMED_RESPONSE")
+ }
+
+ private fun profile(requireCatalog: Boolean) = buildStalkerDeviceProfile(
+ portalUrl = "https://portal.example.com/c",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ requireCatalogValidation = requireCatalog
+ )
+
+ private fun service(bodyFor: (String) -> String): OkHttpStalkerApiService =
+ OkHttpStalkerApiService(
+ okHttpClient = OkHttpClient.Builder().addInterceptor { chain ->
+ val request = chain.request()
+ Response.Builder()
+ .request(request)
+ .protocol(Protocol.HTTP_1_1)
+ .code(200)
+ .message("OK")
+ .body(bodyFor(request.url.queryParameter("action").orEmpty()).toResponseBody("application/json".toMediaType()))
+ .build()
+ }.build(),
+ json = Json { ignoreUnknownKeys = true }
+ )
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerCompatibilityRegistryTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerCompatibilityRegistryTest.kt
new file mode 100644
index 00000000..047d1319
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerCompatibilityRegistryTest.kt
@@ -0,0 +1,109 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerMagPreset
+import com.streamvault.domain.model.StalkerProfileVerification
+import com.streamvault.domain.model.StalkerProtocolFamily
+import org.junit.Test
+
+class StalkerCompatibilityRegistryTest {
+ @Test
+ fun stableIds_areUniqueAndResolvable() {
+ val profiles = StalkerCompatibilityRegistry.profiles
+ assertThat(profiles.map { it.id }.distinct()).hasSize(profiles.size)
+ profiles.forEach { profile ->
+ assertThat(StalkerCompatibilityRegistry.find(profile.id)).isEqualTo(profile)
+ assertThat(profile.revision).isGreaterThan(0)
+ assertThat(profile.model).isNotEmpty()
+ assertThat(profile.generation).isNotEmpty()
+ }
+ }
+
+ @Test
+ fun verifiedClassicProfiles_haveCompleteCapturedFingerprint() {
+ val verified = StalkerCompatibilityRegistry.profiles.filter {
+ it.protocolFamily == StalkerProtocolFamily.CLASSIC_MAG &&
+ it.verification == StalkerProfileVerification.VERIFIED
+ }
+ assertThat(verified.map { it.id }).containsExactly(
+ StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC,
+ StalkerCompatibilityProfileIds.CLASSIC_MAG250_LEGACY,
+ StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT,
+ StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN
+ )
+ verified.forEach { profile ->
+ assertThat(profile.preset).isNotNull()
+ assertThat(profile.bootstrapRecipe).isNotNull()
+ val fingerprint = stalkerMagPresetSpec(profile.preset!!)
+ assertThat(fingerprint.versionString).contains("ImageDescription")
+ assertThat(fingerprint.imageVersion).isNotEmpty()
+ assertThat(fingerprint.hwVersion).isNotEmpty()
+ assertThat(fingerprint.apiSignature).isNotEmpty()
+ }
+ }
+
+ @Test
+ fun experimentalProfiles_areManualOnlyAndResolveWholeBaseFingerprint() {
+ StalkerCompatibilityRegistry.profiles
+ .filter { it.verification == StalkerProfileVerification.EXPERIMENTAL }
+ .forEach { profile ->
+ assertThat(profile.automaticRepresentative).isFalse()
+ if (profile.protocolFamily == StalkerProtocolFamily.CLASSIC_MAG) {
+ val base = StalkerCompatibilityRegistry.baseFingerprint(profile)
+ assertThat(base.verification).isEqualTo(StalkerProfileVerification.VERIFIED)
+ assertThat(base.preset).isNotNull()
+ }
+ }
+ }
+
+ @Test
+ fun autoDiscovery_isBoundedAndKeepsPreferredFirst() {
+ val preferred = StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT
+ val order = StalkerCompatibilityRegistry.classicAutomaticOrder(preferred)
+ assertThat(order.first().id).isEqualTo(preferred)
+ assertThat(order.size).isAtMost(StalkerCompatibilityRegistry.MAX_AUTOMATIC_ATTEMPTS)
+ assertThat(order.all { it.verification == StalkerProfileVerification.VERIFIED }).isTrue()
+ }
+
+ @Test
+ fun oldPresets_mapWithoutChangingFingerprint() {
+ assertThat(StalkerCompatibilityRegistry.idForLegacyPreset(StalkerMagPreset.GENERIC_SAFE))
+ .isEqualTo(StalkerCompatibilityProfileIds.CLASSIC_MAG250_GENERIC)
+ assertThat(StalkerCompatibilityRegistry.idForLegacyPreset(StalkerMagPreset.MAG250_LEGACY))
+ .isEqualTo(StalkerCompatibilityProfileIds.CLASSIC_MAG250_LEGACY)
+ assertThat(StalkerCompatibilityRegistry.idForLegacyPreset(StalkerMagPreset.MAG254_STRICT))
+ .isEqualTo(StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT)
+ assertThat(StalkerCompatibilityRegistry.idForLegacyPreset(StalkerMagPreset.MINISTRA_MODERN))
+ .isEqualTo(StalkerCompatibilityProfileIds.CLASSIC_MAG322_MODERN)
+ }
+
+ @Test
+ fun portalModelSignal_resolvesOnlyVerifiedAutomaticFingerprints() {
+ assertThat(StalkerCompatibilityRegistry.findVerifiedByModelSignal("mag254")?.id)
+ .isEqualTo(StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT)
+ assertThat(StalkerCompatibilityRegistry.findVerifiedByModelSignal("MAG255")?.id)
+ .isEqualTo(StalkerCompatibilityProfileIds.CLASSIC_MAG254_STRICT)
+ assertThat(StalkerCompatibilityRegistry.findVerifiedByModelSignal("MAG270")).isNull()
+ assertThat(StalkerCompatibilityRegistry.findVerifiedByModelSignal("unknown")).isNull()
+ }
+
+ @Test
+ fun mag254Fingerprint_usesFirmwareImageVersionRatherThanModelNumber() {
+ val fingerprint = stalkerMagPresetSpec(StalkerMagPreset.MAG254_STRICT)
+ assertThat(fingerprint.versionString).contains("0.2.18")
+ assertThat(fingerprint.imageVersion).isEqualTo("218")
+ }
+
+ @Test
+ fun urlDiscovery_normalizesCopiedPortalPageUrls() {
+ assertThat(
+ StalkerUrlFactory.loadUrlCandidates(
+ "https://portal.example.com/stalker_portal/c/index.html?ref=setup"
+ )
+ ).containsAtLeast(
+ "https://portal.example.com/stalker_portal/server/load.php",
+ "https://portal.example.com/stalker_portal/portal.php"
+ )
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerDiscoveryBudgetTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerDiscoveryBudgetTest.kt
new file mode 100644
index 00000000..396e729c
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerDiscoveryBudgetTest.kt
@@ -0,0 +1,48 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.DiscoveryBudget
+import org.junit.Test
+
+class StalkerDiscoveryBudgetTest {
+
+ @Test
+ fun `request budget stops deterministically at configured limit`() {
+ val runtime = StalkerDiscoveryRuntime(
+ DiscoveryBudget(maxElapsedMillis = 60_000L, maxRequests = 2)
+ )
+ runtime.begin()
+
+ runtime.consumeRequest()
+ runtime.consumeRequest()
+ val failure = runCatching(runtime::consumeRequest).exceptionOrNull()
+
+ assertThat(runtime.requestCount).isEqualTo(3)
+ assertThat(failure).isInstanceOf(StalkerApiError.DiscoveryBudgetExceeded::class.java)
+ runtime.end()
+ }
+
+ @Test
+ fun `live category sampling prioritizes reported non-empty groups and keeps spread`() {
+ val categories = (0 until 20).map { index ->
+ StalkerCategoryRecord(
+ id = index.toString(),
+ name = "Category $index",
+ advertisedItemCount = when (index) {
+ 3 -> 500
+ 17 -> 200
+ else -> null
+ }
+ )
+ }
+
+ val sampled = sampleLiveDiscoveryCategories(categories, limit = 8)
+
+ assertThat(sampled).hasSize(8)
+ assertThat(sampled.take(2).map(StalkerCategoryRecord::id))
+ .containsExactly("3", "17")
+ .inOrder()
+ assertThat(sampled.map(StalkerCategoryRecord::id)).contains("0")
+ assertThat(sampled.map(StalkerCategoryRecord::id)).contains("19")
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalReplayHarnessTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalReplayHarnessTest.kt
index 51ee4a27..cf7b3eb4 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalReplayHarnessTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalReplayHarnessTest.kt
@@ -12,6 +12,7 @@ import com.streamvault.domain.model.StalkerPlaybackBackendHint
import com.streamvault.domain.model.StalkerPortalFingerprint
import com.streamvault.domain.model.StalkerPortalProfile
import java.io.InputStreamReader
+import java.util.concurrent.atomic.AtomicInteger
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
@@ -44,7 +45,8 @@ class StalkerPortalReplayHarnessTest {
"stalker/fixtures/archive_create_link.json",
"stalker/fixtures/archive_direct_cookie.json",
"stalker/fixtures/archive_strict_mag.json",
- "stalker/fixtures/archive_recipe_fallback.json"
+ "stalker/fixtures/archive_recipe_fallback.json",
+ "stalker/fixtures/on_demand_acceptance.json"
).forEach { path ->
val fixture = loadFixture(path)
val requestedActions = mutableListOf<String>()
@@ -185,23 +187,120 @@ class StalkerPortalReplayHarnessTest {
}
}
+ @Test
+ fun onDemandAcceptanceFixture_bounds_setup_preview_paging_and_epg() = runTest {
+ val path = "stalker/fixtures/on_demand_acceptance.json"
+ val fixture = loadFixture(path)
+ val requestedActions = mutableListOf<String>()
+ val observed = mutableListOf<ReplayObservedRequest>()
+ val active = AtomicInteger(0)
+ val maximumActive = AtomicInteger(0)
+ val service = OkHttpStalkerApiService(
+ okHttpClient = fakeReplayClient(fixture, requestedActions, observed, active, maximumActive),
+ json = json
+ )
+ val profile = buildStalkerDeviceProfile(
+ portalUrl = fixture.device.portalUrl,
+ macAddress = fixture.device.macAddress,
+ authMode = StalkerAuthMode.valueOf(fixture.device.authMode),
+ deviceProfile = fixture.device.deviceProfile,
+ timezone = fixture.device.timezone,
+ locale = fixture.device.locale
+ ).copy(providerId = 77L)
+
+ val milestones = mutableListOf("AUTHENTICATING")
+ val startedAt = System.currentTimeMillis()
+ val auth = service.authenticate(profile) as Result.Success
+ val authenticatedAt = System.currentTimeMillis()
+ val session = auth.data.first
+
+ assertThat(service.getLiveCategories(session, profile)).isInstanceOf(Result.Success::class.java)
+ assertThat(service.streamLiveStreams(session, profile) {}).isInstanceOf(Result.Success::class.java)
+ milestones += "LIVE_READY"
+ assertThat(service.getVodCategories(session, profile)).isInstanceOf(Result.Success::class.java)
+ assertThat(service.getSeriesCategories(session, profile)).isInstanceOf(Result.Success::class.java)
+ milestones += "CATEGORIES_READY"
+ val setupRequestCount = observed.size
+ val readyAt = System.currentTimeMillis()
+ milestones += "READY"
+
+ fixture.operations.forEach { operation ->
+ when (operation.type) {
+ "MOVIE_PREVIEW" -> repeat(operation.pages.coerceIn(1, 2)) { offset ->
+ assertThat(service.getVodStreamsPage(session, profile, operation.categoryId, offset + 1))
+ .isInstanceOf(Result.Success::class.java)
+ }
+ "SERIES_PREVIEW" -> repeat(operation.pages.coerceIn(1, 2)) { offset ->
+ assertThat(service.getSeriesPage(session, profile, operation.categoryId, offset + 1))
+ .isInstanceOf(Result.Success::class.java)
+ }
+ "EPG" -> assertThat(service.streamBulkEpg(session, profile, periodHours = 6) {})
+ .isInstanceOf(Result.Success::class.java)
+ "BACKGROUND_INDEX" -> assertThat(
+ service.getVodStreamsPage(session, profile, operation.categoryId, operation.page)
+ ).isInstanceOf(Result.Success::class.java)
+ }
+ }
+
+ val setupRequests = observed.take(setupRequestCount)
+ fixture.expected.acceptanceRequestOrder?.let { expectedOrder ->
+ assertThat(observed.map(ReplayObservedRequest::action))
+ .containsExactlyElementsIn(expectedOrder)
+ .inOrder()
+ }
+ fixture.expected.requestCount?.let { expectedCount ->
+ assertThat(observed).hasSize(expectedCount)
+ }
+ fixture.expected.orderedPages?.let { expectedPages ->
+ assertThat(observed.filter { it.action == "get_ordered_list" }.mapNotNull(ReplayObservedRequest::page))
+ .containsExactlyElementsIn(expectedPages)
+ .inOrder()
+ }
+ fixture.expected.readinessMilestones?.let { expectedMilestones ->
+ assertThat(milestones).containsExactlyElementsIn(expectedMilestones).inOrder()
+ }
+ assertThat(authenticatedAt - startedAt).isLessThan(fixture.expected.maxAuthenticationMillis ?: 3_000L)
+ assertThat(readyAt - startedAt).isLessThan(fixture.expected.maxReadinessMillis ?: 10_000L)
+ assertThat(setupRequests.count { it.action == "get_ordered_list" }).isEqualTo(0)
+ assertThat(maximumActive.get()).isAtMost(fixture.expected.maxConcurrency ?: 2)
+ assertThat(observed.sumOf { it.responseBytes })
+ .isAtLeast(fixture.expected.minResponseBytes ?: 1L)
+ assertThat(observed.count { it.action == "get_ordered_list" && it.type == "vod" })
+ .isAtMost((fixture.expected.maxMoviePagesAfterSetup ?: 3))
+ assertThat(observed.count { it.action == "get_ordered_list" && it.type == "series" })
+ .isAtMost((fixture.expected.maxSeriesPagesAfterSetup ?: 2))
+ val epgIndex = observed.indexOfFirst { it.action == "get_epg_info" }
+ val backgroundIndex = observed.indexOfLast { it.action == "get_ordered_list" && it.page == 3 }
+ assertThat(epgIndex).isAtLeast(0)
+ assertThat(backgroundIndex).isGreaterThan(epgIndex)
+ }
+
private fun <T> assertWithFixture(path: String, actual: T) =
assertWithMessage(path).that(actual)
private fun fakeReplayClient(
fixture: ReplayFixture,
- requestedActions: MutableList<String>
+ requestedActions: MutableList<String>,
+ observed: MutableList<ReplayObservedRequest>? = null,
+ active: AtomicInteger? = null,
+ maximumActive: AtomicInteger? = null
): OkHttpClient {
val responsesByAction = fixture.responses.groupBy { "${it.method.uppercase()}:${it.action}" }
.mapValues { (_, items) -> items.toMutableList() }
+ val reusableBootstrapResponses = fixture.responses
+ .filter { it.action in setOf("handshake", "do_auth") }
+ .associateBy { "${it.method.uppercase()}:${it.action}" }
return OkHttpClient.Builder()
.addInterceptor { chain ->
val request = chain.request()
+ val activeNow = active?.incrementAndGet() ?: 1
+ maximumActive?.updateAndGet { previous -> maxOf(previous, activeNow) }
val action = request.url.queryParameter("action").orEmpty()
val method = request.method.uppercase()
requestedActions += action
val key = "$method:$action"
val scripted = responsesByAction[key]?.removeFirstOrNull()
+ ?: reusableBootstrapResponses[key]
?: error(
"Missing replay response for $key in fixture ${fixture.name}; " +
"path=${request.url.encodedPath}; " +
@@ -216,7 +315,15 @@ class StalkerPortalReplayHarnessTest {
scripted.headers.orEmpty().forEach { (name, value) ->
builder.addHeader(name, value)
}
- builder.build()
+ observed?.add(
+ ReplayObservedRequest(
+ type = request.url.queryParameter("type").orEmpty(),
+ action = action,
+ page = request.url.queryParameter("p")?.toIntOrNull(),
+ responseBytes = scripted.body.toByteArray().size.toLong()
+ )
+ )
+ builder.build().also { active?.decrementAndGet() }
}
.build()
}
@@ -234,7 +341,23 @@ private data class ReplayFixture(
val name: String,
val device: ReplayDevice,
val responses: List<ReplayResponse>,
- val expected: ReplayExpectation
+ val expected: ReplayExpectation,
+ val operations: List<ReplayOperation> = emptyList()
+)
+
+@Serializable
+private data class ReplayOperation(
+ val type: String,
+ val categoryId: String? = null,
+ val page: Int = 1,
+ val pages: Int = 1
+)
+
+private data class ReplayObservedRequest(
+ val type: String,
+ val action: String,
+ val page: Int?,
+ val responseBytes: Long
)
@Serializable
@@ -284,5 +407,15 @@ private data class ReplayExpectation(
val playbackMode: String? = null,
val resolvedPlaybackUrl: String? = null,
val catchUpStartSeconds: Long? = null,
- val catchUpEndSeconds: Long? = null
+ val catchUpEndSeconds: Long? = null,
+ val maxAuthenticationMillis: Long? = null,
+ val maxReadinessMillis: Long? = null,
+ val maxConcurrency: Int? = null,
+ val maxMoviePagesAfterSetup: Int? = null,
+ val maxSeriesPagesAfterSetup: Int? = null,
+ val acceptanceRequestOrder: List<String>? = null,
+ val requestCount: Int? = null,
+ val orderedPages: List<Int>? = null,
+ val readinessMilestones: List<String>? = null,
+ val minResponseBytes: Long? = null
)
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt
new file mode 100644
index 00000000..a22eed72
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerPortalStateStoreTest.kt
@@ -0,0 +1,102 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.dao.StalkerPortalStateDao
+import com.streamvault.data.local.entity.StalkerPortalStateEntity
+import com.streamvault.domain.model.ContentType
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+
+class StalkerPortalStateStoreTest {
+ @Test
+ fun `capabilities are validated for seven days and selectively invalidated`() = runTest {
+ val dao = FakePortalStateDao()
+ val store = StalkerPortalStateStore(dao)
+ val now = 1_000L
+
+ store.recordBulkLive(1L, supported = false, now = now)
+ store.recordWildcard(1L, ContentType.MOVIE, supported = true, now = now)
+ store.recordEpg(1L, supported = true, now = now)
+ store.recordStressCooldown(1L, cooldownUntil = now + 60_000L, now = now)
+
+ assertThat(store.getValidated(1L, now + 6L * 24L * 60L * 60L * 1000L)).isNotNull()
+ assertThat(store.getValidated(1L, now + 8L * 24L * 60L * 60L * 1000L)).isNull()
+
+ store.invalidateCapabilities(1L)
+ val invalidated = requireNotNull(store.get(1L))
+ assertThat(invalidated.bulkLiveSupported).isNull()
+ assertThat(invalidated.movieWildcardSupported).isNull()
+ assertThat(invalidated.epgSupported).isNull()
+ assertThat(invalidated.safeMetadataConcurrency).isEqualTo(1)
+ assertThat(invalidated.stressCooldownUntil).isEqualTo(now + 60_000L)
+ }
+
+ @Test
+ fun `endpoint health is hashed bounded and expires independently`() = runTest {
+ val dao = FakePortalStateDao()
+ val store = StalkerPortalStateStore(dao)
+ val now = 10_000L
+ val endpoint = "https://portal.example/stalker_portal/server/load.php"
+
+ store.markEndpointUnhealthy(2L, endpoint, now)
+ val state = requireNotNull(store.get(2L))
+
+ assertThat(state.endpointHealthJson).doesNotContain("portal.example")
+ assertThat(store.isEndpointHealthy(state, endpoint, now + 1L)).isFalse()
+ assertThat(store.isEndpointHealthy(state, endpoint, now + 11L * 60L * 1000L)).isTrue()
+
+ repeat(12) { index ->
+ store.markEndpointUnhealthy(2L, "https://example.invalid/$index/portal.php", now + index)
+ }
+ val bounded = requireNotNull(store.get(2L)).endpointHealthJson
+ assertThat(Regex("[a-f0-9]{24}").findAll(bounded).count()).isAtMost(8)
+ }
+
+ @Test
+ fun `healthy probe restores concurrency only after persisted cooldown`() = runTest {
+ val dao = FakePortalStateDao()
+ val store = StalkerPortalStateStore(dao)
+ store.recordStressCooldown(3L, cooldownUntil = 2_000L, now = 1_000L)
+
+ store.recordHealthyMetadataProbe(3L, now = 1_999L)
+ assertThat(store.get(3L)?.safeMetadataConcurrency).isEqualTo(1)
+
+ store.recordHealthyMetadataProbe(3L, now = 2_001L)
+ assertThat(store.get(3L)?.safeMetadataConcurrency).isEqualTo(2)
+ assertThat(store.get(3L)?.stressCooldownUntil).isEqualTo(0L)
+ }
+
+ @Test
+ fun `failed authentication recipe cools down without invalidating endpoint`() = runTest {
+ val dao = FakePortalStateDao()
+ val store = StalkerPortalStateStore(dao)
+ val now = 5_000L
+ dao.upsert(
+ StalkerPortalStateEntity(
+ providerId = 4L,
+ workingEndpoint = "https://portal.invalid/portal.php",
+ bootstrapRecipe = "STRICT_MAG",
+ validatedAt = now
+ )
+ )
+
+ store.markRecipeUnhealthy(4L, "STRICT_MAG", now)
+ val state = requireNotNull(store.get(4L))
+
+ assertThat(store.isRecipeHealthy(state, "STRICT_MAG", now + 1L)).isFalse()
+ assertThat(store.isRecipeHealthy(state, "STRICT_MAG", now + 11L * 60L * 1000L)).isTrue()
+ assertThat(state.workingEndpoint).isEqualTo("https://portal.invalid/portal.php")
+ }
+
+ private class FakePortalStateDao : StalkerPortalStateDao {
+ private val rows = mutableMapOf<Long, StalkerPortalStateEntity>()
+
+ override suspend fun get(providerId: Long): StalkerPortalStateEntity? = rows[providerId]
+
+ override suspend fun upsert(entity: StalkerPortalStateEntity) {
+ rows[entity.providerId] = entity
+ }
+
+ override suspend fun invalidate(providerId: Long): Int = if (rows.remove(providerId) != null) 1 else 0
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt
index 1edd30d5..4d18dded 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerProviderTest.kt
@@ -1,8 +1,16 @@
package com.streamvault.data.remote.stalker
import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.DatabaseTransactionRunner
+import com.streamvault.data.local.dao.StalkerRemoteIdentityDao
+import com.streamvault.data.local.entity.StalkerRemoteIdentityEntity
+import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.ProviderStatus
+import com.streamvault.domain.model.PlaybackTransportMode
import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
import java.time.Instant
import kotlinx.coroutines.test.runTest
import org.junit.Before
@@ -10,9 +18,25 @@ import org.junit.Test
class StalkerProviderTest {
- @Before
+@Before
fun clearSharedAuthCache() {
StalkerProvider.clearSharedAuthCacheForTests()
+ StalkerProvider.clearResolvedStreamUrlCacheForTests()
+ }
+
+ @Test
+ fun truncated_page_is_never_reported_complete() {
+ val page = StalkerPagedResult(
+ items = listOf("cached"),
+ page = 200,
+ totalPages = 200,
+ advertisedTotalPages = 250,
+ isTruncated = true,
+ terminationReason = "page_limit",
+ pageSize = 14
+ )
+
+ assertThat(page.isComplete).isFalse()
}
@Test
@@ -88,6 +112,42 @@ class StalkerProviderTest {
assertThat(authProfile.signature).isEmpty()
}
+ @Test
+ fun authenticate_persistedProvider_disablesCompatibilityDiscovery() = runTest {
+ val api = FakeStalkerApiService(profile = StalkerProviderProfile(accountName = "Room"))
+ val provider = StalkerProvider(
+ providerId = 7,
+ api = api,
+ portalUrl = "https://portal.example.com/c/",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+
+ assertThat(provider.authenticate()).isInstanceOf(Result.Success::class.java)
+
+ assertThat(checkNotNull(api.lastAuthenticateProfile).allowCompatibilityDiscovery).isFalse()
+ }
+
+ @Test
+ fun authenticate_unsavedProvider_allowsExplicitCompatibilityDiscovery() = runTest {
+ val api = FakeStalkerApiService(profile = StalkerProviderProfile(accountName = "Room"))
+ val provider = StalkerProvider(
+ providerId = 0,
+ api = api,
+ portalUrl = "https://portal.example.com/c/",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en"
+ )
+
+ assertThat(provider.authenticate()).isInstanceOf(Result.Success::class.java)
+
+ assertThat(checkNotNull(api.lastAuthenticateProfile).allowCompatibilityDiscovery).isTrue()
+ }
+
@Test
fun authenticate_reusesSessionAcrossEquivalentProviderInstances() = runTest {
val api = FakeStalkerApiService(profile = StalkerProviderProfile(accountName = "Room"))
@@ -146,12 +206,15 @@ class StalkerProviderTest {
}
@Test
- fun getLiveCategories_reauthenticates_only_after_authorization_failed() = runTest {
+ fun getLiveCategories_reauthenticates_onceAfterTypedAuthorizationFailure() = runTest {
val api = FakeStalkerApiService(
profile = StalkerProviderProfile(accountName = "Room"),
liveCategoryResults = ArrayDeque(
listOf(
- Result.error("Authorization failed"),
+ Result.error(
+ "Portal token is invalid",
+ StalkerApiError.Authorization("Portal token is invalid", portalReason = "not_valid_token")
+ ),
Result.success(emptyList())
)
)
@@ -198,6 +261,144 @@ class StalkerProviderTest {
assertThat(api.authenticateCalls).isEqualTo(1)
}
+ @Test
+ fun getSeriesInfo_resolvesCollidingEpisodeRemoteIdsBeforeMapping() = runTest {
+ val identityDao = FakeIdentityDao()
+ val resolver = StalkerRemoteIdentityResolver(identityDao, DirectTransactionRunner)
+ val api = FakeStalkerApiService(
+ profile = StalkerProviderProfile(accountName = "Room"),
+ seriesDetails = StalkerSeriesDetails(
+ series = StalkerItemRecord(id = "series-alpha", name = "Series"),
+ seasons = listOf(
+ StalkerSeasonRecord(
+ seasonNumber = 1,
+ name = "Season 1",
+ episodes = listOf(
+ StalkerEpisodeRecord("ba", "Episode A", 1, 1),
+ StalkerEpisodeRecord("a\u0080", "Episode B", 2, 1)
+ )
+ )
+ )
+ )
+ )
+ val provider = StalkerProvider(
+ providerId = 7,
+ api = api,
+ portalUrl = "https://portal.example.com/c/",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ identityResolver = resolver
+ )
+
+ val result = provider.getSeriesInfo("series-alpha")
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val episodeIds = (result as Result.Success).data.seasons.single().episodes.map { episode -> episode.id }
+ assertThat(episodeIds.toSet()).hasSize(2)
+ assertThat(resolver.reverse(7L, ContentType.SERIES_EPISODE, episodeIds[0])).isEqualTo("ba")
+ assertThat(resolver.reverse(7L, ContentType.SERIES_EPISODE, episodeIds[1])).isEqualTo("a\u0080")
+ }
+
+ @Test
+ fun getVodStreamsPage_preservesRequestedCategoryWhenOnlyReverseIdentityIsCached() = runTest {
+ val resolver = StalkerRemoteIdentityResolver(FakeIdentityDao(), DirectTransactionRunner)
+ resolver.resolveAll(7L, ContentType.MOVIE, listOf("20"))
+ val provider = StalkerProvider(
+ providerId = 7,
+ api = FakeStalkerApiService(
+ profile = StalkerProviderProfile(accountName = "Room"),
+ vodPageItems = listOf(
+ StalkerItemRecord(
+ id = "movie-1",
+ name = "Movie",
+ categoryName = "Action",
+ cmd = "ffmpeg http://cdn.example.com/movie.ts"
+ )
+ )
+ ),
+ portalUrl = "https://portal.example.com/c/",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ identityResolver = resolver
+ )
+
+ val result = provider.getVodStreamsPage(categoryId = 20L, page = 1)
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val movie = (result as Result.Success).data.items.single()
+ assertThat(movie.categoryId).isEqualTo(20L)
+ assertThat(movie.categoryName).isEqualTo("Action")
+ }
+
+ @Test
+ fun getSeriesListPage_preservesRequestedCategoryWhenOnlyReverseIdentityIsCached() = runTest {
+ val resolver = StalkerRemoteIdentityResolver(FakeIdentityDao(), DirectTransactionRunner)
+ resolver.resolveAll(7L, ContentType.SERIES, listOf("30"))
+ val provider = StalkerProvider(
+ providerId = 7,
+ api = FakeStalkerApiService(
+ profile = StalkerProviderProfile(accountName = "Room"),
+ seriesPageItems = listOf(
+ StalkerItemRecord(
+ id = "series-1",
+ name = "Series",
+ categoryName = "Drama"
+ )
+ )
+ ),
+ portalUrl = "https://portal.example.com/c/",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ identityResolver = resolver
+ )
+
+ val result = provider.getSeriesListPage(categoryId = 30L, page = 1)
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val series = (result as Result.Success).data.items.single()
+ assertThat(series.categoryId).isEqualTo(30L)
+ assertThat(series.categoryName).isEqualTo("Drama")
+ }
+
+ @Test
+ fun streamLiveStreams_resolves_large_catalog_identities_in_batches() = runTest {
+ val transactionRunner = CountingTransactionRunner()
+ val resolver = StalkerRemoteIdentityResolver(FakeIdentityDao(), transactionRunner)
+ val liveStreams = (1..1_001).map { id ->
+ StalkerItemRecord(
+ id = id.toString(),
+ name = "Channel $id",
+ categoryId = "10",
+ cmd = "ffmpeg http://cdn.example.com/$id.ts"
+ )
+ }
+ val provider = StalkerProvider(
+ providerId = 7,
+ api = FakeStalkerApiService(
+ profile = StalkerProviderProfile(accountName = "Room"),
+ liveStreams = liveStreams
+ ),
+ portalUrl = "https://portal.example.com/c/",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG250",
+ timezone = "UTC",
+ locale = "en",
+ identityResolver = resolver
+ )
+ val emitted = mutableListOf<Long>()
+
+ val result = provider.streamLiveStreams { channel -> emitted += channel.streamId }
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ assertThat(emitted).hasSize(1_001)
+ assertThat(transactionRunner.transactionCount).isEqualTo(3)
+ }
@Test
fun getLiveStreams_maps_archive_capabilities_to_catch_up_fields() = runTest {
@@ -415,7 +616,8 @@ class StalkerProviderTest {
assertThat(success.data.headers["Connection"]).isEqualTo("keep-alive")
assertThat(success.data.headers["Host"]).isEqualTo("fdox.org:8080")
assertThat(success.data.userAgent).isEqualTo("Lavf53.32.100")
- assertThat(success.data.allowInvalidSsl).isTrue()
+ assertThat(success.data.allowInvalidSsl).isFalse()
+ assertThat(success.data.transportPolicy).isNull()
}
@Test
@@ -491,7 +693,8 @@ class StalkerProviderTest {
assertThat(result).isInstanceOf(Result.Success::class.java)
val success = result as Result.Success
assertThat(success.data.userAgent).isNull()
- assertThat(success.data.allowInvalidSsl).isTrue()
+ assertThat(success.data.allowInvalidSsl).isFalse()
+ assertThat(success.data.transportPolicy).isNull()
assertThat(success.data.proxyHost).isEqualTo("127.0.0.1")
assertThat(success.data.proxyPort).isEqualTo(8080)
assertThat(success.data.headers).doesNotContainKey("Referer")
@@ -673,7 +876,10 @@ class StalkerProviderTest {
private val liveStreams: List<StalkerItemRecord> = emptyList(),
private val createLinkUrl: String = "http://cdn.example.com/stream.ts",
private val currentCookieHeader: String = "",
- private val liveCategoryResults: ArrayDeque<Result<List<StalkerCategoryRecord>>> = ArrayDeque()
+ private val liveCategoryResults: ArrayDeque<Result<List<StalkerCategoryRecord>>> = ArrayDeque(),
+ private val seriesDetails: StalkerSeriesDetails? = null,
+ private val vodPageItems: List<StalkerItemRecord> = emptyList(),
+ private val seriesPageItems: List<StalkerItemRecord> = emptyList()
) : StalkerApiService {
var createLinkCalls: Int = 0
private set
@@ -709,7 +915,10 @@ class StalkerProviderTest {
session: StalkerSession,
profile: StalkerDeviceProfile,
onItem: suspend (StalkerItemRecord) -> Unit
- ) = Result.success(0)
+ ): Result<Int> {
+ liveStreams.forEach { item -> onItem(item) }
+ return Result.success(liveStreams.size)
+ }
override suspend fun getVodCategories(
session: StalkerSession,
@@ -727,7 +936,7 @@ class StalkerProviderTest {
profile: StalkerDeviceProfile,
categoryId: String?,
page: Int
- ) = Result.success(StalkerPagedItems(emptyList(), page, page, 0))
+ ) = Result.success(StalkerPagedItems(vodPageItems, page, page, vodPageItems.size))
override suspend fun getSeriesCategories(
session: StalkerSession,
@@ -745,14 +954,14 @@ class StalkerProviderTest {
profile: StalkerDeviceProfile,
categoryId: String?,
page: Int
- ) = Result.success(StalkerPagedItems(emptyList(), page, page, 0))
+ ) = Result.success(StalkerPagedItems(seriesPageItems, page, page, seriesPageItems.size))
override suspend fun getSeriesDetails(
session: StalkerSession,
profile: StalkerDeviceProfile,
seriesId: String
) = Result.success(
- StalkerSeriesDetails(
+ seriesDetails ?: StalkerSeriesDetails(
series = StalkerItemRecord(id = seriesId, name = "Series"),
seasons = emptyList()
)
@@ -807,4 +1016,120 @@ class StalkerProviderTest {
override fun currentCookieHeader(session: StalkerSession): String = currentCookieHeader
}
+
+ @Test
+ fun resolvePlaybackInfo_applies_accepted_http_only_to_the_granted_origin() = runTest {
+ val grant = StalkerTransportGrant(
+ mode = StalkerTransportMode.USER_ACCEPTED_HTTP,
+ origin = StalkerTransportOrigin("http", "portal.example.com", 8080),
+ consentedAt = 42L
+ )
+ val provider = StalkerProvider(
+ providerId = 7,
+ api = FakeStalkerApiService(
+ profile = StalkerProviderProfile(accountName = "Room"),
+ createLinkUrl = "http://portal.example.com:8080/live/stream.ts"
+ ),
+ portalUrl = "http://portal.example.com:8080/c/",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG322",
+ timezone = "Europe/Amsterdam",
+ locale = "en",
+ transportGrant = grant
+ )
+
+ val result = provider.resolvePlaybackInfo(
+ kind = StalkerStreamKind.LIVE,
+ descriptor = checkNotNull(
+ buildStalkerPlaybackDescriptor(
+ primaryCmd = "ffmpeg http://localhost/ch/1200_",
+ capabilities = StalkerPortalCapabilities(useHttpTemporaryLink = true)
+ )
+ )
+ ) as Result.Success
+
+ assertThat(result.data.allowInvalidSsl).isFalse()
+ assertThat(result.data.transportPolicy?.mode)
+ .isEqualTo(PlaybackTransportMode.USER_ACCEPTED_HTTP)
+ assertThat(result.data.transportPolicy?.origin).isEqualTo(grant.origin)
+ }
+
+@Test
+ fun resolvePlaybackInfo_plays_cleartext_cdn_stream_on_a_different_origin_than_the_portal_consent() = runTest {
+ val provider = StalkerProvider(
+ providerId = 7,
+ api = FakeStalkerApiService(
+ profile = StalkerProviderProfile(accountName = "Room"),
+ createLinkUrl = "http://cdn.example.com/live/stream.ts"
+ ),
+ portalUrl = "http://portal.example.com/c/",
+ macAddress = "00:1A:79:12:34:56",
+ deviceProfile = "MAG322",
+ timezone = "Europe/Amsterdam",
+ locale = "en",
+ transportGrant = StalkerTransportGrant(
+ mode = StalkerTransportMode.USER_ACCEPTED_HTTP,
+ origin = StalkerTransportOrigin("http", "portal.example.com", 80),
+ consentedAt = 42L
+ )
+ )
+
+ val result = provider.resolvePlaybackInfo(
+ kind = StalkerStreamKind.LIVE,
+ descriptor = checkNotNull(
+ buildStalkerPlaybackDescriptor(
+ primaryCmd = "ffmpeg http://localhost/ch/1200_",
+ capabilities = StalkerPortalCapabilities(useHttpTemporaryLink = true)
+ )
+ )
+ )
+
+ // Cleartext IPTV streams commonly come from a different origin than the (often HTTPS)
+ // portal, and the portal already authenticated the resolved URL via create_link, so a
+ // matching portal consent is no longer required for playback.
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ val success = result as Result.Success
+ assertThat(success.data.url).isEqualTo("http://cdn.example.com/live/stream.ts")
+ }
+
+ private object DirectTransactionRunner : DatabaseTransactionRunner {
+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
+ }
+
+ private class CountingTransactionRunner : DatabaseTransactionRunner {
+ var transactionCount = 0
+ private set
+
+ override suspend fun <T> inTransaction(block: suspend () -> T): T {
+ transactionCount += 1
+ return block()
+ }
+ }
+
+ private class FakeIdentityDao : StalkerRemoteIdentityDao {
+ private val rows = mutableListOf<StalkerRemoteIdentityEntity>()
+
+ override suspend fun getByRawId(providerId: Long, contentType: String, rawId: String) =
+ rows.firstOrNull { row ->
+ row.providerId == providerId && row.contentType.name == contentType && row.rawId == rawId
+ }
+
+ override suspend fun getBySurrogateId(providerId: Long, contentType: String, surrogateId: Long) =
+ rows.firstOrNull { row ->
+ row.providerId == providerId && row.contentType.name == contentType && row.surrogateId == surrogateId
+ }
+
+ override suspend fun maxAllocatedSurrogate(providerId: Long, contentType: String, floor: Long): Long? =
+ rows.filter { row ->
+ row.providerId == providerId && row.contentType.name == contentType && row.surrogateId >= floor
+ }.maxOfOrNull(StalkerRemoteIdentityEntity::surrogateId)
+
+ override suspend fun insert(entity: StalkerRemoteIdentityEntity) {
+ check(rows.none { row ->
+ row.providerId == entity.providerId && row.contentType == entity.contentType &&
+ (row.rawId == entity.rawId || row.surrogateId == entity.surrogateId)
+ })
+ rows += entity
+ }
+ }
}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt
new file mode 100644
index 00000000..8e0e25dc
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRemoteIdentityResolverTest.kt
@@ -0,0 +1,51 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.DatabaseTransactionRunner
+import com.streamvault.data.local.dao.StalkerRemoteIdentityDao
+import com.streamvault.data.local.entity.StalkerRemoteIdentityEntity
+import com.streamvault.domain.model.ContentType
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+
+class StalkerRemoteIdentityResolverTest {
+ @Test
+ fun collidingLegacyHashesRemainDistinctAndReversible() = runTest {
+ val dao = FakeIdentityDao()
+ val resolver = StalkerRemoteIdentityResolver(dao, DirectTransactionRunner)
+
+ // "ba" and "a\u0080" have the same Java String hash and remain unchanged by lowercase().
+ val resolved = resolver.resolveAll(7L, ContentType.MOVIE, listOf("ba", "a\u0080"))
+
+ assertThat(resolved.values.toSet()).hasSize(2)
+ resolved.forEach { (rawId, surrogateId) ->
+ assertThat(resolver.reverse(7L, ContentType.MOVIE, surrogateId)).isEqualTo(rawId)
+ }
+ }
+
+ private object DirectTransactionRunner : DatabaseTransactionRunner {
+ override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
+ }
+
+ private class FakeIdentityDao : StalkerRemoteIdentityDao {
+ private val rows = mutableListOf<StalkerRemoteIdentityEntity>()
+
+ override suspend fun getByRawId(providerId: Long, contentType: String, rawId: String) =
+ rows.firstOrNull { it.providerId == providerId && it.contentType.name == contentType && it.rawId == rawId }
+
+ override suspend fun getBySurrogateId(providerId: Long, contentType: String, surrogateId: Long) =
+ rows.firstOrNull { it.providerId == providerId && it.contentType.name == contentType && it.surrogateId == surrogateId }
+
+ override suspend fun maxAllocatedSurrogate(providerId: Long, contentType: String, floor: Long): Long? =
+ rows.filter { it.providerId == providerId && it.contentType.name == contentType && it.surrogateId >= floor }
+ .maxOfOrNull { it.surrogateId }
+
+ override suspend fun insert(entity: StalkerRemoteIdentityEntity) {
+ check(rows.none { row ->
+ row.providerId == entity.providerId && row.contentType == entity.contentType &&
+ (row.rawId == entity.rawId || row.surrogateId == entity.surrogateId)
+ })
+ rows += entity
+ }
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt
new file mode 100644
index 00000000..229148e4
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerRequestCoordinatorTest.kt
@@ -0,0 +1,79 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.StalkerRequestPriority
+import java.util.concurrent.atomic.AtomicInteger
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.async
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+
+class StalkerRequestCoordinatorTest {
+ @Test
+ fun duplicateRequestsShareOneExecution() = runTest {
+ val coordinator = StalkerRequestCoordinator()
+ val executions = AtomicInteger()
+ val release = CompletableDeferred<Unit>()
+
+ val first = async {
+ coordinator.execute(
+ 7L,
+ StalkerRequestPriority.OPEN_CATEGORY,
+ StalkerRequestDescriptor("MOVIE", "CATEGORY_PAGE", categoryKey = "42", page = 1)
+ ) {
+ executions.incrementAndGet()
+ release.await()
+ "done"
+ }
+ }
+ val second = async {
+ coordinator.execute(
+ 7L,
+ StalkerRequestPriority.OPEN_CATEGORY,
+ StalkerRequestDescriptor("MOVIE", "CATEGORY_PAGE", categoryKey = "42", page = 1)
+ ) {
+ executions.incrementAndGet()
+ "duplicate"
+ }
+ }
+ runCurrent()
+ assertThat(executions.get()).isEqualTo(1)
+
+ release.complete(Unit)
+ advanceUntilIdle()
+ assertThat(first.await()).isEqualTo("done")
+ assertThat(second.await()).isEqualTo("done")
+ }
+
+ @Test
+ fun metadataConcurrencyIsCappedAtTwo() = runTest {
+ val coordinator = StalkerRequestCoordinator()
+ val active = AtomicInteger()
+ val peak = AtomicInteger()
+ val release = CompletableDeferred<Unit>()
+
+ val jobs = (1..4).map { page ->
+ async {
+ coordinator.execute(
+ 9L,
+ StalkerRequestPriority.OPEN_CATEGORY,
+ StalkerRequestDescriptor("MOVIE", "CATEGORY_PAGE", categoryKey = "1", page = page)
+ ) {
+ val current = active.incrementAndGet()
+ peak.updateAndGet { previous -> maxOf(previous, current) }
+ release.await()
+ active.decrementAndGet()
+ }
+ }
+ }
+ runCurrent()
+ assertThat(peak.get()).isEqualTo(2)
+
+ release.complete(Unit)
+ advanceUntilIdle()
+ jobs.forEach { it.await() }
+ assertThat(peak.get()).isEqualTo(2)
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTelemetryTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTelemetryTest.kt
new file mode 100644
index 00000000..eab47b6e
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTelemetryTest.kt
@@ -0,0 +1,47 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.StalkerRequestPriority
+import org.junit.Test
+
+class StalkerTelemetryTest {
+ @Test
+ fun `request event never renders raw category item work or termination values`() {
+ val rawUrl = "https://user:[email protected]/portal.php?token=abc"
+ val rawMac = "00:1A:79:AA:BB:CC"
+ val rawWork = "token-cookie-signature"
+ val event = StalkerTelemetry.buildRequestEvent(
+ providerId = 4L,
+ priority = StalkerRequestPriority.OPEN_CATEGORY,
+ descriptor = StalkerRequestDescriptor(
+ contentType = "MOVIE",
+ action = "CATEGORY_PAGE",
+ categoryKey = rawUrl,
+ itemKey = rawMac,
+ page = 2,
+ workId = rawWork
+ ),
+ responseMetrics = StalkerResponseMetrics(
+ items = 18,
+ pages = 2,
+ advertisedTotal = 900,
+ truncated = true,
+ terminationReason = rawUrl
+ ),
+ durationMillis = 42L,
+ active = 1,
+ queued = 0,
+ concurrencyLimit = 2,
+ stressCooldownUntil = 0L,
+ outcome = "success",
+ now = 1L
+ )
+
+ assertThat(event).doesNotContain(rawUrl)
+ assertThat(event).doesNotContain(rawMac)
+ assertThat(event).doesNotContain(rawWork)
+ assertThat(event).doesNotContain("secret")
+ assertThat(event).contains("items=18")
+ assertThat(event).contains("truncated=true")
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
index 1dddc4d6..68fed4dd 100644
--- a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTrafficCoordinatorTest.kt
@@ -17,32 +17,30 @@ class StalkerTrafficCoordinatorTest {
}
@Test
- fun `deferCatalogFetchMillis stays deferred while playback is active`() {
+ fun `background delay increases while playback is active without blocking interactive work`() {
+ val normalDelay = StalkerTrafficCoordinator.backgroundInterPageDelayMillis(providerId = 7L)
StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
- val deferred = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId = 7L)
+ val playbackDelay = StalkerTrafficCoordinator.backgroundInterPageDelayMillis(providerId = 7L)
- assertThat(deferred).isGreaterThan(0L)
+ assertThat(StalkerTrafficCoordinator.isPlaybackActive(7L)).isTrue()
+ assertThat(playbackDelay).isGreaterThan(normalDelay)
}
@Test
- fun `deferCatalogFetchMillis clears immediately when playback stops`() {
+ fun `playback state clears immediately when playback stops`() {
StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
StalkerTrafficCoordinator.notePlaybackStopped(providerId = 7L)
- val deferred = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId = 7L)
-
- assertThat(deferred).isEqualTo(0L)
+ assertThat(StalkerTrafficCoordinator.isPlaybackActive(7L)).isFalse()
}
@Test
- fun `deferCatalogFetchMillis tracks nested playback sessions for same provider`() {
+ fun `playback state tracks nested sessions for same provider`() {
StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
StalkerTrafficCoordinator.notePlaybackStarted(providerId = 7L)
StalkerTrafficCoordinator.notePlaybackStopped(providerId = 7L)
- val deferred = StalkerTrafficCoordinator.deferCatalogFetchMillis(providerId = 7L)
-
- assertThat(deferred).isGreaterThan(0L)
+ assertThat(StalkerTrafficCoordinator.isPlaybackActive(7L)).isTrue()
}
}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTransportFactoryTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTransportFactoryTest.kt
new file mode 100644
index 00000000..304d251c
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerTransportFactoryTest.kt
@@ -0,0 +1,165 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.StalkerTransportChallengeReason
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
+import java.io.IOException
+import kotlinx.coroutines.test.runTest
+import okhttp3.OkHttpClient
+import okhttp3.Request
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
+import okhttp3.tls.HandshakeCertificates
+import okhttp3.tls.HeldCertificate
+import org.junit.Test
+
+class StalkerTransportFactoryTest {
+
+ @Test
+ fun `HTTP sends nothing until exact origin is accepted`() {
+ MockWebServer().use { server ->
+ server.enqueue(MockResponse().setBody("ok"))
+ val factory = StalkerTransportFactory(OkHttpClient())
+
+ val challenge = runCatching { factory.clientFor(server.url("/").toString(), null) }
+ .exceptionOrNull() as StalkerApiError.TransportConsentRequired
+
+ assertThat(challenge.challenge.reason)
+ .isEqualTo(StalkerTransportChallengeReason.CLEARTEXT_HTTP)
+ assertThat(server.requestCount).isEqualTo(0)
+
+ val origin = server.url("/").toTransportOrigin()
+ val client = factory.clientFor(
+ server.url("/").toString(),
+ StalkerTransportGrant(
+ mode = StalkerTransportMode.USER_ACCEPTED_HTTP,
+ origin = origin,
+ consentedAt = 1L
+ )
+ )
+ client.newCall(Request.Builder().url(server.url("/")).build()).execute().use {
+ assertThat(it.isSuccessful).isTrue()
+ }
+ assertThat(server.requestCount).isEqualTo(1)
+ }
+ }
+
+ @Test
+ fun `cross-origin redirect requires consent and strips sensitive headers after acceptance`() {
+ MockWebServer().use { target ->
+ MockWebServer().use { source ->
+ val sourceCertificate = HeldCertificate.Builder()
+ .commonName("localhost")
+ .addSubjectAlternativeName("localhost")
+ .build()
+ val sourceServerCertificates = HandshakeCertificates.Builder()
+ .heldCertificate(sourceCertificate)
+ .build()
+ source.useHttps(sourceServerCertificates.sslSocketFactory(), false)
+ val sourceClientCertificates = HandshakeCertificates.Builder()
+ .addTrustedCertificate(sourceCertificate.certificate)
+ .build()
+ val strictClient = OkHttpClient.Builder()
+ .sslSocketFactory(
+ sourceClientCertificates.sslSocketFactory(),
+ sourceClientCertificates.trustManager
+ )
+ .build()
+ target.enqueue(MockResponse().setBody("ok"))
+ source.enqueue(
+ MockResponse()
+ .setResponseCode(302)
+ .setHeader("Location", target.url("/portal.php"))
+ )
+ val sourceUrl = source.url("/c/").newBuilder().host("localhost").build()
+ val factory = StalkerTransportFactory(strictClient)
+ val request = Request.Builder()
+ .url(sourceUrl)
+ .header("Authorization", "Bearer secret")
+ .header("Cookie", "mac=00:1A:79:00:00:01")
+ .header("X-User-Agent", "Model: MAG250")
+ .build()
+
+ val failure = runCatching {
+ factory.clientFor(sourceUrl.toString(), null)
+ .newCall(request)
+ .execute()
+ .close()
+ }.exceptionOrNull()
+ assertThat(failure).isInstanceOf(StalkerApiError.TransportConsentRequired::class.java)
+ assertThat(target.requestCount).isEqualTo(0)
+
+ source.enqueue(
+ MockResponse()
+ .setResponseCode(302)
+ .setHeader("Location", target.url("/portal.php"))
+ )
+ val targetOrigin = target.url("/").toTransportOrigin()
+ val acceptedClient = factory.clientFor(
+ sourceUrl.toString(),
+ StalkerTransportGrant(
+ mode = StalkerTransportMode.USER_ACCEPTED_HTTP,
+ origin = targetOrigin,
+ consentedAt = 2L
+ )
+ )
+ acceptedClient.newCall(request).execute().use {
+ assertThat(it.isSuccessful).isTrue()
+ }
+ val redirected = target.takeRequest()
+ assertThat(redirected.getHeader("Authorization")).isNull()
+ assertThat(redirected.getHeader("Cookie")).isNull()
+ assertThat(redirected.getHeader("X-User-Agent")).isNull()
+ }
+ }
+ }
+
+ @Test
+ fun `self-signed HTTPS is accepted only for approved origin and SPKI`() = runTest {
+ val certificate = HeldCertificate.Builder()
+ .commonName("localhost")
+ .addSubjectAlternativeName("localhost")
+ .build()
+ val serverCertificates = HandshakeCertificates.Builder()
+ .heldCertificate(certificate)
+ .build()
+ MockWebServer().use { server ->
+ server.useHttps(serverCertificates.sslSocketFactory(), false)
+ server.enqueue(MockResponse().setBody("ok"))
+ val url = server.url("/server/load.php").newBuilder()
+ .host("localhost")
+ .build()
+ val factory = StalkerTransportFactory(OkHttpClient())
+
+ val strictError = runCatching {
+ factory.clientFor(url.toString(), null)
+ .newCall(Request.Builder().url(url).build())
+ .execute()
+ .close()
+ }.exceptionOrNull()
+ assertThat(strictError).isInstanceOf(IOException::class.java)
+
+ val challenge = factory.challengeForTlsFailure(url.toString(), strictError!!)
+ assertThat(challenge).isNotNull()
+ assertThat(challenge!!.reason).isEqualTo(StalkerTransportChallengeReason.INVALID_TLS)
+ assertThat(challenge.proposedSpkiSha256).isNotEmpty()
+
+ val acceptedClient = factory.clientFor(url.toString(), challenge.acceptedGrant(now = 3L))
+ acceptedClient.newCall(Request.Builder().url(url).build()).execute().use {
+ assertThat(it.isSuccessful).isTrue()
+ }
+
+ val wrongOrigin = StalkerTransportGrant(
+ mode = StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS,
+ origin = StalkerTransportOrigin("https", "example.invalid", 443),
+ spkiSha256 = challenge.proposedSpkiSha256,
+ consentedAt = 4L
+ )
+ val mismatch = runCatching { factory.clientFor(url.toString(), wrongOrigin) }
+ .exceptionOrNull()
+ assertThat(mismatch).isInstanceOf(StalkerApiError.TransportConsentRequired::class.java)
+ }
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stalker/StalkerUrlFactoryDiscoveryTest.kt b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerUrlFactoryDiscoveryTest.kt
new file mode 100644
index 00000000..956a8b83
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/remote/stalker/StalkerUrlFactoryDiscoveryTest.kt
@@ -0,0 +1,56 @@
+package com.streamvault.data.remote.stalker
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class StalkerUrlFactoryDiscoveryTest {
+
+ @Test
+ fun `explicit HTTPS and HTTP schemes are preserved for all candidates`() {
+ val https = StalkerUrlFactory.loadUrlCandidates("https://portal.example.com/c/")
+ val http = StalkerUrlFactory.loadUrlCandidates("http://portal.example.com/c/index.html")
+
+ assertThat(https).containsExactly(
+ "https://portal.example.com/server/load.php",
+ "https://portal.example.com/portal.php"
+ ).inOrder()
+ assertThat(http).containsExactly(
+ "http://portal.example.com/server/load.php",
+ "http://portal.example.com/portal.php"
+ ).inOrder()
+ }
+
+ @Test
+ fun `custom base path and explicit RPC endpoint remain bounded and deterministic`() {
+ val custom = StalkerUrlFactory.loadUrlCandidates("https://portal.example.com/custom/base")
+ val direct = StalkerUrlFactory.loadUrlCandidates(
+ "https://portal.example.com/custom/server/load.php"
+ )
+
+ // Modern Ministra API family (server/load.php) is preferred across known install
+ // locations before the legacy portal.php endpoints.
+ assertThat(custom).containsExactly(
+ "https://portal.example.com/custom/base/server/load.php",
+ "https://portal.example.com/custom/base/stalker_portal/server/load.php",
+ "https://portal.example.com/custom/base/portal.php",
+ "https://portal.example.com/custom/base/stalker_portal/portal.php"
+ ).inOrder()
+ assertThat(custom.size).isAtMost(8)
+ assertThat(direct).containsExactly(
+ "https://portal.example.com/custom/server/load.php"
+ )
+ }
+
+ @Test
+ fun `bare portal bases are detected for redirect-hint probing`() {
+ assertThat(StalkerUrlFactory.isBarePortalBase("http://portal.example.com")).isTrue()
+ assertThat(StalkerUrlFactory.isBarePortalBase("http://portal.example.com/")).isTrue()
+ assertThat(StalkerUrlFactory.isBarePortalBase("https://portal.example.com/custom/base")).isTrue()
+
+ assertThat(StalkerUrlFactory.isBarePortalBase("https://portal.example.com/c")).isFalse()
+ assertThat(StalkerUrlFactory.isBarePortalBase("https://portal.example.com/c/")).isFalse()
+ assertThat(StalkerUrlFactory.isBarePortalBase("https://portal.example.com/c/index.html")).isFalse()
+ assertThat(StalkerUrlFactory.isBarePortalBase("https://portal.example.com/server/load.php")).isFalse()
+ assertThat(StalkerUrlFactory.isBarePortalBase("https://portal.example.com/stalker_portal/portal.php")).isFalse()
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
index 3c0dd2a8..bba912e2 100644
--- a/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/MovieRepositoryImplTest.kt
@@ -13,6 +13,7 @@ import com.streamvault.data.local.dao.XtreamIndexJobDao
import com.streamvault.data.local.DatabaseTransactionRunner
import com.streamvault.data.local.entity.FavoriteEntity
import com.streamvault.data.local.entity.MovieBrowseEntity
+import com.streamvault.data.local.entity.MovieCategoryHydrationEntity
import com.streamvault.data.local.entity.MovieEntity
import com.streamvault.data.local.entity.PlaybackHistoryLiteEntity
import com.streamvault.data.local.entity.ProviderEntity
@@ -50,6 +51,7 @@ import com.streamvault.domain.model.VodVariantObservation
import com.streamvault.domain.model.VodVariantPreferenceMode
import com.streamvault.domain.repository.PlaybackHistoryRepository
import com.streamvault.domain.repository.SyncMetadataRepository
+import kotlinx.coroutines.CompletableDeferred
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.flow.flowOf
@@ -59,6 +61,7 @@ import org.mockito.Mockito.timeout
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.argumentCaptor
+import org.mockito.kotlin.doSuspendableAnswer
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
@@ -249,7 +252,7 @@ class MovieRepositoryImplTest {
}
@Test
- fun `getMoviesByCategory prioritizes stalker category when background fetch is already running`() = runTest {
+ fun `getMoviesByCategory directly hydrates stalker category even when background fetch is running`() = runTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))
whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0))
@@ -269,13 +272,22 @@ class MovieRepositoryImplTest {
status = ProviderStatus.ACTIVE
)
)
+ whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(StalkerSession("http://example.com/portal.php", "http://example.com/", "token") to StalkerProviderProfile())
+ )
+ whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord("42", "Action")))
+ )
+ whenever(stalkerApiService.getVodStreamsPage(any(), any(), anyOrNull(), any())).thenReturn(
+ Result.success(StalkerPagedItems(emptyList(), page = 1, totalPages = 1, pageSize = 20))
+ )
val repository = createRepository()
val result = repository.getMoviesByCategory(7L, 42L).first()
assertThat(result).isEmpty()
- verify(syncManager).prioritizeStalkerIndexCategory(7L, ContentType.MOVIE, 42L)
- verify(stalkerApiService, never()).getVodStreamsPage(any(), any(), anyOrNull(), any())
+ verify(syncManager, never()).prioritizeStalkerIndexCategory(any(), any(), any())
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), anyOrNull(), eq(1))
}
@Test
@@ -552,9 +564,184 @@ class MovieRepositoryImplTest {
verify(stalkerApiService, never()).getVodStreamsPage(any(), any(), anyOrNull(), eq(2))
}
+ @Test
+ fun `stalker preview hydration survives preview flow cancellation`() = runTest {
+ val requestStarted = CompletableDeferred<Unit>()
+ val releaseRequest = CompletableDeferred<Unit>()
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0), flowOf(18))
+ whenever(movieDao.getByCategoryPreview(7L, 42L, 18)).thenReturn(flowOf(emptyList()))
+ whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(null)
+ whenever(categoryDao.getByProviderAndType(7L, ContentType.MOVIE.name)).thenReturn(
+ flowOf(
+ listOf(
+ com.streamvault.data.local.entity.CategoryEntity(
+ providerId = 7L,
+ categoryId = 42L,
+ name = "Action",
+ type = ContentType.MOVIE
+ )
+ )
+ )
+ )
+ whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())
+ whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())
+ whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))
+ )
+ whenever(stalkerApiService.getVodStreamsPage(any(), any(), anyOrNull(), eq(1))).doSuspendableAnswer {
+ requestStarted.complete(Unit)
+ releaseRequest.await()
+ Result.success(stalkerMoviePage(page = 1, itemCount = 18, totalPages = 1))
+ }
+
+ createRepository().getCategoryPreviewRows(7L, listOf(42L), 18).first()
+ requestStarted.await()
+ releaseRequest.complete(Unit)
+
+ verify(movieDao, timeout(1_000)).upsertCategoryPage(eq(7L), any())
+ }
+
+ @Test
+ fun `stalker movie hydration restarts at page one when successful pages produced no category rows`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0), flowOf(18))
+ whenever(movieDao.getByCategoryPreview(7L, 42L, 18)).thenReturn(flowOf(emptyList()))
+ whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(
+ MovieCategoryHydrationEntity(
+ providerId = 7L,
+ categoryId = 42L,
+ itemCount = 0,
+ lastStatus = "TRUNCATED",
+ lastLoadedPage = 2,
+ lastAttemptedPage = 2,
+ lastSuccessfulPage = 2,
+ totalPages = 10,
+ pageSize = 14
+ )
+ )
+ whenever(categoryDao.getByProviderAndType(7L, ContentType.MOVIE.name)).thenReturn(
+ flowOf(
+ listOf(
+ com.streamvault.data.local.entity.CategoryEntity(
+ providerId = 7L,
+ categoryId = 42L,
+ name = "Action",
+ type = ContentType.MOVIE
+ )
+ )
+ )
+ )
+ whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())
+ whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())
+ whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))
+ )
+ whenever(stalkerApiService.getVodStreamsPage(any(), any(), anyOrNull(), eq(1))).thenReturn(
+ Result.success(stalkerMoviePage(page = 1, itemCount = 18))
+ )
+
+ createRepository().getCategoryPreviewRows(7L, listOf(42L), 18).first()
+
+ verify(stalkerApiService, timeout(1_000)).getVodStreamsPage(any(), any(), anyOrNull(), eq(1))
+ verify(stalkerApiService, never()).getVodStreamsPage(any(), any(), anyOrNull(), eq(3))
+ }
+
+ @Test
+ fun `opening stalker movie category fills at least forty items across natural pages`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(0), flowOf(14), flowOf(28), flowOf(42))
+ whenever(movieDao.getByCategoryPage(7L, 42L, 60, 0)).thenReturn(flowOf(emptyList()))
+ whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(null)
+ whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())
+ whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())
+ whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))
+ )
+ (1..3).forEach { page ->
+ whenever(stalkerApiService.getVodStreamsPage(any(), any(), anyOrNull(), eq(page))).thenReturn(
+ Result.success(stalkerMoviePage(page = page, itemCount = 14))
+ )
+ }
+
+ createRepository().getMoviesByCategoryPage(7L, 42L, limit = 60, offset = 0).first()
+
+ (1..3).forEach { page ->
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), anyOrNull(), eq(page))
+ }
+ verify(stalkerApiService, never()).getVodStreamsPage(any(), any(), anyOrNull(), eq(4))
+ }
+
+ @Test
+ fun `browsing stalker movie category hydrates every advertised page before returning`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(
+ flowOf(0),
+ flowOf(14),
+ flowOf(28),
+ flowOf(42)
+ )
+ whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(null)
+ whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())
+ whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())
+ whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))
+ )
+ (1..3).forEach { page ->
+ whenever(stalkerApiService.getVodStreamsPage(any(), any(), anyOrNull(), eq(page))).thenReturn(
+ Result.success(stalkerMoviePage(page = page, itemCount = 14, totalPages = 3))
+ )
+ }
+ whenever(movieDao.getFreshByCategoryCursorPage(7L, 42L, 40)).thenReturn(emptyList())
+ whenever(favoriteDao.getAllByType(7L, ContentType.MOVIE.name)).thenReturn(flowOf(emptyList()))
+
+ createRepository().browseMovies(
+ LibraryBrowseQuery(providerId = 7L, categoryId = 42L, limit = 60)
+ ).first()
+
+ (1..3).forEach { page ->
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), anyOrNull(), eq(page))
+ }
+ verify(stalkerApiService, never()).getVodStreamsPage(any(), any(), anyOrNull(), eq(4))
+ }
+
+ @Test
+ fun `scrolling cached stalker movie category appends exactly one natural page`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(movieDao.getCountByCategory(7L, 42L)).thenReturn(flowOf(42), flowOf(56))
+ whenever(movieDao.getByCategoryPage(7L, 42L, 60, 60)).thenReturn(flowOf(emptyList()))
+ whenever(movieCategoryHydrationDao.get(7L, 42L)).thenReturn(
+ MovieCategoryHydrationEntity(
+ providerId = 7L,
+ categoryId = 42L,
+ itemCount = 42,
+ lastStatus = "SUCCESS",
+ lastLoadedPage = 3,
+ lastAttemptedPage = 3,
+ lastSuccessfulPage = 3,
+ totalPages = 10,
+ pageSize = 14
+ )
+ )
+ whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())
+ whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())
+ whenever(stalkerApiService.getVodCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "42", name = "Action")))
+ )
+ whenever(stalkerApiService.getVodStreamsPage(any(), any(), anyOrNull(), eq(4))).thenReturn(
+ Result.success(stalkerMoviePage(page = 4, itemCount = 14))
+ )
+
+ createRepository().getMoviesByCategoryPage(7L, 42L, limit = 60, offset = 60).first()
+
+ verify(stalkerApiService).getVodStreamsPage(any(), any(), anyOrNull(), eq(4))
+ verify(stalkerApiService, never()).getVodStreamsPage(any(), any(), anyOrNull(), eq(5))
+ }
+
@Test
fun `stalker movie category hydration preserves requested category when portal omits item category fields`() = runTest {
- val actionCategoryId = ("7/${ContentType.MOVIE.name}/42".hashCode().toLong() and 0x7fff_ffffL).coerceAtLeast(1L)
+ val actionCategoryId = ("7/${ContentType.MOVIE.name}/42".hashCode().toLong() and 0x7fff_ffffL)
+ .coerceAtLeast(1L)
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(movieDao.getCountByCategory(7L, actionCategoryId)).thenReturn(flowOf(0), flowOf(1))
whenever(movieDao.getByCategory(7L, actionCategoryId)).thenReturn(flowOf(emptyList()))
@@ -969,10 +1156,47 @@ class MovieRepositoryImplTest {
xtreamContentIndexDao = xtreamContentIndexDao,
xtreamIndexJobDao = xtreamIndexJobDao,
syncManager = syncManager,
- transactionRunner = transactionRunner
+ transactionRunner = transactionRunner,
+ stalkerRemoteIdentityResolver = mock(),
+ stalkerRequestCoordinator = com.streamvault.data.remote.stalker.StalkerRequestCoordinator(),
+ stalkerPortalStateStore = mock()
)
}
+ private fun stalkerProviderEntity() = ProviderEntity(
+ id = 7L,
+ name = "Stalker",
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = "http://example.com",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ status = ProviderStatus.ACTIVE
+ )
+
+ private fun stalkerSessionResult(): Result<Pair<StalkerSession, StalkerProviderProfile>> =
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+
+ private fun stalkerMoviePage(page: Int, itemCount: Int, totalPages: Int = 10): StalkerPagedItems =
+ StalkerPagedItems(
+ items = (1..itemCount).map { index ->
+ StalkerItemRecord(
+ id = "${page}00$index",
+ name = "Movie $page-$index",
+ categoryId = "42",
+ cmd = "ffmpeg http://example.com/movie-$page-$index.mp4",
+ containerExtension = "mp4"
+ )
+ },
+ page = page,
+ totalPages = totalPages,
+ pageSize = itemCount
+ )
+
private fun movieEntity(
id: Long,
name: String,
diff --git a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt
index 2657bd9d..9542acf5 100644
--- a/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/ProviderRepositoryImplTest.kt
@@ -5,18 +5,26 @@ 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.MovieCategoryHydrationDao
import com.streamvault.data.local.dao.ProgramDao
import com.streamvault.data.local.dao.ProgramReminderDao
import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.dao.RecordingRunDao
import com.streamvault.data.local.dao.SeriesDao
+import com.streamvault.data.local.dao.SeriesCategoryHydrationDao
+import com.streamvault.data.local.dao.StalkerIndexJobDao
import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.local.entity.CategoryEntity
+import com.streamvault.data.local.entity.StalkerIndexJobEntity
import com.streamvault.data.manager.recording.RecordingAlarmScheduler
import com.streamvault.data.manager.reminder.ProgramReminderAlarmScheduler
import com.streamvault.data.preferences.PreferencesRepository
import com.streamvault.data.remote.jellyfin.JellyfinProvider
import com.streamvault.data.remote.stalker.StalkerApiService
+import com.streamvault.data.remote.stalker.StalkerApiError
+import com.streamvault.data.remote.stalker.StalkerProvider
+import com.streamvault.data.remote.stalker.StalkerProviderProfile
+import com.streamvault.data.remote.stalker.StalkerSession
import com.streamvault.data.remote.xtream.XtreamApiService
import com.streamvault.data.remote.dto.XtreamAuthResponse
import com.streamvault.data.remote.dto.XtreamServerInfo
@@ -29,6 +37,12 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.model.ProviderStatus
import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.ContentType
+import com.streamvault.domain.model.StalkerIndexState
+import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.repository.SyncMetadataRepository
@@ -66,6 +80,9 @@ class ProviderRepositoryImplTest {
private val recordingAlarmScheduler: RecordingAlarmScheduler = mock()
private val programReminderAlarmScheduler: ProgramReminderAlarmScheduler = mock()
private val jellyfinProvider: JellyfinProvider = mock()
+ private val stalkerIndexJobDao: StalkerIndexJobDao = mock()
+ private val movieCategoryHydrationDao: MovieCategoryHydrationDao = mock()
+ private val seriesCategoryHydrationDao: SeriesCategoryHydrationDao = mock()
private val transactionRunner = object : DatabaseTransactionRunner {
override suspend fun <T> inTransaction(block: suspend () -> T): T = block()
}
@@ -90,7 +107,12 @@ class ProviderRepositoryImplTest {
transactionRunner = transactionRunner,
recordingAlarmScheduler = recordingAlarmScheduler,
programReminderAlarmScheduler = programReminderAlarmScheduler,
- jellyfinProvider = jellyfinProvider
+ jellyfinProvider = jellyfinProvider,
+ stalkerRemoteIdentityResolver = mock(),
+ stalkerIndexJobDao = stalkerIndexJobDao,
+ stalkerPortalStateStore = mock(),
+ movieCategoryHydrationDao = movieCategoryHydrationDao,
+ seriesCategoryHydrationDao = seriesCategoryHydrationDao
)
private val repository = createRepository()
@@ -106,6 +128,107 @@ class ProviderRepositoryImplTest {
}
}
+ @Test
+ fun `buildStalkerSearchIndexOnce resets terminal crawl progress before queueing fresh jobs`() = runTest {
+ whenever(providerDao.getById(7L)).thenReturn(
+ ProviderEntity(
+ id = 7L,
+ name = "Stalker",
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = "https://portal.example.com",
+ status = ProviderStatus.ACTIVE
+ )
+ )
+ whenever(stalkerIndexJobDao.get(7L, ContentType.MOVIE.name)).thenReturn(
+ StalkerIndexJobEntity(
+ providerId = 7L,
+ section = ContentType.MOVIE,
+ state = StalkerIndexState.TRUNCATED,
+ completedCategories = 9,
+ indexedRows = 900,
+ lastError = "page limit"
+ )
+ )
+
+ val result = repository.buildStalkerSearchIndexOnce(7L)
+
+ assertThat(result.isSuccess).isTrue()
+ verify(movieCategoryHydrationDao).deleteByProvider(7L)
+ verify(seriesCategoryHydrationDao).deleteByProvider(7L)
+ val jobs = argumentCaptor<StalkerIndexJobEntity>()
+ verify(stalkerIndexJobDao, org.mockito.kotlin.times(2)).upsert(jobs.capture())
+ assertThat(jobs.allValues.map { it.section }).containsExactly(ContentType.MOVIE, ContentType.SERIES)
+ jobs.allValues.forEach { job ->
+ assertThat(job.state).isEqualTo(StalkerIndexState.QUEUED)
+ assertThat(job.completedCategories).isEqualTo(0)
+ assertThat(job.indexedRows).isEqualTo(0)
+ assertThat(job.lastError).isNull()
+ }
+ verify(syncManager).scheduleStalkerIndexSync(7L, force = false)
+ }
+
+ @Test
+ fun `save without verification requires an inconclusive readiness result and stays inactive`() = runTest {
+ StalkerProvider.clearSharedAuthCacheForTests()
+ whenever(providerDao.getByUrlAndUser(any(), any(), any())).thenReturn(null)
+ whenever(providerDao.insert(any())).thenReturn(41L)
+ whenever(credentialCrypto.encryptIfNeeded(any())).thenAnswer { invocation ->
+ invocation.arguments.first() as String
+ }
+ whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.error(
+ "Authentication succeeded, but Live TV readiness could not be verified.",
+ StalkerApiError.ReadinessInconclusive(
+ evidenceCode = "LIVE_BUDGET_EXHAUSTED",
+ cause = java.io.IOException("temporary Live timeout")
+ )
+ ),
+ Result.success(
+ StalkerSession(
+ loadUrl = "https://portal.example.com/server/load.php",
+ portalReferer = "https://portal.example.com/c/",
+ token = "token"
+ ) to StalkerProviderProfile(
+ accountName = "MAG",
+ statusLabel = "1",
+ authAccess = true
+ )
+ )
+ )
+
+ val result = repository.loginStalker(
+ portalUrl = "https://portal.example.com/c/",
+ macAddress = "00:1A:79:12:34:56",
+ name = "MAG",
+ authMode = StalkerAuthMode.MAC_ONLY,
+ transportGrant = StalkerTransportGrant(
+ mode = StalkerTransportMode.VERIFIED_HTTPS,
+ origin = StalkerTransportOrigin("https", "portal.example.com", 443),
+ consentedAt = 0L
+ ),
+ saveWithoutVerification = true
+ )
+
+ assertThat(result).isInstanceOf(Result.Error::class.java)
+ val error = result as Result.Error
+ assertThat(error.exception).isInstanceOf(ProviderSavedWithSyncErrorException::class.java)
+ val saved = (error.exception as ProviderSavedWithSyncErrorException).provider
+ assertThat(saved.id).isEqualTo(41L)
+ assertThat(saved.status).isEqualTo(ProviderStatus.PARTIAL)
+ assertThat(saved.isActive).isFalse()
+ assertThat(saved.stalkerTransportOrigin).isEqualTo("https://portal.example.com:443")
+ verify(stalkerApiService, org.mockito.kotlin.times(2)).authenticate(any())
+ verify(syncManager, never()).sync(
+ any(),
+ any(),
+ anyOrNull(),
+ anyOrNull(),
+ anyOrNull(),
+ any()
+ )
+ verify(syncManager).scheduleProviderSyncResume(41L, 1L)
+ }
+
@Test
fun `deleteProvider cancels recording and reminder alarms before deleting provider rows`() = runTest {
whenever(recordingRunDao.getIdsByProvider(7L)).thenReturn(listOf("run-1", "run-2"))
diff --git a/data/src/test/java/com/streamvault/data/repository/SearchRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/SearchRepositoryImplTest.kt
index 9edc651b..8089021b 100644
--- a/data/src/test/java/com/streamvault/data/repository/SearchRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/SearchRepositoryImplTest.kt
@@ -32,7 +32,9 @@ class SearchRepositoryImplTest {
searchDao = searchDao,
channelRepository = channelRepository,
movieRepository = movieRepository,
- seriesRepository = seriesRepository
+ seriesRepository = seriesRepository,
+ providerDao = mock(),
+ stalkerIndexJobDao = mock()
)
@Test
diff --git a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
index 701db2c6..ba1eafb2 100644
--- a/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/SeriesRepositoryImplTest.kt
@@ -15,6 +15,7 @@ import com.streamvault.data.local.entity.EpisodeBrowseEntity
import com.streamvault.data.local.entity.EpisodeEntity
import com.streamvault.data.local.entity.SeriesEntity
import com.streamvault.data.local.entity.SeriesBrowseEntity
+import com.streamvault.data.local.entity.SeriesCategoryHydrationEntity
import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.local.entity.XtreamIndexJobEntity
import com.streamvault.data.preferences.PreferencesRepository
@@ -125,7 +126,7 @@ class SeriesRepositoryImplTest {
}
@Test
- fun `getSeriesByCategory prioritizes stalker category when background fetch is already running`() = runTest {
+ fun `getSeriesByCategory directly hydrates stalker category even when background fetch is running`() = runTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
whenever(preferencesRepository.xtreamBase64TextCompatibility).thenReturn(flowOf(false))
whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0))
@@ -145,13 +146,22 @@ class SeriesRepositoryImplTest {
status = ProviderStatus.ACTIVE
)
)
+ whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(StalkerSession("http://example.com/portal.php", "http://example.com/", "token") to StalkerProviderProfile())
+ )
+ whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord("77", "Drama")))
+ )
+ whenever(stalkerApiService.getSeriesPage(any(), any(), anyOrNull(), any())).thenReturn(
+ Result.success(StalkerPagedItems(emptyList(), page = 1, totalPages = 1, pageSize = 20))
+ )
val repository = createRepository()
val result = repository.getSeriesByCategory(7L, 77L).first()
assertThat(result).isEmpty()
- verify(syncManager).prioritizeStalkerIndexCategory(7L, ContentType.SERIES, 77L)
- verify(stalkerApiService, never()).getSeriesPage(any(), any(), anyOrNull(), any())
+ verify(syncManager, never()).prioritizeStalkerIndexCategory(any(), any(), any())
+ verify(stalkerApiService).getSeriesPage(any(), any(), anyOrNull(), eq(1))
verify(episodeDao, never()).deleteOrphans()
}
@@ -424,6 +434,64 @@ class SeriesRepositoryImplTest {
verify(stalkerApiService, never()).getSeriesPage(any(), any(), anyOrNull(), eq(2))
}
+ @Test
+ fun `opening stalker series category fills at least forty items across natural pages`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(0), flowOf(14), flowOf(28), flowOf(42))
+ whenever(seriesDao.getByCategoryPage(7L, 77L, 60, 0)).thenReturn(flowOf(emptyList()))
+ whenever(seriesCategoryHydrationDao.get(7L, 77L)).thenReturn(null)
+ whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())
+ whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())
+ whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "77", name = "Drama")))
+ )
+ (1..3).forEach { page ->
+ whenever(stalkerApiService.getSeriesPage(any(), any(), anyOrNull(), eq(page))).thenReturn(
+ Result.success(stalkerSeriesPage(page = page, itemCount = 14))
+ )
+ }
+
+ createRepository().getSeriesByCategoryPage(7L, 77L, limit = 60, offset = 0).first()
+
+ (1..3).forEach { page ->
+ verify(stalkerApiService).getSeriesPage(any(), any(), anyOrNull(), eq(page))
+ }
+ verify(stalkerApiService, never()).getSeriesPage(any(), any(), anyOrNull(), eq(4))
+ }
+
+ @Test
+ fun `scrolling cached stalker series category appends exactly one natural page`() = runTest {
+ whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
+ whenever(seriesDao.getCountByCategory(7L, 77L)).thenReturn(flowOf(42), flowOf(56))
+ whenever(seriesDao.getByCategoryPage(7L, 77L, 60, 60)).thenReturn(flowOf(emptyList()))
+ whenever(seriesCategoryHydrationDao.get(7L, 77L)).thenReturn(
+ SeriesCategoryHydrationEntity(
+ providerId = 7L,
+ categoryId = 77L,
+ itemCount = 42,
+ lastStatus = "SUCCESS",
+ lastLoadedPage = 3,
+ lastAttemptedPage = 3,
+ lastSuccessfulPage = 3,
+ totalPages = 10,
+ pageSize = 14
+ )
+ )
+ whenever(providerDao.getById(7L)).thenReturn(stalkerProviderEntity())
+ whenever(stalkerApiService.authenticate(any())).thenReturn(stalkerSessionResult())
+ whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "77", name = "Drama")))
+ )
+ whenever(stalkerApiService.getSeriesPage(any(), any(), anyOrNull(), eq(4))).thenReturn(
+ Result.success(stalkerSeriesPage(page = 4, itemCount = 14))
+ )
+
+ createRepository().getSeriesByCategoryPage(7L, 77L, limit = 60, offset = 60).first()
+
+ verify(stalkerApiService).getSeriesPage(any(), any(), anyOrNull(), eq(4))
+ verify(stalkerApiService, never()).getSeriesPage(any(), any(), anyOrNull(), eq(5))
+ }
+
@Test
fun `browseSeries recently updated excludes stale entries and uses filtered total count`() = runTest {
whenever(preferencesRepository.parentalControlLevel).thenReturn(flowOf(0))
@@ -1013,7 +1081,43 @@ class SeriesRepositoryImplTest {
xtreamIndexJobDao = xtreamIndexJobDao,
syncManager = syncManager,
seriesCategoryHydrationDao = seriesCategoryHydrationDao,
- jellyfinProvider = jellyfinProvider
+ jellyfinProvider = jellyfinProvider,
+ stalkerRemoteIdentityResolver = mock(),
+ stalkerRequestCoordinator = com.streamvault.data.remote.stalker.StalkerRequestCoordinator(),
+ stalkerPortalStateStore = mock()
)
}
+
+ private fun stalkerProviderEntity() = ProviderEntity(
+ id = 7L,
+ name = "Stalker",
+ type = ProviderType.STALKER_PORTAL,
+ serverUrl = "http://example.com",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ status = ProviderStatus.ACTIVE
+ )
+
+ private fun stalkerSessionResult(): Result<Pair<StalkerSession, StalkerProviderProfile>> =
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+
+ private fun stalkerSeriesPage(page: Int, itemCount: Int): StalkerPagedItems =
+ StalkerPagedItems(
+ items = (1..itemCount).map { index ->
+ StalkerItemRecord(
+ id = "${page}00$index",
+ name = "Series $page-$index",
+ categoryId = "77",
+ isSeries = true
+ )
+ },
+ page = page,
+ totalPages = 10,
+ pageSize = itemCount
+ )
}
diff --git a/data/src/test/java/com/streamvault/data/sync/StalkerIndexWorkerTest.kt b/data/src/test/java/com/streamvault/data/sync/StalkerIndexWorkerTest.kt
new file mode 100644
index 00000000..26bb3240
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/sync/StalkerIndexWorkerTest.kt
@@ -0,0 +1,26 @@
+package com.streamvault.data.sync
+
+import androidx.work.ExistingWorkPolicy
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class StalkerIndexWorkerTest {
+
+ @Test
+ fun `external scheduling keeps an existing provider chain`() {
+ assertThat(stalkerIndexExistingWorkPolicy(force = false, appendSuccessor = false))
+ .isEqualTo(ExistingWorkPolicy.KEEP)
+ }
+
+ @Test
+ fun `worker continuation appends one successor to its provider chain`() {
+ assertThat(stalkerIndexExistingWorkPolicy(force = false, appendSuccessor = true))
+ .isEqualTo(ExistingWorkPolicy.APPEND_OR_REPLACE)
+ }
+
+ @Test
+ fun `forced scheduling replaces the provider chain`() {
+ assertThat(stalkerIndexExistingWorkPolicy(force = true, appendSuccessor = true))
+ .isEqualTo(ExistingWorkPolicy.REPLACE)
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/sync/StalkerReadinessTrackerTest.kt b/data/src/test/java/com/streamvault/data/sync/StalkerReadinessTrackerTest.kt
new file mode 100644
index 00000000..348ddcb1
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/sync/StalkerReadinessTrackerTest.kt
@@ -0,0 +1,44 @@
+package com.streamvault.data.sync
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.StalkerReadiness
+import org.junit.Test
+
+class StalkerReadinessTrackerTest {
+ @Test
+ fun `readiness transitions publish committed milestone timestamps in order`() {
+ val tracker = StalkerReadinessTracker()
+
+ tracker.start(providerId = 7L, now = 100L)
+ tracker.authenticated(providerId = 7L, now = 200L)
+ tracker.liveReady(providerId = 7L, now = 300L)
+ tracker.categoriesReady(providerId = 7L, now = 400L)
+ tracker.ready(providerId = 7L, warningCount = 0, now = 500L)
+
+ assertThat(tracker.current(7L)).isEqualTo(
+ com.streamvault.domain.model.StalkerReadinessSnapshot(
+ providerId = 7L,
+ state = StalkerReadiness.READY,
+ syncStartedAt = 100L,
+ authenticatedAt = 200L,
+ liveReadyAt = 300L,
+ categoriesReadyAt = 400L,
+ readyAt = 500L,
+ warningCount = 0
+ )
+ )
+ }
+
+ @Test
+ fun `warnings produce ready with warnings and clear removes provider`() {
+ val tracker = StalkerReadinessTracker()
+ tracker.start(9L, 100L)
+ tracker.ready(9L, warningCount = 2, now = 200L)
+
+ assertThat(tracker.current(9L)?.state).isEqualTo(StalkerReadiness.READY_WITH_WARNINGS)
+ assertThat(tracker.current(9L)?.warningCount).isEqualTo(2)
+
+ tracker.clear(9L)
+ assertThat(tracker.current(9L)).isNull()
+ }
+}
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 73810ec8..fd6ce147 100644
--- a/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
+++ b/data/src/test/java/com/streamvault/data/sync/SyncManagerTest.kt
@@ -17,6 +17,7 @@ import com.streamvault.data.local.dao.ProgramDao
import com.streamvault.data.local.dao.ProviderDao
import com.streamvault.data.local.dao.SeriesCategoryHydrationDao
import com.streamvault.data.local.dao.SeriesDao
+import com.streamvault.data.local.dao.StalkerIndexJobDao
import com.streamvault.data.local.dao.TmdbIdentityDao
import com.streamvault.data.local.dao.XtreamContentIndexDao
import com.streamvault.data.local.dao.XtreamIndexJobDao
@@ -28,6 +29,8 @@ import com.streamvault.data.local.entity.MovieCategoryHydrationEntity
import com.streamvault.data.local.entity.MovieEntity
import com.streamvault.data.local.entity.ProviderEntity
import com.streamvault.data.local.entity.SeriesCategoryHydrationEntity
+import com.streamvault.data.local.entity.StalkerIndexJobEntity
+import com.streamvault.data.local.entity.StalkerPortalStateEntity
import com.streamvault.data.local.entity.XtreamIndexJobEntity
import com.streamvault.data.local.entity.XtreamLiveOnboardingStateEntity
import com.streamvault.data.parser.M3uParser
@@ -37,6 +40,8 @@ import com.streamvault.domain.model.Result
import com.streamvault.domain.model.ProviderEpgSyncMode
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.ProviderType
+import com.streamvault.domain.model.StalkerIndexState
+import com.streamvault.domain.model.StalkerTransportMode
import com.streamvault.domain.model.SyncMetadata
import com.streamvault.domain.repository.EpgRepository
import com.streamvault.domain.repository.EpgSourceRepository
@@ -336,7 +341,9 @@ class SyncManagerTest {
private fun buildManager(
providerType: ProviderType = ProviderType.XTREAM_CODES,
providerPresent: Boolean = true,
- providerEntity: ProviderEntity? = null
+ providerEntity: ProviderEntity? = null,
+ readinessTracker: StalkerReadinessTracker = StalkerReadinessTracker(),
+ portalStateStore: com.streamvault.data.remote.stalker.StalkerPortalStateStore = mock()
): SyncManager = SyncManager(
applicationContext = applicationContext,
providerDao = FakeProviderDao(
@@ -357,6 +364,81 @@ class SyncManagerTest {
tmdbIdentityDao = tmdbIdentityDao,
xtreamContentIndexDao = xtreamContentIndexDao,
xtreamIndexJobDao = xtreamIndexJobDao,
+ stalkerIndexJobDao = object : StalkerIndexJobDao {
+ override fun observeForProvider(providerId: Long): Flow<List<StalkerIndexJobEntity>> = flowOf(emptyList())
+
+ override suspend fun get(providerId: Long, section: String): StalkerIndexJobEntity? =
+ xtreamIndexJobDao.get(providerId, section)?.let { job ->
+ StalkerIndexJobEntity(
+ providerId = job.providerId,
+ section = ContentType.valueOf(job.section),
+ state = when (job.state) {
+ "QUEUED", "STALE" -> StalkerIndexState.QUEUED
+ "RUNNING" -> StalkerIndexState.RUNNING
+ "FAILED_RETRYABLE" -> StalkerIndexState.RETRY_WAIT
+ "PARTIAL" -> StalkerIndexState.PARTIAL
+ "SUCCESS", "COMPLETE" -> StalkerIndexState.COMPLETE
+ "TRUNCATED" -> StalkerIndexState.TRUNCATED
+ "FAILED", "FAILED_PERMANENT" -> StalkerIndexState.FAILED
+ else -> StalkerIndexState.DISABLED
+ },
+ totalCategories = job.totalCategories,
+ completedCategories = job.completedCategories,
+ nextCategoryIndex = job.nextCategoryIndex,
+ failedCategories = job.failedCategories,
+ indexedRows = job.indexedRows,
+ skippedMalformedRows = job.skippedMalformedRows,
+ deletedPrunedRows = job.deletedPrunedRows,
+ lastError = job.lastError,
+ lastAttemptAt = job.lastAttemptAt,
+ lastSuccessAt = job.lastSuccessAt,
+ updatedAt = job.updatedAt
+ )
+ }
+
+ override suspend fun getNextPending(providerId: Long): StalkerIndexJobEntity? =
+ listOf(ContentType.MOVIE, ContentType.SERIES)
+ .mapNotNull { section -> get(providerId, section.name) }
+ .filter { it.state in setOf(StalkerIndexState.QUEUED, StalkerIndexState.RETRY_WAIT, StalkerIndexState.PARTIAL) }
+ .minByOrNull(StalkerIndexJobEntity::updatedAt)
+
+ override suspend fun upsert(entity: StalkerIndexJobEntity) {
+ xtreamIndexJobDao.upsert(
+ XtreamIndexJobEntity(
+ providerId = entity.providerId,
+ section = entity.section.name,
+ state = when (entity.state) {
+ StalkerIndexState.DISABLED -> "DISABLED"
+ StalkerIndexState.QUEUED -> "QUEUED"
+ StalkerIndexState.RUNNING -> "RUNNING"
+ StalkerIndexState.RETRY_WAIT -> "FAILED_RETRYABLE"
+ StalkerIndexState.PARTIAL -> "PARTIAL"
+ StalkerIndexState.COMPLETE -> "SUCCESS"
+ StalkerIndexState.TRUNCATED -> "TRUNCATED"
+ StalkerIndexState.FAILED -> "FAILED_PERMANENT"
+ },
+ totalCategories = entity.totalCategories,
+ completedCategories = entity.completedCategories,
+ nextCategoryIndex = entity.nextCategoryIndex,
+ failedCategories = entity.failedCategories,
+ indexedRows = entity.indexedRows,
+ skippedMalformedRows = entity.skippedMalformedRows,
+ deletedPrunedRows = entity.deletedPrunedRows,
+ lastError = entity.lastError,
+ lastAttemptAt = entity.lastAttemptAt,
+ lastSuccessAt = entity.lastSuccessAt,
+ updatedAt = entity.updatedAt
+ )
+ )
+ }
+
+ override suspend fun upsertAll(entities: List<StalkerIndexJobEntity>) {
+ entities.forEach { upsert(it) }
+ }
+
+ override suspend fun disableForProvider(providerId: Long, updatedAt: Long): Int = 0
+ override suspend fun deleteByProvider(providerId: Long): Int = 0
+ },
xtreamLiveOnboardingDao = xtreamLiveOnboardingDao,
stalkerApiService = stalkerApiService,
episodeDao = episodeDao,
@@ -370,7 +452,11 @@ class SyncManagerTest {
syncMetadataRepository = syncMetadataRepo,
transactionRunner = transactionRunner,
preferencesRepository = preferencesRepo,
- syncProgressBus = SyncProgressBus()
+ syncProgressBus = SyncProgressBus(),
+ stalkerRemoteIdentityResolver = mock(),
+ stalkerRequestCoordinator = com.streamvault.data.remote.stalker.StalkerRequestCoordinator(),
+ stalkerPortalStateStore = portalStateStore,
+ stalkerReadinessTracker = readinessTracker
)
// ── Initial state ───────────────────────────────────────────────
@@ -469,6 +555,49 @@ class SyncManagerTest {
assertThat(profile.deviceId2).isEqualTo("DDEEFF")
}
+ @Test
+ fun sync_stalker_rebuilt_provider_carries_persisted_transport_grant() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ stalkerTransportMode = StalkerTransportMode.USER_ACCEPTED_HTTP,
+ stalkerTransportOrigin = "http://example.com:80",
+ stalkerTransportConsentAt = 123456789L,
+ epgSyncMode = ProviderEpgSyncMode.SKIP
+ )
+ val mgr = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+
+ mgr.sync(1L, force = true)
+ advanceUntilIdle()
+
+ val profileCaptor = argumentCaptor<StalkerDeviceProfile>()
+ verify(stalkerApiService, atLeastOnce()).authenticate(profileCaptor.capture())
+ val grant = profileCaptor.firstValue.transportGrant
+ assertThat(grant).isNotNull()
+ assertThat(grant!!.mode).isEqualTo(StalkerTransportMode.USER_ACCEPTED_HTTP)
+ assertThat(grant.origin.authority).isEqualTo("http://example.com:80")
+ assertThat(grant.consentedAt).isEqualTo(123456789L)
+ }
+
+ @Test
+ fun sync_stalker_rebuilt_provider_omits_transport_grant_for_auto_strict() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "https://example.com",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ stalkerTransportMode = StalkerTransportMode.AUTO_STRICT,
+ stalkerTransportOrigin = "",
+ epgSyncMode = ProviderEpgSyncMode.SKIP
+ )
+ val mgr = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+
+ mgr.sync(1L, force = true)
+ advanceUntilIdle()
+
+ val profileCaptor = argumentCaptor<StalkerDeviceProfile>()
+ verify(stalkerApiService, atLeastOnce()).authenticate(profileCaptor.capture())
+ assertThat(profileCaptor.firstValue.transportGrant).isNull()
+ }
+
// ── Xtream sync failure ─────────────────────────────────────────
@Test
@@ -1832,7 +1961,7 @@ class SyncManagerTest {
}
@Test
- fun `processQueuedStalkerIndexJobs commits first movie category before fetching next category for one connection provider`() = runTest {
+ fun `processQueuedStalkerIndexJobs metadata concurrency is independent of playback connection entitlement`() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -1897,11 +2026,6 @@ class SyncManagerTest {
}
org.mockito.kotlin.whenever(movieDao.getByStreamIds(eq(1L), any())).thenReturn(emptyList())
- val firstCategoryCommitted = CompletableDeferred<Unit>()
- org.mockito.kotlin.whenever(movieDao.insertAll(any())).doSuspendableAnswer {
- firstCategoryCommitted.complete(Unit)
- Unit
- }
org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("5"), eq(1))).thenReturn(
Result.success(
StalkerPagedItems(
@@ -1919,8 +2043,7 @@ class SyncManagerTest {
)
)
)
- org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("6"), eq(1))).thenAnswer {
- assertThat(firstCategoryCommitted.isCompleted).isTrue()
+ org.mockito.kotlin.whenever(stalkerApiService.getVodStreamsPage(any(), any(), eq("6"), eq(1))).thenReturn(
Result.success(
StalkerPagedItems(
items = listOf(
@@ -1936,7 +2059,7 @@ class SyncManagerTest {
pageSize = 14
)
)
- }
+ )
val result = manager.processQueuedStalkerIndexJobs(
providerId = 1L,
@@ -2430,7 +2553,7 @@ class SyncManagerTest {
}
@Test
- fun sync_stalker_persists_only_vod_and_series_categories_during_initial_sync() = runTest {
+ fun sync_stalker_persists_only_vod_and_series_categories_during_on_demand_initial_sync() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -2438,7 +2561,12 @@ class SyncManagerTest {
stalkerMacAddress = "00:11:22:33:44:55",
epgSyncMode = ProviderEpgSyncMode.SKIP
)
- val manager = buildManager(providerType = ProviderType.STALKER_PORTAL, providerEntity = providerEntity)
+ val readinessTracker = StalkerReadinessTracker()
+ val manager = buildManager(
+ providerType = ProviderType.STALKER_PORTAL,
+ providerEntity = providerEntity,
+ readinessTracker = readinessTracker
+ )
org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
Result.success(
@@ -2476,18 +2604,12 @@ class SyncManagerTest {
assertThat(metadata?.movieSyncMode).isEqualTo(com.streamvault.domain.model.VodSyncMode.PAGED)
assertThat(metadata?.movieCount).isEqualTo(0)
assertThat(metadata?.seriesCount).isEqualTo(0)
- val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
- assertThat(queuedJobCaptor.allValues.any { job ->
- job.providerId == 1L &&
- job.section == ContentType.MOVIE.name &&
- job.state == "QUEUED"
- }).isTrue()
- assertThat(queuedJobCaptor.allValues.any { job ->
- job.providerId == 1L &&
- job.section == ContentType.SERIES.name &&
- job.state == "QUEUED"
- }).isTrue()
+ assertThat(readinessTracker.current(1L)?.state)
+ .isEqualTo(com.streamvault.domain.model.StalkerReadiness.READY)
+ assertThat(readinessTracker.current(1L)?.authenticatedAt).isNotNull()
+ assertThat(readinessTracker.current(1L)?.liveReadyAt).isNotNull()
+ assertThat(readinessTracker.current(1L)?.categoriesReadyAt).isNotNull()
+ verify(xtreamIndexJobDao, org.mockito.kotlin.times(0)).upsert(any())
verify(stalkerApiService).getVodCategories(any(), any())
verify(stalkerApiService).getSeriesCategories(any(), any())
verify(stalkerApiService).streamLiveStreams(any(), any(), any())
@@ -2498,7 +2620,112 @@ class SyncManagerTest {
}
@Test
- fun sync_stalker_with_empty_live_catalog_still_queues_vod_and_series_categories() = runTest {
+ fun sync_stalker_skips_bulk_live_when_validated_capability_is_unsupported() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.SKIP
+ )
+ val portalStateStore = mock<com.streamvault.data.remote.stalker.StalkerPortalStateStore>()
+ org.mockito.kotlin.whenever(portalStateStore.getValidated(eq(1L), any())).thenReturn(
+ StalkerPortalStateEntity(
+ providerId = 1L,
+ bulkLiveSupported = false,
+ bulkLiveCategoryFidelity = false,
+ validatedAt = System.currentTimeMillis()
+ )
+ )
+ val manager = buildManager(
+ providerType = ProviderType.STALKER_PORTAL,
+ providerEntity = providerEntity,
+ portalStateStore = portalStateStore
+ )
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(
+ Result.success(listOf(StalkerCategoryRecord(id = "10", name = "News")))
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getLiveStreams(any(), any(), eq("10"))).thenReturn(
+ Result.success(
+ listOf(
+ StalkerItemRecord(
+ id = "100",
+ name = "News",
+ categoryId = "10",
+ cmd = "ffmpeg http://example.com/live.ts"
+ )
+ )
+ )
+ )
+
+ val result = manager.sync(providerId = 1L, force = false)
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamLiveStreams(any(), any(), any())
+ verify(stalkerApiService).getLiveStreams(any(), any(), eq("10"))
+ }
+
+ @Test
+ fun sync_stalker_skips_known_unsupported_epg_and_finishes_ready_with_warning() = runTest {
+ val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
+ serverUrl = "http://example.com",
+ username = "",
+ password = "",
+ stalkerMacAddress = "00:11:22:33:44:55",
+ epgSyncMode = ProviderEpgSyncMode.UPFRONT,
+ epgUrl = ""
+ )
+ val portalStateStore = mock<com.streamvault.data.remote.stalker.StalkerPortalStateStore>()
+ org.mockito.kotlin.whenever(portalStateStore.getValidated(eq(1L), any())).thenReturn(
+ StalkerPortalStateEntity(
+ providerId = 1L,
+ epgSupported = false,
+ validatedAt = System.currentTimeMillis()
+ )
+ )
+ val readinessTracker = StalkerReadinessTracker()
+ val manager = buildManager(
+ providerType = ProviderType.STALKER_PORTAL,
+ providerEntity = providerEntity,
+ readinessTracker = readinessTracker,
+ portalStateStore = portalStateStore
+ )
+
+ org.mockito.kotlin.whenever(stalkerApiService.authenticate(any())).thenReturn(
+ Result.success(
+ StalkerSession(
+ loadUrl = "http://example.com/stalker_portal/server/load.php",
+ portalReferer = "http://example.com/stalker_portal/c/",
+ token = "token"
+ ) to StalkerProviderProfile(accountName = "Stalker")
+ )
+ )
+ org.mockito.kotlin.whenever(stalkerApiService.getLiveCategories(any(), any())).thenReturn(
+ Result.success(emptyList())
+ )
+
+ val result = manager.sync(providerId = 1L, force = false)
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ assertThat(readinessTracker.current(1L)?.state)
+ .isEqualTo(com.streamvault.domain.model.StalkerReadiness.READY_WITH_WARNINGS)
+ assertThat(readinessTracker.current(1L)?.warningCount).isGreaterThan(0)
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamBulkEpg(any(), any(), any(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), any(), any(), any())
+ }
+
+ @Test
+ fun sync_stalker_with_empty_live_catalog_still_commits_vod_and_series_categories() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -2533,16 +2760,7 @@ class SyncManagerTest {
assertThat(result).isInstanceOf(Result.Success::class.java)
verify(stalkerApiService).getVodCategories(any(), any())
verify(stalkerApiService).getSeriesCategories(any(), any())
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(check<XtreamIndexJobEntity> { job ->
- if (job.section == ContentType.MOVIE.name) {
- assertThat(job.state).isEqualTo("QUEUED")
- }
- })
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(check<XtreamIndexJobEntity> { job ->
- if (job.section == ContentType.SERIES.name) {
- assertThat(job.state).isEqualTo("QUEUED")
- }
- })
+ verify(xtreamIndexJobDao, org.mockito.kotlin.times(0)).upsert(any())
}
@Test
@@ -2595,20 +2813,13 @@ class SyncManagerTest {
it.type == ContentType.SERIES && it.name == "All Series" &&
it.categoryId == stalkerSyntheticCategoryId(1L, ContentType.SERIES, "*")
}).isTrue()
- val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
- assertThat(queuedJobCaptor.allValues.any {
- it.section == ContentType.MOVIE.name && it.state == "QUEUED" && it.totalCategories == 1
- }).isTrue()
- assertThat(queuedJobCaptor.allValues.any {
- it.section == ContentType.SERIES.name && it.state == "QUEUED" && it.totalCategories == 1
- }).isTrue()
+ verify(xtreamIndexJobDao, org.mockito.kotlin.times(0)).upsert(any())
verify(stalkerApiService, org.mockito.kotlin.times(0)).getVodStreamsPage(any(), any(), anyOrNull(), any())
verify(stalkerApiService, org.mockito.kotlin.times(0)).getSeriesPage(any(), any(), anyOrNull(), any())
}
@Test
- fun sync_stalker_queues_epg_until_after_background_catalog_indexing() = runTest {
+ fun sync_stalker_runs_upfront_epg_independently_of_catalog_indexing() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -2646,24 +2857,18 @@ class SyncManagerTest {
org.mockito.kotlin.whenever(stalkerApiService.getSeriesCategories(any(), any())).thenReturn(
Result.success(listOf(StalkerCategoryRecord(id = "77", name = "Drama")))
)
+ org.mockito.kotlin.whenever(channelDao.getGuideSyncEntriesByProvider(1L)).thenReturn(emptyList())
+ org.mockito.kotlin.whenever(programDao.countByProvider(1L)).thenReturn(0)
val result = manager.sync(providerId = 1L, force = false)
assertThat(result).isInstanceOf(Result.Success::class.java)
- val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
- assertThat(queuedJobCaptor.allValues.any { job ->
- job.providerId == 1L &&
- job.section == "EPG" &&
- job.state == "QUEUED"
- }).isTrue()
- verify(stalkerApiService, org.mockito.kotlin.times(0)).streamBulkEpg(any(), any(), any(), any())
- verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), any(), any(), any())
- verify(epgRepo, org.mockito.kotlin.times(0)).refreshEpg(any(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).getVodStreamsPage(any(), any(), anyOrNull(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).getSeriesPage(any(), any(), anyOrNull(), any())
}
@Test
- fun syncEpg_stalker_defers_while_catalog_index_jobs_are_pending() = runTest {
+ fun syncEpg_stalker_does_not_wait_for_pending_catalog_jobs() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -2688,24 +2893,18 @@ class SyncManagerTest {
state = "QUEUED"
)
)
+ org.mockito.kotlin.whenever(channelDao.getGuideSyncEntriesByProvider(1L)).thenReturn(emptyList())
+ org.mockito.kotlin.whenever(programDao.countByProvider(1L)).thenReturn(0)
val result = manager.syncEpg(providerId = 1L, force = false)
assertThat(result).isInstanceOf(Result.Success::class.java)
- val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
- assertThat(queuedJobCaptor.allValues.any { job ->
- job.providerId == 1L &&
- job.section == "EPG" &&
- job.state == "QUEUED"
- }).isTrue()
- verify(stalkerApiService, org.mockito.kotlin.times(0)).streamBulkEpg(any(), any(), any(), any())
- verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), any(), any(), any())
- verify(epgRepo, org.mockito.kotlin.times(0)).refreshEpg(any(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).getVodStreamsPage(any(), any(), anyOrNull(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).getSeriesPage(any(), any(), anyOrNull(), any())
}
@Test
- fun syncEpg_stalker_defers_while_catalog_index_job_is_partial() = runTest {
+ fun syncEpg_stalker_does_not_wait_for_partial_catalog_job() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -2751,20 +2950,14 @@ class SyncManagerTest {
retryBudgetRemaining = 2
)
)
+ org.mockito.kotlin.whenever(channelDao.getGuideSyncEntriesByProvider(1L)).thenReturn(emptyList())
+ org.mockito.kotlin.whenever(programDao.countByProvider(1L)).thenReturn(0)
val result = manager.syncEpg(providerId = 1L, force = false)
assertThat(result).isInstanceOf(Result.Success::class.java)
- val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
- assertThat(queuedJobCaptor.allValues.any { job ->
- job.providerId == 1L &&
- job.section == "EPG" &&
- job.state == "QUEUED"
- }).isTrue()
- verify(stalkerApiService, org.mockito.kotlin.times(0)).streamBulkEpg(any(), any(), any(), any())
- verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), any(), any(), any())
- verify(epgRepo, org.mockito.kotlin.times(0)).refreshEpg(any(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).getVodStreamsPage(any(), any(), anyOrNull(), any())
+ verify(stalkerApiService, org.mockito.kotlin.times(0)).getSeriesPage(any(), any(), anyOrNull(), any())
}
@Test
@@ -2926,7 +3119,7 @@ class SyncManagerTest {
}
@Test
- fun sync_stalker_upfront_epg_queues_native_portal_guide_until_catalog_is_idle() = runTest {
+ fun sync_stalker_upfront_epg_imports_native_portal_guide_before_returning() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -2988,21 +3181,14 @@ class SyncManagerTest {
val result = manager.sync(providerId = 1L, force = true)
assertThat(result).isInstanceOf(Result.Success::class.java)
- val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
- assertThat(queuedJobCaptor.allValues.any { job ->
- job.providerId == 1L &&
- job.section == "EPG" &&
- job.state == "QUEUED"
- }).isTrue()
verify(stalkerApiService).streamLiveStreams(any(), any(), any())
verify(stalkerApiService, org.mockito.kotlin.times(0)).getLiveStreams(any(), any(), eq("10"))
- verify(stalkerApiService, org.mockito.kotlin.times(0)).streamEpg(any(), any(), eq("100"), any(), any())
- verify(programDao, org.mockito.kotlin.times(0)).insertAll(any())
+ verify(stalkerApiService).streamEpg(any(), any(), eq("100"), any(), any())
+ verify(programDao, atLeastOnce()).insertAll(any())
}
@Test
- fun sync_stalker_upfront_epg_defers_batched_native_portal_guide_until_catalog_is_idle() = runTest {
+ fun sync_stalker_upfront_epg_imports_native_portal_guide_in_batches() = runTest {
val providerEntity = sampleProvider(ProviderType.STALKER_PORTAL).copy(
serverUrl = "http://example.com",
username = "",
@@ -3064,14 +3250,7 @@ class SyncManagerTest {
val result = manager.sync(providerId = 1L, force = true)
assertThat(result).isInstanceOf(Result.Success::class.java)
- val queuedJobCaptor = argumentCaptor<XtreamIndexJobEntity>()
- verify(xtreamIndexJobDao, atLeastOnce()).upsert(queuedJobCaptor.capture())
- assertThat(queuedJobCaptor.allValues.any { job ->
- job.providerId == 1L &&
- job.section == "EPG" &&
- job.state == "QUEUED"
- }).isTrue()
- verify(programDao, org.mockito.kotlin.times(0)).insertAll(any())
+ verify(programDao, atLeastOnce()).insertAll(any())
}
@Test
diff --git a/data/src/test/resources/stalker/fixtures/README.md b/data/src/test/resources/stalker/fixtures/README.md
index d347a0a4..ed166072 100644
--- a/data/src/test/resources/stalker/fixtures/README.md
+++ b/data/src/test/resources/stalker/fixtures/README.md
@@ -27,3 +27,13 @@ Capture/export helper:
```
The script extracts Stalker `action=` requests from a HAR capture, redacts domains/tokens/MACs/credentials deterministically, and emits a replay-fixture skeleton in the same format used by `StalkerPortalReplayHarnessTest`.
+
+Fixtures may also include an `operations` array. The acceptance harness currently understands
+`MOVIE_PREVIEW`, `SERIES_PREVIEW`, `EPG`, and `BACKGROUND_INDEX`; it uses these to assert that
+on-demand setup performs no item-page calls and that later work remains page-bounded.
+
+For authorized comparisons, run `tools/stalker-trace-compare.ps1` with a reference-client HAR
+and a StreamVault HAR. Its output contains only action/type/endpoint-family timing and byte counts.
+For connected playback and migration evidence, run `tools/stalker-connected-validation.ps1` once
+per Live channel; the script enforces `ROTATION_270`, captures 61 frames by default, hashes them,
+checks the media session, and writes only filtered and redacted player logs.
diff --git a/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json b/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json
index 4d2472b3..a3dd2be5 100644
--- a/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json
+++ b/data/src/test/resources/stalker/fixtures/archive_recipe_fallback.json
@@ -3,7 +3,7 @@
"device": {
"portalUrl": "https://portal.example.com/c",
"macAddress": "00:1A:79:AC:10:04",
- "authMode": "AUTO",
+ "authMode": "MAC_PLUS_CREDENTIALS",
"username": "archive",
"password": "secret"
},
diff --git a/data/src/test/resources/stalker/fixtures/auth_plus_mag.json b/data/src/test/resources/stalker/fixtures/auth_plus_mag.json
index a896d71b..907be7ee 100644
--- a/data/src/test/resources/stalker/fixtures/auth_plus_mag.json
+++ b/data/src/test/resources/stalker/fixtures/auth_plus_mag.json
@@ -3,7 +3,7 @@
"device": {
"portalUrl": "https://portal.example.com/server/load.php",
"macAddress": "00:1A:79:AA:BB:CC",
- "authMode": "AUTO",
+ "authMode": "MAC_PLUS_CREDENTIALS",
"username": "alice",
"password": "secret"
},
diff --git a/data/src/test/resources/stalker/fixtures/on_demand_acceptance.json b/data/src/test/resources/stalker/fixtures/on_demand_acceptance.json
new file mode 100644
index 00000000..68d210a5
--- /dev/null
+++ b/data/src/test/resources/stalker/fixtures/on_demand_acceptance.json
@@ -0,0 +1,60 @@
+{
+ "name": "on_demand_acceptance",
+ "device": {
+ "portalUrl": "https://portal.example.com/c",
+ "macAddress": "00:1A:79:12:34:56",
+ "authMode": "AUTO",
+ "deviceProfile": "MAG250",
+ "timezone": "Asia/Jerusalem",
+ "locale": "en"
+ },
+ "responses": [
+ { "action": "handshake", "body": "{\"js\":{\"token\":\"fixture-token\"}}" },
+ { "action": "get_profile", "body": "{\"js\":{\"id\":\"77\",\"name\":\"Acceptance\",\"status\":\"1\",\"auth_access\":true}}" },
+ { "action": "get_genres", "body": "{\"js\":[{\"id\":\"10\",\"title\":\"News\"}]}" },
+ { "action": "get_all_channels", "body": "{\"js\":{\"data\":[{\"id\":\"100\",\"name\":\"News One\",\"tv_genre_id\":\"10\",\"cmd\":\"ffmpeg http://media.invalid/live.ts\"}]}}" },
+ { "action": "get_categories", "body": "{\"js\":[{\"id\":\"20\",\"title\":\"Recent Movies\"}]}" },
+ { "action": "get_categories", "body": "{\"js\":[{\"id\":\"30\",\"title\":\"Recent Series\"}]}" },
+ { "action": "get_ordered_list", "body": "{\"js\":{\"total_items\":\"36\",\"max_page_items\":\"18\",\"data\":[{\"id\":\"201\",\"name\":\"Movie 1\",\"category_id\":\"20\"}]}}" },
+ { "action": "get_ordered_list", "body": "{\"js\":{\"total_items\":\"36\",\"max_page_items\":\"18\",\"data\":[{\"id\":\"202\",\"name\":\"Movie 2\",\"category_id\":\"20\"}]}}" },
+ { "action": "get_ordered_list", "body": "{\"js\":{\"total_items\":\"36\",\"max_page_items\":\"18\",\"data\":[{\"id\":\"301\",\"name\":\"Series 1\",\"category_id\":\"30\",\"is_series\":\"1\"}]}}" },
+ { "action": "get_ordered_list", "body": "{\"js\":{\"total_items\":\"36\",\"max_page_items\":\"18\",\"data\":[{\"id\":\"302\",\"name\":\"Series 2\",\"category_id\":\"30\",\"is_series\":\"1\"}]}}" },
+ { "action": "get_epg_info", "body": "{\"js\":[{\"id\":\"p1\",\"ch_id\":\"100\",\"name\":\"Morning News\",\"start_timestamp\":\"1700000000\",\"stop_timestamp\":\"1700003600\"}]}" },
+ { "action": "get_ordered_list", "body": "{\"js\":{\"total_items\":\"54\",\"max_page_items\":\"18\",\"data\":[{\"id\":\"203\",\"name\":\"Movie 3\",\"category_id\":\"20\"}]}}" }
+ ],
+ "operations": [
+ { "type": "MOVIE_PREVIEW", "categoryId": "20", "pages": 2 },
+ { "type": "SERIES_PREVIEW", "categoryId": "30", "pages": 2 },
+ { "type": "EPG" },
+ { "type": "BACKGROUND_INDEX", "categoryId": "20", "page": 3 }
+ ],
+ "expected": {
+ "authMode": "MAC_ONLY",
+ "portalProfile": "MAG_BASIC",
+ "bootstrapEvidence": ["handshake", "get_profile"],
+ "requestOrder": ["handshake", "get_profile"],
+ "maxAuthenticationMillis": 3000,
+ "maxReadinessMillis": 10000,
+ "maxConcurrency": 2,
+ "maxMoviePagesAfterSetup": 3,
+ "maxSeriesPagesAfterSetup": 2,
+ "acceptanceRequestOrder": [
+ "handshake",
+ "get_profile",
+ "get_genres",
+ "get_all_channels",
+ "get_categories",
+ "get_categories",
+ "get_ordered_list",
+ "get_ordered_list",
+ "get_ordered_list",
+ "get_ordered_list",
+ "get_epg_info",
+ "get_ordered_list"
+ ],
+ "requestCount": 12,
+ "orderedPages": [1, 2, 1, 2, 3],
+ "readinessMilestones": ["AUTHENTICATING", "LIVE_READY", "CATEGORIES_READY", "READY"],
+ "minResponseBytes": 1
+ }
+}
diff --git a/data/src/test/resources/stalker/fixtures/recipe_fallback.json b/data/src/test/resources/stalker/fixtures/recipe_fallback.json
index bc6bdeb2..f401eeb2 100644
--- a/data/src/test/resources/stalker/fixtures/recipe_fallback.json
+++ b/data/src/test/resources/stalker/fixtures/recipe_fallback.json
@@ -3,7 +3,7 @@
"device": {
"portalUrl": "https://portal.example.com/c",
"macAddress": "00:1A:79:FA:CE:03",
- "authMode": "AUTO",
+ "authMode": "MAC_PLUS_CREDENTIALS",
"username": "fallback",
"password": "secret"
},
diff --git a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt
index bee3ddf4..b996711f 100644
--- a/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt
+++ b/domain/src/main/java/com/streamvault/domain/manager/BackupManager.kt
@@ -8,7 +8,7 @@ import kotlinx.coroutines.flow.Flow
import com.streamvault.domain.model.Result
data class BackupData(
- val version: Int = 8,
+ val version: Int = 10,
val checksum: String? = null,
val preferences: Map<String, String>? = null,
val providers: List<Provider>? = null,
diff --git a/domain/src/main/java/com/streamvault/domain/manager/ProviderSyncStateReader.kt b/domain/src/main/java/com/streamvault/domain/manager/ProviderSyncStateReader.kt
index 6bf19208..31d851cd 100644
--- a/domain/src/main/java/com/streamvault/domain/manager/ProviderSyncStateReader.kt
+++ b/domain/src/main/java/com/streamvault/domain/manager/ProviderSyncStateReader.kt
@@ -1,9 +1,13 @@
package com.streamvault.domain.manager
import com.streamvault.domain.model.SyncState
+import com.streamvault.domain.model.StalkerReadinessSnapshot
import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.flowOf
interface ProviderSyncStateReader {
fun currentSyncState(providerId: Long): SyncState
+ fun currentStalkerReadiness(providerId: Long): StalkerReadinessSnapshot? = null
+ fun observeStalkerReadiness(providerId: Long): Flow<StalkerReadinessSnapshot?> = flowOf(null)
fun observeBackgroundIndexingActive(providerId: Long): Flow<Boolean>
}
diff --git a/domain/src/main/java/com/streamvault/domain/model/Provider.kt b/domain/src/main/java/com/streamvault/domain/model/Provider.kt
index d66b959d..29e3a226 100644
--- a/domain/src/main/java/com/streamvault/domain/model/Provider.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/Provider.kt
@@ -24,6 +24,19 @@ data class Provider(
val stalkerPortalProfile: StalkerPortalProfile = StalkerPortalProfile.MAG_BASIC,
val stalkerPortalFingerprint: StalkerPortalFingerprint = StalkerPortalFingerprint.BASIC_MAC,
val stalkerMagPreset: StalkerMagPreset = StalkerMagPreset.GENERIC_SAFE,
+ val stalkerProtocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ val stalkerTransportMode: StalkerTransportMode = StalkerTransportMode.AUTO_STRICT,
+ val stalkerTransportOrigin: String = "",
+ val stalkerTlsSpkiSha256: String = "",
+ val stalkerTransportConsentAt: Long = 0L,
+ val stalkerConfigurationGeneration: Long = 0L,
+ val stalkerDiscoverySummary: String = "",
+ val stalkerCapabilitiesJson: String = "",
+ val stalkerRequestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
+ val stalkerLearnedProfileId: String = "",
+ val stalkerProfileRevision: Int = 0,
+ val stalkerProfileVerification: StalkerProfileVerification = StalkerProfileVerification.UNVERIFIED,
+ val stalkerProtocolFamily: StalkerProtocolFamily = StalkerProtocolFamily.CLASSIC_MAG,
val stalkerLastBootstrapRecipe: StalkerBootstrapRecipe = StalkerBootstrapRecipe.GENERIC_SAFE,
val stalkerEndpointPreference: StalkerEndpointPreference = StalkerEndpointPreference.AUTO,
val stalkerCookieMode: StalkerCookieMode = StalkerCookieMode.NONE,
@@ -42,6 +55,7 @@ data class Provider(
val apiVersion: String? = null,
val allowedOutputFormats: List<String> = emptyList(),
val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.UPFRONT,
+ val stalkerCatalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,
val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,
val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,
val xtreamFastSyncEnabled: Boolean = true,
@@ -74,6 +88,61 @@ enum class ProviderEpgSyncMode {
SKIP
}
+enum class StalkerCatalogMode {
+ ON_DEMAND,
+ BACKGROUND_INDEX
+}
+
+enum class StalkerReadiness {
+ AUTHENTICATING,
+ LIVE_READY,
+ CATEGORIES_READY,
+ READY,
+ READY_WITH_WARNINGS
+}
+
+/**
+ * Provider-scoped snapshot of the fast Stalker readiness path.
+ *
+ * Timestamps are epoch milliseconds and are populated only after the corresponding
+ * operation (and, for catalog stages, its database commit) has completed.
+ */
+data class StalkerReadinessSnapshot(
+ val providerId: Long,
+ val state: StalkerReadiness,
+ val syncStartedAt: Long,
+ val authenticatedAt: Long? = null,
+ val liveReadyAt: Long? = null,
+ val categoriesReadyAt: Long? = null,
+ val readyAt: Long? = null,
+ val warningCount: Int = 0
+)
+
+enum class StalkerIndexState {
+ DISABLED,
+ QUEUED,
+ RUNNING,
+ RETRY_WAIT,
+ PARTIAL,
+ COMPLETE,
+ TRUNCATED,
+ FAILED
+}
+
+enum class CatalogCompleteness {
+ COMPLETE,
+ PARTIAL,
+ INDEXING,
+ TRUNCATED
+}
+
+enum class StalkerRequestPriority {
+ OPEN_CATEGORY,
+ VISIBLE_PREVIEW,
+ EPG,
+ BACKGROUND_INDEX
+}
+
enum class GuideSourcePolicy {
AUTO,
EXTERNAL_ONLY,
@@ -125,6 +194,180 @@ enum class StalkerMagPreset {
MINISTRA_MODERN
}
+/** User intent. AUTO may select either protocol, but never mixes their session state. */
+enum class StalkerProtocolPreference {
+ AUTO,
+ CLASSIC_MAG,
+ MINISTRA_API_V3
+}
+
+enum class StalkerProtocolFamily {
+ CLASSIC_MAG,
+ MINISTRA_API_V3
+}
+
+/**
+ * Persisted transport decision for a single Stalker provider.
+ *
+ * AUTO_STRICT never relaxes platform TLS checks and never sends provider identity over HTTP.
+ * User-accepted modes are valid only for the exact [StalkerTransportGrant.origin] stored with
+ * the provider.
+ */
+enum class StalkerTransportMode {
+ AUTO_STRICT,
+ VERIFIED_HTTPS,
+ USER_ACCEPTED_UNVERIFIED_HTTPS,
+ USER_ACCEPTED_HTTP
+}
+
+data class StalkerTransportOrigin(
+ val scheme: String,
+ val host: String,
+ val port: Int
+) {
+ val authority: String
+ get() = "$scheme://${host.lowercase()}:$port"
+}
+
+data class StalkerTransportGrant(
+ val mode: StalkerTransportMode,
+ val origin: StalkerTransportOrigin,
+ /** Base64 SHA-256 of SubjectPublicKeyInfo; required for accepted unverified HTTPS. */
+ val spkiSha256: String? = null,
+ val consentedAt: Long
+)
+
+enum class StalkerTransportChallengeReason {
+ INVALID_TLS,
+ CLEARTEXT_HTTP,
+ ORIGIN_CHANGED
+}
+
+data class StalkerTransportChallenge(
+ val reason: StalkerTransportChallengeReason,
+ val origin: StalkerTransportOrigin,
+ val displayHost: String,
+ /** Public key fingerprint proposed for an unverified HTTPS grant. */
+ val proposedSpkiSha256: String? = null,
+ val detailCode: String? = null
+) {
+ fun acceptedGrant(now: Long = System.currentTimeMillis()): StalkerTransportGrant =
+ StalkerTransportGrant(
+ mode = when (reason) {
+ StalkerTransportChallengeReason.INVALID_TLS ->
+ StalkerTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS
+ StalkerTransportChallengeReason.CLEARTEXT_HTTP ->
+ StalkerTransportMode.USER_ACCEPTED_HTTP
+ StalkerTransportChallengeReason.ORIGIN_CHANGED ->
+ if (origin.scheme.equals("https", ignoreCase = true)) {
+ StalkerTransportMode.VERIFIED_HTTPS
+ } else {
+ StalkerTransportMode.USER_ACCEPTED_HTTP
+ }
+ },
+ origin = origin,
+ spkiSha256 = proposedSpkiSha256,
+ consentedAt = now
+ )
+}
+
+class StalkerTransportConsentRequiredException(
+ val challenge: StalkerTransportChallenge
+) : Exception("Transport consent is required for ${challenge.displayHost}.")
+
+enum class CapabilityState {
+ SUPPORTED,
+ UNSUPPORTED,
+ RESTRICTED,
+ EMPTY,
+ INCONCLUSIVE,
+ NOT_PROBED
+}
+
+data class DiscoveryObservation(
+ val stage: String,
+ val code: String,
+ val scope: String,
+ val elapsedMillis: Long,
+ val attempt: Int
+)
+
+data class DiscoveryAttemptKey(
+ val origin: String,
+ val endpoint: String,
+ val authMode: StalkerAuthMode,
+ val profileId: String,
+ val recipe: StalkerBootstrapRecipe,
+ val headerPolicyHash: String,
+ val cookiePolicy: StalkerCookieMode,
+ val transportGeneration: Long
+)
+
+data class DiscoveryBudget(
+ val maxElapsedMillis: Long = 75_000L,
+ val maxRequests: Int = 24,
+ val maxEndpointCandidates: Int = 8,
+ val maxIdentityProfiles: Int = 6,
+ val maxFreshSessions: Int = 2,
+ val maxRedirectsPerChain: Int = 5,
+ val maxLiveCategorySamples: Int = 8
+)
+
+data class StalkerConnectionFailure(
+ val stage: String,
+ val code: String,
+ val retryable: Boolean,
+ val safeMessage: String
+)
+
+enum class StalkerDiscoveryStage {
+ NORMALIZING,
+ TRANSPORT,
+ ENDPOINT,
+ AUTHENTICATION,
+ LIVE_READINESS,
+ CAPABILITIES,
+ COMMITTING
+}
+
+data class StalkerDiscoveryProgress(
+ val stage: StalkerDiscoveryStage,
+ val attempt: Int,
+ val limit: Int,
+ val elapsedMillis: Long,
+ val latestObservation: DiscoveryObservation? = null,
+ val canCancel: Boolean = true
+)
+
+data class StalkerDiscoveryResult(
+ val normalizedPortal: String,
+ val workingEndpoint: String,
+ val protocolFamily: StalkerProtocolFamily,
+ val identityProfileId: String,
+ val effectiveAuthMode: StalkerAuthMode,
+ val transportGrant: StalkerTransportGrant?,
+ val capabilities: Map<String, CapabilityState>,
+ val observations: List<DiscoveryObservation>,
+ val warnings: List<String>
+)
+
+enum class StalkerProfileVerification {
+ VERIFIED,
+ EXPERIMENTAL,
+ CUSTOM,
+ UNVERIFIED
+}
+
+/** Stable persistence IDs. Model names and enum ordinals are deliberately not persisted as identity. */
+object StalkerCompatibilityProfileIds {
+ const val AUTO = "auto"
+ const val CLASSIC_MAG250_GENERIC = "classic.mag250.generic"
+ const val CLASSIC_MAG250_LEGACY = "classic.mag250.legacy"
+ const val CLASSIC_MAG254_STRICT = "classic.mag254.strict"
+ const val CLASSIC_MAG322_MODERN = "classic.mag322.modern"
+ const val CUSTOM = "custom"
+}
+
enum class StalkerBootstrapRecipe {
GENERIC_SAFE,
LEGACY_MAG,
@@ -172,3 +415,13 @@ class ProviderSavedWithSyncErrorException(
message: String,
cause: Throwable? = null
) : Exception(message, cause)
+
+/**
+ * Authentication and the selected classic-MAG identity succeeded, but the bounded Live
+ * readiness check ended on transient or otherwise inconclusive evidence.
+ */
+class StalkerReadinessInconclusiveException(
+ val evidenceCode: String,
+ message: String,
+ cause: Throwable? = null
+) : Exception(message, cause)
diff --git a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt
index 97972ce5..c76f27c5 100644
--- a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt
@@ -7,6 +7,11 @@ data class StreamInfo(
val title: String? = null,
val headers: Map<String, String> = emptyMap(),
val userAgent: String? = null,
+ /**
+ * Provider-scoped transport decision. The legacy Boolean remains only for existing
+ * non-Stalker compatibility paths.
+ */
+ val playbackTransportPolicy: PlaybackTransportPolicy? = null,
val allowInvalidSsl: Boolean = false,
val proxyHost: String = "",
val proxyPort: Int? = null,
@@ -23,6 +28,27 @@ data class StreamInfo(
}
}
+enum class PlaybackTransportMode {
+ STRICT,
+ USER_ACCEPTED_UNVERIFIED_HTTPS,
+ USER_ACCEPTED_HTTP
+}
+
+data class PlaybackTransportPolicy(
+ val mode: PlaybackTransportMode,
+ val origin: StalkerTransportOrigin,
+ /** Base64 SHA-256 of the approved SubjectPublicKeyInfo. */
+ val spkiSha256: String? = null
+) {
+ init {
+ if (mode == PlaybackTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS) {
+ require(!spkiSha256.isNullOrBlank()) {
+ "Accepted unverified HTTPS playback requires an SPKI fingerprint"
+ }
+ }
+ }
+}
+
data class DrmInfo(
val scheme: DrmScheme,
val licenseUrl: String,
diff --git a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
index 546b0967..915c5990 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/ProviderRepository.kt
@@ -9,6 +9,10 @@ import com.streamvault.domain.model.ProviderEpgSyncMode
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportGrant
import kotlinx.coroutines.flow.Flow
data class LiveStreamProgramRequest(
@@ -68,7 +72,13 @@ interface ProviderRepository {
deviceId2: String = "",
signature: String = "",
stalkerAdvancedOptionsJson: String = "",
+ protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ transportGrant: StalkerTransportGrant? = null,
+ saveWithoutVerification: Boolean = false,
+ repairConnection: Boolean = false,
+ requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,
+ catalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,
guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,
channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,
onProgress: ((String) -> Unit)? = null,
@@ -96,6 +106,8 @@ interface ProviderRepository {
epgSyncModeOverride: ProviderEpgSyncMode? = null,
onProgress: ((String) -> Unit)? = null
): Result<Unit>
+ suspend fun buildStalkerSearchIndexOnce(providerId: Long): Result<Unit> =
+ Result.error("Complete Stalker indexing is unavailable")
suspend fun getProgramsForLiveStream(
providerId: Long,
streamId: Long,
diff --git a/domain/src/main/java/com/streamvault/domain/repository/SearchRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/SearchRepository.kt
index 5f624a82..a867980b 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/SearchRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/SearchRepository.kt
@@ -1,6 +1,7 @@
package com.streamvault.domain.repository
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.CatalogCompleteness
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Series
import kotlinx.coroutines.flow.Flow
@@ -8,7 +9,8 @@ import kotlinx.coroutines.flow.Flow
data class SearchRepositoryResult(
val channels: List<Channel> = emptyList(),
val movies: List<Movie> = emptyList(),
- val series: List<Series> = emptyList()
+ val series: List<Series> = emptyList(),
+ val catalogCompleteness: CatalogCompleteness = CatalogCompleteness.COMPLETE
)
interface SearchRepository {
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt b/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt
index 113826fc..41b18413 100644
--- a/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt
+++ b/domain/src/main/java/com/streamvault/domain/usecase/SearchContent.kt
@@ -2,6 +2,7 @@ package com.streamvault.domain.usecase
import com.streamvault.domain.manager.ProviderSyncStateReader
import com.streamvault.domain.model.Channel
+import com.streamvault.domain.model.CatalogCompleteness
import com.streamvault.domain.model.Movie
import com.streamvault.domain.model.Series
import com.streamvault.domain.model.SyncState
@@ -30,7 +31,8 @@ data class SearchContentResult(
val channels: List<Channel> = emptyList(),
val movies: List<Movie> = emptyList(),
val series: List<Series> = emptyList(),
- val isPartialResult: Boolean = false
+ val isPartialResult: Boolean = false,
+ val catalogCompleteness: CatalogCompleteness = CatalogCompleteness.COMPLETE
)
class SearchContent @Inject constructor(
@@ -68,7 +70,13 @@ class SearchContent @Inject constructor(
channels = result.channels,
movies = result.movies,
series = result.series,
- isPartialResult = searchDegraded || indexingActive || indexWorkActive
+ isPartialResult = searchDegraded || indexingActive || indexWorkActive ||
+ result.catalogCompleteness != CatalogCompleteness.COMPLETE,
+ catalogCompleteness = when {
+ searchDegraded -> CatalogCompleteness.PARTIAL
+ indexingActive || indexWorkActive -> CatalogCompleteness.INDEXING
+ else -> result.catalogCompleteness
+ }
)
}
}
diff --git a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
index fb909b0d..27d36d37 100644
--- a/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
+++ b/domain/src/main/java/com/streamvault/domain/usecase/ValidateAndAddProvider.kt
@@ -9,6 +9,13 @@ import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.ProviderSavedWithSyncErrorException
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerReadinessInconclusiveException
+import com.streamvault.domain.model.StalkerTransportChallenge
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportConsentRequiredException
import com.streamvault.domain.repository.ProviderRepository
import java.net.URI
import java.net.URLDecoder
@@ -59,7 +66,13 @@ data class StalkerProviderSetupCommand(
val deviceId2: String = "",
val signature: String = "",
val stalkerAdvancedOptionsJson: String = "",
+ val protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ val transportGrant: StalkerTransportGrant? = null,
+ val saveWithoutVerification: Boolean = false,
+ val repairConnection: Boolean = false,
+ val requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
val epgSyncMode: ProviderEpgSyncMode = ProviderEpgSyncMode.BACKGROUND,
+ val catalogMode: StalkerCatalogMode = StalkerCatalogMode.ON_DEMAND,
val guideSourcePolicy: GuideSourcePolicy = GuideSourcePolicy.AUTO,
val channelLogoSourcePolicy: ChannelLogoSourcePolicy = ChannelLogoSourcePolicy.SUPPLIER_PREFERRED,
val existingProviderId: Long? = null
@@ -83,6 +96,12 @@ sealed class ValidateAndAddProviderResult {
data class Success(val provider: Provider) : ValidateAndAddProviderResult()
data class SavedWithWarning(val provider: Provider, val warning: String) : ValidateAndAddProviderResult()
data class ValidationError(val message: String) : ValidateAndAddProviderResult()
+ data class TransportConsentRequired(
+ val challenge: StalkerTransportChallenge
+ ) : ValidateAndAddProviderResult()
+ data class VerificationInconclusive(
+ val message: String
+ ) : ValidateAndAddProviderResult()
data class Error(val message: String, val exception: Throwable? = null) : ValidateAndAddProviderResult()
}
@@ -304,7 +323,13 @@ class ValidateAndAddProvider @Inject constructor(
deviceId2 = validated.data.deviceId2,
signature = validated.data.signature,
stalkerAdvancedOptionsJson = validated.data.stalkerAdvancedOptionsJson,
+ protocolPreference = command.protocolPreference,
+ transportGrant = command.transportGrant,
+ saveWithoutVerification = command.saveWithoutVerification,
+ repairConnection = command.repairConnection,
+ requestedProfileId = command.requestedProfileId,
epgSyncMode = command.epgSyncMode,
+ catalogMode = command.catalogMode,
guideSourcePolicy = command.guideSourcePolicy,
channelLogoSourcePolicy = command.channelLogoSourcePolicy,
onProgress = onProgress,
@@ -370,14 +395,33 @@ class ValidateAndAddProvider @Inject constructor(
private fun Result<Provider>.toUseCaseResult(): ValidateAndAddProviderResult = when (this) {
is Result.Success -> ValidateAndAddProviderResult.Success(data)
is Result.Error -> {
- val savedWithWarning = exception as? ProviderSavedWithSyncErrorException
- if (savedWithWarning != null) {
- ValidateAndAddProviderResult.SavedWithWarning(
- provider = savedWithWarning.provider,
- warning = savedWithWarning.message ?: message
+ val transportConsent = generateSequence(exception) { it.cause }
+ .filterIsInstance<StalkerTransportConsentRequiredException>()
+ .firstOrNull()
+ if (transportConsent != null) {
+ ValidateAndAddProviderResult.TransportConsentRequired(
+ transportConsent.challenge
)
} else {
- ValidateAndAddProviderResult.Error(message, exception)
+ val readinessInconclusive = generateSequence(exception) { it.cause }
+ .filterIsInstance<StalkerReadinessInconclusiveException>()
+ .firstOrNull()
+ if (readinessInconclusive != null) {
+ ValidateAndAddProviderResult.VerificationInconclusive(
+ readinessInconclusive.message
+ ?: "Authentication succeeded, but Live TV could not be verified."
+ )
+ } else {
+ val savedWithWarning = exception as? ProviderSavedWithSyncErrorException
+ if (savedWithWarning != null) {
+ ValidateAndAddProviderResult.SavedWithWarning(
+ provider = savedWithWarning.provider,
+ warning = savedWithWarning.message ?: message
+ )
+ } else {
+ ValidateAndAddProviderResult.Error(message, exception)
+ }
+ }
}
}
is Result.Loading -> ValidateAndAddProviderResult.Error("Unexpected loading state")
diff --git a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
index 70a06220..b9604d85 100644
--- a/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
+++ b/domain/src/test/java/com/streamvault/domain/usecase/SyncProviderTest.kt
@@ -13,6 +13,9 @@ import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerTransportGrant
import com.streamvault.domain.model.SyncState
import com.streamvault.domain.repository.ProviderDeleteProgress
import com.streamvault.domain.repository.ProviderRepository
@@ -163,7 +166,13 @@ private class FakeSyncProviderRepository(
deviceId2: String,
signature: String,
stalkerAdvancedOptionsJson: String,
+ protocolPreference: StalkerProtocolPreference,
+ transportGrant: StalkerTransportGrant?,
+ saveWithoutVerification: Boolean,
+ repairConnection: Boolean,
+ requestedProfileId: String,
epgSyncMode: ProviderEpgSyncMode,
+ catalogMode: StalkerCatalogMode,
guideSourcePolicy: GuideSourcePolicy,
channelLogoSourcePolicy: ChannelLogoSourcePolicy,
onProgress: ((String) -> Unit)?,
diff --git a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt
index 62ffe179..9ced188f 100644
--- a/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt
+++ b/domain/src/test/java/com/streamvault/domain/usecase/ValidateAndAddProviderTest.kt
@@ -19,6 +19,16 @@ import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.ProviderXtreamLiveSyncMode
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.StalkerAuthMode
+import com.streamvault.domain.model.StalkerCatalogMode
+import com.streamvault.domain.model.StalkerCompatibilityProfileIds
+import com.streamvault.domain.model.StalkerProtocolPreference
+import com.streamvault.domain.model.StalkerReadinessInconclusiveException
+import com.streamvault.domain.model.StalkerTransportChallenge
+import com.streamvault.domain.model.StalkerTransportChallengeReason
+import com.streamvault.domain.model.StalkerTransportConsentRequiredException
+import com.streamvault.domain.model.StalkerTransportGrant
+import com.streamvault.domain.model.StalkerTransportMode
+import com.streamvault.domain.model.StalkerTransportOrigin
import com.streamvault.domain.repository.ProviderDeleteProgress
import com.streamvault.domain.repository.ProviderRepository
import kotlinx.coroutines.flow.Flow
@@ -484,6 +494,95 @@ class ValidateAndAddProviderTest {
)
)
}
+
+ @Test
+ fun `maps Stalker transport challenge without retaining credentials in a token`() = runTest {
+ val challenge = StalkerTransportChallenge(
+ reason = StalkerTransportChallengeReason.CLEARTEXT_HTTP,
+ origin = StalkerTransportOrigin("http", "portal.example.com", 80),
+ displayHost = "portal.example.com",
+ detailCode = "CLEARTEXT_REQUIRES_CONSENT"
+ )
+ val repository = FakeProviderRepository().apply {
+ stalkerResult = Result.error(
+ "Transport consent required",
+ StalkerTransportConsentRequiredException(challenge)
+ )
+ }
+ val useCase = ValidateAndAddProvider(
+ providerSetupInputValidator = FakeProviderSetupInputValidator(),
+ providerRepository = repository
+ )
+
+ val result = useCase.loginStalker(
+ StalkerProviderSetupCommand(
+ portalUrl = "http://portal.example.com",
+ macAddress = "00:1A:79:12:34:56",
+ name = "MAG",
+ password = "must-not-be-in-challenge"
+ )
+ )
+
+ assertThat(result).isEqualTo(
+ ValidateAndAddProviderResult.TransportConsentRequired(challenge)
+ )
+ val consentResult = result as ValidateAndAddProviderResult.TransportConsentRequired
+ assertThat(consentResult.challenge.toString()).doesNotContain("must-not-be-in-challenge")
+ }
+
+ @Test
+ fun `maps authenticated but inconclusive Live readiness to explicit save choice`() = runTest {
+ val repository = FakeProviderRepository().apply {
+ stalkerResult = Result.error(
+ "Live readiness inconclusive",
+ StalkerReadinessInconclusiveException(
+ evidenceCode = "LIVE_BUDGET_EXHAUSTED",
+ message = "Authentication succeeded, but Live TV could not be verified."
+ )
+ )
+ }
+ val useCase = ValidateAndAddProvider(
+ providerSetupInputValidator = FakeProviderSetupInputValidator(),
+ providerRepository = repository
+ )
+
+ val result = useCase.loginStalker(
+ StalkerProviderSetupCommand(
+ portalUrl = "https://portal.example.com",
+ macAddress = "00:1A:79:12:34:56",
+ name = "MAG",
+ saveWithoutVerification = true
+ )
+ )
+
+ assertThat(result).isEqualTo(
+ ValidateAndAddProviderResult.VerificationInconclusive(
+ "Authentication succeeded, but Live TV could not be verified."
+ )
+ )
+ assertThat(repository.lastStalkerCall?.saveWithoutVerification).isTrue()
+ }
+
+ @Test
+ fun `passes explicit repair connection permission to repository`() = runTest {
+ val repository = FakeProviderRepository()
+ val useCase = ValidateAndAddProvider(
+ providerSetupInputValidator = FakeProviderSetupInputValidator(),
+ providerRepository = repository
+ )
+
+ useCase.loginStalker(
+ StalkerProviderSetupCommand(
+ portalUrl = "https://portal.example.com",
+ macAddress = "00:1A:79:12:34:56",
+ name = "MAG",
+ existingProviderId = 42L,
+ repairConnection = true
+ )
+ )
+
+ assertThat(repository.lastStalkerCall?.repairConnection).isTrue()
+ }
}
private class FakeProviderSetupInputValidator(
@@ -626,6 +725,11 @@ private data class StalkerCall(
val deviceId2: String = "",
val signature: String = "",
val stalkerAdvancedOptionsJson: String = "",
+ val protocolPreference: StalkerProtocolPreference = StalkerProtocolPreference.AUTO,
+ val transportGrant: StalkerTransportGrant? = null,
+ val saveWithoutVerification: Boolean = false,
+ val repairConnection: Boolean = false,
+ val requestedProfileId: String = StalkerCompatibilityProfileIds.AUTO,
val epgSyncMode: ProviderEpgSyncMode,
val id: Long?
)
@@ -712,7 +816,13 @@ private class FakeProviderRepository : ProviderRepository {
deviceId2: String,
signature: String,
stalkerAdvancedOptionsJson: String,
+ protocolPreference: StalkerProtocolPreference,
+ transportGrant: StalkerTransportGrant?,
+ saveWithoutVerification: Boolean,
+ repairConnection: Boolean,
+ requestedProfileId: String,
epgSyncMode: ProviderEpgSyncMode,
+ catalogMode: StalkerCatalogMode,
guideSourcePolicy: GuideSourcePolicy,
channelLogoSourcePolicy: ChannelLogoSourcePolicy,
onProgress: ((String) -> Unit)?,
@@ -735,6 +845,11 @@ private class FakeProviderRepository : ProviderRepository {
deviceId2 = deviceId2,
signature = signature,
stalkerAdvancedOptionsJson = stalkerAdvancedOptionsJson,
+ protocolPreference = protocolPreference,
+ transportGrant = transportGrant,
+ saveWithoutVerification = saveWithoutVerification,
+ repairConnection = repairConnection,
+ requestedProfileId = requestedProfileId,
epgSyncMode = epgSyncMode,
id = id
)
diff --git a/gradle/libs.versions.toml b/gradle/libs.versions.toml
index a941d875..02521bb1 100644
--- a/gradle/libs.versions.toml
+++ b/gradle/libs.versions.toml
@@ -82,6 +82,8 @@ retrofit = { group = "com.squareup.retrofit2", name = "retrofit", version.ref =
retrofit-gson = { group = "com.squareup.retrofit2", name = "converter-gson", version.ref = "retrofit" }
okhttp = { group = "com.squareup.okhttp3", name = "okhttp", version.ref = "okhttp" }
okhttp-logging = { group = "com.squareup.okhttp3", name = "logging-interceptor", version.ref = "okhttp" }
+okhttp-mockwebserver = { group = "com.squareup.okhttp3", name = "mockwebserver", version.ref = "okhttp" }
+okhttp-tls = { group = "com.squareup.okhttp3", name = "okhttp-tls", version.ref = "okhttp" }
gson = { group = "com.google.code.gson", name = "gson", version.ref = "gson" }
zxing-core = { group = "com.google.zxing", name = "core", version.ref = "zxing" }
kotlinx-serialization-json = { group = "org.jetbrains.kotlinx", name = "kotlinx-serialization-json", version.ref = "kotlinx-serialization" }
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
index 39db6afc..99fa9d0f 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
@@ -7,6 +7,7 @@ import androidx.media3.datasource.DefaultDataSource
import androidx.media3.datasource.DataSource
import androidx.media3.datasource.okhttp.OkHttpDataSource
import com.streamvault.domain.model.VodHttpProtocolMode
+import com.streamvault.domain.model.PlaybackTransportPolicy
import com.streamvault.domain.model.StreamInfo
import java.net.InetSocketAddress
import java.net.Proxy
@@ -33,6 +34,7 @@ class PlayerDataSourceFactoryProvider(
val profile: PlayerTimeoutProfile,
val forceHttp1: Boolean,
val port: Int,
+ val transportPolicy: PlaybackTransportPolicy?,
val allowInvalidSsl: Boolean,
val proxyHost: String,
val proxyPort: Int?
@@ -62,15 +64,20 @@ class PlayerDataSourceFactoryProvider(
profile = profile,
forceHttp1 = forceHttp1,
port = port,
+ transportPolicy = streamInfo.playbackTransportPolicy,
allowInvalidSsl = streamInfo.allowInvalidSsl,
proxyHost = streamInfo.proxyHost.trim(),
proxyPort = streamInfo.proxyPort
)
val client = clientsByKey.computeIfAbsent(clientKey) {
- val builder = if (streamInfo.allowInvalidSsl) {
- baseClient.newBuilder().applyUnsafeTlsBypass()
- } else {
- baseClient.newBuilder()
+ val transportPolicy = streamInfo.playbackTransportPolicy
+ val builder = when {
+ transportPolicy != null ->
+ baseClient.newBuilder()
+ .applyPlaybackTransportPolicy(transportPolicy)
+ streamInfo.allowInvalidSsl ->
+ baseClient.newBuilder().applyUnsafeTlsBypass()
+ else -> baseClient.newBuilder()
}
builder
.addInterceptor(StalkerPlaybackRequestLoggingInterceptor)
diff --git a/player/src/main/java/com/streamvault/player/playback/UnsafeTlsSupport.kt b/player/src/main/java/com/streamvault/player/playback/UnsafeTlsSupport.kt
index b6409cae..07bcdf1d 100644
--- a/player/src/main/java/com/streamvault/player/playback/UnsafeTlsSupport.kt
+++ b/player/src/main/java/com/streamvault/player/playback/UnsafeTlsSupport.kt
@@ -1,7 +1,13 @@
package com.streamvault.player.playback
+import com.streamvault.domain.model.PlaybackTransportMode
+import com.streamvault.domain.model.PlaybackTransportPolicy
+import java.io.IOException
+import java.security.MessageDigest
import java.security.SecureRandom
+import java.security.cert.CertificateException
import java.security.cert.X509Certificate
+import java.util.Base64
import javax.net.ssl.HostnameVerifier
import javax.net.ssl.SSLContext
import javax.net.ssl.X509TrustManager
@@ -19,3 +25,64 @@ fun OkHttpClient.Builder.applyUnsafeTlsBypass(): OkHttpClient.Builder {
return sslSocketFactory(sslContext.socketFactory, trustAllManager)
.hostnameVerifier(HostnameVerifier { _, _ -> true })
}
+
+/**
+ * Applies a user-approved Stalker transport decision to one exact playback origin.
+ *
+ * Unlike [applyUnsafeTlsBypass], this cannot trust another provider, host, port, or public key.
+ */
+fun OkHttpClient.Builder.applyPlaybackTransportPolicy(
+ policy: PlaybackTransportPolicy
+): OkHttpClient.Builder {
+ addNetworkInterceptor { chain ->
+ val requestOrigin = chain.request().url
+ val expected = policy.origin
+ if (!requestOrigin.scheme.equals(expected.scheme, ignoreCase = true) ||
+ !requestOrigin.host.equals(expected.host, ignoreCase = true) ||
+ requestOrigin.port != expected.port
+ ) {
+ throw IOException("Playback transport approval does not cover the redirected origin.")
+ }
+ chain.proceed(chain.request())
+ }
+ if (policy.mode != PlaybackTransportMode.USER_ACCEPTED_UNVERIFIED_HTTPS) {
+ return this
+ }
+
+ val expectedPin = requireNotNull(policy.spkiSha256).trim()
+ val trustManager = object : X509TrustManager {
+ override fun checkClientTrusted(
+ chain: Array<out X509Certificate>?,
+ authType: String?
+ ) = Unit
+
+ override fun checkServerTrusted(
+ chain: Array<out X509Certificate>?,
+ authType: String?
+ ) {
+ val leaf = chain?.firstOrNull()
+ ?: throw CertificateException("Playback server did not present a certificate.")
+ if (leaf.playbackSpkiSha256() != expectedPin) {
+ throw CertificateException("Playback server public key changed.")
+ }
+ }
+
+ override fun getAcceptedIssuers(): Array<X509Certificate> = emptyArray()
+ }
+ val sslContext = SSLContext.getInstance("TLS").apply {
+ init(null, arrayOf(trustManager), SecureRandom())
+ }
+ return sslSocketFactory(sslContext.socketFactory, trustManager)
+ .hostnameVerifier { hostname, session ->
+ hostname.equals(policy.origin.host, ignoreCase = true) &&
+ runCatching {
+ (session.peerCertificates.firstOrNull() as? X509Certificate)
+ ?.playbackSpkiSha256() == expectedPin
+ }.getOrDefault(false)
+ }
+}
+
+private fun X509Certificate.playbackSpkiSha256(): String =
+ "sha256/" + Base64.getEncoder().encodeToString(
+ MessageDigest.getInstance("SHA-256").digest(publicKey.encoded)
+ )
diff --git a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt
index afb44fae..e69b059c 100644
--- a/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt
+++ b/player/src/main/java/com/streamvault/player/timeshift/LiveTimeshiftManager.kt
@@ -7,6 +7,7 @@ import com.streamvault.domain.model.TimeshiftBackendPreference
import com.streamvault.domain.model.StreamInfo
import com.streamvault.domain.model.StreamType
import com.streamvault.player.playback.applyUnsafeTlsBypass
+import com.streamvault.player.playback.applyPlaybackTransportPolicy
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.ByteArrayOutputStream
import java.io.File
@@ -366,17 +367,30 @@ internal class DefaultLiveTimeshiftManager @Inject constructor(
private fun httpClientFor(streamInfo: StreamInfo): OkHttpClient {
val proxy = streamInfo.httpProxy()
- if (proxy == null) {
+ if (proxy == null && streamInfo.playbackTransportPolicy == null) {
return if (streamInfo.allowInvalidSsl) unsafeOkHttpClient else okHttpClient
}
- val key = "${streamInfo.allowInvalidSsl}:${streamInfo.proxyHost.trim()}:${streamInfo.proxyPort}"
+ val key = buildString {
+ append(streamInfo.playbackTransportPolicy)
+ append(':')
+ append(streamInfo.allowInvalidSsl)
+ append(':')
+ append(streamInfo.proxyHost.trim())
+ append(':')
+ append(streamInfo.proxyPort)
+ }
return proxiedClients.computeIfAbsent(key) {
- val builder = if (streamInfo.allowInvalidSsl) {
- okHttpClient.newBuilder().applyUnsafeTlsBypass()
- } else {
- okHttpClient.newBuilder()
+ val transportPolicy = streamInfo.playbackTransportPolicy
+ val builder = when {
+ transportPolicy != null ->
+ okHttpClient.newBuilder()
+ .applyPlaybackTransportPolicy(transportPolicy)
+ streamInfo.allowInvalidSsl ->
+ okHttpClient.newBuilder().applyUnsafeTlsBypass()
+ else -> okHttpClient.newBuilder()
}
- builder.proxy(proxy).build()
+ proxy?.let(builder::proxy)
+ builder.build()
}
}
diff --git a/tools/stalker-connected-validation.ps1 b/tools/stalker-connected-validation.ps1
new file mode 100644
index 00000000..3017e779
--- /dev/null
+++ b/tools/stalker-connected-validation.ps1
@@ -0,0 +1,72 @@
+param(
+ [Parameter(Mandatory = $true)] [string] $ChannelName,
+ [string] $OutputDirectory = 'build/stalker-validation',
+ [int] $ScreenshotCount = 61,
+ [int] $IntervalSeconds = 2,
+ [switch] $RunMigrationTest
+)
+
+$ErrorActionPreference = 'Stop'
+$root = (Resolve-Path (Join-Path $PSScriptRoot '..')).Path
+$sdkLine = Get-Content (Join-Path $root 'local.properties') | Where-Object { $_ -like 'sdk.dir=*' } | Select-Object -First 1
+if (-not $sdkLine) { throw 'local.properties does not define sdk.dir.' }
+$sdkDirectory = $sdkLine.Substring(8) -replace '\\:', ':' -replace '\\\\', '\'
+$adb = Join-Path $sdkDirectory 'platform-tools/adb.exe'
+if (-not (Test-Path -LiteralPath $adb)) { throw "adb was not found at $adb" }
+if (-not (& $adb devices | Select-String "`tdevice$")) { throw 'No attached Android device or emulator is ready.' }
+
+& $adb shell cmd window set-ignore-orientation-request true | Out-Null
+& $adb shell cmd window user-rotation lock 3 | Out-Null
+$orientation = (& $adb shell dumpsys window displays | Select-String 'cur=|mRotation=|mUserRotationMode|mUserRotation=|mCurrentRotation|mDisplayRotation|ignoreOrientationRequest' | ForEach-Object Line) -join "`n"
+$required = @('cur=2340x1080 app=2340x1080', 'ROTATION_270', 'mRotation=3', 'USER_ROTATION_LOCKED', 'ignoreOrientationRequest=true')
+foreach ($value in $required) {
+ if ($orientation -notmatch [Regex]::Escape($value)) { throw "Orientation validation failed: missing '$value'.`n$orientation" }
+}
+
+if ($RunMigrationTest) {
+ Push-Location $root
+ try {
+ & .\gradlew.bat :data:connectedDebugAndroidTest '-Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StreamVaultDatabaseMigrationTest#migrate62To63_addsOnDemandCatalogAndDedicatedStalkerState'
+ if ($LASTEXITCODE -ne 0) { throw 'Room 62 -> 63 connected migration test failed.' }
+ } finally {
+ Pop-Location
+ }
+}
+
+$safeChannel = ($ChannelName -replace '[^A-Za-z0-9._-]', '_')
+$runDirectory = Join-Path $root (Join-Path $OutputDirectory $safeChannel)
+New-Item -ItemType Directory -Force -Path $runDirectory | Out-Null
+
+for ($index = 0; $index -lt $ScreenshotCount; $index++) {
+ $file = Join-Path $runDirectory ('frame_{0:d3}.png' -f $index)
+ $quotedAdb = '"' + $adb + '"'
+ $quotedFile = '"' + $file + '"'
+ & cmd.exe /d /c "$quotedAdb exec-out screencap -p > $quotedFile"
+ if ($LASTEXITCODE -ne 0) { throw "Screenshot capture failed at frame $index" }
+ if ($index -lt ($ScreenshotCount - 1)) { Start-Sleep -Seconds $IntervalSeconds }
+}
+
+$hashes = Get-ChildItem -LiteralPath $runDirectory -Filter 'frame_*.png' | Get-FileHash -Algorithm SHA256
+$uniqueHashes = @($hashes.Hash | Sort-Object -Unique).Count
+$mediaSession = (& $adb shell dumpsys media_session | Select-String 'package=com.streamvault.app|state=PlaybackState|error=' | ForEach-Object Line) -join "`n"
+
+$safeLogLines = & $adb logcat -d -v time | Select-String 'fatal-error|live-recovery selected|live-recovery no-candidate|prepare resolvedStreamType=MPEG_TS_LIVE|source-malformed live-ts-fallback|Player stuck|state=ERROR|retry category=|first-frame-success|prepare resolvedStreamType=HLS|read-progress streamType=HLS'
+$sanitizedLog = $safeLogLines -replace 'https?://\S+', '<url-redacted>' -replace '(?i)(token|cookie|signature|authorization|mac)=?\S*', '$1=<redacted>' -replace '(?i)([0-9A-F]{2}:){5}[0-9A-F]{2}', '<mac-redacted>'
+$sanitizedLog | Set-Content -LiteralPath (Join-Path $runDirectory 'sanitized-player.log') -Encoding UTF8
+
+$failurePatterns = 'fatal-error|live-recovery no-candidate|prepare resolvedStreamType=MPEG_TS_LIVE|source-malformed live-ts-fallback|Player stuck|state=ERROR'
+$failures = @($sanitizedLog | Select-String $failurePatterns)
+$report = [pscustomobject]@{
+ channel = $ChannelName
+ screenshotCount = $ScreenshotCount
+ intervalSeconds = $IntervalSeconds
+ uniqueHashCount = $uniqueHashes
+ mediaSessionPlaying = $mediaSession -match 'state=PlaybackState.*PLAYING|state=3'
+ mediaSessionErrorNull = $mediaSession -match 'error=null'
+ fatalFindingCount = $failures.Count
+ orientation = $orientation
+ passed = ($uniqueHashes -gt 1 -and $mediaSession -match 'state=PlaybackState.*PLAYING|state=3' -and $mediaSession -match 'error=null' -and $failures.Count -eq 0)
+}
+$report | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath (Join-Path $runDirectory 'report.json') -Encoding UTF8
+$report | Format-List
+if (-not $report.passed) { exit 2 }
diff --git a/tools/stalker-trace-compare.ps1 b/tools/stalker-trace-compare.ps1
new file mode 100644
index 00000000..bb584439
--- /dev/null
+++ b/tools/stalker-trace-compare.ps1
@@ -0,0 +1,88 @@
+param(
+ [Parameter(Mandatory = $true)] [string] $ReferenceHar,
+ [Parameter(Mandatory = $true)] [string] $StreamVaultHar,
+ [Parameter(Mandatory = $true)] [string] $OutputPath
+)
+
+$ErrorActionPreference = 'Stop'
+
+function Get-SafeLabel([string] $Value) {
+ $safe = ($Value.ToUpperInvariant() -replace '[^A-Z0-9_-]', '')
+ if ([string]::IsNullOrWhiteSpace($safe)) { return 'UNKNOWN' }
+ return $safe.Substring(0, [Math]::Min(40, $safe.Length))
+}
+
+function Get-EndpointFamily([Uri] $Uri) {
+ if ($Uri.AbsolutePath.EndsWith('/portal.php', [StringComparison]::OrdinalIgnoreCase)) { return 'PORTAL_PHP' }
+ if ($Uri.AbsolutePath.EndsWith('/server/load.php', [StringComparison]::OrdinalIgnoreCase)) { return 'SERVER_LOAD' }
+ return 'OTHER'
+}
+
+function Read-SanitizedTrace([string] $Path) {
+ $resolved = (Resolve-Path -LiteralPath $Path).Path
+ $har = Get-Content -LiteralPath $resolved -Raw | ConvertFrom-Json
+ $rows = foreach ($entry in $har.log.entries) {
+ $uri = [Uri]$entry.request.url
+ $query = [System.Web.HttpUtility]::ParseQueryString($uri.Query)
+ $action = Get-SafeLabel $query['action']
+ if ($action -eq 'UNKNOWN') { continue }
+ $started = [DateTimeOffset]::Parse($entry.startedDateTime)
+ $duration = [Math]::Max(0, [double]$entry.time)
+ $bytes = [Math]::Max(0, [long]($entry.response.bodySize))
+ if ($bytes -eq 0) { $bytes = [Math]::Max(0, [long]($entry.response.content.size)) }
+ [pscustomobject]@{
+ action = $action
+ type = Get-SafeLabel $query['type']
+ endpointFamily = Get-EndpointFamily $uri
+ startedMs = $started.ToUnixTimeMilliseconds()
+ durationMs = [Math]::Round($duration, 2)
+ responseBytes = $bytes
+ }
+ }
+ return @($rows | Sort-Object startedMs)
+}
+
+function Measure-MaxConcurrency($Rows) {
+ $events = foreach ($row in $Rows) {
+ [pscustomobject]@{ at = [double]$row.startedMs; delta = 1 }
+ [pscustomobject]@{ at = [double]$row.startedMs + [double]$row.durationMs; delta = -1 }
+ }
+ $active = 0
+ $maximum = 0
+ foreach ($event in ($events | Sort-Object at, delta)) {
+ $active += $event.delta
+ $maximum = [Math]::Max($maximum, $active)
+ }
+ return $maximum
+}
+
+function Summarize-Trace($Rows) {
+ $first = $Rows | Select-Object -First 1
+ $firstContent = $Rows | Where-Object {
+ $_.action -in @('GET_GENRES', 'GET_ALL_CHANNELS', 'GET_CATEGORIES', 'GET_ORDERED_LIST')
+ } | Select-Object -First 1
+ [pscustomobject]@{
+ requestCount = $Rows.Count
+ responseBytes = [long](($Rows | Measure-Object responseBytes -Sum).Sum)
+ maxConcurrency = Measure-MaxConcurrency $Rows
+ timeToFirstContentMs = if ($first -and $firstContent) { $firstContent.startedMs - $first.startedMs } else { $null }
+ actionSequence = @($Rows | ForEach-Object { "$($_.type):$($_.action):$($_.endpointFamily)" })
+ actionCounts = @($Rows | Group-Object action | Sort-Object Name | ForEach-Object {
+ [pscustomobject]@{ action = $_.Name; count = $_.Count }
+ })
+ }
+}
+
+$reference = Read-SanitizedTrace $ReferenceHar
+$streamVault = Read-SanitizedTrace $StreamVaultHar
+$report = [pscustomobject]@{
+ generatedAtUtc = [DateTimeOffset]::UtcNow.ToString('o')
+ sanitization = 'Hosts, URLs, query values, headers, cookies, tokens, MAC addresses, and credentials are omitted.'
+ reference = Summarize-Trace $reference
+ streamVault = Summarize-Trace $streamVault
+}
+
+$parent = Split-Path -Parent $OutputPath
+if ($parent) { New-Item -ItemType Directory -Force -Path $parent | Out-Null }
+$report | ConvertTo-Json -Depth 8 | Set-Content -LiteralPath $OutputPath -Encoding UTF8
+Write-Host "Sanitized comparison written to $OutputPath"