Skip to content

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

Complete Stremio add-on and torrent support

David Nashash2d275bc1e2ca
diff --git a/README.md b/README.md
index ba100dc1..9eba5aee 100644
--- a/README.md
+++ b/README.md
@@ -53,6 +53,7 @@ Built for Android TV first, StreamVault focuses on the things generic IPTV apps
- Built-in DVR with scheduled recording, background capture, recording playback, and app-managed default storage
- Multi-view split-screen playback for watching multiple channels at once
- Plugin API for creating companion Android APKs that extend providers, playback, Cast URL handling, or configuration flows
+- Native Stremio add-on catalogs, metadata, direct/debrid playback, subtitles, and resume history
- Strong parental controls with PIN-protected categories and automatic adult-category detection
- TV integrations including Watch Next, launcher recommendations, TV input sync, Cast support, external-player handoff, and in-app update delivery
@@ -74,7 +75,7 @@ Built for Android TV first, StreamVault focuses on the things generic IPTV apps
- Designed for Android TV and D-pad navigation first
- Fast channel browsing with large-playlist friendly layouts
- Numeric remote input for direct channel entry
-- Configurable startup landing screen so the app can open Home, Live TV, Movies, Series, Guide, Downloads, Plugins, or Settings first
+- Configurable startup landing screen so the app can open Home, Live TV, Movies, Series, Guide, Downloads, Plugins, Stremio-compatible Add-ons, or Settings first
- Colored remote button remapping with global defaults plus playback and live-browse overrides
- Preview mode while browsing channels
- TV-friendly search and text-entry flows
@@ -151,6 +152,15 @@ Built for Android TV first, StreamVault focuses on the things generic IPTV apps
- Plugin developers can expose provider, playback, Cast URL rewrite, and host-rendered or native configuration capabilities.
- See the [StreamVault Plugin API](docs/PLUGIN_API.md) docs to create compatible plugins.
+### Stremio-compatible Add-ons
+
+- Install Stremio-compatible add-ons from a manifest URL and browse their catalogs from the Extensions area.
+- Resolve metadata, streams, and subtitles across enabled add-ons, including when the catalog and stream come from different add-ons.
+- Play direct and debrid HTTP(S) streams with add-on request headers scoped to the selected media origin.
+- Save progress and resume by resolving a fresh stream when reopening Stremio playback history.
+- Plugins and Stremio-compatible Add-ons are grouped under one Extensions navigation item with separate, focusable tabs.
+- Stremio-compatible Add-ons are open by default. Use Settings → Privacy → Hide Stremio-compatible add-ons to hide them independently of IPTV parental controls.
+
## Quick TV Tips
- Long-press a channel, movie, or series to add it to Favorites or a custom group.
diff --git a/app/src/androidTest/java/com/streamvault/app/ui/V6aProviderPlaybackProbeRuntimeTest.kt b/app/src/androidTest/java/com/streamvault/app/ui/V6aProviderPlaybackProbeRuntimeTest.kt
index ba35d9c6..0fc6a01e 100644
--- a/app/src/androidTest/java/com/streamvault/app/ui/V6aProviderPlaybackProbeRuntimeTest.kt
+++ b/app/src/androidTest/java/com/streamvault/app/ui/V6aProviderPlaybackProbeRuntimeTest.kt
@@ -41,6 +41,9 @@ class V6aProviderPlaybackProbeRuntimeTest {
val ids = requireNotNull(InstrumentationRegistry.getArguments().getString("v6aMovieIds"))
.split(',').map(String::trim).filter(String::isNotEmpty).map(String::toLong)
require(ids.size in 2..4)
+ val holdSeconds = InstrumentationRegistry.getArguments().getString("v6aHoldSeconds")
+ ?.toLongOrNull() ?: 0L
+ require(holdSeconds in 0..300)
val providers = component("providerRepositoryImplProvider") as ProviderRepository
val movies = component("movieRepositoryImplProvider") as MovieRepository
val providerId = providers.getActiveProvider().first()?.id ?: error("No active provider")
@@ -54,11 +57,12 @@ class V6aProviderPlaybackProbeRuntimeTest {
engine.bindRenderView(render!!, com.streamvault.player.PlayerSurfaceResizeMode.FIT)
}
try {
- for (id in ids) {
+ for ((index, id) in ids.withIndex()) {
val movie = movies.getMovie(id) ?: error("Missing movie $id")
val detail = movies.getMovieDetails(providerId, id).getOrNull() ?: movie
val source = movies.getStreamInfo(detail).getOrNull() ?: error("Unresolved movie $id")
val started = SystemClock.elapsedRealtime()
+ var firstFrameReady = false
val main = { action: () -> Unit -> instrumentation.runOnMainSync(action) }
main {
engine.prepare(source.copy(
@@ -73,6 +77,7 @@ class V6aProviderPlaybackProbeRuntimeTest {
engine.playbackState.value != PlaybackState.READY || !engine.isPlaying.value
) delay(100)
}
+ firstFrameReady = true
val stats = engine.playerStats.value
"id=$id,stream=${movie.streamId},name=${detail.name},ext=${detail.containerExtension},duration=${detail.durationSeconds}," +
"codec=${stats.videoCodec},audio=${stats.audioCodec},size=${stats.width}x${stats.height},bitrate=${stats.videoBitrate}," +
@@ -81,6 +86,25 @@ class V6aProviderPlaybackProbeRuntimeTest {
"id=$id,stream=${movie.streamId},name=${detail.name},ext=${detail.containerExtension},error=${error.javaClass.simpleName}:${error.message}"
}
android.util.Log.i("V6aProviderPlayback", result)
+ if (index == 0 && firstFrameReady && holdSeconds > 0L) {
+ val holdStarted = SystemClock.elapsedRealtime()
+ var previousPosition = engine.currentPosition.value
+ while (SystemClock.elapsedRealtime() - holdStarted < holdSeconds * 1_000L) {
+ delay(2_000)
+ val position = engine.currentPosition.value
+ check(engine.playbackState.value == PlaybackState.READY && engine.isPlaying.value) {
+ "Playback became unhealthy during hold: state=${engine.playbackState.value}, playing=${engine.isPlaying.value}"
+ }
+ check(position > previousPosition) {
+ "Playback position stopped advancing during hold: previous=$previousPosition, current=$position"
+ }
+ previousPosition = position
+ android.util.Log.i(
+ "V6aProviderPlayback",
+ "hold id=$id elapsedMs=${SystemClock.elapsedRealtime() - holdStarted} positionMs=$position state=${engine.playbackState.value}"
+ )
+ }
+ }
main { engine.stop() }
SystemClock.sleep(1_000)
}
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 4a627486..98d77a8b 100644
--- a/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/DatabaseModule.kt
@@ -99,4 +99,5 @@ object DatabaseModule {
@Provides fun provideM3uClassificationDao(db: StreamVaultDatabase): M3uClassificationDao = db.m3uClassificationDao()
@Provides fun providePluginProviderOwnershipDao(db: StreamVaultDatabase): PluginProviderOwnershipDao = db.pluginProviderOwnershipDao()
@Provides fun provideStremioAddonDao(db: StreamVaultDatabase): StremioAddonDao = db.stremioAddonDao()
+ @Provides fun provideStremioPlaybackHistoryDao(db: StreamVaultDatabase): StremioPlaybackHistoryDao = db.stremioPlaybackHistoryDao()
}
diff --git a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
index 753b3cb3..628b007d 100644
--- a/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
+++ b/app/src/main/java/com/streamvault/app/di/RepositoryModule.kt
@@ -97,6 +97,9 @@ abstract class RepositoryModule {
@Binds @Singleton
abstract fun bindStremioAddonRepository(impl: StremioAddonRepositoryImpl): StremioAddonRepository
+ @Binds @Singleton
+ abstract fun bindStremioPlaybackHistoryRepository(impl: StremioPlaybackHistoryRepositoryImpl): StremioPlaybackHistoryRepository
+
@Binds @Singleton
abstract fun bindExternalRatingsRepository(impl: ExternalRatingsRepositoryImpl): ExternalRatingsRepository
diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavHost.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavHost.kt
index af24f2de..017bc2d4 100644
--- a/app/src/main/java/com/streamvault/app/navigation/AppNavHost.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavHost.kt
@@ -59,6 +59,7 @@ internal fun AppNavHost(
actions = actions,
startupReady = startupReady,
onStartupNavigationRequested = onStartupNavigationRequested,
+ onTopLevelDestinationRequested = onTopLevelDestinationRequested,
scaffold = appSystemScaffold(onTopLevelDestinationRequested),
)
registerProviderGraph(
@@ -83,7 +84,12 @@ internal fun AppNavHost(
}
)
registerLiveGraph(actions, onTopLevelDestinationRequested)
- registerStremioGraph(scaffold = appStremioScaffold(onTopLevelDestinationRequested))
+ registerStremioGraph(
+ navController = navController,
+ actions = actions,
+ onTopLevelDestinationRequested = onTopLevelDestinationRequested,
+ scaffold = appStremioScaffold(onTopLevelDestinationRequested)
+ )
registerCatalogGraph(
actions = actions,
platformHost = catalogPlatformHost,
diff --git a/app/src/main/java/com/streamvault/app/navigation/AppNavigationAdapters.kt b/app/src/main/java/com/streamvault/app/navigation/AppNavigationAdapters.kt
index e6184eb9..721afd1d 100644
--- a/app/src/main/java/com/streamvault/app/navigation/AppNavigationAdapters.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/AppNavigationAdapters.kt
@@ -25,7 +25,6 @@ internal fun AppTopLevelDestination.toAppRoute(): String = when (this) {
AppTopLevelDestination.DOWNLOADS -> Routes.DOWNLOADS
AppTopLevelDestination.GUIDE -> Routes.EPG
AppTopLevelDestination.SEARCH -> Routes.SEARCH
- AppTopLevelDestination.PLUGINS -> Routes.PLUGINS
- AppTopLevelDestination.ADDONS -> Routes.ADDONS
+ AppTopLevelDestination.EXTENSIONS -> Routes.PLUGINS
AppTopLevelDestination.SETTINGS -> Routes.SETTINGS
}
diff --git a/app/src/main/java/com/streamvault/app/navigation/PlayerNavigationAdapters.kt b/app/src/main/java/com/streamvault/app/navigation/PlayerNavigationAdapters.kt
index e3f1514c..eafcc2f0 100644
--- a/app/src/main/java/com/streamvault/app/navigation/PlayerNavigationAdapters.kt
+++ b/app/src/main/java/com/streamvault/app/navigation/PlayerNavigationAdapters.kt
@@ -2,6 +2,8 @@ package com.streamvault.app.navigation
import com.streamvault.core.navigation.AppDestination
import com.streamvault.core.navigation.PlayerNavigationRequest
+import com.streamvault.core.navigation.StremioPlaybackReference
+import com.streamvault.core.navigation.StremioSubtitlePlaybackSource
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.Episode
import com.streamvault.domain.model.Movie
@@ -26,7 +28,9 @@ internal fun playerNavigationRequest(
seriesId: Long? = null,
seasonNumber: Int? = null,
episodeNumber: Int? = null,
- episodeId: Long? = null
+ episodeId: Long? = null,
+ stremioPlaybackReference: StremioPlaybackReference? = null,
+ stremioInlineSubtitles: List<StremioSubtitlePlaybackSource> = emptyList()
): PlayerNavigationRequest = PlayerNavigationRequest(
streamUrl = streamUrl,
title = title,
@@ -46,7 +50,9 @@ internal fun playerNavigationRequest(
seriesId = seriesId,
seasonNumber = seasonNumber,
episodeNumber = episodeNumber,
- episodeId = episodeId
+ episodeId = episodeId,
+ stremioPlaybackReference = stremioPlaybackReference,
+ stremioInlineSubtitles = stremioInlineSubtitles
)
internal fun Channel.toLivePlayerRequest(
diff --git a/app/src/main/java/com/streamvault/app/playback/AppPlaybackServiceAdapters.kt b/app/src/main/java/com/streamvault/app/playback/AppPlaybackServiceAdapters.kt
index 5fd7d151..83f0e1ac 100644
--- a/app/src/main/java/com/streamvault/app/playback/AppPlaybackServiceAdapters.kt
+++ b/app/src/main/java/com/streamvault/app/playback/AppPlaybackServiceAdapters.kt
@@ -25,6 +25,8 @@ class StreamVaultPluginPlaybackServiceAdapter internal constructor(
override suspend fun prepare(streamInfo: StreamInfo): Result<StreamInfo> =
operations.preparePlaybackStreamInfo(streamInfo)
+ override fun stop(streamInfo: StreamInfo) = operations.stopPlayback(streamInfo)
+
override suspend fun rewrite(request: CastMediaRequest): String? = operations.rewriteCastUrl(request)
}
@@ -58,6 +60,8 @@ class AppPlaybackSurfaceRefreshAdapter internal constructor(
internal interface StreamVaultPluginPlaybackOperations {
suspend fun preparePlaybackStreamInfo(streamInfo: StreamInfo): Result<StreamInfo>
+ fun stopPlayback(streamInfo: StreamInfo) = Unit
+
suspend fun rewriteCastUrl(request: CastMediaRequest): String?
}
@@ -77,6 +81,9 @@ private class StreamVaultPluginPlaybackManager(
override suspend fun preparePlaybackStreamInfo(streamInfo: StreamInfo): Result<StreamInfo> =
pluginManager.preparePlaybackStreamInfo(streamInfo)
+ override fun stopPlayback(streamInfo: StreamInfo) =
+ pluginManager.stopPreparedPlayback(streamInfo)
+
override suspend fun rewriteCastUrl(request: CastMediaRequest): String? =
pluginManager.rewriteCastUrl(request)
}
diff --git a/app/src/main/java/com/streamvault/app/plugins/PluginPlaybackRouting.kt b/app/src/main/java/com/streamvault/app/plugins/PluginPlaybackRouting.kt
index 441513ed..4a7c0c39 100644
--- a/app/src/main/java/com/streamvault/app/plugins/PluginPlaybackRouting.kt
+++ b/app/src/main/java/com/streamvault/app/plugins/PluginPlaybackRouting.kt
@@ -40,3 +40,24 @@ private fun StreamVaultPluginManifest.ownsPlaybackUrl(scheme: String, host: Stri
// Hostless schemes (for example, a custom URI) can be owned by scheme alone.
return host == null || playbackUrlHosts.any { it.equals("*", true) || it.equals(host, true) }
}
+
+internal fun isMagnetPlaybackUrl(url: String): Boolean =
+ url.trimStart().startsWith("magnet:", ignoreCase = true)
+
+internal fun isSafeMagnetPlaybackOutputUrl(url: String): Boolean = runCatching {
+ val uri = URI(url)
+ uri.scheme.equals("http", ignoreCase = true) &&
+ uri.host.equals("127.0.0.1", ignoreCase = true) &&
+ uri.port in 1..65535 &&
+ uri.rawUserInfo == null &&
+ uri.rawFragment == null
+}.getOrDefault(false)
+
+internal const val MAGNET_PLUGIN_REQUIRED_MESSAGE =
+ "Magnet playback requires the StreamVault Torrent plugin. Install and enable it from Extensions > Plugins."
+
+internal const val MAGNET_PLUGIN_UNAVAILABLE_MESSAGE =
+ "No enabled plugin could resolve this magnet link. Install and enable the StreamVault Torrent plugin from Extensions > Plugins."
+
+internal const val MAGNET_PLUGIN_INVALID_OUTPUT_MESSAGE =
+ "The torrent plugin did not return a playable loopback stream."
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 3ad57503..502156eb 100644
--- a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt
+++ b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt
@@ -51,10 +51,13 @@ import com.streamvault.feature.system.api.owner
import dagger.hilt.android.qualifiers.ApplicationContext
import java.io.File
import java.net.URI
+import java.util.concurrent.ConcurrentHashMap
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
@@ -87,6 +90,8 @@ class StreamVaultPluginManager @Inject constructor(
private val okHttpClient: OkHttpClient,
private val json: Json
) : ProviderSourceRegistry {
+ private val playbackCleanupScope = CoroutineScope(SupervisorJob() + Dispatchers.IO)
+ private val preparedPlaybackOwners = ConcurrentHashMap<String, InstalledStreamVaultPlugin>()
private val prefs = context.getSharedPreferences("streamvault_plugins", Context.MODE_PRIVATE)
private val discoveryLock = Any()
private val pluginMutationMutex = Mutex()
@@ -481,10 +486,14 @@ class StreamVaultPluginManager @Inject constructor(
suspend fun preparePlaybackStreamInfo(streamInfo: StreamInfo): Result<StreamInfo> = withContext(Dispatchers.IO) {
val url = streamInfo.url
if (url.isBlank()) return@withContext Result.success(streamInfo)
+ val isMagnet = isMagnetPlaybackUrl(url)
val prepared = withPluginPlaybackDeadline(PLAYBACK_TOTAL_TIMEOUT_MILLIS) {
val plugins = playbackCandidates(
discoverPlugins(), url, StreamVaultPluginContract.CAPABILITY_PLAYBACK_PREPARE
)
+ if (isMagnet && plugins.isEmpty()) {
+ return@withPluginPlaybackDeadline Result.error(MAGNET_PLUGIN_REQUIRED_MESSAGE)
+ }
coroutineScope {
val requests = plugins.associateWith { plugin -> async {
runPluginCallOrNull {
@@ -502,16 +511,45 @@ class StreamVaultPluginManager @Inject constructor(
if (!response.getBoolean(StreamVaultPluginContract.KEY_HANDLED, false)) continue
requests.values.forEach { it.cancel() }
return@coroutineScope if (response.getBoolean(StreamVaultPluginContract.KEY_SUCCESS, false)) {
- Result.success(applyPlaybackPreparationResponse(streamInfo, response))
+ val preparedInfo = applyPlaybackPreparationResponse(streamInfo, response)
+ if (isMagnet && !isSafeMagnetPlaybackOutputUrl(preparedInfo.url)) {
+ Result.error(MAGNET_PLUGIN_INVALID_OUTPUT_MESSAGE)
+ } else {
+ if (isMagnet) preparedPlaybackOwners[preparedInfo.url] = plugin
+ Result.success(preparedInfo)
+ }
} else {
Result.error(response.getString(StreamVaultPluginContract.KEY_MESSAGE).orEmpty()
.ifBlank { "${plugin.displayName} could not prepare playback" })
}
}
- Result.success(streamInfo)
+ if (isMagnet) Result.error(MAGNET_PLUGIN_UNAVAILABLE_MESSAGE)
+ else Result.success(streamInfo)
+ }
+ }
+ prepared ?: if (isMagnet) Result.error(MAGNET_PLUGIN_UNAVAILABLE_MESSAGE)
+ else Result.success(streamInfo)
+ }
+
+ /** Stops a plugin session previously associated with the prepared output URL. */
+ fun stopPreparedPlayback(streamInfo: StreamInfo) {
+ val outputUrl = streamInfo.url
+ val plugin = preparedPlaybackOwners.remove(outputUrl) ?: return
+ playbackCleanupScope.launch {
+ runCatching {
+ withPluginPlaybackDeadline(PLAYBACK_HANDLER_TIMEOUT_MILLIS) {
+ messengerClient.send(
+ packageName = plugin.packageName,
+ serviceClassName = plugin.serviceClassName,
+ what = StreamVaultPluginContract.MSG_STOP_PLAYBACK,
+ data = Bundle().apply {
+ putString(StreamVaultPluginContract.KEY_OUTPUT_URL, outputUrl)
+ },
+ timeoutMillis = PLAYBACK_HANDLER_TIMEOUT_MILLIS
+ )
+ }
}
}
- prepared ?: Result.success(streamInfo)
}
suspend fun rewriteCastUrl(request: CastMediaRequest): String? = withContext(Dispatchers.IO) {
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShellNavigation.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShellNavigation.kt
index 010a7d99..e55c938d 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShellNavigation.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShellNavigation.kt
@@ -18,12 +18,8 @@ import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.runtime.staticCompositionLocalOf
import androidx.compose.ui.Modifier
-import androidx.compose.ui.graphics.Color
-import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.vector.ImageVector
-import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.res.stringResource
-import androidx.compose.ui.unit.dp
import com.streamvault.app.R
import com.streamvault.app.navigation.Routes
import com.streamvault.core.ui.components.shell.AppTopBarCloseAction
@@ -67,7 +63,7 @@ fun AppScreenScaffold(
val closeAppLabel = stringResource(R.string.nav_close_app)
CoreAppScreenScaffold(
- currentDestinationId = currentRoute,
+ currentDestinationId = selectedNavigationDestinationId(currentRoute, navigationDestinations),
destinations = navigationDestinations,
onDestinationSelected = onNavigate,
title = title,
@@ -95,6 +91,18 @@ fun AppScreenScaffold(
)
}
+internal fun selectedNavigationDestinationId(
+ currentRoute: String,
+ destinations: List<UiDestination>
+): String = if (
+ currentRoute.substringBefore('?') == Routes.ADDONS &&
+ destinations.any { destination -> destination.id == Routes.PLUGINS }
+) {
+ Routes.PLUGINS
+} else {
+ currentRoute
+}
+
internal data class AppDestinationItem(
val route: String,
@param:StringRes val labelRes: Int,
@@ -147,40 +155,6 @@ private fun AppTopLevelDestination.toDestinationItem(): AppDestinationItem = whe
AppTopLevelDestination.DOWNLOADS -> AppDestinationItem(Routes.DOWNLOADS, R.string.nav_downloads, Icons.Default.Download)
AppTopLevelDestination.GUIDE -> AppDestinationItem(Routes.EPG, R.string.nav_epg, Icons.Default.Info)
AppTopLevelDestination.SEARCH -> AppDestinationItem(Routes.SEARCH, R.string.search_title, Icons.Default.Search)
- AppTopLevelDestination.PLUGINS -> AppDestinationItem(Routes.PLUGINS, R.string.nav_plugins, PluginBlocksIcon)
- AppTopLevelDestination.ADDONS -> AppDestinationItem(Routes.ADDONS, R.string.nav_addons, Icons.Default.Extension)
+ AppTopLevelDestination.EXTENSIONS -> AppDestinationItem(Routes.PLUGINS, R.string.nav_extensions, Icons.Default.Extension)
AppTopLevelDestination.SETTINGS -> AppDestinationItem(Routes.SETTINGS, R.string.nav_settings, Icons.Default.Settings)
}
-
-private val PluginBlocksIcon: ImageVector
- get() {
- if (_pluginBlocksIcon != null) return _pluginBlocksIcon!!
- _pluginBlocksIcon = ImageVector.Builder(
- name = "PluginBlocks",
- defaultWidth = 24.dp,
- defaultHeight = 24.dp,
- viewportWidth = 24f,
- viewportHeight = 24f
- ).apply {
- path(fill = SolidColor(Color.Black)) {
- moveTo(3f, 4f)
- horizontalLineTo(10f)
- verticalLineTo(11f)
- horizontalLineTo(3f)
- close()
- moveTo(14f, 4f)
- horizontalLineTo(21f)
- verticalLineTo(11f)
- horizontalLineTo(14f)
- close()
- moveTo(8.5f, 13f)
- horizontalLineTo(15.5f)
- verticalLineTo(20f)
- horizontalLineTo(8.5f)
- close()
- }
- }.build()
- return _pluginBlocksIcon!!
- }
-
-private var _pluginBlocksIcon: ImageVector? = null
diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml
index 1b3df26f..113b65c8 100644
--- a/app/src/main/res/values/strings.xml
+++ b/app/src/main/res/values/strings.xml
@@ -10,7 +10,8 @@
<string name="nav_epg">Guide</string>
<string name="nav_settings">Settings</string>
<string name="nav_plugins">Plugins</string>
-<string name="nav_addons">Addons</string>
+ <string name="nav_addons">Stremio-compatible Add-ons</string>
+ <string name="nav_extensions">Extensions</string>
<string name="nav_close_app">Close app</string>
diff --git a/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt b/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt
index fb93f549..baacf0e1 100644
--- a/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt
+++ b/app/src/test/java/com/streamvault/app/navigation/RoutesTest.kt
@@ -164,7 +164,7 @@ class RoutesTest {
assertThat(AppTopLevelDestination.DOWNLOADS.toAppRoute()).isEqualTo(Routes.DOWNLOADS)
assertThat(AppTopLevelDestination.GUIDE.toAppRoute()).isEqualTo(Routes.EPG)
assertThat(AppTopLevelDestination.SEARCH.toAppRoute()).isEqualTo(Routes.SEARCH)
- assertThat(AppTopLevelDestination.PLUGINS.toAppRoute()).isEqualTo(Routes.PLUGINS)
+ assertThat(AppTopLevelDestination.EXTENSIONS.toAppRoute()).isEqualTo(Routes.PLUGINS)
assertThat(AppTopLevelDestination.SETTINGS.toAppRoute()).isEqualTo(Routes.SETTINGS)
}
@@ -191,6 +191,18 @@ class RoutesTest {
)
}
+ @Test
+ fun `extensions top level keeps plugin and addon startup choices available`() {
+ val available = AppTopLevelDestination.availableLandingDestinations(
+ listOf(AppTopLevelDestination.HOME, AppTopLevelDestination.EXTENSIONS, AppTopLevelDestination.SETTINGS)
+ )
+
+ assertThat(available).containsAtLeast(
+ AppLandingDestination.PLUGINS,
+ AppLandingDestination.ADDONS
+ )
+ }
+
@Test
fun `startup player modes fall back when live tv is not visible`() {
val resolved = AppTopLevelDestination.resolveLandingDestination(
diff --git a/app/src/test/java/com/streamvault/app/ui/components/shell/AppShellNavigationTest.kt b/app/src/test/java/com/streamvault/app/ui/components/shell/AppShellNavigationTest.kt
index f4bdc7a1..7ee18cdc 100644
--- a/app/src/test/java/com/streamvault/app/ui/components/shell/AppShellNavigationTest.kt
+++ b/app/src/test/java/com/streamvault/app/ui/components/shell/AppShellNavigationTest.kt
@@ -2,8 +2,11 @@ package com.streamvault.app.ui.components.shell
import com.google.common.truth.Truth.assertThat
import com.streamvault.app.navigation.Routes
+import com.streamvault.core.ui.components.shell.UiDestination
import com.streamvault.domain.model.AppTopLevelDestination
import com.streamvault.domain.model.CatalogLayout
+import androidx.compose.material.icons.Icons
+import androidx.compose.material.icons.filled.Extension
import org.junit.Test
class AppShellNavigationTest {
@@ -25,10 +28,21 @@ class AppShellNavigationTest {
Routes.EPG,
Routes.SEARCH,
Routes.PLUGINS,
- Routes.ADDONS,
Routes.SETTINGS
)
.inOrder()
+ assertThat(result.single { it.route == Routes.PLUGINS }.labelRes)
+ .isEqualTo(com.streamvault.app.R.string.nav_extensions)
+ }
+
+ @Test
+ fun addonsRouteSelectsTheExtensionsNavigationItem() {
+ val destinations = listOf(
+ UiDestination(Routes.PLUGINS, "Extensions", Icons.Default.Extension)
+ )
+
+ assertThat(selectedNavigationDestinationId(Routes.ADDONS, destinations))
+ .isEqualTo(Routes.PLUGINS)
}
@Test
diff --git a/core/navigation/src/main/kotlin/com/streamvault/core/navigation/PlayerNavigationRequest.kt b/core/navigation/src/main/kotlin/com/streamvault/core/navigation/PlayerNavigationRequest.kt
index 91d45a16..141832fd 100644
--- a/core/navigation/src/main/kotlin/com/streamvault/core/navigation/PlayerNavigationRequest.kt
+++ b/core/navigation/src/main/kotlin/com/streamvault/core/navigation/PlayerNavigationRequest.kt
@@ -21,5 +21,8 @@ data class PlayerNavigationRequest(
val seriesId: Long? = null,
val seasonNumber: Int? = null,
val episodeNumber: Int? = null,
- val episodeId: Long? = null
+ val episodeId: Long? = null,
+ val stremioPlaybackReference: StremioPlaybackReference? = null,
+ val stremioMediaRequestHeaders: Map<String, String> = emptyMap(),
+ val stremioInlineSubtitles: List<StremioSubtitlePlaybackSource> = emptyList()
) : Serializable
diff --git a/core/navigation/src/main/kotlin/com/streamvault/core/navigation/StremioPlaybackReference.kt b/core/navigation/src/main/kotlin/com/streamvault/core/navigation/StremioPlaybackReference.kt
new file mode 100644
index 00000000..c62725c2
--- /dev/null
+++ b/core/navigation/src/main/kotlin/com/streamvault/core/navigation/StremioPlaybackReference.kt
@@ -0,0 +1,35 @@
+package com.streamvault.core.navigation
+
+import java.io.Serializable
+
+/** Stable content and addon provenance carried from a Stremio stream choice into the player. */
+data class StremioPlaybackReference(
+ val mediaType: String,
+ val exactVideoId: String,
+ val parentSeriesId: String? = null,
+ val catalogOriginKey: String,
+ val metaOriginKey: String? = null,
+ val streamOriginKey: String,
+ val videoHash: String? = null,
+ val videoSize: Long? = null,
+ val filename: String? = null
+) : Serializable
+
+/** Ephemeral subtitle source passed into the player; never stored in Stremio history. */
+data class StremioSubtitlePlaybackSource(
+ val url: String,
+ val language: String,
+ val id: String? = null
+) : Serializable
+
+data class StremioPlayerHandoff(
+ val streamUrl: String,
+ val title: String,
+ val artworkUrl: String? = null,
+ val contentType: String,
+ val reference: StremioPlaybackReference,
+ /** Ephemeral only; never copied into addon history. */
+ val mediaRequestHeaders: Map<String, String> = emptyMap(),
+ /** Inline subtitle URLs live only for this player handoff and are never persisted. */
+ val inlineSubtitles: List<StremioSubtitlePlaybackSource> = emptyList()
+) : Serializable
diff --git a/core/navigation/src/test/kotlin/com/streamvault/core/navigation/PlayerNavigationRequestTest.kt b/core/navigation/src/test/kotlin/com/streamvault/core/navigation/PlayerNavigationRequestTest.kt
index 9230a11c..f24ce5f4 100644
--- a/core/navigation/src/test/kotlin/com/streamvault/core/navigation/PlayerNavigationRequestTest.kt
+++ b/core/navigation/src/test/kotlin/com/streamvault/core/navigation/PlayerNavigationRequestTest.kt
@@ -19,7 +19,25 @@ class PlayerNavigationRequestTest {
seriesId = 12L,
seasonNumber = 3,
episodeNumber = 4,
- episodeId = 77L
+ episodeId = 77L,
+ stremioPlaybackReference = StremioPlaybackReference(
+ mediaType = "series",
+ exactVideoId = "tt123:custom:episode-id",
+ parentSeriesId = "tt123",
+ catalogOriginKey = "catalog-fingerprint",
+ metaOriginKey = "meta-fingerprint",
+ streamOriginKey = "stream-fingerprint",
+ videoHash = "abc123",
+ videoSize = 1024L,
+ filename = "episode.mkv"
+ ),
+ stremioInlineSubtitles = listOf(
+ StremioSubtitlePlaybackSource(
+ url = "https://subtitles.example.test/episode.srt?token=temporary",
+ language = "eng",
+ id = "inline-eng"
+ )
+ )
)
val bytes = ByteArrayOutputStream()
diff --git a/core/ui/src/main/java/com/streamvault/core/ui/components/shell/ExtensionsEmptyState.kt b/core/ui/src/main/java/com/streamvault/core/ui/components/shell/ExtensionsEmptyState.kt
new file mode 100644
index 00000000..1ab1fa61
--- /dev/null
+++ b/core/ui/src/main/java/com/streamvault/core/ui/components/shell/ExtensionsEmptyState.kt
@@ -0,0 +1,41 @@
+package com.streamvault.core.ui.components.shell
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.text.style.TextAlign
+import androidx.compose.ui.unit.dp
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Text
+import com.streamvault.core.ui.design.AppColors
+
+@Composable
+fun ExtensionsEmptyState(
+ title: String,
+ description: String,
+ modifier: Modifier = Modifier,
+ action: (@Composable () -> Unit)? = null,
+) {
+ Box(modifier.fillMaxWidth(), contentAlignment = Alignment.Center) {
+ Column(
+ modifier = Modifier.widthIn(max = 600.dp)
+ .background(AppColors.Surface, RoundedCornerShape(16.dp)).padding(32.dp),
+ horizontalAlignment = Alignment.CenterHorizontally,
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Text(title, style = MaterialTheme.typography.headlineSmall,
+ color = AppColors.TextPrimary, textAlign = TextAlign.Center)
+ Text(description, style = MaterialTheme.typography.bodyMedium,
+ color = AppColors.TextSecondary, textAlign = TextAlign.Center)
+ action?.invoke()
+ }
+ }
+}
diff --git a/core/ui/src/main/java/com/streamvault/core/ui/components/shell/ExtensionsSectionTabs.kt b/core/ui/src/main/java/com/streamvault/core/ui/components/shell/ExtensionsSectionTabs.kt
new file mode 100644
index 00000000..2e6e20fd
--- /dev/null
+++ b/core/ui/src/main/java/com/streamvault/core/ui/components/shell/ExtensionsSectionTabs.kt
@@ -0,0 +1,75 @@
+package com.streamvault.core.ui.components.shell
+
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.LaunchedEffect
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.focus.FocusRequester
+import androidx.compose.ui.focus.focusRequester
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.role
+import androidx.compose.ui.semantics.selected
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.unit.dp
+import androidx.tv.material3.Border
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.MaterialTheme
+import androidx.tv.material3.Text
+import com.streamvault.core.ui.design.AppColors
+import com.streamvault.core.ui.interaction.TvButton
+
+@Composable
+fun ExtensionsSectionTabs(
+ selectedIndex: Int,
+ pluginsLabel: String,
+ stremioAddonsLabel: String,
+ onTabSelected: (Int) -> Unit,
+) {
+ val selectedTabFocus = remember { FocusRequester() }
+ var needsEntryFocus by rememberSaveable { mutableStateOf(true) }
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ listOf(pluginsLabel, stremioAddonsLabel).forEachIndexed { index, label ->
+ val active = selectedIndex == index
+ val shape = RoundedCornerShape(8.dp)
+ TvButton(
+ onClick = { if (!active) onTabSelected(index) },
+ modifier = Modifier.heightIn(min = 40.dp)
+ .then(if (active) Modifier.focusRequester(selectedTabFocus) else Modifier)
+ .semantics {
+ selected = active
+ role = Role.Tab
+ },
+ scale = ButtonDefaults.scale(focusedScale = 1f, pressedScale = 1f),
+ shape = ButtonDefaults.shape(shape),
+ border = ButtonDefaults.border(
+ border = if (active) Border(BorderStroke(1.dp, AppColors.Brand), shape = shape) else Border.None,
+ focusedBorder = Border(BorderStroke(2.dp, AppColors.TextPrimary), shape = shape)
+ ),
+ colors = ButtonDefaults.colors(
+ containerColor = if (active) AppColors.BrandMuted else AppColors.Surface,
+ contentColor = if (active) AppColors.TextPrimary else AppColors.TextSecondary,
+ focusedContainerColor = if (active) AppColors.BrandMuted else AppColors.SurfaceEmphasis,
+ focusedContentColor = AppColors.TextPrimary
+ )
+ ) {
+ Text(label, modifier = Modifier.padding(horizontal = 8.dp), style = MaterialTheme.typography.titleSmall)
+ }
+ }
+ }
+ LaunchedEffect(selectedIndex) {
+ if (needsEntryFocus) {
+ selectedTabFocus.requestFocus()
+ needsEntryFocus = false
+ }
+ }
+}
diff --git a/core/ui/src/main/java/com/streamvault/core/ui/interaction/TvPrimaryButton.kt b/core/ui/src/main/java/com/streamvault/core/ui/interaction/TvPrimaryButton.kt
new file mode 100644
index 00000000..d726ea3c
--- /dev/null
+++ b/core/ui/src/main/java/com/streamvault/core/ui/interaction/TvPrimaryButton.kt
@@ -0,0 +1,51 @@
+package com.streamvault.core.ui.interaction
+
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.RowScope
+import androidx.compose.foundation.layout.heightIn
+import androidx.compose.foundation.shape.RoundedCornerShape
+import androidx.compose.runtime.Composable
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.unit.dp
+import androidx.tv.material3.Border
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.ButtonScale
+import androidx.tv.material3.MaterialTheme
+import com.streamvault.core.ui.design.AppColors
+import com.streamvault.core.ui.design.FocusSpec
+
+/** Shared primary action treatment for TV screens, including a white focus ring. */
+@Composable
+fun TvPrimaryButton(
+ onClick: () -> Unit,
+ modifier: Modifier = Modifier,
+ enabled: Boolean = true,
+ contentPadding: PaddingValues = PaddingValues(horizontal = 20.dp, vertical = 7.dp),
+ content: @Composable RowScope.() -> Unit,
+) {
+ val shape = RoundedCornerShape(8.dp)
+ TvButton(
+ onClick = onClick,
+ modifier = modifier.heightIn(min = 44.dp),
+ enabled = enabled,
+ shape = ButtonDefaults.shape(shape),
+ colors = ButtonDefaults.colors(
+ containerColor = AppColors.Brand,
+ contentColor = AppColors.OnPrimary,
+ focusedContainerColor = AppColors.Brand.copy(alpha = 0.88f),
+ focusedContentColor = AppColors.OnPrimary,
+ disabledContainerColor = AppColors.SurfaceEmphasis.copy(alpha = 0.56f),
+ disabledContentColor = AppColors.TextDisabled,
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, AppColors.Focus),
+ shape = shape,
+ ),
+ ),
+ scale = ButtonDefaults.scale(focusedScale = 1f, pressedScale = 1f),
+ contentPadding = contentPadding,
+ content = content,
+ )
+}
diff --git a/data/schemas/com.streamvault.data.local.StreamVaultDatabase/80.json b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/80.json
new file mode 100644
index 00000000..a1aab24a
--- /dev/null
+++ b/data/schemas/com.streamvault.data.local.StreamVaultDatabase/80.json
@@ -0,0 +1,7269 @@
+{
+ "formatVersion": 1,
+ "database": {
+ "version": 80,
+ "identityHash": "47af036c49883dad3d96a09b0574b12a",
+ "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, `is_active` 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": "isActive",
+ "columnName": "is_active",
+ "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_type",
+ "unique": false,
+ "columnNames": [
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_providers_type` ON `${TABLE_NAME}` (`type`)"
+ },
+ {
+ "name": "index_providers_is_active",
+ "unique": false,
+ "columnNames": [
+ "is_active"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_providers_is_active` ON `${TABLE_NAME}` (`is_active`)"
+ }
+ ]
+ },
+ {
+ "tableName": "provider_configs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `type` TEXT NOT NULL, `schema_version` INTEGER NOT NULL, `configuration_generation` INTEGER NOT NULL, `identity_key` TEXT NOT NULL, `encrypted_config_json` TEXT NOT NULL, `guide_source_policy` TEXT NOT NULL, `channel_logo_source_policy` TEXT NOT NULL, `updated_at` 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": "type",
+ "columnName": "type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "schemaVersion",
+ "columnName": "schema_version",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "configurationGeneration",
+ "columnName": "configuration_generation",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "identityKey",
+ "columnName": "identity_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "encryptedConfigJson",
+ "columnName": "encrypted_config_json",
+ "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": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_configs_provider_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_provider_configs_identity_key",
+ "unique": true,
+ "columnNames": [
+ "identity_key"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_configs_identity_key` ON `${TABLE_NAME}` (`identity_key`)"
+ },
+ {
+ "name": "index_provider_configs_type",
+ "unique": false,
+ "columnNames": [
+ "type"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_configs_type` ON `${TABLE_NAME}` (`type`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "provider_account_runtime",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `max_connections` INTEGER NOT NULL, `expiration_date` INTEGER, `api_version` TEXT, `allowed_output_formats_json` TEXT NOT NULL, `catalog_layout` TEXT NOT NULL, `catalog_layout_detection_version` INTEGER NOT NULL, `observed_at` 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": "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": "catalogLayout",
+ "columnName": "catalog_layout",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catalogLayoutDetectionVersion",
+ "columnName": "catalog_layout_detection_version",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "observedAt",
+ "columnName": "observed_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_account_runtime_provider_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_account_runtime_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "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, `playback_metadata_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": "playbackMetadataJson",
+ "columnName": "playback_metadata_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, `playback_metadata_json` TEXT, 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
+ },
+ {
+ "fieldPath": "playbackMetadataJson",
+ "columnName": "playback_metadata_json",
+ "affinity": "TEXT"
+ }
+ ],
+ "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, `catalog_origin` TEXT NOT NULL, `episode_playback_template_url` TEXT, 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
+ },
+ {
+ "fieldPath": "catalogOrigin",
+ "columnName": "catalog_origin",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "episodePlaybackTemplateUrl",
+ "columnName": "episode_playback_template_url",
+ "affinity": "TEXT"
+ }
+ ],
+ "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, `provider_order` INTEGER NOT NULL DEFAULT 0, `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": "providerOrder",
+ "columnName": "provider_order",
+ "affinity": "INTEGER",
+ "notNull": true,
+ "defaultValue": "0"
+ },
+ {
+ "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, `playback_metadata_json` TEXT, `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": "playbackMetadataJson",
+ "columnName": "playback_metadata_json",
+ "affinity": "TEXT"
+ },
+ {
+ "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, `playback_metadata_json` TEXT, `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": "playbackMetadataJson",
+ "columnName": "playback_metadata_json",
+ "affinity": "TEXT"
+ },
+ {
+ "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, `provider_order` INTEGER NOT NULL DEFAULT 0, `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": "providerOrder",
+ "columnName": "provider_order",
+ "affinity": "INTEGER",
+ "notNull": true,
+ "defaultValue": "0"
+ },
+ {
+ "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, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `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": "advertisedTotalItems",
+ "columnName": "advertised_total_items",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "advertisedTotalPages",
+ "columnName": "advertised_total_pages",
+ "affinity": "INTEGER"
+ },
+ {
+ "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, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `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": "advertisedTotalItems",
+ "columnName": "advertised_total_items",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "advertisedTotalPages",
+ "columnName": "advertised_total_pages",
+ "affinity": "INTEGER"
+ },
+ {
+ "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": "vod_category_hydration",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `last_loaded_page` INTEGER NOT NULL, `last_attempted_page` INTEGER NOT NULL, `last_successful_page` INTEGER NOT NULL, `total_pages` INTEGER NOT NULL, `advertised_total_items` INTEGER, `advertised_total_pages` INTEGER, `page_size` INTEGER NOT NULL, `item_count` INTEGER NOT NULL, `is_complete` INTEGER NOT NULL, `has_movies` INTEGER NOT NULL, `has_series` INTEGER NOT NULL, `last_hydrated_at` INTEGER NOT NULL, `last_status` TEXT NOT NULL, `last_error` TEXT, `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": "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": "advertisedTotalItems",
+ "columnName": "advertised_total_items",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "advertisedTotalPages",
+ "columnName": "advertised_total_pages",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "pageSize",
+ "columnName": "page_size",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemCount",
+ "columnName": "item_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isComplete",
+ "columnName": "is_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "hasMovies",
+ "columnName": "has_movies",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "hasSeries",
+ "columnName": "has_series",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastHydratedAt",
+ "columnName": "last_hydrated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastStatus",
+ "columnName": "last_status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ },
+ {
+ "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_vod_category_hydration_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_category_hydration_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "vod_catalog_entries",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `category_id` INTEGER NOT NULL, `raw_item_id` TEXT NOT NULL, `item_type` TEXT NOT NULL, `target_id` INTEGER NOT NULL, `raw_page` INTEGER NOT NULL, `raw_index` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `category_id`, `raw_item_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": "rawItemId",
+ "columnName": "raw_item_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "itemType",
+ "columnName": "item_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "targetId",
+ "columnName": "target_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rawPage",
+ "columnName": "raw_page",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "rawIndex",
+ "columnName": "raw_index",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "raw_item_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_vod_catalog_entries_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "category_id",
+ "raw_page",
+ "raw_index"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id_category_id_raw_page_raw_index` ON `${TABLE_NAME}` (`provider_id`, `category_id`, `raw_page`, `raw_index`)"
+ },
+ {
+ "name": "index_vod_catalog_entries_provider_id_item_type_target_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "item_type",
+ "target_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_vod_catalog_entries_provider_id_item_type_target_id` ON `${TABLE_NAME}` (`provider_id`, `item_type`, `target_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, `timezone_policy` TEXT NOT NULL, `timezone_id` 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"
+ },
+ {
+ "fieldPath": "timezonePolicy",
+ "columnName": "timezone_policy",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "timezoneId",
+ "columnName": "timezone_id",
+ "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, `exact_alarm_armed` INTEGER NOT NULL, `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": "exactAlarmArmed",
+ "columnName": "exact_alarm_armed",
+ "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": [
+ "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, `exact_alarm_armed` INTEGER NOT NULL, `delivery_state` TEXT NOT NULL, `delivery_attempt_token` TEXT, `delivery_attempted_at` INTEGER, `delivery_attempt_count` INTEGER NOT NULL, `delivery_failure_reason` TEXT, `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": "exactAlarmArmed",
+ "columnName": "exact_alarm_armed",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deliveryState",
+ "columnName": "delivery_state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deliveryAttemptToken",
+ "columnName": "delivery_attempt_token",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "deliveryAttemptedAt",
+ "columnName": "delivery_attempted_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "deliveryAttemptCount",
+ "columnName": "delivery_attempt_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "deliveryFailureReason",
+ "columnName": "delivery_failure_reason",
+ "affinity": "TEXT"
+ },
+ {
+ "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, `configuration_generation` INTEGER NOT NULL, `learning_json` TEXT NOT NULL, `observation_source` TEXT NOT NULL, `observed_at` 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
+ },
+ {
+ "fieldPath": "configurationGeneration",
+ "columnName": "configuration_generation",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "learningJson",
+ "columnName": "learning_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "observationSource",
+ "columnName": "observation_source",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "observedAt",
+ "columnName": "observed_at",
+ "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, `owner_id` TEXT, `owner_epoch` INTEGER NOT NULL, `heartbeat_at` INTEGER, `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": "ownerId",
+ "columnName": "owner_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "ownerEpoch",
+ "columnName": "owner_epoch",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "heartbeatAt",
+ "columnName": "heartbeat_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "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`)"
+ }
+ ]
+ },
+ {
+ "tableName": "provider_deletion_cleanup",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `provider_id` INTEGER NOT NULL, `action` TEXT NOT NULL, `target_id` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "action",
+ "columnName": "action",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "targetId",
+ "columnName": "target_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "attemptCount",
+ "columnName": "attempt_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastError",
+ "columnName": "last_error",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_deletion_cleanup_provider_id_action_target_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id",
+ "action",
+ "target_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_provider_deletion_cleanup_provider_id_action_target_id` ON `${TABLE_NAME}` (`provider_id`, `action`, `target_id`)"
+ }
+ ]
+ },
+ {
+ "tableName": "plugin_provider_ownership",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`package_name` TEXT NOT NULL, `service_class_name` TEXT NOT NULL, `manifest_id` TEXT NOT NULL, `provider_id` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, PRIMARY KEY(`package_name`, `service_class_name`, `manifest_id`), FOREIGN KEY(`provider_id`) REFERENCES `providers`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "packageName",
+ "columnName": "package_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "serviceClassName",
+ "columnName": "service_class_name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "manifestId",
+ "columnName": "manifest_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerId",
+ "columnName": "provider_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "createdAt",
+ "columnName": "created_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "package_name",
+ "service_class_name",
+ "manifest_id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_plugin_provider_ownership_provider_id",
+ "unique": true,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_plugin_provider_ownership_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "provider_config_revisions",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `revision` INTEGER NOT NULL, `config_json` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `revision`), 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": "revision",
+ "columnName": "revision",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "configJson",
+ "columnName": "config_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "attemptCount",
+ "columnName": "attempt_count",
+ "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
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "revision"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_config_revisions_provider_id_state",
+ "unique": false,
+ "columnNames": [
+ "provider_id",
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_config_revisions_provider_id_state` ON `${TABLE_NAME}` (`provider_id`, `state`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "backup_restore_checkpoints",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`restore_key` TEXT NOT NULL, `room_complete` INTEGER NOT NULL, `preferences_complete` INTEGER NOT NULL, `presets_complete` INTEGER NOT NULL, `schedules_complete` INTEGER NOT NULL, `state` TEXT NOT NULL, `preference_snapshot_json` TEXT, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`restore_key`))",
+ "fields": [
+ {
+ "fieldPath": "restoreKey",
+ "columnName": "restore_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "roomComplete",
+ "columnName": "room_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "preferencesComplete",
+ "columnName": "preferences_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "presetsComplete",
+ "columnName": "presets_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "schedulesComplete",
+ "columnName": "schedules_complete",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "preferenceSnapshotJson",
+ "columnName": "preference_snapshot_json",
+ "affinity": "TEXT"
+ },
+ {
+ "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
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "restore_key"
+ ]
+ }
+ },
+ {
+ "tableName": "backup_restore_jobs",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` TEXT NOT NULL, `restore_key` TEXT NOT NULL, `backup_version` INTEGER NOT NULL, `conflict_strategy` TEXT NOT NULL, `status` TEXT NOT NULL, `total_count` INTEGER NOT NULL, `pending_count` INTEGER NOT NULL, `applied_count` INTEGER NOT NULL, `unresolved_count` INTEGER NOT NULL, `failed_count` INTEGER NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`id`))",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "restoreKey",
+ "columnName": "restore_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "backupVersion",
+ "columnName": "backup_version",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "conflictStrategy",
+ "columnName": "conflict_strategy",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalCount",
+ "columnName": "total_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "pendingCount",
+ "columnName": "pending_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "appliedCount",
+ "columnName": "applied_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "unresolvedCount",
+ "columnName": "unresolved_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "failedCount",
+ "columnName": "failed_count",
+ "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": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_backup_restore_jobs_restore_key",
+ "unique": true,
+ "columnNames": [
+ "restore_key"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_backup_restore_jobs_restore_key` ON `${TABLE_NAME}` (`restore_key`)"
+ },
+ {
+ "name": "index_backup_restore_jobs_status",
+ "unique": false,
+ "columnNames": [
+ "status"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_jobs_status` ON `${TABLE_NAME}` (`status`)"
+ },
+ {
+ "name": "index_backup_restore_jobs_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_jobs_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ]
+ },
+ {
+ "tableName": "backup_restore_items",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `job_id` TEXT NOT NULL, `provider_identity_key` TEXT NOT NULL, `local_provider_id` INTEGER, `section` TEXT NOT NULL, `content_type` TEXT, `stable_reference_key` TEXT NOT NULL, `reference_json` TEXT NOT NULL, `payload_json` TEXT NOT NULL, `status` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `last_error` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, FOREIGN KEY(`job_id`) REFERENCES `backup_restore_jobs`(`id`) ON UPDATE NO ACTION ON DELETE CASCADE )",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "jobId",
+ "columnName": "job_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "providerIdentityKey",
+ "columnName": "provider_identity_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "localProviderId",
+ "columnName": "local_provider_id",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "section",
+ "columnName": "section",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "contentType",
+ "columnName": "content_type",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "stableReferenceKey",
+ "columnName": "stable_reference_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "referenceJson",
+ "columnName": "reference_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "payloadJson",
+ "columnName": "payload_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "status",
+ "columnName": "status",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "attemptCount",
+ "columnName": "attempt_count",
+ "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
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": true,
+ "columnNames": [
+ "id"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_backup_restore_items_job_id",
+ "unique": false,
+ "columnNames": [
+ "job_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_job_id` ON `${TABLE_NAME}` (`job_id`)"
+ },
+ {
+ "name": "index_backup_restore_items_provider_identity_key_status",
+ "unique": false,
+ "columnNames": [
+ "provider_identity_key",
+ "status"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_provider_identity_key_status` ON `${TABLE_NAME}` (`provider_identity_key`, `status`)"
+ },
+ {
+ "name": "index_backup_restore_items_job_id_status",
+ "unique": false,
+ "columnNames": [
+ "job_id",
+ "status"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_backup_restore_items_job_id_status` ON `${TABLE_NAME}` (`job_id`, `status`)"
+ },
+ {
+ "name": "index_backup_restore_items_job_id_section_stable_reference_key",
+ "unique": true,
+ "columnNames": [
+ "job_id",
+ "section",
+ "stable_reference_key"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_backup_restore_items_job_id_section_stable_reference_key` ON `${TABLE_NAME}` (`job_id`, `section`, `stable_reference_key`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "backup_restore_jobs",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "job_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "provider_workflows",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `state` TEXT NOT NULL, `reason` TEXT NOT NULL, `priority` INTEGER NOT NULL, `force` INTEGER NOT NULL, `current_phase` TEXT, `lease_token` TEXT, `lease_expires_at` INTEGER, `heartbeat_at` INTEGER, `progress_message` TEXT, `last_error_code` TEXT, `last_error_message` 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": "generation",
+ "columnName": "generation",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "reason",
+ "columnName": "reason",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "priority",
+ "columnName": "priority",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "force",
+ "columnName": "force",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "currentPhase",
+ "columnName": "current_phase",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "leaseToken",
+ "columnName": "lease_token",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "leaseExpiresAt",
+ "columnName": "lease_expires_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "heartbeatAt",
+ "columnName": "heartbeat_at",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "progressMessage",
+ "columnName": "progress_message",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastErrorCode",
+ "columnName": "last_error_code",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastErrorMessage",
+ "columnName": "last_error_message",
+ "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_provider_workflows_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_provider_workflows_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ },
+ {
+ "name": "index_provider_workflows_lease_expires_at",
+ "unique": false,
+ "columnNames": [
+ "lease_expires_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflows_lease_expires_at` ON `${TABLE_NAME}` (`lease_expires_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "provider_workflow_phases",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `generation` INTEGER NOT NULL, `phase` TEXT NOT NULL, `state` TEXT NOT NULL, `attempt_count` INTEGER NOT NULL, `checkpoint` TEXT, `last_error_code` TEXT, `last_error_message` TEXT, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL, `completed_at` INTEGER, PRIMARY KEY(`provider_id`, `generation`, `phase`), 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": "generation",
+ "columnName": "generation",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "phase",
+ "columnName": "phase",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "state",
+ "columnName": "state",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "attemptCount",
+ "columnName": "attempt_count",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "checkpoint",
+ "columnName": "checkpoint",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastErrorCode",
+ "columnName": "last_error_code",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "lastErrorMessage",
+ "columnName": "last_error_message",
+ "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",
+ "generation",
+ "phase"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_provider_workflow_phases_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ },
+ {
+ "name": "index_provider_workflow_phases_state",
+ "unique": false,
+ "columnNames": [
+ "state"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_state` ON `${TABLE_NAME}` (`state`)"
+ },
+ {
+ "name": "index_provider_workflow_phases_updated_at",
+ "unique": false,
+ "columnNames": [
+ "updated_at"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_provider_workflow_phases_updated_at` ON `${TABLE_NAME}` (`updated_at`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "m3u_classification_overrides",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `source_key` TEXT NOT NULL, `stream_id` INTEGER NOT NULL, `target_type` TEXT NOT NULL, `group_key` TEXT NOT NULL, `series_key` TEXT, `series_name` TEXT, `season_number` INTEGER, `episode_number` INTEGER, `episode_title` TEXT, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `source_key`), 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": "sourceKey",
+ "columnName": "source_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamId",
+ "columnName": "stream_id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "targetType",
+ "columnName": "target_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "groupKey",
+ "columnName": "group_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "seriesKey",
+ "columnName": "series_key",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seriesName",
+ "columnName": "series_name",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "seasonNumber",
+ "columnName": "season_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeNumber",
+ "columnName": "episode_number",
+ "affinity": "INTEGER"
+ },
+ {
+ "fieldPath": "episodeTitle",
+ "columnName": "episode_title",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "source_key"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_m3u_classification_overrides_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_m3u_classification_overrides_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "m3u_category_classification_rules",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`provider_id` INTEGER NOT NULL, `group_key` TEXT NOT NULL, `target_type` TEXT NOT NULL, `updated_at` INTEGER NOT NULL, PRIMARY KEY(`provider_id`, `group_key`), 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": "groupKey",
+ "columnName": "group_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "targetType",
+ "columnName": "target_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "updatedAt",
+ "columnName": "updated_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "provider_id",
+ "group_key"
+ ]
+ },
+ "indices": [
+ {
+ "name": "index_m3u_category_classification_rules_provider_id",
+ "unique": false,
+ "columnNames": [
+ "provider_id"
+ ],
+ "orders": [],
+ "createSql": "CREATE INDEX IF NOT EXISTS `index_m3u_category_classification_rules_provider_id` ON `${TABLE_NAME}` (`provider_id`)"
+ }
+ ],
+ "foreignKeys": [
+ {
+ "table": "providers",
+ "onDelete": "CASCADE",
+ "onUpdate": "NO ACTION",
+ "columns": [
+ "provider_id"
+ ],
+ "referencedColumns": [
+ "id"
+ ]
+ }
+ ]
+ },
+ {
+ "tableName": "stremio_addons",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `install_url` TEXT NOT NULL, `manifest_id` TEXT NOT NULL, `name` TEXT NOT NULL, `version` TEXT NOT NULL, `manifest_json` TEXT NOT NULL, `enabled` INTEGER NOT NULL, `sort_order` INTEGER NOT NULL, `catalog_settings_json` TEXT NOT NULL, `created_at` INTEGER NOT NULL, `updated_at` INTEGER NOT NULL)",
+ "fields": [
+ {
+ "fieldPath": "id",
+ "columnName": "id",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "installUrl",
+ "columnName": "install_url",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "manifestId",
+ "columnName": "manifest_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "name",
+ "columnName": "name",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "version",
+ "columnName": "version",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "manifestJson",
+ "columnName": "manifest_json",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "enabled",
+ "columnName": "enabled",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "sortOrder",
+ "columnName": "sort_order",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catalogSettingsJson",
+ "columnName": "catalog_settings_json",
+ "affinity": "TEXT",
+ "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_stremio_addons_install_url",
+ "unique": true,
+ "columnNames": [
+ "install_url"
+ ],
+ "orders": [],
+ "createSql": "CREATE UNIQUE INDEX IF NOT EXISTS `index_stremio_addons_install_url` ON `${TABLE_NAME}` (`install_url`)"
+ }
+ ]
+ },
+ {
+ "tableName": "stremio_playback_history",
+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`content_key` TEXT NOT NULL, `media_type` TEXT NOT NULL, `exact_video_id` TEXT NOT NULL, `parent_series_id` TEXT, `title` TEXT NOT NULL, `poster_url` TEXT, `resume_position_ms` INTEGER NOT NULL, `total_duration_ms` INTEGER NOT NULL, `is_watched` INTEGER NOT NULL, `last_watched_at` INTEGER NOT NULL, `catalog_origin_key` TEXT NOT NULL, `stream_origin_key_hint` TEXT, PRIMARY KEY(`content_key`))",
+ "fields": [
+ {
+ "fieldPath": "contentKey",
+ "columnName": "content_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "mediaType",
+ "columnName": "media_type",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "exactVideoId",
+ "columnName": "exact_video_id",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "parentSeriesId",
+ "columnName": "parent_series_id",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "title",
+ "columnName": "title",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "posterUrl",
+ "columnName": "poster_url",
+ "affinity": "TEXT"
+ },
+ {
+ "fieldPath": "resumePositionMs",
+ "columnName": "resume_position_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "totalDurationMs",
+ "columnName": "total_duration_ms",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "isWatched",
+ "columnName": "is_watched",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "lastWatchedAt",
+ "columnName": "last_watched_at",
+ "affinity": "INTEGER",
+ "notNull": true
+ },
+ {
+ "fieldPath": "catalogOriginKey",
+ "columnName": "catalog_origin_key",
+ "affinity": "TEXT",
+ "notNull": true
+ },
+ {
+ "fieldPath": "streamOriginKeyHint",
+ "columnName": "stream_origin_key_hint",
+ "affinity": "TEXT"
+ }
+ ],
+ "primaryKey": {
+ "autoGenerate": false,
+ "columnNames": [
+ "content_key"
+ ]
+ }
+ }
+ ],
+ "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, '47af036c49883dad3d96a09b0574b12a')"
+ ]
+ }
+}
\ 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 121f8552..1b30a32f 100644
--- a/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
+++ b/data/src/androidTest/java/com/streamvault/data/local/StreamVaultDatabaseMigrationTest.kt
@@ -2024,6 +2024,48 @@ class StreamVaultDatabaseMigrationTest {
migrated.close()
}
+ @Test
+ fun migrate79To80_createsUrlFreeStremioProgressTable() {
+ val name = "streamvault-79-80-stremio-progress"
+ migrationTestHelper.createDatabase(name, 79).close()
+
+ val migrated = migrationTestHelper.runMigrationsAndValidate(
+ name,
+ 80,
+ true,
+ *StreamVaultDatabaseMigrationRegistry.v79To80.toTypedArray()
+ )
+
+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='stremio_playback_history'"))
+ assertEquals(12, countRows(migrated, "SELECT COUNT(*) FROM pragma_table_info('stremio_playback_history')"))
+ assertEquals(0, countRows(migrated, "SELECT COUNT(*) FROM pragma_table_info('stremio_playback_history') WHERE name IN ('stream_url','headers','response_body')"))
+ assertEquals(0, countRows(migrated, "SELECT COUNT(*) FROM pragma_foreign_key_list('stremio_playback_history')"))
+ assertEquals(0, countRows(migrated, "SELECT COUNT(*) FROM pragma_foreign_key_check"))
+ migrated.close()
+ }
+
+ @Test
+ fun migrate78To80_preservesAddonRegistryAndValidatesHistorySchema() {
+ val name = "streamvault-78-80-stremio-progress-chain"
+ migrationTestHelper.createDatabase(name, 78).apply {
+ execSQL("INSERT INTO search_history (query, content_scope, provider_id, used_at, use_count) VALUES ('foundation', 'MOVIE', 0, 100, 1)")
+ close()
+ }
+
+ val migrated = migrationTestHelper.runMigrationsAndValidate(
+ name,
+ 80,
+ true,
+ *(StreamVaultDatabaseMigrationRegistry.v78To79 + StreamVaultDatabaseMigrationRegistry.v79To80).toTypedArray()
+ )
+
+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM search_history WHERE query='foundation'"))
+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='stremio_addons'"))
+ assertEquals(1, countRows(migrated, "SELECT COUNT(*) FROM sqlite_master WHERE type='table' AND name='stremio_playback_history'"))
+ assertEquals(0, countRows(migrated, "SELECT COUNT(*) FROM pragma_foreign_key_check"))
+ migrated.close()
+ }
+
private fun SupportSQLiteDatabase.insertProvider72(id: Long, name: String, type: String) {
execSQL(
"""
diff --git a/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV79To80.kt b/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV79To80.kt
new file mode 100644
index 00000000..81c1152d
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/FeatureMigrationsV79To80.kt
@@ -0,0 +1,31 @@
+package com.streamvault.data.local
+
+import androidx.room.migration.Migration
+import androidx.sqlite.db.SupportSQLiteDatabase
+
+/** Adds provider-independent progress for Stremio media without retaining playable URLs. */
+object FeatureMigrationsV79To80 {
+ val MIGRATION_79_80 = object : Migration(79, 80) {
+ override fun migrate(db: SupportSQLiteDatabase) {
+ db.execSQL(
+ """
+ CREATE TABLE IF NOT EXISTS `stremio_playback_history` (
+ `content_key` TEXT NOT NULL,
+ `media_type` TEXT NOT NULL,
+ `exact_video_id` TEXT NOT NULL,
+ `parent_series_id` TEXT,
+ `title` TEXT NOT NULL,
+ `poster_url` TEXT,
+ `resume_position_ms` INTEGER NOT NULL,
+ `total_duration_ms` INTEGER NOT NULL,
+ `is_watched` INTEGER NOT NULL,
+ `last_watched_at` INTEGER NOT NULL,
+ `catalog_origin_key` TEXT NOT NULL,
+ `stream_origin_key_hint` TEXT,
+ PRIMARY KEY(`content_key`)
+ )
+ """.trimIndent()
+ )
+ }
+ }
+}
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 fcc04072..c4971951 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabase.kt
@@ -12,7 +12,7 @@ import org.json.JSONObject
import java.net.URI
import java.security.MessageDigest
-internal const val STREAM_VAULT_DATABASE_VERSION = 79
+internal const val STREAM_VAULT_DATABASE_VERSION = 80
@Database(
entities = [
@@ -73,7 +73,8 @@ internal const val STREAM_VAULT_DATABASE_VERSION = 79
ProviderWorkflowPhaseEntity::class,
M3uClassificationOverrideEntity::class,
M3uCategoryClassificationRuleEntity::class,
- StremioAddonEntity::class
+ StremioAddonEntity::class,
+ StremioPlaybackHistoryEntity::class
],
version = STREAM_VAULT_DATABASE_VERSION,
exportSchema = true // ← was false; schema JSON now tracked in version control
@@ -129,6 +130,7 @@ abstract class StreamVaultDatabase : RoomDatabase() {
abstract fun providerWorkflowDao(): ProviderWorkflowDao
abstract fun m3uClassificationDao(): M3uClassificationDao
abstract fun stremioAddonDao(): StremioAddonDao
+ abstract fun stremioPlaybackHistoryDao(): StremioPlaybackHistoryDao
companion object {
val MIGRATION_1_2 = LegacyMigrationsV1To24.MIGRATION_1_2
@@ -209,5 +211,6 @@ abstract class StreamVaultDatabase : RoomDatabase() {
val MIGRATION_76_77 = FeatureMigrationsV76To77.MIGRATION_76_77
val MIGRATION_77_78 = FeatureMigrationsV77To78.MIGRATION_77_78
val MIGRATION_78_79 = FeatureMigrationsV78To79.MIGRATION_78_79
+ val MIGRATION_79_80 = FeatureMigrationsV79To80.MIGRATION_79_80
}
}
diff --git a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt
index 75148d2f..dff6bc5b 100644
--- a/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt
+++ b/data/src/main/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistry.kt
@@ -16,7 +16,8 @@ object StreamVaultDatabaseMigrationRegistry {
val v76To77: List<Migration> = listOf(FeatureMigrationsV76To77.MIGRATION_76_77)
val v77To78: List<Migration> = listOf(FeatureMigrationsV77To78.MIGRATION_77_78)
val v78To79: List<Migration> = listOf(FeatureMigrationsV78To79.MIGRATION_78_79)
- val all: List<Migration> = (v1To24 + v24To49 + v49To75 + v75To76 + v76To77 + v77To78 + v78To79).also(::validate)
+ val v79To80: List<Migration> = listOf(FeatureMigrationsV79To80.MIGRATION_79_80)
+ val all: List<Migration> = (v1To24 + v24To49 + v49To75 + v75To76 + v76To77 + v77To78 + v78To79 + v79To80).also(::validate)
private fun validate(migrations: List<Migration>) {
require(migrations.map { it.startVersion }.distinct().size == migrations.size) {
diff --git a/data/src/main/java/com/streamvault/data/local/dao/StremioPlaybackHistoryDao.kt b/data/src/main/java/com/streamvault/data/local/dao/StremioPlaybackHistoryDao.kt
new file mode 100644
index 00000000..2efb5a27
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/dao/StremioPlaybackHistoryDao.kt
@@ -0,0 +1,23 @@
+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.StremioPlaybackHistoryEntity
+import kotlinx.coroutines.flow.Flow
+
+@Dao
+interface StremioPlaybackHistoryDao {
+ @Query("SELECT * FROM stremio_playback_history WHERE is_watched = 0 AND resume_position_ms > 0 ORDER BY last_watched_at DESC LIMIT :limit")
+ fun observeContinueWatching(limit: Int): Flow<List<StremioPlaybackHistoryEntity>>
+
+ @Query("SELECT * FROM stremio_playback_history WHERE content_key = :contentKey LIMIT 1")
+ suspend fun get(contentKey: String): StremioPlaybackHistoryEntity?
+
+ @Insert(onConflict = OnConflictStrategy.REPLACE)
+ suspend fun upsert(entity: StremioPlaybackHistoryEntity)
+
+ @Query("DELETE FROM stremio_playback_history WHERE content_key = :contentKey")
+ suspend fun delete(contentKey: String)
+}
diff --git a/data/src/main/java/com/streamvault/data/local/entity/StremioPlaybackHistoryEntity.kt b/data/src/main/java/com/streamvault/data/local/entity/StremioPlaybackHistoryEntity.kt
new file mode 100644
index 00000000..be659bf8
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/local/entity/StremioPlaybackHistoryEntity.kt
@@ -0,0 +1,21 @@
+package com.streamvault.data.local.entity
+
+import androidx.room.ColumnInfo
+import androidx.room.Entity
+import androidx.room.PrimaryKey
+
+@Entity(tableName = "stremio_playback_history")
+data class StremioPlaybackHistoryEntity(
+ @PrimaryKey @ColumnInfo(name = "content_key") val contentKey: String,
+ @ColumnInfo(name = "media_type") val mediaType: String,
+ @ColumnInfo(name = "exact_video_id") val exactVideoId: String,
+ @ColumnInfo(name = "parent_series_id") val parentSeriesId: String?,
+ val title: String,
+ @ColumnInfo(name = "poster_url") val posterUrl: String?,
+ @ColumnInfo(name = "resume_position_ms") val resumePositionMs: Long,
+ @ColumnInfo(name = "total_duration_ms") val totalDurationMs: Long,
+ @ColumnInfo(name = "is_watched") val isWatched: Boolean,
+ @ColumnInfo(name = "last_watched_at") val lastWatchedAt: Long,
+ @ColumnInfo(name = "catalog_origin_key") val catalogOriginKey: String,
+ @ColumnInfo(name = "stream_origin_key_hint") val streamOriginKeyHint: String?
+)
diff --git a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
index c9ec99e4..ac76a981 100644
--- a/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
+++ b/data/src/main/java/com/streamvault/data/preferences/PreferencesRepository.kt
@@ -195,6 +195,7 @@ class PreferencesRepository @Inject constructor(
val ACTIVE_LIVE_SOURCE_TYPE = stringPreferencesKey("active_live_source_type")
val ACTIVE_LIVE_SOURCE_ID = longPreferencesKey("active_live_source_id")
val DEFAULT_VIEW_MODE = stringPreferencesKey("default_view_mode")
+ val HIDE_STREMIO_ADDONS = booleanPreferencesKey("hide_stremio_addons")
val PARENTAL_CONTROL_LEVEL = intPreferencesKey("parental_control_level")
val PARENTAL_V2_MIGRATED = booleanPreferencesKey("parental_v2_migrated")
val LEGACY_PARENTAL_PIN = stringPreferencesKey("parental_pin")
@@ -694,6 +695,16 @@ class PreferencesRepository @Inject constructor(
val recentSearchQueries: Flow<List<String>> = getRecentSearchQueries(SearchHistoryScope.ALL, null)
+ override val hideStremioAddons: Flow<Boolean> = context.dataStore.data.map { preferences ->
+ preferences[PreferencesKeys.HIDE_STREMIO_ADDONS] ?: false
+ }
+
+ override suspend fun setHideStremioAddons(hidden: Boolean) {
+ context.dataStore.edit { preferences ->
+ preferences[PreferencesKeys.HIDE_STREMIO_ADDONS] = hidden
+ }
+ }
+
override val parentalControlLevel: Flow<Int> = context.dataStore.data
.map { preferences ->
val stored = preferences[PreferencesKeys.PARENTAL_CONTROL_LEVEL] ?: 2 // Default to 2 = PRIVATE
diff --git a/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonClient.kt b/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonClient.kt
index bba49727..56ae49f1 100644
--- a/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonClient.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonClient.kt
@@ -23,6 +23,8 @@ import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response
+import okhttp3.Authenticator
+import okhttp3.CookieJar
@Singleton
class StremioAddonClient @Inject constructor(
@@ -96,6 +98,7 @@ class StremioAddonClient @Inject constructor(
type: StremioMediaType,
id: String,
videoHash: String? = null,
+ videoSize: Long? = null,
filename: String? = null
): Result<List<StremioSubtitle>> {
if (id.isBlank()) return Result.error(MISSING_ID_MESSAGE)
@@ -103,6 +106,7 @@ class StremioAddonClient @Inject constructor(
val location = StremioAddonUrl.parse(addonUrl) ?: return Result.error(INVALID_URL_MESSAGE)
val extras = buildList {
videoHash?.trim()?.takeIf { it.isNotEmpty() }?.let { add("videoHash" to it) }
+ videoSize?.takeIf { it > 0L }?.let { add("videoSize" to it.toString()) }
filename?.trim()?.takeIf { it.isNotEmpty() }?.let { add("filename" to it) }
}
val path = StremioAddonUrl.subtitlePath(type, id, extras)
@@ -126,12 +130,18 @@ class StremioAddonClient @Inject constructor(
Result.success(map(json.decodeFromString(deserializer, body), body))
} catch (cancellation: CancellationException) {
throw cancellation
- } catch (parseError: SerializationException) {
- Result.error("Addon response could not be parsed", parseError)
- } catch (parseError: IllegalArgumentException) {
- Result.error("Addon response could not be parsed", parseError)
+ } catch (_: SerializationException) {
+ Result.error("Addon response could not be parsed")
+ } catch (_: IllegalArgumentException) {
+ Result.error("Addon response could not be parsed")
} catch (error: Exception) {
- Result.error(error.message ?: "Addon request failed", error)
+ val message = when (error) {
+ is StremioHttpException, is StremioResponseTooLargeException, is StremioParseException ->
+ error.message ?: "Addon request failed"
+ else -> "Addon request failed. Check the connection and addon configuration."
+ }
+ // Do not retain arbitrary OkHttp/parser exceptions: they can include a configured URL path or query.
+ Result.error(message)
}
private suspend fun executeBody(url: String): String {
@@ -141,6 +151,7 @@ class StremioAddonClient @Inject constructor(
.get()
.build()
return okHttpClient.newBuilder()
+ .applyStremioAddonRequestPolicy()
.callTimeout(REQUEST_TIMEOUT_SECONDS, TimeUnit.SECONDS)
.build()
.newCall(request)
@@ -185,6 +196,17 @@ class StremioAddonClient @Inject constructor(
}
}
+/** Addon URLs may contain install credentials in paths or queries; keep them out of inherited app logging and state. */
+private fun OkHttpClient.Builder.applyStremioAddonRequestPolicy(): OkHttpClient.Builder {
+ interceptors().clear()
+ networkInterceptors().clear()
+ cookieJar(CookieJar.NO_COOKIES)
+ .authenticator(Authenticator.NONE)
+ .proxyAuthenticator(Authenticator.NONE)
+ .cache(null)
+ return this
+}
+
class StremioHttpException(val statusCode: Int) : IOException("Addon request failed with HTTP $statusCode")
class StremioResponseTooLargeException(observedBytes: Long) :
diff --git a/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonDtos.kt b/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonDtos.kt
index e16ea325..34c817e7 100644
--- a/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonDtos.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonDtos.kt
@@ -106,6 +106,7 @@ internal data class StremioStreamDto(
val fileIdx: Int? = null,
val externalUrl: String? = null,
val sources: List<String>? = null,
+ val subtitles: List<StremioSubtitleDto>? = null,
val behaviorHints: StremioStreamBehaviorHintsDto? = null
)
diff --git a/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonUrl.kt b/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonUrl.kt
index f417de03..558d2ff6 100644
--- a/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonUrl.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stremio/StremioAddonUrl.kt
@@ -3,6 +3,7 @@ package com.streamvault.data.remote.stremio
import com.streamvault.domain.model.stremio.StremioMediaType
import java.net.URI
import java.net.URLEncoder
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
data class StremioAddonLocation(
val baseUrl: String,
@@ -19,22 +20,32 @@ object StremioAddonUrl {
private const val MANIFEST_SUFFIX = "/manifest.json"
fun parse(raw: String): StremioAddonLocation? {
- val trimmed = raw.trim()
+ val trimmed = raw.trimPastedUrlBoundaryCharacters()
if (trimmed.isEmpty()) return null
val upgraded = if (trimmed.startsWith("stremio://", ignoreCase = true)) {
"https://" + trimmed.substring("stremio://".length)
} else {
trimmed
}
- val uri = runCatching { URI(upgraded) }.getOrNull() ?: return null
- val scheme = uri.scheme?.lowercase() ?: return null
+ val httpUrl = upgraded.toHttpUrlOrNull() ?: return null
+ val uri = runCatching { URI(upgraded) }.getOrNull()
+ if (uri != null && uri.rawAuthority.isNullOrBlank()) return null
+ val scheme = (uri?.scheme ?: httpUrl.scheme).lowercase()
if (scheme != "http" && scheme != "https") return null
- val host = uri.host?.takeIf { it.isNotBlank() } ?: return null
- val authority = if (uri.port == -1) host else "$host:${uri.port}"
- val basePath = normalizedBasePath(uri.path.orEmpty())
+ val uriHost = uri?.host?.takeIf { it.isNotBlank() }
+ val authority = if (uriHost != null) {
+ if (uri.port == -1) uriHost else "$uriHost:${uri.port}"
+ } else {
+ val isDefaultPort = (httpUrl.scheme == "https" && httpUrl.port == 443) ||
+ (httpUrl.scheme == "http" && httpUrl.port == 80)
+ if (isDefaultPort) httpUrl.host else "${httpUrl.host}:${httpUrl.port}"
+ }
+ // Configured addon URLs can encode tenant/configuration bytes in the path.
+ // Preserve those bytes so endpoints and install identity round-trip exactly.
+ val basePath = normalizedBasePath(uri?.rawPath ?: httpUrl.encodedPath)
return StremioAddonLocation(
baseUrl = "$scheme://$authority$basePath",
- query = uri.rawQuery.orEmpty()
+ query = uri?.rawQuery ?: httpUrl.encodedQuery.orEmpty()
)
}
@@ -79,3 +90,24 @@ object StremioAddonUrl {
.replace("+", "%20")
.replace("%3A", ":")
}
+
+private fun String.trimPastedUrlBoundaryCharacters(): String {
+ var start = 0
+ var end = length
+ while (start < end) {
+ val codePoint = codePointAt(start)
+ if (!codePoint.isPastedUrlBoundaryCharacter()) break
+ start += Character.charCount(codePoint)
+ }
+ while (start < end) {
+ val codePoint = codePointBefore(end)
+ if (!codePoint.isPastedUrlBoundaryCharacter()) break
+ end -= Character.charCount(codePoint)
+ }
+ return substring(start, end)
+}
+
+private fun Int.isPastedUrlBoundaryCharacter(): Boolean =
+ Character.isWhitespace(this) ||
+ Character.isSpaceChar(this) ||
+ Character.getType(this) == Character.FORMAT.toInt()
diff --git a/data/src/main/java/com/streamvault/data/remote/stremio/StremioMapper.kt b/data/src/main/java/com/streamvault/data/remote/stremio/StremioMapper.kt
index b1adcae8..a888872b 100644
--- a/data/src/main/java/com/streamvault/data/remote/stremio/StremioMapper.kt
+++ b/data/src/main/java/com/streamvault/data/remote/stremio/StremioMapper.kt
@@ -13,7 +13,6 @@ import com.streamvault.domain.model.stremio.StremioProxyHeaders
import com.streamvault.domain.model.stremio.StremioResourceKind
import com.streamvault.domain.model.stremio.StremioStream
import com.streamvault.domain.model.stremio.StremioStreamBehaviorHints
-import com.streamvault.domain.model.stremio.StremioStreamKind
import com.streamvault.domain.model.stremio.StremioSubtitle
import com.streamvault.domain.model.stremio.StremioVideo
import kotlinx.serialization.json.JsonArray
@@ -26,11 +25,6 @@ import kotlinx.serialization.json.contentOrNull
internal fun StremioManifestDto.toDomain(): StremioManifest? {
val manifestId = id?.trim().orEmpty()
if (manifestId.isEmpty()) return null
- val manifestTypes = types.orEmpty()
- .map(StremioMediaType::fromTypeName)
- .filter { it != StremioMediaType.UNKNOWN }
- .distinct()
- val parsedResources = parseResources(resources)
return StremioManifest(
id = manifestId,
name = name?.trim()?.takeIf { it.isNotEmpty() } ?: manifestId,
@@ -38,16 +32,12 @@ internal fun StremioManifestDto.toDomain(): StremioManifest? {
description = description?.trim()?.takeIf { it.isNotEmpty() },
logo = logo?.trim()?.takeIf { it.isNotEmpty() },
background = background?.trim()?.takeIf { it.isNotEmpty() },
- types = manifestTypes,
- resources = parsedResources.map { resource ->
- if (resource.types.isEmpty() && manifestTypes.isNotEmpty()) {
- resource.copy(types = manifestTypes)
- } else {
- resource
- }
- },
+ types = types?.map(StremioMediaType::fromTypeName)
+ ?.filter { it != StremioMediaType.UNKNOWN }
+ ?.distinct(),
+ resources = parseResources(resources),
catalogs = parseCatalogs(catalogs),
- idPrefixes = idPrefixes.orEmpty().mapNotNull { it.trim().takeIf(String::isNotEmpty) }.distinct(),
+ idPrefixes = idPrefixes?.mapNotNull { it.trim().takeIf(String::isNotEmpty) }?.distinct(),
behaviorHints = behaviorHints?.toDomain() ?: StremioManifestBehaviorHints()
)
}
@@ -61,7 +51,8 @@ internal fun StremioManifestBehaviorHintsDto.toDomain(): StremioManifestBehavior
internal fun StremioCatalogResponseDto.toDomain(): StremioCatalogPage =
StremioCatalogPage(
metas = metas.orEmpty().mapNotNull { it.toDomain() },
- hasMore = hasMore ?: false
+ hasMore = hasMore,
+ rawItemCount = metas.orEmpty().size
)
internal fun StremioMetaPreviewDto.toDomain(): StremioMetaPreview? {
@@ -128,9 +119,11 @@ internal fun StremioStreamDto.toDomain(): StremioStream? {
fileIdx = fileIdx?.takeIf { it >= 0 },
externalUrl = externalUrl?.trim()?.takeIf { it.isNotEmpty() },
sources = sources.orEmpty().mapNotNull { it.trim().takeIf(String::isNotEmpty) },
+ subtitles = subtitles.orEmpty().mapNotNull { it.toDomain() },
behaviorHints = behaviorHints?.toDomain()
)
- return stream.takeIf { it.kind != StremioStreamKind.UNKNOWN }
+ // Keep recognizable-but-unsupported protocol rows visible to the picker as disabled entries.
+ return stream
}
internal fun StremioStreamBehaviorHintsDto.toDomain(): StremioStreamBehaviorHints =
@@ -164,7 +157,7 @@ private fun parseResources(resources: List<JsonElement>?): List<StremioManifestR
is JsonPrimitive -> element.contentOrNull
?.let(StremioResourceKind::fromResourceName)
?.takeIf { it != StremioResourceKind.UNKNOWN }
- ?.let { StremioManifestResource(kind = it) }
+ ?.let { StremioManifestResource(kind = it, isStringResource = true) }
is JsonObject -> {
val kind = StremioResourceKind.fromResourceName(element["name"].asString())
if (kind == StremioResourceKind.UNKNOWN) {
@@ -172,11 +165,11 @@ private fun parseResources(resources: List<JsonElement>?): List<StremioManifestR
} else {
StremioManifestResource(
kind = kind,
- types = element["types"].asStringList()
- .map(StremioMediaType::fromTypeName)
- .filter { it != StremioMediaType.UNKNOWN }
- .distinct(),
- idPrefixes = element["idPrefixes"].asStringList().distinct()
+ types = element["types"].asStringListOrNull()
+ ?.map(StremioMediaType::fromTypeName)
+ ?.filter { it != StremioMediaType.UNKNOWN }
+ ?.distinct(),
+ idPrefixes = element["idPrefixes"].asStringListOrNull()?.distinct()
)
}
}
@@ -225,8 +218,8 @@ private fun parseCatalogExtras(extra: JsonElement?): List<StremioCatalogExtraDef
private fun JsonElement?.asString(): String? =
(this as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf { it.isNotEmpty() }
-private fun JsonElement?.asStringList(): List<String> =
- (this as? JsonArray).orEmpty().mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf(String::isNotEmpty) }
+private fun JsonElement?.asStringListOrNull(): List<String>? =
+ (this as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.contentOrNull?.trim()?.takeIf(String::isNotEmpty) }
private fun JsonElement?.asBoolean(): Boolean = (this as? JsonPrimitive)?.booleanOrNull ?: false
diff --git a/data/src/main/java/com/streamvault/data/repository/StremioAddonRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/StremioAddonRepositoryImpl.kt
index 245a45b5..f57727ec 100644
--- a/data/src/main/java/com/streamvault/data/repository/StremioAddonRepositoryImpl.kt
+++ b/data/src/main/java/com/streamvault/data/repository/StremioAddonRepositoryImpl.kt
@@ -5,8 +5,19 @@ import com.streamvault.data.local.entity.StremioAddonEntity
import com.streamvault.data.remote.stremio.StremioAddonClient
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioCatalogPage
+import com.streamvault.domain.model.stremio.StremioCatalogQuery
+import com.streamvault.domain.model.stremio.StremioCatalogRef
+import com.streamvault.domain.model.stremio.StremioInstalledAddon
import com.streamvault.domain.model.stremio.StremioManifest
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaResolution
+import com.streamvault.domain.model.stremio.StremioResourceKind
+import com.streamvault.domain.model.stremio.StremioResourceResolution
+import com.streamvault.domain.model.stremio.StremioStream
+import com.streamvault.domain.model.stremio.StremioSubtitle
import com.streamvault.domain.repository.StremioAddonRepository
+import com.streamvault.domain.repository.StremioResourceResolver
import javax.inject.Inject
import javax.inject.Singleton
import kotlinx.coroutines.flow.Flow
@@ -15,7 +26,8 @@ import kotlinx.coroutines.flow.map
@Singleton
class StremioAddonRepositoryImpl @Inject constructor(
private val dao: StremioAddonDao,
- private val client: StremioAddonClient
+ private val client: StremioAddonClient,
+ private val resourceResolver: StremioResourceResolver
) : StremioAddonRepository {
override fun observeAddons(): Flow<List<StremioAddon>> =
@@ -26,6 +38,118 @@ class StremioAddonRepositoryImpl @Inject constructor(
override suspend fun getManifest(addonId: Long): StremioManifest? =
dao.getById(addonId)?.let { entity -> client.parseManifest(entity.manifestJson) }
+ override suspend fun fetchCatalog(
+ addonId: Long,
+ catalog: StremioCatalogRef,
+ query: StremioCatalogQuery
+ ): Result<StremioCatalogPage> {
+ val entity = dao.getById(addonId) ?: return Result.error("Addon is not installed")
+ if (!entity.enabled) return Result.error("This addon is disabled")
+ val catalogKey = catalog.settingsKey
+ if (!StremioCatalogSettingsCodec.decode(entity.catalogSettingsJson).let { it[catalogKey] ?: true }) {
+ return Result.error("This catalog is disabled")
+ }
+ val manifest = client.parseManifest(entity.manifestJson)
+ ?: return Result.error("Addon manifest could not be read")
+ val currentCatalog = manifest.catalogs.firstOrNull { it.settingsKey == catalogKey }
+ ?: return Result.error("This catalog is no longer available")
+ val supportedExtras = setOf("search", "genre", "skip")
+ val unsupportedRequired = currentCatalog.extras.firstOrNull {
+ it.isRequired && it.name.lowercase() !in supportedExtras
+ }
+ if (unsupportedRequired != null) {
+ return Result.error("This catalog requires an unsupported '${unsupportedRequired.name}' filter")
+ }
+ val missingRequired = currentCatalog.extras.firstOrNull { extra ->
+ if (!extra.isRequired) return@firstOrNull false
+ when (extra.name.lowercase()) {
+ "search" -> query.search.isNullOrBlank()
+ "genre" -> query.genre.isNullOrBlank()
+ "skip" -> query.skip == null
+ else -> false
+ }
+ }
+ if (missingRequired != null) {
+ val instruction = when (missingRequired.name.lowercase()) {
+ "search" -> "Enter a search before loading this catalog"
+ "genre" -> "Choose a genre before loading this catalog"
+ else -> "This catalog requires pagination support"
+ }
+ return Result.error(instruction)
+ }
+ return client.fetchCatalog(entity.installUrl, currentCatalog.type, currentCatalog.id, query)
+ }
+
+ override suspend fun resolveMeta(
+ catalogOriginAddonId: Long,
+ type: StremioMediaType,
+ exactId: String
+ ): StremioMetaResolution {
+ val candidates = resourceCandidates()
+ val ordered = resourceResolver.candidates(
+ addons = candidates,
+ kind = StremioResourceKind.META,
+ type = type,
+ exactId = exactId,
+ preferredAddonId = catalogOriginAddonId
+ )
+ return resourceResolver.resolveMeta(ordered, type, exactId) { addon ->
+ client.fetchMeta(addon.installUrl, type, exactId)
+ }
+ }
+
+ override suspend fun resolveStreams(
+ type: StremioMediaType,
+ exactId: String,
+ addonIds: Set<Long>?
+ ): StremioResourceResolution<StremioStream> {
+ val eligible = resourceResolver.candidates(
+ addons = resourceCandidates(),
+ kind = StremioResourceKind.STREAM,
+ type = type,
+ exactId = exactId,
+ addonIds = addonIds
+ )
+ return resourceResolver.resolveMany(eligible) { addon ->
+ client.fetchStreams(addon.installUrl, type, exactId)
+ }
+ }
+
+ override suspend fun resolveSubtitles(
+ type: StremioMediaType,
+ exactVideoId: String,
+ videoHash: String?,
+ videoSize: Long?,
+ filename: String?,
+ addonIds: Set<Long>?
+ ): StremioResourceResolution<StremioSubtitle> {
+ val eligible = resourceResolver.candidates(
+ addons = resourceCandidates(),
+ kind = StremioResourceKind.SUBTITLES,
+ type = type,
+ exactId = exactVideoId,
+ addonIds = addonIds
+ )
+ return resourceResolver.resolveMany(eligible) { addon ->
+ client.fetchSubtitles(
+ addon.installUrl,
+ type,
+ exactVideoId,
+ videoHash,
+ videoSize,
+ filename
+ )
+ }
+ }
+
+ private suspend fun resourceCandidates(): List<StremioInstalledAddon> = dao.getAll().asSequence()
+ .filter { it.enabled }
+ .mapNotNull { entity ->
+ val manifest = client.parseManifest(entity.manifestJson) ?: return@mapNotNull null
+ StremioInstalledAddon(entity.toDomain(), manifest)
+ }
+ .toList()
+
override suspend fun installAddon(installUrl: String): Result<StremioAddon> {
val snapshotResult = client.fetchManifestSnapshot(installUrl)
val snapshot = snapshotResult.getOrNull() ?: return Result.error(
diff --git a/data/src/main/java/com/streamvault/data/repository/StremioPlaybackHistoryRepositoryImpl.kt b/data/src/main/java/com/streamvault/data/repository/StremioPlaybackHistoryRepositoryImpl.kt
new file mode 100644
index 00000000..71d031c3
--- /dev/null
+++ b/data/src/main/java/com/streamvault/data/repository/StremioPlaybackHistoryRepositoryImpl.kt
@@ -0,0 +1,71 @@
+package com.streamvault.data.repository
+
+import com.streamvault.data.local.dao.StremioPlaybackHistoryDao
+import com.streamvault.data.local.entity.StremioPlaybackHistoryEntity
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
+import com.streamvault.domain.repository.StremioPlaybackHistoryRepository
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.map
+
+@Singleton
+class StremioPlaybackHistoryRepositoryImpl @Inject constructor(
+ private val dao: StremioPlaybackHistoryDao
+) : StremioPlaybackHistoryRepository {
+ override fun observeContinueWatching(limit: Int): Flow<List<StremioPlaybackHistory>> =
+ dao.observeContinueWatching(limit.coerceIn(1, MAX_CONTINUE_WATCHING_ITEMS))
+ .map { rows -> rows.map { it.toDomain() } }
+
+ override suspend fun get(contentKey: String): StremioPlaybackHistory? =
+ dao.get(contentKey)?.toDomain()
+
+ override suspend fun save(history: StremioPlaybackHistory): Result<Unit> = runCatching {
+ dao.upsert(history.toEntity())
+ }.fold(
+ onSuccess = { Result.success(Unit) },
+ onFailure = { Result.error("Stremio playback progress could not be saved", it) }
+ )
+
+ override suspend fun delete(contentKey: String): Result<Unit> = runCatching {
+ dao.delete(contentKey)
+ }.fold(
+ onSuccess = { Result.success(Unit) },
+ onFailure = { Result.error("Stremio playback history could not be removed", it) }
+ )
+
+ private fun StremioPlaybackHistoryEntity.toDomain() = StremioPlaybackHistory(
+ contentKey = contentKey,
+ mediaType = mediaType,
+ exactVideoId = exactVideoId,
+ parentSeriesId = parentSeriesId,
+ title = title,
+ posterUrl = posterUrl,
+ resumePositionMs = resumePositionMs,
+ totalDurationMs = totalDurationMs,
+ watched = isWatched,
+ lastWatchedAt = lastWatchedAt,
+ catalogOriginKey = catalogOriginKey,
+ streamOriginKeyHint = streamOriginKeyHint
+ )
+
+ private fun StremioPlaybackHistory.toEntity() = StremioPlaybackHistoryEntity(
+ contentKey = contentKey,
+ mediaType = mediaType,
+ exactVideoId = exactVideoId,
+ parentSeriesId = parentSeriesId,
+ title = title,
+ posterUrl = posterUrl,
+ resumePositionMs = resumePositionMs,
+ totalDurationMs = totalDurationMs,
+ isWatched = watched,
+ lastWatchedAt = lastWatchedAt,
+ catalogOriginKey = catalogOriginKey,
+ streamOriginKeyHint = streamOriginKeyHint
+ )
+
+ private companion object {
+ const val MAX_CONTINUE_WATCHING_ITEMS = 100
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistryTest.kt b/data/src/test/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistryTest.kt
index b799d36a..cb146f06 100644
--- a/data/src/test/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistryTest.kt
+++ b/data/src/test/java/com/streamvault/data/local/StreamVaultDatabaseMigrationRegistryTest.kt
@@ -27,5 +27,7 @@ class StreamVaultDatabaseMigrationRegistryTest {
assertThat(StreamVaultDatabaseMigrationRegistry.v75To76.single().endVersion).isEqualTo(76)
assertThat(StreamVaultDatabaseMigrationRegistry.v76To77.single().endVersion).isEqualTo(77)
assertThat(StreamVaultDatabaseMigrationRegistry.v77To78.single().endVersion).isEqualTo(78)
+ assertThat(StreamVaultDatabaseMigrationRegistry.v78To79.single().endVersion).isEqualTo(79)
+ assertThat(StreamVaultDatabaseMigrationRegistry.v79To80.single().endVersion).isEqualTo(80)
}
}
diff --git a/data/src/test/java/com/streamvault/data/preferences/StremioVisibilityPreferenceTest.kt b/data/src/test/java/com/streamvault/data/preferences/StremioVisibilityPreferenceTest.kt
new file mode 100644
index 00000000..e3a86623
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/preferences/StremioVisibilityPreferenceTest.kt
@@ -0,0 +1,48 @@
+package com.streamvault.data.preferences
+
+import android.content.Context
+import androidx.datastore.preferences.preferencesDataStoreFile
+import com.google.common.truth.Truth.assertThat
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import org.junit.After
+import org.junit.Before
+import org.junit.Test
+import org.junit.runner.RunWith
+import org.mockito.kotlin.mock
+import org.robolectric.RobolectricTestRunner
+import org.robolectric.RuntimeEnvironment
+
+@RunWith(RobolectricTestRunner::class)
+class StremioVisibilityPreferenceTest {
+ private lateinit var context: Context
+
+ @Before
+ fun setUp() {
+ context = RuntimeEnvironment.getApplication()
+ context.preferencesDataStoreFile("user_preferences").delete()
+ }
+
+ @After
+ fun tearDown() {
+ context.preferencesDataStoreFile("user_preferences").delete()
+ }
+
+ private fun repository() = PreferencesRepository(
+ context = context,
+ channelPreferenceDao = mock(),
+ searchHistoryDao = mock(),
+ corruptionRecovery = mock()
+ )
+
+ @Test
+ fun visibilityDefaultsAndPersists() = runBlocking {
+ val preferences = repository()
+ assertThat(preferences.hideStremioAddons.first()).isFalse()
+ val globalLevel = preferences.parentalControlLevel.first()
+ preferences.setHideStremioAddons(true)
+ assertThat(preferences.hideStremioAddons.first()).isTrue()
+ assertThat(preferences.parentalControlLevel.first()).isEqualTo(globalLevel)
+ assertThat(context.preferencesDataStoreFile("user_preferences").isFile).isTrue()
+ }
+}
diff --git a/data/src/test/java/com/streamvault/data/remote/stremio/StremioAddonClientTest.kt b/data/src/test/java/com/streamvault/data/remote/stremio/StremioAddonClientTest.kt
index 2a366316..13941392 100644
--- a/data/src/test/java/com/streamvault/data/remote/stremio/StremioAddonClientTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stremio/StremioAddonClientTest.kt
@@ -8,6 +8,9 @@ import com.streamvault.domain.model.stremio.StremioStreamKind
import java.io.InputStreamReader
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
+import okhttp3.Cookie
+import okhttp3.CookieJar
+import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
@@ -66,8 +69,7 @@ class StremioAddonClientTest {
assertThat(metaResource.types)
.containsExactly(StremioMediaType.MOVIE, StremioMediaType.SERIES)
val catalogResource = manifest.resources.first { it.kind == StremioResourceKind.CATALOG }
- assertThat(catalogResource.types)
- .containsExactly(StremioMediaType.MOVIE, StremioMediaType.SERIES)
+ assertThat(catalogResource.types).isNull()
assertThat(manifest.supportsResource(StremioResourceKind.STREAM, StremioMediaType.SERIES)).isTrue()
assertThat(manifest.supportsResource(StremioResourceKind.STREAM, StremioMediaType.CHANNEL)).isFalse()
assertThat(manifest.idPrefixes).containsExactly("tt")
@@ -91,6 +93,99 @@ class StremioAddonClientTest {
assertThat(seriesCatalog.extras.map { it.name }).containsExactly("search", "skip").inOrder()
}
+ @Test
+ fun `addon requests do not inherit app logging or cookies`() = runTest {
+ server.enqueue(MockResponse().setBody(fixture("stremio/fixtures/cinemeta_manifest.json")))
+ val inheritedRequests = mutableListOf<String>()
+ val appClient = OkHttpClient.Builder()
+ .addInterceptor(Interceptor { chain ->
+ inheritedRequests += chain.request().url.toString()
+ chain.proceed(chain.request())
+ })
+ .cookieJar(object : CookieJar {
+ override fun loadForRequest(url: okhttp3.HttpUrl): List<Cookie> = listOf(
+ Cookie.Builder().name("session").value("provider-secret")
+ .domain(url.host).path("/").build()
+ )
+
+ override fun saveFromResponse(url: okhttp3.HttpUrl, cookies: List<Cookie>) = Unit
+ })
+ .build()
+ val addonClient = StremioAddonClient(
+ okHttpClient = appClient,
+ json = Json { ignoreUnknownKeys = true; isLenient = true; explicitNulls = false }
+ )
+
+ val result = addonClient.fetchManifest(baseUrl())
+
+ assertThat(result.isSuccess).isTrue()
+ assertThat(inheritedRequests).isEmpty()
+ assertThat(server.takeRequest().getHeader("Cookie")).isNull()
+ }
+
+ @Test
+ fun `manifest preserves omitted and explicitly empty resource filters`() {
+ val manifest = client.parseManifest(
+ """
+ {
+ "id":"filter-fixture",
+ "types":["movie"],
+ "idPrefixes":[],
+ "resources":[
+ "stream",
+ {"name":"meta","types":[],"idPrefixes":[]},
+ {"name":"subtitles","types":["series"],"idPrefixes":["custom:"]}
+ ]
+ }
+ """.trimIndent()
+ )!!
+
+ val stringResource = manifest.resources.first { it.kind == StremioResourceKind.STREAM }
+ val emptyResource = manifest.resources.first { it.kind == StremioResourceKind.META }
+ val overriddenResource = manifest.resources.first { it.kind == StremioResourceKind.SUBTITLES }
+ assertThat(stringResource.types).isNull()
+ assertThat(stringResource.idPrefixes).isNull()
+ assertThat(emptyResource.types).isEmpty()
+ assertThat(emptyResource.idPrefixes).isEmpty()
+ assertThat(overriddenResource.types).containsExactly(StremioMediaType.SERIES)
+ assertThat(overriddenResource.idPrefixes).containsExactly("custom:")
+ assertThat(manifest.idPrefixes).isEmpty()
+ assertThat(manifest.supportsResource(StremioResourceKind.STREAM, StremioMediaType.MOVIE, "custom:1"))
+ .isFalse()
+ assertThat(manifest.supportsResource(StremioResourceKind.META, StremioMediaType.MOVIE, "tt123"))
+ .isFalse()
+ assertThat(manifest.supportsResource(StremioResourceKind.SUBTITLES, StremioMediaType.SERIES, "custom:1"))
+ .isTrue()
+ }
+
+ @Test
+ fun `object resource uses its own omitted prefix filter`() {
+ val manifest = client.parseManifest(
+ """
+ {
+ "id":"object-filter-fixture",
+ "types":["movie"],
+ "idPrefixes":["tt"],
+ "resources":[{"name":"meta","types":["movie"]}]
+ }
+ """.trimIndent()
+ )!!
+
+ assertThat(manifest.supportsResource(StremioResourceKind.META, StremioMediaType.MOVIE, "custom:1"))
+ .isTrue()
+ }
+
+ @Test
+ fun `unknown stream rows remain available for disabled picker presentation`() = runTest {
+ server.enqueue(MockResponse().setBody("""{"streams":[{"name":"Unsupported"}]}"""))
+
+ val result = client.fetchStreams(baseUrl(), StremioMediaType.MOVIE, "custom:1")
+
+ assertThat(result.isSuccess).isTrue()
+ assertThat(result.getOrNull()).hasSize(1)
+ assertThat(result.getOrNull()!!.single().kind).isEqualTo(StremioStreamKind.UNKNOWN)
+ }
+
@Test
fun `catalog page parses metas and hasMore`() = runTest {
server.enqueue(MockResponse().setBody(fixture("stremio/fixtures/catalog_movies_top.json")))
@@ -101,6 +196,7 @@ class StremioAddonClientTest {
assertThat(server.takeRequest().path).isEqualTo("/catalog/movie/top.json")
val page = result.getOrNull()!!
assertThat(page.hasMore).isTrue()
+ assertThat(page.rawItemCount).isEqualTo(3)
assertThat(page.metas).hasSize(2)
val first = page.metas.first()
assertThat(first.id).isEqualTo("tt0111161")
@@ -111,6 +207,19 @@ class StremioAddonClientTest {
assertThat(first.genres).containsExactly("Drama")
}
+ @Test
+ fun `catalog page preserves omitted hasMore and raw item count`() = runTest {
+ server.enqueue(MockResponse().setBody("""
+ {"metas":[{"id":"tt001","type":"movie"},{"type":"movie"}]}
+ """.trimIndent()))
+
+ val page = client.fetchCatalog(baseUrl(), StremioMediaType.MOVIE, "top").getOrNull()!!
+
+ assertThat(page.hasMore).isNull()
+ assertThat(page.rawItemCount).isEqualTo(2)
+ assertThat(page.metas).hasSize(1)
+ }
+
@Test
fun `catalog request encodes search genre and skip extras`() = runTest {
server.enqueue(MockResponse().setBody(fixture("stremio/fixtures/catalog_search.json")))
@@ -171,12 +280,13 @@ class StremioAddonClientTest {
assertThat(result.isSuccess).isTrue()
assertThat(server.takeRequest().path).isEqualTo("/stream/movie/tt0111161.json")
val streams = result.getOrNull()!!
- assertThat(streams).hasSize(4)
+ assertThat(streams).hasSize(5)
assertThat(streams.map { it.kind }).containsExactly(
StremioStreamKind.TORRENT,
StremioStreamKind.DIRECT,
StremioStreamKind.YOUTUBE,
- StremioStreamKind.EXTERNAL
+ StremioStreamKind.EXTERNAL,
+ StremioStreamKind.UNKNOWN
).inOrder()
val torrent = streams[0]
assertThat(torrent.infoHash).isEqualTo("abcdef1234567890abcdef1234567890abcdef12")
@@ -188,6 +298,13 @@ class StremioAddonClientTest {
assertThat(torrent.behaviorHints?.bingeGroup).isEqualTo("torrentio-1080p")
val direct = streams[1]
assertThat(direct.url).isEqualTo("https://cdn.example.test/movies/shawshank/1080p.mp4")
+ assertThat(direct.subtitles).containsExactly(
+ com.streamvault.domain.model.stremio.StremioSubtitle(
+ id = "inline-eng",
+ url = "https://cdn.example.test/subtitles/eng.srt",
+ lang = "eng"
+ )
+ )
assertThat(direct.behaviorHints?.proxyHeaders?.request?.get("Authorization"))
.isEqualTo("Bearer token123")
assertThat(streams[2].ytId).isEqualTo("6hB3S9bIaco")
@@ -214,12 +331,13 @@ class StremioAddonClientTest {
StremioMediaType.MOVIE,
"tt0111161",
videoHash = "abc123",
+ videoSize = 1234L,
filename = "The Shawshank Redemption.mkv"
)
assertThat(result.isSuccess).isTrue()
assertThat(server.takeRequest().path).isEqualTo(
- "/subtitles/movie/tt0111161/videoHash=abc123&filename=The%20Shawshank%20Redemption.mkv.json"
+ "/subtitles/movie/tt0111161/videoHash=abc123&videoSize=1234&filename=The%20Shawshank%20Redemption.mkv.json"
)
val subtitles = result.getOrNull()!!
assertThat(subtitles).hasSize(2)
diff --git a/data/src/test/java/com/streamvault/data/remote/stremio/StremioAddonUrlTest.kt b/data/src/test/java/com/streamvault/data/remote/stremio/StremioAddonUrlTest.kt
index 83eaf79c..4285b0b2 100644
--- a/data/src/test/java/com/streamvault/data/remote/stremio/StremioAddonUrlTest.kt
+++ b/data/src/test/java/com/streamvault/data/remote/stremio/StremioAddonUrlTest.kt
@@ -14,6 +14,14 @@ class StremioAddonUrlTest {
assertThat(location.manifestUrl).isEqualTo("https://v3-cinemeta.strem.io/manifest.json")
}
+ @Test
+ fun `cinemeta manifest url is accepted`() {
+ val location = StremioAddonUrl.parse("https://v3-cinemeta.strem.io/manifest.json")
+
+ assertThat(location).isNotNull()
+ assertThat(location!!.manifestUrl).isEqualTo("https://v3-cinemeta.strem.io/manifest.json")
+ }
+
@Test
fun `configured manifest path is preserved`() {
val location = StremioAddonUrl.parse("https://torrentio.strem.fun/qualityfilter=720p,av1/manifest.json")
@@ -21,6 +29,30 @@ class StremioAddonUrlTest {
assertThat(location!!.baseUrl).isEqualTo("https://torrentio.strem.fun/qualityfilter=720p,av1")
}
+ @Test
+ fun `clipboard direction marks around manifest url are ignored`() {
+ val location = StremioAddonUrl.parse(
+ "\u200F\uFEFF https://thepiratebay-plus.strem.fun/manifest.json\u200E\u200F "
+ )
+
+ assertThat(location).isNotNull()
+ assertThat(location!!.manifestUrl)
+ .isEqualTo("https://thepiratebay-plus.strem.fun/manifest.json")
+ }
+
+ @Test
+ fun `encoded configured path bytes round trip unchanged`() {
+ val location = StremioAddonUrl.parse(
+ "https://example.test/tenant%2Fprivate/quality%3D720p/manifest.json?token=secret"
+ )
+
+ assertThat(location).isNotNull()
+ assertThat(location!!.manifestUrl)
+ .isEqualTo("https://example.test/tenant%2Fprivate/quality%3D720p/manifest.json?token=secret")
+ assertThat(location.endpointUrl("/catalog/movie/top.json"))
+ .isEqualTo("https://example.test/tenant%2Fprivate/quality%3D720p/catalog/movie/top.json?token=secret")
+ }
+
@Test
fun `trailing slash and manifest suffix normalize to the same base`() {
assertThat(StremioAddonUrl.parse("https://example.test/addon/")!!.baseUrl)
diff --git a/data/src/test/java/com/streamvault/data/repository/StremioAddonRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/StremioAddonRepositoryImplTest.kt
index 0d58dc51..221bf388 100644
--- a/data/src/test/java/com/streamvault/data/repository/StremioAddonRepositoryImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/repository/StremioAddonRepositoryImplTest.kt
@@ -4,14 +4,19 @@ import com.google.common.truth.Truth.assertThat
import com.streamvault.data.local.dao.StremioAddonDao
import com.streamvault.data.local.entity.StremioAddonEntity
import com.streamvault.data.remote.stremio.StremioAddonClient
+import com.streamvault.domain.model.stremio.StremioCatalogQuery
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.repository.StremioResourceResolver
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.test.runTest
import kotlinx.serialization.json.Json
import okhttp3.OkHttpClient
+import okhttp3.mockwebserver.Dispatcher
import okhttp3.mockwebserver.MockResponse
import okhttp3.mockwebserver.MockWebServer
+import okhttp3.mockwebserver.RecordedRequest
import org.junit.After
import org.junit.Before
import org.junit.Test
@@ -37,7 +42,8 @@ class StremioAddonRepositoryImplTest {
explicitNulls = false
coerceInputValues = true
}
- )
+ ),
+ resourceResolver = StremioResourceResolver()
)
}
@@ -103,6 +109,200 @@ class StremioAddonRepositoryImplTest {
assertThat(result.errorMessageOrNull()).contains("500")
}
+ @Test
+ fun `catalog fetch sends zero skip when supported`() = runTest {
+ server.enqueue(manifestResponse("com.one", "One"))
+ val addon = repository.installAddon("${baseUrl()}/one").getOrNull()!!
+ server.enqueue(MockResponse().setBody("""{"metas":[]}"""))
+
+ val result = repository.fetchCatalog(
+ addonId = addon.id,
+ catalog = repository.getManifest(addon.id)!!.catalogs.single(),
+ query = StremioCatalogQuery(skip = 0)
+ )
+
+ assertThat(result.isSuccess).isTrue()
+ assertThat(server.takeRequest().path).isEqualTo("/one/manifest.json")
+ assertThat(server.takeRequest().path).isEqualTo("/one/catalog/movie/top/skip=0.json")
+ }
+
+ @Test
+ fun `cross addon resolution keeps catalog origin and partial stream results`() = runTest {
+ server.enqueue(
+ manifestWithResources(
+ "catalog",
+ "Catalog",
+ "\"catalog\",{\"name\":\"meta\",\"types\":[\"movie\"],\"idPrefixes\":[\"tt\"]}",
+ catalog = true
+ )
+ )
+ server.enqueue(
+ manifestWithResources(
+ "streamer",
+ "Streamer",
+ "{\"name\":\"stream\",\"types\":[\"movie\"],\"idPrefixes\":[\"tt\"]}"
+ )
+ )
+ server.enqueue(
+ manifestWithResources(
+ "broken-streamer",
+ "Broken Streamer",
+ "{\"name\":\"stream\",\"types\":[\"movie\"],\"idPrefixes\":[\"tt\"]}"
+ )
+ )
+ server.enqueue(
+ manifestWithResources(
+ "unrelated",
+ "Unrelated",
+ "{\"name\":\"stream\",\"types\":[\"movie\"],\"idPrefixes\":[\"kitsu\"]}"
+ )
+ )
+ server.enqueue(
+ manifestWithResources(
+ "disabled",
+ "Disabled",
+ "{\"name\":\"stream\",\"types\":[\"movie\"],\"idPrefixes\":[\"tt\"]}"
+ )
+ )
+
+ val catalog = repository.installAddon("${baseUrl()}/catalog").getOrNull()!!
+ val streamer = repository.installAddon("${baseUrl()}/streamer").getOrNull()!!
+ val brokenStreamer = repository.installAddon("${baseUrl()}/broken-streamer").getOrNull()!!
+ repository.installAddon("${baseUrl()}/unrelated")
+ val disabled = repository.installAddon("${baseUrl()}/disabled").getOrNull()!!
+ repository.setAddonEnabled(disabled.id, false)
+ repository.setCatalogEnabled(catalog.id, "movie:top", false)
+
+ val requestPaths = mutableListOf<String?>()
+ server.dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest): MockResponse {
+ requestPaths += request.path
+ return when (request.path) {
+ "/catalog/meta/movie/tt123.json" -> MockResponse().setBody(
+ """{"meta":{"id":"tt123","type":"movie","name":"Catalog metadata"}}"""
+ )
+ "/streamer/stream/movie/tt123.json" -> MockResponse().setBody(
+ """{"streams":[{"name":"Direct","url":"https://media.example/video.mp4"}]}"""
+ )
+ "/broken-streamer/stream/movie/tt123.json" -> MockResponse().setResponseCode(503)
+ else -> MockResponse().setResponseCode(404)
+ }
+ }
+ }
+
+ val metadata = repository.resolveMeta(catalog.id, StremioMediaType.MOVIE, "tt123")
+ val streams = repository.resolveStreams(StremioMediaType.MOVIE, "tt123")
+
+ assertThat(metadata.result?.source?.addonId).isEqualTo(catalog.id)
+ assertThat(metadata.result?.resource?.name).isEqualTo("Catalog metadata")
+ assertThat(streams.candidateCount).isEqualTo(2)
+ assertThat(streams.results.map { it.source.addonId }).containsExactly(streamer.id)
+ assertThat(streams.failures.map { it.source.addonId }).containsExactly(brokenStreamer.id)
+ assertThat(requestPaths).containsExactly(
+ "/catalog/meta/movie/tt123.json",
+ "/streamer/stream/movie/tt123.json",
+ "/broken-streamer/stream/movie/tt123.json"
+ )
+ }
+
+ @Test
+ fun `subtitle routing uses the exact episode id and video extras`() = runTest {
+ server.enqueue(
+ manifestWithResources(
+ "subtitle-addon",
+ "Subtitle Addon",
+ "{\"name\":\"subtitles\",\"types\":[\"series\"],\"idPrefixes\":[\"series:\"]}"
+ )
+ )
+ val subtitleAddon = repository.installAddon("${baseUrl()}/subtitle-addon").getOrNull()!!
+ server.takeRequest() // Consume the install request before inspecting the subtitle endpoint.
+ val exactVideoId = "series:custom:episode-04"
+ server.dispatcher = object : Dispatcher() {
+ override fun dispatch(request: RecordedRequest): MockResponse = MockResponse().setBody(
+ """{"subtitles":[{"id":"eng-1","url":"https://subs.example/episode.vtt","lang":"eng"}]}"""
+ )
+ }
+
+ val result = repository.resolveSubtitles(
+ type = StremioMediaType.SERIES,
+ exactVideoId = exactVideoId,
+ videoHash = "hash-1",
+ videoSize = 99L,
+ filename = "Episode One.mkv"
+ )
+
+ val request = server.takeRequest()
+ assertThat(request.path).isEqualTo(
+ "/subtitle-addon/subtitles/series/series:custom:episode-04/videoHash=hash-1&videoSize=99&filename=Episode%20One.mkv.json"
+ )
+ assertThat(result.results.single().source.addonId).isEqualTo(subtitleAddon.id)
+ assertThat(result.results.single().resource.lang).isEqualTo("eng")
+ }
+
+ @Test
+ fun `catalog fetch rejects missing required extras before network request`() = runTest {
+ server.enqueue(
+ MockResponse().setBody(
+ """
+ {
+ "id":"com.search.only","version":"1","name":"Search Only",
+ "resources":["catalog"],"types":["movie"],
+ "catalogs":[{"type":"movie","id":"search","extra":[{"name":"search","isRequired":true}]}]
+ }
+ """.trimIndent()
+ )
+ )
+ val addon = repository.installAddon("${baseUrl()}/search").getOrNull()!!
+ val catalog = repository.getManifest(addon.id)!!.catalogs.single()
+
+ val result = repository.fetchCatalog(addon.id, catalog, StremioCatalogQuery())
+
+ assertThat(result.isError).isTrue()
+ assertThat(result.errorMessageOrNull()).contains("Enter a search")
+ assertThat(server.requestCount).isEqualTo(1)
+ }
+
+ @Test
+ fun `catalog fetch rejects unsupported required extras before network request`() = runTest {
+ server.enqueue(
+ MockResponse().setBody(
+ """
+ {
+ "id":"com.date.only","version":"1","name":"Date Only",
+ "resources":["catalog"],"types":["movie"],
+ "catalogs":[{"type":"movie","id":"date","extra":[{"name":"date","isRequired":true}]}]
+ }
+ """.trimIndent()
+ )
+ )
+ val addon = repository.installAddon("${baseUrl()}/date").getOrNull()!!
+ val catalog = repository.getManifest(addon.id)!!.catalogs.single()
+
+ val result = repository.fetchCatalog(addon.id, catalog, StremioCatalogQuery())
+
+ assertThat(result.isError).isTrue()
+ assertThat(result.errorMessageOrNull()).contains("unsupported 'date'")
+ assertThat(server.requestCount).isEqualTo(1)
+ }
+
+ @Test
+ fun `disabled addons cannot fetch catalogs`() = runTest {
+ server.enqueue(manifestResponse("com.one", "One"))
+ val addon = repository.installAddon("${baseUrl()}/one").getOrNull()!!
+ val catalog = repository.getManifest(addon.id)!!.catalogs.single()
+ repository.setAddonEnabled(addon.id, false)
+
+ val result = repository.fetchCatalog(
+ addon.id,
+ catalog,
+ StremioCatalogQuery(search = "film", skip = 0)
+ )
+
+ assertThat(result.isError).isTrue()
+ assertThat(result.errorMessageOrNull()).contains("disabled")
+ assertThat(server.requestCount).isEqualTo(1)
+ }
+
@Test
fun `manifest without an id is rejected`() = runTest {
server.enqueue(MockResponse().setBody("""{"version":"1.0.0","name":"No Id","resources":["catalog"]}"""))
@@ -211,6 +411,24 @@ class StremioAddonRepositoryImplTest {
}
""".trimIndent()
)
+
+ private fun manifestWithResources(
+ id: String,
+ name: String,
+ resourcesJson: String,
+ catalog: Boolean = false
+ ): MockResponse = MockResponse().setBody(
+ """
+ {
+ "id":"$id",
+ "name":"$name",
+ "version":"1.0.0",
+ "types":["movie","series"],
+ "resources":[$resourcesJson],
+ "catalogs":${if (catalog) "[{\"type\":\"movie\",\"id\":\"top\",\"name\":\"Popular\"}]" else "[]"}
+ }
+ """.trimIndent()
+ )
}
private class FakeStremioAddonDao : StremioAddonDao {
diff --git a/data/src/test/java/com/streamvault/data/repository/StremioPlaybackHistoryRepositoryImplTest.kt b/data/src/test/java/com/streamvault/data/repository/StremioPlaybackHistoryRepositoryImplTest.kt
new file mode 100644
index 00000000..7d4365d5
--- /dev/null
+++ b/data/src/test/java/com/streamvault/data/repository/StremioPlaybackHistoryRepositoryImplTest.kt
@@ -0,0 +1,55 @@
+package com.streamvault.data.repository
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.data.local.dao.StremioPlaybackHistoryDao
+import com.streamvault.data.local.entity.StremioPlaybackHistoryEntity
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+
+class StremioPlaybackHistoryRepositoryImplTest {
+ @Test
+ fun `save and read retain exact identity and progress without stream urls`() = runTest {
+ val dao = FakeStremioPlaybackHistoryDao()
+ val repository = StremioPlaybackHistoryRepositoryImpl(dao)
+ val history = StremioPlaybackHistory(
+ contentKey = "stremio:global:series-episode:tt12345:1:2",
+ mediaType = "series",
+ exactVideoId = "tt12345:1:2",
+ parentSeriesId = "tt12345",
+ title = "Episode 2",
+ posterUrl = "https://images.example.test/poster.jpg",
+ resumePositionMs = 45_000L,
+ totalDurationMs = 900_000L,
+ catalogOriginKey = "a".repeat(64),
+ streamOriginKeyHint = "b".repeat(64)
+ )
+
+ assertThat(repository.save(history).isSuccess).isTrue()
+ assertThat(repository.get(history.contentKey)).isEqualTo(history)
+ assertThat(dao.row?.exactVideoId).isEqualTo("tt12345:1:2")
+ assertThat(dao.row?.resumePositionMs).isEqualTo(45_000L)
+ }
+}
+
+private class FakeStremioPlaybackHistoryDao : StremioPlaybackHistoryDao {
+ private val rows = MutableStateFlow<List<StremioPlaybackHistoryEntity>>(emptyList())
+ val row: StremioPlaybackHistoryEntity? get() = rows.value.firstOrNull()
+
+ override fun observeContinueWatching(limit: Int): Flow<List<StremioPlaybackHistoryEntity>> =
+ rows.asStateFlow()
+
+ override suspend fun get(contentKey: String): StremioPlaybackHistoryEntity? =
+ rows.value.firstOrNull { it.contentKey == contentKey }
+
+ override suspend fun upsert(entity: StremioPlaybackHistoryEntity) {
+ rows.value = rows.value.filterNot { it.contentKey == entity.contentKey } + entity
+ }
+
+ override suspend fun delete(contentKey: String) {
+ rows.value = rows.value.filterNot { it.contentKey == contentKey }
+ }
+}
diff --git a/data/src/test/resources/stremio/fixtures/streams_movie.json b/data/src/test/resources/stremio/fixtures/streams_movie.json
index e59b39ec..4a2b877d 100644
--- a/data/src/test/resources/stremio/fixtures/streams_movie.json
+++ b/data/src/test/resources/stremio/fixtures/streams_movie.json
@@ -20,6 +20,9 @@
"name": "Premium",
"title": "1080p direct",
"url": "https://cdn.example.test/movies/shawshank/1080p.mp4",
+ "subtitles": [
+ {"id": "inline-eng", "url": "https://cdn.example.test/subtitles/eng.srt", "lang": "eng"}
+ ],
"behaviorHints": {
"proxyHeaders": {
"request": {
diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md
index 6f5177b7..3bbd8130 100644
--- a/docs/CHANGELOG.md
+++ b/docs/CHANGELOG.md
@@ -6,6 +6,8 @@ All notable product changes are recorded in this document.
### Added
+- Clarified Extensions navigation and plugin installation actions, added Stremio onboarding, and replaced its blanket parental gate with an independent Hide Stremio Add-ons option under Privacy (off by default).
+- Added native Stremio add-on support with manifest URL installation, catalog browsing, cross-addon metadata/stream/subtitle resolution, direct and debrid HTTP(S) playback, and resume history. Plugins and Stremio Add-ons are grouped under the Extensions navigation item.
- Added temporary automatic quality reduction for supported adaptive streams when decoding struggles, with gradual restoration and respect for manual quality choices.
- Added AVC/H.264 fallback for eligible HEVC episodes, preserving playback position, audio, subtitles, and episode history.
diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md
index 8307f58c..7d230e5a 100644
--- a/docs/PLUGIN_API.md
+++ b/docs/PLUGIN_API.md
@@ -171,13 +171,15 @@ Messages:
| 8 | `MSG_GET_CONFIGURATION_VALUES` | Return `configuration_values_json`. |
| 9 | `MSG_SET_CONFIGURATION_VALUES` | Persist `configuration_values_json`. |
| 10 | `MSG_RUN_CONFIGURATION_ACTION` | Run `configuration_action_id`. |
+| 11 | `MSG_STOP_PLAYBACK` | Release a prepared playback session identified by `output_url`. |
For `playback.prepare` and `cast.rewriteUrl`, StreamVault only sends the message
to plugins whose manifest already owns the URL (see `playbackUrlSchemes` /
`playbackUrlHosts` above). Within that narrowed set, plugins should still set
`handled=false` when the specific URL is not one they can actually prepare.
StreamVault then continues with other matching enabled plugins or the original
-URL.
+URL. For `magnet:` inputs, StreamVault fails closed when no enabled plugin
+handles the link; the unresolved magnet is never passed to the player.
`MSG_REWRITE_CAST_URL` is Cast-specific. StreamVault sends the stream context that
made direct receiver playback unsafe:
@@ -218,6 +220,15 @@ player. When `handled=true` and `success=true`, the plugin can return:
}
```
+For magnet playback, the host accepts a successful plugin response only when
+`output_url` is an HTTP URL on `127.0.0.1` with an explicit port. The plugin
+should bind its streaming server to loopback only. Torrent companion plugins
+should honor a `so` file-selection parameter when present. When playback ends,
+StreamVault sends `MSG_STOP_PLAYBACK` with the exact `output_url` returned by
+that plugin; the plugin should stop the matching session and release its
+foreground-service resources. Stop delivery is best effort, so the plugin must
+also clean up expired or abandoned sessions itself.
+
`scheme` accepts `widevine`, `playready`, `clearkey`, or their platform UUID
aliases (`com.widevine.alpha`, `com.microsoft.playready`, `org.w3.clearkey`).
For `SMOOTH_STREAMING` + `clearkey`, StreamVault normalizes the ISML
diff --git a/docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md b/docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md
new file mode 100644
index 00000000..00ceb724
--- /dev/null
+++ b/docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md
@@ -0,0 +1,74 @@
+# Stremio-compatible Add-ons acceptance checklist
+
+Use this checklist for the Android TV UI, D-pad, and normal-use pass after the
+direct/debrid and P6 companion implementations are handed over. Run it on the
+dedicated `Codex_StremioProvider_Validation_20261013` AVD or another clean profile. The
+public Cinemeta add-on is catalog/metadata only; stream and subtitle checks need
+separately installed add-ons that provide those resources. Use a legal direct
+or debrid HTTP(S) stream source for the direct-playback checks. Torrent/magnet
+acceptance has its own checklist in `STREMIO_TORRENT_P6_ACCEPTANCE.md`.
+## Navigation and install
+
+- [ ] Extensions keeps the same heading on both tabs. Compact tabs distinguish
+ the active section from D-pad focus and do not enlarge when focused.
+- [ ] Plugin installation explicitly says APK or APK URL; Stremio installation
+ explicitly asks for a manifest URL. Each section explains what it provides.
+- [ ] With no add-ons installed, the Stremio-compatible Add-ons page shows an onboarding message and a
+ visible Add Stremio-compatible add-on action without requiring navigation to Manage.
+
+- [ ] The top navigation has one Extensions item; its focused tabs switch between
+ Plugins and Stremio-compatible Add-ons and Back returns to the prior content.
+- [ ] Install Cinemeta with `https://v3-cinemeta.strem.io/manifest.json`, then
+ confirm the manager displays the add-on and its catalogs.
+- [ ] Add a stream-capable add-on from its manifest URL. Confirm duplicate,
+ malformed, unavailable, and configuration-required URLs give a useful result.
+- [ ] Confirm Manage displays only the add-on server origin, not URL userinfo,
+ path, query, or fragment. Disable/enable, reorder, and remove the add-on.
+- [ ] Reopen the app and confirm retained add-ons and manager settings persist.
+
+## Browse and choose a stream
+
+- [ ] Browse an enabled catalog, move focus across cards, open an item, and use
+ Back to return with focus and scroll position intact.
+- [ ] Try catalog search and genre filters where offered. Load additional items
+ and confirm paging ends without duplicated or endlessly repeated cards.
+- [ ] Open an item whose metadata comes from a different add-on than its catalog.
+ Confirm the detail page keeps the catalog provenance and shows stream rows
+ from enabled stream add-ons.
+- [ ] Test no-stream, unsupported-stream, partial-add-on-failure, retry, and
+ parental-control states. Confirm one failing add-on does not hide other results.
+
+## Playback and history
+
+- [ ] Play a direct MP4 stream and an HLS stream. Confirm playback starts, seek
+ works, and Back returns to a usable detail or browse screen.
+- [ ] If available, try a stream requiring request headers. Confirm playback
+ works internally and the credentials do not appear in UI or logs.
+- [ ] Open the subtitle picker with inline and add-on-provided subtitles. Select
+ a track, then switch episodes and confirm the old episode's results do not
+ remain selected or appear in the new episode.
+- [ ] Stop and reopen an item from Stremio progress/history. Confirm the app
+ resolves a fresh stream and resumes near the saved position.
+- [ ] Without the Torrent plugin enabled, confirm magnet rows show the clear
+ missing-plugin or disabled-plugin message. With it enabled, use
+ `STREMIO_TORRENT_P6_ACCEPTANCE.md` for torrent playback, seek, and teardown.
+ Cast must reject add-on-origin-scoped headers rather than send them to a
+ receiver. Stremio external-player handoff is not part of v1.
+
+## Privacy and visibility — revised during user acceptance (2026-10-14)
+
+Implemented in the UI/UX cleanup; user acceptance is pending. These criteria replace
+the previous blanket Stremio parental-control gate.
+
+- [ ] Stremio-compatible Add-ons are open by default, including browsing, installation,
+ and playback, independently of the global parental-control level.
+- [ ] Settings → Privacy offers "Hide Stremio-compatible add-ons", off by default.
+- [ ] Enabling the option hides Stremio-compatible Add-ons; disabling it restores access.
+- [ ] The visibility choice persists after restarting the app.
+- [ ] Existing global parental-control settings continue to work for their
+ other content without being changed to access Stremio-compatible Add-ons.
+
+Record the device/profile, add-on names and capabilities, steps that failed, and
+the screen/remote action where focus or expected behavior diverged. Redact
+configured URLs, tokens, cookies, and authorization headers from any notes or
+screenshots.
diff --git a/docs/STREMIO_ADDONS_HANDOFF.md b/docs/STREMIO_ADDONS_HANDOFF.md
index 87642cc5..0b9e3b75 100644
--- a/docs/STREMIO_ADDONS_HANDOFF.md
+++ b/docs/STREMIO_ADDONS_HANDOFF.md
@@ -1,11 +1,72 @@
# Stremio addons — continuation handoff
-Review update (2026-10-11): read `STREMIO_ADDONS_PLAN_REVIEW.md` before continuing.
-The implementation plan records the correct 78→79 migration. Follow-up work fixed
-the missing `StremioManifestResource` test import and rejects manifests marked
-`configurationRequired`; the latter has repository test coverage. Fresh unit and
-emulator smoke results are below. The review still tracks cross-addon routing,
-playback identity/privacy, subtitles, parental-control, and torrent-contract work.
+User acceptance correction (2026-10-14), implemented; user acceptance pending: Stremio
+Add-ons must be open by default, independent of the global parental-control
+level. Add Settings → Privacy → "Hide Stremio Add-ons", off by default.
+This replaces the blanket parental gate documented in the historical results
+below. The updated debug APK is installed on emulator-5558. Track
+the new acceptance criteria in `STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md`.
+
+Working agreement: the user owns manual UI/UX and emulator acceptance testing.
+The agent implements changes and runs build/code checks, then hands over the
+build. Do not continue manual emulator testing unless the user asks.
+
+UI cleanup implements a stable Extensions heading, compact fixed-scale tabs,
+plugin-specific APK/URL action labels, and Stremio onboarding with a visible
+Add action. The hide preference is independent of global parental controls,
+off by default, and retained in DataStore. The temporary hide choice used
+during agent checks was returned to off; global parental settings are intact.
+Build and code checks passed (30 Stremio, 63 Settings, 165 app unit tests,
+plus the focused visibility preference test). Four existing plugin UI checks
+passed before the user clarified testing ownership. Plugin golden assets were
+re-recorded; their subsequent comparison was not run. User acceptance items
+remain unchecked.
+
+P6 implementation is complete. The Stremio stream picker constructs a validated
+magnet URI from `infoHash`, tracker sources, and `fileIdx`; the plugin manager
+requires an enabled scheme-owning handler, rejects non-loopback plugin outputs,
+and sends best-effort stop IPC when playback closes. The separate companion
+repository at `D:\antigravity-scratch\streamvault-torrent-plugin` contains the
+libtorrent engine, loopback byte-range server, plugin IPC service, configuration
+Activity, tests, and a successful debug APK build. JVM tests and APK assembly
+pass. The companion source is committed locally at `9ac943c` (branch `main`, no
+remote configured). Real torrent playback, seeking, replay, and teardown have not been tested;
+the user owns that manual acceptance pass in `STREMIO_TORRENT_P6_ACCEPTANCE.md`.
+
+Continuation update (2026-10-12): P0–P5 are implemented in this worktree. P1 is
+committed at `e96ce49e`; P2–P5 and the Extensions navigation follow-up remain
+uncommitted. Unit tests and debug assembly pass. P4 direct MP4 playback and
+history/resume were smoke-tested. The synthetic HLS fixture raised transient
+network EOFs over local HTTP/1.0, but the same playlist and segments completed
+over HTTP/1.1 on the same host port; validate with a real third-party addon
+endpoint before classifying this as a player defect. A remote HLS VOD smoke also
+passed through the local Stremio fixture, as recorded below. P5 inline subtitle
+discovery and the picker were smoke-tested. Cross-addon subtitle playback is now
+verified on isolated API 36 `emulator-5556`: the fresh `tt7654327` item exposed
+the German track from the independent subtitle-only addon, and its VTT cue
+rendered while the player remained healthy. At that point the remaining v1
+gates were a real third-party addon HLS/DASH child-resource check, provider
+playback, and header-dependent cast/external-player regression. No suitable
+public-domain third-party HLS addon was found. The install-URL storage/export/
+removal policy is documented, Manage shows only addon server origins, and D-pad
+focus through Extensions and its sub-tabs is verified. See
+`STREMIO_ADDONS_PLAN_REVIEW.md`.
+
+Continuation update (2026-10-13): provider playback now passes on a dedicated
+clean Android TV API 36 AVD using the local V11 fixture. HLS played through a
+145-second health/position-advance hold; 61 screenshots at two-second cadence
+span 120.26 seconds with 60 distinct hashes because the synthetic VOD loops at
+120 seconds. Media session was PLAYING with `error=null` during capture, and
+sanitized logs show HLS prepare, first frame, playlist/segment reads, and no
+retry, fatal error, stuck timeout, or MPEG-TS fallback. Progressive MP4 also
+reached first frame. Cleanup passed and the fixture provider row count is zero.
+This is provider-fixture VOD validation, not a real provider or live-TV result.
+The real third-party addon HLS/DASH child-request check remains open: the
+official Public Domain Movies addon returns torrents, the Archive.org addon
+returns direct files and its old host is down, and the community Public Domain
+Foreign Movies manifest URL returns 404; its source contains no HLS playlist
+references. The header-dependent cast/external-player regression also remains
+open.
Copy this whole block into a new session working in the worktree.
@@ -14,33 +75,89 @@ Copy this whole block into a new session working in the worktree.
Continue the StreamVault Stremio addon feature. Work only in:
`D:\antigravity-scratch\iptv-player\.worktrees\stremio-addons` (branch `feature/stremio-addons`, based on `develop` @ 540ec30c). Read `docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md` first. P1 was committed after its verification; check the current branch history for the commit.
-Important: this branch's Room DB version is 78 (not 81 — that number in the plan belongs to the `codex/stalker-sync-improvements` branch). The migration added here is 78→79.
+Important: the worktree now uses Room DB version 80. It includes the historical
+78→79 addon-registry migration and the new 79→80 Stremio playback-history
+migration. A separate emulator profile with a version-81 database is still not a
+valid target for this branch; do not clear shared emulator data to work around it.
## Done and verified
-- P0 (protocol client): `data/src/main/java/com/streamvault/data/remote/stremio/` (`StremioAddonClient`, `StremioAddonUrl`, `StremioAddonDtos`, `StremioMapper`) + domain models `domain/src/main/java/com/streamvault/domain/model/stremio/`; 22 unit tests green.
-- P1 data layer: `StremioAddonEntity`, `StremioAddonDao`, `FeatureMigrationsV78To79`, `StremioAddonRepository` (domain) + `StremioAddonRepositoryImpl`, `StremioCatalogSettingsCodec`, `StremioAddonClient.fetchManifestSnapshot/parseManifest`; DI wired in `DatabaseModule`/`RepositoryModule`; schema export `data/schemas/com.streamvault.data.local.StreamVaultDatabase/79.json`; `StremioAddonRepositoryImplTest` now has 10 passing tests including configuration-required rejection; `StreamVaultDatabaseMigrationTest` — 43 tests green on emulator-5554 (API 36), including the new `migrate78To79_...` test.
+- P0 (protocol client): `data/src/main/java/com/streamvault/data/remote/stremio/` (`StremioAddonClient`, `StremioAddonUrl`, `StremioAddonDtos`, `StremioMapper`) + domain models `domain/src/main/java/com/streamvault/domain/model/stremio/`; the latest focused client/URL run has 24 passing tests.
+- P1 data layer: `StremioAddonEntity`, `StremioAddonDao`, `FeatureMigrationsV78To79`, `StremioAddonRepository` (domain) + `StremioAddonRepositoryImpl`, `StremioCatalogSettingsCodec`, `StremioAddonClient.fetchManifestSnapshot/parseManifest`; DI wired in `DatabaseModule`/`RepositoryModule`; schema export `data/schemas/com.streamvault.data.local.StreamVaultDatabase/79.json`; repository tests covered configuration-required rejection (14 now passing after P2 coverage); `StreamVaultDatabaseMigrationTest` — 43 tests green on emulator-5554 (API 36), including the new `migrate78To79_...` test.
- P1 verification update: `:app:testDebugUnitTest` passed 163 tests; `:feature:stremio:testDebugUnitTest` passed 6; focused data tests passed 34 (`StremioAddonClientTest` 13, `StremioAddonUrlTest` 9, `StremioAddonRepositoryImplTest` 10, migration registry 2). `:app:assembleDebug` succeeded. A broader data run hit unrelated download mock-server and Google Drive backup test failures; the focused Stremio rerun passed.
-- Emulator smoke: installed `com.streamvault.app.debug` on `Television_1080p` (API 36, temporary read-only session), opened Addons, and installed `https://v3-cinemeta.strem.io/manifest.json`. Screenshot: `addons.png`. `Television_4K_2` already has a version-81 database, so this version-79 branch crashes there on the unsupported 81→79 downgrade; its data was left untouched.
-- P1 nav/UI: `AppDestination.Addons`; `AppTopLevelDestination.ADDONS`; route codec/adapters/startup resolver/shell nav (`Icons.Default.Extension`, `R.string.nav_addons`); new module `feature:stremio` (build.gradle.kts, `StremioRoutePatterns.ADDONS="addons"`, `registerStremioGraph`, `StremioScaffoldContent`, `AddonsViewModel`, `AddonsScreen`, `AddonsViewModelTest`); wired in `AppNavHost` via `appStremioScaffold`; settings exhaustive `when`s updated; `nav_addons` added to app/settings strings and 25 app locale `strings_missing.xml` files. Unit and emulator smoke validation are complete.
+- P1 emulator smoke: installed `com.streamvault.app.debug` on isolated `Television_1080p` (API 36) and installed `https://v3-cinemeta.strem.io/manifest.json`. Screenshot: `addons.png`. At that point the branch was at DB v79. The current worktree is v80; `Television_4K_2` was later found at DB v82 and remains incompatible, so its data was left untouched.
+- P1 nav/UI: `AppDestination.Addons` and its route remain distinct; the global navbar now uses one `AppTopLevelDestination.EXTENSIONS` item with focusable Plugins / Stremio Add-ons tabs. Legacy saved top-level `plugins` and `addons` values migrate to `extensions`, while plugin/addon startup destinations remain available. The new `feature:stremio` module (`StremioRoutePatterns.ADDONS="addons"`, `AddonsViewModel`, `AddonsScreen`) is wired through `AppNavHost`; the APK Plugins screen is still separate. Unit and emulator smoke validation for P1 are complete.
+- P2 catalog browsing and Extensions navigation polish are implemented but uncommitted: Browse and Manage tabs, enabled-addon/catalog rows, search/genre and required-extra gates, nullable `hasMore`, raw response counts and 100-item skip pagination, duplicate-page/page-count guards, cancellation of stale requests, refresh-aware cache identity, 200-page/5-minute LRU cache, errors/retry/empty/loading states, and TV card focus border. Seven `StremioCatalogBrowseViewModelTest` cases and six existing Addons ViewModel tests pass. Focused data tests pass (14 client, 10 URL, 14 repository); `:app:assembleDebug` passes.
+- P2 TV smoke: on isolated `Television_1080p` API 36 (`emulator-5556`), installed the latest APK, installed Cinemeta through Manage, loaded its Popular catalog/posters through Browse, and navigated by D-pad to a focused card. The catalog heading renders with readable foreground contrast. The shared `emulator-5554` was not used for this smoke.
+- Extensions navigation follow-up (2026-10-12): one Extensions navbar/settings item now opens focusable Plugins and Stremio Add-ons tabs; the plugin and addon routes and startup landing choices remain distinct. Legacy top-level `plugins`/`addons` preferences normalize to `extensions`. `:domain:test`, `:app:testDebugUnitTest`, `:feature:system:testDebugUnitTest`, `:feature:stremio:testDebugUnitTest`, `:feature:system:compileDebugAndroidTestKotlin`, and `:app:assembleDebug` pass. Updated plugin golden screenshots; both plugin screenshot tests pass on the isolated read-only `Codex_Trakt` API 36 emulator. The full System golden class still has four existing welcome/download pixel mismatches on that AVD.
+- P3 meta/detail and cross-addon resource routing (2026-10-12): implemented `StremioResourceResolver` for enabled addons with resource/type/exact-ID-prefix matching, catalog-origin-first metadata fallback, stable bounded stream/subtitle fan-out, attributed partial results, retry, and cancellation. The detail page preserves catalog provenance and exact `meta.videos[].id` values, shows unsupported stream rows with reasons, and creates a typed playback reference for eligible direct URLs.
+- P4 playback/history (2026-10-12): direct/debrid playback uses the normal player pipeline with selected media headers scoped to media requests; magnet casting is blocked with an explicit unsupported state; addon progress lives in `stremio_playback_history` at Room version 80 and reopens through fresh stream resolution rather than stored URLs. Migration, history, playback-identity, header-sanitization, cast, and player tests pass. The migration instrumentation suite passed all 45 tests on isolated `Television_1080p` (API 36), including 79→80. On isolated API 36 `emulator-5556`, synthetic MP4 playback and resume/history reopening worked. The synthetic 120-second HLS asset raised `unexpected end of stream` at media positions 67.878s and 115.874s when served by the local HTTP/1.0 fixture; the player retried and recovered each time. The same playlist and segments served over HTTP/1.1 on the same host port completed at 120.007s with 51 screenshots (38 unique frames), all 31 datasource reads complete, and no retry/error. Treat the failure as a local fixture transport issue pending a real Stremio addon HLS smoke. This VOD check is not live-TV validation.
+- P4 remote HLS VOD smoke (2026-10-12): the public Mux Big Buck Bunny HLS sample (`https://test-streams.mux.dev/x36xhzz/x36xhzz.m3u8`) played through the local Stremio fixture on isolated API 36 `emulator-5556`. Captured 61 screenshots at a two-second cadence; all 61 frame hashes were unique. Logs showed HLS prepare and first-frame success, and media session was `PLAYING` at position 213,376 ms with `error=null` when capture ended. There were two startup audio-underrun warnings and no retry, fatal error, stuck timeout, or MPEG-TS fallback. This validates remote HLS VOD playback; a real third-party addon endpoint and its redirect/header behavior remain open. This is not live-TV validation.
+- P5 subtitles (2026-10-12): inline `stream.subtitles` are parsed and carried ephemerally with the playback request; addon subtitle resources are loaded lazily from the player picker, including `videoHash`, `videoSize`, and `filename` extras, language mapping, URL filtering/deduplication, and external-track injection. A focused overlay test fixed the no-embedded-track dead end by keeping the CC action visible when Stremio subtitle sources exist. Focused subtitle, player, data, app tests and debug assembly pass. On isolated API 36 `emulator-5556`, the picker showed the German resource from the independent subtitle-only addon for `tt7654327`; selecting it logged `addExternalSubtitle language=de`, rendered “Fixture German subtitle,” and media session remained `PLAYING` with `error=null`.
+- Parental-control gate (2026-10-13): because addon catalogs and meta do not provide a dependable age rating, the whole Stremio feature is treated as protected content. Off allows access; Locked and Private require the existing PIN once per app session; Hidden blocks Stremio content and install. Private also omits Stremio continue-watching from the aggregate surface. Both browse and item routes are gated before their screens (and network requests) are created; install, catalog fetch, metadata, and stream actions also fail closed. Unit tests cover all four levels and blocked install/catalog/detail requests. TV smoke on isolated `Television_1080p` API 36 (`emulator-5556`) verified Hidden denial, Locked and Private PIN prompts, rejection of a wrong PIN, successful unlock, re-lock after changing levels, and Off access without a PIN. The original 1,750-byte preferences file was restored and its SHA-256 verified; `emulator-5554` and `Television_4K_2` were not used.
+- Header/privacy review (2026-10-13): selected stream headers are validated and applied by an isolated playback client with cookies, authenticators, and cache disabled. The network interceptor adds them only for the selected media origin; an existing MockWebServer test confirms a cross-origin 302 does not forward Authorization. Playback history contains no stream URL or request headers. Credential policy: keep configured install URLs in app-private Room so addon configuration survives app restarts; do not log, back up, or include addon records in manual export; show only the origin in Manage; Remove deletes the active addon row, while disabling retains it. Room does not add app-level encryption, so protection relies on the Android app sandbox and device storage encryption. HLS/DASH child-resource and cast/external-player behavior still need verification with a suitable addon or fixture.
+- Public-domain addon source check (2026-10-13): the official Public Domain Movies addon serves torrent `infoHash` streams for public-domain catalog items (verified with `tt0012349`, `tt0063350`, and `tt0013257`); torrent playback is deferred to P6, so this cannot validate direct HLS playback. The maintained Internet Archive addon source generates `archive.org/download/...` file URLs for AVI/MP4/MKV/WMV/MOV/M4V and does not emit HLS playlists; its previously published Baby-Beamup host no longer resolves. The community Public Domain Foreign Movies repository advertises public-domain/free-to-view sources, but its published `now.sh` manifest currently returns 404 and a source scan found no `.m3u8` stream references. No suitable public-domain third-party HLS addon was found. Keep the third-party-addon HLS gate open; do not count either local-fixture VOD smoke as satisfying it. Sources: [official Stremio addon index](https://github.com/Stremio/stremio-official-addons/blob/master/index.json), [Public Domain Foreign Movies source](https://github.com/jaruba/stremio-public-domain-foreign/blob/master/index.js), [Public Domain Foreign Movies README](https://github.com/jaruba/stremio-public-domain-foreign/blob/master/README.md).
+- TV navigation regression check (2026-10-13): on isolated API 36 `emulator-5556`, D-pad focus moved from Home to the single Extensions navbar item, then between Plugins and Stremio Add-ons tabs. The Stremio Add-ons content correctly displayed the Hidden parental-control gate. The emulator's restored 1,750-byte preferences file still matches its original SHA-256; no settings were changed.
+- Provider playback fixture validation (2026-10-13): created a separate clean Android TV API 36 AVD, `Codex_StremioProvider_Validation_20261013` (`emulator-5558`), and ran instrumentation directly with `adb` so Gradle did not uninstall app data. `V11 HLS Adaptive Fixture` resolved as HLS (H.264/AAC, 640x360, 2.5 Mbps; TTFF 1,122 ms); local server events included the master and child playlist plus `segment_000.ts` and `segment_001.ts`. The probe held HLS playback for 145 seconds and checked every two seconds that state stayed READY, `isPlaying` stayed true, and position advanced. Concurrent capture took 61 screenshots at a two-second cadence over 120.26 seconds; 60 hashes were unique because the 120-second synthetic VOD loop repeats its first frame at the end. At about 105 seconds, media session was PLAYING at position 105,101 ms with `error=null`. Logs contain HLS prepare/first-frame and progressing hold entries, with no retry, fatal error, stuck timeout, or MPEG-TS fallback. The progressive fixture also reached first frame (H.264/AAC, 640x360; TTFF 354 ms). A cleanup instrumentation test passed, and a read-only database check found zero `stremio_addons` rows after cleanup. This is VOD fixture validation, not live-TV validation or a third-party addon test.
+- Playback-test environment incident (2026-10-13): `:app:connectedDebugAndroidTest` was run without a serial filter, so Gradle targeted both connected devices. The isolated `Television_1080p` run passed; `Television_4K_2` failed because its database is version 82 while this worktree expects version 80. Gradle removed `com.streamvault.app.debug` from `emulator-5556` after the run. The app was reinstalled and its Room v80 database and saved preferences were restored from local snapshots, but uninstalling destroyed Android Keystore keys: the restored provider rows' encrypted credentials now fail decryption and must be re-entered. The original local M3U cache was not in the available backups. Do not use `emulator-5556` for provider playback until credentials are re-entered, do not clear `emulator-5554`/`Television_4K_2`, and avoid connected Gradle tasks without an explicit single-device filter. The fresh `emulator-5558` was used for the fixture check instead.
+- Credential display regression fix (2026-10-13): the Manage-addon row now renders only the parsed server origin, omitting credentials in URL userinfo, path, query, and fragment. `StremioAddonOriginLabelTest` covers configured secrets, default/custom ports, IPv6, and malformed URLs. The focused Stremio unit test and `:app:assembleDebug` pass.
+- Cast privacy and usability follow-up (2026-10-13): Stremio playback retains an origin marker even with no request headers so its isolated network client is still used. `CastMediaRequestFactory` now blocks casting only when a Stremio stream actually has scoped headers; headerless direct streams can use the normal cast path. Focused playback tests cover both outcomes, including `blocks addon origin scoped headers from cast requests` and `allows headerless addon media to use the normal cast path`.
+- Final local code gate (2026-10-13): `:feature:playback:testDebugUnitTest --tests com.streamvault.feature.playback.cast.CastMediaRequestFactoryTest :app:testDebugUnitTest :feature:stremio:testDebugUnitTest :domain:test :data:testDebugUnitTest :app:assembleDebug` passed. The latest APK was installed with `adb -s emulator-5558 install -r ...` and launched on the dedicated clean Android TV API 36 AVD; `com.streamvault.app.debug/MainActivity` resumed successfully. No connected Gradle task was run.
+- P3 verification: `:domain:test --tests com.streamvault.domain.repository.StremioResourceResolverTest`, focused Stremio data tests (`StremioAddonClientTest`, `StremioAddonRepositoryImplTest`), `:feature:stremio:testDebugUnitTest`, `:app:testDebugUnitTest`, and `:app:assembleDebug` passed. A fresh `:feature:stremio:testDebugUnitTest :app:assembleDebug` run also passed after a TV-discovered detail-text contrast fix.
+- P3 TV smoke: on read-only isolated `Television_1080p` API 36 (`emulator-5556`), installed Cinemeta, browsed Popular, opened the Unabomber detail page, confirmed metadata provenance and readable text, then requested streams and confirmed the clear no-enabled-stream-addon state. This smoke did not validate playback or a real multi-addon stream list; cross-addon behavior is covered by repository/domain/feature tests. The shared `emulator-5554` was not used.
## Immediate next steps
1. P1 unit verification, emulator install smoke, and the reviewed P1 commit are
- complete; see the results above.
-2. Design cross-addon resource resolution and a compatible stable playback
- identity before beginning P2/P3, following `STREMIO_ADDONS_PLAN_REVIEW.md`.
+ complete; see the results above. Commit: `e96ce49e`.
+2. P2 and P3 are implemented and verified against AD-10 and AD-9. Their worktree
+ changes, including the Extensions navigation follow-up, remain uncommitted.
+3. The direct/debrid v1 implementation and local verification are complete.
+ The parental PIN smoke is complete on isolated API 36 `emulator-5556` at
+ Off, Locked, Private, and Hidden levels. D-pad navigation through Extensions
+ and its Plugins/Stremio Add-ons tabs is also verified. No suitable
+ public-domain third-party HLS addon was found: the official public-domain
+ catalog returns torrent streams, Archive.org returns direct files, and the
+ community foreign-movies addon has a dead manifest host and no HLS URLs in
+ its source. Keep the real-addon HLS gate open until an eligible endpoint is
+ available; the remote sample and provider fixture through local servers are
+ complete. The credential storage/export/removal policy is now documented and
+ the Manage screen displays only the server origin. Scoped-header casting is
+ intentionally rejected and unit-tested; headerless direct streams use the
+ normal cast path. External-player handoff is outside direct/debrid v1. The
+ only remaining external qualification is real-addon HLS/DASH child-resource
+ playback; no suitable public-domain endpoint was found. The independent
+ subtitle-only fixture smoke is complete. Playback checks use VOD only; do not
+ report them as live-TV validation. The latest debug APK is installed and
+ launched on clean Android TV API 36 `emulator-5558` for the manual UI/usage
+ pass in `docs/STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md`.
+4. P6 implementation is complete; the user still owns the real-torrent manual
+ acceptance pass in `STREMIO_TORRENT_P6_ACCEPTANCE.md`. Home/global search
+ remains optional.
## Environment gotchas
- Windows PowerShell; use `.\gradlew.bat`. Long builds: run detached `Start-Process cmd.exe -ArgumentList "/c",".\gradlew.bat ... > log 2>&1" -PassThru -NoNewWindow` and poll the log — don't block in foreground >2 min.
- Worktree has its own `local.properties` (sdk.dir=C:\Users\David\AppData\Local\Android\Sdk).
- Emulator `emulator-5554` (API 36) is connected; instrumented: `:data:connectedDebugAndroidTest -Pandroid.testInstrumentationRunnerArguments.class=com.streamvault.data.local.StreamVaultDatabaseMigrationTest`.
-- `Television_4K_2` emulator may hold database version 81 from another branch; use a clean/read-only emulator profile for this 78→79 branch smoke test rather than clearing shared app data.
+- `Television_4K_2` has database version 82 while this worktree is at 80; use a clean/read-only emulator profile for this version-80 worktree rather than clearing shared app data.
+- The 2026-10-13 unfiltered `:app:connectedDebugAndroidTest` also targeted `Television_4K_2` and uninstalled the app from `emulator-5556`; app-private backups do not restore Android Keystore keys. Existing provider credentials there cannot decrypt until re-entered. Use serial-targeted `adb shell am instrument` on the clean `emulator-5558` for fixture work, and do not clear data on `emulator-5554` or `Television_4K_2`.
- Data module uses OkHttp + kotlinx.serialization DTOs; domain has no serialization — keep that split.
-- Cosmetic compiler warning: `@StringRes` on data-class property (KT-73255) in `AddonsViewModel` — can switch to `@param:StringRes`.
+- Cosmetic compiler warning: `hiltViewModel()` has moved to `androidx.hilt.lifecycle.viewmodel.compose`; the current build succeeds.
- Do not reuse provider URL policies for addon streams (relevant in P4).
## Remaining phases (details in the plan doc)
-P2 catalog browsing UI, P3 meta + stream picker, P4 playback integration (+ magnet cast guard), P5 subtitles, P6 torrent companion plugin, P7 polish. Do not start until P1 is verified and committed.
+Direct/debrid v1 implementation (P0–P5 and required P7) and local regression
+checks are complete. Cross-addon subtitles, remote HLS VOD through the local
+Stremio fixture, provider fixture playback, the parental gate, and Extensions
+navigation have passed their recorded checks. The latest debug APK is installed
+and launched on clean Android TV API 36 `emulator-5558`, ready for the manual
+UI/usage pass. A real third-party addon HLS/DASH and child-resource smoke remains
+external qualification because no suitable public-domain addon endpoint was
+found. Scoped-header casting is intentionally rejected and unit-tested;
+headerless direct addon streams use the normal cast path. External-player
+handoff is outside direct/debrid v1. P6 implementation is complete and its
+real-torrent acceptance remains with the user; optional Home/global search
+remains deferred. P1 is verified and
+committed; P2–P5, the parental gate, and Extensions navigation remain uncommitted.
diff --git a/docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md b/docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md
index 867547b5..ff8238e6 100644
--- a/docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md
+++ b/docs/STREMIO_ADDONS_IMPLEMENTATION_PLAN.md
@@ -1,7 +1,64 @@
# Stremio addon support implementation plan
-Status: P0 and P1 implemented; P1 unit and emulator smoke verification complete. Plan reviewed
-2026-10-11; see `STREMIO_ADDONS_PLAN_REVIEW.md` for required additions and gates.
+Status (2026-10-16): P0–P6 implementation and required P7 polish are complete;
+P6 real-torrent playback acceptance is pending the user. The companion source
+and debug APK live in the separate `D:\antigravity-scratch\streamvault-torrent-plugin`
+repository. P1–P6 code/build verification is recorded in
+`STREMIO_ADDONS_HANDOFF.md`. P4 MP4/history and provider fixture
+playback checks passed. The synthetic HLS VOD fixture initially failed around
+68 seconds over local HTTP/1.0; the same asset completed over HTTP/1.1 on the
+same host port. A public Mux HLS sample passed 61 screenshots at a two-second
+cadence through the local Stremio fixture, with unique frames and a healthy
+media session. The provider HLS fixture then passed a 145-second advancing
+playback hold, with 61 screenshots across 120.26 seconds (60 unique hashes
+because the fixture loops at 120 seconds), healthy media-session state, and no
+retry/fatal/stuck/fallback logs. These local fixtures do not close the external
+real third-party addon HLS/DASH child-resource qualification. Scoped addon
+headers are intentionally rejected for casting, while headerless direct streams
+use the normal cast path; external-player handoff is outside v1. P5 inline and
+independent subtitle-addon playback smoke passed on the isolated API 36 emulator;
+the German WebVTT cue rendered from the subtitle-only addon.
+The parental PIN gate is now smoke-tested at all four levels on TV, and D-pad
+focus through Extensions and its Plugins/Stremio Add-ons tabs passes. Credential
+storage/export/removal policy is documented, and Manage shows only addon server
+origins. No suitable public-domain third-party HLS addon was found: the official
+catalog returns torrents, the Archive.org addon returns direct files, and the
+community Foreign Movies manifest host is down and its source has no HLS
+playlist references. All direct/debrid v1 implementation and local regression
+gates are complete. A real-addon HLS/DASH child-request smoke remains external
+qualification. Scoped-header cast rejection is unit-tested; headerless direct
+streams use the normal cast path. External-player handoff is outside v1.
+Plan reviewed 2026-10-11; see `STREMIO_ADDONS_PLAN_REVIEW.md` for external
+qualification and user acceptance.
+
+## Current handoff status (2026-10-16)
+
+- **User acceptance correction (2026-10-14), implemented; user acceptance pending:** UI/UX
+ cleanup makes Stremio Add-ons open by default, independently of the
+ global parental-control level. Uses a separate Settings → Privacy →
+ "Hide Stremio Add-ons" option, off by default. This supersedes the blanket
+ Stremio parental gate described below; those sections record the prior
+ implementation and its historical verification. The user owns manual UI/UX
+ acceptance testing; agent checks should be limited to builds and code tests.
+- [x] P0–P5 direct/debrid Stremio support is implemented; required P7 polish is
+ implemented. Verification details are in `STREMIO_ADDONS_HANDOFF.md`.
+- [x] P6 implementation is complete: the host routes validated magnet URIs to
+ an enabled scheme-owning plugin, restricts plugin output to loopback, and
+ sends best-effort playback-stop IPC. The separate companion repository
+ contains the libtorrent engine, byte-range server, configuration Activity,
+ and debug APK. Unit tests and APK build pass; real-torrent emulator acceptance
+ is pending the user. See `STREMIO_TORRENT_P6_ACCEPTANCE.md`.
+- [x] Debug APK `1.0.19-debug` was built from this worktree, installed with
+ replace/retain-data on `emulator-5558`, and `MainActivity` was launched on the
+ dedicated Android TV API 36 AVD `Codex_StremioProvider_Validation_20261013`.
+- [ ] User UI/UX and normal-use acceptance pass is pending; use
+ `STREMIO_ADDONS_ACCEPTANCE_CHECKLIST.md` and leave its items unchecked until
+ the user exercises them.
+- [ ] Real third-party addon HLS/DASH child-request qualification remains open.
+- [ ] User end-to-end torrent playback acceptance is pending; use
+ `STREMIO_TORRENT_P6_ACCEPTANCE.md`. The agent has not installed the companion
+ APK or tested a real torrent.
+
Prepared 2026-10-10 against source
revision `540ec30c` (`develop`), branch `feature/stremio-addons`, worktree
`.worktrees/stremio-addons`.
@@ -148,18 +205,21 @@ companion APK in its own repository, not in this repo or the main APK. The host
learns nothing about torrents beyond "a `magnet:` URL may be resolved by an
enabled plugin".
-### AD-4: New top-level "Addons" destination
+### AD-4: One top-level "Extensions" destination
-Add `AppDestination.Addons`, `AppTopLevelDestination.ADDONS` ("addons",
-`AppLandingDestination.ADDONS`), route constant, shell nav item, and startup
-landing mapping. Users can reorder/hide it like existing tabs
-(`AppTopLevelDestination.defaultOrder`), and redirect startup to it. The addon
-manager UI is part of the Addons surface, not the APK Plugins screen; the torrent
-plugin is still managed as an APK plugin under Plugins.
+Keep separate `AppDestination.Plugins` and `AppDestination.Addons` routes and
+startup landing options, but show one `AppTopLevelDestination.EXTENSIONS`
+destination in the global navigation. Its screen has focusable in-page tabs for
+native APK Plugins and Stremio Add-ons, so both features remain distinct without
+using two top-level slots. Migrate saved `plugins` and `addons` top-level
+navigation values to `extensions`; retain Plugins and Stremio Add-ons as
+separate startup choices while Extensions is visible. The addon manager remains
+inside Stremio Add-ons, and torrent plugins remain managed as APK plugins.
Files: `domain/.../model/AppTopLevelDestination.kt`,
`domain/.../model/AppLandingDestination.kt`,
`app/.../navigation/AppRouteCodec.kt`, `app/.../navigation/AppNavigationAdapters.kt`,
`app/.../ui/components/shell/AppShellNavigation.kt`,
+`core/ui/.../components/shell/ExtensionsSectionTabs.kt`,
`app/.../navigation/StartupNavigationResolver.kt`, `app/.../navigation/AppNavHost.kt`.
### AD-5: Dedicated addon-stream ingress policy
@@ -184,7 +244,12 @@ and never forward addon-supplied headers to non-addon hosts.
loopback URLs — without a cast-capable plugin the cast attempt fails as
`UNSUPPORTED`, which is acceptable and should surface a clear message.
- External player handoff: only resolved http(s) URLs are offered; the external
- launcher allowlist already excludes `magnet`.
+ launcher allowlist already excludes `magnet`. Stremio external-player handoff
+ is outside direct/debrid v1 because the launcher cannot preserve origin-scoped
+ request headers.
+- Casting rejects Stremio media with addon-supplied request headers, since the
+ receiver cannot preserve their origin scope. Headerless direct streams use the
+ normal cast path. This behavior is covered by unit tests.
### AD-7: Phase gating — direct/debrid first, torrents at P6
@@ -195,10 +260,99 @@ main repository for as long as possible.
### AD-8: Content identity, resume, and history
-Use a stable identity: `stremio:{type}:{id}` (e.g. `stremio:series:tt1234:1:2` for
-episodes). This keeps resume/history working across addons and re-installs and is
-the future key for Watch Next integration. Do not map addon items onto synced
-catalog ids.
+Do not use `PlaybackHistory` for addon items. That table requires a real provider
+row through a foreign key, numeric `contentId`/`providerId`, and its replay
+navigation currently reuses the stored `streamUrl`. Those assumptions do not fit
+remote Stremio IDs, and a stored direct/debrid URL may expire.
+
+Add a `StremioPlaybackHistory` model/repository and a Room table keyed by a
+canonical string `contentKey`. The table stores the exact Stremio item/video ID,
+type, parent series ID where applicable, display metadata, resume position,
+duration, watched state, and catalog-origin namespace. It does not store a
+playable URL, stream headers, or addon response bodies. A selected stream's addon
+namespace may be kept as a preference hint, but never as content identity.
+
+Identity rules:
+
+- Preserve protocol IDs byte-for-byte after the existing trim validation; do
+ not synthesize episode IDs from season/episode numbers. The `meta.videos[].id`
+ value is the episode's request ID; retain the parent `meta.id` separately.
+- Recognize only validated IMDb IDs (`tt` followed by digits) as cross-addon
+ identities: `stremio:global:{type}:{exact-id}`. Episode keys use the exact
+ `video.id` under `series-episode`; the parent series key remains separate.
+- Namespace every other ID by the catalog-origin install identity:
+ `stremio:addon:{source-key}:{type}:{exact-id}`. `source-key` is a
+ domain-separated SHA-256 fingerprint of the persisted configured manifest
+ URL (preserving raw encoded path and query bytes), never a numeric playback
+ ID. This survives uninstall/reinstall of that
+ same configured addon without storing a credential-bearing URL in history;
+ do not log the fingerprint or configured URL. Different addon installs with
+ colliding custom IDs remain separate.
+- Keep `catalogOrigin`, `metaOrigin`, and selected `streamOrigin` distinct.
+ Switching stream providers for a global ID preserves progress. A custom ID
+ stays scoped to its catalog origin even when another addon can answer the
+ same prefix.
+
+Add an optional typed Stremio playback reference to `PlayerNavigationRequest`.
+The player uses it to read/write addon progress through the Stremio history
+repository; it does not fabricate numeric provider/content IDs. History replay
+routes back through the Addons feature, resolves fresh metadata and streams, and
+shows the picker unless a prior stream choice can be safely revalidated. For a
+global IMDb ID, reinstalled/other eligible addons may provide fresh streams. For
+a custom ID, try its origin first and keep the item unavailable until that
+source is reinstalled if no eligible metadata/stream source can resolve it.
+Keep an Addons-owned Continue Watching row in v1; integrating the existing
+provider-only Watch Next/history surfaces is a later explicit project.
+
+### AD-9: Resource routing across installed addons
+
+Use a single `StremioResourceResolver` for meta, stream, and subtitle requests.
+Its candidate input is the enabled installed-addon snapshot, resource kind,
+Stremio type, exact requested ID, and optional preferred origin. Catalog
+selection controls only which catalog rows are shown; disabling a catalog does
+not suppress that addon's meta/stream/subtitle capability. A disabled addon is
+never a candidate.
+
+Match manifests using protocol filters, preserving missing versus explicitly
+empty arrays in the parsed model. A string resource uses manifest-level `types`
+and optional `idPrefixes`; an object resource uses its resource-level type
+filter (falling back to manifest-level types only when omitted) and its own
+optional `idPrefixes`. Omitted prefixes mean any ID; an explicitly empty prefix
+list matches no IDs. `catalog` is routed only through the catalog declaration,
+not by ID-prefix matching. Compare prefixes against the exact request ID.
+
+For meta, query the eligible catalog-origin addon first, then remaining eligible
+addons in installed order. Empty and failed responses fall through; cancellation
+propagates. If no meta succeeds, keep the catalog preview usable. A movie may
+still request streams using its item ID; a series without `videos` stays
+preview-only and cannot invent episode IDs.
+
+For streams and subtitles, fan out to eligible enabled addons with bounded
+concurrency (maximum four in flight). Preserve installed order while merging
+results, attach addon attribution to each row, expose partial errors/retry per
+addon, and cancel the fan-out when item or screen scope changes. Apply
+`idPrefixes` to the exact movie ID or exact episode `video.id`, never to the
+parent series ID by assumption. Subtitle requests use the protocol's video ID
+and carry available hash/size/filename separately.
+
+### AD-10: Catalog page and cache contract
+
+Preserve optional `hasMore` as nullable and retain raw response count before
+filtering/deduplication. A catalog advertises `skip` before the UI offers
+pagination. Request 100 raw items per page; when `hasMore` is absent, continue
+only after a full raw page. When present, honor it, but guard against repeated
+page fingerprints and impose a per-session page cap. Advance `skip` by raw
+response count, not the number of renderable cards. Never paginate a catalog
+without `skip`.
+
+Required extras must be satisfied before making a request. V1 supports `search`,
+`genre`, and `skip`; a required unknown extra disables that catalog row with a
+clear unsupported-requirement message. Search-only catalogs wait for a nonblank
+query. Reset pagination and stale-request ownership on query/filter changes.
+Keep the P2 cache bounded to 200 pages with a five-minute TTL; key it by
+configured-addon fingerprint, catalog type/id, normalized search/genre, and
+skip. Invalidate affected entries on addon removal, manifest refresh, or catalog
+setting changes.
## Phases
@@ -206,12 +360,12 @@ catalog ids.
| --- | --- | --- | --- |
| P0 | Protocol client + models | Done | Domain models (manifest/catalog/meta/stream/subtitle), lenient DTO mapping, URL normalization (`stremio://` → https, configured paths, query preservation) and endpoint builders, `StremioAddonClient` with bounded responses and fixture-based tests — 22 tests passing (`StremioAddonClientTest`, `StremioAddonUrlTest`) |
| P1 | Persistence + addon manager | Implemented and verified | Room migration 78 → 79 (`stremio_addons`) with `MigrationTestHelper` coverage and schema export per `docs/DATABASE_MIGRATION_INVARIANTS.md`; add/remove/enable/reorder/catalog-select; configuration-required manifests rejected with a clear message; unit tests and emulator install smoke pass. Remaining release concerns are tracked in `docs/STREMIO_ADDONS_PLAN_REVIEW.md`. |
-| P2 | Catalog browsing | Planned | Addons screen with per-addon catalog rows, pagination (`skip`), genre filter, catalog search, loading/empty/error states, D-pad focus pass on TV |
-| P3 | Meta + stream picker | Planned | Movie and series meta pages (videos → seasons/episodes), stream list rendering name/title/description/behaviorHints, unsupported-kind rows marked, selection hands a play request to the player |
-| P4 | Playback integration | Planned | Direct http/https streams play through `PlayerPreparationCoordinator` with headers/UA from the addon when declared; resume/history on `stremio:` ids; cast guard for magnet; clear "needs torrent plugin" state |
-| P5 | Subtitles | Planned | Addon subtitles fetched lazily in the player, language mapping from 3-letter codes, wired via `PlayerEngine.addExternalSubtitle` (`player/.../PlayerEngine.kt:104`), respects existing subtitle style/preferences |
-| P6 | Torrent companion plugin | Planned | Separate repo/APK: libtorrent4j engine + loopback HTTP streaming server; `playbackUrlSchemes: ["magnet"]`; `MSG_PREPARE_PLAYBACK` resolves `magnet:` → `http://127.0.0.1:<port>/...`; config Activity with buffer/speed/status; end-to-end emulator validation with real torrent-backed addon |
-| P7 | Polish + integration options | Planned | Parental filtering stance for addon content, startup destination wiring, optional Home row / global search fan-out, docs (`docs/PLUGIN_API.md` magnet appendix, this plan updated to Done), CHANGELOG entries |
+| P2 | Catalog browsing | Implemented and verified | Browse/Manage tabs with enabled per-addon catalog rows; nullable `hasMore`, raw-count 100-item pagination only when `skip` is advertised, required `search`/`genre` gating and unsupported-extra states, stale-request cancellation, refresh-aware bounded cache, loading/empty/error states, and visible D-pad focus on TV. Seven browse ViewModel tests pass; Cinemeta catalog fetch and TV card-focus smoke pass on API 36. |
+| P3 | Meta + stream picker | Implemented and verified | Catalog cards open a detail page with provenance-first metadata fallback, preview-only behavior, exact episode IDs, attributed cross-addon stream rows, bounded partial fan-out and per-addon retry, visible unsupported stream kinds, and a typed player handoff. Focused domain, data, and feature tests plus app unit tests and debug assembly pass. API 36 TV smoke verified Cinemeta detail/provenance and the no-stream-provider state; it did not validate playback. |
+| P4 | Playback integration | Implemented; fixture playback verified | Direct/debrid streams use the existing player preparation path with media headers scoped to playback requests; Room v80 stores Stremio progress without URLs or headers; resume/history reopening resolves fresh streams; magnet cast/playback states are explicit. Tests, MP4/history smoke, and all 45 migration instrumentation tests pass on isolated API 36, including 79→80. Synthetic HLS completed at 120 seconds over HTTP/1.1; HTTP/1.0 serving produced transient EOFs. Remote Mux HLS passed through the local Stremio fixture. On a clean dedicated API 36 AVD, a provider HLS fixture passed a 145-second advancing hold and 61 screenshots over 120.26 seconds (60 unique frames due to the fixture loop); progressive MP4 reached first frame. This is fixture VOD coverage. A real third-party addon HLS/DASH and child-resource smoke remains external qualification because no suitable public-domain addon was found. Same-origin scoped headers are applied by the playback policy, and cross-origin redirect removal is integration-tested. Cast rejects scoped addon headers but allows headerless direct streams; external-player handoff is outside v1. |
+| P5 | Subtitles | Implemented; partial emulator verification | Inline and addon subtitles are carried to the player, addon resources load lazily, request extras include hash/size/filename, language codes map to Android locales, and external tracks use `PlayerEngine.addExternalSubtitle`. The CC picker remains available for Stremio subtitles even when the stream has no embedded text track. Tests/build and independent subtitle-only addon playback smoke pass. |
+| P6 | Torrent companion plugin | Implementation complete; user acceptance pending | Host: validated `infoHash`/tracker/file-index conversion, scheme-owned plugin prepare, clear missing/unhandled plugin errors, loopback-only output validation, and best-effort `MSG_STOP_PLAYBACK`. Separate repo/APK: libtorrent engine, loopback HTTP range streaming server, `playbackUrlSchemes: ["magnet"]`, and configuration Activity with buffer/speed/status/stop/clear controls. Unit tests and debug build pass. User still needs to verify real torrent playback, seeking, replay, and teardown with a torrent-backed addon. |
+| P7 | Required polish + optional integrations | Implemented; optional Home/global search deferred | Conservative parental gate is implemented, unit-tested, and smoke-tested on TV at Off/Locked/Private/Hidden; Private omits Stremio continue-watching from the aggregate. Extensions and the Plugins/Stremio Add-ons landing destinations are wired. README, handoff, plan review, changelog, and the user acceptance checklist document the feature and its limitations. Optional Home/global search remains deferred. |
Effort estimate: P0–P5 ≈ 5–6 weeks for a shippable direct/debrid v1; P6 adds
≈ 4–8 weeks (torrent engine quality on TV hardware is the dominant risk); P7
@@ -230,8 +384,8 @@ New module `feature:stremio` (add to `settings.gradle.kts`), following the
Data layer:
-- `data/.../local/` — `stremio_addons` entity, DAO, database version bump
- (`STREAM_VAULT_DATABASE_VERSION` → 79) and `78 → 79` migration, schema export.
+- `data/.../local/` — `stremio_addons` and `stremio_playback_history` entities,
+ Room version 80, migrations `78 → 79` and `79 → 80`, and schema exports.
- `data/.../stremio/` — `StremioAddonRepository`, `StremioCatalogClient` (HTTP),
response models, bounded cache.
@@ -302,10 +456,23 @@ existing plugin API; the host needs zero torrent-specific code.
schema JSON export committed, `PRAGMA foreign_key_check` on the new table.
- P2–P3: viewmodel/repository tests with a fake client; D-pad focus checks on
emulator for the new screens (TV-first).
-- P4: playback validation on emulator with screenshots — direct stream from a
- fixture addon plays to first frame and keeps progressing; resume restores
- position; magnet without plugin shows the explicit state (no engine start).
-- P5: subtitle selection test using `ExternalSubtitlePlayback` paths.
+- P4: emulator smoke confirmed direct MP4 playback and history/resume. The
+ synthetic HLS asset completed for 120 seconds over HTTP/1.1 on the same host
+ port; local HTTP/1.0 serving produced transient network EOFs. A remote Mux HLS
+ sample played through the local Stremio fixture for 61 screenshots at a
+ two-second cadence (61 unique hashes), with HLS prepare/first-frame logs and a
+ healthy session. A separate provider HLS fixture reached first frame and
+ advanced for 145 seconds; 61 screenshots over 120.26 seconds had 60 unique
+ hashes because the synthetic source loops at 120 seconds. Media session was
+ PLAYING with `error=null`; logs showed HLS playlist/segment reads without retry,
+ fatal error, stuck timeout, or MPEG-TS fallback. Progressive fixture MP4 also
+ reached first frame. This remains fixture VOD evidence. Verify a real
+ third-party addon endpoint and its redirect/header behavior before closing
+ that gate. Confirm magnet-without-plugin does not start the engine.
+- P5: tests cover inline/addon subtitle conversion and external playback paths.
+ Emulator smoke confirmed inline English discovery and selected a German track
+ from an independent subtitle-only addon; its WebVTT cue rendered during playback.
+ Episode-switching subtitle isolation remains a regression check.
- P6: end-to-end on emulator with the torrent plugin APK: magnet → plugin prepare
→ first frame; seek forward/back; plugin stop tears the session down; capture
log evidence analogous to the AGENTS.md live playback validation discipline
@@ -321,23 +488,31 @@ existing plugin API; the host needs zero torrent-specific code.
| Legal exposure for torrent support | Takedown/abuse reports | Engine only in separate plugin APK/repo; main repo has no torrent code; document posture |
| TV hardware limits for torrent streaming | Poor playback | Buffer/peer caps, file selection heuristics, clear errors; validate on 4K TV emulator and real device before calling P6 done |
| Room migration mistakes | Data loss | Follow `DATABASE_MIGRATION_INVARIANTS.md`; migration tests + schema export as a hard gate |
-| Adult content via addon catalogs | Parental controls bypass | P7 filtering stance: per-addon disable + adult catalog/meta flag handling; decide before enabling Home/search integration |
+| Adult content via addon catalogs | Parental controls bypass | Treat all unrated Stremio content as protected; gate install, catalogs, details, playback, and history through the existing parental PIN policy; deny all at Hidden |
| Cast expectations | User confusion | Cast hidden for magnet; resolved loopback streams surface the existing `UNSUPPORTED` path with a clear message |
-| Scope creep (config webviews, Home integration early) | Slips v1 | Phase gate: P0–P5 is the product; P6/P7 are explicit follow-ons |
-
-## Open questions
-
-- Do we ship an in-app "not supported (YouTube/external)" stream row, or hide
- unsupported kinds per addon? (P3 decision, default: show a disabled row with
- reason.)
-- Subtitle language mapping from Stremio 3-letter codes to Android locales — do we
- reuse `VodTrackPreference` or add a Stremio-specific preference? (P5.)
-- Persistent response caching (disk) — worth it, or session cache only? (Defer
- unless browsing performance proves it necessary.)
-- `stremio://` deep-link registration on the host manifest — required for browser
- install buttons, or is copy/paste enough for TV? (P1 decision; manifest change
- is cheap.)
-- Per-addon account/config flows for addons whose manifest is
- `configurationRequired` — v1 rejects with a clear message; revisit in P7.
-- Debrid API keys: plan assumes addons (e.g. Torrentio) return already-resolved
- direct URLs; no in-app debrid credential UI. Confirm desired.
+| Scope creep (config webviews, Home integration early) | Slips v1 | Phase gate: P0–P5 plus required P7 polish is direct/debrid v1; P6 torrents and optional Home/search integration are follow-ons |
+
+## Resolved implementation decisions
+
+- Stremio metadata has no dependable age-rating coverage, so the entire feature
+ is treated as protected: Off allows access, Locked/Private require a PIN once
+ per process session, and Hidden blocks the feature. Private omits the Stremio
+ continue-watching aggregate. Route gates prevent protected screens and their
+ requests from starting before unlock; view-model entry points fail closed.
+- Unsupported YouTube/external stream kinds stay visible as disabled rows with a
+ reason.
+- Subtitle language codes map through the existing player locale/preferences
+ path; no Stremio-specific preference was added.
+- Catalog responses use a bounded in-memory cache; disk persistence is deferred
+ unless browsing performance requires it.
+- V1 accepts copy/paste install links; `stremio://` intent registration is
+ optional.
+- V1 rejects `configurationRequired` addons with a clear configure-in-browser
+ message.
+
+## Deferred follow-ups
+
+- V1 assumes configured addons return playable direct/debrid HTTP(S) URLs. In-app
+ debrid credentials and API-key UI are outside the current scope.
+- Manifest refresh with last-known-good fallback, capability changes, and
+ catalog-setting reconciliation is post-v1 work.
diff --git a/docs/STREMIO_ADDONS_PLAN_REVIEW.md b/docs/STREMIO_ADDONS_PLAN_REVIEW.md
index 2681c986..bb55b4e7 100644
--- a/docs/STREMIO_ADDONS_PLAN_REVIEW.md
+++ b/docs/STREMIO_ADDONS_PLAN_REVIEW.md
@@ -1,26 +1,90 @@
# Stremio addons plan review
+2026-10-14 acceptance correction: the blanket Stremio parental gate described
+below is superseded. Stremio is open by default with a separate Settings →
+Privacy → Hide Stremio Add-ons preference. The prior gate verification remains
+historical evidence; use the revised acceptance checklist for current UX.
+
+2026-10-14 acceptance correction: the blanket Stremio parental gate described
+below is superseded. Stremio is open by default with a separate Settings →
+Privacy → Hide Stremio Add-ons preference. The prior gate verification remains
+historical evidence; use the revised acceptance checklist for current UX.
+
Reviewed 2026-10-11 in `.worktrees/stremio-addons`, branch
`feature/stremio-addons`, against the uncommitted implementation and the official
Stremio SDK protocol documentation. The review itself was a planning/code
inspection pass; subsequent verification results are recorded in
`STREMIO_ADDONS_HANDOFF.md`.
-The host-native client, separate addon registry, dedicated Addons destination,
-and direct/debrid-first delivery are appropriate. Keep those decisions. The
-following additions are needed before treating the plan as implementation-ready.
+Design follow-up (2026-10-11): resource routing, catalog pagination, and
+playback identity now have concrete decisions in implementation-plan AD-8
+through AD-10. Those design gates are closed. AD-8 through AD-10 implementation
+is now in place; the HLS and remaining release-check gaps are described in the
+2026-10-12 update below.
+
+P2 verification update (2026-10-11): AD-10 catalog browsing is implemented and
+verified. The handoff records unit-test, build, and API 36 TV emulator evidence.
+AD-9 resource routing, AD-8 playback history, and the release gates below were
+still open at that review point; see the implementation updates below.
+
+P3 verification update (2026-10-12): AD-9 resource routing and the meta/detail
+stream picker are implemented and verified. Tests cover catalog-only,
+stream-only, and subtitle-only capabilities, ID-prefix filtering, provenance
+fallback, partial fan-out/retry, exact episode IDs, and cancellation. An isolated
+API 36 TV smoke confirmed the Cinemeta detail page and no-stream-provider state;
+it did not validate playback. P4 and P5 have since been implemented, with the
+remaining smoke and release gates recorded below and in the handoff.
+
+Implementation update (2026-10-12): P0–P5 are implemented. P4 adds direct
+playback, scoped media headers, magnet guards, and URL-free Room progress at
+database version 80. Synthetic MP4 playback and history/resume smoke passed. The
+synthetic HLS VOD fixture raised transient `unexpected end of stream` errors over
+local HTTP/1.0; the same asset completed over HTTP/1.1 on the same host port with
+no error. A remote Mux Big Buck Bunny HLS sample then passed 61 screenshots at a
+two-second cadence through the local Stremio fixture, with 61 unique frame hashes,
+HLS prepare/first-frame logs, and a healthy media session. Confirm against a real
+third-party addon endpoint and its redirect/header behavior before closing that gate.
+P5 carries inline subtitles and lazily resolves addon subtitle resources; tests,
+debug assembly, inline English discovery, and independent subtitle-only playback
+smoke pass. On isolated API 36 `emulator-5556`, the fresh `tt7654327` item exposed
+the German subtitle-only addon track, selection logged `addExternalSubtitle`, and
+the WebVTT cue rendered while media session remained healthy. Direct/debrid v1 is
+still gated on a real third-party addon HLS endpoint, the final header/privacy
+review, and TV regression checks. The parental PIN gate was smoke-tested at all
+four levels on isolated API 36 `emulator-5556` on 2026-10-13; details are below.
+
+Provider-playback update (2026-10-13): on a new clean API 36 TV AVD, the local
+V11 provider fixture played HLS through a 145-second health and position-advance
+hold and progressive MP4 to first frame. The HLS capture used 61 screenshots at
+two-second cadence over 120.26 seconds, with 60 unique hashes because the
+synthetic VOD repeats after 120 seconds. During capture media session was
+PLAYING with `error=null`; sanitized logs show HLS prepare, first frame, playlist
+and segment reads, and no retry/fatal/stuck/MPEG-TS fallback. This closes the
+provider-fixture regression check, not the real third-party-addon gate. A check
+of the community Public Domain Foreign Movies addon found its manifest host
+returns 404 and no `.m3u8` references in source; the official public-domain addon
+returns torrents and Archive.org returns direct files. No suitable public-domain
+HLS addon was found.
+
+The host-native client, separate addon registry, dedicated Addons route, and
+direct/debrid-first delivery are appropriate. The Plugins and Stremio Add-ons
+routes are now grouped under one Extensions navigation destination with
+focusable in-page tabs. Direct/debrid v1 implementation and local regression
+checks are complete; the remaining items below identify external qualification
+and the user's manual UI/usage acceptance pass.
## Required additions
-### 1. Cross-addon resource routing (P2–P3, release blocker)
+### 1. Cross-addon resource routing (P2–P3, implemented and verified)
The plan describes picking from "the addon's" streams but does not define how a
catalog-only addon such as Cinemeta connects to stream-only and subtitle-only
addons. Add a resource resolver that queries enabled installed addons matching
resource, media type, and content/video ID. Honor global restrictions and
per-resource overrides, including `idPrefixes`; distinguish absent restrictions
-from explicitly empty ones where the protocol requires it. The current
-`StremioManifest.supportsResource` only checks resource/type, not ID prefixes.
+from explicitly empty ones where the protocol requires it. The original
+implementation only checked resource/type; P3 now preserves absent versus empty
+filters and applies manifest/resource-level type and prefix rules to exact IDs.
Keep catalog origin as provenance. For metadata, define deterministic precedence
(origin first when eligible, then installed order), fallback after empty/failure,
@@ -32,9 +96,11 @@ catalog rows must not disable that addon's stream/subtitle resources.
Acceptance: browse a Cinemeta item and see streams from a separate stream-only
addon; one failing addon does not hide successful results; an unrelated ID prefix
-is never queried; disabling an addon removes it from resource routing.
+is never queried; disabling an addon removes it from resource routing. These
+cases are covered by domain/repository/feature tests; the TV smoke verified the
+metadata detail and preview state, not real multi-addon playback.
-### 2. Catalog capability and pagination semantics (P2, release blocker)
+### 2. Catalog capability and pagination semantics (P2, implemented and verified)
`StremioMapper` currently converts absent `hasMore` to `false`. The standard
catalog response does not require that field, so consuming this boolean directly
@@ -74,55 +140,54 @@ Acceptance: progress survives process death and addon reinstall; changing stream
providers retains position for the same video; expired URLs are resolved again;
two unrelated custom-ID addons cannot overwrite each other's progress.
-### 4. Media headers and credentials (P1/P4, release blocker)
-
-AD-5 says never forward addon headers to non-addon hosts, while P4 requires
-`proxyHeaders.request` for playback. Stream/CDN hosts commonly differ from the
-addon API host. Replace this conflict with an explicit media-origin policy:
-validated request headers belong to the selected stream's media requests, not to
-every addon API/image/subtitle request. Define handling for redirects and HLS/DASH
-child resources on other hosts, with credential scoping and fixtures. Response
-proxy headers are not outgoing request headers. Header-dependent casting and
-external-player handoff need explicit support or a clear unavailable state.
-
-Configured install paths/queries and returned media URLs may contain secrets.
-Preserve encoded path bytes (`StremioAddonUrl.parse` currently uses decoded
-`URI.path`), redact entire sensitive paths/queries from logs/errors/screenshots,
-and decide storage, backup/export, and removal policy. Verify the injected HTTP
-client's interceptors do not log configured URLs or attach provider credentials.
-Validate schemes for API, media, artwork, subtitles, and plugin output separately;
-HTTP support must also be checked against Android network configuration.
+### 4. Media headers and credentials (P1/P4, implemented; external HLS qualification open)
+
+P4 implements origin-scoped selected-stream headers. The playback client avoids
+shared interceptors/cookies/authentication state, applies credentials only to
+the configured media origin, and strips them after a redirect to another host.
+Addon URL parsing preserves encoded path bytes, and playback diagnostics redact
+private origins and paths. Tests cover origin matching and sanitization.
+
+The local MockWebServer test confirms a cross-origin 302 removes Authorization;
+the playback client also isolates cookies, authenticators, and cache. Every HLS
+or DASH child request uses the same origin-scoped media policy. Credential
+policy: configured manifest URLs remain in app-private Room; do not log, back up,
+or manually export addon records; show only the server origin in Manage; Remove
+deletes the active addon row, while disabling retains it. Room is not app-level
+encrypted and relies on the Android app sandbox and device storage encryption.
+Stremio streams with scoped headers are rejected by casting; headerless direct
+streams can use the normal cast path. External-player handoff is outside v1
+because it cannot preserve the header scope. The public-domain addons checked
+did not provide a suitable HLS/DASH endpoint, so real-addon child-resource
+playback remains external qualification rather than a local implementation gap.
+The app's network security configuration allows HTTP for media sources.
Acceptance: encoded configuration paths round-trip; a header-dependent stream
plays without credentials leaking to unrelated hosts; sanitized diagnostics
-contain no configured URL secrets.
-
-### 5. P1 completeness and manifest lifecycle (before the P1 gate)
-
-The plan claims rejection of `configurationRequired`, but
-`StremioAddonRepositoryImpl.installAddon` currently persists such manifests.
-Define a clear configure-in-browser/paste-configured-URL error and implement it.
-Manifest parsing currently requires only an ID and defaults missing name/version;
-decide which malformed or unusable manifests to reject while still accepting
-valid stream-only/subtitle-only addons. Define duplicate identity as configured
-install URL (same manifest ID with different configuration can be legitimate).
-Map database/uniqueness errors to user-facing failures; serialize or transact
-conflicting registry operations rather than letting rapid updates lose settings.
-
-Add explicit manifest refresh with last-known-good fallback, version/capability
-changes, and reconciliation of catalog selections. Decide now that v1 supports
-copy/paste install links; OS `stremio://` intent registration is optional and must
-not be implied by URL parsing support. Separate the manager from catalog browsing
-within the Addons destination.
-
-Existing `stremio-test-run2.log` ends in a compile failure:
-`AddonsViewModelTest.kt:157` cannot resolve `StremioManifestResource`; its import
-is absent in the inspected file. The handoff's previously reported passes are
-historical evidence, not fresh verification. Run app, Stremio, settings, and
-targeted data tests as separate invocations so data test filters don't exclude
-unrelated test classes. Then complete manager emulator validation (install,
-duplicate/configuration errors, enable/disable, reorder, catalog selection,
-removal, restart persistence, and TV focus), beyond the single install screenshot.
+contain no configured URL secrets. Unit and MockWebServer redirect coverage pass.
+A suitable real addon remains needed to confirm end-to-end HLS/DASH child
+requests with its own manifest and media URLs.
+
+### 5. P1 completeness and manifest lifecycle
+
+Resolved P1 finding: `StremioAddonRepositoryImpl.installAddon` rejects
+`configurationRequired` manifests with a configure-in-browser/paste-configured-URL
+message, and the configured install URL is the registry identity.
+
+Manifest refresh with last-known-good fallback, version/capability changes, and
+catalog-selection reconciliation remains a post-v1 follow-up. Document validation
+boundaries for malformed or unusable manifests while retaining valid stream-only
+and subtitle-only addons. V1 supports copy/paste install links; OS `stremio://`
+intent registration remains optional. Keep the manager separate from catalog
+browsing within the Addons destination.
+
+The compile failure recorded in `stremio-test-run2.log`
+(`AddonsViewModelTest.kt:157` could not resolve `StremioManifestResource`) is
+historical; the import was fixed and the current Stremio/app tests and debug build
+pass. Emulator smoke confirmed addon installation. Repository/ViewModel tests
+cover duplicate and configuration-required installs, enable/disable, reorder,
+catalog selection, and removal. The manual acceptance pass should confirm
+retention after app restart and D-pad focus through the manager.
### 6. Torrent plugin contract feasibility (design spike before P6)
@@ -155,26 +220,33 @@ fixture before a real-network end-to-end trial.
### 7. Subtitle coverage (P5)
-Handle both inline `stream.subtitles` and enabled subtitle-resource addons. The
-current DTO/model does not include inline subtitles; `fetchSubtitles` lacks the
-standard `videoSize` extra although behavior hints already retain it. Carry video
-ID/hash/size/filename through the playback request. Deduplicate with provenance,
-handle unavailable tracks without interrupting video, reset on stream/episode
-changes, and reuse existing language/style preferences. Verify three-letter
-language aliases, unknown codes, and supported formats against player capabilities.
+Implemented: inline `stream.subtitles` and enabled subtitle-resource addons are
+carried to playback. Requests include the exact video ID and available
+`videoHash`, `videoSize`, and `filename` extras. Results are deduplicated with
+provenance, three-letter language codes are mapped, and external tracks use the
+existing player path and preferences. The subtitle picker appears when Stremio
+sources exist even if no embedded text track is present. Focused tests/build and
+the inline English picker smoke pass. An isolated API 36 TV smoke selected a
+German track from an independent subtitle-only fixture and rendered its WebVTT
+cue over playback.
-Acceptance: inline-only subtitles and an independent subtitle addon both work;
-the correct episode and optional hash/size/filename reach the addon; switching
-episodes cannot retain the previous subtitle request/result.
+Remaining acceptance: verify that switching episodes cannot retain the previous
+subtitle request/result.
### 8. Parental controls and content-type scope (before v1 release)
-Move the parental-control decision out of optional P7 polish. An Addons screen
-can bypass restrictions even without Home/search integration. Manifest
-`behaviorHints.adult` exists but is absent from the current model. Do not assume
-all catalogs/meta expose a reliable adult flag. Decide a conservative behavior for
-unrated/custom addon content under a locked profile, and gate install, details,
-playback, and history entry points consistently with the app's existing controls.
+The parental-control decision is now implemented ahead of v1. Addon catalogs
+and metadata do not provide dependable age ratings, so all Stremio content is
+treated as protected: Off allows access, Locked and Private require the existing
+PIN once per app session, and Hidden blocks the feature, including installation.
+Both browse and item routes are gated before screen construction/network fetches;
+install, catalog, metadata, and stream actions also fail closed. Private omits
+Stremio continue-watching from the aggregate surface. Feature tests cover each
+level and blocked install/catalog/detail requests. The isolated API 36 TV smoke
+verified Hidden denial, Locked/Private PIN prompts, wrong-PIN rejection, valid
+unlock, re-lock after a level change, and Off access without a PIN; the original
+emulator preferences were restored and hash-verified. This release gate is
+closed.
Explicitly define v1 as movie/series playback, with `tv`/`channel` browsing or
playback deferred unless separately implemented. The current model recognizes
@@ -182,7 +254,7 @@ these types, while the plan's playback/resume design assumes VOD. Newer guide an
archive-source capabilities remain unsupported v1 states; preserve a visible
unsupported row rather than silently dropping identifiable stream kinds.
-### 9. Release validation and documentation (P4–P5 release gate)
+### 9. Release validation and documentation (P4–P5 release gate)
Add a deterministic multi-addon fixture setup covering catalog-only, stream-only,
subtitle-only, custom episode IDs, missing `hasMore`, required extras, redirects,
@@ -190,8 +262,10 @@ headers, unsupported stream kinds, cancellation, partial failures, and expiring
URLs. Use legitimate direct MP4 and HLS media; exercise seek, resume after restart,
audio/subtitle selection, TV focus restoration, and existing provider playback.
-First frame/build/install alone are not playback acceptance. Capture progression
-and sanitized player logs across a meaningful playback window. If live addon
+First frame/build/install alone are not playback acceptance. The provider
+fixture now covers a 145-second advancing HLS playback window and progressive
+first frame; real addon HLS/DASH and child-resource behavior remains open. Capture
+progression and sanitized player logs across a meaningful playback window. If live addon
playback is added, follow AGENTS.md exactly: at least 45 screenshots at two-second
intervals (prefer 61 for prior one-minute failures), healthy media session, no
fatal/stuck/unintended fallback, and multiple channels for general live bugs.
@@ -203,15 +277,34 @@ original estimates do not account for these unresolved integration contracts.
## Recommended continuation order
-1. Close P1 registry/configuration and verification gaps; obtain the requested
- commit decision only after concrete test/emulator evidence exists.
-2. Design resource resolution and playback identity before starting P2/P3 UI.
-3. Implement P2/P3 with fake multi-addon fixtures, then P4 direct playback and
- history reopening, then P5 subtitles.
-4. Ship direct/debrid v1 only after parental controls, privacy, TV interaction,
- and regression validation pass.
-5. Run the plugin feasibility spike before committing to the P6 implementation
- spec. Home/global search remains optional after v1.
+1. P1 registry/configuration, verification, and commit are complete; results
+ are in the handoff.
+2. P2 catalog browsing against AD-10 is implemented and verified; results are
+ recorded in the handoff.
+3. P3 cross-addon routing and the detail/stream picker against AD-9 are complete
+ and verified; results are recorded in the handoff. P4/P5 are implemented, and
+ the direct MP4/history and independent subtitle-addon smoke checks passed.
+4. Parental PIN TV smoke at Off, Locked, Private, and Hidden is complete. D-pad
+ navigation through Extensions and its Plugins/Stremio Add-ons tabs also
+ passes. No suitable public-domain third-party HLS addon was found: the
+ official Public Domain Movies addon returns torrent hashes, while the
+ maintained Archive.org addon returns direct file URLs and its published host
+ no longer resolves. The community Public Domain Foreign Movies endpoint also
+ returns 404 and its source has no HLS playlist references. Keep the real-addon
+ HLS gate open; neither local fixture smoke satisfies that gate.
+5. Provider playback passes with a dedicated fixture. Direct/debrid v1 code and
+ local regression gates are complete. A real third-party addon HLS/DASH and
+ child-resource smoke remains external qualification because the public-domain
+ candidates checked so far do not provide usable HLS. Same-origin headers are
+ scoped in the player request policy and the cross-origin redirect integration
+ test confirms credentials are removed. Casting rejects streams with scoped
+ addon headers and allows headerless direct streams. External-player handoff
+ is outside v1.
+ The install-URL secret storage, backup/export, Manage display, and removal
+ policy is documented in the handoff and enforced by the origin-only row.
+6. Keep the P6 torrent-plugin feasibility spike deferred until the direct/debrid
+ user acceptance pass is reviewed. Home/global search remains optional after
+ v1.
## Primary protocol references
diff --git a/docs/STREMIO_TORRENT_P6_ACCEPTANCE.md b/docs/STREMIO_TORRENT_P6_ACCEPTANCE.md
new file mode 100644
index 00000000..9fa2bbaa
--- /dev/null
+++ b/docs/STREMIO_TORRENT_P6_ACCEPTANCE.md
@@ -0,0 +1,56 @@
+# Stremio torrent playback — P6 acceptance
+
+The companion implementation and debug APK are ready for manual testing. This
+pass belongs to the user; no real torrent playback has been performed by the
+build workflow. Cinemeta is catalog/metadata only, so test with an installed
+Stremio addon that actually returns torrent streams.
+
+The host app was rebuilt from the current Stremio worktree as
+`1.0.19-debug`. If your installed host predates this handoff, update it from:
+
+`D:\antigravity-scratch\iptv-player\.worktrees\stremio-addons\app\build\outputs\apk\debug\app-debug.apk`
+
+Then install the companion from StreamVault → Extensions → Plugins → Install
+plugin APK, using:
+
+`D:\antigravity-scratch\streamvault-torrent-plugin\app\build\outputs\apk\debug\app-debug.apk`
+
+The companion is `0.1.0-debug`; its SHA-256 is
+`F3908E11E1DECB38F2589AEE8F33F164E7722FEDBFAC488F83D512B627588C06`.
+
+Enable **StreamVault Torrent** in Plugins. Open its configuration Activity to
+confirm the service is ready. Keep the host app and companion APK versions noted
+when reporting results.
+
+## Playback
+
+- [ ] Open a movie with a torrent stream, select it, and confirm playback starts
+ without exposing the magnet URI to the media player.
+- [ ] Seek forward and back. Confirm playback continues and the selected title
+ remains usable.
+- [ ] Stop playback, reopen the same torrent, and confirm it can start again.
+- [ ] Open the plugin configuration while playing and confirm status shows the
+ active file, peers, and transfer rates.
+- [ ] Stop playback and confirm the session disappears from status shortly after
+ the host sends its stop message.
+- [ ] Use **Stop all torrent sessions** and confirm playback stops and status
+ returns to ready.
+- [ ] Disable the plugin and select a torrent stream. Confirm StreamVault gives
+ a clear disabled or missing-plugin message and does not start the magnet in
+ the media player. Re-enable the plugin afterward if desired.
+
+## Configuration and cleanup
+
+- [ ] Change the buffer target and download/upload caps; confirm the displayed
+ values persist after leaving and reopening the configuration Activity.
+- [ ] If the device has removable app-private storage, choose it and confirm a
+ new session can use it. Otherwise verify the default private app storage.
+- [ ] Clear downloaded torrent data while idle and confirm the action succeeds.
+- [ ] Confirm the stream server remains local to the device and is not reachable
+ from another device on the network.
+
+If a multi-file torrent is available, also verify a stream with `fileIdx` selects
+that file and a stream without an index chooses the largest supported video.
+Record addon name, title, device/AVD, first-frame result, seek result, stop/replay
+result, and any error shown. Redact magnet hashes, tracker URLs, and account or
+authorization data from screenshots and logs.
diff --git a/domain/src/main/java/com/streamvault/domain/model/AppTopLevelDestination.kt b/domain/src/main/java/com/streamvault/domain/model/AppTopLevelDestination.kt
index 4cafe665..fd2c9abf 100644
--- a/domain/src/main/java/com/streamvault/domain/model/AppTopLevelDestination.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/AppTopLevelDestination.kt
@@ -12,8 +12,7 @@ enum class AppTopLevelDestination(
DOWNLOADS("downloads", AppLandingDestination.DOWNLOADS),
GUIDE("guide", AppLandingDestination.GUIDE),
SEARCH("search"),
- PLUGINS("plugins", AppLandingDestination.PLUGINS),
- ADDONS("addons", AppLandingDestination.ADDONS),
+ EXTENSIONS("extensions"),
SETTINGS("settings", AppLandingDestination.SETTINGS, isRequired = true);
companion object {
@@ -25,13 +24,17 @@ enum class AppTopLevelDestination(
DOWNLOADS,
GUIDE,
SEARCH,
- PLUGINS,
- ADDONS,
+ EXTENSIONS,
SETTINGS
)
fun fromStorage(value: String?): AppTopLevelDestination? =
entries.firstOrNull { it.storageValue.equals(value, ignoreCase = true) }
+ ?: when {
+ value.equals("plugins", ignoreCase = true) -> EXTENSIONS
+ value.equals("addons", ignoreCase = true) -> EXTENSIONS
+ else -> null
+ }
fun normalizeForStorage(destinations: List<AppTopLevelDestination>): List<AppTopLevelDestination> {
val unique = linkedSetOf<AppTopLevelDestination>()
@@ -45,7 +48,12 @@ enum class AppTopLevelDestination(
): List<AppLandingDestination> {
val normalized = normalizeForStorage(destinations)
val available = normalized
- .mapNotNull { it.landingDestination }
+ .flatMap { destination ->
+ when (destination) {
+ EXTENSIONS -> listOf(AppLandingDestination.PLUGINS, AppLandingDestination.ADDONS)
+ else -> listOfNotNull(destination.landingDestination)
+ }
+ }
.distinct()
.toMutableList()
if (LIVE_TV in normalized) {
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 675e6539..85345333 100644
--- a/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/StreamInfo.kt
@@ -20,7 +20,9 @@ data class StreamInfo(
val catchUpUrl: String? = null,
val expirationTime: Long? = null,
val drmInfo: DrmInfo? = null,
- val playbackContentKind: PlaybackContentKind = PlaybackContentKind.UNKNOWN
+ val playbackContentKind: PlaybackContentKind = PlaybackContentKind.UNKNOWN,
+ /** When set, request headers are attached only to requests matching this HTTP origin. */
+ val requestHeadersOrigin: String? = null
) {
init {
require(url.isNotBlank()) { "StreamInfo url must not be blank" }
diff --git a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioAddon.kt b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioAddon.kt
index d122b0ea..f98d510a 100644
--- a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioAddon.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioAddon.kt
@@ -1,5 +1,7 @@
package com.streamvault.domain.model.stremio
+import java.security.MessageDigest
+
data class StremioAddon(
val id: Long = 0L,
val installUrl: String,
@@ -21,3 +23,8 @@ data class StremioAddon(
fun isCatalogEnabled(catalogKey: String): Boolean = catalogSettings[catalogKey] ?: true
}
+
+/** Stable, non-secret identity for a configured addon install. */
+fun StremioAddon.installFingerprint(): String = MessageDigest.getInstance("SHA-256")
+ .digest("stremio-addon-install\u0000$installUrl".toByteArray(Charsets.UTF_8))
+ .joinToString("") { byte -> "%02x".format(byte) }
diff --git a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioCatalog.kt b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioCatalog.kt
index c7b2ead0..5ef5c70c 100644
--- a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioCatalog.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioCatalog.kt
@@ -16,7 +16,10 @@ data class StremioMetaPreview(
data class StremioCatalogPage(
val metas: List<StremioMetaPreview>,
- val hasMore: Boolean = false
+ /** `null` means the addon omitted the optional protocol field. */
+ val hasMore: Boolean? = null,
+ /** Count from the unfiltered JSON array, used for stable remote skip offsets. */
+ val rawItemCount: Int = metas.size
)
data class StremioCatalogQuery(
@@ -27,6 +30,6 @@ data class StremioCatalogQuery(
fun toExtras(): List<Pair<String, String>> = buildList {
search?.trim()?.takeIf { it.isNotEmpty() }?.let { add("search" to it) }
genre?.trim()?.takeIf { it.isNotEmpty() }?.let { add("genre" to it) }
- skip?.takeIf { it > 0 }?.let { add("skip" to it.toString()) }
+ skip?.takeIf { it >= 0 }?.let { add("skip" to it.toString()) }
}
}
diff --git a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioManifest.kt b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioManifest.kt
index 210e9e67..1621c357 100644
--- a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioManifest.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioManifest.kt
@@ -32,8 +32,12 @@ enum class StremioResourceKind(val resourceName: String) {
data class StremioManifestResource(
val kind: StremioResourceKind,
- val types: List<StremioMediaType> = emptyList(),
- val idPrefixes: List<String> = emptyList()
+ /** String declarations inherit manifest-level filters; object declarations use their own. */
+ val isStringResource: Boolean = false,
+ /** `null` means omitted; an empty list is an explicit match-none filter. */
+ val types: List<StremioMediaType>? = null,
+ /** `null` means omitted; an empty list is an explicit match-none filter. */
+ val idPrefixes: List<String>? = null
)
data class StremioCatalogExtraDef(
@@ -52,8 +56,7 @@ data class StremioCatalogRef(
val settingsKey: String get() = "${type.typeName}:$id"
val supportsSearch: Boolean get() = extras.any { it.name.equals("search", ignoreCase = true) }
val supportsSkip: Boolean get() = extras.any { it.name.equals("skip", ignoreCase = true) }
- val supportsGenre: Boolean
- get() = genres.isNotEmpty() || extras.any { it.name.equals("genre", ignoreCase = true) }
+ val supportsGenre: Boolean get() = extras.any { it.name.equals("genre", ignoreCase = true) }
}
data class StremioManifestBehaviorHints(
@@ -68,14 +71,33 @@ data class StremioManifest(
val description: String? = null,
val logo: String? = null,
val background: String? = null,
- val types: List<StremioMediaType> = emptyList(),
+ /** `null` means omitted; an empty list is an explicit match-none filter. */
+ val types: List<StremioMediaType>? = null,
val resources: List<StremioManifestResource> = emptyList(),
val catalogs: List<StremioCatalogRef> = emptyList(),
- val idPrefixes: List<String> = emptyList(),
+ /** `null` means omitted; an empty list is an explicit match-none filter. */
+ val idPrefixes: List<String>? = null,
val behaviorHints: StremioManifestBehaviorHints = StremioManifestBehaviorHints()
) {
- fun supportsResource(kind: StremioResourceKind, type: StremioMediaType): Boolean =
+ fun supportsResource(
+ kind: StremioResourceKind,
+ type: StremioMediaType,
+ exactId: String? = null
+ ): Boolean =
resources.any { resource ->
- resource.kind == kind && (resource.types.isEmpty() || type in resource.types)
+ if (resource.kind != kind) {
+ false
+ } else {
+ val effectiveTypes = resource.types ?: types
+ val typeMatches = effectiveTypes == null || type in effectiveTypes
+ val effectivePrefixes = if (resource.isStringResource) idPrefixes else resource.idPrefixes
+ val prefixMatches = when {
+ effectivePrefixes == null -> true
+ effectivePrefixes.isEmpty() -> false
+ exactId == null -> true
+ else -> effectivePrefixes.any(exactId::startsWith)
+ }
+ typeMatches && prefixMatches
+ }
}
}
diff --git a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioMediaRequestHeaders.kt b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioMediaRequestHeaders.kt
new file mode 100644
index 00000000..2ac9d65b
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioMediaRequestHeaders.kt
@@ -0,0 +1,56 @@
+package com.streamvault.domain.model.stremio
+
+import java.net.URI
+
+data class StremioMediaRequestHeaders(
+ val origin: String,
+ val headers: Map<String, String>
+)
+
+/** Validates Stremio proxyHeaders.request and binds them to the direct stream's HTTP origin. */
+fun stremioMediaRequestHeaders(
+ mediaUrl: String,
+ suppliedHeaders: Map<String, String>?
+): StremioMediaRequestHeaders? {
+ val origin = stremioHttpOrigin(mediaUrl) ?: return null
+ val headers = suppliedHeaders.orEmpty()
+ if (headers.size > MAX_HEADER_COUNT) return null
+ var totalBytes = 0
+ val safeHeaders = linkedMapOf<String, String>()
+ val normalizedNames = mutableSetOf<String>()
+ headers.forEach { (rawName, value) ->
+ val name = rawName.trim()
+ val normalizedName = name.lowercase()
+ if (!HEADER_NAME.matches(name) || normalizedName in FORBIDDEN_HEADERS ||
+ !normalizedNames.add(normalizedName)
+ ) return null
+ if (value.length > MAX_HEADER_VALUE_LENGTH || value.any { it == '\r' || it == '\n' || it.code < 0x20 && it != '\t' }) {
+ return null
+ }
+ totalBytes += name.toByteArray(Charsets.UTF_8).size + value.toByteArray(Charsets.UTF_8).size
+ if (totalBytes > MAX_HEADER_BYTES) return null
+ safeHeaders[name] = value
+ }
+ return StremioMediaRequestHeaders(origin = origin, headers = safeHeaders.toMap())
+}
+
+/** Canonical scheme/host/port tuple. Paths, queries, and credentials never enter the scope key. */
+fun stremioHttpOrigin(url: String): String? = runCatching {
+ val uri = URI(url)
+ val scheme = uri.scheme?.lowercase() ?: return null
+ if (scheme != "http" && scheme != "https") return null
+ val host = uri.host?.trimStart('[')?.trimEnd(']')?.lowercase() ?: return null
+ if (uri.rawUserInfo != null) return null
+ val port = uri.port.takeIf { it >= 0 } ?: if (scheme == "https") 443 else 80
+ val formattedHost = if (host.contains(':')) "[$host]" else host
+ "$scheme://$formattedHost:$port"
+}.getOrNull()
+
+private const val MAX_HEADER_COUNT = 32
+private const val MAX_HEADER_VALUE_LENGTH = 8_192
+private const val MAX_HEADER_BYTES = 16_384
+private val HEADER_NAME = Regex("[!#$%&'*+.^_`|~0-9A-Za-z-]{1,128}")
+private val FORBIDDEN_HEADERS = setOf(
+ "connection", "content-length", "host", "keep-alive", "proxy-authenticate",
+ "proxy-authorization", "te", "trailer", "transfer-encoding", "upgrade"
+)
diff --git a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioPlaybackHistory.kt b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioPlaybackHistory.kt
new file mode 100644
index 00000000..d7922772
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioPlaybackHistory.kt
@@ -0,0 +1,49 @@
+package com.streamvault.domain.model.stremio
+
+/** Progress for one Stremio movie or exact episode request ID. Never contains a stream URL. */
+data class StremioPlaybackHistory(
+ val contentKey: String,
+ val mediaType: String,
+ val exactVideoId: String,
+ val parentSeriesId: String? = null,
+ val title: String,
+ val posterUrl: String? = null,
+ val resumePositionMs: Long = 0L,
+ val totalDurationMs: Long = 0L,
+ val watched: Boolean = false,
+ val lastWatchedAt: Long = System.currentTimeMillis(),
+ val catalogOriginKey: String,
+ val streamOriginKeyHint: String? = null
+)
+
+/**
+ * Creates the canonical history key. Only validated IMDb movie IDs and exact episode IDs
+ * belonging to an IMDb parent are global; all other IDs remain scoped to the catalog addon.
+ */
+fun stremioPlaybackContentKey(
+ mediaType: String,
+ exactVideoId: String,
+ parentSeriesId: String?,
+ catalogOriginKey: String
+): String? {
+ if (exactVideoId.isBlank() || !catalogOriginKey.matches(Regex("[0-9a-fA-F]{64}"))) return null
+
+ val typeKey = when (mediaType.lowercase()) {
+ "movie" -> "movie"
+ "series" -> "series-episode"
+ else -> return null
+ }
+ val imdbId = Regex("tt[0-9]+")
+ val isGlobal = when (typeKey) {
+ "movie" -> imdbId.matches(exactVideoId)
+ "series-episode" -> parentSeriesId?.let { parent ->
+ imdbId.matches(parent) && Regex("${Regex.escape(parent)}:[0-9]+:[0-9]+").matches(exactVideoId)
+ } == true
+ else -> false
+ }
+ return if (isGlobal) {
+ "stremio:global:$typeKey:$exactVideoId"
+ } else {
+ "stremio:addon:${catalogOriginKey.lowercase()}:$typeKey:$exactVideoId"
+ }
+}
diff --git a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioResourceResolution.kt b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioResourceResolution.kt
new file mode 100644
index 00000000..60b62636
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioResourceResolution.kt
@@ -0,0 +1,35 @@
+package com.streamvault.domain.model.stremio
+
+data class StremioInstalledAddon(
+ val addon: StremioAddon,
+ val manifest: StremioManifest
+)
+
+data class StremioAddonSource(
+ val addonId: Long,
+ val addonName: String,
+ val manifestId: String,
+ val installFingerprint: String
+)
+
+data class StremioAttributedResource<T>(
+ val source: StremioAddonSource,
+ val resource: T
+)
+
+data class StremioAddonResourceFailure(
+ val source: StremioAddonSource,
+ val message: String
+)
+
+data class StremioMetaResolution(
+ val result: StremioAttributedResource<StremioMetaDetail>? = null,
+ val failures: List<StremioAddonResourceFailure> = emptyList(),
+ val candidateCount: Int = 0
+)
+
+data class StremioResourceResolution<T>(
+ val results: List<StremioAttributedResource<T>> = emptyList(),
+ val failures: List<StremioAddonResourceFailure> = emptyList(),
+ val candidateCount: Int = 0
+)
diff --git a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioStream.kt b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioStream.kt
index e29865f9..5278c8f0 100644
--- a/domain/src/main/java/com/streamvault/domain/model/stremio/StremioStream.kt
+++ b/domain/src/main/java/com/streamvault/domain/model/stremio/StremioStream.kt
@@ -1,5 +1,9 @@
package com.streamvault.domain.model.stremio
+import java.net.URI
+import java.net.URLDecoder
+import java.net.URLEncoder
+
enum class StremioStreamKind {
DIRECT,
TORRENT,
@@ -32,14 +36,91 @@ data class StremioStream(
val fileIdx: Int? = null,
val externalUrl: String? = null,
val sources: List<String> = emptyList(),
+ val subtitles: List<StremioSubtitle> = emptyList(),
val behaviorHints: StremioStreamBehaviorHints? = null
) {
val kind: StremioStreamKind
get() = when {
!infoHash.isNullOrBlank() -> StremioStreamKind.TORRENT
+ url?.let(::isMagnetScheme) == true -> StremioStreamKind.TORRENT
!url.isNullOrBlank() -> StremioStreamKind.DIRECT
!ytId.isNullOrBlank() -> StremioStreamKind.YOUTUBE
!externalUrl.isNullOrBlank() -> StremioStreamKind.EXTERNAL
else -> StremioStreamKind.UNKNOWN
}
}
+
+/** Builds the URL passed to a scheme-owning playback plugin for this torrent stream. */
+fun StremioStream.toMagnetUri(): String? {
+ val hash = infoHash?.trim()?.takeIf(BTIH_PATTERN::matches)
+ if (hash != null) {
+ val query = mutableListOf("xt=urn%3Abtih%3A${encodeMagnetValue(hash)}")
+ (behaviorHints?.filename ?: title ?: name)
+ ?.trim()
+ ?.takeIf(String::isNotEmpty)
+ ?.take(MAX_MAGNET_DISPLAY_NAME_LENGTH)
+ ?.let { query += "dn=${encodeMagnetValue(it)}" }
+ fileIdx?.takeIf { it >= 0 }?.let { query += "so=$it" }
+ sources.asSequence()
+ .mapNotNull(::trackerUrl)
+ .distinct()
+ .take(MAX_MAGNET_TRACKERS)
+ .forEach { query += "tr=${encodeMagnetValue(it)}" }
+ return "magnet:?${query.joinToString("&")}".takeIf { it.length <= MAX_MAGNET_URI_LENGTH }
+ }
+
+ val rawMagnet = url?.trim()?.takeIf {
+ it.length <= MAX_MAGNET_URI_LENGTH && isValidMagnetUri(it)
+ } ?: return null
+ val selectionAlreadyPresent = rawMagnetQuery(URI(rawMagnet)).orEmpty()
+ .split('&')
+ .mapNotNull { parameter -> parameter.substringBefore('=').decodeMagnetValueOrNull() }
+ .any { it.equals("so", ignoreCase = true) }
+ val selectedFile = fileIdx?.takeIf { it >= 0 } ?: return rawMagnet
+ return if (selectionAlreadyPresent) rawMagnet
+ else "$rawMagnet&so=$selectedFile".takeIf { it.length <= MAX_MAGNET_URI_LENGTH }
+}
+
+private fun isMagnetScheme(value: String): Boolean =
+ value.startsWith("magnet:", ignoreCase = true)
+
+private fun isValidMagnetUri(value: String): Boolean = runCatching {
+ val uri = URI(value)
+ if (!uri.scheme.equals("magnet", ignoreCase = true) || uri.rawAuthority != null ||
+ !uri.rawPath.isNullOrEmpty() || uri.rawFragment != null
+ ) return@runCatching false
+ rawMagnetQuery(uri)?.split('&')?.any { parameter ->
+ val name = parameter.substringBefore('=').decodeMagnetValueOrNull()
+ val valuePart = parameter.substringAfter('=', "").decodeMagnetValueOrNull()
+ name.equals("xt", ignoreCase = true) &&
+ valuePart?.startsWith("urn:btih:", ignoreCase = true) == true &&
+ BTIH_PATTERN.matches(valuePart.substringAfterLast(':'))
+ } == true
+}.getOrDefault(false)
+
+/** `magnet:` is an opaque URI, so Java exposes its query after `?` as the scheme-specific part. */
+private fun rawMagnetQuery(uri: URI): String? =
+ uri.rawSchemeSpecificPart?.takeIf { it.startsWith("?") }?.substring(1)
+
+private fun trackerUrl(source: String): String? {
+ val candidate = source.trim().let {
+ if (it.startsWith("tracker:", ignoreCase = true)) it.substringAfter(':') else it
+ }
+ if (candidate.length > MAX_TRACKER_URL_LENGTH) return null
+ val uri = runCatching { URI(candidate) }.getOrNull() ?: return null
+ if (uri.scheme?.lowercase() !in TRACKER_SCHEMES || uri.host.isNullOrBlank()) return null
+ return candidate
+}
+
+private fun encodeMagnetValue(value: String): String =
+ URLEncoder.encode(value, Charsets.UTF_8.name()).replace("+", "%20")
+
+private fun String.decodeMagnetValueOrNull(): String? =
+ runCatching { URLDecoder.decode(this, Charsets.UTF_8.name()) }.getOrNull()
+
+private val BTIH_PATTERN = Regex("(?i)(?:[0-9a-f]{40}|[a-z2-7]{32})")
+private val TRACKER_SCHEMES = setOf("http", "https", "udp")
+private const val MAX_MAGNET_DISPLAY_NAME_LENGTH = 512
+private const val MAX_MAGNET_TRACKERS = 8
+private const val MAX_TRACKER_URL_LENGTH = 512
+private const val MAX_MAGNET_URI_LENGTH = 16_384
diff --git a/domain/src/main/java/com/streamvault/domain/repository/StremioAddonRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/StremioAddonRepository.kt
index 360ab8a8..89584f24 100644
--- a/domain/src/main/java/com/streamvault/domain/repository/StremioAddonRepository.kt
+++ b/domain/src/main/java/com/streamvault/domain/repository/StremioAddonRepository.kt
@@ -2,7 +2,15 @@ package com.streamvault.domain.repository
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioCatalogPage
+import com.streamvault.domain.model.stremio.StremioCatalogQuery
+import com.streamvault.domain.model.stremio.StremioCatalogRef
import com.streamvault.domain.model.stremio.StremioManifest
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaResolution
+import com.streamvault.domain.model.stremio.StremioResourceResolution
+import com.streamvault.domain.model.stremio.StremioStream
+import com.streamvault.domain.model.stremio.StremioSubtitle
import kotlinx.coroutines.flow.Flow
interface StremioAddonRepository {
@@ -12,6 +20,33 @@ interface StremioAddonRepository {
suspend fun getManifest(addonId: Long): StremioManifest?
+ suspend fun fetchCatalog(
+ addonId: Long,
+ catalog: StremioCatalogRef,
+ query: StremioCatalogQuery
+ ): Result<StremioCatalogPage>
+
+ suspend fun resolveMeta(
+ catalogOriginAddonId: Long,
+ type: StremioMediaType,
+ exactId: String
+ ): StremioMetaResolution
+
+ suspend fun resolveStreams(
+ type: StremioMediaType,
+ exactId: String,
+ addonIds: Set<Long>? = null
+ ): StremioResourceResolution<StremioStream>
+
+ suspend fun resolveSubtitles(
+ type: StremioMediaType,
+ exactVideoId: String,
+ videoHash: String? = null,
+ videoSize: Long? = null,
+ filename: String? = null,
+ addonIds: Set<Long>? = null
+ ): StremioResourceResolution<StremioSubtitle>
+
suspend fun installAddon(installUrl: String): Result<StremioAddon>
suspend fun removeAddon(id: Long): Result<Unit>
diff --git a/domain/src/main/java/com/streamvault/domain/repository/StremioPlaybackHistoryRepository.kt b/domain/src/main/java/com/streamvault/domain/repository/StremioPlaybackHistoryRepository.kt
new file mode 100644
index 00000000..28236b8a
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/repository/StremioPlaybackHistoryRepository.kt
@@ -0,0 +1,15 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
+import kotlinx.coroutines.flow.Flow
+
+interface StremioPlaybackHistoryRepository {
+ fun observeContinueWatching(limit: Int = 20): Flow<List<StremioPlaybackHistory>>
+
+ suspend fun get(contentKey: String): StremioPlaybackHistory?
+
+ suspend fun save(history: StremioPlaybackHistory): Result<Unit>
+
+ suspend fun delete(contentKey: String): Result<Unit>
+}
diff --git a/domain/src/main/java/com/streamvault/domain/repository/StremioResourceResolver.kt b/domain/src/main/java/com/streamvault/domain/repository/StremioResourceResolver.kt
new file mode 100644
index 00000000..8f136007
--- /dev/null
+++ b/domain/src/main/java/com/streamvault/domain/repository/StremioResourceResolver.kt
@@ -0,0 +1,148 @@
+package com.streamvault.domain.repository
+
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioAddonResourceFailure
+import com.streamvault.domain.model.stremio.StremioAddonSource
+import com.streamvault.domain.model.stremio.StremioAttributedResource
+import com.streamvault.domain.model.stremio.StremioInstalledAddon
+import com.streamvault.domain.model.stremio.installFingerprint
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaDetail
+import com.streamvault.domain.model.stremio.StremioMetaResolution
+import com.streamvault.domain.model.stremio.StremioResourceKind
+import com.streamvault.domain.model.stremio.StremioResourceResolution
+import javax.inject.Inject
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitAll
+import kotlinx.coroutines.coroutineScope
+import kotlinx.coroutines.sync.Semaphore
+import kotlinx.coroutines.sync.withPermit
+
+/** Selects eligible addon resources and coordinates deterministic, bounded requests. */
+class StremioResourceResolver @Inject constructor() {
+
+ fun candidates(
+ addons: List<StremioInstalledAddon>,
+ kind: StremioResourceKind,
+ type: StremioMediaType,
+ exactId: String,
+ addonIds: Set<Long>? = null,
+ preferredAddonId: Long? = null
+ ): List<StremioInstalledAddon> {
+ if (exactId.isBlank() || type == StremioMediaType.UNKNOWN) return emptyList()
+ val eligible = addons.filter { installed ->
+ installed.addon.enabled &&
+ (addonIds == null || installed.addon.id in addonIds) &&
+ if (kind == StremioResourceKind.CATALOG) {
+ // Catalog IDs come from manifest.catalogs; prefixes never route catalogs.
+ installed.manifest.catalogs.any { it.type == type && it.id == exactId }
+ } else {
+ installed.manifest.supportsResource(kind, type, exactId)
+ }
+ }
+ return if (preferredAddonId == null) {
+ eligible
+ } else {
+ eligible.sortedBy { if (it.addon.id == preferredAddonId) 0 else 1 }
+ }
+ }
+
+ suspend fun resolveMeta(
+ candidates: List<StremioInstalledAddon>,
+ requestedType: StremioMediaType,
+ exactId: String,
+ request: suspend (StremioAddon) -> Result<StremioMetaDetail>
+ ): StremioMetaResolution {
+ val failures = mutableListOf<StremioAddonResourceFailure>()
+ for (candidate in candidates) {
+ val result = try {
+ request(candidate.addon)
+ } catch (cancellation: CancellationException) {
+ throw cancellation
+ } catch (_: Exception) {
+ Result.error("Addon request failed")
+ }
+ when (result) {
+ is Result.Success -> {
+ val meta = result.data
+ if (meta.id == exactId && (meta.type == requestedType || meta.type == StremioMediaType.UNKNOWN)) {
+ val normalized = if (meta.type == StremioMediaType.UNKNOWN) {
+ meta.copy(type = requestedType)
+ } else {
+ meta
+ }
+ return StremioMetaResolution(
+ result = StremioAttributedResource(candidate.addon.toSource(), normalized),
+ failures = failures,
+ candidateCount = candidates.size
+ )
+ }
+ failures += failure(candidate.addon, "Addon returned metadata for a different item")
+ }
+ is Result.Error -> failures += failure(candidate.addon, result.message)
+ Result.Loading -> failures += failure(candidate.addon, "Addon request did not complete")
+ }
+ }
+ return StremioMetaResolution(failures = failures, candidateCount = candidates.size)
+ }
+
+ suspend fun <T> resolveMany(
+ candidates: List<StremioInstalledAddon>,
+ request: suspend (StremioAddon) -> Result<List<T>>
+ ): StremioResourceResolution<T> {
+ if (candidates.isEmpty()) return StremioResourceResolution()
+ val semaphore = Semaphore(MAX_CONCURRENT_REQUESTS)
+ val outcomes = coroutineScope {
+ candidates.map { candidate ->
+ async {
+ semaphore.withPermit {
+ val result = try {
+ request(candidate.addon)
+ } catch (cancellation: CancellationException) {
+ throw cancellation
+ } catch (_: Exception) {
+ Result.error("Addon request failed")
+ }
+ candidate to result
+ }
+ }
+ }.awaitAll()
+ }
+ val results = mutableListOf<StremioAttributedResource<T>>()
+ val failures = mutableListOf<StremioAddonResourceFailure>()
+ outcomes.forEach { (candidate, result) ->
+ when (result) {
+ is Result.Success -> result.data.forEach { resource ->
+ results += StremioAttributedResource(candidate.addon.toSource(), resource)
+ }
+ is Result.Error -> failures += failure(candidate.addon, result.message)
+ Result.Loading -> failures += failure(candidate.addon, "Addon request did not complete")
+ }
+ }
+ return StremioResourceResolution(results, failures, candidates.size)
+ }
+
+ private fun failure(addon: StremioAddon, rawMessage: String): StremioAddonResourceFailure {
+ val sanitized = URL_PATTERN.replace(rawMessage, "addon endpoint")
+ .replace(addon.installUrl, "addon endpoint")
+ .trim()
+ .take(MAX_FAILURE_MESSAGE_LENGTH)
+ .ifBlank { "Addon request failed" }
+ return StremioAddonResourceFailure(addon.toSource(), sanitized)
+ }
+
+ private fun StremioAddon.toSource() = StremioAddonSource(
+ addonId = id,
+ addonName = name,
+ manifestId = manifestId,
+ installFingerprint = installFingerprint()
+ )
+
+ private companion object {
+ const val MAX_CONCURRENT_REQUESTS = 4
+ const val MAX_FAILURE_MESSAGE_LENGTH = 180
+ val URL_PATTERN = Regex("(?i)(?:https?|magnet)://[^\\s\\\"']+")
+ }
+}
diff --git a/domain/src/main/java/com/streamvault/domain/settings/SettingsPreferences.kt b/domain/src/main/java/com/streamvault/domain/settings/SettingsPreferences.kt
index 9d838ebf..22649528 100644
--- a/domain/src/main/java/com/streamvault/domain/settings/SettingsPreferences.kt
+++ b/domain/src/main/java/com/streamvault/domain/settings/SettingsPreferences.kt
@@ -32,6 +32,10 @@ import kotlinx.coroutines.flow.Flow
/** Preference streams and commands consumed by settings; persistence remains in the data layer. */
interface SettingsPreferences {
+ val hideStremioAddons: Flow<Boolean>
+
+ suspend fun setHideStremioAddons(hidden: Boolean)
+
val isIncognitoMode: Flow<Boolean>
val useXtreamTextClassification: Flow<Boolean>
diff --git a/domain/src/test/java/com/streamvault/domain/model/AppTopLevelDestinationTest.kt b/domain/src/test/java/com/streamvault/domain/model/AppTopLevelDestinationTest.kt
new file mode 100644
index 00000000..006bb9f0
--- /dev/null
+++ b/domain/src/test/java/com/streamvault/domain/model/AppTopLevelDestinationTest.kt
@@ -0,0 +1,28 @@
+package com.streamvault.domain.model
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class AppTopLevelDestinationTest {
+
+ @Test
+ fun `legacy plugin and addon navigation preferences migrate to extensions`() {
+ assertThat(AppTopLevelDestination.fromStorage("plugins"))
+ .isEqualTo(AppTopLevelDestination.EXTENSIONS)
+ assertThat(AppTopLevelDestination.fromStorage("ADDONS"))
+ .isEqualTo(AppTopLevelDestination.EXTENSIONS)
+ }
+
+ @Test
+ fun `legacy plugin and addon entries normalize to one extensions destination`() {
+ assertThat(
+ AppTopLevelDestination.normalizeForStorage(
+ listOf(
+ AppTopLevelDestination.fromStorage("plugins")!!,
+ AppTopLevelDestination.fromStorage("addons")!!
+ )
+ )
+ ).containsExactly(AppTopLevelDestination.EXTENSIONS, AppTopLevelDestination.SETTINGS)
+ .inOrder()
+ }
+}
diff --git a/domain/src/test/java/com/streamvault/domain/model/stremio/StremioMediaRequestHeadersTest.kt b/domain/src/test/java/com/streamvault/domain/model/stremio/StremioMediaRequestHeadersTest.kt
new file mode 100644
index 00000000..2b1b356f
--- /dev/null
+++ b/domain/src/test/java/com/streamvault/domain/model/stremio/StremioMediaRequestHeadersTest.kt
@@ -0,0 +1,45 @@
+package com.streamvault.domain.model.stremio
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class StremioMediaRequestHeadersTest {
+ @Test
+ fun `valid request headers are scoped to scheme host and port`() {
+ val scoped = stremioMediaRequestHeaders(
+ "https://Media.Example.test:443/path/master.m3u8?token=private",
+ mapOf("Authorization" to "Bearer secret", "Referer" to "https://Media.Example.test/")
+ )
+
+ assertThat(scoped?.origin).isEqualTo("https://media.example.test:443")
+ assertThat(scoped?.headers).containsEntry("Authorization", "Bearer secret")
+ }
+
+ @Test
+ fun `rejects control characters forbidden transport headers and oversized header sets`() {
+ assertThat(stremioMediaRequestHeaders("https://media.example.test/v.m3u8", mapOf("X-Test" to "ok\r\nInjected: yes")))
+ .isNull()
+ assertThat(stremioMediaRequestHeaders("https://media.example.test/v.m3u8", mapOf("Host" to "other.example.test")))
+ .isNull()
+ assertThat(stremioMediaRequestHeaders("https://media.example.test/v.m3u8", (1..33).associate { "X-$it" to "v" }))
+ .isNull()
+ }
+
+ @Test
+ fun `rejects non-http urls and urls with embedded credentials`() {
+ assertThat(stremioMediaRequestHeaders("magnet:?xt=urn:btih:abcd", emptyMap())).isNull()
+ assertThat(stremioMediaRequestHeaders("https://user:[email protected]/video", emptyMap())).isNull()
+ }
+
+ @Test
+ fun `canonicalizes IPv6 media origin and rejects duplicate case insensitive names`() {
+ assertThat(stremioMediaRequestHeaders("http://[::1]/video", emptyMap())?.origin)
+ .isEqualTo("http://[::1]:80")
+ assertThat(
+ stremioMediaRequestHeaders(
+ "https://media.example.test/video",
+ mapOf("Authorization" to "Bearer first", "authorization" to "Bearer second")
+ )
+ ).isNull()
+ }
+}
diff --git a/domain/src/test/java/com/streamvault/domain/model/stremio/StremioPlaybackHistoryIdentityTest.kt b/domain/src/test/java/com/streamvault/domain/model/stremio/StremioPlaybackHistoryIdentityTest.kt
new file mode 100644
index 00000000..8d47beee
--- /dev/null
+++ b/domain/src/test/java/com/streamvault/domain/model/stremio/StremioPlaybackHistoryIdentityTest.kt
@@ -0,0 +1,53 @@
+package com.streamvault.domain.model.stremio
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class StremioPlaybackHistoryIdentityTest {
+ private val originA = "a".repeat(64)
+ private val originB = "b".repeat(64)
+
+ @Test
+ fun `validated IMDb movie identity is shared across addons`() {
+ val keyA = stremioPlaybackContentKey("movie", "tt12345", null, originA)
+ val keyB = stremioPlaybackContentKey("movie", "tt12345", null, originB)
+
+ assertThat(keyA).isEqualTo("stremio:global:movie:tt12345")
+ assertThat(keyB).isEqualTo(keyA)
+ }
+
+ @Test
+ fun `IMDb episode identity uses the exact video id and IMDb parent`() {
+ assertThat(stremioPlaybackContentKey("series", "tt12345:1:2", "tt12345", originA))
+ .isEqualTo("stremio:global:series-episode:tt12345:1:2")
+ }
+
+ @Test
+ fun `custom IDs are scoped to catalog origin`() {
+ val keyA = stremioPlaybackContentKey("movie", "vendor:movie:7", null, originA)
+ val keyB = stremioPlaybackContentKey("movie", "vendor:movie:7", null, originB)
+
+ assertThat(keyA).isNotEqualTo(keyB)
+ assertThat(keyA).isEqualTo("stremio:addon:${originA}:movie:vendor:movie:7")
+ }
+
+ @Test
+ fun `invalid IMDb shaped and unsupported media IDs stay namespaced or unavailable`() {
+ assertThat(stremioPlaybackContentKey("movie", "tt12abc", null, originA))
+ .isEqualTo("stremio:addon:${originA}:movie:tt12abc")
+ assertThat(stremioPlaybackContentKey("channel", "tt12345", null, originA)).isNull()
+ assertThat(stremioPlaybackContentKey("movie", "tt12345", null, "bad-origin")).isNull()
+ }
+
+ @Test
+ fun `episode under a custom parent does not become globally shared`() {
+ assertThat(stremioPlaybackContentKey("series", "custom:1:2", "custom", originA))
+ .isEqualTo("stremio:addon:${originA}:series-episode:custom:1:2")
+ }
+
+ @Test
+ fun `nonstandard video id under an IMDb parent remains origin scoped`() {
+ assertThat(stremioPlaybackContentKey("series", "tt12345:cut:director", "tt12345", originA))
+ .isEqualTo("stremio:addon:${originA}:series-episode:tt12345:cut:director")
+ }
+}
diff --git a/domain/src/test/java/com/streamvault/domain/model/stremio/StremioStreamMagnetUriTest.kt b/domain/src/test/java/com/streamvault/domain/model/stremio/StremioStreamMagnetUriTest.kt
new file mode 100644
index 00000000..cd3cfae7
--- /dev/null
+++ b/domain/src/test/java/com/streamvault/domain/model/stremio/StremioStreamMagnetUriTest.kt
@@ -0,0 +1,30 @@
+package com.streamvault.domain.model.stremio
+
+import com.google.common.truth.Truth.assertThat
+import org.junit.Test
+
+class StremioStreamMagnetUriTest {
+ @Test
+ fun `adds file index to raw magnet when it has no selection`() {
+ val magnet = StremioStream(
+ url = "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567",
+ fileIdx = 4
+ ).toMagnetUri()
+
+ assertThat(magnet).isEqualTo(
+ "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&so=4"
+ )
+ }
+
+ @Test
+ fun `preserves file selection already present in raw magnet`() {
+ val magnet = StremioStream(
+ url = "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&so=2",
+ fileIdx = 4
+ ).toMagnetUri()
+
+ assertThat(magnet).isEqualTo(
+ "magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&so=2"
+ )
+ }
+}
diff --git a/domain/src/test/java/com/streamvault/domain/repository/StremioResourceResolverTest.kt b/domain/src/test/java/com/streamvault/domain/repository/StremioResourceResolverTest.kt
new file mode 100644
index 00000000..09fc2d2a
--- /dev/null
+++ b/domain/src/test/java/com/streamvault/domain/repository/StremioResourceResolverTest.kt
@@ -0,0 +1,250 @@
+package com.streamvault.domain.repository
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioInstalledAddon
+import com.streamvault.domain.model.stremio.StremioManifest
+import com.streamvault.domain.model.stremio.StremioManifestResource
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaDetail
+import com.streamvault.domain.model.stremio.StremioResourceKind
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.async
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.cancelAndJoin
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.test.runTest
+import org.junit.Test
+
+class StremioResourceResolverTest {
+ private val resolver = StremioResourceResolver()
+
+ @Test
+ fun `resource candidates honor exact type prefix enabled state and catalog origin` () {
+ val catalogOnly = installed(
+ 1,
+ resources = listOf(StremioManifestResource(StremioResourceKind.CATALOG)),
+ catalogs = listOf(
+ com.streamvault.domain.model.stremio.StremioCatalogRef(StremioMediaType.MOVIE, "top")
+ )
+ )
+ val streamOnly = installed(
+ 2,
+ types = listOf(StremioMediaType.MOVIE),
+ idPrefixes = listOf("tt"),
+ resources = listOf(
+ StremioManifestResource(
+ StremioResourceKind.STREAM,
+ types = listOf(StremioMediaType.MOVIE),
+ idPrefixes = listOf("tt")
+ )
+ )
+ )
+ val subtitleOnly = installed(
+ 3,
+ types = listOf(StremioMediaType.MOVIE),
+ idPrefixes = listOf("tt"),
+ resources = listOf(StremioManifestResource(StremioResourceKind.SUBTITLES, isStringResource = true))
+ )
+ val unrelatedPrefix = installed(
+ 4,
+ types = listOf(StremioMediaType.MOVIE),
+ idPrefixes = listOf("kitsu"),
+ resources = listOf(
+ StremioManifestResource(
+ StremioResourceKind.STREAM,
+ idPrefixes = listOf("kitsu")
+ )
+ )
+ )
+ val explicitlyEmptyPrefixes = installed(
+ 5,
+ types = listOf(StremioMediaType.MOVIE),
+ idPrefixes = emptyList(),
+ resources = listOf(
+ StremioManifestResource(StremioResourceKind.STREAM, idPrefixes = emptyList())
+ )
+ )
+ val disabled = installed(
+ 6,
+ types = listOf(StremioMediaType.MOVIE),
+ idPrefixes = listOf("tt"),
+ resources = listOf(
+ StremioManifestResource(StremioResourceKind.STREAM, idPrefixes = listOf("tt"))
+ ),
+ enabled = false
+ )
+ val addons = listOf(
+ catalogOnly,
+ streamOnly,
+ subtitleOnly,
+ unrelatedPrefix,
+ explicitlyEmptyPrefixes,
+ disabled
+ )
+
+ assertThat(
+ resolver.candidates(addons, StremioResourceKind.STREAM, StremioMediaType.MOVIE, "tt123")
+ .map { it.addon.id }
+ ).containsExactly(2L).inOrder()
+ assertThat(
+ resolver.candidates(addons, StremioResourceKind.SUBTITLES, StremioMediaType.MOVIE, "tt123")
+ .map { it.addon.id }
+ ).containsExactly(3L).inOrder()
+ assertThat(
+ resolver.candidates(
+ addons,
+ StremioResourceKind.CATALOG,
+ StremioMediaType.MOVIE,
+ "top"
+ ).map { it.addon.id }
+ ).containsExactly(1L)
+ assertThat(
+ resolver.candidates(
+ addons,
+ StremioResourceKind.CATALOG,
+ StremioMediaType.MOVIE,
+ "tt123"
+ )
+ ).isEmpty()
+ }
+
+ @Test
+ fun `resource filters preserve omitted versus explicitly empty type lists`() {
+ val inherited = installed(
+ 1,
+ types = listOf(StremioMediaType.MOVIE),
+ resources = listOf(StremioManifestResource(StremioResourceKind.META))
+ )
+ val matchNone = installed(
+ 2,
+ types = listOf(StremioMediaType.MOVIE),
+ resources = listOf(StremioManifestResource(StremioResourceKind.META, types = emptyList()))
+ )
+ val unrestricted = installed(
+ 3,
+ resources = listOf(StremioManifestResource(StremioResourceKind.META))
+ )
+
+ assertThat(
+ resolver.candidates(
+ listOf(inherited, matchNone, unrestricted),
+ StremioResourceKind.META,
+ StremioMediaType.MOVIE,
+ "custom-id"
+ ).map { it.addon.id }
+ ).containsExactly(1L, 3L).inOrder()
+ }
+
+ @Test
+ fun `metadata prefers the catalog origin then falls through failed providers`() = runTest {
+ val addons = listOf(1L, 2L, 3L).map { id ->
+ installed(
+ id,
+ types = listOf(StremioMediaType.MOVIE),
+ resources = listOf(StremioManifestResource(StremioResourceKind.META))
+ )
+ }
+ val candidates = resolver.candidates(
+ addons,
+ StremioResourceKind.META,
+ StremioMediaType.MOVIE,
+ "tt123",
+ preferredAddonId = 2L
+ )
+ val requested = mutableListOf<Long>()
+
+ val result = resolver.resolveMeta(candidates, StremioMediaType.MOVIE, "tt123") { addon ->
+ requested += addon.id
+ when (addon.id) {
+ 2L -> Result.error("provider offline")
+ 1L -> Result.success(meta("wrong-id"))
+ else -> Result.success(meta("tt123"))
+ }
+ }
+
+ assertThat(requested).containsExactly(2L, 1L, 3L).inOrder()
+ assertThat(result.result?.source?.addonId).isEqualTo(3L)
+ assertThat(result.failures.map { it.source.addonId }).containsExactly(2L, 1L).inOrder()
+ }
+
+ @Test
+ fun `fanout preserves install order partial results and bounds concurrency`() = runTest {
+ val candidates = (1L..7L).map { id ->
+ installed(
+ id,
+ types = listOf(StremioMediaType.MOVIE),
+ resources = listOf(StremioManifestResource(StremioResourceKind.STREAM))
+ )
+ }
+ var inFlight = 0
+ var maxInFlight = 0
+ val result = resolver.resolveMany(candidates) { addon ->
+ inFlight++
+ maxInFlight = maxOf(maxInFlight, inFlight)
+ delay(10)
+ inFlight--
+ if (addon.id == 2L) Result.error("provider offline") else Result.success(listOf(addon.id))
+ }
+
+ assertThat(maxInFlight).isAtMost(4)
+ assertThat(result.results.map { it.resource }).containsExactly(1L, 3L, 4L, 5L, 6L, 7L).inOrder()
+ assertThat(result.results.map { it.source.addonId }).containsExactly(1L, 3L, 4L, 5L, 6L, 7L).inOrder()
+ assertThat(result.failures.single().source.addonId).isEqualTo(2L)
+ assertThat(result.candidateCount).isEqualTo(7)
+ }
+
+ @Test
+ fun `cancelling fanout cancels outstanding addon requests`() = runTest {
+ val started = CompletableDeferred<Unit>()
+ val candidate = installed(
+ 1,
+ types = listOf(StremioMediaType.MOVIE),
+ resources = listOf(StremioManifestResource(StremioResourceKind.STREAM))
+ )
+ val request = async {
+ resolver.resolveMany<Long>(listOf(candidate)) {
+ started.complete(Unit)
+ awaitCancellation()
+ }
+ }
+ started.await()
+ request.cancelAndJoin()
+ assertThat(request.isCancelled).isTrue()
+ }
+
+ private fun installed(
+ id: Long,
+ types: List<StremioMediaType>? = null,
+ idPrefixes: List<String>? = null,
+ resources: List<StremioManifestResource>,
+ catalogs: List<com.streamvault.domain.model.stremio.StremioCatalogRef> = emptyList(),
+ enabled: Boolean = true
+ ): StremioInstalledAddon {
+ val addon = StremioAddon(
+ id = id,
+ installUrl = "https://example.test/$id/manifest.json",
+ manifestId = "test.$id",
+ name = "Addon $id",
+ version = "1.0.0",
+ enabled = enabled
+ )
+ val manifest = StremioManifest(
+ id = addon.manifestId,
+ name = addon.name,
+ version = addon.version,
+ types = types,
+ idPrefixes = idPrefixes,
+ resources = resources,
+ catalogs = catalogs
+ )
+ return StremioInstalledAddon(addon, manifest)
+ }
+
+ private fun meta(id: String) = StremioMetaDetail(
+ id = id,
+ type = StremioMediaType.MOVIE,
+ name = id
+ )
+}
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/api/PlaybackServicePorts.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/api/PlaybackServicePorts.kt
index a38c7f63..e3c97722 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/api/PlaybackServicePorts.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/api/PlaybackServicePorts.kt
@@ -36,6 +36,9 @@ enum class CastRewriteRequiredReason {
interface PlaybackStreamPreparer {
suspend fun prepare(streamInfo: StreamInfo): Result<StreamInfo>
+
+ /** Gives the owning plugin a chance to release resources for a prepared stream. */
+ fun stop(streamInfo: StreamInfo) = Unit
}
interface CastUrlRewriter {
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/cast/CastMediaRequestFactory.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/cast/CastMediaRequestFactory.kt
index c43fd540..19f53aad 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/cast/CastMediaRequestFactory.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/cast/CastMediaRequestFactory.kt
@@ -21,6 +21,12 @@ class CastMediaRequestFactory @Inject constructor() {
): CastMediaRequestBuildResult {
val resolvedUrl = streamInfo.url.takeIf { it.isNotBlank() }
?: return CastMediaRequestBuildResult.Unsupported(CastMediaRequestUnsupportedReason.EMPTY_URL)
+ if (runCatching { URI(resolvedUrl).scheme.equals("magnet", ignoreCase = true) }.getOrDefault(false)) {
+ return CastMediaRequestBuildResult.Unsupported(CastMediaRequestUnsupportedReason.UNSUPPORTED_PROTOCOL)
+ }
+ if (streamInfo.requestHeadersOrigin != null && streamInfo.headers.isNotEmpty()) {
+ return CastMediaRequestBuildResult.Unsupported(CastMediaRequestUnsupportedReason.SCOPED_HEADERS_UNSUPPORTED)
+ }
if (streamInfo.drmInfo != null) {
return CastMediaRequestBuildResult.Unsupported(CastMediaRequestUnsupportedReason.DRM_PROTECTED)
}
@@ -96,7 +102,8 @@ enum class CastMediaRequestUnsupportedReason {
STREAM_UNAVAILABLE,
EMPTY_URL,
UNSUPPORTED_PROTOCOL,
- DRM_PROTECTED
+ DRM_PROTECTED,
+ SCOPED_HEADERS_UNSUPPORTED
}
internal fun StreamInfo.inferCastStreamType(): StreamType {
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/cast/CastUiMessages.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/cast/CastUiMessages.kt
index 0bf10154..175cb7ef 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/cast/CastUiMessages.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/cast/CastUiMessages.kt
@@ -9,6 +9,7 @@ fun CastMediaRequestUnsupportedReason.toCastBuildFailureMessageRes(): Int = when
CastMediaRequestUnsupportedReason.EMPTY_URL -> R.string.cast_item_unavailable
CastMediaRequestUnsupportedReason.UNSUPPORTED_PROTOCOL -> R.string.cast_protocol_unsupported
CastMediaRequestUnsupportedReason.DRM_PROTECTED -> R.string.cast_drm_unsupported
+ CastMediaRequestUnsupportedReason.SCOPED_HEADERS_UNSUPPORTED -> R.string.cast_scoped_headers_unsupported
}
fun CastMediaRequest.toCastUnsupportedMessageRes(): Int = when (rewriteRequiredReason) {
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/navigation/PlaybackGraph.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/navigation/PlaybackGraph.kt
index 2c04a08d..15da97d7 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/navigation/PlaybackGraph.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/navigation/PlaybackGraph.kt
@@ -62,6 +62,9 @@ fun NavGraphBuilder.registerPlaybackGraph(
seasonNumber = safePlayerRequest.seasonNumber,
episodeNumber = safePlayerRequest.episodeNumber,
episodeId = safePlayerRequest.episodeId,
+ stremioPlaybackReference = safePlayerRequest.stremioPlaybackReference,
+ stremioMediaRequestHeaders = safePlayerRequest.stremioMediaRequestHeaders,
+ stremioInlineSubtitles = safePlayerRequest.stremioInlineSubtitles,
onBack = { actions.returnTo(safePlayerRequest.returnDestination) },
playbackPlatformHost = platformHost,
splitScreenPlanner = { pendingChannel, onDismiss, onLaunch ->
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerAutoPlayActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerAutoPlayActions.kt
index d8a0b552..b4f368c8 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerAutoPlayActions.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerAutoPlayActions.kt
@@ -11,6 +11,18 @@ private const val AUTO_PLAY_COUNTDOWN_SECONDS = 10
internal suspend fun PlayerViewModel.persistPlaybackCompletion() {
val durationMs = playerEngine.duration.value
+ if (currentStremioPlaybackReference != null) {
+ val history = buildStremioPlaybackHistorySnapshot(
+ positionMs = durationMs.coerceAtLeast(playerEngine.currentPosition.value),
+ durationMs = durationMs,
+ watched = true
+ ) ?: return
+ logRepositoryFailure(
+ operation = "Mark Stremio playback watched",
+ result = playbackHistoryCoordinator.saveStremioPlaybackHistory(history)
+ )
+ return
+ }
val completedHistory = buildPlaybackHistorySnapshot(
positionMs = durationMs.coerceAtLeast(playerEngine.currentPosition.value),
durationMs = durationMs
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt
index 98b721df..5420c323 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerControlsOverlayHost.kt
@@ -91,6 +91,7 @@ internal fun PlayerControlsOverlayHost(
val currentSeries by viewModel.currentSeries.collectAsStateWithLifecycle()
val availableAudioTracks by viewModel.availableAudioTracks.collectAsStateWithLifecycle()
val availableSubtitleTracks by viewModel.availableSubtitleTracks.collectAsStateWithLifecycle()
+ val stremioSubtitlePickerState by viewModel.stremioSubtitlePickerState.collectAsStateWithLifecycle()
val availableVideoQualities by viewModel.availableVideoQualities.collectAsStateWithLifecycle()
val liveTranslationAvailable by viewModel.liveTranslationAvailable.collectAsStateWithLifecycle()
val currentChannelRecording by viewModel.currentChannelRecording.collectAsStateWithLifecycle()
@@ -116,6 +117,7 @@ internal fun PlayerControlsOverlayHost(
currentPositionMs = currentPosition,
showEpisodesAction = canOpenEpisodePicker,
subtitleTrackCount = availableSubtitleTracks.size,
+ showStremioSubtitleAction = stremioSubtitlePickerState.enabled,
audioTrackCount = availableAudioTracks.size,
videoQualityCount = availableVideoQualities.size,
audioVideoSyncEnabled = audioVideoSyncEnabled,
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerHistoryCoordinator.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerHistoryCoordinator.kt
index d3820424..8aae6e90 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerHistoryCoordinator.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerHistoryCoordinator.kt
@@ -4,7 +4,9 @@ import com.streamvault.feature.playback.api.PlaybackSurfaceRefreshPort
import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
import com.streamvault.domain.repository.PlaybackHistoryRepository
+import com.streamvault.domain.repository.StremioPlaybackHistoryRepository
import com.streamvault.domain.usecase.MarkAsWatched
import kotlinx.coroutines.flow.Flow
import javax.inject.Inject
@@ -12,6 +14,7 @@ import javax.inject.Inject
/** Keeps player history reads and writes behind one feature-scoped boundary. */
class PlayerHistoryCoordinator @Inject constructor(
private val repository: PlaybackHistoryRepository,
+ private val stremioRepository: StremioPlaybackHistoryRepository,
private val playbackSurfaceRefreshPort: PlaybackSurfaceRefreshPort,
private val markAsWatched: MarkAsWatched
) {
@@ -50,6 +53,12 @@ class PlayerHistoryCoordinator @Inject constructor(
internal suspend fun flushPendingProgress(): Result<Unit> =
repository.flushPendingProgress()
+ internal suspend fun getStremioPlaybackHistory(contentKey: String): StremioPlaybackHistory? =
+ stremioRepository.get(contentKey)
+
+ internal suspend fun saveStremioPlaybackHistory(history: StremioPlaybackHistory): Result<Unit> =
+ stremioRepository.save(history)
+
internal suspend fun refreshPlaybackSurfaces() {
playbackSurfaceRefreshPort.refreshWatchNext()
playbackSurfaceRefreshPort.refreshRecommendations()
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt
index 0ccb4bbc..fa2e3d12 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerLifecycleActions.kt
@@ -67,12 +67,21 @@ internal fun isUsableTokenRenewalExpiry(
/** Captures the old content before prepare mutates the shared playback context. */
internal fun PlayerViewModel.queueContentSwitchProgressFlush(): Job? {
if (currentContentType == ContentType.LIVE) return null
- val history = buildPlaybackHistorySnapshot(
+ val stremioHistory = buildStremioPlaybackHistorySnapshot(
positionMs = playerEngine.currentPosition.value,
durationMs = playerEngine.duration.value
)
+ val history = buildPlaybackHistorySnapshot(
+ positionMs = playerEngine.currentPosition.value,
+ durationMs = playerEngine.duration.value
+ ).takeIf { currentStremioPlaybackReference == null }
return viewModelScope.launch {
- if (history != null) {
+ if (stremioHistory != null) {
+ logRepositoryFailure(
+ operation = "Flush Stremio progress for content switch",
+ result = playbackHistoryCoordinator.saveStremioPlaybackHistory(stremioHistory)
+ )
+ } else if (history != null) {
val result = playbackHistoryCoordinator.updateResumePosition(history)
logRepositoryFailure(
operation = "Flush playback progress for content switch",
@@ -96,9 +105,21 @@ internal fun PlayerViewModel.queueContentSwitchProgressFlush(): Job? {
*/
internal fun PlayerViewModel.queueForcedProgressFlush(): Job? {
if (currentContentType == ContentType.LIVE) return null
- val history = buildPlaybackHistorySnapshot(playerEngine.currentPosition.value, playerEngine.duration.value)
+ val stremioHistory = buildStremioPlaybackHistorySnapshot(
+ playerEngine.currentPosition.value,
+ playerEngine.duration.value
+ )
+ val history = buildPlaybackHistorySnapshot(
+ playerEngine.currentPosition.value,
+ playerEngine.duration.value
+ ).takeIf { currentStremioPlaybackReference == null }
return viewModelScope.launch {
- if (history != null) {
+ if (stremioHistory != null) {
+ logRepositoryFailure(
+ "Persist Stremio playback progress",
+ playbackHistoryCoordinator.saveStremioPlaybackHistory(stremioHistory)
+ )
+ } else if (history != null) {
val result = playbackHistoryCoordinator.updateResumePosition(history)
logRepositoryFailure("Persist playback resume position", result)
if (result.isSuccess) playbackHistoryCoordinator.updateWatchNextProgress(history)
@@ -129,6 +150,14 @@ internal suspend fun PlayerViewModel.persistPlaybackProgress() {
val dur = playerEngine.duration.value
if (pos > 0 && dur > 0) {
+ if (currentStremioPlaybackReference != null) {
+ val history = buildStremioPlaybackHistorySnapshot(pos, dur) ?: return
+ logRepositoryFailure(
+ "Persist Stremio playback progress",
+ playbackHistoryCoordinator.saveStremioPlaybackHistory(history)
+ )
+ return
+ }
val history = buildPlaybackHistorySnapshot(pos, dur) ?: return
val result = playbackHistoryCoordinator.updateResumePosition(history)
logRepositoryFailure(
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalHosts.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalHosts.kt
index d0a34f62..69fd0219 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalHosts.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerModalHosts.kt
@@ -93,11 +93,15 @@ internal fun PlayerControlsModalHost(
}
if (!isInPictureInPictureMode && showTrackSelection != null) {
+ LaunchedEffect(showTrackSelection) {
+ if (showTrackSelection == TrackType.TEXT) viewModel.loadStremioAddonSubtitles()
+ }
val availableAudioTracks by viewModel.availableAudioTracks.collectAsStateWithLifecycle()
val availableSubtitleTracks by viewModel.availableSubtitleTracks.collectAsStateWithLifecycle()
val availableVideoQualities by viewModel.availableVideoQualities.collectAsStateWithLifecycle()
val liveTranslationAvailable by viewModel.liveTranslationAvailable.collectAsStateWithLifecycle()
val liveTranslationActive by viewModel.liveTranslationActive.collectAsStateWithLifecycle()
+ val stremioSubtitlePicker by viewModel.stremioSubtitlePickerState.collectAsStateWithLifecycle()
PlayerTrackSelectionDialog(
trackType = showTrackSelection,
audioTracks = availableAudioTracks,
@@ -105,6 +109,7 @@ internal fun PlayerControlsModalHost(
videoTracks = availableVideoQualities,
liveTranslationAvailable = liveTranslationAvailable,
liveTranslationActive = liveTranslationActive,
+ stremioSubtitlePicker = stremioSubtitlePicker,
onDismiss = onDismissModal,
onSelectAudio = viewModel::selectAudioTrack,
onSelectVideo = viewModel::selectVideoQuality,
@@ -115,7 +120,9 @@ internal fun PlayerControlsModalHost(
onSelectLiveTranslation = {
viewModel.selectSubtitleTrack(null)
viewModel.activateLiveTranslation()
- }
+ },
+ onSelectStremioSubtitle = viewModel::selectStremioSubtitle,
+ onRetryStremioSubtitles = viewModel::retryStremioAddonSubtitles
)
}
if (!isInPictureInPictureMode && showVariantSelection) {
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.kt
index d4980f74..2abe0737 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerPreparationCoordinator.kt
@@ -30,6 +30,10 @@ class PlayerPreparationCoordinator @Inject constructor(
private val playerEngineCoordinator: PlayerEngineCoordinator,
private val playerContentResolver: PlayerContentResolver
) {
+ internal fun stopPlayback(streamInfo: StreamInfo?) {
+ streamInfo?.let(streamPreparer::stop)
+ }
+
internal data class Request(
val streamInfo: StreamInfo,
val contentType: ContentType,
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerScreen.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerScreen.kt
index 3ac21dcd..5c57fef6 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerScreen.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerScreen.kt
@@ -93,6 +93,8 @@ import com.streamvault.feature.playback.player.overlay.NextEpisodeCountdownOverl
import com.streamvault.feature.playback.player.overlay.SkipChapterOverlay
import com.streamvault.feature.playback.player.LiveClockOverlay
import com.streamvault.core.navigation.AppDestination
+import com.streamvault.core.navigation.StremioPlaybackReference
+import com.streamvault.core.navigation.StremioSubtitlePlaybackSource
@@ -119,6 +121,9 @@ fun PlayerScreen(
seasonNumber: Int? = null,
episodeNumber: Int? = null,
episodeId: Long? = null,
+ stremioPlaybackReference: StremioPlaybackReference? = null,
+ stremioMediaRequestHeaders: Map<String, String> = emptyMap(),
+ stremioInlineSubtitles: List<StremioSubtitlePlaybackSource> = emptyList(),
returnDestination: AppDestination? = null,
onBack: () -> Unit,
onNavigate: ((AppDestination) -> Unit)? = null,
@@ -320,7 +325,10 @@ fun PlayerScreen(
combinedSourceFilterProviderId = combinedSourceFilterProviderId,
contentType = contentType,
archiveStartMs = archiveStartMs,
- archiveEndMs = archiveEndMs
+ archiveEndMs = archiveEndMs,
+ stremioPlaybackReference = stremioPlaybackReference,
+ stremioMediaRequestHeaders = stremioMediaRequestHeaders,
+ stremioInlineSubtitles = stremioInlineSubtitles
)
LaunchedEffect(prepareIdentity) {
@@ -342,7 +350,10 @@ fun PlayerScreen(
seriesId = seriesId,
seasonNumber = seasonNumber,
episodeNumber = episodeNumber,
- episodeId = episodeId
+ episodeId = episodeId,
+ stremioPlaybackReference = stremioPlaybackReference,
+ stremioMediaRequestHeaders = stremioMediaRequestHeaders,
+ stremioInlineSubtitles = stremioInlineSubtitles
)
}
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt
index 711bb64f..bb83b4c8 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModel.kt
@@ -1,6 +1,9 @@
package com.streamvault.feature.playback.player
+import android.net.Uri
import android.os.SystemClock
+import com.streamvault.core.navigation.StremioPlaybackReference
+import com.streamvault.core.navigation.StremioSubtitlePlaybackSource
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.feature.playback.cast.CastConnectionState
@@ -23,6 +26,11 @@ import com.streamvault.domain.model.ProviderType
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.Series
import com.streamvault.domain.model.StreamInfo
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.stremioPlaybackContentKey
+import com.streamvault.domain.model.stremio.stremioMediaRequestHeaders as validateStremioMediaRequestHeaders
+import com.streamvault.domain.repository.StremioAddonRepository
import com.streamvault.domain.model.VirtualCategoryIds
import com.streamvault.domain.model.VideoFormat
import com.streamvault.domain.settings.VodTrackPreferences
@@ -49,6 +57,7 @@ import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import kotlinx.coroutines.sync.Mutex
import android.content.Context
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
import javax.inject.Inject
@HiltViewModel
@@ -76,6 +85,7 @@ class PlayerViewModel @Inject constructor(
internal val playerPlaybackContextCoordinator: PlayerPlaybackContextCoordinator,
internal val playerRecoveryCoordinator: PlayerRecoveryCoordinator,
internal val playerRecoveryExecutionCoordinator: PlayerRecoveryExecutionCoordinator,
+ private val stremioAddonRepository: StremioAddonRepository
) : ViewModel() {
companion object {
private const val MIN_WATCHED_FOR_AUTO_PLAY_MS = 5_000L
@@ -176,6 +186,9 @@ class PlayerViewModel @Inject constructor(
internal val _playerNotice = MutableStateFlow<PlayerNoticeState?>(null)
val playerNotice: StateFlow<PlayerNoticeState?> = _playerNotice.asStateFlow()
+ private val _stremioSubtitlePickerState = MutableStateFlow(StremioSubtitlePickerState())
+ val stremioSubtitlePickerState: StateFlow<StremioSubtitlePickerState> =
+ _stremioSubtitlePickerState.asStateFlow()
private val _playerDiagnostics = MutableStateFlow(PlayerDiagnosticsUiState())
val playerDiagnostics: StateFlow<PlayerDiagnosticsUiState> = _playerDiagnostics.asStateFlow()
internal val audioVideoOffsetPreviewMs = MutableStateFlow<Int?>(null)
@@ -218,6 +231,10 @@ class PlayerViewModel @Inject constructor(
internal val livePlaybackRecordCoordinator =
LivePlaybackRecordCoordinator(playbackHistoryCoordinator::recordPlayback)
private var currentStreamClassLabel: String = "Primary"
+ internal var currentStremioPlaybackReference: StremioPlaybackReference? = null
+ private var currentStremioInlineSubtitles: List<StremioSubtitlePlaybackSource> = emptyList()
+ private var stremioSubtitleLoadJob: Job? = null
+ private var loadedStremioSubtitleLookupKey: String? = null
internal var lastRecordedVariantObservationSignature: String? = null
internal var lastRecordedVodVariantObservationSignature: String? = null
internal val playbackSessionCoordinator = PlaybackSessionCoordinator(viewModelScope)
@@ -1224,6 +1241,82 @@ class PlayerViewModel @Inject constructor(
)
}
+ internal fun buildStremioPlaybackHistorySnapshot(
+ positionMs: Long,
+ durationMs: Long,
+ watched: Boolean = false
+ ): StremioPlaybackHistory? {
+ val reference = currentStremioPlaybackReference ?: return null
+ return buildStremioPlaybackHistorySnapshot(
+ reference = reference,
+ positionMs = positionMs,
+ durationMs = durationMs,
+ title = currentTitle,
+ posterUrl = currentArtworkUrl,
+ watched = watched
+ )
+ }
+
+ fun loadStremioAddonSubtitles() = resolveStremioAddonSubtitles(forceRefresh = false)
+
+ fun retryStremioAddonSubtitles() = resolveStremioAddonSubtitles(forceRefresh = true)
+
+ fun selectStremioSubtitle(option: StremioPlayerSubtitleOption) {
+ if (option !in _stremioSubtitlePickerState.value.options) return
+ val uri = option.url.trim().toHttpUrlOrNull()?.toString()?.let { Uri.parse(it) } ?: return
+ playerEngine.addExternalSubtitle(uri, option.languageTag, option.label)
+ }
+
+ private fun resolveStremioAddonSubtitles(forceRefresh: Boolean) {
+ val reference = currentStremioPlaybackReference ?: return
+ val mediaType = StremioMediaType.fromTypeName(reference.mediaType)
+ if (mediaType == StremioMediaType.UNKNOWN) return
+ val lookupKey = listOf(
+ reference.mediaType,
+ reference.exactVideoId,
+ reference.videoHash.orEmpty(),
+ reference.videoSize?.toString().orEmpty(),
+ reference.filename.orEmpty()
+ ).joinToString("|")
+ if (!forceRefresh && (
+ loadedStremioSubtitleLookupKey == lookupKey || stremioSubtitleLoadJob?.isActive == true
+ )
+ ) return
+
+ stremioSubtitleLoadJob?.cancel()
+ loadedStremioSubtitleLookupKey = lookupKey
+ _stremioSubtitlePickerState.update {
+ it.copy(loading = true, failed = false)
+ }
+ stremioSubtitleLoadJob = viewModelScope.launch {
+ try {
+ val result = stremioAddonRepository.resolveSubtitles(
+ type = mediaType,
+ exactVideoId = reference.exactVideoId,
+ videoHash = reference.videoHash,
+ videoSize = reference.videoSize,
+ filename = reference.filename
+ )
+ if (currentStremioPlaybackReference != reference) return@launch
+ _stremioSubtitlePickerState.value = StremioSubtitlePickerState(
+ enabled = true,
+ loading = false,
+ failed = result.failures.isNotEmpty(),
+ options = buildStremioPlayerSubtitleOptions(
+ inlineSubtitles = currentStremioInlineSubtitles,
+ addonSubtitles = result.results
+ )
+ )
+ } catch (cancellation: kotlinx.coroutines.CancellationException) {
+ throw cancellation
+ } catch (_: Exception) {
+ if (currentStremioPlaybackReference == reference) {
+ _stremioSubtitlePickerState.update { it.copy(loading = false, failed = true) }
+ }
+ }
+ }
+ }
+
internal fun isActivePlaybackSession(
requestVersion: Long,
expectedLogicalUrl: String? = null
@@ -1347,7 +1440,10 @@ class PlayerViewModel @Inject constructor(
seasonNumber: Int? = null,
episodeNumber: Int? = null,
episodeId: Long? = null,
- showResumePrompt: Boolean = true
+ showResumePrompt: Boolean = true,
+ stremioPlaybackReference: StremioPlaybackReference? = null,
+ stremioMediaRequestHeaders: Map<String, String> = emptyMap(),
+ stremioInlineSubtitles: List<StremioSubtitlePlaybackSource> = emptyList()
) {
val hasArchiveRequest = hasArchivePlaybackIdentity(
contentType = contentType,
@@ -1362,6 +1458,19 @@ class PlayerViewModel @Inject constructor(
PlaybackResolutionUiState.Resolving
}
val contentSwitchFlush = queueContentSwitchProgressFlush()
+ if (
+ currentStremioPlaybackReference != stremioPlaybackReference ||
+ currentStremioInlineSubtitles != stremioInlineSubtitles
+ ) {
+ stremioSubtitleLoadJob?.cancel()
+ loadedStremioSubtitleLookupKey = null
+ _stremioSubtitlePickerState.value = StremioSubtitlePickerState(
+ enabled = stremioPlaybackReference != null,
+ options = buildStremioPlayerSubtitleOptions(stremioInlineSubtitles, emptyList())
+ )
+ }
+ currentStremioPlaybackReference = stremioPlaybackReference
+ currentStremioInlineSubtitles = stremioInlineSubtitles
val requestVersion = beginPlaybackSession()
val shouldReloadPlaylist = applyPrepareSessionState(
streamUrl = streamUrl,
@@ -1387,7 +1496,7 @@ class PlayerViewModel @Inject constructor(
playbackSessionScope(requestVersion)?.launch {
contentSwitchFlush?.join()
if (!isActivePlaybackSession(requestVersion)) return@launch
- if (playerPreviewCoordinator.tryAdoptFullscreenHandoff(
+ if (stremioPlaybackReference == null && playerPreviewCoordinator.tryAdoptFullscreenHandoff(
channelId = internalChannelId,
providerId = providerId,
contentType = currentContentType,
@@ -1453,7 +1562,24 @@ class PlayerViewModel @Inject constructor(
currentContentType
)
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
- val streamInfo = resolution.streamInfo
+ val resolvedStreamInfo = resolution.streamInfo
+ val scopedHeaders = if (stremioPlaybackReference != null) {
+ validateStremioMediaRequestHeaders(streamUrl, stremioMediaRequestHeaders)
+ } else null
+ if (stremioPlaybackReference != null && scopedHeaders == null) {
+ _playbackResolutionUiState.value = PlaybackResolutionUiState.Failure(
+ "The selected addon stream supplied invalid media request headers."
+ )
+ return@launch
+ }
+ val streamInfo = resolvedStreamInfo?.let { resolved ->
+ scopedHeaders?.let { validated ->
+ resolved.copy(
+ headers = validated.headers,
+ requestHeadersOrigin = validated.origin
+ )
+ } ?: resolved
+ }
if (streamInfo == null) {
if (!isActivePlaybackSession(requestVersion, streamUrl)) return@launch
resolution.failureMessage?.let(::setLastFailureReason)
@@ -1472,24 +1598,44 @@ class PlayerViewModel @Inject constructor(
// Check for resume position after the player is fully prepared (VOD only).
// Doing this after preparePlayer ensures pause() acts on the live player instance,
// not a stale one that may have already been replaced by prepareInternal().
- if (showResumePrompt && currentContentType != ContentType.LIVE && currentContentId != -1L && currentProviderId != -1L) {
- val history = playbackHistoryCoordinator.getPlaybackHistory(
- contentId = currentContentId,
- contentType = currentContentType,
- providerId = currentProviderId,
- seriesId = currentSeriesId,
- seasonNumber = currentSeasonNumber,
- episodeNumber = currentEpisodeNumber
- )
- if (isActivePlaybackSession(requestVersion, playbackLogicalUrl)) {
- if (history != null && history.resumePositionMs > 5000L && !isPlaybackComplete(history.resumePositionMs, history.totalDurationMs)) {
- playerEngine.pause()
- _resumePrompt.value = ResumePromptState(
- show = true,
- positionMs = history.resumePositionMs,
- title = currentTitle
- )
- }
+ if (showResumePrompt && currentContentType != ContentType.LIVE) {
+ val reference = currentStremioPlaybackReference
+ val contentKey = reference?.let {
+ stremioPlaybackContentKey(
+ mediaType = it.mediaType,
+ exactVideoId = it.exactVideoId,
+ parentSeriesId = it.parentSeriesId,
+ catalogOriginKey = it.catalogOriginKey
+ )
+ }
+ val stremioHistory = contentKey?.let {
+ playbackHistoryCoordinator.getStremioPlaybackHistory(it)
+ }
+ val providerHistory = if (
+ reference == null && currentContentId != -1L && currentProviderId != -1L
+ ) {
+ playbackHistoryCoordinator.getPlaybackHistory(
+ contentId = currentContentId,
+ contentType = currentContentType,
+ providerId = currentProviderId,
+ seriesId = currentSeriesId,
+ seasonNumber = currentSeasonNumber,
+ episodeNumber = currentEpisodeNumber
+ )
+ } else null
+ val resumePosition = stremioHistory?.takeUnless { it.watched }?.resumePositionMs
+ ?: providerHistory?.resumePositionMs
+ val resumeDuration = stremioHistory?.totalDurationMs ?: providerHistory?.totalDurationMs
+ if (isActivePlaybackSession(requestVersion, playbackLogicalUrl) &&
+ resumePosition != null && resumeDuration != null && resumePosition > 5000L &&
+ !isPlaybackComplete(resumePosition, resumeDuration)
+ ) {
+ playerEngine.pause()
+ _resumePrompt.value = ResumePromptState(
+ show = true,
+ positionMs = resumePosition,
+ title = currentTitle
+ )
}
}
}
@@ -1731,6 +1877,7 @@ class PlayerViewModel @Inject constructor(
override fun onCleared() {
playbackSessionCoordinator.invalidate()
+ playerPreparationCoordinator.stopPlayback(currentResolvedStreamInfo)
super.onCleared()
cleanupAfterCleared(playerEngineCoordinator.mainEngine)
}
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModelModels.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModelModels.kt
index a4d92cc7..52b74557 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModelModels.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/PlayerViewModelModels.kt
@@ -1,6 +1,8 @@
package com.streamvault.feature.playback.player
import android.graphics.Bitmap
+import com.streamvault.core.navigation.StremioPlaybackReference
+import com.streamvault.core.navigation.StremioSubtitlePlaybackSource
import com.streamvault.domain.model.Channel
import com.streamvault.domain.model.ChannelQualityOption
import com.streamvault.domain.model.ContentType
@@ -145,7 +147,10 @@ data class PlayerPrepareIdentity(
val combinedSourceFilterProviderId: Long?,
val contentType: String,
val archiveStartMs: Long?,
- val archiveEndMs: Long?
+ val archiveEndMs: Long?,
+ val stremioPlaybackReference: StremioPlaybackReference? = null,
+ val stremioMediaRequestHeaders: Map<String, String> = emptyMap(),
+ val stremioInlineSubtitles: List<StremioSubtitlePlaybackSource> = emptyList()
)
internal fun buildPlayerPrepareIdentity(
@@ -159,7 +164,10 @@ internal fun buildPlayerPrepareIdentity(
combinedSourceFilterProviderId: Long?,
contentType: String,
archiveStartMs: Long?,
- archiveEndMs: Long?
+ archiveEndMs: Long?,
+ stremioPlaybackReference: StremioPlaybackReference? = null,
+ stremioMediaRequestHeaders: Map<String, String> = emptyMap(),
+ stremioInlineSubtitles: List<StremioSubtitlePlaybackSource> = emptyList()
): PlayerPrepareIdentity = PlayerPrepareIdentity(
streamUrl = streamUrl,
epgChannelId = epgChannelId,
@@ -171,7 +179,10 @@ internal fun buildPlayerPrepareIdentity(
combinedSourceFilterProviderId = combinedSourceFilterProviderId?.takeIf { it > 0L },
contentType = contentType,
archiveStartMs = archiveStartMs,
- archiveEndMs = archiveEndMs
+ archiveEndMs = archiveEndMs,
+ stremioPlaybackReference = stremioPlaybackReference,
+ stremioMediaRequestHeaders = stremioMediaRequestHeaders,
+ stremioInlineSubtitles = stremioInlineSubtitles
)
internal fun hasArchivePlaybackIdentity(
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/StremioPlaybackHistorySupport.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/StremioPlaybackHistorySupport.kt
new file mode 100644
index 00000000..a34e6d83
--- /dev/null
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/StremioPlaybackHistorySupport.kt
@@ -0,0 +1,37 @@
+package com.streamvault.feature.playback.player
+
+import com.streamvault.core.navigation.StremioPlaybackReference
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
+import com.streamvault.domain.model.stremio.stremioPlaybackContentKey
+
+internal fun buildStremioPlaybackHistorySnapshot(
+ reference: StremioPlaybackReference,
+ positionMs: Long,
+ durationMs: Long,
+ title: String,
+ posterUrl: String?,
+ watched: Boolean = false,
+ lastWatchedAt: Long = System.currentTimeMillis()
+): StremioPlaybackHistory? {
+ if (positionMs < 0L || durationMs <= 0L) return null
+ val contentKey = stremioPlaybackContentKey(
+ mediaType = reference.mediaType,
+ exactVideoId = reference.exactVideoId,
+ parentSeriesId = reference.parentSeriesId,
+ catalogOriginKey = reference.catalogOriginKey
+ ) ?: return null
+ return StremioPlaybackHistory(
+ contentKey = contentKey,
+ mediaType = reference.mediaType,
+ exactVideoId = reference.exactVideoId,
+ parentSeriesId = reference.parentSeriesId,
+ title = title,
+ posterUrl = posterUrl,
+ resumePositionMs = if (watched) durationMs else positionMs.coerceAtMost(durationMs),
+ totalDurationMs = durationMs,
+ watched = watched,
+ lastWatchedAt = lastWatchedAt,
+ catalogOriginKey = reference.catalogOriginKey,
+ streamOriginKeyHint = reference.streamOriginKey
+ )
+}
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/StremioSubtitleSupport.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/StremioSubtitleSupport.kt
new file mode 100644
index 00000000..d90ae7c5
--- /dev/null
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/StremioSubtitleSupport.kt
@@ -0,0 +1,136 @@
+package com.streamvault.feature.playback.player
+
+import com.streamvault.core.navigation.StremioSubtitlePlaybackSource
+import com.streamvault.domain.model.stremio.StremioAttributedResource
+import com.streamvault.domain.model.stremio.StremioSubtitle
+import java.util.Locale
+import okhttp3.HttpUrl.Companion.toHttpUrlOrNull
+
+data class StremioPlayerSubtitleOption(
+ val key: String,
+ val url: String,
+ val languageTag: String,
+ val label: String
+)
+
+data class StremioSubtitlePickerState(
+ val enabled: Boolean = false,
+ val loading: Boolean = false,
+ val failed: Boolean = false,
+ val options: List<StremioPlayerSubtitleOption> = emptyList()
+)
+
+internal fun buildStremioPlayerSubtitleOptions(
+ inlineSubtitles: List<StremioSubtitlePlaybackSource>,
+ addonSubtitles: List<StremioAttributedResource<StremioSubtitle>>
+): List<StremioPlayerSubtitleOption> {
+ val candidates = buildList {
+ inlineSubtitles.forEachIndexed { index, subtitle ->
+ add(
+ subtitleOption(
+ url = subtitle.url,
+ language = subtitle.language,
+ id = subtitle.id,
+ sourceKey = "inline",
+ sourceLabel = "Stream",
+ index = index
+ )
+ )
+ }
+ addonSubtitles.forEach { attributed ->
+ add(
+ subtitleOption(
+ url = attributed.resource.url,
+ language = attributed.resource.lang,
+ id = attributed.resource.id,
+ sourceKey = attributed.source.installFingerprint,
+ sourceLabel = attributed.source.addonName,
+ index = 0
+ )
+ )
+ }
+ }.filterNotNull()
+
+ return candidates.distinctBy { "${it.url}\u0000${it.languageTag}" }
+}
+
+internal fun stremioSubtitleLanguageTag(language: String): String {
+ val raw = language.trim().replace('_', '-')
+ if (raw.isEmpty()) return "und"
+ val parts = raw.split('-')
+ val primary = parts.first().lowercase(Locale.ROOT)
+ val languageCode = when {
+ primary.length == 2 && primary.all(Char::isLetter) -> primary
+ primary.length == 3 && primary.all(Char::isLetter) ->
+ ISO_639_3_TO_639_1[primary] ?: ISO_639_3_ALIASES[primary] ?: "und"
+ else -> "und"
+ }
+ if (languageCode == "und" || parts.size == 1) return languageCode
+ val regionAndVariants = parts.drop(1).filter { it.isNotBlank() }
+ return (listOf(languageCode) + regionAndVariants
+ .map { part ->
+ when {
+ part.length == 2 && part.all(Char::isLetter) -> part.uppercase(Locale.ROOT)
+ part.length == 4 && part.all(Char::isLetter) ->
+ part.lowercase(Locale.ROOT).replaceFirstChar(Char::uppercaseChar)
+ else -> part.lowercase(Locale.ROOT)
+ }
+ }
+ )
+ .joinToString("-")
+}
+
+private fun subtitleOption(
+ url: String,
+ language: String,
+ id: String?,
+ sourceKey: String,
+ sourceLabel: String,
+ index: Int
+): StremioPlayerSubtitleOption? {
+ val canonicalUrl = url.trim().toHttpUrlOrNull()?.toString() ?: return null
+ val languageTag = stremioSubtitleLanguageTag(language)
+ val languageName = Locale.forLanguageTag(languageTag)
+ .getDisplayLanguage(Locale.getDefault())
+ .takeIf { it.isNotBlank() && languageTag != "und" }
+ ?: languageTag
+ return StremioPlayerSubtitleOption(
+ key = "$sourceKey:${id ?: index}:$languageTag",
+ url = canonicalUrl,
+ languageTag = languageTag,
+ label = "$languageName · $sourceLabel"
+ )
+}
+
+private val ISO_639_3_TO_639_1: Map<String, String> by lazy {
+ Locale.getISOLanguages().mapNotNull { language ->
+ runCatching {
+ val locale = Locale.Builder()
+ .setLanguage(language)
+ .build()
+ locale.getISO3Language().lowercase(Locale.ROOT) to language.lowercase(Locale.ROOT)
+ }.getOrNull()
+ }.toMap()
+}
+
+private val ISO_639_3_ALIASES = mapOf(
+ "alb" to "sq",
+ "arm" to "hy",
+ "baq" to "eu",
+ "bur" to "my",
+ "chi" to "zh",
+ "cze" to "cs",
+ "dut" to "nl",
+ "fre" to "fr",
+ "geo" to "ka",
+ "ger" to "de",
+ "gre" to "el",
+ "ice" to "is",
+ "mac" to "mk",
+ "may" to "ms",
+ "per" to "fa",
+ "rum" to "ro",
+ "slo" to "sk",
+ "tib" to "bo",
+ "wel" to "cy"
+)
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt
index 409ad0c8..56d7bad9 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/VodOverlayState.kt
@@ -26,6 +26,7 @@ internal fun buildVodOverlayState(
currentPositionMs: Long,
showEpisodesAction: Boolean,
subtitleTrackCount: Int,
+ showStremioSubtitleAction: Boolean = false,
audioTrackCount: Int,
videoQualityCount: Int,
audioVideoSyncEnabled: Boolean = false,
@@ -48,7 +49,7 @@ internal fun buildVodOverlayState(
nextChapterTargetMs = nextChapterTarget(visibleChapters, currentPositionMs),
showChapterAction = isVod && visibleChapters.isNotEmpty() && !isCastConnected,
showEpisodesAction = isVod && normalizedContentType == "SERIES_EPISODE" && showEpisodesAction,
- showSubtitleAction = isVod && subtitleTrackCount > 0,
+ showSubtitleAction = isVod && (subtitleTrackCount > 0 || showStremioSubtitleAction),
showAudioAction = isVod && audioTrackCount > 0,
showVideoQualityAction = isVod && videoQualityCount > 0,
showAudioVideoSyncAction = isVod && audioVideoSyncEnabled && !isCastConnected,
diff --git a/feature/playback/src/main/java/com/streamvault/feature/playback/player/overlay/PlayerSystemOverlays.kt b/feature/playback/src/main/java/com/streamvault/feature/playback/player/overlay/PlayerSystemOverlays.kt
index 08bc4bfa..f44ffd03 100644
--- a/feature/playback/src/main/java/com/streamvault/feature/playback/player/overlay/PlayerSystemOverlays.kt
+++ b/feature/playback/src/main/java/com/streamvault/feature/playback/player/overlay/PlayerSystemOverlays.kt
@@ -86,6 +86,8 @@ import com.streamvault.domain.model.Season
import com.streamvault.player.PlayerError
import com.streamvault.player.PlayerTrack
import com.streamvault.player.TrackType
+import com.streamvault.feature.playback.player.StremioPlayerSubtitleOption
+import com.streamvault.feature.playback.player.StremioSubtitlePickerState
import com.streamvault.player.AUDIO_VIDEO_OFFSET_MAX_MS
import com.streamvault.player.AUDIO_VIDEO_OFFSET_MIN_MS
import java.util.Locale
@@ -258,11 +260,14 @@ fun PlayerTrackSelectionDialog(
videoTracks: List<PlayerTrack>,
liveTranslationAvailable: Boolean = false,
liveTranslationActive: Boolean = false,
+ stremioSubtitlePicker: StremioSubtitlePickerState = StremioSubtitlePickerState(),
onDismiss: () -> Unit,
onSelectAudio: (String) -> Unit,
onSelectVideo: (String) -> Unit,
onSelectSubtitle: (String?) -> Unit,
- onSelectLiveTranslation: () -> Unit = {}
+ onSelectLiveTranslation: () -> Unit = {},
+ onSelectStremioSubtitle: (StremioPlayerSubtitleOption) -> Unit = {},
+ onRetryStremioSubtitles: () -> Unit = {}
) {
if (trackType == null) return
@@ -371,6 +376,59 @@ fun PlayerTrackSelectionDialog(
)
}
}
+
+ if (trackType == TrackType.TEXT && stremioSubtitlePicker.enabled) {
+ item {
+ Text(
+ text = stringResource(R.string.player_stremio_subtitles_heading),
+ style = MaterialTheme.typography.titleSmall,
+ color = Color.White,
+ modifier = Modifier.padding(top = 12.dp, bottom = 4.dp)
+ )
+ }
+ if (stremioSubtitlePicker.loading) {
+ item {
+ Text(
+ text = stringResource(R.string.player_stremio_subtitles_loading),
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White.copy(alpha = 0.72f),
+ modifier = Modifier.padding(vertical = 8.dp)
+ )
+ }
+ }
+ if (stremioSubtitlePicker.failed) {
+ item {
+ TrackSelectionItem(
+ name = stringResource(R.string.player_stremio_subtitles_retry),
+ isSelected = false,
+ onClick = onRetryStremioSubtitles
+ )
+ }
+ }
+ if (!stremioSubtitlePicker.loading &&
+ !stremioSubtitlePicker.failed &&
+ stremioSubtitlePicker.options.isEmpty()
+ ) {
+ item {
+ Text(
+ text = stringResource(R.string.player_stremio_subtitles_empty),
+ style = MaterialTheme.typography.bodyMedium,
+ color = Color.White.copy(alpha = 0.72f),
+ modifier = Modifier.padding(vertical = 8.dp)
+ )
+ }
+ }
+ items(stremioSubtitlePicker.options, key = { it.key }) { option ->
+ TrackSelectionItem(
+ name = option.label,
+ isSelected = false,
+ onClick = {
+ onSelectStremioSubtitle(option)
+ onDismiss()
+ }
+ )
+ }
+ }
}
}
}
diff --git a/feature/playback/src/main/res/values/playback_player_strings.xml b/feature/playback/src/main/res/values/playback_player_strings.xml
index 825a8650..446c848a 100644
--- a/feature/playback/src/main/res/values/playback_player_strings.xml
+++ b/feature/playback/src/main/res/values/playback_player_strings.xml
@@ -213,6 +213,10 @@
<string name="player_track_live_translation" tools:ignore="MissingTranslation">Real-time translation</string>
<string name="player_track_off">Off</string>
<string name="player_track_subs">Select Subtitles</string>
+ <string name="player_stremio_subtitles_heading">Stremio subtitles</string>
+ <string name="player_stremio_subtitles_loading">Loading add-on subtitles…</string>
+ <string name="player_stremio_subtitles_empty">No add-on subtitles available</string>
+ <string name="player_stremio_subtitles_retry">Retry add-on subtitles</string>
<string name="player_try_alternate_stream">Try another path</string>
<string name="player_type_channel_number">Type channel number</string>
<string name="player_type_movie">Movie</string>
diff --git a/feature/playback/src/main/res/values/playback_support_strings.xml b/feature/playback/src/main/res/values/playback_support_strings.xml
index f4e1bcf9..5abadbda 100644
--- a/feature/playback/src/main/res/values/playback_support_strings.xml
+++ b/feature/playback/src/main/res/values/playback_support_strings.xml
@@ -3,6 +3,7 @@
<string name="cast_unavailable" tools:ignore="MissingTranslation">Google Cast is unavailable on this device.</string>
<string name="cast_stream_unsupported" tools:ignore="MissingTranslation">This stream format is not supported by Google Cast.</string>
<string name="cast_protocol_unsupported" tools:ignore="MissingTranslation">RTSP and RTMP streams are not supported for casting.</string>
+ <string name="cast_scoped_headers_unsupported" tools:ignore="MissingTranslation">Addon request headers cannot be sent to a Cast receiver.</string>
<string name="cast_drm_unsupported" tools:ignore="MissingTranslation">DRM-protected streams are not supported by Google Cast in this app.</string>
<string name="cast_item_unavailable" tools:ignore="MissingTranslation">This item cannot be sent to a Cast receiver.</string>
<string name="cast_local_url_unsupported" tools:ignore="MissingTranslation">This stream uses a local or device-only URL that Chromecast cannot reach directly.</string>
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/cast/CastMediaRequestFactoryTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/cast/CastMediaRequestFactoryTest.kt
index 6bae9fde..e5c0a175 100644
--- a/feature/playback/src/test/java/com/streamvault/feature/playback/cast/CastMediaRequestFactoryTest.kt
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/cast/CastMediaRequestFactoryTest.kt
@@ -49,6 +49,22 @@ class CastMediaRequestFactoryTest {
assertThat(request("https://example.test/live", streamType = StreamType.RTSP)).isNull()
}
+ @Test
+ fun `rejects unresolved magnets before building a cast request`() {
+ val result = factory.buildFromStreamInfo(
+ streamInfo = StreamInfo(url = "magnet:?xt=urn:btih:0123456789abcdef"),
+ title = "Torrent",
+ subtitle = null,
+ artworkUrl = null,
+ isLive = false,
+ startPositionMs = 0L
+ )
+
+ assertThat(result).isEqualTo(
+ CastMediaRequestBuildResult.Unsupported(CastMediaRequestUnsupportedReason.UNSUPPORTED_PROTOCOL)
+ )
+ }
+
@Test
fun `reports DRM protected streams as unsupported`() {
val result = factory.buildFromStreamInfo(
@@ -91,6 +107,45 @@ class CastMediaRequestFactoryTest {
assertThat(request?.headers).containsEntry("Cookie", "session=abc")
}
+ @Test
+ fun `blocks addon origin scoped headers from cast requests`() {
+ val result = factory.buildFromStreamInfo(
+ streamInfo = StreamInfo(
+ url = "https://media.example.test/movie.m3u8",
+ headers = mapOf("Authorization" to "Bearer private"),
+ requestHeadersOrigin = "https://media.example.test:443"
+ ),
+ title = "Movie",
+ subtitle = null,
+ artworkUrl = null,
+ isLive = false,
+ startPositionMs = 0L
+ )
+
+ assertThat(result).isEqualTo(
+ CastMediaRequestBuildResult.Unsupported(CastMediaRequestUnsupportedReason.SCOPED_HEADERS_UNSUPPORTED)
+ )
+ }
+
+ @Test
+ fun `allows headerless addon media to use the normal cast path`() {
+ val result = factory.buildFromStreamInfo(
+ streamInfo = StreamInfo(
+ url = "https://media.example.test/movie.m3u8",
+ requestHeadersOrigin = "https://media.example.test:443"
+ ),
+ title = "Movie",
+ subtitle = null,
+ artworkUrl = null,
+ isLive = false,
+ startPositionMs = 0L
+ )
+
+ assertThat(result).isInstanceOf(CastMediaRequestBuildResult.Success::class.java)
+ assertThat((result as CastMediaRequestBuildResult.Success).request.headers).isEmpty()
+ assertThat(result.request.rewriteRequiredReason).isNull()
+ }
+
@Test
fun `marks streams with app-only playback context as requiring cast rewrite`() {
assertThat(
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/cast/CastUiMessagesTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/cast/CastUiMessagesTest.kt
index bed600e3..81c6da4a 100644
--- a/feature/playback/src/test/java/com/streamvault/feature/playback/cast/CastUiMessagesTest.kt
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/cast/CastUiMessagesTest.kt
@@ -18,6 +18,8 @@ class CastUiMessagesTest {
.isEqualTo(R.string.cast_protocol_unsupported)
assertThat(CastMediaRequestUnsupportedReason.DRM_PROTECTED.toCastBuildFailureMessageRes())
.isEqualTo(R.string.cast_drm_unsupported)
+ assertThat(CastMediaRequestUnsupportedReason.SCOPED_HEADERS_UNSUPPORTED.toCastBuildFailureMessageRes())
+ .isEqualTo(R.string.cast_scoped_headers_unsupported)
}
@Test
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerHistoryCoordinatorTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerHistoryCoordinatorTest.kt
index b7b55a5e..2adc338b 100644
--- a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerHistoryCoordinatorTest.kt
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerHistoryCoordinatorTest.kt
@@ -5,6 +5,7 @@ import com.streamvault.domain.model.ContentType
import com.streamvault.domain.model.PlaybackHistory
import com.streamvault.domain.model.Result
import com.streamvault.domain.repository.PlaybackHistoryRepository
+import com.streamvault.domain.repository.StremioPlaybackHistoryRepository
import com.streamvault.domain.usecase.MarkAsWatched
import com.streamvault.feature.playback.api.PlaybackSurfaceRefreshPort
import kotlinx.coroutines.test.runTest
@@ -32,6 +33,7 @@ class PlayerHistoryCoordinatorTest {
whenever(repository.markAsWatched(history)).thenReturn(expected)
val coordinator = PlayerHistoryCoordinator(
repository = repository,
+ stremioRepository = mock<StremioPlaybackHistoryRepository>(),
playbackSurfaceRefreshPort = mock<PlaybackSurfaceRefreshPort>(),
markAsWatched = MarkAsWatched(repository)
)
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPrepareIdentityTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPrepareIdentityTest.kt
index 3bb83b2f..f81fbf9d 100644
--- a/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPrepareIdentityTest.kt
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/PlayerPrepareIdentityTest.kt
@@ -1,6 +1,7 @@
package com.streamvault.feature.playback.player
import com.google.common.truth.Truth.assertThat
+import com.streamvault.core.navigation.StremioPlaybackReference
import org.junit.Test
class PlayerPrepareIdentityTest {
@@ -71,6 +72,35 @@ class PlayerPrepareIdentityTest {
assertThat(changedWindow).isNotEqualTo(baseline)
}
+ @Test
+ fun `buildPlayerPrepareIdentity changes when Stremio content identity changes`() {
+ fun identity(exactVideoId: String) = buildPlayerPrepareIdentity(
+ streamUrl = "https://example.com/stream.mp4",
+ epgChannelId = null,
+ internalChannelId = -1L,
+ categoryId = null,
+ providerId = null,
+ isVirtual = false,
+ combinedProfileId = null,
+ combinedSourceFilterProviderId = null,
+ contentType = "SERIES_EPISODE",
+ archiveStartMs = null,
+ archiveEndMs = null,
+ stremioPlaybackReference = StremioPlaybackReference(
+ mediaType = "series",
+ exactVideoId = exactVideoId,
+ parentSeriesId = "series-id",
+ catalogOriginKey = "catalog-key",
+ streamOriginKey = "stream-key"
+ )
+ )
+
+ val baseline = identity("episode-one")
+ val nextEpisode = identity("episode-two")
+
+ assertThat(nextEpisode).isNotEqualTo(baseline)
+ }
+
@Test
fun `resolveRouteDisplayTitle prefers archive title for live archive playback`() {
assertThat(
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/StremioPlaybackHistorySupportTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/StremioPlaybackHistorySupportTest.kt
new file mode 100644
index 00000000..980bb20c
--- /dev/null
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/StremioPlaybackHistorySupportTest.kt
@@ -0,0 +1,52 @@
+package com.streamvault.feature.playback.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.core.navigation.StremioPlaybackReference
+import org.junit.Test
+
+class StremioPlaybackHistorySupportTest {
+ @Test
+ fun `history snapshot preserves exact episode identity and only progress metadata`() {
+ val history = buildStremioPlaybackHistorySnapshot(
+ reference = StremioPlaybackReference(
+ mediaType = "series",
+ exactVideoId = "tt12345:1:4",
+ parentSeriesId = "tt12345",
+ catalogOriginKey = "a".repeat(64),
+ metaOriginKey = "b".repeat(64),
+ streamOriginKey = "c".repeat(64)
+ ),
+ positionMs = 120_000L,
+ durationMs = 600_000L,
+ title = "Series · Episode 4",
+ posterUrl = "https://images.example.test/episode.jpg",
+ lastWatchedAt = 1_700_000_000_000L
+ )
+
+ assertThat(history?.contentKey).isEqualTo("stremio:global:series-episode:tt12345:1:4")
+ assertThat(history?.exactVideoId).isEqualTo("tt12345:1:4")
+ assertThat(history?.resumePositionMs).isEqualTo(120_000L)
+ assertThat(history?.streamOriginKeyHint).isEqualTo("c".repeat(64))
+ }
+
+ @Test
+ fun `completion snapshot marks watched and clamps progress to duration`() {
+ val history = buildStremioPlaybackHistorySnapshot(
+ reference = StremioPlaybackReference(
+ mediaType = "movie",
+ exactVideoId = "tt12345",
+ catalogOriginKey = "a".repeat(64),
+ streamOriginKey = "c".repeat(64)
+ ),
+ positionMs = 700_000L,
+ durationMs = 600_000L,
+ title = "Movie",
+ posterUrl = null,
+ watched = true,
+ lastWatchedAt = 1L
+ )
+
+ assertThat(history?.watched).isTrue()
+ assertThat(history?.resumePositionMs).isEqualTo(600_000L)
+ }
+}
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/StremioSubtitleSupportTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/StremioSubtitleSupportTest.kt
new file mode 100644
index 00000000..d5cdb1dc
--- /dev/null
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/StremioSubtitleSupportTest.kt
@@ -0,0 +1,62 @@
+package com.streamvault.feature.playback.player
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.core.navigation.StremioSubtitlePlaybackSource
+import com.streamvault.domain.model.stremio.StremioAddonSource
+import com.streamvault.domain.model.stremio.StremioAttributedResource
+import com.streamvault.domain.model.stremio.StremioSubtitle
+import org.junit.Test
+
+class StremioSubtitleSupportTest {
+ @Test
+ fun `three letter language codes map to player language tags`() {
+ assertThat(stremioSubtitleLanguageTag("eng")).isEqualTo("en")
+ assertThat(stremioSubtitleLanguageTag("ger")).isEqualTo("de")
+ assertThat(stremioSubtitleLanguageTag("pt_br")).isEqualTo("pt-BR")
+ assertThat(stremioSubtitleLanguageTag("unknown")).isEqualTo("und")
+ }
+
+ @Test
+ fun `subtitle options include inline and addon resources and deduplicate urls`() {
+ val options = buildStremioPlayerSubtitleOptions(
+ inlineSubtitles = listOf(
+ StremioSubtitlePlaybackSource(
+ url = "https://cdn.example.test/eng.srt?sig=secret",
+ language = "eng",
+ id = "inline"
+ )
+ ),
+ addonSubtitles = listOf(
+ StremioAttributedResource(
+ source = StremioAddonSource(1L, "Subtitles", "subtitles", "addon-key"),
+ resource = StremioSubtitle(
+ url = "https://cdn.example.test/eng.srt?sig=secret",
+ lang = "en",
+ id = "resource"
+ )
+ ),
+ StremioAttributedResource(
+ source = StremioAddonSource(1L, "Subtitles", "subtitles", "addon-key"),
+ resource = StremioSubtitle(
+ url = "file:///private/subtitle.srt",
+ lang = "eng"
+ )
+ ),
+ StremioAttributedResource(
+ source = StremioAddonSource(1L, "Subtitles", "subtitles", "addon-key"),
+ resource = StremioSubtitle(
+ url = "https://cdn.example.test/de.srt",
+ lang = "deu",
+ id = "german"
+ )
+ )
+ )
+ )
+
+ assertThat(options).hasSize(2)
+ assertThat(options[0].languageTag).isEqualTo("en")
+ assertThat(options[0].label).contains("Stream")
+ assertThat(options[1].languageTag).isEqualTo("de")
+ assertThat(options[1].label).contains("Subtitles")
+ }
+}
diff --git a/feature/playback/src/test/java/com/streamvault/feature/playback/player/VodOverlayStateTest.kt b/feature/playback/src/test/java/com/streamvault/feature/playback/player/VodOverlayStateTest.kt
index d30fc392..299181e6 100644
--- a/feature/playback/src/test/java/com/streamvault/feature/playback/player/VodOverlayStateTest.kt
+++ b/feature/playback/src/test/java/com/streamvault/feature/playback/player/VodOverlayStateTest.kt
@@ -58,6 +58,25 @@ class VodOverlayStateTest {
assertThat(state.showChapterAction).isFalse()
}
+ @Test
+ fun `stremio subtitle source exposes picker without built in text tracks`() {
+ val state = buildVodOverlayState(
+ contentType = "MOVIE",
+ isCatchUpPlayback = false,
+ chapters = emptyList(),
+ currentPositionMs = 0L,
+ showEpisodesAction = false,
+ subtitleTrackCount = 0,
+ showStremioSubtitleAction = true,
+ audioTrackCount = 0,
+ videoQualityCount = 0,
+ showExternalPlayerAction = false,
+ isCastConnected = false
+ )
+
+ assertThat(state.showSubtitleAction).isTrue()
+ }
+
@Test
fun `cast hides chapter action while preserving navigation state`() {
val state = buildVodOverlayState(
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsContentPane.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsContentPane.kt
index fb8e079d..6b28b07c 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsContentPane.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsContentPane.kt
@@ -382,6 +382,7 @@ public fun SettingsContentPane(
settingsPrivacySection(
uiState = uiState,
onToggleIncognitoMode = viewModel::toggleIncognitoMode,
+ onHideStremioAddonsChange = viewModel::setHideStremioAddons,
onToggleXtreamTextClassification = viewModel::toggleXtreamTextClassification,
onToggleXtreamBase64TextCompatibility = viewModel::toggleXtreamBase64TextCompatibility,
onPendingProtectionLevelChange = { dialogState.pendingProtectionLevel = it },
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPreferenceModels.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPreferenceModels.kt
index 1a8d05d8..9ff895f3 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPreferenceModels.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPreferenceModels.kt
@@ -101,6 +101,7 @@ data class SettingsPreferenceSnapshot(
val lastSpeedTestTransport: String?,
val lastSpeedTestRecommendedHeight: Int?,
val lastSpeedTestEstimated: Boolean,
+ val hideStremioAddons: Boolean = false,
val isIncognitoMode: Boolean,
val useXtreamTextClassification: Boolean,
val xtreamBase64TextCompatibility: Boolean,
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPreferenceSnapshotMapper.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPreferenceSnapshotMapper.kt
index 4d0cb3b5..fd495512 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPreferenceSnapshotMapper.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPreferenceSnapshotMapper.kt
@@ -63,6 +63,7 @@ fun SettingsUiState.applyPreferenceSnapshot(
isEstimated = snapshot.lastSpeedTestEstimated
)
},
+ hideStremioAddons = snapshot.hideStremioAddons,
isIncognitoMode = snapshot.isIncognitoMode,
useXtreamTextClassification = snapshot.useXtreamTextClassification,
xtreamBase64TextCompatibility = snapshot.xtreamBase64TextCompatibility,
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPrivacySection.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPrivacySection.kt
index 39b14468..b449060f 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPrivacySection.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsPrivacySection.kt
@@ -13,6 +13,7 @@ import com.streamvault.feature.settings.R
public fun LazyListScope.settingsPrivacySection(
uiState: SettingsUiState,
onToggleIncognitoMode: () -> Unit,
+ onHideStremioAddonsChange: (Boolean) -> Unit,
onToggleXtreamTextClassification: () -> Unit,
onToggleXtreamBase64TextCompatibility: () -> Unit,
onPendingProtectionLevelChange: (Int?) -> Unit,
@@ -25,6 +26,15 @@ public fun LazyListScope.settingsPrivacySection(
targetItemId: String? = null,
targetFocusModifier: Modifier = Modifier,
) {
+ item {
+ SwitchSettingsRow(
+ label = stringResource(R.string.settings_hide_stremio_addons),
+ value = stringResource(R.string.settings_hide_stremio_addons_subtitle),
+ checked = uiState.hideStremioAddons,
+ onCheckedChange = onHideStremioAddonsChange,
+ modifier = if (targetItemId == "privacy.hide_stremio_addons") targetFocusModifier else firstFocusModifier,
+ )
+ }
item {
ParentalControlCard(
level = uiState.parentalControlLevel,
@@ -53,7 +63,7 @@ public fun LazyListScope.settingsPrivacySection(
firstActionModifier = if (targetItemId == "privacy.protection_level") {
targetFocusModifier
} else {
- firstFocusModifier
+ Modifier
},
secondActionModifier = if (targetItemId == "privacy.pin") targetFocusModifier else Modifier,
)
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt
index 58cd8995..0baf56ba 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsSearchSurface.kt
@@ -298,6 +298,7 @@ private fun resolvedSettingsCatalog(
remoteSetting(RemoteShortcutProfile.BROWSE, R.string.settings_remote_profile_browse, RemoteColorButton.GREEN, R.string.settings_remote_button_green),
remoteSetting(RemoteShortcutProfile.BROWSE, R.string.settings_remote_profile_browse, RemoteColorButton.YELLOW, R.string.settings_remote_button_yellow),
remoteSetting(RemoteShortcutProfile.BROWSE, R.string.settings_remote_profile_browse, RemoteColorButton.BLUE, R.string.settings_remote_button_blue),
+ setting("privacy.hide_stremio_addons", SettingsCategory.PRIVACY, null, R.string.settings_hide_stremio_addons, "extensions", "addons", "visibility"),
setting("privacy.incognito", SettingsCategory.PRIVACY, null, R.string.settings_incognito_mode, "private viewing", "history"),
setting("privacy.clear_history", SettingsCategory.PRIVACY, null, R.string.settings_clear_history, "watch progress", "recents"),
setting("privacy.protection_level", SettingsCategory.PRIVACY, null, R.string.settings_protection_level, "parental controls", "lock"),
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsStateBindings.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsStateBindings.kt
index 57ac462a..69175e28 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsStateBindings.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsStateBindings.kt
@@ -231,6 +231,8 @@ fun observeSettingsPreferenceSnapshot(
snapshot.copy(lastSpeedTestRecommendedHeight = lastSpeedTestRecommendedHeight)
}.combine(preferencesRepository.lastSpeedTestEstimated) { snapshot, lastSpeedTestEstimated ->
snapshot.copy(lastSpeedTestEstimated = lastSpeedTestEstimated)
+ }.combine(preferencesRepository.hideStremioAddons) { snapshot, hidden ->
+ snapshot.copy(hideStremioAddons = hidden)
}.combine(preferencesRepository.isIncognitoMode) { snapshot, incognito ->
snapshot.copy(isIncognitoMode = incognito)
}.combine(preferencesRepository.useXtreamTextClassification) { snapshot, useTextClass ->
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsUiStateModel.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsUiStateModel.kt
index 1651f19e..3513b46f 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsUiStateModel.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsUiStateModel.kt
@@ -153,6 +153,7 @@ data class SettingsUiState(
val wifiOnlyRecording: Boolean = false,
val recordingPaddingBeforeMinutes: Int = 0,
val recordingPaddingAfterMinutes: Int = 0,
+ val hideStremioAddons: Boolean = false,
val isIncognitoMode: Boolean = false,
val useXtreamTextClassification: Boolean = true,
val xtreamBase64TextCompatibility: Boolean = false,
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
index 844919b1..705f45d0 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/SettingsViewModel.kt
@@ -1065,6 +1065,10 @@ class SettingsViewModel @Inject constructor(
}
}
+ fun setHideStremioAddons(hidden: Boolean) {
+ viewModelScope.launch { preferencesRepository.setHideStremioAddons(hidden) }
+ }
+
fun toggleIncognitoMode() {
viewModelScope.launch {
val current = _uiState.value.isIncognitoMode
diff --git a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/TopNavigationDialog.kt b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/TopNavigationDialog.kt
index e86d8777..4317cafa 100644
--- a/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/TopNavigationDialog.kt
+++ b/feature/settings/src/main/java/com/streamvault/feature/settings/presentation/TopNavigationDialog.kt
@@ -243,7 +243,6 @@ private fun AppTopLevelDestination.labelResId(): Int = when (this) {
AppTopLevelDestination.DOWNLOADS -> R.string.nav_downloads
AppTopLevelDestination.GUIDE -> R.string.nav_epg
AppTopLevelDestination.SEARCH -> R.string.search_title
- AppTopLevelDestination.PLUGINS -> R.string.nav_plugins
- AppTopLevelDestination.ADDONS -> R.string.nav_addons
+ AppTopLevelDestination.EXTENSIONS -> R.string.nav_extensions
AppTopLevelDestination.SETTINGS -> R.string.nav_settings
}
diff --git a/feature/settings/src/main/res/values/strings.xml b/feature/settings/src/main/res/values/strings.xml
index 996da1df..2fc2a8d8 100644
--- a/feature/settings/src/main/res/values/strings.xml
+++ b/feature/settings/src/main/res/values/strings.xml
@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
+ <string name="settings_hide_stremio_addons">Hide Stremio-compatible add-ons</string>
+ <string name="settings_hide_stremio_addons_subtitle">Hide add-on browsing, installation, and history. Installed add-ons are kept.</string>
<string name="dashboard_favorite_channels">Favorite Channels</string>
<string name="dashboard_recent_channels">Recent Channels</string>
<string name="dashboard_live_shortcuts">Live Shortcuts</string>
@@ -545,7 +547,8 @@
<string name="nav_epg">Guide</string>
<string name="nav_downloads">Downloads</string>
<string name="nav_plugins">Plugins</string>
- <string name="nav_addons">Addons</string>
+ <string name="nav_addons">Stremio-compatible Add-ons</string>
+ <string name="nav_extensions">Extensions</string>
<string name="nav_settings">Settings</string>
<string name="settings_overview_title">Control Center</string>
<string name="settings_overview_subtitle">Review your provider, protection, and playback setup at a glance.</string>
diff --git a/feature/stremio/build.gradle.kts b/feature/stremio/build.gradle.kts
index 93d17eb6..98941d8b 100644
--- a/feature/stremio/build.gradle.kts
+++ b/feature/stremio/build.gradle.kts
@@ -51,6 +51,8 @@ dependencies {
implementation(libs.compose.material.icons.extended)
implementation(libs.compose.tv.foundation)
implementation(libs.compose.tv.material)
+ implementation(libs.coil.compose)
+ implementation(libs.coil.network.okhttp)
implementation(libs.activity.compose)
implementation(libs.lifecycle.runtime.ktx)
implementation(libs.lifecycle.runtime.compose)
@@ -66,6 +68,7 @@ dependencies {
testImplementation(libs.junit)
testImplementation(libs.truth)
testImplementation(libs.coroutines.test)
+ testImplementation(libs.mockito.kotlin)
androidTestImplementation(libs.androidx.test.ext.junit)
androidTestImplementation(libs.androidx.test.runner)
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/navigation/StremioGraph.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/navigation/StremioGraph.kt
index bfdadb89..7339a600 100644
--- a/feature/stremio/src/main/java/com/streamvault/feature/stremio/navigation/StremioGraph.kt
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/navigation/StremioGraph.kt
@@ -1,12 +1,86 @@
package com.streamvault.feature.stremio.navigation
+import androidx.navigation.NavHostController
import androidx.navigation.NavGraphBuilder
+import androidx.navigation.NavType
import androidx.navigation.compose.composable
+import androidx.navigation.navArgument
+import androidx.compose.ui.res.stringResource
+import com.streamvault.core.navigation.AppDestination
+import com.streamvault.core.navigation.NavigationActions
+import com.streamvault.core.navigation.PlayerNavigationRequest
import com.streamvault.feature.stremio.api.StremioScaffoldContent
import com.streamvault.feature.stremio.presentation.AddonsScreen
+import com.streamvault.feature.stremio.presentation.StremioItemDetailScreen
+import com.streamvault.feature.stremio.presentation.StremioVisibilityHost
+import com.streamvault.feature.stremio.R
-fun NavGraphBuilder.registerStremioGraph(scaffold: StremioScaffoldContent) {
+fun NavGraphBuilder.registerStremioGraph(
+ navController: NavHostController,
+ actions: NavigationActions,
+ onTopLevelDestinationRequested: (AppDestination) -> Unit,
+ scaffold: StremioScaffoldContent
+) {
composable(StremioRoutePatterns.ADDONS) {
- AddonsScreen(scaffold = scaffold)
+ StremioVisibilityHost(
+ scaffold = scaffold,
+ onOpenSettings = { actions.navigate(AppDestination.Settings()) },
+ title = stringResource(R.string.extensions_title),
+ showExtensionsTabs = true,
+ onNavigateToPlugins = { onTopLevelDestinationRequested(AppDestination.Plugins) },
+ content = { accessState ->
+ AddonsScreen(
+ scaffold = scaffold,
+ showContinueWatching = accessState.showContinueWatching,
+ onNavigateToPlugins = { onTopLevelDestinationRequested(AppDestination.Plugins) },
+ onOpenItem = { addonId, preview ->
+ navController.navigate(StremioRoutePatterns.itemRoute(addonId, preview))
+ },
+ onOpenHistory = { history, originAddonId ->
+ navController.navigate(StremioRoutePatterns.historyRoute(originAddonId, history))
+ }
+ )
+ }
+ )
+ }
+ composable(
+ route = StremioRoutePatterns.ITEM,
+ arguments = listOf(
+ navArgument("originAddonId") { type = NavType.LongType },
+ navArgument("type") { type = NavType.StringType },
+ navArgument("exactId") { type = NavType.StringType },
+ navArgument("name") { type = NavType.StringType },
+ navArgument("poster") { type = NavType.StringType; defaultValue = "" },
+ navArgument("description") { type = NavType.StringType; defaultValue = "" },
+ navArgument("releaseInfo") { type = NavType.StringType; defaultValue = "" },
+ navArgument("replayVideoId") { type = NavType.StringType; defaultValue = "" },
+ navArgument("replayOriginKey") { type = NavType.StringType; defaultValue = "" },
+ navArgument("replayRequiresOrigin") { type = NavType.BoolType; defaultValue = false }
+ )
+ ) {
+ StremioVisibilityHost(
+ scaffold = scaffold,
+ onOpenSettings = { actions.navigate(AppDestination.Settings()) },
+ title = stringResource(R.string.stremio_title),
+ content = {
+ StremioItemDetailScreen(
+ scaffold = scaffold,
+ onPlay = { handoff ->
+ actions.openPlayer(
+ PlayerNavigationRequest(
+ streamUrl = handoff.streamUrl,
+ title = handoff.title,
+ contentType = handoff.contentType,
+ artworkUrl = handoff.artworkUrl,
+ returnDestination = AppDestination.Addons,
+ stremioPlaybackReference = handoff.reference,
+ stremioMediaRequestHeaders = handoff.mediaRequestHeaders,
+ stremioInlineSubtitles = handoff.inlineSubtitles
+ )
+ )
+ }
+ )
+ }
+ )
}
}
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/navigation/StremioRoutePatterns.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/navigation/StremioRoutePatterns.kt
index 10e34169..448b4ed5 100644
--- a/feature/stremio/src/main/java/com/streamvault/feature/stremio/navigation/StremioRoutePatterns.kt
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/navigation/StremioRoutePatterns.kt
@@ -1,5 +1,46 @@
package com.streamvault.feature.stremio.navigation
+import android.net.Uri
+import com.streamvault.domain.model.stremio.StremioMetaPreview
+
object StremioRoutePatterns {
const val ADDONS = "addons"
+ const val ITEM = "addons/item/{originAddonId}/{type}/{exactId}?name={name}&poster={poster}&description={description}&releaseInfo={releaseInfo}&replayVideoId={replayVideoId}&replayOriginKey={replayOriginKey}&replayRequiresOrigin={replayRequiresOrigin}"
+
+ fun itemRoute(
+ originAddonId: Long,
+ preview: StremioMetaPreview,
+ replayVideoId: String? = null,
+ replayOriginKey: String? = null,
+ replayRequiresOrigin: Boolean = false
+ ): String =
+ "addons/item/$originAddonId/${preview.type.typeName}/${Uri.encode(preview.id)}" +
+ "?name=${Uri.encode(preview.name)}" +
+ "&poster=${Uri.encode(preview.poster.orEmpty())}" +
+ "&description=${Uri.encode(preview.description.orEmpty())}" +
+ "&releaseInfo=${Uri.encode(preview.releaseInfo.orEmpty())}" +
+ "&replayVideoId=${Uri.encode(replayVideoId.orEmpty())}" +
+ "&replayOriginKey=${Uri.encode(replayOriginKey.orEmpty())}" +
+ "&replayRequiresOrigin=$replayRequiresOrigin"
+
+ fun historyRoute(originAddonId: Long, history: com.streamvault.domain.model.stremio.StremioPlaybackHistory): String {
+ val type = com.streamvault.domain.model.stremio.StremioMediaType.fromTypeName(history.mediaType)
+ val itemId = if (type == com.streamvault.domain.model.stremio.StremioMediaType.SERIES) {
+ history.parentSeriesId ?: history.exactVideoId
+ } else history.exactVideoId
+ val preview = StremioMetaPreview(
+ id = itemId,
+ type = type,
+ name = history.title,
+ poster = history.posterUrl
+ )
+ val requireOrigin = !history.contentKey.startsWith("stremio:global:")
+ return itemRoute(
+ originAddonId = originAddonId,
+ preview = preview,
+ replayVideoId = history.exactVideoId,
+ replayOriginKey = history.catalogOriginKey,
+ replayRequiresOrigin = requireOrigin
+ )
+ }
}
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/AddonsScreen.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/AddonsScreen.kt
index 964a7dea..f453a158 100644
--- a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/AddonsScreen.kt
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/AddonsScreen.kt
@@ -11,17 +11,19 @@ import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.itemsIndexed
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.KeyboardArrowDown
import androidx.compose.material.icons.filled.KeyboardArrowUp
import androidx.compose.material3.AlertDialog
-import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
+import androidx.compose.material3.LinearProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
@@ -30,6 +32,9 @@ import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableIntStateOf
+import androidx.compose.runtime.saveable.rememberSaveable
+import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
@@ -38,6 +43,15 @@ import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.streamvault.core.navigation.AppDestination
+import com.streamvault.core.ui.components.shell.ExtensionsEmptyState
+import com.streamvault.core.ui.design.AppColors
+import com.streamvault.core.ui.interaction.TvButton
+import com.streamvault.core.ui.interaction.TvPrimaryButton
+import androidx.tv.material3.ButtonDefaults
+import com.streamvault.core.ui.components.shell.ExtensionsSectionTabs
+import com.streamvault.domain.model.stremio.StremioMetaPreview
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
+import com.streamvault.domain.model.stremio.installFingerprint
import com.streamvault.feature.stremio.R
import com.streamvault.feature.stremio.api.StremioScaffoldContent
import kotlinx.coroutines.delay
@@ -45,9 +59,14 @@ import kotlinx.coroutines.delay
@Composable
fun AddonsScreen(
scaffold: StremioScaffoldContent,
+ showContinueWatching: Boolean = true,
+ onNavigateToPlugins: () -> Unit = {},
+ onOpenItem: (Long, StremioMetaPreview) -> Unit = { _, _ -> },
+ onOpenHistory: (StremioPlaybackHistory, Long) -> Unit = { _, _ -> },
viewModel: AddonsViewModel = hiltViewModel()
) {
val state by viewModel.state.collectAsStateWithLifecycle()
+ var selectedTab by rememberSaveable { mutableIntStateOf(0) }
state.statusMessageRes?.let { messageRes ->
LaunchedEffect(messageRes) {
@@ -58,21 +77,34 @@ fun AddonsScreen(
scaffold(
AppDestination.Addons,
- stringResource(R.string.stremio_title),
- stringResource(R.string.stremio_subtitle),
+ stringResource(R.string.extensions_title),
+ null,
false,
true
) {
Column(
modifier = Modifier
- .fillMaxSize()
- .padding(horizontal = 24.dp, vertical = 8.dp),
+ .fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
- Button(onClick = viewModel::showInstallDialog) {
- Icon(imageVector = Icons.Default.Add, contentDescription = null)
- Spacer(modifier = Modifier.size(8.dp))
- Text(text = stringResource(R.string.stremio_add))
+ ExtensionsSectionTabs(
+ selectedIndex = 1,
+ pluginsLabel = stringResource(R.string.extensions_tab_plugins),
+ stremioAddonsLabel = stringResource(R.string.extensions_tab_stremio_addons),
+ onTabSelected = { selectedIndex ->
+ if (selectedIndex == 0) onNavigateToPlugins()
+ }
+ )
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp)) {
+ Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(stringResource(R.string.stremio_title), style = androidx.tv.material3.MaterialTheme.typography.titleLarge, color = AppColors.TextPrimary)
+ Text(stringResource(R.string.stremio_section_description), style = MaterialTheme.typography.bodyMedium, color = AppColors.TextSecondary)
+ }
+ TvPrimaryButton(onClick = viewModel::showInstallDialog) {
+ Icon(imageVector = Icons.Default.Add, contentDescription = null, tint = AppColors.OnPrimary)
+ Spacer(Modifier.size(8.dp))
+ Text(stringResource(R.string.stremio_add), color = AppColors.OnPrimary)
+ }
}
state.errorMessage?.let { message ->
MessageBanner(message = message, onClick = viewModel::consumeError)
@@ -80,40 +112,88 @@ fun AddonsScreen(
state.statusMessageRes?.let { messageRes ->
MessageBanner(message = stringResource(messageRes), onClick = viewModel::consumeStatusMessage)
}
- when {
- state.loading -> Box(
- modifier = Modifier.fillMaxSize(),
- contentAlignment = Alignment.Center
- ) {
- CircularProgressIndicator()
- }
- state.addons.isEmpty() -> Text(
- text = stringResource(R.string.stremio_empty),
- style = MaterialTheme.typography.bodyLarge,
- color = MaterialTheme.colorScheme.onSurfaceVariant
+ if (!state.loading && state.addons.isEmpty()) {
+ ExtensionsEmptyState(
+ title = stringResource(R.string.stremio_empty_title),
+ description = stringResource(R.string.stremio_empty_description),
+ modifier = Modifier.weight(1f)
)
- else -> LazyColumn(
- modifier = Modifier.fillMaxSize(),
- verticalArrangement = Arrangement.spacedBy(12.dp)
- ) {
- itemsIndexed(
- items = state.addons,
- key = { _, entry -> entry.addon.id }
- ) { index, entry ->
- AddonCard(
- entry = entry,
- expanded = state.expandedAddonId == entry.addon.id,
- canMoveUp = index > 0,
- canMoveDown = index < state.addons.lastIndex,
- onEnabledChange = { enabled -> viewModel.setEnabled(entry, enabled) },
- onMoveUp = { viewModel.moveAddon(entry, -1) },
- onMoveDown = { viewModel.moveAddon(entry, 1) },
- onToggleExpanded = { viewModel.toggleExpanded(entry.addon.id) },
- onCatalogEnabledChange = { catalogKey, enabled ->
- viewModel.setCatalogEnabled(entry, catalogKey, enabled)
- },
- onRemove = { viewModel.removeAddon(entry) }
+ } else {
+ Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ listOf(R.string.stremio_tab_browse, R.string.stremio_tab_manage).forEachIndexed { index, label ->
+ TvButton(
+ onClick = { selectedTab = index },
+ scale = ButtonDefaults.scale(focusedScale = 1f, pressedScale = 1f),
+ colors = ButtonDefaults.colors(
+ containerColor = if (selectedTab == index) AppColors.BrandMuted else AppColors.Surface,
+ contentColor = AppColors.TextPrimary,
+ focusedContainerColor = AppColors.SurfaceEmphasis,
+ focusedContentColor = AppColors.TextPrimary
+ )
+ ) { Text(stringResource(label), color = AppColors.TextPrimary) }
+ }
+ }
+ if (selectedTab == 0) {
+ if (showContinueWatching && state.continueWatching.isNotEmpty()) {
+ Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
+ Text(
+ text = stringResource(R.string.stremio_continue_watching),
+ style = MaterialTheme.typography.titleMedium
+ )
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ items(state.continueWatching, key = { it.contentKey }) { item ->
+ val originAddonId = state.addons.firstOrNull {
+ it.addon.installFingerprint() == item.catalogOriginKey
+ }?.addon?.id ?: 0L
+ ContinueWatchingCard(
+ item = item,
+ onClick = { onOpenHistory(item, originAddonId) }
+ )
+ }
+ }
+ }
+ }
+ StremioCatalogBrowseContent(
+ modifier = Modifier.weight(1f),
+ onOpenItem = onOpenItem
+ )
+ } else {
+ when {
+ state.loading -> Box(
+ modifier = Modifier.weight(1f).fillMaxWidth(),
+ contentAlignment = Alignment.Center
+ ) {
+ CircularProgressIndicator()
+ }
+ state.addons.isEmpty() -> Text(
+ text = stringResource(R.string.stremio_empty),
+ style = MaterialTheme.typography.bodyLarge,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
)
+ else -> LazyColumn(
+ modifier = Modifier.weight(1f).fillMaxWidth(),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ itemsIndexed(
+ items = state.addons,
+ key = { _, entry -> entry.addon.id }
+ ) { index, entry ->
+ AddonCard(
+ entry = entry,
+ expanded = state.expandedAddonId == entry.addon.id,
+ canMoveUp = index > 0,
+ canMoveDown = index < state.addons.lastIndex,
+ onEnabledChange = { enabled -> viewModel.setEnabled(entry, enabled) },
+ onMoveUp = { viewModel.moveAddon(entry, -1) },
+ onMoveDown = { viewModel.moveAddon(entry, 1) },
+ onToggleExpanded = { viewModel.toggleExpanded(entry.addon.id) },
+ onCatalogEnabledChange = { catalogKey, enabled ->
+ viewModel.setCatalogEnabled(entry, catalogKey, enabled)
+ },
+ onRemove = { viewModel.removeAddon(entry) }
+ )
+ }
+ }
}
}
}
@@ -132,6 +212,29 @@ fun AddonsScreen(
}
}
+@Composable
+private fun ContinueWatchingCard(item: StremioPlaybackHistory, onClick: () -> Unit) {
+ val progress = if (item.totalDurationMs > 0L) {
+ (item.resumePositionMs.toFloat() / item.totalDurationMs).coerceIn(0f, 1f)
+ } else 0f
+ Card(
+ modifier = Modifier.size(width = 220.dp, height = 92.dp).clickable(onClick = onClick)
+ ) {
+ Column(
+ modifier = Modifier.fillMaxSize().padding(12.dp),
+ verticalArrangement = Arrangement.SpaceBetween
+ ) {
+ Text(
+ text = item.title,
+ style = MaterialTheme.typography.titleSmall,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ LinearProgressIndicator(progress = { progress }, modifier = Modifier.fillMaxWidth())
+ }
+ }
+}
+
@Composable
private fun AddonCard(
entry: AddonsViewModel.AddonEntry,
@@ -162,7 +265,11 @@ private fun AddonCard(
color = MaterialTheme.colorScheme.onSurfaceVariant
)
Text(
- text = addon.installUrl,
+ text = stringResource(
+ R.string.stremio_addon_server_format,
+ stremioAddonOriginLabel(addon.installUrl)
+ ?: stringResource(R.string.stremio_addon_server_unknown)
+ ),
style = MaterialTheme.typography.bodySmall,
color = MaterialTheme.colorScheme.onSurfaceVariant,
maxLines = 1,
@@ -251,11 +358,16 @@ private fun InstallAddonDialog(
title = { Text(text = stringResource(R.string.stremio_install_title)) },
text = {
Column(verticalArrangement = Arrangement.spacedBy(12.dp)) {
+ Text(
+ text = stringResource(R.string.stremio_install_description),
+ style = MaterialTheme.typography.bodyMedium
+ )
OutlinedTextField(
value = url,
onValueChange = onUrlChange,
singleLine = true,
enabled = !installing,
+ label = { Text(stringResource(R.string.stremio_install_url_label)) },
placeholder = { Text(text = stringResource(R.string.stremio_install_hint)) },
modifier = Modifier.fillMaxWidth()
)
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/AddonsViewModel.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/AddonsViewModel.kt
index a33c9713..18a94280 100644
--- a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/AddonsViewModel.kt
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/AddonsViewModel.kt
@@ -5,8 +5,10 @@ import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
import com.streamvault.domain.model.stremio.StremioCatalogRef
import com.streamvault.domain.repository.StremioAddonRepository
+import com.streamvault.domain.repository.StremioPlaybackHistoryRepository
import com.streamvault.feature.stremio.R
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
@@ -18,7 +20,9 @@ import kotlinx.coroutines.launch
@HiltViewModel
class AddonsViewModel @Inject constructor(
- private val repository: StremioAddonRepository
+ private val repository: StremioAddonRepository,
+ private val historyRepository: StremioPlaybackHistoryRepository,
+ private val contentAccess: StremioContentAccess
) : ViewModel() {
data class AddonEntry(
@@ -29,11 +33,12 @@ class AddonsViewModel @Inject constructor(
data class UiState(
val loading: Boolean = true,
val addons: List<AddonEntry> = emptyList(),
+ val continueWatching: List<StremioPlaybackHistory> = emptyList(),
val installDialogVisible: Boolean = false,
val installUrl: String = "",
val installing: Boolean = false,
val expandedAddonId: Long? = null,
- @StringRes val statusMessageRes: Int? = null,
+ @param:StringRes val statusMessageRes: Int? = null,
val errorMessage: String? = null
)
@@ -52,9 +57,15 @@ class AddonsViewModel @Inject constructor(
_state.update { it.copy(loading = false, addons = entries) }
}
}
+ viewModelScope.launch {
+ historyRepository.observeContinueWatching().collect { history ->
+ _state.update { it.copy(continueWatching = history) }
+ }
+ }
}
fun showInstallDialog() {
+ if (!contentAccess.canAccessContentNow()) return
_state.update { it.copy(installDialogVisible = true, errorMessage = null) }
}
@@ -67,10 +78,15 @@ class AddonsViewModel @Inject constructor(
}
fun install() {
+ if (!contentAccess.canAccessContentNow()) return
val url = _state.value.installUrl.trim()
if (url.isEmpty() || _state.value.installing) return
_state.update { it.copy(installing = true, errorMessage = null) }
viewModelScope.launch {
+ if (!contentAccess.canAccessContentNow()) {
+ _state.update { it.copy(installing = false) }
+ return@launch
+ }
when (val result = repository.installAddon(url)) {
is Result.Success -> _state.update {
it.copy(
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioAddonOriginLabel.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioAddonOriginLabel.kt
new file mode 100644
index 00000000..20010ad6
--- /dev/null
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioAddonOriginLabel.kt
@@ -0,0 +1,19 @@
+package com.streamvault.feature.stremio.presentation
+
+import java.net.URI
+
+/** Returns only the server origin so configured manifest path/query tokens are never shown. */
+internal fun stremioAddonOriginLabel(installUrl: String): String? = runCatching {
+ val uri = URI(installUrl)
+ val scheme = uri.scheme?.lowercase() ?: return@runCatching null
+ val host = uri.host ?: return@runCatching null
+ val bareHost = host.removePrefix("[").removeSuffix("]")
+ val safeHost = if (bareHost.contains(':')) "[$bareHost]" else bareHost
+ val defaultPort = when (scheme) {
+ "http" -> 80
+ "https" -> 443
+ else -> -1
+ }
+ val port = uri.port.takeIf { it >= 0 && it != defaultPort }
+ "$scheme://$safeHost${port?.let { ":$it" }.orEmpty()}"
+}.getOrNull()
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseContent.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseContent.kt
new file mode 100644
index 00000000..c853f726
--- /dev/null
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseContent.kt
@@ -0,0 +1,238 @@
+package com.streamvault.feature.stremio.presentation
+
+import androidx.compose.foundation.focusable
+import androidx.compose.foundation.clickable
+import androidx.compose.foundation.BorderStroke
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.LazyRow
+import androidx.compose.foundation.lazy.items
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.CardDefaults
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.FilterChip
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.OutlinedTextField
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.focus.onFocusChanged
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.hilt.navigation.compose.hiltViewModel
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import coil3.compose.AsyncImage
+import com.streamvault.feature.stremio.R
+import com.streamvault.domain.model.stremio.StremioMetaPreview
+
+@Composable
+internal fun StremioCatalogBrowseContent(
+ modifier: Modifier = Modifier,
+ viewModel: StremioCatalogBrowseViewModel = hiltViewModel(),
+ onOpenItem: (Long, StremioMetaPreview) -> Unit = { _, _ -> }
+) {
+ val state = viewModel.state.collectAsStateWithLifecycle().value
+ when {
+ state.loading -> Box(modifier.fillMaxSize(), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator()
+ }
+ state.rows.isEmpty() -> Box(
+ modifier = modifier.fillMaxSize().padding(24.dp),
+ contentAlignment = Alignment.Center
+ ) {
+ Text(
+ text = stringResource(R.string.stremio_browse_empty),
+ style = MaterialTheme.typography.bodyLarge,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ else -> LazyColumn(
+ modifier = modifier.fillMaxSize(),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ items(items = state.rows, key = { "${it.key.addonId}:${it.key.catalogKey}" }) { row ->
+ CatalogRow(row, viewModel, onOpenItem)
+ }
+ }
+ }
+}
+
+@Composable
+private fun CatalogRow(
+ row: StremioCatalogRowState,
+ viewModel: StremioCatalogBrowseViewModel,
+ onOpenItem: (Long, StremioMetaPreview) -> Unit
+) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Column {
+ Text(
+ text = row.catalog.name?.takeIf { it.isNotBlank() } ?: row.catalog.id,
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onSurface
+ )
+ Text(
+ text = "${row.addonName} · ${row.catalog.type.typeName}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+
+ if (row.supportsSearch) {
+ OutlinedTextField(
+ value = row.search,
+ onValueChange = { viewModel.setSearch(row.key, it) },
+ modifier = Modifier.fillMaxWidth(),
+ label = { Text(stringResource(R.string.stremio_search_catalog)) },
+ singleLine = true,
+ enabled = row.blockedReason == null
+ )
+ }
+
+ if (row.supportsGenre) {
+ if (row.genreOptions.isNotEmpty()) {
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ if (!row.genreRequired) {
+ item(key = "all") {
+ FilterChip(
+ selected = row.genre.isBlank(),
+ onClick = { viewModel.setGenre(row.key, "") },
+ label = { Text(stringResource(R.string.stremio_all_genres)) }
+ )
+ }
+ }
+ items(row.genreOptions, key = { it }) { genre ->
+ FilterChip(
+ selected = row.genre == genre,
+ onClick = { viewModel.setGenre(row.key, genre) },
+ label = { Text(genre) }
+ )
+ }
+ }
+ } else {
+ OutlinedTextField(
+ value = row.genre,
+ onValueChange = { viewModel.setGenre(row.key, it) },
+ modifier = Modifier.fillMaxWidth(),
+ label = { Text(stringResource(R.string.stremio_filter_genre)) },
+ singleLine = true,
+ enabled = row.blockedReason == null
+ )
+ }
+ }
+
+ row.blockedReason?.let { reason ->
+ Text(reason, color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.bodyMedium)
+ }
+ row.waitingForInput?.let {
+ val waiting = when {
+ row.searchRequired && row.search.isBlank() -> stringResource(R.string.stremio_catalog_waiting_search)
+ row.genreRequired && row.genre.isBlank() -> stringResource(R.string.stremio_catalog_waiting_genre)
+ else -> it
+ }
+ Text(waiting, color = MaterialTheme.colorScheme.onSurfaceVariant, style = MaterialTheme.typography.bodyMedium)
+ }
+ row.error?.let { error ->
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(error, modifier = Modifier.weight(1f), color = MaterialTheme.colorScheme.error)
+ TextButton(onClick = { viewModel.retry(row.key) }) {
+ Text(stringResource(R.string.stremio_retry))
+ }
+ }
+ }
+
+ if (row.loading && row.metas.isEmpty()) {
+ Box(Modifier.fillMaxWidth().height(180.dp), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator()
+ }
+ } else if (row.metas.isEmpty() && row.blockedReason == null &&
+ row.waitingForInput == null && row.error == null
+ ) {
+ Text(
+ text = stringResource(R.string.stremio_empty_catalog),
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ } else if (row.metas.isNotEmpty()) {
+ LazyRow(horizontalArrangement = Arrangement.spacedBy(12.dp)) {
+ items(
+ items = row.metas,
+ key = { "${it.type.typeName}:${it.id}" }
+ ) { meta ->
+ CatalogMetaCard(meta) { onOpenItem(row.key.addonId, meta) }
+ }
+ }
+ }
+
+ if (row.canLoadMore || row.loadingMore) {
+ Button(
+ onClick = { viewModel.loadMore(row.key) },
+ enabled = !row.loadingMore && !row.loading
+ ) {
+ if (row.loadingMore) {
+ CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
+ Spacer(Modifier.width(8.dp))
+ }
+ Text(stringResource(R.string.stremio_load_more))
+ }
+ }
+ }
+}
+
+@Composable
+private fun CatalogMetaCard(meta: StremioMetaPreview, onClick: () -> Unit) {
+ var isFocused by remember(meta.type, meta.id) { mutableStateOf(false) }
+ val colors = MaterialTheme.colorScheme
+ val description = stringResource(
+ R.string.stremio_catalog_item_a11y,
+ meta.name,
+ meta.releaseInfo.orEmpty()
+ )
+ Card(
+ modifier = Modifier
+ .width(144.dp)
+ .onFocusChanged { isFocused = it.isFocused }
+ .clickable(onClick = onClick)
+ .focusable()
+ .semantics { contentDescription = description },
+ colors = CardDefaults.cardColors(
+ containerColor = if (isFocused) colors.surfaceVariant else colors.surface
+ ),
+ border = if (isFocused) BorderStroke(2.dp, colors.primary) else null
+ ) {
+ Column {
+ AsyncImage(
+ model = meta.poster,
+ contentDescription = null,
+ modifier = Modifier.fillMaxWidth().height(204.dp),
+ contentScale = ContentScale.Crop
+ )
+ Text(
+ text = meta.name,
+ modifier = Modifier.padding(horizontal = 8.dp, vertical = 6.dp),
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis,
+ style = MaterialTheme.typography.bodyMedium
+ )
+ }
+ }
+}
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseViewModel.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseViewModel.kt
new file mode 100644
index 00000000..08b07697
--- /dev/null
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseViewModel.kt
@@ -0,0 +1,369 @@
+package com.streamvault.feature.stremio.presentation
+
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioCatalogPage
+import com.streamvault.domain.model.stremio.StremioCatalogQuery
+import com.streamvault.domain.model.stremio.StremioCatalogRef
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaPreview
+import com.streamvault.domain.repository.StremioAddonRepository
+import dagger.hilt.android.lifecycle.HiltViewModel
+import java.security.MessageDigest
+import javax.inject.Inject
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.delay
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.collect
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+import kotlinx.coroutines.sync.Semaphore
+import kotlinx.coroutines.sync.withPermit
+
+data class StremioCatalogRowKey(val addonId: Long, val catalogKey: String)
+
+data class StremioCatalogRowState(
+ val key: StremioCatalogRowKey,
+ val addonName: String,
+ val addonFingerprint: String,
+ val catalog: StremioCatalogRef,
+ val metas: List<StremioMetaPreview> = emptyList(),
+ val search: String = "",
+ val genre: String = "",
+ val loading: Boolean = false,
+ val loadingMore: Boolean = false,
+ val nextSkip: Int = 0,
+ val pageCount: Int = 0,
+ val canLoadMore: Boolean = false,
+ val error: String? = null,
+ val blockedReason: String? = null,
+ val waitingForInput: String? = null
+) {
+ val supportsSearch: Boolean get() = catalog.extras.any { it.name.equals("search", ignoreCase = true) }
+ val searchRequired: Boolean get() = catalog.extras.any {
+ it.name.equals("search", ignoreCase = true) && it.isRequired
+ }
+ val supportsSkip: Boolean get() = catalog.supportsSkip
+ val supportsGenre: Boolean get() = catalog.supportsGenre || catalog.extras.any {
+ it.name.equals("genre", ignoreCase = true)
+ }
+ val genreRequired: Boolean get() = catalog.extras.any {
+ it.name.equals("genre", ignoreCase = true) && it.isRequired
+ }
+ val genreOptions: List<String> get() = catalog.extras
+ .firstOrNull { it.name.equals("genre", ignoreCase = true) }
+ ?.options
+ ?.takeIf { it.isNotEmpty() }
+ ?: catalog.genres
+}
+
+data class StremioCatalogBrowseState(
+ val loading: Boolean = true,
+ val rows: List<StremioCatalogRowState> = emptyList()
+)
+
+@HiltViewModel
+class StremioCatalogBrowseViewModel @Inject constructor(
+ private val repository: StremioAddonRepository,
+ private val contentAccess: StremioContentAccess
+) : ViewModel() {
+
+ private val _state = MutableStateFlow(StremioCatalogBrowseState())
+ val state: StateFlow<StremioCatalogBrowseState> = _state.asStateFlow()
+
+ private val jobs = mutableMapOf<StremioCatalogRowKey, Job>()
+ private val generations = mutableMapOf<StremioCatalogRowKey, Long>()
+ private val seenPageFingerprints = mutableMapOf<StremioCatalogRowKey, MutableSet<String>>()
+ private val pageCache = CatalogPageMemoryCache()
+ private val requestSemaphore = Semaphore(MAX_CONCURRENT_REQUESTS)
+
+ init {
+ viewModelScope.launch {
+ repository.observeAddons().collect { addons -> refreshRows(addons) }
+ }
+ }
+
+ private suspend fun refreshRows(addons: List<StremioAddon>) {
+ val oldRows = _state.value.rows.associateBy { it.key }
+ val rows = buildList {
+ addons.asSequence().filter { it.enabled }.forEach addonLoop@{ addon ->
+ val manifest = repository.getManifest(addon.id) ?: return@addonLoop
+ manifest.catalogs.forEach catalogLoop@{ catalog ->
+ if (!addon.isCatalogEnabled(catalog.settingsKey)) return@catalogLoop
+ val key = StremioCatalogRowKey(addon.id, catalog.settingsKey)
+ val addonFingerprint = fingerprint(addon.installUrl, addon.manifestJson)
+ val blockedReason = when (catalog.type) {
+ StremioMediaType.MOVIE, StremioMediaType.SERIES ->
+ catalog.extras.firstOrNull { extra ->
+ extra.isRequired && extra.name.lowercase() !in SUPPORTED_EXTRAS
+ }?.let { "Requires unsupported '${it.name}' filter" }
+ else -> "${catalog.type.typeName} catalogs are not supported yet"
+ }
+ add(
+ oldRows[key]?.takeIf { it.addonFingerprint == addonFingerprint }?.copy(
+ addonName = addon.name,
+ addonFingerprint = addonFingerprint,
+ catalog = catalog,
+ blockedReason = blockedReason
+ ) ?: StremioCatalogRowState(
+ key = key,
+ addonName = addon.name,
+ addonFingerprint = addonFingerprint,
+ catalog = catalog,
+ blockedReason = blockedReason
+ )
+ )
+ }
+ }
+ }
+ val activeKeys = rows.mapTo(mutableSetOf()) { it.key }
+ val removedRows = oldRows.values.filter { it.key !in activeKeys }
+ removedRows.forEach { row ->
+ jobs.remove(row.key)?.cancel()
+ generations.remove(row.key)
+ seenPageFingerprints.remove(row.key)
+ pageCache.removeCatalog(row.addonFingerprint, row.catalog.settingsKey)
+ }
+ val refreshedKeys = rows.mapNotNull { row ->
+ row.key.takeIf { oldRows[it]?.addonFingerprint?.let { old -> old != row.addonFingerprint } == true }
+ }.toSet()
+ rows.forEach { row ->
+ oldRows[row.key]?.takeIf { row.key in refreshedKeys }?.let { old ->
+ jobs.remove(row.key)?.cancel()
+ seenPageFingerprints.remove(row.key)
+ pageCache.removeCatalog(old.addonFingerprint, old.catalog.settingsKey)
+ }
+ }
+ val isFirstLoad = _state.value.loading
+ _state.value = StremioCatalogBrowseState(loading = false, rows = rows)
+ rows.filter { (it.key !in oldRows || it.key in refreshedKeys) && it.blockedReason == null }.forEach { row ->
+ startRequest(row.key, reset = true, debounceMs = 0L)
+ }
+ if (isFirstLoad && rows.isEmpty()) _state.update { it.copy(loading = false) }
+ }
+
+ fun setSearch(key: StremioCatalogRowKey, search: String) {
+ if (_state.value.rows.firstOrNull { it.key == key }?.supportsSearch != true) return
+ updateRow(key) { it.copy(search = search, error = null, waitingForInput = null) }
+ startRequest(key, reset = true, debounceMs = SEARCH_DEBOUNCE_MS)
+ }
+
+ fun setGenre(key: StremioCatalogRowKey, genre: String) {
+ if (_state.value.rows.firstOrNull { it.key == key }?.supportsGenre != true) return
+ updateRow(key) { it.copy(genre = genre, error = null, waitingForInput = null) }
+ startRequest(key, reset = true, debounceMs = 0L)
+ }
+
+ fun retry(key: StremioCatalogRowKey) {
+ startRequest(key, reset = true, debounceMs = 0L)
+ }
+
+ fun loadMore(key: StremioCatalogRowKey) {
+ val row = _state.value.rows.firstOrNull { it.key == key } ?: return
+ if (!row.supportsSkip || !row.canLoadMore || row.loading || row.loadingMore || row.blockedReason != null) return
+ startRequest(key, reset = false, debounceMs = 0L)
+ }
+
+ private fun startRequest(key: StremioCatalogRowKey, reset: Boolean, debounceMs: Long) {
+ if (!contentAccess.canAccessContentNow()) return
+ val row = _state.value.rows.firstOrNull { it.key == key } ?: return
+ if (row.blockedReason != null) return
+ jobs.remove(key)?.cancel()
+ val generation = (generations[key] ?: 0L) + 1L
+ generations[key] = generation
+ if (reset) {
+ seenPageFingerprints[key] = mutableSetOf()
+ updateRow(key) {
+ it.copy(
+ metas = emptyList(),
+ loading = rowCanRequest(it),
+ loadingMore = false,
+ nextSkip = 0,
+ pageCount = 0,
+ canLoadMore = false,
+ error = null,
+ waitingForInput = missingRequiredInput(it)
+ )
+ }
+ } else {
+ updateRow(key) { it.copy(loadingMore = true, error = null) }
+ }
+ if (!rowCanRequest(_state.value.rows.first { it.key == key })) return
+ jobs[key] = viewModelScope.launch {
+ if (debounceMs > 0L) delay(debounceMs)
+ requestPage(key, generation, reset)
+ }
+ }
+
+ private suspend fun requestPage(
+ key: StremioCatalogRowKey,
+ generation: Long,
+ reset: Boolean
+ ) {
+ if (!contentAccess.canAccessContentNow()) return
+ val row = _state.value.rows.firstOrNull { it.key == key } ?: return
+ val skip = if (row.supportsSkip) row.nextSkip else null
+ val query = StremioCatalogQuery(
+ search = row.search.trim().takeIf { it.isNotEmpty() },
+ genre = row.genre.trim().takeIf { it.isNotEmpty() },
+ skip = skip
+ )
+ val cacheKey = CatalogPageCacheKey(
+ addonFingerprint = row.addonFingerprint,
+ catalogKey = row.catalog.settingsKey,
+ search = query.search.orEmpty(),
+ genre = query.genre.orEmpty(),
+ skip = skip
+ )
+ try {
+ val cachedPage = pageCache.get(cacheKey)
+ val result = if (cachedPage != null) {
+ null
+ } else {
+ requestSemaphore.withPermit {
+ repository.fetchCatalog(key.addonId, row.catalog, query)
+ .also { result -> result.getOrNull()?.let { pageCache.put(cacheKey, it) } }
+ }
+ }
+ val page = cachedPage ?: result?.getOrNull()
+ if (generations[key] != generation) return
+ if (page == null) {
+ val error = result?.errorMessageOrNull() ?: "Catalog could not be loaded"
+ updateRow(key) {
+ it.copy(loading = false, loadingMore = false, error = error, canLoadMore = false)
+ }
+ return
+ }
+ applyPage(key, row, page, skip ?: 0, reset)
+ } catch (cancellation: CancellationException) {
+ throw cancellation
+ } catch (error: Exception) {
+ if (generations[key] == generation) {
+ updateRow(key) {
+ it.copy(
+ loading = false,
+ loadingMore = false,
+ error = error.message ?: "Catalog could not be loaded",
+ canLoadMore = false
+ )
+ }
+ }
+ }
+ }
+
+ private fun applyPage(
+ key: StremioCatalogRowKey,
+ requestedRow: StremioCatalogRowState,
+ page: StremioCatalogPage,
+ skip: Int,
+ reset: Boolean
+ ) {
+ val fingerprint = buildString {
+ append(page.rawItemCount)
+ page.metas.forEach { append('|').append(it.type.typeName).append(':').append(it.id) }
+ }
+ val seen = seenPageFingerprints.getOrPut(key) { mutableSetOf() }
+ val repeated = !seen.add(fingerprint)
+ val current = _state.value.rows.firstOrNull { it.key == key } ?: return
+ val known = if (reset) emptySet() else current.metas.mapTo(mutableSetOf()) { it.type.typeName to it.id }
+ val uniqueNew = page.metas.distinctBy { it.type.typeName to it.id }
+ .filterNot { (it.type.typeName to it.id) in known }
+ val nextSkip = skip + page.rawItemCount
+ val rawHasMore = page.hasMore ?: (page.rawItemCount >= PAGE_SIZE)
+ val canLoadMore = requestedRow.supportsSkip && rawHasMore && page.rawItemCount > 0 &&
+ !repeated && current.pageCount + 1 < MAX_PAGES_PER_QUERY
+ updateRow(key) {
+ it.copy(
+ metas = if (reset) uniqueNew else it.metas + uniqueNew,
+ loading = false,
+ loadingMore = false,
+ nextSkip = nextSkip,
+ pageCount = if (reset) 1 else it.pageCount + 1,
+ canLoadMore = canLoadMore,
+ error = when {
+ repeated -> "The addon repeated a page; loading stopped."
+ rawHasMore && !canLoadMore && page.rawItemCount > 0 &&
+ requestedRow.supportsSkip && current.pageCount + 1 >= MAX_PAGES_PER_QUERY ->
+ "Catalog page limit reached."
+ else -> null
+ }
+ )
+ }
+ }
+
+ private fun missingRequiredInput(row: StremioCatalogRowState): String? = when {
+ row.searchRequired && row.search.isBlank() -> "Enter a search to load this catalog."
+ row.genreRequired && row.genre.isBlank() -> "Choose a genre to load this catalog."
+ else -> null
+ }
+
+ private fun rowCanRequest(row: StremioCatalogRowState): Boolean =
+ row.blockedReason == null && missingRequiredInput(row) == null
+
+ private fun updateRow(key: StremioCatalogRowKey, transform: (StremioCatalogRowState) -> StremioCatalogRowState) {
+ _state.update { state -> state.copy(rows = state.rows.map { row -> if (row.key == key) transform(row) else row }) }
+ }
+
+ private fun fingerprint(url: String, manifestJson: String): String = MessageDigest.getInstance("SHA-256")
+ .digest("stremio-addon-install\u0000$url\u0000$manifestJson".toByteArray(Charsets.UTF_8))
+ .joinToString("") { byte -> "%02x".format(byte) }
+
+ override fun onCleared() {
+ jobs.values.forEach(Job::cancel)
+ jobs.clear()
+ super.onCleared()
+ }
+
+ private data class CatalogPageCacheKey(
+ val addonFingerprint: String,
+ val catalogKey: String,
+ val search: String,
+ val genre: String,
+ val skip: Int?
+ )
+
+ private class CatalogPageMemoryCache {
+ private data class Entry(val expiresAtMs: Long, val page: StremioCatalogPage)
+
+ private val entries = object : LinkedHashMap<CatalogPageCacheKey, Entry>(16, 0.75f, true) {}
+
+ @Synchronized
+ fun get(key: CatalogPageCacheKey): StremioCatalogPage? {
+ val entry = entries[key] ?: return null
+ if (entry.expiresAtMs <= System.currentTimeMillis()) {
+ entries.remove(key)
+ return null
+ }
+ return entry.page
+ }
+
+ @Synchronized
+ fun put(key: CatalogPageCacheKey, page: StremioCatalogPage) {
+ entries[key] = Entry(System.currentTimeMillis() + CACHE_TTL_MS, page)
+ while (entries.size > MAX_CACHED_PAGES) {
+ entries.entries.iterator().run { next(); remove() }
+ }
+ }
+
+ @Synchronized
+ fun removeCatalog(addonFingerprint: String, catalogKey: String) {
+ entries.keys.removeAll {
+ it.addonFingerprint == addonFingerprint && it.catalogKey == catalogKey
+ }
+ }
+ }
+
+ private companion object {
+ const val PAGE_SIZE = 100
+ const val MAX_PAGES_PER_QUERY = 100
+ const val MAX_CONCURRENT_REQUESTS = 4
+ const val MAX_CACHED_PAGES = 200
+ const val CACHE_TTL_MS = 5 * 60 * 1000L
+ const val SEARCH_DEBOUNCE_MS = 350L
+ val SUPPORTED_EXTRAS = setOf("search", "genre", "skip")
+ }
+}
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioContentAccess.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioContentAccess.kt
new file mode 100644
index 00000000..271f138c
--- /dev/null
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioContentAccess.kt
@@ -0,0 +1,63 @@
+package com.streamvault.feature.stremio.presentation
+
+import androidx.lifecycle.ViewModel
+import com.streamvault.domain.settings.SettingsPreferences
+import dagger.Binds
+import dagger.Module
+import dagger.hilt.InstallIn
+import dagger.hilt.components.SingletonComponent
+import javax.inject.Inject
+import javax.inject.Singleton
+import kotlinx.coroutines.CoroutineScope
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.SupervisorJob
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.distinctUntilChanged
+import kotlinx.coroutines.launch
+
+// Null means the persisted preference has not loaded yet; routes wait before fetching content.
+data class StremioVisibilityState(val hidden: Boolean? = null) {
+ val canAccessContent: Boolean get() = hidden == false
+ val showContinueWatching: Boolean get() = canAccessContent
+}
+
+interface StremioContentAccess {
+ val state: StateFlow<StremioVisibilityState>
+ fun canAccessContentNow(): Boolean = state.value.canAccessContent
+}
+
+class StremioVisibilityViewModel @Inject constructor(
+ contentAccess: StremioContentAccess
+) : ViewModel() {
+ val state = contentAccess.state
+}
+
+@Singleton
+class StremioVisibilityManager @Inject constructor(
+ preferences: SettingsPreferences
+) : StremioContentAccess {
+ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Default)
+ private val _state = MutableStateFlow(StremioVisibilityState())
+ override val state: StateFlow<StremioVisibilityState> = _state.asStateFlow()
+
+ init {
+ scope.launch {
+ preferences.hideStremioAddons.distinctUntilChanged().collect { hidden ->
+ _state.value = StremioVisibilityState(hidden = hidden)
+ }
+ }
+ }
+}
+
+@Module
+@InstallIn(SingletonComponent::class)
+abstract class StremioContentAccessModule {
+ @Binds
+ @Singleton
+ abstract fun bindStremioContentAccess(
+ implementation: StremioVisibilityManager
+ ): StremioContentAccess
+}
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioItemDetailContent.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioItemDetailContent.kt
new file mode 100644
index 00000000..7ed301d8
--- /dev/null
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioItemDetailContent.kt
@@ -0,0 +1,410 @@
+package com.streamvault.feature.stremio.presentation
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.Spacer
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.height
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.size
+import androidx.compose.foundation.layout.width
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.lazy.itemsIndexed
+import androidx.compose.material3.Button
+import androidx.compose.material3.Card
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.material3.MaterialTheme
+import androidx.compose.material3.Text
+import androidx.compose.material3.TextButton
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.layout.ContentScale
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.text.style.TextOverflow
+import androidx.compose.ui.unit.dp
+import androidx.hilt.navigation.compose.hiltViewModel
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import coil3.compose.AsyncImage
+import com.streamvault.core.navigation.AppDestination
+import com.streamvault.core.navigation.StremioPlaybackReference
+import com.streamvault.core.navigation.StremioPlayerHandoff
+import com.streamvault.core.navigation.StremioSubtitlePlaybackSource
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioStream
+import com.streamvault.domain.model.stremio.StremioStreamKind
+import com.streamvault.domain.model.stremio.stremioMediaRequestHeaders
+import com.streamvault.domain.model.stremio.toMagnetUri
+import com.streamvault.feature.stremio.R
+import com.streamvault.feature.stremio.api.StremioScaffoldContent
+
+@Composable
+internal fun StremioItemDetailScreen(
+ scaffold: StremioScaffoldContent,
+ onPlay: (StremioPlayerHandoff) -> Unit,
+ viewModel: StremioItemDetailViewModel = hiltViewModel()
+) {
+ val state by viewModel.state.collectAsStateWithLifecycle()
+ scaffold(
+ AppDestination.Addons,
+ state.displayName,
+ state.displayReleaseInfo,
+ false,
+ true
+ ) {
+ StremioItemDetailContent(
+ state = state,
+ onLoadMovieStreams = { viewModel.loadStreams(state.preview.id) },
+ onLoadEpisodeStreams = viewModel::loadStreams,
+ onRetryMetadata = viewModel::retryMetadata,
+ onRetryAddon = viewModel::retryStreamsForAddon,
+ onPlay = onPlay
+ )
+ }
+}
+
+@Composable
+private fun StremioItemDetailContent(
+ state: StremioItemDetailState,
+ onLoadMovieStreams: () -> Unit,
+ onLoadEpisodeStreams: (String) -> Unit,
+ onRetryMetadata: () -> Unit,
+ onRetryAddon: (Long) -> Unit,
+ onPlay: (StremioPlayerHandoff) -> Unit
+) {
+ LazyColumn(
+ modifier = Modifier.fillMaxSize().padding(horizontal = 24.dp, vertical = 12.dp),
+ verticalArrangement = Arrangement.spacedBy(16.dp)
+ ) {
+ if (state.replayOriginUnavailable) {
+ item(key = "history-origin-unavailable") {
+ Text(
+ stringResource(R.string.stremio_history_origin_unavailable),
+ color = MaterialTheme.colorScheme.error
+ )
+ }
+ }
+ item(key = "meta") {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.spacedBy(20.dp)
+ ) {
+ AsyncImage(
+ model = state.displayPoster,
+ contentDescription = null,
+ modifier = Modifier.width(160.dp).height(230.dp),
+ contentScale = ContentScale.Crop
+ )
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ Text(
+ state.displayName,
+ style = MaterialTheme.typography.headlineSmall,
+ color = MaterialTheme.colorScheme.onSurface
+ )
+ state.displayReleaseInfo?.let {
+ Text(
+ it,
+ style = MaterialTheme.typography.bodyMedium,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ state.metadata?.genres?.takeIf { it.isNotEmpty() }?.let { genres ->
+ Text(
+ genres.joinToString(" · "),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ state.displayDescription?.let { description ->
+ Text(
+ description,
+ style = MaterialTheme.typography.bodyMedium,
+ maxLines = 6,
+ overflow = TextOverflow.Ellipsis,
+ color = MaterialTheme.colorScheme.onSurface
+ )
+ }
+ state.metaOrigin?.let { origin ->
+ Text(
+ "Metadata from ${origin.addonName}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ if (state.metadataLoading) {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
+ Spacer(Modifier.width(8.dp))
+ Text(
+ stringResource(R.string.stremio_item_metadata_loading),
+ color = MaterialTheme.colorScheme.onSurface
+ )
+ }
+ } else if (state.metadata == null) {
+ Text(
+ stringResource(R.string.stremio_item_preview_only),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ state.metadataFailures.forEach { failure ->
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ stringResource(
+ R.string.stremio_item_metadata_failed,
+ failure.source.addonName,
+ failure.message
+ ),
+ modifier = Modifier.weight(1f),
+ color = MaterialTheme.colorScheme.error
+ )
+ TextButton(onClick = onRetryMetadata) {
+ Text(stringResource(R.string.stremio_retry))
+ }
+ }
+ }
+ }
+ }
+ }
+ }
+
+ if (state.preview.type == StremioMediaType.MOVIE) {
+ item(key = "movie-streams") {
+ Button(onClick = onLoadMovieStreams, enabled = !state.replayOriginUnavailable) {
+ Text(stringResource(R.string.stremio_item_find_streams))
+ }
+ }
+ } else if (state.preview.type == StremioMediaType.SERIES) {
+ item(key = "episodes-header") {
+ Text(
+ stringResource(R.string.stremio_item_episodes),
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onSurface
+ )
+ }
+ if (state.metadataLoading) {
+ item(key = "episodes-loading") {
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ CircularProgressIndicator(modifier = Modifier.size(18.dp), strokeWidth = 2.dp)
+ Spacer(Modifier.width(8.dp))
+ Text(
+ stringResource(R.string.stremio_item_metadata_loading),
+ color = MaterialTheme.colorScheme.onSurface
+ )
+ }
+ }
+ } else if (state.videos.isEmpty()) {
+ item(key = "episodes-empty") {
+ Text(
+ stringResource(R.string.stremio_item_no_episode_ids),
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ } else {
+ items(state.videos, key = { "episode:${it.id}" }) { video ->
+ Button(
+ onClick = { onLoadEpisodeStreams(video.id) },
+ enabled = !state.replayOriginUnavailable,
+ modifier = Modifier.fillMaxWidth()
+ ) {
+ Text(episodeLabel(video))
+ }
+ }
+ }
+ }
+
+ state.requestedVideoId?.let { requestedVideoId ->
+ item(key = "streams-heading") {
+ Text(
+ stringResource(
+ R.string.stremio_item_streams_for,
+ state.selectedVideo?.title ?: state.displayName
+ ),
+ style = MaterialTheme.typography.titleLarge,
+ color = MaterialTheme.colorScheme.onSurface
+ )
+ }
+ if (state.streamsLoading && state.streams.isEmpty()) {
+ item(key = "streams-loading") {
+ Box(Modifier.fillMaxWidth().height(96.dp), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator()
+ }
+ }
+ }
+ if (!state.streamsLoading && state.streams.isEmpty() &&
+ state.streamFailures.isEmpty() && state.streamCandidateCount == 0
+ ) {
+ item(key = "streams-no-addon") {
+ Text(
+ stringResource(R.string.stremio_item_no_stream_addons),
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ } else if (!state.streamsLoading && state.streams.isEmpty() && state.streamFailures.isEmpty()) {
+ item(key = "streams-empty") {
+ Text(
+ stringResource(R.string.stremio_item_no_streams),
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+ itemsIndexed(
+ items = state.streams,
+ key = { index, item -> "stream:${item.source.addonId}:$index" }
+ ) { _, attributed ->
+ val stream = attributed.resource
+ val mediaHeaders = stream.url?.let {
+ stremioMediaRequestHeaders(it, stream.behaviorHints?.proxyHeaders?.request)
+ }
+ val isHttpUrl = stream.url?.let {
+ it.startsWith("http://", ignoreCase = true) || it.startsWith("https://", ignoreCase = true)
+ } == true
+ val canPlay = when (stream.kind) {
+ StremioStreamKind.DIRECT -> mediaHeaders != null && isHttpUrl
+ StremioStreamKind.TORRENT -> stream.toMagnetUri() != null
+ else -> false
+ }
+ Card(modifier = Modifier.fillMaxWidth()) {
+ Row(
+ modifier = Modifier.fillMaxWidth().padding(16.dp),
+ verticalAlignment = Alignment.CenterVertically,
+ horizontalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Column(modifier = Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ stream.title ?: stream.name ?: stream.description ?: stream.kind.name,
+ style = MaterialTheme.typography.titleMedium
+ )
+ Text(
+ "${attributed.source.addonName} · ${stream.kind.name.lowercase()}",
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ if (!canPlay) {
+ Text(
+ unsupportedStreamLabel(stream),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ } else if (stream.kind == StremioStreamKind.TORRENT) {
+ Text(
+ stringResource(R.string.stremio_item_torrent_plugin_hint),
+ style = MaterialTheme.typography.bodySmall,
+ color = MaterialTheme.colorScheme.onSurfaceVariant
+ )
+ }
+ }
+ if (canPlay) {
+ Button(
+ enabled = state.catalogOriginKey != null && requestedVideoId.isNotBlank(),
+ onClick = {
+ buildHandoff(state, attributed.source.installFingerprint, stream, requestedVideoId)
+ ?.let(onPlay)
+ }
+ ) { Text(stringResource(R.string.stremio_item_play)) }
+ }
+ }
+ }
+ }
+ items(state.streamFailures, key = { "stream-error:${it.source.addonId}" }) { failure ->
+ Row(verticalAlignment = Alignment.CenterVertically) {
+ Text(
+ stringResource(
+ R.string.stremio_item_stream_failed,
+ failure.source.addonName,
+ failure.message
+ ),
+ modifier = Modifier.weight(1f),
+ color = MaterialTheme.colorScheme.error
+ )
+ TextButton(onClick = { onRetryAddon(failure.source.addonId) }) {
+ Text(stringResource(R.string.stremio_retry))
+ }
+ }
+ }
+ }
+ }
+}
+
+private fun episodeLabel(video: com.streamvault.domain.model.stremio.StremioVideo): String {
+ val number = listOfNotNull(video.season?.let { "S$it" }, video.episode?.let { "E$it" })
+ .joinToString("")
+ return listOfNotNull(number.takeIf(String::isNotBlank), video.title ?: video.id).joinToString(" · ")
+}
+
+@Composable
+private fun unsupportedStreamLabel(stream: StremioStream): String {
+ val stringRes = when {
+ stream.kind == StremioStreamKind.DIRECT && stream.url?.let {
+ stremioMediaRequestHeaders(it, stream.behaviorHints?.proxyHeaders?.request)
+ } == null -> R.string.stremio_item_headers_unavailable
+ stream.kind == StremioStreamKind.TORRENT -> if (stream.toMagnetUri() == null) {
+ R.string.stremio_item_torrent_invalid
+ } else {
+ R.string.stremio_item_torrent_unavailable
+ }
+ stream.kind == StremioStreamKind.UNKNOWN -> R.string.stremio_item_unsupported_stream
+ stream.kind == StremioStreamKind.YOUTUBE || stream.kind == StremioStreamKind.EXTERNAL ->
+ R.string.stremio_item_external_unavailable
+ else -> R.string.stremio_item_external_unavailable
+ }
+ return stringResource(stringRes)
+}
+
+private fun buildHandoff(
+ state: StremioItemDetailState,
+ streamOriginKey: String,
+ stream: StremioStream,
+ exactVideoId: String
+): StremioPlayerHandoff? {
+ val (url, requestHeaders) = when (stream.kind) {
+ StremioStreamKind.DIRECT -> {
+ val directUrl = stream.url?.takeIf {
+ it.startsWith("http://", ignoreCase = true) || it.startsWith("https://", ignoreCase = true)
+ } ?: return null
+ val headers = stremioMediaRequestHeaders(directUrl, stream.behaviorHints?.proxyHeaders?.request)
+ ?: return null
+ directUrl to headers.headers
+ }
+ StremioStreamKind.TORRENT -> (stream.toMagnetUri() ?: return null) to emptyMap()
+ else -> return null
+ }
+ val catalogOriginKey = state.catalogOriginKey ?: return null
+ val contentType = when (state.preview.type) {
+ StremioMediaType.MOVIE -> "MOVIE"
+ StremioMediaType.SERIES -> "SERIES_EPISODE"
+ else -> return null
+ }
+ return StremioPlayerHandoff(
+ streamUrl = url,
+ title = state.selectedVideo?.title?.let { "${state.displayName} · $it" } ?: state.displayName,
+ artworkUrl = state.selectedVideo?.thumbnail ?: state.displayPoster,
+ contentType = contentType,
+ mediaRequestHeaders = requestHeaders,
+ reference = StremioPlaybackReference(
+ mediaType = state.preview.type.typeName,
+ exactVideoId = exactVideoId,
+ parentSeriesId = state.preview.id.takeIf { state.preview.type == StremioMediaType.SERIES },
+ catalogOriginKey = catalogOriginKey,
+ metaOriginKey = state.metaOrigin?.installFingerprint,
+ streamOriginKey = streamOriginKey,
+ videoHash = stream.behaviorHints?.videoHash,
+ videoSize = stream.behaviorHints?.videoSize,
+ filename = stream.behaviorHints?.filename
+ ),
+ inlineSubtitles = stream.subtitles.map { subtitle ->
+ StremioSubtitlePlaybackSource(
+ url = subtitle.url,
+ language = subtitle.lang,
+ id = subtitle.id
+ )
+ }
+ )
+}
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioItemDetailViewModel.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioItemDetailViewModel.kt
new file mode 100644
index 00000000..692e6270
--- /dev/null
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioItemDetailViewModel.kt
@@ -0,0 +1,232 @@
+package com.streamvault.feature.stremio.presentation
+
+import androidx.lifecycle.SavedStateHandle
+import androidx.lifecycle.ViewModel
+import androidx.lifecycle.viewModelScope
+import com.streamvault.domain.model.stremio.StremioAddonResourceFailure
+import com.streamvault.domain.model.stremio.StremioAddonSource
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaDetail
+import com.streamvault.domain.model.stremio.StremioMetaPreview
+import com.streamvault.domain.model.stremio.StremioStream
+import com.streamvault.domain.model.stremio.StremioSubtitle
+import com.streamvault.domain.model.stremio.StremioVideo
+import com.streamvault.domain.model.stremio.installFingerprint
+import com.streamvault.domain.repository.StremioAddonRepository
+import dagger.hilt.android.lifecycle.HiltViewModel
+import javax.inject.Inject
+import kotlinx.coroutines.CancellationException
+import kotlinx.coroutines.Job
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+import kotlinx.coroutines.flow.asStateFlow
+import kotlinx.coroutines.flow.update
+import kotlinx.coroutines.launch
+
+data class StremioItemDetailState(
+ val preview: StremioMetaPreview,
+ val catalogOriginAddonId: Long,
+ val catalogOriginKey: String? = null,
+ val replayOriginUnavailable: Boolean = false,
+ val metadata: StremioMetaDetail? = null,
+ val metaOrigin: StremioAddonSource? = null,
+ val metadataLoading: Boolean = true,
+ val metadataFailures: List<StremioAddonResourceFailure> = emptyList(),
+ val requestedVideoId: String? = null,
+ val selectedVideo: StremioVideo? = null,
+ val streamsLoading: Boolean = false,
+ val streams: List<com.streamvault.domain.model.stremio.StremioAttributedResource<StremioStream>> = emptyList(),
+ val streamFailures: List<StremioAddonResourceFailure> = emptyList(),
+ val streamCandidateCount: Int = 0,
+ val subtitles: List<com.streamvault.domain.model.stremio.StremioAttributedResource<StremioSubtitle>> = emptyList(),
+ val subtitleFailures: List<StremioAddonResourceFailure> = emptyList()
+) {
+ val displayName: String get() = metadata?.name ?: preview.name
+ val displayPoster: String? get() = metadata?.poster ?: preview.poster
+ val displayDescription: String? get() = metadata?.description ?: preview.description
+ val displayReleaseInfo: String? get() = metadata?.releaseInfo ?: preview.releaseInfo
+ val videos: List<StremioVideo> get() = metadata?.videos.orEmpty()
+}
+
+@HiltViewModel
+class StremioItemDetailViewModel @Inject constructor(
+ savedStateHandle: SavedStateHandle,
+ private val repository: StremioAddonRepository,
+ private val contentAccess: StremioContentAccess
+) : ViewModel() {
+
+ private val originAddonId = savedStateHandle.get<Long>(ARG_ORIGIN_ADDON_ID) ?: -1L
+ private val type = StremioMediaType.fromTypeName(savedStateHandle[ARG_TYPE])
+ private val exactId = savedStateHandle.get<String>(ARG_EXACT_ID).orEmpty()
+ private val replayVideoId = savedStateHandle.get<String>(ARG_REPLAY_VIDEO_ID)?.takeIf(String::isNotBlank)
+ private val replayOriginKey = savedStateHandle.get<String>(ARG_REPLAY_ORIGIN_KEY)?.takeIf(String::isNotBlank)
+ private val replayRequiresOrigin = savedStateHandle.get<Boolean>(ARG_REPLAY_REQUIRES_ORIGIN) ?: false
+ private val preview = StremioMetaPreview(
+ id = exactId,
+ type = type,
+ name = savedStateHandle.get<String>(ARG_NAME)?.takeIf(String::isNotBlank) ?: exactId,
+ poster = savedStateHandle.get<String>(ARG_POSTER)?.takeIf(String::isNotBlank),
+ description = savedStateHandle.get<String>(ARG_DESCRIPTION)?.takeIf(String::isNotBlank),
+ releaseInfo = savedStateHandle.get<String>(ARG_RELEASE_INFO)?.takeIf(String::isNotBlank)
+ )
+
+ private val _state = MutableStateFlow(
+ StremioItemDetailState(
+ preview = preview,
+ catalogOriginAddonId = originAddonId,
+ catalogOriginKey = replayOriginKey
+ )
+ )
+ val state: StateFlow<StremioItemDetailState> = _state.asStateFlow()
+
+ private var metadataJob: Job? = null
+ private var streamJob: Job? = null
+ private var streamGeneration = 0L
+
+ init {
+ loadMetadata()
+ }
+
+ fun retryMetadata() = loadMetadata()
+
+ fun loadStreams(videoId: String) {
+ if (!contentAccess.canAccessContentNow() || videoId.isBlank() ||
+ type == StremioMediaType.UNKNOWN || _state.value.replayOriginUnavailable
+ ) return
+ val current = _state.value
+ val selectedVideo = when (type) {
+ StremioMediaType.MOVIE -> {
+ if (videoId != exactId) return
+ null
+ }
+ StremioMediaType.SERIES -> current.metadata?.videos?.firstOrNull { it.id == videoId }
+ ?: if (videoId == replayVideoId) null else return
+ else -> return
+ }
+ streamJob?.cancel()
+ val generation = ++streamGeneration
+ _state.update {
+ it.copy(
+ requestedVideoId = videoId,
+ selectedVideo = selectedVideo,
+ streamsLoading = true,
+ streams = emptyList(),
+ streamFailures = emptyList(),
+ streamCandidateCount = 0,
+ subtitles = emptyList(),
+ subtitleFailures = emptyList()
+ )
+ }
+ streamJob = viewModelScope.launch {
+ try {
+ if (!contentAccess.canAccessContentNow()) return@launch
+ val result = repository.resolveStreams(type, videoId)
+ if (generation == streamGeneration) {
+ _state.update {
+ it.copy(
+ streamsLoading = false,
+ streams = result.results,
+ streamFailures = result.failures,
+ streamCandidateCount = result.candidateCount
+ )
+ }
+ }
+ } catch (cancellation: CancellationException) {
+ throw cancellation
+ } catch (_: Exception) {
+ if (generation == streamGeneration) {
+ _state.update { it.copy(streamsLoading = false) }
+ }
+ }
+ }
+ }
+
+ fun retryStreamsForAddon(addonId: Long) {
+ if (!contentAccess.canAccessContentNow()) return
+ val current = _state.value
+ val videoId = current.requestedVideoId ?: return
+ val generation = ++streamGeneration
+ streamJob?.cancel()
+ _state.update { it.copy(streamsLoading = true) }
+ streamJob = viewModelScope.launch {
+ try {
+ if (!contentAccess.canAccessContentNow()) return@launch
+ val result = repository.resolveStreams(type, videoId, setOf(addonId))
+ if (generation == streamGeneration) {
+ _state.update { state ->
+ state.copy(
+ streamsLoading = false,
+ streams = state.streams.filterNot { it.source.addonId == addonId } + result.results,
+ streamFailures = state.streamFailures.filterNot { it.source.addonId == addonId } + result.failures,
+ streamCandidateCount = maxOf(state.streamCandidateCount, result.candidateCount)
+ )
+ }
+ }
+ } catch (cancellation: CancellationException) {
+ throw cancellation
+ } catch (_: Exception) {
+ if (generation == streamGeneration) {
+ _state.update { it.copy(streamsLoading = false) }
+ }
+ }
+ }
+ }
+
+ private fun loadMetadata() {
+ if (!contentAccess.canAccessContentNow()) {
+ metadataJob?.cancel()
+ _state.update { it.copy(metadataLoading = false) }
+ return
+ }
+ metadataJob?.cancel()
+ _state.update { it.copy(metadataLoading = true, metadataFailures = emptyList()) }
+ metadataJob = viewModelScope.launch {
+ if (!contentAccess.canAccessContentNow()) {
+ _state.update { it.copy(metadataLoading = false) }
+ return@launch
+ }
+ val origin = repository.getAddon(originAddonId)
+ val originKey = origin?.installFingerprint()
+ if (replayRequiresOrigin && (origin == null || !origin.enabled || originKey != replayOriginKey)) {
+ _state.update {
+ it.copy(
+ metadataLoading = false,
+ catalogOriginKey = replayOriginKey,
+ replayOriginUnavailable = true
+ )
+ }
+ return@launch
+ }
+ _state.update { it.copy(catalogOriginKey = replayOriginKey ?: originKey) }
+ try {
+ val result = repository.resolveMeta(originAddonId, type, exactId)
+ _state.update {
+ it.copy(
+ metadataLoading = false,
+ metadata = result.result?.resource,
+ metaOrigin = result.result?.source,
+ metadataFailures = result.failures
+ )
+ }
+ replayVideoId?.let(::loadStreams)
+ } catch (cancellation: CancellationException) {
+ throw cancellation
+ } catch (_: Exception) {
+ _state.update { it.copy(metadataLoading = false) }
+ }
+ }
+ }
+
+ companion object {
+ const val ARG_ORIGIN_ADDON_ID = "originAddonId"
+ const val ARG_TYPE = "type"
+ const val ARG_EXACT_ID = "exactId"
+ const val ARG_NAME = "name"
+ const val ARG_POSTER = "poster"
+ const val ARG_DESCRIPTION = "description"
+ const val ARG_RELEASE_INFO = "releaseInfo"
+ const val ARG_REPLAY_VIDEO_ID = "replayVideoId"
+ const val ARG_REPLAY_ORIGIN_KEY = "replayOriginKey"
+ const val ARG_REPLAY_REQUIRES_ORIGIN = "replayRequiresOrigin"
+ }
+}
diff --git a/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioVisibilityHost.kt b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioVisibilityHost.kt
new file mode 100644
index 00000000..29126c80
--- /dev/null
+++ b/feature/stremio/src/main/java/com/streamvault/feature/stremio/presentation/StremioVisibilityHost.kt
@@ -0,0 +1,70 @@
+package com.streamvault.feature.stremio.presentation
+
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Box
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.material3.CircularProgressIndicator
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.res.stringResource
+import androidx.compose.ui.unit.dp
+import androidx.hilt.navigation.compose.hiltViewModel
+import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import com.streamvault.core.navigation.AppDestination
+import com.streamvault.core.ui.components.shell.ExtensionsEmptyState
+import com.streamvault.core.ui.components.shell.ExtensionsSectionTabs
+import com.streamvault.core.ui.interaction.TvButton
+import androidx.tv.material3.ButtonDefaults
+import androidx.tv.material3.Text
+import com.streamvault.feature.stremio.R
+import com.streamvault.feature.stremio.api.StremioScaffoldContent
+
+@Composable
+internal fun StremioVisibilityHost(
+ scaffold: StremioScaffoldContent,
+ title: String,
+ showExtensionsTabs: Boolean = false,
+ onNavigateToPlugins: () -> Unit = {},
+ onOpenSettings: () -> Unit,
+ content: @Composable (StremioVisibilityState) -> Unit,
+ viewModel: StremioVisibilityViewModel = hiltViewModel()
+) {
+ val state by viewModel.state.collectAsStateWithLifecycle()
+ if (state.canAccessContent) {
+ content(state)
+ } else {
+ scaffold(AppDestination.Addons, title, null, false, true) {
+ Column(Modifier.fillMaxSize(), verticalArrangement = Arrangement.spacedBy(20.dp)) {
+ if (showExtensionsTabs) {
+ ExtensionsSectionTabs(
+ selectedIndex = 1,
+ pluginsLabel = stringResource(R.string.extensions_tab_plugins),
+ stremioAddonsLabel = stringResource(R.string.extensions_tab_stremio_addons),
+ onTabSelected = { if (it == 0) onNavigateToPlugins() }
+ )
+ }
+ if (state.hidden == null) {
+ Box(Modifier.weight(1f).fillMaxWidth(), contentAlignment = Alignment.Center) {
+ CircularProgressIndicator()
+ }
+ } else {
+ ExtensionsEmptyState(
+ title = stringResource(R.string.stremio_hidden_title),
+ description = stringResource(R.string.stremio_hidden_message),
+ modifier = Modifier.weight(1f),
+ action = {
+ TvButton(
+ onClick = onOpenSettings,
+ scale = ButtonDefaults.scale(focusedScale = 1f, pressedScale = 1f)
+ ) { Text(stringResource(R.string.stremio_open_settings)) }
+ }
+ )
+ }
+ }
+ }
+ }
+}
diff --git a/feature/stremio/src/main/res/values/strings.xml b/feature/stremio/src/main/res/values/strings.xml
index d354e7c5..5e49fb0e 100644
--- a/feature/stremio/src/main/res/values/strings.xml
+++ b/feature/stremio/src/main/res/values/strings.xml
@@ -1,20 +1,67 @@
<resources>
- <string name="stremio_title">Addons</string>
- <string name="stremio_subtitle">Stremio addons</string>
- <string name="stremio_add">Add addon</string>
- <string name="stremio_empty">No addons installed yet. Paste a Stremio addon manifest URL to get started.</string>
- <string name="stremio_install_title">Add Stremio addon</string>
+ <string name="stremio_title">Stremio-compatible Add-ons</string>
+ <string name="stremio_subtitle">Stremio-compatible add-ons</string>
+ <string name="stremio_add">Add Stremio-compatible add-on</string>
+ <string name="stremio_empty">No add-ons installed yet. Paste a Stremio-compatible add-on manifest URL to get started.</string>
+ <string name="stremio_install_title">Add Stremio-compatible add-on</string>
+ <string name="stremio_install_description">Paste a Stremio-compatible add-on manifest URL or stremio:// install link. If the add-on needs configuration, configure it in your browser first and paste the resulting link.</string>
+ <string name="stremio_install_url_label">Add-on manifest URL</string>
<string name="stremio_install_hint">https://example.com/manifest.json</string>
<string name="stremio_install_confirm">Add</string>
- <string name="stremio_installing">Adding addon…</string>
+ <string name="stremio_installing">Adding add-on...</string>
<string name="stremio_cancel">Cancel</string>
<string name="stremio_enabled">Enabled</string>
<string name="stremio_move_up">Move up</string>
<string name="stremio_move_down">Move down</string>
<string name="stremio_catalogs">Catalogs</string>
<string name="stremio_remove">Remove</string>
- <string name="stremio_status_installed">Addon installed</string>
- <string name="stremio_status_removed">Addon removed</string>
- <string name="stremio_no_catalogs">This addon exposes no browsable catalogs.</string>
+ <string name="stremio_status_installed">Add-on installed</string>
+ <string name="stremio_status_removed">Add-on removed</string>
+ <string name="stremio_addon_server_format">Server: %1$s</string>
+ <string name="stremio_addon_server_unknown">Custom endpoint</string>
+ <string name="stremio_no_catalogs">This add-on exposes no browsable catalogs.</string>
<string name="stremio_version_format">Version %1$s</string>
+ <string name="stremio_tab_browse">Browse</string>
+ <string name="stremio_tab_manage">Manage add-ons</string>
+ <string name="stremio_continue_watching">Continue watching</string>
+ <string name="stremio_history_origin_unavailable">This item came from an add-on that is not currently enabled. Enable or reinstall that add-on to continue.</string>
+ <string name="extensions_tab_plugins">Plugins</string>
+ <string name="extensions_tab_stremio_addons">Stremio-compatible Add-ons</string>
+ <string name="stremio_browse_empty">Enable a catalog or install a compatible add-on to browse Stremio titles.</string>
+ <string name="stremio_browse_manage_hint">Manage installed add-ons</string>
+ <string name="stremio_search_catalog">Search this catalog</string>
+ <string name="stremio_filter_genre">Genre</string>
+ <string name="stremio_all_genres">All genres</string>
+ <string name="stremio_load_more">Load more</string>
+ <string name="stremio_retry">Retry</string>
+ <string name="stremio_empty_catalog">No titles found.</string>
+ <string name="stremio_catalog_waiting_search">Enter a search to load this catalog.</string>
+ <string name="stremio_catalog_waiting_genre">Choose a genre to load this catalog.</string>
+ <string name="stremio_unsupported_catalog_type">This catalog type is not supported yet.</string>
+ <string name="stremio_catalog_item_a11y">%1$s, %2$s</string>
+ <string name="stremio_item_metadata_loading">Loading title details...</string>
+ <string name="stremio_item_preview_only">Showing the catalog preview because no enabled add-on returned full metadata.</string>
+ <string name="stremio_item_metadata_failed">Metadata from %1$s could not be loaded: %2$s</string>
+ <string name="stremio_item_episodes">Episodes</string>
+ <string name="stremio_item_no_episode_ids">Episode streams are unavailable until metadata supplies an exact video ID.</string>
+ <string name="stremio_item_find_streams">Find streams</string>
+ <string name="stremio_item_streams">Streams</string>
+ <string name="stremio_item_streams_for">Streams for %1$s</string>
+ <string name="stremio_item_no_stream_addons">No enabled add-on supports streams for this item ID.</string>
+ <string name="stremio_item_no_streams">No streams were found.</string>
+ <string name="stremio_item_stream_failed">%1$s: %2$s</string>
+ <string name="stremio_item_play">Play</string>
+ <string name="stremio_item_torrent_unavailable">Magnet playback requires the StreamVault Torrent plugin.</string>
+ <string name="stremio_item_torrent_invalid">This torrent stream has no valid info hash or magnet link.</string>
+ <string name="stremio_item_torrent_plugin_hint">Magnet links are resolved by an installed StreamVault plugin that supports magnet playback.</string>
+ <string name="stremio_item_unsupported_stream">Unsupported stream format</string>
+ <string name="stremio_item_external_unavailable">This stream type is not supported yet</string>
+ <string name="stremio_item_headers_unavailable">This stream has invalid or unsupported add-on request headers.</string>
+ <string name="extensions_title">Extensions</string>
+ <string name="stremio_section_description">Browse catalogs and play streams from Stremio-compatible add-ons.</string>
+ <string name="stremio_empty_title">Add your first Stremio-compatible add-on</string>
+ <string name="stremio_empty_description">Add a manifest URL to get started. Catalog add-ons provide titles to browse; playback needs an add-on that provides streams.</string>
+ <string name="stremio_hidden_title">Stremio-compatible add-ons are hidden</string>
+ <string name="stremio_open_settings">Open settings</string>
+ <string name="stremio_hidden_message">To show your add-ons, open Settings → Privacy and turn off Hide Stremio-compatible add-ons. Your installed add-ons are kept.</string>
</resources>
diff --git a/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/AddonsViewModelTest.kt b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/AddonsViewModelTest.kt
index 2422e6bd..2813bb76 100644
--- a/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/AddonsViewModelTest.kt
+++ b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/AddonsViewModelTest.kt
@@ -3,12 +3,20 @@ package com.streamvault.feature.stremio.presentation
import com.google.common.truth.Truth.assertThat
import com.streamvault.domain.model.Result
import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioCatalogPage
+import com.streamvault.domain.model.stremio.StremioCatalogQuery
import com.streamvault.domain.model.stremio.StremioCatalogRef
import com.streamvault.domain.model.stremio.StremioManifest
import com.streamvault.domain.model.stremio.StremioManifestResource
import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaResolution
+import com.streamvault.domain.model.stremio.StremioPlaybackHistory
+import com.streamvault.domain.model.stremio.StremioResourceResolution
import com.streamvault.domain.model.stremio.StremioResourceKind
+import com.streamvault.domain.model.stremio.StremioStream
+import com.streamvault.domain.model.stremio.StremioSubtitle
import com.streamvault.domain.repository.StremioAddonRepository
+import com.streamvault.domain.repository.StremioPlaybackHistoryRepository
import com.streamvault.feature.stremio.R
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.ExperimentalCoroutinesApi
@@ -44,7 +52,7 @@ class AddonsViewModelTest {
repository.addons.value = listOf(addon(id = 1L, name = "Cinemeta"))
repository.manifests[1L] = manifestWithOneCatalog()
- val viewModel = AddonsViewModel(repository)
+ val viewModel = createViewModel(repository)
advanceUntilIdle()
val state = viewModel.state.value
@@ -58,7 +66,7 @@ class AddonsViewModelTest {
fun `install success closes the dialog and reports status`() = runTest(dispatcher) {
val repository = FakeStremioAddonRepository()
repository.installResult = Result.success(addon(id = 5L, name = "New Addon"))
- val viewModel = AddonsViewModel(repository)
+ val viewModel = createViewModel(repository)
advanceUntilIdle()
viewModel.showInstallDialog()
@@ -74,11 +82,29 @@ class AddonsViewModelTest {
assertThat(state.errorMessage).isNull()
}
+ @Test
+ fun `hidden Stremio addons cannot be installed`() = runTest(dispatcher) {
+ val repository = FakeStremioAddonRepository()
+ val access = FakeStremioContentAccess(
+ StremioVisibilityState(hidden = true)
+ )
+ val viewModel = createViewModel(repository, access)
+ advanceUntilIdle()
+
+ viewModel.showInstallDialog()
+ viewModel.updateInstallUrl("https://example.test/manifest.json")
+ viewModel.install()
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.installDialogVisible).isFalse()
+ assertThat(repository.installCalls).isEmpty()
+ }
+
@Test
fun `install failure keeps the dialog and shows the error`() = runTest(dispatcher) {
val repository = FakeStremioAddonRepository()
repository.installResult = Result.error("Addon request failed with HTTP 500")
- val viewModel = AddonsViewModel(repository)
+ val viewModel = createViewModel(repository)
advanceUntilIdle()
viewModel.showInstallDialog()
@@ -95,7 +121,7 @@ class AddonsViewModelTest {
@Test
fun `blank install urls are ignored`() = runTest(dispatcher) {
val repository = FakeStremioAddonRepository()
- val viewModel = AddonsViewModel(repository)
+ val viewModel = createViewModel(repository)
advanceUntilIdle()
viewModel.showInstallDialog()
@@ -111,7 +137,7 @@ class AddonsViewModelTest {
fun `remove collapses the expanded card and reports status`() = runTest(dispatcher) {
val repository = FakeStremioAddonRepository()
repository.addons.value = listOf(addon(id = 3L, name = "Cinemeta"))
- val viewModel = AddonsViewModel(repository)
+ val viewModel = createViewModel(repository)
advanceUntilIdle()
viewModel.toggleExpanded(3L)
@@ -128,7 +154,7 @@ class AddonsViewModelTest {
fun `enabled move and catalog toggles reach the repository`() = runTest(dispatcher) {
val repository = FakeStremioAddonRepository()
repository.addons.value = listOf(addon(id = 7L, name = "Cinemeta"))
- val viewModel = AddonsViewModel(repository)
+ val viewModel = createViewModel(repository)
advanceUntilIdle()
val entry = viewModel.state.value.addons.single()
@@ -162,6 +188,22 @@ class AddonsViewModelTest {
)
}
+private fun createViewModel(
+ repository: StremioAddonRepository,
+ contentAccess: StremioContentAccess = FakeStremioContentAccess()
+) = AddonsViewModel(repository, FakeStremioPlaybackHistoryRepository(), contentAccess)
+
+private class FakeStremioPlaybackHistoryRepository : StremioPlaybackHistoryRepository {
+ override fun observeContinueWatching(limit: Int): Flow<List<StremioPlaybackHistory>> =
+ MutableStateFlow(emptyList())
+
+ override suspend fun get(contentKey: String): StremioPlaybackHistory? = null
+
+ override suspend fun save(history: StremioPlaybackHistory): Result<Unit> = Result.success(Unit)
+
+ override suspend fun delete(contentKey: String): Result<Unit> = Result.success(Unit)
+}
+
private class FakeStremioAddonRepository : StremioAddonRepository {
val addons = MutableStateFlow<List<StremioAddon>>(emptyList())
val manifests = mutableMapOf<Long, StremioManifest>()
@@ -179,6 +221,33 @@ private class FakeStremioAddonRepository : StremioAddonRepository {
override suspend fun getManifest(addonId: Long): StremioManifest? = manifests[addonId]
+ override suspend fun fetchCatalog(
+ addonId: Long,
+ catalog: StremioCatalogRef,
+ query: StremioCatalogQuery
+ ): Result<StremioCatalogPage> = Result.success(StremioCatalogPage(emptyList()))
+
+ override suspend fun resolveMeta(
+ catalogOriginAddonId: Long,
+ type: StremioMediaType,
+ exactId: String
+ ): StremioMetaResolution = StremioMetaResolution()
+
+ override suspend fun resolveStreams(
+ type: StremioMediaType,
+ exactId: String,
+ addonIds: Set<Long>?
+ ): StremioResourceResolution<StremioStream> = StremioResourceResolution()
+
+ override suspend fun resolveSubtitles(
+ type: StremioMediaType,
+ exactVideoId: String,
+ videoHash: String?,
+ videoSize: Long?,
+ filename: String?,
+ addonIds: Set<Long>?
+ ): StremioResourceResolution<StremioSubtitle> = StremioResourceResolution()
+
override suspend fun installAddon(installUrl: String): Result<StremioAddon> {
installCalls += installUrl
return installResult
diff --git a/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/FakeStremioContentAccess.kt b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/FakeStremioContentAccess.kt
new file mode 100644
index 00000000..d6d5a67d
--- /dev/null
+++ b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/FakeStremioContentAccess.kt
@@ -0,0 +1,17 @@
+package com.streamvault.feature.stremio.presentation
+
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.StateFlow
+
+internal class FakeStremioContentAccess(
+ initialState: StremioVisibilityState = StremioVisibilityState(
+ hidden = false
+ )
+) : StremioContentAccess {
+ private val mutableState = MutableStateFlow(initialState)
+ override val state: StateFlow<StremioVisibilityState> = mutableState
+
+ fun setState(state: StremioVisibilityState) {
+ mutableState.value = state
+ }
+}
diff --git a/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioAddonOriginLabelTest.kt b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioAddonOriginLabelTest.kt
new file mode 100644
index 00000000..97408515
--- /dev/null
+++ b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioAddonOriginLabelTest.kt
@@ -0,0 +1,30 @@
+package com.streamvault.feature.stremio.presentation
+
+import org.junit.Assert.assertEquals
+import org.junit.Test
+
+class StremioAddonOriginLabelTest {
+ @Test
+ fun `omits configured path query fragment and user info`() {
+ val label = stremioAddonOriginLabel(
+ "https://user:[email protected]:8443/config/private-token/manifest.json?key=query-secret#fragment-secret"
+ )
+
+ assertEquals("https://example.com:8443", label)
+ }
+
+ @Test
+ fun `omits default port`() {
+ assertEquals("https://example.com", stremioAddonOriginLabel("https://example.com:443/path/manifest.json"))
+ }
+
+ @Test
+ fun `brackets ipv6 hosts`() {
+ assertEquals("http://[2001:db8::1]:8080", stremioAddonOriginLabel("http://[2001:db8::1]:8080/a/manifest.json"))
+ }
+
+ @Test
+ fun `returns null for malformed endpoint`() {
+ assertEquals(null, stremioAddonOriginLabel("not a URL with secrets"))
+ }
+}
diff --git a/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseViewModelTest.kt b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseViewModelTest.kt
new file mode 100644
index 00000000..52099e79
--- /dev/null
+++ b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioCatalogBrowseViewModelTest.kt
@@ -0,0 +1,313 @@
+package com.streamvault.feature.stremio.presentation
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioCatalogExtraDef
+import com.streamvault.domain.model.stremio.StremioCatalogPage
+import com.streamvault.domain.model.stremio.StremioCatalogQuery
+import com.streamvault.domain.model.stremio.StremioCatalogRef
+import com.streamvault.domain.model.stremio.StremioManifest
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaPreview
+import com.streamvault.domain.model.stremio.StremioMetaResolution
+import com.streamvault.domain.model.stremio.StremioResourceResolution
+import com.streamvault.domain.model.stremio.StremioStream
+import com.streamvault.domain.model.stremio.StremioSubtitle
+import com.streamvault.domain.repository.StremioAddonRepository
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.advanceTimeBy
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.runTest
+import kotlinx.coroutines.test.setMain
+import org.junit.After
+import org.junit.Before
+import org.junit.Test
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class StremioCatalogBrowseViewModelTest {
+ private val dispatcher = StandardTestDispatcher()
+
+ @Before
+ fun setUp() {
+ Dispatchers.setMain(dispatcher)
+ }
+
+ @After
+ fun tearDown() {
+ Dispatchers.resetMain()
+ }
+
+ @Test
+ fun `full page without hasMore loads next page using raw offset`() = runTest(dispatcher) {
+ val repository = CatalogRepositoryFake(catalogWithSkip())
+ repository.pages += StremioCatalogPage((0 until 100).map { preview("tt$it") }, rawItemCount = 100)
+ repository.pages += StremioCatalogPage(
+ metas = listOf(preview("tt0"), preview("tt100")),
+ rawItemCount = 7
+ )
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+
+ val rowKey = viewModel.state.value.rows.single().key
+ assertThat(viewModel.state.value.rows.single().nextSkip).isEqualTo(100)
+ assertThat(viewModel.state.value.rows.single().canLoadMore).isTrue()
+
+ viewModel.loadMore(rowKey)
+ advanceUntilIdle()
+
+ val row = viewModel.state.value.rows.single()
+ assertThat(repository.calls.map { it.query.skip }).containsExactly(0, 100).inOrder()
+ assertThat(row.nextSkip).isEqualTo(107)
+ assertThat(row.metas).hasSize(101)
+ assertThat(row.canLoadMore).isFalse()
+ }
+
+ @Test
+ fun `short page without hasMore stops pagination`() = runTest(dispatcher) {
+ val repository = CatalogRepositoryFake(catalogWithSkip())
+ repository.pages += StremioCatalogPage(listOf(preview("tt1")), rawItemCount = 99)
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+
+ val row = viewModel.state.value.rows.single()
+ assertThat(row.canLoadMore).isFalse()
+ assertThat(row.nextSkip).isEqualTo(99)
+ }
+
+ @Test
+ fun `required search catalog waits until query exists`() = runTest(dispatcher) {
+ val catalog = catalogWithSkip(
+ extras = listOf(
+ StremioCatalogExtraDef("search", isRequired = true),
+ StremioCatalogExtraDef("skip")
+ )
+ )
+ val repository = CatalogRepositoryFake(catalog)
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+
+ val row = viewModel.state.value.rows.single()
+ assertThat(repository.calls).isEmpty()
+ assertThat(row.waitingForInput).isNotNull()
+
+ viewModel.setSearch(row.key, " galaxy ")
+ advanceTimeBy(350)
+ advanceUntilIdle()
+
+ assertThat(repository.calls).hasSize(1)
+ assertThat(repository.calls.single().query.search).isEqualTo("galaxy")
+ assertThat(repository.calls.single().query.skip).isEqualTo(0)
+ }
+
+ @Test
+ fun `repeated page response stops further pagination`() = runTest(dispatcher) {
+ val repository = CatalogRepositoryFake(catalogWithSkip())
+ val samePage = StremioCatalogPage(listOf(preview("tt1")), hasMore = true, rawItemCount = 1)
+ repository.pages += samePage
+ repository.pages += samePage
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+ val key = viewModel.state.value.rows.single().key
+
+ viewModel.loadMore(key)
+ advanceUntilIdle()
+
+ val row = viewModel.state.value.rows.single()
+ assertThat(row.canLoadMore).isFalse()
+ assertThat(row.error).contains("repeated a page")
+ }
+
+ @Test
+ fun `manifest refresh discards cached rows and reloads the catalog`() = runTest(dispatcher) {
+ val repository = CatalogRepositoryFake(catalogWithSkip())
+ repository.pages += StremioCatalogPage(listOf(preview("before-refresh")), rawItemCount = 1)
+ repository.pages += StremioCatalogPage(listOf(preview("after-refresh")), rawItemCount = 1)
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+
+ repository.addons.value = repository.addons.value.map { it.copy(manifestJson = "{\"version\":2}") }
+ advanceUntilIdle()
+
+ assertThat(repository.calls).hasSize(2)
+ assertThat(viewModel.state.value.rows.single().metas.map { it.id })
+ .containsExactly("after-refresh")
+ }
+
+ @Test
+ fun `changing search cancels the stale catalog request`() = runTest(dispatcher) {
+ val catalog = catalogWithSkip(
+ extras = listOf(StremioCatalogExtraDef("search"), StremioCatalogExtraDef("skip"))
+ )
+ val repository = CatalogRepositoryFake(catalog)
+ val staleRequestCancelled = CompletableDeferred<Unit>()
+ repository.fetchResponder = { call ->
+ if (call.query.search == null) {
+ try {
+ awaitCancellation()
+ } finally {
+ staleRequestCancelled.complete(Unit)
+ }
+ } else {
+ Result.success(StremioCatalogPage(listOf(preview("fresh-result")), rawItemCount = 1))
+ }
+ }
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ runCurrent()
+ val rowKey = viewModel.state.value.rows.single().key
+
+ viewModel.setSearch(rowKey, "Matrix")
+ advanceTimeBy(350)
+ runCurrent()
+
+ assertThat(staleRequestCancelled.isCompleted).isTrue()
+ assertThat(repository.calls.map { it.query.search }).containsExactly(null, "Matrix").inOrder()
+ assertThat(viewModel.state.value.rows.single().metas.map { it.id }).containsExactly("fresh-result")
+ }
+
+ @Test
+ fun `disabled addons and catalogs are excluded from browse rows`() = runTest(dispatcher) {
+ val repository = CatalogRepositoryFake(catalogWithSkip())
+ repository.addons.value = listOf(
+ addon(id = 1L, enabled = true),
+ addon(id = 2L, enabled = false),
+ addon(id = 3L, enabled = true, catalogEnabled = false)
+ )
+ repository.manifests[1L] = manifest(catalogWithSkip())
+ repository.manifests[2L] = manifest(catalogWithSkip())
+ repository.manifests[3L] = manifest(catalogWithSkip())
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.rows.map { it.key.addonId }).containsExactly(1L)
+ assertThat(repository.calls.map { it.addonId }).containsExactly(1L)
+ }
+
+ @Test
+ fun `hidden Stremio does not fetch addon catalog pages`() = runTest(dispatcher) {
+ val repository = CatalogRepositoryFake(catalogWithSkip())
+ val access = FakeStremioContentAccess(
+ StremioVisibilityState(hidden = true)
+ )
+ val viewModel = StremioCatalogBrowseViewModel(repository, access)
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.rows).hasSize(1)
+ assertThat(repository.calls).isEmpty()
+ }
+
+ private fun catalogWithSkip(
+ extras: List<StremioCatalogExtraDef> = listOf(StremioCatalogExtraDef("skip"))
+ ) = StremioCatalogRef(
+ type = StremioMediaType.MOVIE,
+ id = "top",
+ name = "Popular",
+ extras = extras
+ )
+
+ private fun manifest(catalog: StremioCatalogRef) = StremioManifest(
+ id = "test.addon",
+ name = "Test",
+ version = "1",
+ types = listOf(StremioMediaType.MOVIE),
+ catalogs = listOf(catalog)
+ )
+
+ private fun addon(
+ id: Long,
+ enabled: Boolean,
+ catalogEnabled: Boolean = true
+ ) = StremioAddon(
+ id = id,
+ installUrl = "https://example.test/$id/manifest.json",
+ manifestId = "test.$id",
+ name = "Addon $id",
+ version = "1",
+ enabled = enabled,
+ catalogSettings = mapOf("movie:top" to catalogEnabled)
+ )
+
+ private fun preview(id: String) = StremioMetaPreview(
+ id = id,
+ type = StremioMediaType.MOVIE,
+ name = id
+ )
+}
+
+private class CatalogRepositoryFake(catalog: StremioCatalogRef) : StremioAddonRepository {
+ data class FetchCall(val addonId: Long, val query: StremioCatalogQuery)
+
+ val addons = MutableStateFlow(listOf(addon(id = 1L, enabled = true)))
+ val manifests = mutableMapOf(1L to manifest(catalog))
+ val calls = mutableListOf<FetchCall>()
+ val pages = ArrayDeque<StremioCatalogPage>()
+ var fetchResponder: (suspend (FetchCall) -> Result<StremioCatalogPage>)? = null
+
+ override fun observeAddons(): Flow<List<StremioAddon>> = addons
+ override suspend fun getAddon(id: Long): StremioAddon? = addons.value.firstOrNull { it.id == id }
+ override suspend fun getManifest(addonId: Long): StremioManifest? = manifests[addonId]
+ override suspend fun fetchCatalog(
+ addonId: Long,
+ catalog: StremioCatalogRef,
+ query: StremioCatalogQuery
+ ): Result<StremioCatalogPage> {
+ val call = FetchCall(addonId, query)
+ calls += call
+ fetchResponder?.let { responder -> return responder(call) }
+ return Result.success(pages.removeFirstOrNull() ?: StremioCatalogPage(emptyList()))
+ }
+ override suspend fun resolveMeta(
+ catalogOriginAddonId: Long,
+ type: StremioMediaType,
+ exactId: String
+ ): StremioMetaResolution = StremioMetaResolution()
+ override suspend fun resolveStreams(
+ type: StremioMediaType,
+ exactId: String,
+ addonIds: Set<Long>?
+ ): StremioResourceResolution<StremioStream> = StremioResourceResolution()
+ override suspend fun resolveSubtitles(
+ type: StremioMediaType,
+ exactVideoId: String,
+ videoHash: String?,
+ videoSize: Long?,
+ filename: String?,
+ addonIds: Set<Long>?
+ ): StremioResourceResolution<StremioSubtitle> = StremioResourceResolution()
+ override suspend fun installAddon(installUrl: String): Result<StremioAddon> = Result.error("unused")
+ override suspend fun removeAddon(id: Long): Result<Unit> = Result.success(Unit)
+ override suspend fun setAddonEnabled(id: Long, enabled: Boolean): Result<Unit> = Result.success(Unit)
+ override suspend fun moveAddon(id: Long, offset: Int): Result<Unit> = Result.success(Unit)
+ override suspend fun setCatalogEnabled(addonId: Long, catalogKey: String, enabled: Boolean): Result<Unit> =
+ Result.success(Unit)
+}
+
+private fun addon(
+ id: Long,
+ enabled: Boolean,
+ catalogEnabled: Boolean = true
+) = StremioAddon(
+ id = id,
+ installUrl = "https://example.test/$id/manifest.json",
+ manifestId = "test.$id",
+ name = "Addon $id",
+ version = "1",
+ enabled = enabled,
+ catalogSettings = mapOf("movie:top" to catalogEnabled)
+)
+
+private fun manifest(catalog: StremioCatalogRef) = StremioManifest(
+ id = "test.addon",
+ name = "Test",
+ version = "1",
+ types = listOf(StremioMediaType.MOVIE),
+ catalogs = listOf(catalog)
+)
diff --git a/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioContentAccessTest.kt b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioContentAccessTest.kt
new file mode 100644
index 00000000..b346891c
--- /dev/null
+++ b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioContentAccessTest.kt
@@ -0,0 +1,46 @@
+package com.streamvault.feature.stremio.presentation
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.settings.SettingsPreferences
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.flow.first
+import kotlinx.coroutines.runBlocking
+import kotlinx.coroutines.withTimeout
+import org.junit.Test
+import org.mockito.kotlin.mock
+import org.mockito.kotlin.whenever
+
+class StremioContentAccessTest {
+ @Test
+ fun `waits for visibility preference before fetching content`() {
+ assertThat(StremioVisibilityState().canAccessContent).isFalse()
+ }
+
+ @Test
+ fun `global parental levels do not block visible Stremio addons`() = runBlocking {
+ for (level in 0..3) {
+ val preferences = mock<SettingsPreferences>()
+ whenever(preferences.parentalControlLevel).thenReturn(MutableStateFlow(level))
+ whenever(preferences.hideStremioAddons).thenReturn(MutableStateFlow(false))
+ val manager = StremioVisibilityManager(preferences)
+ val visible = withTimeout(2_000) { manager.state.first { it.hidden == false } }
+ assertThat(visible.canAccessContent).isTrue()
+ assertThat(visible.showContinueWatching).isTrue()
+ }
+ }
+
+ @Test
+ fun `explicit hide choice blocks content and history and can be reversed`() = runBlocking {
+ val hidden = MutableStateFlow(false)
+ val preferences = mock<SettingsPreferences>()
+ whenever(preferences.hideStremioAddons).thenReturn(hidden)
+ val manager = StremioVisibilityManager(preferences)
+ withTimeout(2_000) { manager.state.first { it.canAccessContent } }
+ hidden.value = true
+ val blocked = withTimeout(2_000) { manager.state.first { it.hidden == true } }
+ assertThat(blocked.canAccessContent).isFalse()
+ assertThat(blocked.showContinueWatching).isFalse()
+ hidden.value = false
+ assertThat(withTimeout(2_000) { manager.state.first { it.canAccessContent } }.showContinueWatching).isTrue()
+ }
+}
diff --git a/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioItemDetailViewModelTest.kt b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioItemDetailViewModelTest.kt
new file mode 100644
index 00000000..25c51a62
--- /dev/null
+++ b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioItemDetailViewModelTest.kt
@@ -0,0 +1,360 @@
+package com.streamvault.feature.stremio.presentation
+
+import androidx.lifecycle.SavedStateHandle
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.domain.model.Result
+import com.streamvault.domain.model.stremio.StremioAddon
+import com.streamvault.domain.model.stremio.StremioAddonSource
+import com.streamvault.domain.model.stremio.StremioAttributedResource
+import com.streamvault.domain.model.stremio.StremioCatalogPage
+import com.streamvault.domain.model.stremio.StremioCatalogQuery
+import com.streamvault.domain.model.stremio.StremioCatalogRef
+import com.streamvault.domain.model.stremio.StremioManifest
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaDetail
+import com.streamvault.domain.model.stremio.StremioMetaResolution
+import com.streamvault.domain.model.stremio.StremioResourceResolution
+import com.streamvault.domain.model.stremio.StremioStream
+import com.streamvault.domain.model.stremio.StremioSubtitle
+import com.streamvault.domain.model.stremio.StremioVideo
+import com.streamvault.domain.model.stremio.installFingerprint
+import com.streamvault.domain.repository.StremioAddonRepository
+import kotlinx.coroutines.CompletableDeferred
+import kotlinx.coroutines.Dispatchers
+import kotlinx.coroutines.ExperimentalCoroutinesApi
+import kotlinx.coroutines.awaitCancellation
+import kotlinx.coroutines.flow.Flow
+import kotlinx.coroutines.flow.MutableStateFlow
+import kotlinx.coroutines.test.StandardTestDispatcher
+import kotlinx.coroutines.test.advanceUntilIdle
+import kotlinx.coroutines.test.resetMain
+import kotlinx.coroutines.test.runCurrent
+import kotlinx.coroutines.test.runTest
+import kotlinx.coroutines.test.setMain
+import org.junit.After
+import org.junit.Before
+import org.junit.Test
+
+@OptIn(ExperimentalCoroutinesApi::class)
+class StremioItemDetailViewModelTest {
+ private val dispatcher = StandardTestDispatcher()
+
+ private data class StreamCall(val exactId: String, val addonIds: Set<Long>?)
+
+ @Before
+ fun setUp() {
+ Dispatchers.setMain(dispatcher)
+ }
+
+ @After
+ fun tearDown() {
+ Dispatchers.resetMain()
+ }
+
+ @Test
+ fun `episode stream lookup uses exact video id and preserves catalog provenance`() = runTest(dispatcher) {
+ val exactVideoId = "series:custom-id:season 02/episode 04"
+ val addon = addon(11L)
+ val repository = ItemRepositoryFake(addon).apply {
+ meta = StremioMetaDetail(
+ id = "series:custom-id",
+ type = StremioMediaType.SERIES,
+ name = "Series",
+ videos = listOf(StremioVideo(exactVideoId, title = "Episode 4", season = 2, episode = 4))
+ )
+ }
+ val viewModel = viewModel(repository, "series", "series:custom-id")
+ advanceUntilIdle()
+ val episode = viewModel.state.value.videos.single()
+
+ viewModel.loadStreams(episode.id)
+ advanceUntilIdle()
+
+ assertThat(repository.streamCalls.single().exactId).isEqualTo(exactVideoId)
+ assertThat(viewModel.state.value.requestedVideoId).isEqualTo(exactVideoId)
+ assertThat(viewModel.state.value.selectedVideo?.id).isEqualTo(exactVideoId)
+ assertThat(viewModel.state.value.catalogOriginKey).isEqualTo(addon.installFingerprint())
+ assertThat(viewModel.state.value.streams.single().source.addonId).isEqualTo(21L)
+ }
+
+ @Test
+ fun `history replay resolves fresh streams for the saved exact episode id`() = runTest(dispatcher) {
+ val exactVideoId = "tt12345:1:2"
+ val addon = addon(11L)
+ val repository = ItemRepositoryFake(addon).apply {
+ meta = StremioMetaDetail(
+ id = "tt12345",
+ type = StremioMediaType.SERIES,
+ name = "Series",
+ videos = listOf(StremioVideo(exactVideoId, title = "Episode 2"))
+ )
+ }
+ val replayOriginKey = addon.installFingerprint()
+ val viewModel = StremioItemDetailViewModel(
+ savedStateHandle = SavedStateHandle(
+ mapOf(
+ StremioItemDetailViewModel.ARG_ORIGIN_ADDON_ID to addon.id,
+ StremioItemDetailViewModel.ARG_TYPE to "series",
+ StremioItemDetailViewModel.ARG_EXACT_ID to "tt12345",
+ StremioItemDetailViewModel.ARG_NAME to "Series",
+ StremioItemDetailViewModel.ARG_REPLAY_VIDEO_ID to exactVideoId,
+ StremioItemDetailViewModel.ARG_REPLAY_ORIGIN_KEY to replayOriginKey,
+ StremioItemDetailViewModel.ARG_REPLAY_REQUIRES_ORIGIN to true
+ )
+ ),
+ repository = repository,
+ contentAccess = FakeStremioContentAccess()
+ )
+ advanceUntilIdle()
+
+ assertThat(repository.metaCalls).containsExactly(addon.id to "tt12345")
+ assertThat(repository.streamCalls.single().exactId).isEqualTo(exactVideoId)
+ assertThat(viewModel.state.value.catalogOriginKey).isEqualTo(replayOriginKey)
+ assertThat(viewModel.state.value.requestedVideoId).isEqualTo(exactVideoId)
+ }
+
+ @Test
+ fun `custom history replay stays unavailable when its origin addon is missing`() = runTest(dispatcher) {
+ val repository = ItemRepositoryFake(addon(11L))
+ val viewModel = StremioItemDetailViewModel(
+ savedStateHandle = SavedStateHandle(
+ mapOf(
+ StremioItemDetailViewModel.ARG_ORIGIN_ADDON_ID to 0L,
+ StremioItemDetailViewModel.ARG_TYPE to "movie",
+ StremioItemDetailViewModel.ARG_EXACT_ID to "vendor:item:7",
+ StremioItemDetailViewModel.ARG_NAME to "Custom item",
+ StremioItemDetailViewModel.ARG_REPLAY_VIDEO_ID to "vendor:item:7",
+ StremioItemDetailViewModel.ARG_REPLAY_ORIGIN_KEY to "a".repeat(64),
+ StremioItemDetailViewModel.ARG_REPLAY_REQUIRES_ORIGIN to true
+ )
+ ),
+ repository = repository,
+ contentAccess = FakeStremioContentAccess()
+ )
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.replayOriginUnavailable).isTrue()
+ assertThat(repository.metaCalls).isEmpty()
+ viewModel.loadStreams("vendor:item:7")
+ advanceUntilIdle()
+ assertThat(repository.streamCalls).isEmpty()
+ }
+
+ @Test
+ fun `retry requests only failed addon and keeps other addon rows`() = runTest(dispatcher) {
+ val repository = ItemRepositoryFake(addon(11L)).apply {
+ streamResponder = { _, addonIds ->
+ if (addonIds == null) {
+ StremioResourceResolution(
+ results = listOf(attributedStream(21L, "old-21")),
+ failures = listOf(failure(22L)),
+ candidateCount = 2
+ )
+ } else {
+ StremioResourceResolution(
+ results = listOf(attributedStream(22L, "new-22")),
+ candidateCount = 1
+ )
+ }
+ }
+ }
+ val viewModel = viewModel(repository, "movie", "tt123")
+ advanceUntilIdle()
+
+ viewModel.loadStreams("tt123")
+ advanceUntilIdle()
+ viewModel.retryStreamsForAddon(22L)
+ advanceUntilIdle()
+
+ assertThat(repository.streamCalls.map { it.addonIds }).containsExactly(null, setOf(22L)).inOrder()
+ assertThat(viewModel.state.value.streams.map { it.resource.title }).containsExactly("old-21", "new-22")
+ .inOrder()
+ assertThat(viewModel.state.value.streamFailures).isEmpty()
+ }
+
+ @Test
+ fun `changing episode cancels prior fanout and only publishes current id`() = runTest(dispatcher) {
+ val firstStarted = CompletableDeferred<Unit>()
+ val repository = ItemRepositoryFake(addon(11L)).apply {
+ meta = StremioMetaDetail(
+ id = "series-id",
+ type = StremioMediaType.SERIES,
+ name = "Series",
+ videos = listOf(StremioVideo("episode-one"), StremioVideo("episode-two"))
+ )
+ streamResponder = { exactId, _ ->
+ if (exactId == "episode-one") {
+ firstStarted.complete(Unit)
+ awaitCancellation()
+ } else {
+ StremioResourceResolution(results = listOf(attributedStream(21L, exactId)))
+ }
+ }
+ }
+ val viewModel = viewModel(repository, "series", "series-id")
+ advanceUntilIdle()
+
+ viewModel.loadStreams("episode-one")
+ runCurrent()
+ firstStarted.await()
+ viewModel.loadStreams("episode-two")
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.requestedVideoId).isEqualTo("episode-two")
+ assertThat(viewModel.state.value.streams.single().resource.title).isEqualTo("episode-two")
+ }
+
+ @Test
+ fun `catalog preview remains usable when no metadata addon succeeds`() = runTest(dispatcher) {
+ val repository = ItemRepositoryFake(addon(11L)).apply {
+ metaResolution = StremioMetaResolution(candidateCount = 0)
+ }
+ val viewModel = viewModel(repository, "movie", "tt123", name = "Catalog Preview")
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.metadata).isNull()
+ assertThat(viewModel.state.value.preview.name).isEqualTo("Catalog Preview")
+ assertThat(viewModel.state.value.metadataLoading).isFalse()
+ assertThat(repository.metaCalls.single()).isEqualTo(11L to "tt123")
+ }
+
+ @Test
+ fun `series without exact episode ids cannot request parent streams`() = runTest(dispatcher) {
+ val repository = ItemRepositoryFake(addon(11L)).apply {
+ meta = StremioMetaDetail(
+ id = "series-custom",
+ type = StremioMediaType.SERIES,
+ name = "Series without videos"
+ )
+ }
+ val viewModel = viewModel(repository, "series", "series-custom")
+ advanceUntilIdle()
+
+ viewModel.loadStreams("series-custom")
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.videos).isEmpty()
+ assertThat(viewModel.state.value.requestedVideoId).isNull()
+ assertThat(repository.streamCalls).isEmpty()
+ }
+
+ @Test
+ fun `hidden Stremio blocks metadata and stream resolution`() = runTest(dispatcher) {
+ val repository = ItemRepositoryFake(addon(11L))
+ val access = FakeStremioContentAccess(
+ StremioVisibilityState(hidden = true)
+ )
+ val viewModel = viewModel(repository, "movie", "tt123", contentAccess = access)
+ advanceUntilIdle()
+
+ viewModel.loadStreams("tt123")
+ advanceUntilIdle()
+
+ assertThat(repository.metaCalls).isEmpty()
+ assertThat(repository.streamCalls).isEmpty()
+ assertThat(viewModel.state.value.metadataLoading).isFalse()
+ }
+
+ private fun viewModel(
+ repository: ItemRepositoryFake,
+ type: String,
+ exactId: String,
+ name: String = "Preview",
+ contentAccess: StremioContentAccess = FakeStremioContentAccess()
+ ) = StremioItemDetailViewModel(
+ savedStateHandle = SavedStateHandle(
+ mapOf(
+ StremioItemDetailViewModel.ARG_ORIGIN_ADDON_ID to 11L,
+ StremioItemDetailViewModel.ARG_TYPE to type,
+ StremioItemDetailViewModel.ARG_EXACT_ID to exactId,
+ StremioItemDetailViewModel.ARG_NAME to name,
+ StremioItemDetailViewModel.ARG_POSTER to "https://images.example/poster.jpg"
+ )
+ ),
+ repository = repository,
+ contentAccess = contentAccess
+ )
+
+ private fun addon(id: Long) = StremioAddon(
+ id = id,
+ installUrl = "https://example.test/$id/manifest.json",
+ manifestId = "addon.$id",
+ name = "Addon $id",
+ version = "1"
+ )
+
+ private fun source(id: Long) = StremioAddonSource(
+ addonId = id,
+ addonName = "Addon $id",
+ manifestId = "addon.$id",
+ installFingerprint = "fingerprint-$id"
+ )
+
+ private fun attributedStream(id: Long, title: String) = StremioAttributedResource(
+ source = source(id),
+ resource = StremioStream(title = title, url = "https://media.example/$title.mp4")
+ )
+
+ private fun failure(id: Long) = com.streamvault.domain.model.stremio.StremioAddonResourceFailure(
+ source(id),
+ "offline"
+ )
+
+ private inner class ItemRepositoryFake(private val addon: StremioAddon) : StremioAddonRepository {
+ val addons = MutableStateFlow(listOf(addon))
+ val metaCalls = mutableListOf<Pair<Long, String>>()
+ val streamCalls = mutableListOf<StreamCall>()
+ var meta: StremioMetaDetail? = StremioMetaDetail(
+ id = "tt123",
+ type = StremioMediaType.MOVIE,
+ name = "Resolved"
+ )
+ var metaResolution: StremioMetaResolution? = null
+ var streamResponder: suspend (String, Set<Long>?) -> StremioResourceResolution<StremioStream> =
+ { exactId, _ -> StremioResourceResolution(results = listOf(attributedStream(21L, exactId))) }
+
+ override fun observeAddons(): Flow<List<StremioAddon>> = addons
+ override suspend fun getAddon(id: Long): StremioAddon? = addon.takeIf { it.id == id }
+ override suspend fun getManifest(addonId: Long): StremioManifest? = null
+ override suspend fun fetchCatalog(
+ addonId: Long,
+ catalog: StremioCatalogRef,
+ query: StremioCatalogQuery
+ ): Result<StremioCatalogPage> = Result.success(StremioCatalogPage(emptyList()))
+ override suspend fun resolveMeta(
+ catalogOriginAddonId: Long,
+ type: StremioMediaType,
+ exactId: String
+ ): StremioMetaResolution {
+ metaCalls += catalogOriginAddonId to exactId
+ return metaResolution ?: meta?.let {
+ StremioMetaResolution(
+ result = StremioAttributedResource(source(31L), it),
+ candidateCount = 1
+ )
+ } ?: StremioMetaResolution()
+ }
+ override suspend fun resolveStreams(
+ type: StremioMediaType,
+ exactId: String,
+ addonIds: Set<Long>?
+ ): StremioResourceResolution<StremioStream> {
+ streamCalls += StreamCall(exactId, addonIds)
+ return streamResponder(exactId, addonIds)
+ }
+ override suspend fun resolveSubtitles(
+ type: StremioMediaType,
+ exactVideoId: String,
+ videoHash: String?,
+ videoSize: Long?,
+ filename: String?,
+ addonIds: Set<Long>?
+ ): StremioResourceResolution<StremioSubtitle> = StremioResourceResolution()
+ override suspend fun installAddon(installUrl: String): Result<StremioAddon> = Result.error("unused")
+ override suspend fun removeAddon(id: Long): Result<Unit> = Result.success(Unit)
+ override suspend fun setAddonEnabled(id: Long, enabled: Boolean): Result<Unit> = Result.success(Unit)
+ override suspend fun moveAddon(id: Long, offset: Int): Result<Unit> = Result.success(Unit)
+ override suspend fun setCatalogEnabled(addonId: Long, catalogKey: String, enabled: Boolean): Result<Unit> =
+ Result.success(Unit)
+ }
+}
diff --git a/feature/system/src/androidTest/assets/ui-goldens/plugins_configuration.png b/feature/system/src/androidTest/assets/ui-goldens/plugins_configuration.png
index c36bec7e..43824dd0 100644
Binary files a/feature/system/src/androidTest/assets/ui-goldens/plugins_configuration.png and b/feature/system/src/androidTest/assets/ui-goldens/plugins_configuration.png differ
diff --git a/feature/system/src/androidTest/assets/ui-goldens/plugins_empty.png b/feature/system/src/androidTest/assets/ui-goldens/plugins_empty.png
index 56d9ffd6..ae9da77b 100644
Binary files a/feature/system/src/androidTest/assets/ui-goldens/plugins_empty.png and b/feature/system/src/androidTest/assets/ui-goldens/plugins_empty.png differ
diff --git a/feature/system/src/androidTest/java/com/streamvault/feature/system/SystemPresentationVariantTest.kt b/feature/system/src/androidTest/java/com/streamvault/feature/system/SystemPresentationVariantTest.kt
index b3a505b7..d883829d 100644
--- a/feature/system/src/androidTest/java/com/streamvault/feature/system/SystemPresentationVariantTest.kt
+++ b/feature/system/src/androidTest/java/com/streamvault/feature/system/SystemPresentationVariantTest.kt
@@ -123,9 +123,9 @@ class SystemPresentationVariantTest {
}
}
- composeRule.onNodeWithText("No compatible StreamVault plugins are installed.")
+ composeRule.onNodeWithText("No plugins installed")
.assertIsDisplayed()
- composeRule.onNode(hasText("Refresh") and hasClickAction())
+ composeRule.onNode(hasText("Check installed plugins") and hasClickAction())
.assertIsDisplayed()
.assertHasClickAction()
}
diff --git a/feature/system/src/androidTest/java/com/streamvault/feature/system/navigation/SystemRouteGraphBehaviorTest.kt b/feature/system/src/androidTest/java/com/streamvault/feature/system/navigation/SystemRouteGraphBehaviorTest.kt
index 5793992b..2c4e95c5 100644
--- a/feature/system/src/androidTest/java/com/streamvault/feature/system/navigation/SystemRouteGraphBehaviorTest.kt
+++ b/feature/system/src/androidTest/java/com/streamvault/feature/system/navigation/SystemRouteGraphBehaviorTest.kt
@@ -36,6 +36,7 @@ class SystemRouteGraphBehaviorTest {
actions = recordingActions(),
startupReady = true,
onStartupNavigationRequested = {},
+ onTopLevelDestinationRequested = {},
scaffold = testScaffold,
)
}
diff --git a/feature/system/src/androidTest/java/com/streamvault/feature/system/presentation/plugins/PluginsPresentationTest.kt b/feature/system/src/androidTest/java/com/streamvault/feature/system/presentation/plugins/PluginsPresentationTest.kt
index 638305fb..0cb1c648 100644
--- a/feature/system/src/androidTest/java/com/streamvault/feature/system/presentation/plugins/PluginsPresentationTest.kt
+++ b/feature/system/src/androidTest/java/com/streamvault/feature/system/presentation/plugins/PluginsPresentationTest.kt
@@ -51,13 +51,13 @@ class PluginsPresentationTest {
}
}
- composeRule.onNodeWithText("No compatible StreamVault plugins are installed.")
+ composeRule.onNodeWithText("No plugins installed")
.assertIsDisplayed()
- composeRule.onNode(hasText("Install URL") and hasClickAction())
+ composeRule.onNode(hasText("Install plugin from URL") and hasClickAction())
.performSemanticsAction(SemanticsActions.OnClick)
- composeRule.onNode(hasText("Install file") and hasClickAction())
+ composeRule.onNode(hasText("Install plugin APK") and hasClickAction())
.performSemanticsAction(SemanticsActions.OnClick)
- composeRule.onNode(hasText("Refresh") and hasClickAction())
+ composeRule.onNode(hasText("Check installed plugins") and hasClickAction())
.performSemanticsAction(SemanticsActions.OnClick)
assertThat(installUrlClicks).isEqualTo(1)
diff --git a/feature/system/src/main/java/com/streamvault/feature/system/api/StreamVaultPluginContract.kt b/feature/system/src/main/java/com/streamvault/feature/system/api/StreamVaultPluginContract.kt
index 8e23e52c..822e5aec 100644
--- a/feature/system/src/main/java/com/streamvault/feature/system/api/StreamVaultPluginContract.kt
+++ b/feature/system/src/main/java/com/streamvault/feature/system/api/StreamVaultPluginContract.kt
@@ -25,6 +25,7 @@ object StreamVaultPluginContract {
const val MSG_GET_CONFIGURATION_VALUES = 8
const val MSG_SET_CONFIGURATION_VALUES = 9
const val MSG_RUN_CONFIGURATION_ACTION = 10
+ const val MSG_STOP_PLAYBACK = 11
const val KEY_API_VERSION = "api_version"
const val KEY_REQUEST_ID = "request_id"
diff --git a/feature/system/src/main/java/com/streamvault/feature/system/navigation/SystemGraph.kt b/feature/system/src/main/java/com/streamvault/feature/system/navigation/SystemGraph.kt
index e64a5f0d..a9d797be 100644
--- a/feature/system/src/main/java/com/streamvault/feature/system/navigation/SystemGraph.kt
+++ b/feature/system/src/main/java/com/streamvault/feature/system/navigation/SystemGraph.kt
@@ -15,6 +15,7 @@ fun NavGraphBuilder.registerSystemGraph(
actions: NavigationActions,
startupReady: Boolean,
onStartupNavigationRequested: (AppDestination) -> Unit,
+ onTopLevelDestinationRequested: (AppDestination) -> Unit,
scaffold: SystemScaffoldContent,
) {
composable(SystemRoutePatterns.WELCOME) {
@@ -35,6 +36,9 @@ fun NavGraphBuilder.registerSystemGraph(
DownloadsScreen(scaffold = scaffold)
}
composable(SystemRoutePatterns.PLUGINS) {
- PluginsScreen(scaffold = scaffold)
+ PluginsScreen(
+ scaffold = scaffold,
+ onNavigateToStremioAddons = { onTopLevelDestinationRequested(AppDestination.Addons) }
+ )
}
}
diff --git a/feature/system/src/main/java/com/streamvault/feature/system/presentation/plugins/PluginsScreen.kt b/feature/system/src/main/java/com/streamvault/feature/system/presentation/plugins/PluginsScreen.kt
index 00c26ff0..1c9a012b 100644
--- a/feature/system/src/main/java/com/streamvault/feature/system/presentation/plugins/PluginsScreen.kt
+++ b/feature/system/src/main/java/com/streamvault/feature/system/presentation/plugins/PluginsScreen.kt
@@ -40,6 +40,7 @@ import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
+import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.text.input.KeyboardType
@@ -60,19 +61,23 @@ import com.streamvault.feature.system.api.PluginConfigurationSection
import com.streamvault.feature.system.api.owner
import com.streamvault.feature.system.api.toBundleSafeKey
import com.streamvault.feature.system.api.SystemScaffoldContent
+import com.streamvault.feature.system.R
import com.streamvault.core.ui.components.dialogs.PremiumDialog
import com.streamvault.core.ui.components.dialogs.PremiumDialogFooterButton
import com.streamvault.core.ui.components.shell.StatusPill
+import com.streamvault.core.ui.components.shell.ExtensionsEmptyState
+import com.streamvault.core.ui.components.shell.ExtensionsSectionTabs
import com.streamvault.core.ui.design.AppColors
import com.streamvault.core.ui.design.FocusSpec
import com.streamvault.core.ui.interaction.TvButton
+import com.streamvault.core.ui.interaction.TvPrimaryButton
import com.streamvault.core.ui.theme.FocusBorder
import com.streamvault.core.ui.theme.OnSurface
-import com.streamvault.core.ui.theme.Primary
@Composable
fun PluginsScreen(
scaffold: SystemScaffoldContent,
+ onNavigateToStremioAddons: () -> Unit = {},
modifier: Modifier = Modifier,
viewModel: PluginsViewModel = hiltViewModel()
) {
@@ -110,6 +115,7 @@ fun PluginsScreen(
PluginsContent(
uiState = uiState,
scaffold = scaffold,
+ onNavigateToStremioAddons = onNavigateToStremioAddons,
showInstallUrlDialog = showInstallUrlDialog,
onShowInstallUrlDialog = { showInstallUrlDialog = true },
onDismissInstallUrlDialog = { showInstallUrlDialog = false },
@@ -147,6 +153,7 @@ internal data class PluginsActions(
internal fun PluginsContent(
uiState: PluginsUiState,
scaffold: SystemScaffoldContent,
+ onNavigateToStremioAddons: () -> Unit = {},
showInstallUrlDialog: Boolean,
onShowInstallUrlDialog: () -> Unit,
onDismissInstallUrlDialog: () -> Unit,
@@ -157,8 +164,8 @@ internal fun PluginsContent(
) {
scaffold(
AppDestination.Plugins,
- "Plugins",
- "Install companion APKs, activate capabilities, and sync plugin providers.",
+ stringResource(R.string.extensions_title),
+ null,
true,
true
) {
@@ -166,6 +173,14 @@ internal fun PluginsContent(
modifier = modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
+ ExtensionsSectionTabs(
+ selectedIndex = 0,
+ pluginsLabel = stringResource(R.string.extensions_tab_plugins),
+ stremioAddonsLabel = stringResource(R.string.extensions_tab_stremio_addons),
+ onTabSelected = { selectedIndex ->
+ if (selectedIndex == 1) onNavigateToStremioAddons()
+ }
+ )
val configuration = uiState.configuration
if (configuration != null) {
PluginConfigurationPanel(
@@ -177,6 +192,10 @@ internal fun PluginsContent(
onRunAction = actions.onRunConfigurationAction
)
} else {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(stringResource(R.string.extensions_tab_plugins), style = MaterialTheme.typography.titleLarge, color = AppColors.TextPrimary)
+ Text(stringResource(R.string.plugins_section_description), style = MaterialTheme.typography.bodyMedium, color = AppColors.TextSecondary)
+ }
PluginInstallPanel(
isInstalling = uiState.isInstalling,
onInstallFromUrl = onShowInstallUrlDialog,
@@ -210,19 +229,16 @@ internal fun PluginsContent(
)
}
- LazyColumn(
- modifier = Modifier.fillMaxSize(),
+ if (uiState.plugins.isEmpty() && !uiState.isLoading) {
+ ExtensionsEmptyState(
+ title = stringResource(R.string.plugins_empty_title),
+ description = stringResource(R.string.plugins_empty_description),
+ modifier = Modifier.weight(1f)
+ )
+ } else LazyColumn(
+ modifier = Modifier.weight(1f).fillMaxWidth(),
verticalArrangement = Arrangement.spacedBy(10.dp)
) {
- if (uiState.plugins.isEmpty() && !uiState.isLoading) {
- item {
- Text(
- text = "No compatible StreamVault plugins are installed.",
- style = MaterialTheme.typography.bodyMedium,
- color = AppColors.TextSecondary
- )
- }
- }
items(uiState.plugins, key = { it.owner.toBundleSafeKey() }) { plugin ->
PluginCard(
plugin = plugin,
@@ -255,45 +271,40 @@ private fun PluginButton(
content: @Composable RowScope.() -> Unit
) {
val shape = RoundedCornerShape(8.dp)
- val colors = when (tone) {
- PluginButtonTone.Primary -> ButtonDefaults.colors(
- containerColor = Primary,
- contentColor = Color.White,
- focusedContainerColor = Primary.copy(alpha = 0.88f),
- focusedContentColor = Color.White,
- disabledContainerColor = AppColors.SurfaceEmphasis.copy(alpha = 0.56f),
- disabledContentColor = AppColors.TextDisabled
- )
- PluginButtonTone.Secondary -> ButtonDefaults.colors(
- containerColor = MaterialTheme.colorScheme.surfaceVariant,
- contentColor = OnSurface,
- focusedContainerColor = MaterialTheme.colorScheme.surface,
- focusedContentColor = OnSurface,
- disabledContainerColor = AppColors.SurfaceEmphasis.copy(alpha = 0.56f),
- disabledContentColor = AppColors.TextDisabled
+ if (tone == PluginButtonTone.Primary) {
+ TvPrimaryButton(
+ onClick = onClick,
+ modifier = modifier,
+ enabled = enabled,
+ content = content,
)
- }
-
- TvButton(
- onClick = onClick,
- modifier = modifier
- .heightIn(min = 44.dp),
- enabled = enabled,
- shape = ButtonDefaults.shape(shape),
- colors = colors,
- border = ButtonDefaults.border(
- focusedBorder = Border(
- border = BorderStroke(FocusSpec.BorderWidth, FocusBorder),
- shape = shape
- )
- ),
- scale = ButtonDefaults.scale(focusedScale = FocusSpec.FocusedScale),
- contentPadding = androidx.compose.foundation.layout.PaddingValues(
- horizontal = 20.dp,
- vertical = 7.dp
+ } else {
+ TvButton(
+ onClick = onClick,
+ modifier = modifier.heightIn(min = 44.dp),
+ enabled = enabled,
+ shape = ButtonDefaults.shape(shape),
+ colors = ButtonDefaults.colors(
+ containerColor = MaterialTheme.colorScheme.surfaceVariant,
+ contentColor = OnSurface,
+ focusedContainerColor = MaterialTheme.colorScheme.surface,
+ focusedContentColor = OnSurface,
+ disabledContainerColor = AppColors.SurfaceEmphasis.copy(alpha = 0.56f),
+ disabledContentColor = AppColors.TextDisabled
+ ),
+ border = ButtonDefaults.border(
+ focusedBorder = Border(
+ border = BorderStroke(FocusSpec.BorderWidth, FocusBorder),
+ shape = shape
+ )
+ ),
+ scale = ButtonDefaults.scale(focusedScale = 1f, pressedScale = 1f),
+ contentPadding = androidx.compose.foundation.layout.PaddingValues(
+ horizontal = 20.dp,
+ vertical = 7.dp
+ ),
+ content = content,
)
- ) {
- content()
}
}
@@ -321,20 +332,20 @@ private fun PluginInstallPanel(
onClick = onInstallFromUrl,
tone = PluginButtonTone.Primary
) {
- Text("Install URL")
+ Text(stringResource(R.string.plugins_install_url))
}
PluginButton(
enabled = !isInstalling,
onClick = onInstallFromFile
) {
- Text("Install file")
+ Text(stringResource(R.string.plugins_install_file))
}
PluginButton(onClick = onRefresh) {
- Text("Refresh")
+ Text(stringResource(R.string.plugins_refresh))
}
}
Text(
- text = "Manual installs are detected when this screen refreshes. Compatible plugins expose the StreamVault plugin service.",
+ text = stringResource(R.string.plugins_install_hint),
style = MaterialTheme.typography.bodySmall,
color = AppColors.TextTertiary
)
diff --git a/feature/system/src/main/res/values/strings.xml b/feature/system/src/main/res/values/strings.xml
index b02043f8..5bb5be3a 100644
--- a/feature/system/src/main/res/values/strings.xml
+++ b/feature/system/src/main/res/values/strings.xml
@@ -1,5 +1,13 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
+ <string name="extensions_title">Extensions</string>
+ <string name="plugins_section_description">Add features to StreamVault with companion Android apps.</string>
+ <string name="plugins_install_url">Install plugin from URL</string>
+ <string name="plugins_install_file">Install plugin APK</string>
+ <string name="plugins_refresh">Check installed plugins</string>
+ <string name="plugins_install_hint">Use an APK file or a direct APK download link. For Stremio-compatible add-on manifest URLs, use the Stremio-compatible Add-ons tab.</string>
+ <string name="plugins_empty_title">No plugins installed</string>
+ <string name="plugins_empty_description">Install a compatible StreamVault plugin using the buttons above. Already installed one outside the app? Choose Check installed plugins.</string>
<string name="app_name">StreamVault</string>
<string name="welcome_setup_provider">Setup Provider</string>
<string name="welcome_setup_later">Set up later</string>
@@ -13,6 +21,8 @@
<string name="welcome_subtitle">Lean back into live channels, catch-up viewing, movies, and series with a first-party Android TV experience.</string>
<string name="settings_cancel">Cancel</string>
<string name="nav_downloads">Downloads</string>
+ <string name="extensions_tab_plugins">Plugins</string>
+ <string name="extensions_tab_stremio_addons">Stremio-compatible Add-ons</string>
<string name="downloads_loading">Loading downloads...</string>
<string name="downloads_empty_title">No downloads yet</string>
<string name="downloads_empty_hint">Download movies or episodes from detail screens and they will appear here.</string>
@@ -33,4 +43,4 @@
<string name="download_resume">Resume</string>
<string name="download_delete">Delete</string>
<string name="downloads_resumed">Download resumed</string>
-</resources>
\ No newline at end of file
+</resources>
diff --git a/player/build.gradle.kts b/player/build.gradle.kts
index 427c6ec1..9d8fdb07 100644
--- a/player/build.gradle.kts
+++ b/player/build.gradle.kts
@@ -219,5 +219,6 @@ dependencies {
testImplementation(libs.junit)
testImplementation(libs.truth)
testImplementation(libs.coroutines.test)
+ testImplementation(libs.okhttp.mockwebserver)
testImplementation(libs.robolectric)
}
diff --git a/player/src/main/java/com/streamvault/player/ExternalSubtitlePlayback.kt b/player/src/main/java/com/streamvault/player/ExternalSubtitlePlayback.kt
index c3283cad..b178edb4 100644
--- a/player/src/main/java/com/streamvault/player/ExternalSubtitlePlayback.kt
+++ b/player/src/main/java/com/streamvault/player/ExternalSubtitlePlayback.kt
@@ -37,13 +37,24 @@ internal fun TrackSelectionParameters.withExternalSubtitleEnabled(): TrackSelect
internal fun buildExternalSubtitleConfiguration(
subtitleUri: Uri,
- language: String
+ language: String,
+ label: String? = null
): MediaItem.SubtitleConfiguration = MediaItem.SubtitleConfiguration.Builder(subtitleUri)
- .setMimeType(MimeTypes.APPLICATION_SUBRIP)
+ .setMimeType(externalSubtitleMimeType(subtitleUri))
.setLanguage(language)
+ .setLabel(label?.takeIf(String::isNotBlank))
.setSelectionFlags(C.SELECTION_FLAG_DEFAULT)
.build()
+private fun externalSubtitleMimeType(uri: Uri): String = when (
+ uri.lastPathSegment.orEmpty().substringAfterLast('.', "").lowercase()
+) {
+ "vtt", "webvtt" -> MimeTypes.TEXT_VTT
+ "ass", "ssa" -> MimeTypes.TEXT_SSA
+ "ttml", "dfxp" -> MimeTypes.APPLICATION_TTML
+ else -> MimeTypes.APPLICATION_SUBRIP
+}
+
@UnstableApi
internal fun buildExternalSubtitleMediaSource(
dataSourceFactory: DataSource.Factory,
diff --git a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
index d5d0244f..df908fbd 100644
--- a/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/Media3PlayerEngine.kt
@@ -60,13 +60,13 @@ import com.streamvault.player.playback.PlaybackCodecSelector
import com.streamvault.player.playback.PlaybackCompatibilityProfile
import com.streamvault.player.playback.PlaybackBufferPolicies
import com.streamvault.player.playback.PlaybackBufferPolicy
+import com.streamvault.player.playback.PlaybackLogSanitizer
import com.streamvault.player.playback.PlaybackLoadControl
import com.streamvault.player.playback.LiveVideoStallRecovery
import com.streamvault.player.playback.PlaybackErrorCategory
import com.streamvault.player.playback.FfmpegAudioFallbackRequest
import com.streamvault.player.playback.FfmpegExtensionSupport
import com.streamvault.player.playback.InitialBitratePolicy
-import com.streamvault.player.playback.PlaybackLogSanitizer
import com.streamvault.player.playback.PlaybackPreparationPlan
import com.streamvault.player.playback.PlaybackRetryContext
import com.streamvault.player.playback.PlayerDataSourceFactoryProvider
@@ -885,7 +885,7 @@ class Media3PlayerEngine @Inject constructor(
liveAudioTap = tap
}
- override fun addExternalSubtitle(subtitleUri: android.net.Uri, language: String) {
+ override fun addExternalSubtitle(subtitleUri: android.net.Uri, language: String, label: String?) {
val player = exoPlayer ?: return
val streamInfo = lastStreamInfo ?: return
val retryPolicy = currentRetryPolicy ?: return
@@ -901,7 +901,7 @@ class Media3PlayerEngine @Inject constructor(
vodHttpProtocolMode = requestedVodHttpProtocolMode,
preload = false
)
- val subtitleConfig = buildExternalSubtitleConfiguration(subtitleUri, language)
+ val subtitleConfig = buildExternalSubtitleConfiguration(subtitleUri, language, label)
val subtitleSource = buildExternalSubtitleMediaSource(
dataSourceFactory = androidx.media3.datasource.DefaultDataSource.Factory(context),
configuration = subtitleConfig
@@ -913,7 +913,11 @@ class Media3PlayerEngine @Inject constructor(
player.prepare()
transition.resumePositionMs.takeIf { it > 0L }?.let(player::seekTo)
player.playWhenReady = transition.playWhenReady
- Log.i(TAG, "addExternalSubtitle language=$language uri=$subtitleUri")
+ Log.i(
+ TAG,
+ "addExternalSubtitle language=$language " +
+ "target=${PlaybackLogSanitizer.sanitizeOrigin(subtitleUri.toString())}"
+ )
}
override fun toggleMute() {
diff --git a/player/src/main/java/com/streamvault/player/PlayerEngine.kt b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
index b1ff6a2e..7eb068bd 100644
--- a/player/src/main/java/com/streamvault/player/PlayerEngine.kt
+++ b/player/src/main/java/com/streamvault/player/PlayerEngine.kt
@@ -101,7 +101,7 @@ interface PlayerEngine {
fun selectAudioTrack(trackId: String)
fun selectVideoTrack(trackId: String)
fun selectSubtitleTrack(trackId: String?) // null to disable subtitles
- fun addExternalSubtitle(subtitleUri: android.net.Uri, language: String)
+ fun addExternalSubtitle(subtitleUri: android.net.Uri, language: String, label: String? = null)
fun setInjectedSubtitleText(text: String?)
fun setLiveAudioTap(tap: LiveAudioTap?)
fun clearLiveAudioTap() = setLiveAudioTap(null)
diff --git a/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt b/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt
index c262a7dc..df824da7 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlaybackLogSanitizer.kt
@@ -3,6 +3,16 @@ package com.streamvault.player.playback
import java.net.URI
internal object PlaybackLogSanitizer {
+ fun sanitizeOrigin(url: String?): String {
+ if (url.isNullOrBlank()) return "<unknown>"
+ val uri = runCatching { URI(url) }.getOrNull() ?: return "<malformed>"
+ val scheme = uri.scheme?.lowercase()?.takeIf { it == "http" || it == "https" }
+ ?: return "<unsupported>"
+ val host = uri.host?.takeIf(String::isNotBlank) ?: return "<unknown-host>"
+ val port = if (uri.port > 0) ":${uri.port}" else ""
+ return "$scheme://$host$port"
+ }
+
fun sanitizeUrl(url: String?): String {
if (url.isNullOrBlank()) return "<unknown>"
val uri = runCatching { URI(url) }.getOrNull() ?: return "<malformed>"
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 7571194d..87d92066 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceFactoryProvider.kt
@@ -18,6 +18,8 @@ import java.util.concurrent.TimeUnit
import okhttp3.Interceptor
import okhttp3.OkHttpClient
import okhttp3.Protocol
+import okhttp3.Authenticator
+import okhttp3.CookieJar
@UnstableApi
class PlayerDataSourceFactoryProvider(
@@ -74,9 +76,48 @@ class PlayerDataSourceFactoryProvider(
proxyHost = streamInfo.proxyHost.trim(),
proxyPort = streamInfo.proxyPort
)
- val client = clientsByKey.getOrPut(clientKey) {
+ val client = if (streamInfo.requestHeadersOrigin != null) {
+ // Stremio URLs may contain credentials; keep their playback client out of shared logging,
+ // cookie, authenticator, cache, and client-cache state.
+ buildClient(streamInfo, profile, forceHttp1, port, headers)
+ } else {
+ clientsByKey.getOrPut(clientKey) {
+ buildClient(streamInfo, profile, forceHttp1, port, emptyMap())
+ }
+ }
+ val upstreamFactory = OkHttpDataSource.Factory(client).apply {
+ if (headers.isNotEmpty() && streamInfo.requestHeadersOrigin == null) {
+ setDefaultRequestProperties(headers)
+ }
+ }
+ val defaultFactory = DefaultDataSource.Factory(context, upstreamFactory)
+ if (!preload) {
+ transferListener?.let(defaultFactory::setTransferListener)
+ }
+ val factory = if (shouldWrapDataSourceReadStats(resolvedStreamType)) {
+ PlayerDataSourceReadStatsFactory(
+ upstream = defaultFactory,
+ resolvedStreamType = resolvedStreamType,
+ initialTargetUrl = streamInfo.url,
+ sensitiveTargetOrigin = streamInfo.requestHeadersOrigin
+ )
+ } else {
+ defaultFactory
+ }
+ return profile to factory
+ }
+
+ private fun buildClient(
+ streamInfo: StreamInfo,
+ profile: PlayerTimeoutProfile,
+ forceHttp1: Boolean,
+ port: Int,
+ originScopedHeaders: Map<String, String>
+ ): OkHttpClient {
+ val isStremioMediaRequest = streamInfo.requestHeadersOrigin != null
val transportPolicy = streamInfo.playbackTransportPolicy
val builder = when {
+ isStremioMediaRequest -> baseClient.newBuilder()
transportPolicy != null ->
baseClient.newBuilder()
.applyPlaybackTransportPolicy(transportPolicy)
@@ -84,8 +125,16 @@ class PlayerDataSourceFactoryProvider(
baseClient.newBuilder().applyUnsafeTlsBypass()
else -> baseClient.newBuilder()
}
- builder
- .addInterceptor(StalkerPlaybackRequestLoggingInterceptor)
+ val stremioMediaOrigin = streamInfo.requestHeadersOrigin
+ if (stremioMediaOrigin != null) {
+ builder.applyStremioMediaRequestPolicy(
+ origin = stremioMediaOrigin,
+ headers = originScopedHeaders
+ )
+ } else {
+ builder.addInterceptor(StalkerPlaybackRequestLoggingInterceptor)
+ }
+ return builder
.connectTimeout(profile.connectTimeoutMs, TimeUnit.MILLISECONDS)
.readTimeout(profile.readTimeoutMs, TimeUnit.MILLISECONDS)
.writeTimeout(profile.writeTimeoutMs, TimeUnit.MILLISECONDS)
@@ -95,32 +144,16 @@ class PlayerDataSourceFactoryProvider(
if (forceHttp1) {
protocols(listOf(Protocol.HTTP_1_1))
}
- streamInfo.httpProxy()?.let { proxy(it) }
+ if (!isStremioMediaRequest) {
+ streamInfo.httpProxy()?.let { proxy(it) }
+ }
}
.build()
- }
- if (forceHttp1) {
- Log.i(TAG, "data-source streamType=$resolvedStreamType timeout=$profile httpProtocol=HTTP_1_1")
- }
- val upstreamFactory = OkHttpDataSource.Factory(client).apply {
- if (headers.isNotEmpty()) {
- setDefaultRequestProperties(headers)
+ .also {
+ if (forceHttp1) {
+ Log.i(TAG, "data-source timeout=$profile httpProtocol=HTTP_1_1")
+ }
}
- }
- val defaultFactory = DefaultDataSource.Factory(context, upstreamFactory)
- if (!preload) {
- transferListener?.let(defaultFactory::setTransferListener)
- }
- val factory = if (shouldWrapDataSourceReadStats(resolvedStreamType)) {
- PlayerDataSourceReadStatsFactory(
- upstream = defaultFactory,
- resolvedStreamType = resolvedStreamType,
- initialTargetUrl = streamInfo.url
- )
- } else {
- defaultFactory
- }
- return profile to factory
}
internal fun clientCacheSizeForTests(): Int = clientsByKey.size()
@@ -130,6 +163,7 @@ class PlayerDataSourceFactoryProvider(
headers: Map<String, String>,
preload: Boolean
) {
+ if (streamInfo.requestHeadersOrigin != null) return
val hasStalkerHeaders = headers.containsKey("X-User-Agent") ||
headers.containsKey("Authorization") ||
headers["Cookie"]?.contains("mac=", ignoreCase = true) == true
@@ -163,6 +197,50 @@ class PlayerDataSourceFactoryProvider(
}
}
+internal fun OkHttpClient.Builder.applyStremioMediaRequestPolicy(
+ origin: String,
+ headers: Map<String, String>
+): OkHttpClient.Builder {
+ interceptors().clear()
+ networkInterceptors().clear()
+ cookieJar(CookieJar.NO_COOKIES)
+ .authenticator(Authenticator.NONE)
+ .proxyAuthenticator(Authenticator.NONE)
+ .cache(null)
+ .followRedirects(true)
+ .followSslRedirects(true)
+ if (headers.isNotEmpty()) {
+ addNetworkInterceptor(OriginScopedPlaybackHeadersInterceptor(origin, headers))
+ }
+ return this
+}
+
+internal class OriginScopedPlaybackHeadersInterceptor(
+ private val origin: String,
+ private val headers: Map<String, String>
+) : Interceptor {
+ override fun intercept(chain: Interceptor.Chain): okhttp3.Response {
+ return chain.proceed(originScopedPlaybackRequest(chain.request(), origin, headers))
+ }
+}
+
+internal fun originScopedPlaybackRequest(
+ request: okhttp3.Request,
+ origin: String,
+ headers: Map<String, String>
+): okhttp3.Request = request.newBuilder().apply {
+ // Remove these names on redirects too: OkHttp may carry a prior exchange's request forward.
+ headers.keys.forEach { removeHeader(it) }
+ if (playbackRequestOrigin(request.url) == origin) {
+ headers.forEach { (name, value) -> header(name, value) }
+ }
+}.build()
+
+internal fun playbackRequestOrigin(url: okhttp3.HttpUrl): String {
+ val host = url.host.let { if (it.contains(':')) "[$it]" else it }
+ return "${url.scheme}://$host:${url.port}"
+}
+
internal fun effectivePlaybackRequestProperties(
headers: Map<String, String>,
userAgent: String?
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceReadStats.kt b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceReadStats.kt
index 4c550fb9..22bc3dec 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceReadStats.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerDataSourceReadStats.kt
@@ -14,6 +14,7 @@ internal class PlayerDataSourceReadStatsFactory(
private val upstream: DataSource.Factory,
private val resolvedStreamType: ResolvedStreamType,
private val initialTargetUrl: String,
+ private val sensitiveTargetOrigin: String? = null,
private val clockMs: () -> Long = SystemClock::elapsedRealtime
) : DataSource.Factory {
override fun createDataSource(): DataSource =
@@ -21,6 +22,7 @@ internal class PlayerDataSourceReadStatsFactory(
upstream = upstream.createDataSource(),
resolvedStreamType = resolvedStreamType,
initialTargetUrl = initialTargetUrl,
+ sensitiveTargetOrigin = sensitiveTargetOrigin,
clockMs = clockMs
)
}
@@ -34,10 +36,11 @@ private class PlayerDataSourceReadStatsDataSource(
private val upstream: DataSource,
private val resolvedStreamType: ResolvedStreamType,
initialTargetUrl: String,
+ private val sensitiveTargetOrigin: String?,
private val clockMs: () -> Long
) : DataSource {
private val tracker = PlayerDataSourceReadStatsTracker()
- private var target = PlaybackLogSanitizer.sanitizeUrl(initialTargetUrl)
+ private var target = sanitizeTarget(initialTargetUrl)
private var opened = false
override fun addTransferListener(transferListener: TransferListener) {
@@ -46,7 +49,7 @@ private class PlayerDataSourceReadStatsDataSource(
@Throws(IOException::class)
override fun open(dataSpec: DataSpec): Long {
- target = PlaybackLogSanitizer.sanitizeUrl(dataSpec.uri.toString())
+ target = sanitizeTarget(dataSpec.uri.toString())
val length = upstream.open(dataSpec)
tracker.open(clockMs())
opened = true
@@ -104,6 +107,9 @@ private class PlayerDataSourceReadStatsDataSource(
private fun readStatsLoggingEnabled(): Boolean = Log.isLoggable(TAG, Log.DEBUG)
+ private fun sanitizeTarget(url: String): String =
+ PlaybackLogSanitizer.sanitizeUrl(sensitiveTargetOrigin ?: url)
+
private companion object {
const val TAG = "PlayerDataReadStats"
}
diff --git a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt
index 93084869..15c847bb 100644
--- a/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt
+++ b/player/src/main/java/com/streamvault/player/playback/PlayerMediaSourceFactory.kt
@@ -74,7 +74,8 @@ class PlayerMediaSourceFactory(
Log.i(
TAG,
- "media-source streamType=$resolvedStreamType timeout=$timeoutProfile source=${mediaSource::class.java.simpleName} target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.url)}"
+ "media-source streamType=$resolvedStreamType timeout=$timeoutProfile source=${mediaSource::class.java.simpleName} " +
+ "target=${PlaybackLogSanitizer.sanitizeUrl(streamInfo.requestHeadersOrigin ?: streamInfo.url)}"
)
return timeoutProfile to mediaSource
}
diff --git a/player/src/test/java/com/streamvault/player/ExternalSubtitlePlaybackTest.kt b/player/src/test/java/com/streamvault/player/ExternalSubtitlePlaybackTest.kt
index 54879a4d..1ee45c25 100644
--- a/player/src/test/java/com/streamvault/player/ExternalSubtitlePlaybackTest.kt
+++ b/player/src/test/java/com/streamvault/player/ExternalSubtitlePlaybackTest.kt
@@ -54,6 +54,19 @@ class ExternalSubtitlePlaybackTest {
assertThat(configuration.selectionFlags).isEqualTo(C.SELECTION_FLAG_DEFAULT)
}
+ @Test
+ fun `external subtitle configuration preserves label and detects webvtt`() {
+ val configuration = buildExternalSubtitleConfiguration(
+ subtitleUri = Uri.parse("https://example.test/private/path/captions.vtt?token=hidden"),
+ language = "en",
+ label = "English · Subtitles"
+ )
+
+ assertThat(configuration.mimeType).isEqualTo(MimeTypes.TEXT_VTT)
+ assertThat(configuration.language).isEqualTo("en")
+ assertThat(configuration.label).isEqualTo("English · Subtitles")
+ }
+
@Test
fun `external subtitles use extraction based progressive media source`() {
val configuration = buildExternalSubtitleConfiguration(
diff --git a/player/src/test/java/com/streamvault/player/playback/PlaybackLogSanitizerTest.kt b/player/src/test/java/com/streamvault/player/playback/PlaybackLogSanitizerTest.kt
index 534859f3..639dd7c9 100644
--- a/player/src/test/java/com/streamvault/player/playback/PlaybackLogSanitizerTest.kt
+++ b/player/src/test/java/com/streamvault/player/playback/PlaybackLogSanitizerTest.kt
@@ -4,6 +4,17 @@ import com.google.common.truth.Truth.assertThat
import org.junit.Test
class PlaybackLogSanitizerTest {
+ @Test
+ fun `subtitle origin logging removes private path and query`() {
+ val sanitized = PlaybackLogSanitizer.sanitizeOrigin(
+ "https://subtitles.example.test/private/configured/path.srt?token=hidden"
+ )
+
+ assertThat(sanitized).isEqualTo("https://subtitles.example.test")
+ assertThat(sanitized).doesNotContain("private")
+ assertThat(sanitized).doesNotContain("hidden")
+ }
+
@Test
fun `redacts live username and password path segments`() {
val sanitized = PlaybackLogSanitizer.sanitizeUrl(
diff --git a/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt b/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt
index 45b9bf15..f774e862 100644
--- a/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt
+++ b/player/src/test/java/com/streamvault/player/playback/PlayerDataSourceFactoryProviderTest.kt
@@ -5,8 +5,81 @@ import com.streamvault.domain.model.PlaybackTransportMode
import com.streamvault.domain.model.PlaybackTransportPolicy
import com.streamvault.domain.model.StalkerTransportOrigin
import org.junit.Test
+import okhttp3.Request
+import okhttp3.OkHttpClient
+import okhttp3.Response
+import okhttp3.Interceptor
+import okhttp3.mockwebserver.MockResponse
+import okhttp3.mockwebserver.MockWebServer
class PlayerDataSourceFactoryProviderTest {
+ @Test
+ fun `Stremio credentials attach only to the selected media origin`() {
+ val headers = mapOf("Authorization" to "Bearer private", "Referer" to "https://media.example/entry")
+ val sameOrigin = originScopedPlaybackRequest(
+ Request.Builder().url("https://media.example/segment/1.ts").build(),
+ "https://media.example:443",
+ headers
+ )
+ val redirected = originScopedPlaybackRequest(
+ Request.Builder().url("https://cdn.example/segment/1.ts").header("Authorization", "Bearer private").build(),
+ "https://media.example:443",
+ headers
+ )
+
+ assertThat(sameOrigin.header("Authorization")).isEqualTo("Bearer private")
+ assertThat(sameOrigin.header("Referer")).isEqualTo("https://media.example/entry")
+ assertThat(redirected.header("Authorization")).isNull()
+ assertThat(redirected.header("Referer")).isNull()
+ }
+
+ @Test
+ fun `Stremio origin matching handles IPv6 hosts`() {
+ val request = Request.Builder().url("http://[::1]/segment.ts").build()
+
+ assertThat(playbackRequestOrigin(request.url)).isEqualTo("http://[::1]:80")
+ }
+
+ @Test
+ fun `Stremio credentials are removed on a cross-origin redirect`() {
+ val mediaServer = MockWebServer()
+ val cdnServer = MockWebServer()
+ mediaServer.start()
+ cdnServer.start()
+ try {
+ mediaServer.enqueue(
+ MockResponse().setResponseCode(302).addHeader("Location", cdnServer.url("/segment.ts"))
+ )
+ cdnServer.enqueue(MockResponse().setResponseCode(200).setBody("segment"))
+ val mediaOrigin = "http://${mediaServer.hostName}:${mediaServer.port}"
+ val inheritedLogs = mutableListOf<String>()
+ val baseClient = OkHttpClient.Builder()
+ .followRedirects(false)
+ .addInterceptor(Interceptor { chain ->
+ inheritedLogs += chain.request().url.toString()
+ chain.proceed(chain.request())
+ })
+ .build()
+ val client = baseClient.newBuilder()
+ .applyStremioMediaRequestPolicy(
+ origin = mediaOrigin,
+ headers = mapOf("Authorization" to "Bearer private")
+ )
+ .build()
+
+ client.newCall(Request.Builder().url(mediaServer.url("/master.m3u8")).build()).execute().use { response: Response ->
+ assertThat(response.code).isEqualTo(200)
+ }
+
+ assertThat(mediaServer.takeRequest().getHeader("Authorization")).isEqualTo("Bearer private")
+ assertThat(cdnServer.takeRequest().getHeader("Authorization")).isNull()
+ assertThat(inheritedLogs).isEmpty()
+ } finally {
+ mediaServer.shutdown()
+ cdnServer.shutdown()
+ }
+ }
+
@Test
fun `effective playback request properties inject explicit user agent`() {
val headers = effectivePlaybackRequestProperties(