Skip to content

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

Add APK companion plugin framework

Jorge Ceballos72f27a5da400
diff --git a/app/build.gradle.kts b/app/build.gradle.kts
index dbd2b7c8..6955c7b2 100644
--- a/app/build.gradle.kts
+++ b/app/build.gradle.kts
@@ -7,6 +7,7 @@ plugins {
alias(libs.plugins.android.application)
alias(libs.plugins.kotlin.android)
alias(libs.plugins.kotlin.compose)
+ alias(libs.plugins.kotlin.serialization)
alias(libs.plugins.ksp)
alias(libs.plugins.hilt)
alias(libs.plugins.kover)
diff --git a/app/src/main/java/com/streamvault/app/MainActivity.kt b/app/src/main/java/com/streamvault/app/MainActivity.kt
index e0cdbcc1..33666866 100644
--- a/app/src/main/java/com/streamvault/app/MainActivity.kt
+++ b/app/src/main/java/com/streamvault/app/MainActivity.kt
@@ -40,6 +40,8 @@ import android.content.res.Configuration
import android.text.TextUtils
import android.view.View
import androidx.core.view.WindowCompat
+import androidx.core.view.WindowInsetsCompat
+import androidx.core.view.WindowInsetsControllerCompat
import java.util.Locale
import android.content.Context
import android.content.ContextWrapper
@@ -107,6 +109,7 @@ class MainActivity : ComponentActivity() {
// This fixes keyboard-covers-input-field on API 30+ where adjustResize is
// ignored when the theme sets windowFullscreen=true.
WindowCompat.setDecorFitsSystemWindows(window, false)
+ applyImmersiveSystemUi()
_pictureInPictureModeFlow.value = isInPictureInPictureMode
handleExternalIntent(intent)
if (isTelevisionDevice()) {
@@ -167,6 +170,18 @@ class MainActivity : ComponentActivity() {
}
}
+ override fun onResume() {
+ super.onResume()
+ applyImmersiveSystemUi()
+ }
+
+ override fun onWindowFocusChanged(hasFocus: Boolean) {
+ super.onWindowFocusChanged(hasFocus)
+ if (hasFocus) {
+ applyImmersiveSystemUi()
+ }
+ }
+
override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
setIntent(intent)
@@ -220,6 +235,24 @@ class MainActivity : ComponentActivity() {
return enterPlayerPictureInPictureModeIfEligible(requirePlaying = false)
}
+ @Suppress("DEPRECATION")
+ private fun applyImmersiveSystemUi() {
+ val decorView = window.decorView
+ decorView.systemUiVisibility = (
+ View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
+ or View.SYSTEM_UI_FLAG_LAYOUT_STABLE
+ or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
+ or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
+ or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
+ or View.SYSTEM_UI_FLAG_FULLSCREEN
+ )
+ WindowCompat.getInsetsController(window, decorView).apply {
+ systemBarsBehavior =
+ WindowInsetsControllerCompat.BEHAVIOR_SHOW_TRANSIENT_BARS_BY_SWIPE
+ hide(WindowInsetsCompat.Type.systemBars())
+ }
+ }
+
fun openCastRouteChooser() {
startActivity(Intent(this, CastRouteChooserActivity::class.java))
}
diff --git a/app/src/main/java/com/streamvault/app/plugins/PluginModels.kt b/app/src/main/java/com/streamvault/app/plugins/PluginModels.kt
index 0453856d..83a74bf8 100644
--- a/app/src/main/java/com/streamvault/app/plugins/PluginModels.kt
+++ b/app/src/main/java/com/streamvault/app/plugins/PluginModels.kt
@@ -2,6 +2,8 @@ package com.streamvault.app.plugins
import kotlinx.serialization.SerialName
import kotlinx.serialization.Serializable
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
@Serializable
data class StreamVaultPluginManifest(
@@ -12,10 +14,15 @@ data class StreamVaultPluginManifest(
val versionCode: Long = 0L,
val description: String = "",
val capabilities: List<String> = emptyList(),
+ val configurationMode: String? = null,
val configurationActivityAction: String? = null,
val providerName: String? = null
) {
fun hasCapability(capability: String): Boolean = capability in capabilities
+
+ val supportsHostRenderedConfiguration: Boolean
+ get() = hasCapability(StreamVaultPluginContract.CAPABILITY_CONFIGURATION_SCHEMA) ||
+ configurationMode == StreamVaultPluginContract.CONFIGURATION_MODE_HOST_SCHEMA
}
data class InstalledStreamVaultPlugin(
@@ -35,3 +42,69 @@ data class PluginActionResult(
val success: Boolean,
val message: String
)
+
+data class PluginConfigurationSnapshot(
+ val plugin: InstalledStreamVaultPlugin,
+ val schema: PluginConfigurationSchema,
+ val values: JsonObject
+)
+
+@Serializable
+data class PluginConfigurationSchema(
+ val schemaVersion: Int = 1,
+ val title: String = "",
+ val description: String = "",
+ val sections: List<PluginConfigurationSection> = emptyList(),
+ val actions: List<PluginConfigurationAction> = emptyList()
+)
+
+@Serializable
+data class PluginConfigurationSection(
+ val id: String,
+ val title: String,
+ val description: String = "",
+ val fields: List<PluginConfigurationField> = emptyList()
+)
+
+@Serializable
+data class PluginConfigurationField(
+ val key: String,
+ val type: String = TYPE_TEXT,
+ val label: String,
+ val description: String = "",
+ val placeholder: String = "",
+ val required: Boolean = false,
+ val readOnly: Boolean = false,
+ val secret: Boolean = false,
+ val defaultValue: JsonElement? = null,
+ val options: List<PluginConfigurationOption> = emptyList(),
+ val min: Double? = null,
+ val max: Double? = null
+) {
+ companion object {
+ const val TYPE_INFO = "info"
+ const val TYPE_TEXT = "text"
+ const val TYPE_PASSWORD = "password"
+ const val TYPE_URL = "url"
+ const val TYPE_NUMBER = "number"
+ const val TYPE_BOOLEAN = "boolean"
+ const val TYPE_SELECT = "select"
+ const val TYPE_TEXTAREA = "textarea"
+ }
+}
+
+@Serializable
+data class PluginConfigurationOption(
+ val value: String,
+ val label: String,
+ val description: String = ""
+)
+
+@Serializable
+data class PluginConfigurationAction(
+ val id: String,
+ val label: String,
+ val description: String = "",
+ val destructive: Boolean = false,
+ val refreshAfterRun: Boolean = true
+)
diff --git a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginContract.kt b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginContract.kt
index ebbcaf84..6fc32ca9 100644
--- a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginContract.kt
+++ b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginContract.kt
@@ -11,6 +11,7 @@ object StreamVaultPluginContract {
const val META_VERSION_CODE = "com.streamvault.plugin.VERSION_CODE"
const val META_DESCRIPTION = "com.streamvault.plugin.DESCRIPTION"
const val META_CAPABILITIES = "com.streamvault.plugin.CAPABILITIES"
+ const val META_CONFIGURATION_MODE = "com.streamvault.plugin.CONFIGURATION_MODE"
const val META_CONFIGURATION_ACTIVITY_ACTION = "com.streamvault.plugin.CONFIGURATION_ACTIVITY_ACTION"
const val META_PROVIDER_NAME = "com.streamvault.plugin.PROVIDER_NAME"
@@ -20,6 +21,10 @@ object StreamVaultPluginContract {
const val MSG_GET_PROVIDER_URL = 4
const val MSG_PREPARE_PLAYBACK = 5
const val MSG_REWRITE_CAST_URL = 6
+ const val MSG_GET_CONFIGURATION_SCHEMA = 7
+ const val MSG_GET_CONFIGURATION_VALUES = 8
+ const val MSG_SET_CONFIGURATION_VALUES = 9
+ const val MSG_RUN_CONFIGURATION_ACTION = 10
const val KEY_API_VERSION = "api_version"
const val KEY_REQUEST_ID = "request_id"
@@ -33,9 +38,17 @@ object StreamVaultPluginContract {
const val KEY_PROVIDER_NAME = "provider_name"
const val KEY_INPUT_URL = "input_url"
const val KEY_OUTPUT_URL = "output_url"
+ const val KEY_CONFIGURATION_SCHEMA_JSON = "configuration_schema_json"
+ const val KEY_CONFIGURATION_VALUES_JSON = "configuration_values_json"
+ const val KEY_CONFIGURATION_ACTION_ID = "configuration_action_id"
+ const val KEY_CONFIGURATION_ERRORS_JSON = "configuration_errors_json"
const val CAPABILITY_PROVIDER_M3U = "provider.m3u"
const val CAPABILITY_PLAYBACK_PREPARE = "playback.prepare"
const val CAPABILITY_CAST_REWRITE_URL = "cast.rewriteUrl"
+ const val CAPABILITY_CONFIGURATION_SCHEMA = "configuration.schema"
const val CAPABILITY_CONFIGURATION_ACTIVITY = "configuration.activity"
+
+ const val CONFIGURATION_MODE_HOST_SCHEMA = "host.schema"
+ const val CONFIGURATION_MODE_ACTIVITY = "activity"
}
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 557bf89a..31759760 100644
--- a/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt
+++ b/app/src/main/java/com/streamvault/app/plugins/StreamVaultPluginManager.kt
@@ -30,6 +30,7 @@ import kotlinx.coroutines.flow.first
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import kotlinx.serialization.json.Json
+import kotlinx.serialization.json.JsonObject
import okhttp3.OkHttpClient
import okhttp3.Request
@@ -144,6 +145,117 @@ class StreamVaultPluginManager @Inject constructor(
}
}
+ suspend fun loadPluginConfiguration(plugin: InstalledStreamVaultPlugin): Result<PluginConfigurationSnapshot> =
+ withContext(Dispatchers.IO) {
+ if (!plugin.manifest.supportsHostRenderedConfiguration) {
+ return@withContext Result.error("This plugin does not expose a StreamVault configuration schema")
+ }
+
+ val schemaResponse = runCatching {
+ messengerClient.send(
+ packageName = plugin.packageName,
+ serviceClassName = plugin.serviceClassName,
+ what = StreamVaultPluginContract.MSG_GET_CONFIGURATION_SCHEMA,
+ timeoutMillis = 10_000L
+ )
+ }.getOrElse { error ->
+ return@withContext Result.error(error.message ?: "Plugin configuration schema is unavailable")
+ }
+ if (!schemaResponse.getBoolean(StreamVaultPluginContract.KEY_SUCCESS, false)) {
+ return@withContext Result.error(
+ schemaResponse.getString(StreamVaultPluginContract.KEY_MESSAGE).orEmpty()
+ .ifBlank { "Plugin configuration schema is unavailable" }
+ )
+ }
+
+ val schemaJson = schemaResponse
+ .getString(StreamVaultPluginContract.KEY_CONFIGURATION_SCHEMA_JSON)
+ .orEmpty()
+ val schema = runCatching { json.decodeFromString<PluginConfigurationSchema>(schemaJson) }
+ .getOrElse { error ->
+ return@withContext Result.error(error.message ?: "Plugin configuration schema is invalid")
+ }
+ if (schema.sections.isEmpty() && schema.actions.isEmpty()) {
+ return@withContext Result.error("Plugin configuration schema is empty")
+ }
+
+ val values = loadPluginConfigurationValues(plugin).getOrNull() ?: JsonObject(emptyMap())
+ Result.success(PluginConfigurationSnapshot(plugin, schema, values))
+ }
+
+ suspend fun loadPluginConfigurationValues(plugin: InstalledStreamVaultPlugin): Result<JsonObject> =
+ withContext(Dispatchers.IO) {
+ val valuesResponse = runCatching {
+ messengerClient.send(
+ packageName = plugin.packageName,
+ serviceClassName = plugin.serviceClassName,
+ what = StreamVaultPluginContract.MSG_GET_CONFIGURATION_VALUES,
+ timeoutMillis = 10_000L
+ )
+ }.getOrElse { error ->
+ return@withContext Result.error(error.message ?: "Plugin configuration values are unavailable")
+ }
+ if (!valuesResponse.getBoolean(StreamVaultPluginContract.KEY_SUCCESS, false)) {
+ return@withContext Result.error(
+ valuesResponse.getString(StreamVaultPluginContract.KEY_MESSAGE).orEmpty()
+ .ifBlank { "Plugin configuration values are unavailable" }
+ )
+ }
+
+ val valuesJson = valuesResponse
+ .getString(StreamVaultPluginContract.KEY_CONFIGURATION_VALUES_JSON)
+ .orEmpty()
+ val values = if (valuesJson.isBlank()) {
+ JsonObject(emptyMap())
+ } else {
+ runCatching { json.decodeFromString<JsonObject>(valuesJson) }
+ .getOrElse { error ->
+ return@withContext Result.error(error.message ?: "Plugin configuration values are invalid")
+ }
+ }
+ Result.success(values)
+ }
+
+ suspend fun savePluginConfiguration(
+ plugin: InstalledStreamVaultPlugin,
+ valuesJson: String
+ ): PluginActionResult = withContext(Dispatchers.IO) {
+ val response = runCatching {
+ messengerClient.send(
+ packageName = plugin.packageName,
+ serviceClassName = plugin.serviceClassName,
+ what = StreamVaultPluginContract.MSG_SET_CONFIGURATION_VALUES,
+ data = Bundle().apply {
+ putString(StreamVaultPluginContract.KEY_CONFIGURATION_VALUES_JSON, valuesJson)
+ },
+ timeoutMillis = 60_000L
+ )
+ }.getOrElse { error ->
+ return@withContext PluginActionResult(false, error.message ?: "Plugin settings could not be saved")
+ }
+ response.toPluginActionResult("Plugin settings saved")
+ }
+
+ suspend fun runPluginConfigurationAction(
+ plugin: InstalledStreamVaultPlugin,
+ actionId: String
+ ): PluginActionResult = withContext(Dispatchers.IO) {
+ val response = runCatching {
+ messengerClient.send(
+ packageName = plugin.packageName,
+ serviceClassName = plugin.serviceClassName,
+ what = StreamVaultPluginContract.MSG_RUN_CONFIGURATION_ACTION,
+ data = Bundle().apply {
+ putString(StreamVaultPluginContract.KEY_CONFIGURATION_ACTION_ID, actionId)
+ },
+ timeoutMillis = 120_000L
+ )
+ }.getOrElse { error ->
+ return@withContext PluginActionResult(false, error.message ?: "Plugin action failed")
+ }
+ response.toPluginActionResult("Plugin action completed")
+ }
+
suspend fun preparePlaybackUrl(url: String): Result<Unit> = withContext(Dispatchers.IO) {
if (url.isBlank()) return@withContext Result.success(Unit)
val plugins = discoverPlugins()
@@ -383,6 +495,8 @@ class StreamVaultPluginManager @Inject constructor(
versionCode = metaData.metaLong(StreamVaultPluginContract.META_VERSION_CODE),
description = metaData.metaString(StreamVaultPluginContract.META_DESCRIPTION),
capabilities = metaData.metaCsv(StreamVaultPluginContract.META_CAPABILITIES),
+ configurationMode = metaData.metaString(StreamVaultPluginContract.META_CONFIGURATION_MODE)
+ .takeIf { it.isNotBlank() },
configurationActivityAction = metaData
.metaString(StreamVaultPluginContract.META_CONFIGURATION_ACTIVITY_ACTION)
.takeIf { it.isNotBlank() },
@@ -481,3 +595,12 @@ private fun Bundle.metaCsv(key: String): List<String> =
.split(',')
.map { it.trim() }
.filter { it.isNotBlank() }
+
+private fun Bundle.toPluginActionResult(successMessage: String): PluginActionResult {
+ val success = getBoolean(StreamVaultPluginContract.KEY_SUCCESS, false)
+ return PluginActionResult(
+ success = success,
+ message = getString(StreamVaultPluginContract.KEY_MESSAGE).orEmpty()
+ .ifBlank { if (success) successMessage else "Plugin operation failed" }
+ )
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
index bf4dad85..e9dfa8e2 100644
--- a/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
+++ b/app/src/main/java/com/streamvault/app/ui/components/shell/AppShell.kt
@@ -46,8 +46,10 @@ import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.zIndex
import androidx.compose.ui.graphics.Brush
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.graphics.SolidColor
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.graphics.vector.ImageVector
+import androidx.compose.ui.graphics.vector.path
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.semantics.LiveRegionMode
import androidx.compose.ui.semantics.heading
@@ -775,7 +777,7 @@ private fun RailButton(
private data class DestinationItem(
val route: String,
- @StringRes val labelRes: Int,
+ @param:StringRes val labelRes: Int,
val icon: ImageVector
)
@@ -795,6 +797,39 @@ private fun buildDestinationItems(): List<DestinationItem> = listOf(
DestinationItem(Routes.SERIES, R.string.nav_series, Icons.Default.Menu),
DestinationItem(Routes.EPG, R.string.nav_epg, Icons.Default.Info),
DestinationItem(Routes.SEARCH, R.string.search_title, Icons.Default.Search),
- DestinationItem(Routes.PLUGINS, R.string.nav_plugins, Icons.Default.Settings),
+ DestinationItem(Routes.PLUGINS, R.string.nav_plugins, PluginBlocksIcon),
DestinationItem(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/java/com/streamvault/app/ui/interaction/MouseSupport.kt b/app/src/main/java/com/streamvault/app/ui/interaction/MouseSupport.kt
index 3ff52366..9b094254 100644
--- a/app/src/main/java/com/streamvault/app/ui/interaction/MouseSupport.kt
+++ b/app/src/main/java/com/streamvault/app/ui/interaction/MouseSupport.kt
@@ -33,12 +33,13 @@ fun Modifier.mouseClickable(
): Modifier = composed {
val context = LocalContext.current
val isTv = remember(context) { context.isTelevisionDevice() }
- var pressedFromMouse by remember { mutableStateOf(false) }
+ var pressedFromPointer by remember { mutableStateOf(false) }
if (!isTv) {
- // Phone / tablet path: intercept touch so the first tap fires the action without
- // needing the TV Surface's "focus first, then click on second tap" behaviour.
- if (enabled) {
+ if (!enabled) {
+ this
+ } else if (onLongClick != null) {
+ // Phone / tablet path with long-press support.
this.pointerInput(onClick, onLongClick) {
detectTapGestures(
onTap = { _ -> onClick() },
@@ -46,7 +47,30 @@ fun Modifier.mouseClickable(
)
}
} else {
- this
+ // Phone / tablet path for simple clicks. Interop receives the raw
+ // down/up pair before TV Material's focus-first touch handling.
+ this.pointerInteropFilter { event ->
+ when (event.actionMasked) {
+ MotionEvent.ACTION_DOWN,
+ MotionEvent.ACTION_BUTTON_PRESS -> {
+ pressedFromPointer = true
+ focusRequester?.requestFocus()
+ true
+ }
+ MotionEvent.ACTION_UP,
+ MotionEvent.ACTION_BUTTON_RELEASE -> {
+ val shouldClick = pressedFromPointer
+ pressedFromPointer = false
+ if (shouldClick) onClick()
+ shouldClick
+ }
+ MotionEvent.ACTION_CANCEL -> {
+ pressedFromPointer = false
+ false
+ }
+ else -> false
+ }
+ }
}
} else {
// TV path: existing mouse / pointer-device interop filter.
@@ -55,19 +79,19 @@ fun Modifier.mouseClickable(
when (event.actionMasked) {
MotionEvent.ACTION_DOWN,
MotionEvent.ACTION_BUTTON_PRESS -> {
- pressedFromMouse = true
+ pressedFromPointer = true
focusRequester?.requestFocus()
true
}
MotionEvent.ACTION_UP,
MotionEvent.ACTION_BUTTON_RELEASE -> {
- val shouldClick = pressedFromMouse
- pressedFromMouse = false
+ val shouldClick = pressedFromPointer
+ pressedFromPointer = false
if (shouldClick) onClick()
shouldClick
}
MotionEvent.ACTION_CANCEL -> {
- pressedFromMouse = false
+ pressedFromPointer = false
false
}
else -> false
diff --git a/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt b/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt
index 9ad4f6a8..385ec1d5 100644
--- a/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt
+++ b/app/src/main/java/com/streamvault/app/ui/interaction/TvComponents.kt
@@ -1,11 +1,13 @@
package com.streamvault.app.ui.interaction
+import android.view.KeyEvent
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.BoxScope
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.RowScope
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
+import androidx.compose.ui.input.key.onPreviewKeyEvent
import androidx.tv.material3.Border
import androidx.tv.material3.Button
import androidx.tv.material3.ButtonBorder
@@ -46,7 +48,9 @@ fun TvClickableSurface(
Surface(
onClick = onClick,
onLongClick = onLongClick,
- modifier = modifier.mouseClickable(onClick = onClick, enabled = enabled, onLongClick = onLongClick),
+ modifier = modifier
+ .activateOnRemoteKey(enabled = enabled, onClick = onClick)
+ .mouseClickable(onClick = onClick, enabled = enabled, onLongClick = onLongClick),
enabled = enabled,
shape = shape,
colors = colors,
@@ -78,7 +82,9 @@ fun TvButton(
) {
Button(
onClick = onClick,
- modifier = modifier.mouseClickable(onClick = onClick, enabled = enabled),
+ modifier = modifier
+ .activateOnRemoteKey(enabled = enabled, onClick = onClick)
+ .mouseClickable(onClick = onClick, enabled = enabled),
enabled = enabled,
scale = scale,
glow = glow,
@@ -112,7 +118,9 @@ fun TvIconButton(
IconButton(
onClick = onClick,
onLongClick = onLongClick,
- modifier = modifier.mouseClickable(onClick = onClick, enabled = enabled),
+ modifier = modifier
+ .activateOnRemoteKey(enabled = enabled, onClick = onClick)
+ .mouseClickable(onClick = onClick, enabled = enabled),
enabled = enabled,
scale = scale,
glow = glow,
@@ -123,3 +131,24 @@ fun TvIconButton(
content = content,
)
}
+
+private fun Modifier.activateOnRemoteKey(
+ enabled: Boolean,
+ onClick: () -> Unit
+): Modifier = onPreviewKeyEvent { event ->
+ if (!enabled) return@onPreviewKeyEvent false
+ val nativeEvent = event.nativeKeyEvent
+ val isActivationKey = when (nativeEvent.keyCode) {
+ KeyEvent.KEYCODE_DPAD_CENTER,
+ KeyEvent.KEYCODE_ENTER,
+ KeyEvent.KEYCODE_NUMPAD_ENTER,
+ KeyEvent.KEYCODE_SPACE,
+ KeyEvent.KEYCODE_BUTTON_A -> true
+ else -> false
+ }
+ if (!isActivationKey) return@onPreviewKeyEvent false
+ if (nativeEvent.action == KeyEvent.ACTION_UP) {
+ onClick()
+ }
+ nativeEvent.action == KeyEvent.ACTION_DOWN || nativeEvent.action == KeyEvent.ACTION_UP
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsScreen.kt b/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsScreen.kt
index 9f259b25..a731cb32 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsScreen.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsScreen.kt
@@ -2,17 +2,24 @@ package com.streamvault.app.ui.screens.plugins
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
+import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
+import androidx.compose.foundation.horizontalScroll
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.RowScope
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.heightIn
import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.layout.widthIn
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.OutlinedTextFieldDefaults
@@ -22,24 +29,40 @@ import androidx.compose.material3.Switch
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.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
+import androidx.compose.ui.text.input.KeyboardType
+import androidx.compose.ui.text.input.PasswordVisualTransformation
+import androidx.compose.ui.text.input.VisualTransformation
+import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.lifecycle.viewmodel.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
+import androidx.tv.material3.Border
+import androidx.tv.material3.ButtonDefaults
import androidx.tv.material3.MaterialTheme
import androidx.tv.material3.Text
import com.streamvault.app.navigation.Routes
import com.streamvault.app.plugins.InstalledStreamVaultPlugin
+import com.streamvault.app.plugins.PluginConfigurationAction
+import com.streamvault.app.plugins.PluginConfigurationField
+import com.streamvault.app.plugins.PluginConfigurationSection
import com.streamvault.app.plugins.StreamVaultPluginContract
import com.streamvault.app.ui.components.shell.AppNavigationChrome
import com.streamvault.app.ui.components.shell.AppScreenScaffold
import com.streamvault.app.ui.components.shell.StatusPill
import com.streamvault.app.ui.design.AppColors
+import com.streamvault.app.ui.design.FocusSpec
import com.streamvault.app.ui.interaction.TvButton
+import com.streamvault.app.ui.theme.FocusBorder
+import com.streamvault.app.ui.theme.OnSurface
+import com.streamvault.app.ui.theme.Primary
@Composable
fun PluginsScreen(
@@ -74,59 +97,127 @@ fun PluginsScreen(
modifier = Modifier.fillMaxSize(),
verticalArrangement = Arrangement.spacedBy(12.dp)
) {
- PluginInstallPanel(
- installUrl = uiState.installUrl,
- isInstalling = uiState.isInstalling,
- onInstallUrlChange = viewModel::updateInstallUrl,
- onInstallFromUrl = viewModel::installFromUrl,
- onInstallFromFile = {
- apkPicker.launch(
- arrayOf(
- "application/vnd.android.package-archive",
- "application/octet-stream",
- "*/*"
+ val configuration = uiState.configuration
+ if (configuration != null) {
+ PluginConfigurationPanel(
+ configuration = configuration,
+ onBack = viewModel::closePluginConfiguration,
+ onRefresh = viewModel::refreshPluginConfiguration,
+ onSave = viewModel::savePluginConfiguration,
+ onValueChange = viewModel::updateConfigurationValue,
+ onRunAction = viewModel::runConfigurationAction
+ )
+ } else {
+ PluginInstallPanel(
+ installUrl = uiState.installUrl,
+ isInstalling = uiState.isInstalling,
+ onInstallUrlChange = viewModel::updateInstallUrl,
+ onInstallFromUrl = viewModel::installFromUrl,
+ onInstallFromFile = {
+ apkPicker.launch(
+ arrayOf(
+ "application/vnd.android.package-archive",
+ "application/octet-stream",
+ "*/*"
+ )
)
- )
- },
- onRefresh = viewModel::refreshPlugins
- )
-
- uiState.syncProgress?.let {
- Text(
- text = it,
- style = MaterialTheme.typography.bodySmall,
- color = AppColors.Brand
+ },
+ onRefresh = viewModel::refreshPlugins
)
- }
- LazyColumn(
- modifier = Modifier.fillMaxSize(),
- 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
+ uiState.syncProgress?.let {
+ Text(
+ text = it,
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.Brand
+ )
+ }
+
+ LazyColumn(
+ modifier = Modifier.fillMaxSize(),
+ 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.manifest.id }) { plugin ->
+ PluginCard(
+ plugin = plugin,
+ busy = uiState.activePluginId == plugin.manifest.id,
+ onEnabledChange = { enabled -> viewModel.setPluginEnabled(plugin, enabled) },
+ onOpenConfiguration = { viewModel.openPluginConfiguration(plugin) }
)
}
+ item { Spacer(modifier = Modifier.height(20.dp)) }
}
- items(uiState.plugins, key = { it.manifest.id }) { plugin ->
- PluginCard(
- plugin = plugin,
- busy = uiState.activePluginId == plugin.manifest.id,
- onEnabledChange = { enabled -> viewModel.setPluginEnabled(plugin, enabled) },
- onOpenConfiguration = { viewModel.openPluginConfiguration(plugin) }
- )
- }
- item { Spacer(modifier = Modifier.height(20.dp)) }
}
}
SnackbarHost(hostState = snackbarHostState)
}
}
+private enum class PluginButtonTone {
+ Primary,
+ Secondary
+}
+
+@Composable
+private fun PluginButton(
+ onClick: () -> Unit,
+ modifier: Modifier = Modifier,
+ enabled: Boolean = true,
+ tone: PluginButtonTone = PluginButtonTone.Secondary,
+ 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
+ )
+ }
+
+ 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
+ )
+ ) {
+ content()
+ }
+}
+
@Composable
private fun PluginInstallPanel(
installUrl: String,
@@ -164,19 +255,20 @@ private fun PluginInstallPanel(
cursorColor = AppColors.Brand
)
)
- TvButton(
+ PluginButton(
enabled = !isInstalling && installUrl.isNotBlank(),
- onClick = onInstallFromUrl
+ onClick = onInstallFromUrl,
+ tone = PluginButtonTone.Primary
) {
Text("Install URL")
}
- TvButton(
+ PluginButton(
enabled = !isInstalling,
onClick = onInstallFromFile
) {
Text("Install file")
}
- TvButton(onClick = onRefresh) {
+ PluginButton(onClick = onRefresh) {
Text("Refresh")
}
}
@@ -250,8 +342,11 @@ private fun PluginCard(
}
}
Row(horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.CenterVertically) {
- TvButton(
- enabled = !busy && plugin.manifest.hasCapability(StreamVaultPluginContract.CAPABILITY_CONFIGURATION_ACTIVITY),
+ PluginButton(
+ enabled = !busy && (
+ plugin.manifest.supportsHostRenderedConfiguration ||
+ plugin.manifest.hasCapability(StreamVaultPluginContract.CAPABILITY_CONFIGURATION_ACTIVITY)
+ ),
onClick = onOpenConfiguration
) {
Text("Configure")
@@ -274,3 +369,387 @@ private fun PluginCard(
}
}
}
+
+@Composable
+private fun PluginConfigurationPanel(
+ configuration: ActivePluginConfiguration,
+ onBack: () -> Unit,
+ onRefresh: () -> Unit,
+ onSave: () -> Unit,
+ onValueChange: (String, String) -> Unit,
+ onRunAction: (PluginConfigurationAction) -> Unit
+) {
+ val busy = configuration.isSaving || configuration.runningActionId != null
+ Column(
+ modifier = Modifier.fillMaxSize(),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ PluginConfigurationHeader(
+ configuration = configuration,
+ busy = busy,
+ onBack = onBack,
+ onRefresh = onRefresh,
+ onSave = onSave
+ )
+
+ LazyColumn(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ configuration.schema.sections.forEach { section ->
+ item(key = section.id) {
+ PluginConfigurationSectionCard(
+ section = section,
+ configuration = configuration,
+ busy = busy,
+ onValueChange = onValueChange
+ )
+ }
+ }
+
+ if (configuration.schema.actions.isNotEmpty()) {
+ item {
+ PluginConfigurationActions(
+ actions = configuration.schema.actions,
+ runningActionId = configuration.runningActionId,
+ busy = configuration.isSaving,
+ onRunAction = onRunAction
+ )
+ }
+ }
+
+ item { Spacer(modifier = Modifier.height(20.dp)) }
+ }
+ }
+}
+
+@Composable
+private fun PluginConfigurationHeader(
+ configuration: ActivePluginConfiguration,
+ busy: Boolean,
+ onBack: () -> Unit,
+ onRefresh: () -> Unit,
+ onSave: () -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(AppColors.Surface.copy(alpha = 0.72f), RoundedCornerShape(10.dp))
+ .padding(14.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Row(
+ modifier = Modifier.fillMaxWidth(),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(4.dp)
+ ) {
+ Text(
+ text = configuration.schema.title.ifBlank { configuration.plugin.displayName },
+ style = MaterialTheme.typography.titleMedium,
+ color = AppColors.TextPrimary,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ val description = configuration.schema.description
+ .ifBlank { configuration.plugin.manifest.description }
+ if (description.isNotBlank()) {
+ Text(
+ text = description,
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextSecondary,
+ maxLines = 2,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ Row(
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ PluginButton(enabled = !busy, onClick = onBack) { Text("Back") }
+ PluginButton(enabled = !busy, onClick = onRefresh) { Text("Refresh") }
+ PluginButton(
+ enabled = !busy && configuration.isDirty,
+ onClick = onSave,
+ tone = PluginButtonTone.Primary
+ ) { Text("Save") }
+ }
+ }
+ if (configuration.validationErrors.isNotEmpty()) {
+ Text(
+ text = "Some plugin settings need attention before saving.",
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.Live
+ )
+ }
+ }
+}
+
+@Composable
+private fun PluginConfigurationSectionCard(
+ section: PluginConfigurationSection,
+ configuration: ActivePluginConfiguration,
+ busy: Boolean,
+ onValueChange: (String, String) -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(AppColors.Surface.copy(alpha = 0.55f), RoundedCornerShape(10.dp))
+ .padding(14.dp),
+ verticalArrangement = Arrangement.spacedBy(12.dp)
+ ) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ text = section.title,
+ style = MaterialTheme.typography.titleSmall,
+ color = AppColors.TextPrimary
+ )
+ if (section.description.isNotBlank()) {
+ Text(
+ text = section.description,
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextSecondary
+ )
+ }
+ }
+
+ section.fields.forEach { field ->
+ PluginConfigurationFieldRow(
+ field = field,
+ value = configuration.draftValues[field.key].orEmpty(),
+ error = configuration.validationErrors[field.key],
+ busy = busy,
+ onValueChange = { onValueChange(field.key, it) }
+ )
+ }
+ }
+}
+
+@Composable
+private fun PluginConfigurationFieldRow(
+ field: PluginConfigurationField,
+ value: String,
+ error: String?,
+ busy: Boolean,
+ onValueChange: (String) -> Unit
+) {
+ when (field.type) {
+ PluginConfigurationField.TYPE_INFO -> PluginConfigurationInfoField(field, value)
+ PluginConfigurationField.TYPE_BOOLEAN -> PluginConfigurationBooleanField(field, value, busy, onValueChange)
+ PluginConfigurationField.TYPE_SELECT -> PluginConfigurationSelectField(field, value, busy, onValueChange)
+ else -> PluginConfigurationTextField(field, value, error, busy, onValueChange)
+ }
+}
+
+@Composable
+private fun PluginConfigurationInfoField(field: PluginConfigurationField, value: String) {
+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
+ Text(
+ text = field.label,
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextTertiary
+ )
+ Text(
+ text = value.ifBlank { field.placeholder.ifBlank { "-" } },
+ style = MaterialTheme.typography.bodyMedium,
+ color = AppColors.TextPrimary
+ )
+ if (field.description.isNotBlank()) {
+ Text(
+ text = field.description,
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextSecondary
+ )
+ }
+ }
+}
+
+@Composable
+private fun PluginConfigurationBooleanField(
+ field: PluginConfigurationField,
+ value: String,
+ busy: Boolean,
+ onValueChange: (String) -> Unit
+) {
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(AppColors.Surface.copy(alpha = 0.38f), RoundedCornerShape(8.dp))
+ .padding(horizontal = 12.dp, vertical = 10.dp),
+ horizontalArrangement = Arrangement.SpaceBetween,
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ Column(
+ modifier = Modifier.weight(1f),
+ verticalArrangement = Arrangement.spacedBy(3.dp)
+ ) {
+ Text(
+ text = field.label,
+ style = MaterialTheme.typography.bodyMedium,
+ color = if (field.readOnly) AppColors.TextSecondary else AppColors.TextPrimary
+ )
+ if (field.description.isNotBlank()) {
+ Text(
+ text = field.description,
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextTertiary
+ )
+ }
+ }
+ Switch(
+ checked = value.equals("true", ignoreCase = true),
+ enabled = !busy && !field.readOnly,
+ onCheckedChange = { onValueChange(it.toString()) }
+ )
+ }
+}
+
+@Composable
+private fun PluginConfigurationSelectField(
+ field: PluginConfigurationField,
+ value: String,
+ busy: Boolean,
+ onValueChange: (String) -> Unit
+) {
+ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(
+ text = field.label,
+ style = MaterialTheme.typography.bodyMedium,
+ color = AppColors.TextPrimary
+ )
+ if (field.description.isNotBlank()) {
+ Text(
+ text = field.description,
+ style = MaterialTheme.typography.bodySmall,
+ color = AppColors.TextSecondary
+ )
+ }
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .horizontalScroll(rememberScrollState()),
+ horizontalArrangement = Arrangement.spacedBy(8.dp)
+ ) {
+ field.options.forEach { option ->
+ PluginButton(
+ enabled = !busy && !field.readOnly,
+ onClick = { onValueChange(option.value) }
+ ) {
+ Text(
+ text = if (option.value == value) "${option.label} ✓" else option.label,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+}
+
+@Composable
+private fun PluginConfigurationTextField(
+ field: PluginConfigurationField,
+ value: String,
+ error: String?,
+ busy: Boolean,
+ onValueChange: (String) -> Unit
+) {
+ val singleLine = field.type != PluginConfigurationField.TYPE_TEXTAREA
+ OutlinedTextField(
+ value = value,
+ onValueChange = onValueChange,
+ modifier = Modifier
+ .fillMaxWidth()
+ .then(if (singleLine) Modifier else Modifier.heightIn(min = 96.dp)),
+ enabled = !busy && !field.readOnly,
+ readOnly = field.readOnly,
+ singleLine = singleLine,
+ maxLines = if (singleLine) 1 else 5,
+ label = { androidx.compose.material3.Text(field.label) },
+ placeholder = {
+ if (field.placeholder.isNotBlank()) {
+ androidx.compose.material3.Text(field.placeholder)
+ }
+ },
+ isError = error != null,
+ supportingText = {
+ val helper = error ?: field.description.takeIf { it.isNotBlank() }
+ if (helper != null) {
+ androidx.compose.material3.Text(helper)
+ }
+ },
+ keyboardOptions = KeyboardOptions(
+ keyboardType = when (field.type) {
+ PluginConfigurationField.TYPE_NUMBER -> KeyboardType.Number
+ PluginConfigurationField.TYPE_URL -> KeyboardType.Uri
+ else -> KeyboardType.Text
+ }
+ ),
+ visualTransformation = if (field.secret || field.type == PluginConfigurationField.TYPE_PASSWORD) {
+ PasswordVisualTransformation()
+ } else {
+ VisualTransformation.None
+ },
+ colors = OutlinedTextFieldDefaults.colors(
+ focusedTextColor = AppColors.TextPrimary,
+ unfocusedTextColor = AppColors.TextPrimary,
+ disabledTextColor = AppColors.TextSecondary,
+ focusedBorderColor = AppColors.Brand,
+ unfocusedBorderColor = AppColors.Outline,
+ disabledBorderColor = AppColors.Outline.copy(alpha = 0.4f),
+ errorBorderColor = AppColors.Live,
+ focusedLabelColor = AppColors.Brand,
+ unfocusedLabelColor = AppColors.TextSecondary,
+ disabledLabelColor = AppColors.TextTertiary,
+ cursorColor = AppColors.Brand
+ )
+ )
+}
+
+@Composable
+private fun PluginConfigurationActions(
+ actions: List<PluginConfigurationAction>,
+ runningActionId: String?,
+ busy: Boolean,
+ onRunAction: (PluginConfigurationAction) -> Unit
+) {
+ Column(
+ modifier = Modifier
+ .fillMaxWidth()
+ .background(AppColors.Surface.copy(alpha = 0.55f), RoundedCornerShape(10.dp))
+ .padding(14.dp),
+ verticalArrangement = Arrangement.spacedBy(10.dp)
+ ) {
+ Text(
+ text = "Actions",
+ style = MaterialTheme.typography.titleSmall,
+ color = AppColors.TextPrimary
+ )
+ Row(
+ modifier = Modifier
+ .fillMaxWidth()
+ .horizontalScroll(rememberScrollState()),
+ horizontalArrangement = Arrangement.spacedBy(8.dp),
+ verticalAlignment = Alignment.CenterVertically
+ ) {
+ actions.forEach { action ->
+ PluginButton(
+ enabled = !busy && runningActionId == null,
+ onClick = { onRunAction(action) },
+ modifier = Modifier.widthIn(min = 120.dp)
+ ) {
+ Text(
+ text = if (runningActionId == action.id) "${action.label}..." else action.label,
+ maxLines = 1,
+ overflow = TextOverflow.Ellipsis
+ )
+ }
+ }
+ }
+ }
+}
diff --git a/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsViewModel.kt b/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsViewModel.kt
index 5fa107a1..4d0ca86b 100644
--- a/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsViewModel.kt
+++ b/app/src/main/java/com/streamvault/app/ui/screens/plugins/PluginsViewModel.kt
@@ -4,6 +4,9 @@ import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.streamvault.app.plugins.InstalledStreamVaultPlugin
+import com.streamvault.app.plugins.PluginConfigurationAction
+import com.streamvault.app.plugins.PluginConfigurationField
+import com.streamvault.app.plugins.PluginConfigurationSchema
import com.streamvault.app.plugins.StreamVaultPluginManager
import com.streamvault.domain.model.Result
import dagger.hilt.android.lifecycle.HiltViewModel
@@ -13,17 +16,41 @@ import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
+import kotlinx.serialization.json.JsonElement
+import kotlinx.serialization.json.JsonObject
+import kotlinx.serialization.json.JsonPrimitive
+import kotlinx.serialization.json.booleanOrNull
+import kotlinx.serialization.json.buildJsonObject
+import kotlinx.serialization.json.contentOrNull
+import kotlinx.serialization.json.doubleOrNull
+import kotlinx.serialization.json.longOrNull
+import kotlinx.serialization.json.put
data class PluginsUiState(
val plugins: List<InstalledStreamVaultPlugin> = emptyList(),
val installUrl: String = "",
val isLoading: Boolean = false,
val isInstalling: Boolean = false,
+ val isConfigurationLoading: Boolean = false,
val activePluginId: String? = null,
+ val configuration: ActivePluginConfiguration? = null,
val syncProgress: String? = null,
val userMessage: String? = null
)
+data class ActivePluginConfiguration(
+ val plugin: InstalledStreamVaultPlugin,
+ val schema: PluginConfigurationSchema,
+ val values: JsonObject,
+ val draftValues: Map<String, String>,
+ val validationErrors: Map<String, String> = emptyMap(),
+ val isSaving: Boolean = false,
+ val runningActionId: String? = null
+) {
+ val isDirty: Boolean
+ get() = draftValues != schema.toDraftValues(values)
+}
+
@HiltViewModel
class PluginsViewModel @Inject constructor(
private val pluginManager: StreamVaultPluginManager
@@ -47,6 +74,12 @@ class PluginsViewModel @Inject constructor(
it.copy(
plugins = result.getOrDefault(emptyList()),
isLoading = false,
+ configuration = it.configuration?.let { configuration ->
+ val refreshedPlugin = result.getOrDefault(emptyList())
+ .firstOrNull { plugin -> plugin.manifest.id == configuration.plugin.manifest.id }
+ ?: configuration.plugin
+ configuration.copy(plugin = refreshedPlugin)
+ },
userMessage = result.exceptionOrNull()?.message
)
}
@@ -111,8 +144,148 @@ class PluginsViewModel @Inject constructor(
}
fun openPluginConfiguration(plugin: InstalledStreamVaultPlugin) {
- val result = pluginManager.openPluginConfiguration(plugin)
- _uiState.update { it.copy(userMessage = result.message) }
+ if (!plugin.manifest.supportsHostRenderedConfiguration) {
+ val result = pluginManager.openPluginConfiguration(plugin)
+ _uiState.update { it.copy(userMessage = result.message) }
+ return
+ }
+
+ viewModelScope.launch {
+ _uiState.update {
+ it.copy(
+ isConfigurationLoading = true,
+ activePluginId = plugin.manifest.id,
+ userMessage = null
+ )
+ }
+ when (val result = pluginManager.loadPluginConfiguration(plugin)) {
+ is Result.Error -> {
+ _uiState.update {
+ it.copy(
+ isConfigurationLoading = false,
+ activePluginId = null,
+ userMessage = result.message
+ )
+ }
+ }
+ Result.Loading -> Unit
+ is Result.Success -> {
+ val snapshot = result.data
+ _uiState.update {
+ it.copy(
+ isConfigurationLoading = false,
+ activePluginId = null,
+ configuration = ActivePluginConfiguration(
+ plugin = snapshot.plugin,
+ schema = snapshot.schema,
+ values = snapshot.values,
+ draftValues = snapshot.schema.toDraftValues(snapshot.values)
+ )
+ )
+ }
+ }
+ }
+ }
+ }
+
+ fun closePluginConfiguration() {
+ _uiState.update { it.copy(configuration = null, isConfigurationLoading = false) }
+ }
+
+ fun updateConfigurationValue(key: String, value: String) {
+ _uiState.update { state ->
+ val configuration = state.configuration ?: return@update state
+ state.copy(
+ configuration = configuration.copy(
+ draftValues = configuration.draftValues + (key to value),
+ validationErrors = configuration.validationErrors - key
+ )
+ )
+ }
+ }
+
+ fun savePluginConfiguration() {
+ val configuration = _uiState.value.configuration ?: return
+ val validationErrors = configuration.schema.validate(configuration.draftValues)
+ if (validationErrors.isNotEmpty()) {
+ _uiState.update {
+ it.copy(
+ configuration = configuration.copy(validationErrors = validationErrors),
+ userMessage = "Review the highlighted plugin settings"
+ )
+ }
+ return
+ }
+
+ viewModelScope.launch {
+ _uiState.updateConfiguration { it.copy(isSaving = true, validationErrors = emptyMap()) }
+ val valuesJson = configuration.schema.toValuesJson(configuration.draftValues).toString()
+ val result = pluginManager.savePluginConfiguration(configuration.plugin, valuesJson)
+ val refreshedValues = if (result.success) {
+ pluginManager.loadPluginConfigurationValues(configuration.plugin).getOrNull()
+ } else {
+ null
+ }
+ _uiState.updateConfiguration { current ->
+ val values = refreshedValues ?: current.values
+ current.copy(
+ values = values,
+ draftValues = if (refreshedValues != null) current.schema.toDraftValues(values) else current.draftValues,
+ isSaving = false
+ )
+ }
+ _uiState.update { it.copy(userMessage = result.message) }
+ }
+ }
+
+ fun refreshPluginConfiguration() {
+ val configuration = _uiState.value.configuration ?: return
+ viewModelScope.launch {
+ _uiState.updateConfiguration { it.copy(isSaving = true, validationErrors = emptyMap()) }
+ when (val result = pluginManager.loadPluginConfiguration(configuration.plugin)) {
+ is Result.Error -> {
+ _uiState.updateConfiguration { it.copy(isSaving = false) }
+ _uiState.update { it.copy(userMessage = result.message) }
+ }
+ Result.Loading -> Unit
+ is Result.Success -> {
+ _uiState.update {
+ it.copy(
+ configuration = ActivePluginConfiguration(
+ plugin = result.data.plugin,
+ schema = result.data.schema,
+ values = result.data.values,
+ draftValues = result.data.schema.toDraftValues(result.data.values)
+ )
+ )
+ }
+ }
+ }
+ }
+ }
+
+ fun runConfigurationAction(action: PluginConfigurationAction) {
+ val configuration = _uiState.value.configuration ?: return
+ viewModelScope.launch {
+ _uiState.updateConfiguration { it.copy(runningActionId = action.id) }
+ val result = pluginManager.runPluginConfigurationAction(configuration.plugin, action.id)
+ if (result.success && action.refreshAfterRun) {
+ pluginManager.loadPluginConfiguration(configuration.plugin).getOrNull()?.let { snapshot ->
+ _uiState.update {
+ it.copy(
+ configuration = ActivePluginConfiguration(
+ plugin = snapshot.plugin,
+ schema = snapshot.schema,
+ values = snapshot.values,
+ draftValues = snapshot.schema.toDraftValues(snapshot.values)
+ )
+ )
+ }
+ }
+ }
+ _uiState.updateConfiguration { it.copy(runningActionId = null) }
+ _uiState.update { it.copy(userMessage = result.message) }
+ }
}
fun clearMessage() {
@@ -125,3 +298,60 @@ class PluginsViewModel @Inject constructor(
is Result.Success -> successMessage
}
}
+
+private fun MutableStateFlow<PluginsUiState>.updateConfiguration(
+ transform: (ActivePluginConfiguration) -> ActivePluginConfiguration
+) {
+ update { state ->
+ val configuration = state.configuration ?: return@update state
+ state.copy(configuration = transform(configuration))
+ }
+}
+
+private fun PluginConfigurationSchema.fields(): List<PluginConfigurationField> =
+ sections.flatMap { it.fields }
+
+private fun PluginConfigurationSchema.toDraftValues(values: JsonObject): Map<String, String> =
+ fields().associate { field ->
+ field.key to (values[field.key] ?: field.defaultValue).toUiString()
+ }
+
+private fun PluginConfigurationSchema.validate(draftValues: Map<String, String>): Map<String, String> =
+ fields()
+ .filter { field ->
+ field.required &&
+ !field.readOnly &&
+ field.type != PluginConfigurationField.TYPE_INFO &&
+ draftValues[field.key].orEmpty().isBlank()
+ }
+ .associate { it.key to "${it.label} is required" }
+
+private fun PluginConfigurationSchema.toValuesJson(draftValues: Map<String, String>): JsonObject =
+ buildJsonObject {
+ fields()
+ .filter { !it.readOnly && it.type != PluginConfigurationField.TYPE_INFO }
+ .forEach { field ->
+ val value = draftValues[field.key].orEmpty()
+ when (field.type) {
+ PluginConfigurationField.TYPE_BOOLEAN -> put(field.key, value.equals("true", ignoreCase = true))
+ PluginConfigurationField.TYPE_NUMBER -> {
+ val longValue = value.toLongOrNull()
+ val doubleValue = value.toDoubleOrNull()
+ when {
+ longValue != null -> put(field.key, longValue)
+ doubleValue != null -> put(field.key, doubleValue)
+ else -> put(field.key, value)
+ }
+ }
+ else -> put(field.key, value)
+ }
+ }
+ }
+
+private fun JsonElement?.toUiString(): String {
+ val primitive = this as? JsonPrimitive ?: return ""
+ return primitive.booleanOrNull?.toString()
+ ?: primitive.longOrNull?.toString()
+ ?: primitive.doubleOrNull?.toString()
+ ?: primitive.contentOrNull.orEmpty()
+}
diff --git a/docs/PLUGIN_API.md b/docs/PLUGIN_API.md
index bd7001c5..81dbd480 100644
--- a/docs/PLUGIN_API.md
+++ b/docs/PLUGIN_API.md
@@ -7,7 +7,7 @@ through Android `Messenger` IPC.
This keeps the plugin boundary installable, removable, and compatible with
Android package isolation while still allowing plugins to add provider, playback,
-and Cast capabilities.
+Cast, and host-rendered configuration capabilities.
## Package Discovery
@@ -52,11 +52,13 @@ metadata fields if the JSON is missing or invalid.
"versionCode": 1,
"description": "Adds external capabilities to StreamVault.",
"providerName": "Example Provider",
+ "configurationMode": "host.schema",
"configurationActivityAction": "com.example.plugin.CONFIGURE",
"capabilities": [
"provider.m3u",
"playback.prepare",
"cast.rewriteUrl",
+ "configuration.schema",
"configuration.activity"
]
}
@@ -71,8 +73,9 @@ Recommended fallback metadata:
<meta-data android:name="com.streamvault.plugin.VERSION_CODE" android:value="1" />
<meta-data android:name="com.streamvault.plugin.DESCRIPTION" android:value="Adds external capabilities to StreamVault." />
<meta-data android:name="com.streamvault.plugin.PROVIDER_NAME" android:value="Example Provider" />
+<meta-data android:name="com.streamvault.plugin.CONFIGURATION_MODE" android:value="host.schema" />
<meta-data android:name="com.streamvault.plugin.CONFIGURATION_ACTIVITY_ACTION" android:value="com.example.plugin.CONFIGURE" />
-<meta-data android:name="com.streamvault.plugin.CAPABILITIES" android:value="provider.m3u,playback.prepare,cast.rewriteUrl,configuration.activity" />
+<meta-data android:name="com.streamvault.plugin.CAPABILITIES" android:value="provider.m3u,playback.prepare,cast.rewriteUrl,configuration.schema,configuration.activity" />
```
Capability names:
@@ -82,8 +85,10 @@ Capability names:
- `playback.prepare`: the plugin can prepare a stream URL before playback starts.
- `cast.rewriteUrl`: the plugin can rewrite a playback URL before Google Cast
loads it.
-- `configuration.activity`: the plugin exposes an Android activity that
- StreamVault can open.
+- `configuration.schema`: the plugin exposes a declarative configuration schema
+ that StreamVault renders with its own UI.
+- `configuration.activity`: fallback capability for plugins that need a custom
+ Android activity for exceptional flows.
## IPC Messages
@@ -109,13 +114,124 @@ Messages:
| 4 | `MSG_GET_PROVIDER_URL` | Return `url` and optional `provider_name`. |
| 5 | `MSG_PREPARE_PLAYBACK` | Prepare `input_url`; set `handled` when relevant. |
| 6 | `MSG_REWRITE_CAST_URL` | Rewrite `input_url`; return `output_url` when relevant. |
+| 7 | `MSG_GET_CONFIGURATION_SCHEMA` | Return `configuration_schema_json`. |
+| 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`. |
For `playback.prepare` and `cast.rewriteUrl`, plugins should set `handled=false`
when the URL is not theirs. StreamVault then continues with other enabled
plugins or the original URL.
-## Configuration Activity
+## Host-Rendered Configuration
-If `configuration.activity` is present, StreamVault starts the action in
-`configurationActivityAction` with the plugin package set explicitly. The plugin
-activity should be exported and include the `DEFAULT` category.
+Host-rendered configuration is the standard configuration mode. The plugin
+describes fields and actions, but StreamVault owns the visual shell, focus
+behavior, typography, controls, validation placement, and feedback.
+
+A plugin opts in with:
+
+- Manifest field `configurationMode: "host.schema"`.
+- Capability `configuration.schema`.
+- IPC handlers for messages 7 through 10.
+
+Schema response:
+
+```json
+{
+ "schemaVersion": 1,
+ "title": "Example Plugin",
+ "description": "Settings rendered by StreamVault.",
+ "sections": [
+ {
+ "id": "connection",
+ "title": "Connection",
+ "description": "Endpoint used by this plugin.",
+ "fields": [
+ {
+ "key": "serverUrl",
+ "type": "url",
+ "label": "Server URL",
+ "placeholder": "http://192.168.1.20:8080",
+ "required": true
+ },
+ {
+ "key": "token",
+ "type": "password",
+ "label": "Token",
+ "secret": true
+ },
+ {
+ "key": "lanMode",
+ "type": "boolean",
+ "label": "LAN mode",
+ "description": "Expose local URLs to other devices."
+ },
+ {
+ "key": "quality",
+ "type": "select",
+ "label": "Preferred quality",
+ "options": [
+ { "value": "auto", "label": "Auto" },
+ { "value": "1080p", "label": "1080p" }
+ ]
+ },
+ {
+ "key": "status",
+ "type": "info",
+ "label": "Status",
+ "readOnly": true
+ }
+ ]
+ }
+ ],
+ "actions": [
+ {
+ "id": "testConnection",
+ "label": "Test connection",
+ "description": "Ask the plugin to validate its current settings.",
+ "refreshAfterRun": true
+ }
+ ]
+}
+```
+
+Supported field types:
+
+- `info`: read-only text rendered by StreamVault.
+- `text`: single-line text.
+- `password`: single-line secret text.
+- `url`: URL text field.
+- `number`: numeric text field.
+- `boolean`: switch.
+- `select`: one value from `options`.
+- `textarea`: multi-line text.
+
+Values response:
+
+```json
+{
+ "serverUrl": "http://192.168.1.20:8080",
+ "token": "",
+ "lanMode": true,
+ "quality": "auto",
+ "status": "Ready"
+}
+```
+
+For `MSG_SET_CONFIGURATION_VALUES`, StreamVault sends the same JSON object in
+`configuration_values_json`. Plugins should persist supported writable keys,
+ignore unknown or read-only keys, and return `success=false` with `message` when
+validation fails.
+
+For `MSG_RUN_CONFIGURATION_ACTION`, StreamVault sends `configuration_action_id`.
+Plugins should execute the action, return a user-facing `message`, and refresh
+their values when `refreshAfterRun` is true.
+
+## Configuration Activity Fallback
+
+If a plugin cannot express a flow declaratively, it can still expose
+`configuration.activity`. StreamVault starts `configurationActivityAction` with
+the plugin package set explicitly. The plugin activity should be exported and
+include the `DEFAULT` category. Use this only for flows that need custom UI, such
+as OAuth, device pairing, or an embedded web surface.