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 follow-up safeguards

David Nashashaaa4a1d212b2
diff --git a/app/src/test/java/com/streamvault/app/plugins/PluginPlaybackRoutingTest.kt b/app/src/test/java/com/streamvault/app/plugins/PluginPlaybackRoutingTest.kt
index 02b10a05..9b8b351f 100644
--- a/app/src/test/java/com/streamvault/app/plugins/PluginPlaybackRoutingTest.kt
+++ b/app/src/test/java/com/streamvault/app/plugins/PluginPlaybackRoutingTest.kt
@@ -37,6 +37,33 @@ class PluginPlaybackRoutingTest {
assertThat(playbackCandidates(listOf(plugin), "https://other.example/live", StreamVaultPluginContract.CAPABILITY_PLAYBACK_PREPARE)).isEmpty()
}
+ @Test
+ fun `magnet requests require an enabled plugin that explicitly owns magnet URLs`() {
+ val magnet = "magnet:?xt=urn:btih:0123456789abcdef"
+ val torrentPlugin = plugin("torrent", schemes = listOf("magnet"))
+
+ assertThat(playbackCandidates(emptyList(), magnet, StreamVaultPluginContract.CAPABILITY_PLAYBACK_PREPARE))
+ .isEmpty()
+ assertThat(
+ playbackCandidates(
+ listOf(torrentPlugin.copy(enabled = false)),
+ magnet,
+ StreamVaultPluginContract.CAPABILITY_PLAYBACK_PREPARE
+ )
+ ).isEmpty()
+ assertThat(playbackCandidates(listOf(torrentPlugin), magnet, StreamVaultPluginContract.CAPABILITY_PLAYBACK_PREPARE))
+ .containsExactly(torrentPlugin)
+ }
+
+ @Test
+ fun `magnet preparation accepts only a safe local HTTP output with an explicit port`() {
+ assertThat(isSafeMagnetPlaybackOutputUrl("http://127.0.0.1:6878/stream/abc")).isTrue()
+ assertThat(isSafeMagnetPlaybackOutputUrl("http://localhost:6878/stream/abc")).isFalse()
+ assertThat(isSafeMagnetPlaybackOutputUrl("https://127.0.0.1:6878/stream/abc")).isFalse()
+ assertThat(isSafeMagnetPlaybackOutputUrl("http://127.0.0.1/stream/abc")).isFalse()
+ assertThat(isSafeMagnetPlaybackOutputUrl("http://[email protected]:6878/stream/abc")).isFalse()
+ }
+
@Test
fun `playback deadline bounds discovery and handler work together`() = runTest {
val result = withPluginPlaybackDeadline(5_000L) {
diff --git a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
index 84210958..83819433 100644
--- a/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
+++ b/data/src/main/java/com/streamvault/data/manager/BackupManagerImpl.kt
@@ -309,6 +309,7 @@ class BackupManagerImpl @Inject constructor(
put("recordingPaddingAfterMinutes", preferencesRepository.recordingPaddingAfterMinutes.first().toString())
put("maxConcurrentStreams", preferencesRepository.maxConcurrentStreams.first().toString())
put("isIncognitoMode", preferencesRepository.isIncognitoMode.first().toString())
+ put("hideStremioAddons", preferencesRepository.hideStremioAddons.first().toString())
put("useXtreamTextClassification", preferencesRepository.useXtreamTextClassification.first().toString())
put("xtreamBase64TextCompatibility", preferencesRepository.xtreamBase64TextCompatibility.first().toString())
put("guideDensity", preferencesRepository.guideDensity.first() ?: "")
@@ -3379,6 +3380,7 @@ class BackupManagerImpl @Inject constructor(
put("recordingPaddingAfterMinutes", preferencesRepository.recordingPaddingAfterMinutes.first().toString())
put("maxConcurrentStreams", preferencesRepository.maxConcurrentStreams.first().toString())
put("isIncognitoMode", preferencesRepository.isIncognitoMode.first().toString())
+ put("hideStremioAddons", preferencesRepository.hideStremioAddons.first().toString())
put("useXtreamTextClassification", preferencesRepository.useXtreamTextClassification.first().toString())
put("xtreamBase64TextCompatibility", preferencesRepository.xtreamBase64TextCompatibility.first().toString())
put("guideDensity", preferencesRepository.guideDensity.first() ?: "")
@@ -4042,6 +4044,8 @@ class BackupManagerImpl @Inject constructor(
?.let { preferencesRepository.setMaxConcurrentStreams(it) }
prefs["isIncognitoMode"]?.toBooleanStrictOrNull()
?.let { preferencesRepository.setIncognitoMode(it) }
+ prefs["hideStremioAddons"]?.toBooleanStrictOrNull()
+ ?.let { preferencesRepository.setHideStremioAddons(it) }
prefs["useXtreamTextClassification"]?.toBooleanStrictOrNull()
?.let { preferencesRepository.setUseXtreamTextClassification(it) }
prefs["xtreamBase64TextCompatibility"]?.toBooleanStrictOrNull()
diff --git a/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt b/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt
index 9975441f..14141946 100644
--- a/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt
+++ b/data/src/main/java/com/streamvault/data/manager/PreferenceBackupRegistry.kt
@@ -24,7 +24,7 @@ internal object PreferenceBackupRegistry {
"epg_time_shift_by_provider", "promoted_live_group_ids", "multiview_preset_1",
"multiview_preset_2", "multiview_preset_3", "multiview_performance_mode",
"multiview_center_two_slot_layout", "multiview_respect_provider_connection_limit",
- "is_incognito_mode", "player_muted", "player_media_session_enabled", "player_back_button_visibility",
+ "is_incognito_mode", "hide_stremio_addons", "player_muted", "player_media_session_enabled", "player_back_button_visibility",
"player_confirm_close_playback",
"player_fast_retry_on_transient_failures", "player_audio_decoder_mode", "player_video_decoder_mode",
"player_playback_buffer_mode", "player_live_stream_format_mode", "player_vod_http_protocol_mode",
@@ -115,7 +115,7 @@ internal object PreferenceBackupRegistry {
"defaultStopPlaybackTimerMinutes", "defaultIdleStandbyTimerMinutes", "preventStandbyDuringPlayback",
"zapAutoRevert", "autoPlayNextEpisode", "autoCheckAppUpdates", "autoDownloadAppUpdates",
"recordingWifiOnly", "recordingPaddingBeforeMinutes", "recordingPaddingAfterMinutes",
- "maxConcurrentStreams", "isIncognitoMode", "useXtreamTextClassification",
+ "maxConcurrentStreams", "isIncognitoMode", "hideStremioAddons", "useXtreamTextClassification",
"xtreamBase64TextCompatibility", "guideDensity", "guideChannelMode", "guideFavoritesOnly",
"guideScheduledOnly", "guideAnchorTime"
)
diff --git a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
index 8b00d936..82de2aa3 100644
--- a/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
+++ b/data/src/test/java/com/streamvault/data/manager/BackupManagerImplTest.kt
@@ -1640,6 +1640,33 @@ class BackupManagerImplTest {
assertThat(import.failedSections.single()).contains("Preferences: DataStore unavailable")
}
+ @Test
+ fun `importConfig restores Stremio add-on visibility preference`() = runBlocking {
+ val context: Context = mock()
+ val contentResolver: ContentResolver = mock()
+ val preferencesRepository: PreferencesRepository = mock()
+ val providerDao: ProviderDao = mock()
+ whenever(context.contentResolver).thenReturn(contentResolver)
+ whenever(providerDao.getAllSync()).thenReturn(emptyList())
+ whenever(contentResolver.openInputStream(Uri.parse("content://backup-stremio-visibility"))).thenReturn(
+ ByteArrayInputStream(
+ Gson().toJson(BackupData(preferences = mapOf("hideStremioAddons" to "true"))).toByteArray()
+ )
+ )
+
+ val result = backupManagerForValidation(
+ context = context,
+ preferencesRepository = preferencesRepository,
+ providerDao = providerDao
+ ).importConfig(
+ uriString = "content://backup-stremio-visibility",
+ plan = preferencesOnlyPlan()
+ )
+
+ assertThat(result).isInstanceOf(Result.Success::class.java)
+ verify(preferencesRepository).setHideStremioAddons(true)
+ }
+
@Test
fun `importConfig clears optional guide preferences when backup has no selected value`() = runBlocking {
val context: Context = mock()
@@ -3728,6 +3755,7 @@ class BackupManagerImplTest {
storedProviders: List<Provider> = emptyList(),
): BackupManagerImpl {
whenever(preferencesRepository.defaultCategoryId).thenReturn(flowOf(null))
+ whenever(preferencesRepository.hideStremioAddons).thenReturn(flowOf(false))
whenever(recordingManager.observeRecordingItems()).thenReturn(flowOf(emptyList()))
whenever(recordingManager.observeStorageState()).thenReturn(flowOf(RecordingStorageState()))
return BackupManagerImpl(
diff --git a/data/src/test/java/com/streamvault/data/manager/PreferenceBackupRegistryTest.kt b/data/src/test/java/com/streamvault/data/manager/PreferenceBackupRegistryTest.kt
index 5c9cd3ba..56e166bd 100644
--- a/data/src/test/java/com/streamvault/data/manager/PreferenceBackupRegistryTest.kt
+++ b/data/src/test/java/com/streamvault/data/manager/PreferenceBackupRegistryTest.kt
@@ -52,5 +52,7 @@ class PreferenceBackupRegistryTest {
PreferenceBackupClassification.PORTABLE_PROVIDER_CONTENT
) && PreferenceBackupRegistry.portableCodecForStorageKey(it) == null
}).isEmpty()
+ assertThat(PreferenceBackupRegistry.classification("hideStremioAddons"))
+ .isEqualTo(PreferenceBackupClassification.PORTABLE_GLOBAL)
}
}
diff --git a/docs/STREMIO_UX_AND_FUNCTIONALITY_PLAN.md b/docs/STREMIO_UX_AND_FUNCTIONALITY_PLAN.md
index bbe7cb6b..77f5ac0b 100644
--- a/docs/STREMIO_UX_AND_FUNCTIONALITY_PLAN.md
+++ b/docs/STREMIO_UX_AND_FUNCTIONALITY_PLAN.md
@@ -1,7 +1,7 @@
# Stremio and Extensions UX and functionality improvement plan
- Date: 2026-10-16.
-- Status: Implementation in progress; debug APK is installed on the requested emulator; manual UX and real-torrent acceptance remain pending.
+- Status: Implementation in progress; catalog replacement, focus restoration, backup compatibility, and playback handoff regressions are covered. Debug APK is installed on the requested emulator; configured-emulator UX and real-torrent acceptance remain pending.
- Reviewed baseline: `f1ac7d3d` on `feature/stremio-addons`.
- Worktree: `D:\antigravity-scratch\iptv-player\.worktrees\stremio-addons`.
@@ -180,8 +180,12 @@ Addresses R1-R2.
variants and the already-installed current schema. Follow the database
invariants, export the final schema, and preserve providers, add-on settings,
recordings, and playback history.
-- [ ] Add regression coverage for direct HTTP, invalid headers, missing/failed
- torrent plugin, valid plugin output, and populated supported upgrade origins.
+- [x] Cover direct HTTP header scoping, invalid headers, unavailable torrent
+ capability, explicit magnet plugin routing, safe/unsafe loopback output, and
+ populated supported upgrade origins.
+- [ ] Add a plugin-manager binder-level test for handler-reported failure and
+ successful magnet handoff. Current tests cover the policy and UI availability
+ decisions without invoking the Android Messenger call path.
Gate: targeted playback tests pass, supported database upgrades validate the
final Room schema and foreign keys, and a current debug APK builds.
@@ -200,9 +204,11 @@ Addresses UI decisions 1-3 and 5; R3, R6, R9, R11, and R12.
and no duplicate section tabs.
- [x] Add capability-aware details, catalog settings, ordering, and removal
confirmation. Make repeated actions safe.
-- [ ] Verify explicit remote-focus restoration after a row is reordered or
- removed; stable row keys are in place, but this needs targeted testing on the
- installed TV emulator.
+- [x] Implement explicit remote-focus restoration after a row is reordered or
+ removed, with a fallback target if the operation fails.
+- [ ] Verify reorder and removal focus on a configured TV emulator. The current
+ `emulator-5558` install opens first-run provider setup and has no add-ons to
+ exercise those actions.
- [x] Add manifest refresh preserving install identity, enabled state, catalog
choices, ordering, and history. Keep the saved manifest if refresh fails.
Invalidate affected browse data after successful refresh.
@@ -241,7 +247,8 @@ Addresses R5-R7 and the playback-facing portion of R1.
when none is available.
- [x] Return from the player to the selected title/episode context, then restore
the browse catalog, query, filters, position, and focused poster on Back.
-- [ ] Cover history/resume and subtitle behavior across the new flow.
+- [x] Cover exact history replay/resume identity, scoped playback handoff,
+ inline subtitle handoff, and inline/add-on subtitle picker behavior.
Gate: exact-episode, cancellation, partial-failure, player-return, history, and
subtitle tests pass; user acceptance covers a long series and multiple providers.
@@ -254,15 +261,18 @@ Addresses R8-R10 and verifies all five UI decisions.
source operations handle expected/unexpected errors and clear loading state.
- [x] Separate an actual empty result, no eligible provider, unsupported resource,
and request failure. Keep retry actions tied to the failed operation.
-- [ ] Handle an add-on/catalog being disabled or removed while its content is
- selected, with a valid next selection and useful explanation.
+- [x] When the selected add-on/catalog is disabled or removed, select another
+ available catalog and show a useful explanation; cover disable/removal cases
+ in browse state tests.
+- [x] Classify and back up the Hide Stremio Add-ons preference as a portable
+ global setting. The full data suite caught the missing classification and
+ import/export mapping; a restore regression now covers it.
- [x] Retain URL/token sanitization in UI errors, logs, and stored history.
-- [ ] Obtain a clean run of the relevant repository checks; other targeted
- state, resolver, playback, migration, build, and install checks have passed.
- `com.streamvault.app.debug` is installed on `emulator-5558` with app data
- retained for the user's manual acceptance.
-- [ ] Record build/test evidence separately from user UI and real-playback
- acceptance. Close acceptance items only when supported by that evidence.
+- [x] Obtain clean runs of the relevant Stremio, playback, app, and data unit
+ suites; build and install the debug APK on the requested emulator.
+- [x] Record implementation verification separately from user UI and
+ real-playback acceptance; those acceptance items remain open until inspected
+ on a configured emulator and a real stream is exercised.
Gate: required code checks pass and user-owned acceptance results are recorded.
@@ -270,13 +280,14 @@ Gate: required code checks pass and user-owned acceptance results are recorded.
The review baseline ran 107 existing tests with no failures: 30 Stremio
feature/state, 17 Stremio domain, 48 Stremio data, and 12 targeted playback
-tests. Implementation verification has since passed the Stremio feature, system,
-shared UI, domain, and playback unit suites, plus the Room migration
-instrumentation suite. The focused Stremio data repository run exposed
-intermittent MockWebServer connection timeouts; one previously failing install
-case passed when run alone. The debug APK has built and is installed on
-`emulator-5558`. These checks do not establish visual quality or real torrent
-playback.
+tests. Implementation verification passed `:feature:stremio:testDebugUnitTest`,
+`:feature:playback:testDebugUnitTest`, `:app:testDebugUnitTest`, and the full
+`:data:testDebugUnitTest` suite. The first full data run exposed an
+unclassified `hide_stremio_addons` preference; the registry and backup
+import/export mappings were fixed, and the full suite then passed. The debug APK
+`1.0.19-debug` built and installed on `emulator-5558`. That emulator is currently
+at first-run provider setup, so add-on management focus could not be exercised
+there. These checks do not establish visual quality or real torrent playback.
| Area | Required evidence after implementation |
| --- | --- |
@@ -287,7 +298,7 @@ playback.
| Catalog requests | Tests cover selected-only loading, required/unsupported extras, stale-response cancellation, page retry retaining previous items, and explicit refresh/cache behavior. |
| Sources and series | Tests cover exact episode IDs, long episode lists, progressive providers, partial failures, retry, and rapid episode changes; user verifies the source-picker flow. |
| Navigation | User verifies player-to-title-to-browse Back behavior and retained selection, filters, scroll, and focus; automated state/navigation checks cover the same contracts where practical. |
-| Playback and subtitles | Regression tests cover HTTP headers, plugin failure/success handoff, resume identity, inline/add-on subtitles, and supported casting behavior. Real stream/torrent acceptance remains with the user. |
+| Playback and subtitles | Tests cover direct HTTP headers, invalid headers, magnet capability/routing/output policy, handoff headers, resume identity, and inline/add-on subtitles. Plugin Messenger failure/success integration and real stream/torrent acceptance remain open. |
| Database upgrade | Migration tests use populated supported historical variants and verify final schema, episode uniqueness, Xtream columns, preserved data, and foreign keys. |
| Visibility | Tests retain independent Hide Stremio Add-ons behavior and prevent content access through hidden Stremio routes. |
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 d90360a8..ab82674f 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
@@ -36,6 +36,7 @@ import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
+import androidx.compose.runtime.withFrameNanos
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
@@ -75,6 +76,12 @@ import com.streamvault.feature.stremio.R
import com.streamvault.feature.stremio.api.StremioScaffoldContent
import kotlinx.coroutines.delay
+private data class AddonFocusRestore(
+ val actionAddonId: Long,
+ val targetAddonId: Long?,
+ val expectedAddonIds: List<Long>
+)
+
@Composable
fun AddonsScreen(
scaffold: StremioScaffoldContent,
@@ -84,6 +91,39 @@ fun AddonsScreen(
) {
val state by viewModel.state.collectAsStateWithLifecycle()
var pendingRemoval by remember { mutableStateOf<AddonsViewModel.AddonEntry?>(null) }
+ var pendingFocusRestore by remember { mutableStateOf<AddonFocusRestore?>(null) }
+ val addonIds = state.addons.map { it.addon.id }
+ val addonFocusRequesters = remember(addonIds) { addonIds.associateWith { FocusRequester() } }
+ val addButtonFocusRequester = remember { FocusRequester() }
+
+ LaunchedEffect(addonIds, pendingFocusRestore, state.busyAddonIds) {
+ val request = pendingFocusRestore ?: return@LaunchedEffect
+ if (addonIds != request.expectedAddonIds) {
+ if (request.actionAddonId !in state.busyAddonIds) {
+ delay(250)
+ withFrameNanos { }
+ val fallbackRequester = addonFocusRequesters[request.actionAddonId] ?: addButtonFocusRequester
+ runCatching { fallbackRequester.requestFocus() }
+ pendingFocusRestore = null
+ }
+ return@LaunchedEffect
+ }
+ withFrameNanos { }
+ val requester = request.targetAddonId?.let(addonFocusRequesters::get) ?: addButtonFocusRequester
+ runCatching { requester.requestFocus() }
+ pendingFocusRestore = null
+ }
+
+ fun moveAddonAndRestoreFocus(entry: AddonsViewModel.AddonEntry, index: Int, offset: Int) {
+ val destination = index + offset
+ if (destination !in addonIds.indices) return
+ val expectedOrder = addonIds.toMutableList().apply {
+ val movedId = removeAt(index)
+ add(destination, movedId)
+ }
+ pendingFocusRestore = AddonFocusRestore(entry.addon.id, entry.addon.id, expectedOrder)
+ viewModel.moveAddon(entry, offset)
+ }
state.statusMessageRes?.let { messageRes ->
LaunchedEffect(messageRes) {
@@ -124,7 +164,10 @@ fun AddonsScreen(
description = stringResource(R.string.stremio_empty_description),
modifier = Modifier.weight(1f),
action = {
- TvPrimaryButton(onClick = viewModel::showInstallDialog) {
+ TvPrimaryButton(
+ onClick = viewModel::showInstallDialog,
+ modifier = Modifier.focusRequester(addButtonFocusRequester)
+ ) {
Icon(imageVector = Icons.Default.Add, contentDescription = null)
Spacer(Modifier.size(8.dp))
Text(stringResource(R.string.stremio_add))
@@ -143,7 +186,10 @@ fun AddonsScreen(
style = MaterialTheme.typography.titleMedium,
color = AppColors.TextPrimary
)
- TvPrimaryButton(onClick = viewModel::showInstallDialog) {
+ TvPrimaryButton(
+ onClick = viewModel::showInstallDialog,
+ modifier = Modifier.focusRequester(addButtonFocusRequester)
+ ) {
Icon(imageVector = Icons.Default.Add, contentDescription = null)
Spacer(Modifier.size(8.dp))
Text(stringResource(R.string.stremio_add))
@@ -160,14 +206,15 @@ fun AddonsScreen(
itemsIndexed(items = state.addons, key = { _, entry -> entry.addon.id }) { index, entry ->
AddonCard(
entry = entry,
+ detailsFocusRequester = addonFocusRequesters.getValue(entry.addon.id),
expanded = state.expandedAddonId == entry.addon.id,
refreshing = state.refreshingAddonId == entry.addon.id,
busy = entry.addon.id in state.busyAddonIds,
canMoveUp = index > 0,
canMoveDown = index < state.addons.lastIndex,
onEnabledChange = { enabled -> viewModel.setEnabled(entry, enabled) },
- onMoveUp = { viewModel.moveAddon(entry, -1) },
- onMoveDown = { viewModel.moveAddon(entry, 1) },
+ onMoveUp = { moveAddonAndRestoreFocus(entry, index, -1) },
+ onMoveDown = { moveAddonAndRestoreFocus(entry, index, 1) },
onToggleExpanded = { viewModel.toggleExpanded(entry.addon.id) },
onCatalogEnabledChange = { catalogKey, enabled ->
viewModel.setCatalogEnabled(entry, catalogKey, enabled)
@@ -208,6 +255,17 @@ fun AddonsScreen(
PremiumDialogFooterButton(
label = stringResource(R.string.stremio_remove),
onClick = {
+ val removedIndex = addonIds.indexOf(entry.addon.id)
+ val targetId = when {
+ removedIndex > 0 -> addonIds[removedIndex - 1]
+ removedIndex >= 0 -> addonIds.getOrNull(removedIndex + 1)
+ else -> null
+ }
+ pendingFocusRestore = AddonFocusRestore(
+ actionAddonId = entry.addon.id,
+ targetAddonId = targetId,
+ expectedAddonIds = addonIds.filterNot { it == entry.addon.id }
+ )
pendingRemoval = null
viewModel.removeAddon(entry)
},
@@ -269,6 +327,7 @@ private fun ContinueWatchingCard(item: StremioPlaybackHistory, onClick: () -> Un
@Composable
private fun AddonCard(
entry: AddonsViewModel.AddonEntry,
+ detailsFocusRequester: FocusRequester,
expanded: Boolean,
refreshing: Boolean,
busy: Boolean,
@@ -338,7 +397,7 @@ private fun AddonCard(
Row(modifier = Modifier.fillMaxWidth(), verticalAlignment = Alignment.CenterVertically) {
TvButton(
onClick = onToggleExpanded,
- modifier = Modifier.heightIn(min = 44.dp),
+ modifier = Modifier.heightIn(min = 44.dp).focusRequester(detailsFocusRequester),
colors = androidx.tv.material3.ButtonDefaults.colors(
containerColor = AppColors.Surface,
contentColor = AppColors.TextPrimary,
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
index ff334ab8..fe12f7b6 100644
--- 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
@@ -82,6 +82,7 @@ internal fun StremioCatalogBrowseContent(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
+ StremioCatalogSelectionNoticeMessage(state.selectionNotice)
val message = when (state.emptyReason) {
StremioBrowseEmptyReason.NO_INSTALLED_ADDONS -> R.string.stremio_browse_no_installed_addons
StremioBrowseEmptyReason.NO_ENABLED_ADDONS -> R.string.stremio_browse_no_enabled_addons
@@ -100,6 +101,7 @@ internal fun StremioCatalogBrowseContent(
horizontalAlignment = Alignment.CenterHorizontally,
verticalArrangement = Arrangement.Center
) {
+ StremioCatalogSelectionNoticeMessage(state.selectionNotice)
Text(stringResource(R.string.stremio_no_supported_catalogs), color = AppColors.TextSecondary)
Spacer(Modifier.height(12.dp))
TvButton(onClick = onManageAddons) { Text(stringResource(R.string.stremio_manage_addons)) }
@@ -148,6 +150,8 @@ internal fun StremioCatalogBrowseContent(
}
}
+ StremioCatalogSelectionNoticeMessage(state.selectionNotice)
+
if (selected.supportsSearch) {
SearchInput(
value = selected.search,
@@ -396,6 +400,16 @@ private fun CatalogMetaCard(
}
}
+@Composable
+private fun StremioCatalogSelectionNoticeMessage(notice: StremioCatalogSelectionNotice?) {
+ val message = when (notice) {
+ StremioCatalogSelectionNotice.ADDON_UNAVAILABLE -> R.string.stremio_selected_addon_unavailable
+ StremioCatalogSelectionNotice.CATALOG_UNAVAILABLE -> R.string.stremio_selected_catalog_unavailable
+ null -> null
+ }
+ message?.let { CatalogMessage(message = stringResource(it)) }
+}
+
@Composable
private fun CatalogMessage(message: String, error: Boolean = false) {
Row(
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
index dc6e6888..604329f6 100644
--- 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
@@ -68,10 +68,13 @@ data class StremioCatalogRowState(
enum class StremioBrowseEmptyReason { NO_INSTALLED_ADDONS, NO_ENABLED_ADDONS, NO_ENABLED_CATALOGS }
+enum class StremioCatalogSelectionNotice { ADDON_UNAVAILABLE, CATALOG_UNAVAILABLE }
+
data class StremioCatalogBrowseState(
val loading: Boolean = true,
val rows: List<StremioCatalogRowState> = emptyList(),
val selectedCatalogKey: StremioCatalogRowKey? = null,
+ val selectionNotice: StremioCatalogSelectionNotice? = null,
val emptyReason: StremioBrowseEmptyReason? = null,
val loadError: String? = null
)
@@ -185,9 +188,23 @@ class StremioCatalogBrowseViewModel @Inject constructor(
pageCache.removeCatalog(old.addonFingerprint, old.catalog.settingsKey)
}
}
- val selectedKey = _state.value.selectedCatalogKey
- ?.takeIf { key -> rows.any { it.key == key } }
+ val previousSelectedKey = _state.value.selectedCatalogKey
+ val previousSelectionUnavailable = previousSelectedKey != null &&
+ rows.none { it.key == previousSelectedKey && it.blockedReason == null }
+ val selectedKey = previousSelectedKey
+ ?.takeIf { key -> rows.any { it.key == key && it.blockedReason == null } }
?: rows.firstOrNull { it.blockedReason == null }?.key
+ ?: rows.firstOrNull()?.key
+ val selectionNotice = if (previousSelectionUnavailable) {
+ val originAddon = addons.firstOrNull { it.id == previousSelectedKey?.addonId }
+ if (originAddon == null || !originAddon.enabled) {
+ StremioCatalogSelectionNotice.ADDON_UNAVAILABLE
+ } else {
+ StremioCatalogSelectionNotice.CATALOG_UNAVAILABLE
+ }
+ } else {
+ _state.value.selectionNotice
+ }
val emptyReason = when {
addons.isEmpty() -> StremioBrowseEmptyReason.NO_INSTALLED_ADDONS
addons.none { it.enabled } -> StremioBrowseEmptyReason.NO_ENABLED_ADDONS
@@ -198,6 +215,7 @@ class StremioCatalogBrowseViewModel @Inject constructor(
loading = false,
rows = rows,
selectedCatalogKey = selectedKey,
+ selectionNotice = selectionNotice,
emptyReason = emptyReason
)
selectedKey?.let { key ->
@@ -212,7 +230,7 @@ class StremioCatalogBrowseViewModel @Inject constructor(
fun selectCatalog(key: StremioCatalogRowKey) {
val row = _state.value.rows.firstOrNull { it.key == key } ?: return
- _state.update { it.copy(selectedCatalogKey = key) }
+ _state.update { it.copy(selectedCatalogKey = key, selectionNotice = null) }
if (row.blockedReason == null && row.pageCount == 0 && !row.loading && row.error == null) {
startRequest(key, reset = true, debounceMs = 0L)
}
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
index 84757c27..3f157275 100644
--- 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
@@ -547,7 +547,7 @@ private fun unsupportedStreamLabel(
return stringResource(stringRes)
}
-private fun buildHandoff(
+internal fun buildHandoff(
state: StremioItemDetailState,
streamOriginKey: String,
stream: StremioStream,
diff --git a/feature/stremio/src/main/res/values/strings.xml b/feature/stremio/src/main/res/values/strings.xml
index 6c90a6d4..f3f24dd3 100644
--- a/feature/stremio/src/main/res/values/strings.xml
+++ b/feature/stremio/src/main/res/values/strings.xml
@@ -49,6 +49,8 @@
<string name="stremio_browse_no_installed_addons">No Stremio add-ons are installed yet.</string>
<string name="stremio_browse_no_enabled_addons">All Stremio add-ons are disabled. Enable one to browse its catalogs.</string>
<string name="stremio_browse_no_enabled_catalogs">There are no enabled catalogs. Enable a catalog in add-on details to browse.</string>
+ <string name="stremio_selected_addon_unavailable">The selected add-on was disabled or removed. Choose another catalog or manage add-ons.</string>
+ <string name="stremio_selected_catalog_unavailable">The selected catalog was disabled or removed. Choose another catalog.</string>
<string name="stremio_catalog_updating_previous_results">Updating this catalog. Showing the previous results until the new search finishes.</string>
<string name="stremio_catalog_previous_results_label">Showing results for the previous search.</string>
<string name="stremio_catalog_refreshing_previous_results">Refreshing this catalog. Showing the current results until refresh finishes.</string>
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
index 55972b7e..5857acfa 100644
--- 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
@@ -313,6 +313,76 @@ class StremioCatalogBrowseViewModelTest {
assertThat(repository.calls.map { it.addonId }).containsExactly(1L)
}
+ @Test
+ fun `disabling the selected addon selects another catalog and explains the change`() = runTest(dispatcher) {
+ val catalog = catalogWithSkip()
+ val repository = CatalogRepositoryFake(catalog)
+ val firstAddon = addon(id = 1L, enabled = true)
+ val secondAddon = addon(id = 2L, enabled = true)
+ repository.addons.value = listOf(firstAddon, secondAddon)
+ repository.manifests[1L] = manifest(catalog).copy(name = "First")
+ repository.manifests[2L] = manifest(catalog).copy(name = "Second")
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+ val secondKey = viewModel.state.value.rows.single { it.key.addonId == secondAddon.id }.key
+ viewModel.selectCatalog(secondKey)
+ advanceUntilIdle()
+
+ repository.addons.value = listOf(firstAddon, secondAddon.copy(enabled = false))
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.selectedCatalogKey?.addonId).isEqualTo(firstAddon.id)
+ assertThat(viewModel.state.value.selectionNotice)
+ .isEqualTo(StremioCatalogSelectionNotice.ADDON_UNAVAILABLE)
+ }
+
+ @Test
+ fun `removing the selected addon selects another catalog and explains the change`() = runTest(dispatcher) {
+ val catalog = catalogWithSkip()
+ val repository = CatalogRepositoryFake(catalog)
+ val firstAddon = addon(id = 1L, enabled = true)
+ val secondAddon = addon(id = 2L, enabled = true)
+ repository.addons.value = listOf(firstAddon, secondAddon)
+ repository.manifests[1L] = manifest(catalog).copy(name = "First")
+ repository.manifests[2L] = manifest(catalog).copy(name = "Second")
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+ val secondKey = viewModel.state.value.rows.single { it.key.addonId == secondAddon.id }.key
+ viewModel.selectCatalog(secondKey)
+ advanceUntilIdle()
+
+ repository.addons.value = listOf(firstAddon)
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.selectedCatalogKey?.addonId).isEqualTo(firstAddon.id)
+ assertThat(viewModel.state.value.selectionNotice)
+ .isEqualTo(StremioCatalogSelectionNotice.ADDON_UNAVAILABLE)
+ }
+
+ @Test
+ fun `disabling selected catalog selects another catalog and explains the change`() = runTest(dispatcher) {
+ val firstCatalog = catalogWithSkip()
+ val secondCatalog = firstCatalog.copy(id = "recent", name = "Recently Added")
+ val repository = CatalogRepositoryFake(firstCatalog)
+ val catalogSettings = mapOf("movie:top" to true, "movie:recent" to true)
+ repository.addons.value = listOf(addon(1L, enabled = true).copy(catalogSettings = catalogSettings))
+ repository.manifests[1L] = manifest(firstCatalog).copy(catalogs = listOf(firstCatalog, secondCatalog))
+ val viewModel = StremioCatalogBrowseViewModel(repository, FakeStremioContentAccess())
+ advanceUntilIdle()
+ val secondKey = viewModel.state.value.rows.single { it.catalog.id == "recent" }.key
+ viewModel.selectCatalog(secondKey)
+ advanceUntilIdle()
+
+ repository.addons.value = listOf(
+ addon(1L, enabled = true).copy(catalogSettings = catalogSettings + ("movie:recent" to false))
+ )
+ advanceUntilIdle()
+
+ assertThat(viewModel.state.value.selectedCatalogKey?.catalogKey).isEqualTo("movie:top")
+ assertThat(viewModel.state.value.selectionNotice)
+ .isEqualTo(StremioCatalogSelectionNotice.CATALOG_UNAVAILABLE)
+ }
+
@Test
fun `hidden Stremio does not fetch addon catalog pages`() = runTest(dispatcher) {
val repository = CatalogRepositoryFake(catalogWithSkip())
diff --git a/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioPlaybackHandoffTest.kt b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioPlaybackHandoffTest.kt
new file mode 100644
index 00000000..aa5d3c85
--- /dev/null
+++ b/feature/stremio/src/test/java/com/streamvault/feature/stremio/presentation/StremioPlaybackHandoffTest.kt
@@ -0,0 +1,70 @@
+package com.streamvault.feature.stremio.presentation
+
+import com.google.common.truth.Truth.assertThat
+import com.streamvault.core.navigation.StremioSubtitlePlaybackSource
+import com.streamvault.domain.model.stremio.StremioMediaType
+import com.streamvault.domain.model.stremio.StremioMetaPreview
+import com.streamvault.domain.model.stremio.StremioStream
+import com.streamvault.domain.model.stremio.StremioStreamBehaviorHints
+import com.streamvault.domain.model.stremio.StremioProxyHeaders
+import com.streamvault.domain.model.stremio.StremioSubtitle
+import org.junit.Test
+
+class StremioPlaybackHandoffTest {
+ @Test
+ fun `player handoff retains scoped headers and inline subtitles`() {
+ val subtitles = listOf(
+ StremioSubtitle("https://subs.example/en.vtt", "eng", "english"),
+ StremioSubtitle("https://subs.example/es.vtt", "spa", "spanish")
+ )
+ val state = StremioItemDetailState(
+ preview = StremioMetaPreview(
+ id = "tt123",
+ type = StremioMediaType.MOVIE,
+ name = "Example Movie"
+ ),
+ catalogOriginAddonId = 11L,
+ catalogOriginKey = "catalog-origin"
+ )
+ val stream = StremioStream(
+ url = "https://media.example/movie.mp4",
+ subtitles = subtitles,
+ behaviorHints = StremioStreamBehaviorHints(
+ proxyHeaders = StremioProxyHeaders(request = mapOf("Authorization" to "Bearer token"))
+ )
+ )
+
+ val handoff = requireNotNull(buildHandoff(state, "stream-origin", stream, "tt123"))
+
+ assertThat(handoff.mediaRequestHeaders).containsEntry("Authorization", "Bearer token")
+ assertThat(handoff.inlineSubtitles).containsExactly(
+ StremioSubtitlePlaybackSource("https://subs.example/en.vtt", "eng", "english"),
+ StremioSubtitlePlaybackSource("https://subs.example/es.vtt", "spa", "spanish")
+ ).inOrder()
+ assertThat(handoff.reference.exactVideoId).isEqualTo("tt123")
+ assertThat(handoff.reference.streamOriginKey).isEqualTo("stream-origin")
+ }
+
+ @Test
+ fun `series player handoff preserves the exact episode identity`() {
+ val state = StremioItemDetailState(
+ preview = StremioMetaPreview(
+ id = "series-id",
+ type = StremioMediaType.SERIES,
+ name = "Example Series"
+ ),
+ catalogOriginAddonId = 11L,
+ catalogOriginKey = "catalog-origin"
+ )
+
+ val handoff = requireNotNull(buildHandoff(
+ state,
+ "stream-origin",
+ StremioStream(url = "https://media.example/episode.mp4"),
+ "episode:vendor-id:season-02:episode-04"
+ ))
+
+ assertThat(handoff.reference.exactVideoId).isEqualTo("episode:vendor-id:season-02:episode-04")
+ assertThat(handoff.reference.parentSeriesId).isEqualTo("series-id")
+ }
+}