Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions FEATURES.md
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,7 @@ Shown only while Settings → Experimental → Watch Party is on (default on in
|---|:---:|:---:|---|
| Household profiles (multiple per account) | ✅ | ✅ | `ProfileRepository` |
| PIN-protected & child profiles, content-rating limits | ✅ | ✅ | |
| Profile Selection at launch (Automatic, Every Time, After 1 Hour, After 12 Hours) | ➖ | ✅ | TV: Settings → General; device-local; tvOS parity, including hiding Watch Next |
| Per-profile language / subtitle / playback prefs | ✅ | ✅ | |
| Library access restrictions per profile | ✅ | ✅ | |
| Favorites & watchlist | ✅ | ✅ | TV: from Settings |
Expand Down
12 changes: 12 additions & 0 deletions androidTvApp/src/androidMain/AndroidManifest.xml
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,18 @@
</intent-filter>
</receiver>

<!-- Profile Selection: removes the Watch Next row when a timed
choice runs out while Silo is away (our own wake-up alarm), and
re-applies the setting after a reboot or a clock change. -->
<receiver
android:name=".watchnext.WatchNextProfileExpiryReceiver"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.TIME_SET" />
</intent-filter>
</receiver>

<!-- Media3 documents this as an exported service so system media
controllers can discover and bind to the app session. -->
<service
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package org.siloserver.silo.tv
import android.annotation.SuppressLint
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
Expand All @@ -18,6 +19,7 @@ import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
Expand Down Expand Up @@ -54,6 +56,10 @@ import org.siloserver.silo.repository.ProfileRepository
import org.siloserver.silo.repository.SectionRepository
import org.siloserver.silo.repository.port.HomeCachePort
import org.siloserver.silo.tv.cast.TvSiloCastReceiver
import org.siloserver.silo.tv.data.preferences.ProfileLaunchBehavior
import org.siloserver.silo.tv.data.preferences.TvProfileLaunchPreferences
import org.siloserver.silo.tv.profiles.TvActiveProfileReset
import org.siloserver.silo.tv.profiles.TvProfileAwayTracker
import org.siloserver.silo.tv.ui.navigation.TvAppNavigation
import org.siloserver.silo.tv.ui.navigation.TvRoute
import org.siloserver.silo.tv.ui.screens.player.TvPlayerRemoteKeyBridge
Expand All @@ -66,6 +72,7 @@ import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.mapLatest
import kotlinx.coroutines.flow.merge
import kotlinx.coroutines.flow.onSubscription
Expand All @@ -89,6 +96,12 @@ class MainTvActivity : ComponentActivity() {
@Volatile
private var hasShownColdSplash = false

// Profile Selection's launch rule applies once per process, like the
// splash: a later Activity in the same process follows the return rule
// instead (see resolveStartDestination).
@Volatile
private var hasResolvedLaunchProfile = false

/** Shared with [TvAppNavigation]'s consumer so intake and consumption
* of a deep link line up in one logcat filter. */
const val DEEP_LINK_TAG = "SiloDeepLink"
Expand Down Expand Up @@ -116,6 +129,19 @@ class MainTvActivity : ComponentActivity() {
// the navigation collector observes it as soon as it subscribes.
handleIntent(intent)

// Recents and a warm return to Silo show a snapshot of its last screen.
// When Profile Selection asks, that is the previous viewer's profile,
// so keep no snapshot then (Android 13+; earlier versions have no
// equivalent short of blocking screenshots altogether).
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
lifecycleScope.launch {
get<TvProfileLaunchPreferences>(TvProfileLaunchPreferences::class.java).state
.map { it.behavior == ProfileLaunchBehavior.Automatic }
.distinctUntilChanged()
.collect { automatic -> setRecentsScreenshotEnabled(automatic) }
}
}

// Run the SiloCast receiver while the app is started AND signed in,
// following sign-in, profile selection and sign-out without needing a
// background/foreground cycle. start()/stop() run here on the main
Expand Down Expand Up @@ -150,6 +176,12 @@ class MainTvActivity : ComponentActivity() {
launchAuthenticatedStartupWarmup(route)
}

// Profile Selection: from the moment Silo returns and the setting
// asks, cover the previous profile's screens until Who's Watching
// has replaced them (TvAppNavigation lifts the request).
val profileAwayTracker = remember { get<TvProfileAwayTracker>(TvProfileAwayTracker::class.java) }
val profileCoverVisible by profileAwayTracker.selectionRequired.collectAsState()

SiloTvTheme {
val resolvedRoute = startRoute
val splashVisible = resolvedRoute == null || !splashPlaybackComplete
Expand All @@ -160,11 +192,12 @@ class MainTvActivity : ComponentActivity() {
// Consume ALL input at the root while the splash
// overlay is up: no input-dispatch-timeout ANR, and
// no keys leak into the app pre-rendering below —
// even after its content grabs focus.
// even after its content grabs focus. The profile
// cover gates input the same way.
if (splashVisible) {
TvFocusLog.d { "key swallowed by splash gate" }
}
splashVisible
splashVisible || profileCoverVisible
},
) {
if (resolvedRoute != null) {
Expand All @@ -179,6 +212,9 @@ class MainTvActivity : ComponentActivity() {
modifier = Modifier.fillMaxSize(),
)
}
if (profileCoverVisible && !splashVisible) {
Box(modifier = Modifier.fillMaxSize().background(Color.Black))
}
if (splashVisible) {
val splashFocus = remember { FocusRequester() }
// PURE black — the splash video's encoded black is #000000, and any
Expand Down Expand Up @@ -232,6 +268,7 @@ class MainTvActivity : ComponentActivity() {
override fun onStart() {
super.onStart()
DiagnosticsLifecycleLogger.state("foreground")
get<TvProfileAwayTracker>(TvProfileAwayTracker::class.java).onForeground()
val refresher = get<ServerDrivenConfigRefresher>(ServerDrivenConfigRefresher::class.java)
val monitor = get<ServerReachabilityMonitor>(ServerReachabilityMonitor::class.java)
monitor.startForeground()
Expand Down Expand Up @@ -300,6 +337,10 @@ class MainTvActivity : ComponentActivity() {
override fun onStop() {
DiagnosticsLifecycleLogger.state("background")
super.onStop()
// A configuration-change recreation is not leaving Silo.
if (!isChangingConfigurations) {
get<TvProfileAwayTracker>(TvProfileAwayTracker::class.java).onBackground()
}
val monitor = get<ServerReachabilityMonitor>(ServerReachabilityMonitor::class.java)
monitor.stopForeground()
get<TvSiloCastReceiver>(TvSiloCastReceiver::class.java).stop()
Expand All @@ -317,6 +358,8 @@ class MainTvActivity : ComponentActivity() {
private suspend fun resolveStartDestination(): String {
val registry = get<ServerRegistry>(ServerRegistry::class.java)
val tokenManager = get<TokenManager>(TokenManager::class.java)
val processStart = !hasResolvedLaunchProfile
hasResolvedLaunchProfile = true

val activeEntry = registry.activeEntry.value
?: return TvRoute.ServerSetup.route
Expand Down Expand Up @@ -350,6 +393,30 @@ class MainTvActivity : ComponentActivity() {
val profileId = tokenManager.getProfileId()
if (profileId.isNullOrBlank()) return TvRoute.ProfileSelection.route

// A remote-playback overlay (only possible when the Activity is
// recreated in a live process) owns identity until it ends; the
// navigation graph applies the return rule once it has.
if (tokenManager.hasTemporaryScope()) return TvRoute.Main.route

// Profile Selection (silo-apple `ProfileLaunchState.resolution`). A
// process start applies the launch rule: Every Time, or a timed choice
// whose away interval ran out while Silo was closed. A later Activity
// in this process (Back left Silo, then it was reopened) follows the
// return rule the away tracker evaluated in onStart. Either way the
// profile is cleared here, before the picker loads, and losing its PIN
// proof makes a protected profile ask for its PIN again.
val launchPreferences = get<TvProfileLaunchPreferences>(TvProfileLaunchPreferences::class.java)
val requiresSelection = if (processStart) {
launchPreferences.requiresSelectionAtLaunch()
} else {
get<TvProfileAwayTracker>(TvProfileAwayTracker::class.java).selectionRequired.value
}
if (requiresSelection) {
get<TvActiveProfileReset>(TvActiveProfileReset::class.java).clearActiveProfile()
return TvRoute.ProfileSelection.route
}
if (processStart) launchPreferences.clearBackgroundedAt()

return TvRoute.Main.route
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,171 @@
package org.siloserver.silo.tv.data.preferences

import android.content.Context
import android.content.SharedPreferences
import androidx.core.content.edit
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow

/**
* When this Android TV asks "Who's watching?" instead of reopening the last
* profile. Mirrors silo-apple `ProfileLaunchBehavior` (tvOS General → PROFILE
* AT LAUNCH → Profile Selection), including its titles and descriptions.
*/
enum class ProfileLaunchBehavior(
/** Stored value. Same strings as silo-apple's raw values. */
val raw: String,
val title: String,
val description: String,
/** How long Silo can be away before the picker shows again; null for the untimed choices. */
val awayTimeoutMs: Long?,
) {
Automatic(
raw = "automatic",
title = "Automatic",
description = "Use the last profile selected on this Android TV. " +
"A protected profile can reopen without asking for its PIN.",
awayTimeoutMs = null,
),
EveryTime(
raw = "askEveryLaunch",
title = "Every Time",
description = "Show Who's Watching whenever you return to Silo.",
awayTimeoutMs = null,
),
AfterOneHour(
raw = "afterOneHour",
title = "After 1 Hour",
description = "Show Who's Watching when you've been away from Silo for 1 hour.",
awayTimeoutMs = 60 * 60 * 1000L,
),
AfterTwelveHours(
raw = "afterTwelveHours",
title = "After 12 Hours",
description = "Show Who's Watching when you've been away from Silo for 12 hours.",
awayTimeoutMs = 12 * 60 * 60 * 1000L,
),
;

companion object {
/** Unknown or missing values fall back to today's behavior. */
fun fromRaw(raw: String?): ProfileLaunchBehavior =
entries.firstOrNull { it.raw == raw } ?: Automatic
}
}

/**
* The policy plus the start of the current interval away from Silo. Pure, so
* the timing rules are unit-testable. Mirrors silo-apple `ProfileLaunchState`.
*/
data class ProfileLaunchState(
val behavior: ProfileLaunchBehavior = ProfileLaunchBehavior.Automatic,
/** Epoch ms when Silo last went to the background unused; null while in use. */
val backgroundedAtMs: Long? = null,
) {
/**
* Cold start. Every Time asks even when the previous process never
* recorded a background; the timed choices ask only once a recorded away
* interval has run out.
*/
fun requiresSelectionAtLaunch(nowMs: Long): Boolean =
behavior == ProfileLaunchBehavior.EveryTime || hasExpiredAwayInterval(nowMs)

/** Warm return. Needs a recorded background, so a brief pause never locks. */
fun requiresSelectionAfterBackground(nowMs: Long): Boolean {
if (backgroundedAtMs == null) return false
return behavior == ProfileLaunchBehavior.EveryTime || hasExpiredAwayInterval(nowMs)
}

/**
* Whether the launcher's Watch Next row may show the active profile's
* titles. silo-apple `TopShelfProfilePolicy`: never with Every Time, and
* not once a timed choice has expired.
*/
fun allowsWatchNext(nowMs: Long): Boolean =
behavior != ProfileLaunchBehavior.EveryTime && !requiresSelectionAfterBackground(nowMs)

/** When the current away interval runs out; null when nothing is timing out. */
val awayExpiresAtMs: Long?
get() {
val since = backgroundedAtMs ?: return null
val timeout = behavior.awayTimeoutMs ?: return null
return since + timeout
}

/** Automatic never keeps an away interval. */
fun withBehavior(behavior: ProfileLaunchBehavior): ProfileLaunchState = copy(
behavior = behavior,
backgroundedAtMs = if (behavior == ProfileLaunchBehavior.Automatic) null else backgroundedAtMs,
)

fun markedBackgrounded(atMs: Long): ProfileLaunchState =
if (behavior == ProfileLaunchBehavior.Automatic) copy(backgroundedAtMs = null) else copy(backgroundedAtMs = atMs)

private fun hasExpiredAwayInterval(nowMs: Long): Boolean {
val since = backgroundedAtMs ?: return false
val timeout = behavior.awayTimeoutMs ?: return false
// A clock behind the recorded start (a TV that booted before its time
// synced, or a manual change) cannot show how long Silo was away, so
// ask rather than keep the profile open indefinitely.
if (nowMs < since) return true
return nowMs - since >= timeout
}
}

/**
* Device-wide Profile Selection setting. It is never sent to the server, so a
* choice on this TV leaves every other device alone (silo-apple
* profile-launch design §12). It survives sign-out; the profile itself does
* not.
*
* Backed by SharedPreferences rather than DataStore: `onStop` writes the away
* marker and `onStart` reads it straight after, and SharedPreferences makes
* that write visible synchronously.
*/
class TvProfileLaunchPreferences(
private val prefs: SharedPreferences,
private val clock: () -> Long = System::currentTimeMillis,
) {
constructor(context: Context) : this(context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE))

private val _state = MutableStateFlow(read())
val state: StateFlow<ProfileLaunchState> = _state.asStateFlow()

fun requiresSelectionAtLaunch(): Boolean = state.value.requiresSelectionAtLaunch(clock())

fun requiresSelectionAfterBackground(): Boolean = state.value.requiresSelectionAfterBackground(clock())

fun allowsWatchNext(): Boolean = state.value.allowsWatchNext(clock())

fun setBehavior(behavior: ProfileLaunchBehavior) = update { it.withBehavior(behavior) }

/** Start the away clock. A no-op under Automatic. */
fun markBackgrounded() = update { it.markedBackgrounded(clock()) }

/** End the away interval: Silo is in use again with a chosen profile. */
fun clearBackgroundedAt() = update { it.copy(backgroundedAtMs = null) }

@Synchronized
private fun update(change: (ProfileLaunchState) -> ProfileLaunchState) {
val next = change(_state.value)
if (next == _state.value) return
prefs.edit {
putString(KEY_BEHAVIOR, next.behavior.raw)
val at = next.backgroundedAtMs
if (at == null) remove(KEY_BACKGROUNDED_AT) else putLong(KEY_BACKGROUNDED_AT, at)
}
_state.value = next
}

private fun read(): ProfileLaunchState = ProfileLaunchState(
behavior = ProfileLaunchBehavior.fromRaw(prefs.getString(KEY_BEHAVIOR, null)),
backgroundedAtMs = if (prefs.contains(KEY_BACKGROUNDED_AT)) prefs.getLong(KEY_BACKGROUNDED_AT, 0L) else null,
)

private companion object {
const val PREFS_NAME = "silo_tv_profile_launch"
const val KEY_BEHAVIOR = "behavior"
const val KEY_BACKGROUNDED_AT = "backgrounded_at_ms"
}
}
Loading