Skip to content
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,9 @@ data class SiloCastTarget(
* controllable without a handoff; others need the v2 profile handoff. */
val serverId: String? = null,
val serverName: String? = null,
/** The deployment identity behind [serverId] (TXT `serverIdentity`), so a
* phone signed in at another address of the same server still matches. */
val serverIdentity: String? = null,
/** The receiver's advertised `playing` TXT flag. Drives the picker's
* "Playing now" badge and gates silent auto-resume (idle TVs must never
* be reattached — a bare connection flips them into standby takeover). */
Expand Down Expand Up @@ -221,6 +224,7 @@ class SiloCastNsdBrowser(context: Context) {
version = string("v")?.toIntOrNull() ?: 1,
serverId = string("server"),
serverName = string("serverName"),
serverIdentity = string("serverIdentity"),
isPlaying = string("playing") == "1",
)
}
Expand Down

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,127 @@
package org.siloserver.silo.android.cast

import org.siloserver.silo.cast.SiloCastCloseReason
import org.siloserver.silo.cast.SiloCastLaunchRequest
import org.siloserver.silo.cast.SiloCastNowPlayingSummary
import org.siloserver.silo.common.cast.SiloCastTarget

/** What the phone does when the TV closes its session (silo-apple `SiloControlCloseResponse`). */
sealed interface SiloCastCloseResponse {
/** Connect again quietly, as after a dropped link. */
data object Reconnect : SiloCastCloseResponse

/** End the session. With [forgetTarget], no later foreground probe silently reattaches to that TV. */
data class LetGo(val forgetTarget: Boolean) : SiloCastCloseResponse
}

object SiloCastClosePolicy {
/**
* A TV without `multi_controller` closes only to hand the slot to another
* phone or because someone pressed Disconnect, so the phone lets go and
* forgets it, as it always has. A TV that keeps several controllers says
* why: a deliberate disconnect (or no reason) still forgets the TV, a
* timeout reconnects, and the rest end the session but let a later
* foreground find the TV again.
*/
fun response(reason: String?, tvKeepsOtherControllers: Boolean): SiloCastCloseResponse {
if (!tvKeepsOtherControllers) return SiloCastCloseResponse.LetGo(forgetTarget = true)
return when (reason) {
SiloCastCloseReason.Timeout -> SiloCastCloseResponse.Reconnect
null, SiloCastCloseReason.TvDisconnected -> SiloCastCloseResponse.LetGo(forgetTarget = true)
else -> SiloCastCloseResponse.LetGo(forgetTarget = false)
}
}
}

/**
* The user's agreement to replace one particular title on the TV, carried from
* the prompt to the offer's `replacingContentId`.
*/
data class SiloCastReplaceConsent(
/** The title the user saw when agreeing; null when the TV didn't say. */
val contentId: String?,
)

/**
* A launch waiting for the user to agree to replace what the TV plays. Asked
* either by the phone before sending a different title to an engaged TV, or by
* the TV when another profile's title is on screen.
*/
data class SiloCastPendingReplace(
val target: SiloCastTarget,
val request: SiloCastLaunchRequest,
val message: String,
val confirmLabel: String,
/** Consent sent with the launch once the user agrees. */
val consent: SiloCastReplaceConsent,
)

object SiloCastReplacePrompt {
/** The TV refused the handoff because another profile's title is on screen. */
fun fromTv(
target: SiloCastTarget,
request: SiloCastLaunchRequest,
nowPlaying: SiloCastNowPlayingSummary?,
fallbackMessage: String?,
): SiloCastPendingReplace = SiloCastPendingReplace(
target = target,
request = request,
message = tvMessage(nowPlaying, target.name, fallbackMessage),
confirmLabel = "Replace",
consent = SiloCastReplaceConsent(contentId = nowPlaying?.contentId),
)

/** The phone is about to send a different title to a TV that is playing one. */
fun beforeSending(
target: SiloCastTarget,
request: SiloCastLaunchRequest,
currentContentId: String,
currentTitle: String,
): SiloCastPendingReplace = SiloCastPendingReplace(
target = target,
request = request,
message = "${target.name} is playing $currentTitle. Playing this will stop it.",
confirmLabel = "Play on ${target.name}",
consent = SiloCastReplaceConsent(contentId = currentContentId),
)

/** Whether sending [contentId] would replace a different title the TV is playing. */
fun replacesPlayingTitle(playingContentId: String?, contentId: String): Boolean =
!playingContentId.isNullOrEmpty() && playingContentId != contentId

/** The same sentence silo-apple builds from the TV's summary. */
fun tvMessage(nowPlaying: SiloCastNowPlayingSummary?, tvName: String, fallbackMessage: String?): String {
if (nowPlaying == null) return fallbackMessage ?: "Someone is watching something on $tvName. Play yours instead?"
val who = nowPlaying.profileName ?: "Someone"
val what = listOfNotNull(nowPlaying.subtitle, nowPlaying.title)
.filter { it.isNotEmpty() }
.joinToString(" · ")
return "$who is watching $what on $tvName. Play yours instead?"
}
}

/**
* Resume tokens the TVs issued this phone, held in memory only. A token lets a
* later connection to the same TV reuse the profile it already holds for this
* phone without a new approval, as after a Wi-Fi change.
*/
class SiloCastResumeTokens(
private val serverIdsMatch: (String?, String?) -> Boolean,
) {
private data class Entry(val serverId: String, val profileId: String, val token: String)

private val entries = mutableMapOf<String, Entry>()

@Synchronized
fun token(tvId: String, serverId: String, profileId: String): String? {
val entry = entries[tvId] ?: return null
if (!serverIdsMatch(entry.serverId, serverId) || entry.profileId != profileId) return null
return entry.token
}

@Synchronized
fun store(token: String?, tvId: String, serverId: String, profileId: String) {
if (token.isNullOrEmpty()) return
entries[tvId] = Entry(serverId, profileId, token)
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import kotlinx.coroutines.flow.drop
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import org.siloserver.silo.model.profile.ActiveProfileStore
import org.siloserver.silo.common.downloads.DownloadEnqueuer
import org.siloserver.silo.common.downloads.DownloadSubscriptionEvaluatorFactory
import org.siloserver.silo.common.downloads.DownloadSubscriptionWorker
Expand Down Expand Up @@ -293,6 +294,7 @@ val androidModule = module {
}
single<SiloCastLastTargetStore> { SharedPrefsSiloCastLastTargetStore(androidContext()) }
single {
val activeProfiles = get<ActiveProfileStore>()
SiloCastController(
browser = get(),
serverRegistry = get(),
Expand All @@ -304,6 +306,10 @@ val androidModule = module {
android.os.Build.MODEL?.trim()?.ifBlank { null } ?: "Android Phone"
},
deviceIdProvider = { PairingDeviceId.stable(androidContext()) },
profileNameProvider = { profileId ->
activeProfiles.activeProfile.value?.takeIf { it.id == profileId }?.name
},
serverIdentities = get(),
)
}
single<AndroidPushTokenProvider> { FirebaseAndroidPushTokenProvider(androidContext()) }
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,9 @@ fun SiloCastMiniBar(
strokeWidth = 2.dp,
)
} else {
IconButton(onClick = { controller.playPause() }) {
// Explicit, for what the bar shows: another controller may
// have changed it since.
IconButton(onClick = { controller.setPlaying(playback?.isPlaying != true) }) {
Icon(
if (playback?.isPlaying == true) Icons.Filled.Pause else Icons.Filled.PlayArrow,
contentDescription = if (playback?.isPlaying == true) "Pause" else "Play",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,18 @@ fun SiloCastRemoteScreen(
)
}

state.pendingReplace?.let { pending ->
SiloConfirmDialog(
title = stringResource(R.string.remote_replace_title),
body = pending.message,
confirmLabel = pending.confirmLabel,
dismissLabel = stringResource(R.string.remote_replace_cancel),
destructive = false,
onConfirm = controller::confirmReplace,
onDismiss = controller::cancelReplace,
)
}

if (showBatteryPrompt) {
val dismissBatteryPrompt = {
RemoteControlBatteryOptimization.markPromptShown(context)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -63,7 +63,9 @@ fun SiloCastTargetPickerSheet(
serverRegistry: ServerRegistry = koinInject(),
) {
val state by controller.state.collectAsState()
val activeServerId = serverRegistry.activeEntry.collectAsState().value?.id
val activeServer = serverRegistry.activeEntry.collectAsState().value
val activeServerId = activeServer?.id
val activeServerIdentity = activeServer?.verifiedServerId
var searchTimedOut by remember { mutableStateOf(false) }
// Remote-only mode keeps the sheet open through the connect (the row shows
// a spinner, like Apple's picker) and dismisses once the session is up.
Expand All @@ -89,7 +91,7 @@ fun SiloCastTargetPickerSheet(
state.targets
} else {
state.targets.filter {
AndroidServerRegistry.serverIdsMatch(it.serverId, activeServerId)
AndroidServerRegistry.serversMatch(it.serverId, it.serverIdentity, activeServerId, activeServerIdentity)
}
}

Expand Down Expand Up @@ -122,6 +124,7 @@ fun SiloCastTargetPickerSheet(
target = target,
launchRequest = launchRequest,
activeServerId = activeServerId,
activeServerIdentity = activeServerIdentity,
isConnectingToThis = state.connectingDeviceId == target.deviceId,
onSelect = {
if (launchRequest == null) {
Expand Down Expand Up @@ -202,12 +205,14 @@ private fun TargetRow(
target: SiloCastTarget,
launchRequest: SiloCastLaunchRequest?,
activeServerId: String?,
activeServerIdentity: String?,
isConnectingToThis: Boolean,
onSelect: () -> Unit,
) {
val needsUpdate = target.version < SiloCastProtocol.version
val enabled = !needsUpdate
val targetsActiveServer = AndroidServerRegistry.serverIdsMatch(target.serverId, activeServerId)
val targetsActiveServer =
AndroidServerRegistry.serversMatch(target.serverId, target.serverIdentity, activeServerId, activeServerIdentity)

Row(
verticalAlignment = Alignment.CenterVertically,
Expand Down
2 changes: 2 additions & 0 deletions androidApp/src/androidMain/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@
<string name="action_sign_out">Sign Out</string>

<!-- Remote Control -->
<string name="remote_replace_title">Replace what\'s playing?</string>
<string name="remote_replace_cancel">Cancel</string>
<string name="remote_battery_title">Keep Remote Control connected</string>
<string name="remote_battery_message">Allow Silo to run without battery restrictions so Remote Control can stay connected after you leave the app. In Battery optimization, choose Silo and set it to Not optimized.</string>
<string name="remote_battery_settings">Battery settings</string>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
package org.siloserver.silo.android.cast

import org.junit.Assert.assertEquals
import org.junit.Assert.assertFalse
import org.junit.Assert.assertNull
import org.junit.Assert.assertTrue
import org.junit.Test
import org.siloserver.silo.cast.SiloCastCloseReason
import org.siloserver.silo.cast.SiloCastLaunchRequest
import org.siloserver.silo.cast.SiloCastNowPlayingSummary
import org.siloserver.silo.cast.SiloCastPlaybackRequest
import org.siloserver.silo.common.cast.SiloCastTarget

/** The phone's rules for a TV that keeps several controllers (silo-apple SiloControlPhonePolicy). */
class SiloCastPhonePolicyTest {
private val target = SiloCastTarget(deviceId = "tv-1", name = "Living Room", host = "10.0.0.2", port = 4711, version = 2)
private val request = SiloCastLaunchRequest(
serverId = "srv-1",
playback = SiloCastPlaybackRequest(contentId = "miasma", startFromBeginning = true),
)

@Test
fun anOlderTvsCloseAlwaysForgetsIt() {
for (reason in listOf(null, SiloCastCloseReason.Timeout, SiloCastCloseReason.Replaced)) {
assertEquals(
SiloCastCloseResponse.LetGo(forgetTarget = true),
SiloCastClosePolicy.response(reason, tvKeepsOtherControllers = false),
)
}
}

@Test
fun aMultiControllerTvSaysWhetherToReconnectOrForget() {
fun response(reason: String?) = SiloCastClosePolicy.response(reason, tvKeepsOtherControllers = true)
assertEquals(SiloCastCloseResponse.Reconnect, response(SiloCastCloseReason.Timeout))
assertEquals(SiloCastCloseResponse.LetGo(forgetTarget = true), response(SiloCastCloseReason.TvDisconnected))
assertEquals(SiloCastCloseResponse.LetGo(forgetTarget = true), response(null))
for (reason in listOf(
SiloCastCloseReason.TooManyControllers,
SiloCastCloseReason.Unauthorized,
SiloCastCloseReason.LaunchTimeout,
SiloCastCloseReason.Replaced,
)) {
assertEquals(reason, SiloCastCloseResponse.LetGo(forgetTarget = false), response(reason))
}
}

@Test
fun theTvsPromptNamesWhoIsWatchingAndTiesConsentToThatTitle() {
val pending = SiloCastReplacePrompt.fromTv(
target,
request,
SiloCastNowPlayingSummary(contentId = "oak", title = "Oak Street", subtitle = "Season 1", profileName = "Alex"),
fallbackMessage = "Alex is watching Oak Street on this TV.",
)
assertEquals("Alex is watching Season 1 · Oak Street on Living Room. Play yours instead?", pending.message)
assertEquals("Replace", pending.confirmLabel)
assertEquals(SiloCastReplaceConsent(contentId = "oak"), pending.consent)
assertEquals(request, pending.request)
}

@Test
fun aPromptWithoutAProfileNameOrSummaryStillReads() {
assertEquals(
"Someone is watching Oak Street on Living Room. Play yours instead?",
SiloCastReplacePrompt.tvMessage(SiloCastNowPlayingSummary(title = "Oak Street"), "Living Room", null),
)
val fallback = SiloCastReplacePrompt.fromTv(target, request, nowPlaying = null, fallbackMessage = "Taken.")
assertEquals("Taken.", fallback.message)
assertNull(fallback.consent.contentId)
}

@Test
fun thePhoneAsksBeforeReplacingADifferentTitleOnly() {
assertTrue(SiloCastReplacePrompt.replacesPlayingTitle("oak", "miasma"))
assertFalse(SiloCastReplacePrompt.replacesPlayingTitle("oak", "oak"))
assertFalse(SiloCastReplacePrompt.replacesPlayingTitle(null, "miasma"))
assertFalse(SiloCastReplacePrompt.replacesPlayingTitle("", "miasma"))

val pending = SiloCastReplacePrompt.beforeSending(target, request, currentContentId = "oak", currentTitle = "Oak Street")
assertEquals("Living Room is playing Oak Street. Playing this will stop it.", pending.message)
assertEquals("Play on Living Room", pending.confirmLabel)
assertEquals(SiloCastReplaceConsent(contentId = "oak"), pending.consent)
}

@Test
fun resumeTokensBelongToOneTvServerAndProfile() {
val tokens = SiloCastResumeTokens { lhs, rhs -> lhs == rhs }
tokens.store("tok-1", tvId = "tv-1", serverId = "srv-1", profileId = "alex")
assertEquals("tok-1", tokens.token("tv-1", "srv-1", "alex"))
assertNull(tokens.token("tv-2", "srv-1", "alex"))
assertNull(tokens.token("tv-1", "srv-2", "alex"))
assertNull(tokens.token("tv-1", "srv-1", "sam"))

// A ready without a token (older TV, or a reused identity) keeps the last one.
tokens.store(null, tvId = "tv-1", serverId = "srv-1", profileId = "alex")
tokens.store("", tvId = "tv-1", serverId = "srv-1", profileId = "alex")
assertEquals("tok-1", tokens.token("tv-1", "srv-1", "alex"))
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,8 @@ class TvSiloCastReceiver(
is SiloCastMessage.Ping -> session.send(SiloCastMessage.Pong())
is SiloCastMessage.Pong -> session.missedHeartbeats = 0
is SiloCastMessage.Close -> return false
// This receiver doesn't list `presence`, so controllers don't send it.
is SiloCastMessage.Presence,
is SiloCastMessage.State,
is SiloCastMessage.Error,
is SiloCastMessage.HandoffChallenge,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -438,6 +438,18 @@ class AndroidServerRegistry(
* are canonicalized; credentials and the remaining URL components are
* retained exactly.
*/
/**
* Whether two server references name the same deployment: the same
* registry key, or the same verified deployment identity (silo-apple
* `ServerRegistry.serversMatch`).
*/
fun serversMatch(lhsId: String?, lhsIdentity: String?, rhsId: String?, rhsIdentity: String?): Boolean {
if (serverIdsMatch(lhsId, rhsId)) return true
val lhs = lhsIdentity?.trim()?.takeIf { it.isNotEmpty() } ?: return false
val rhs = rhsIdentity?.trim()?.takeIf { it.isNotEmpty() } ?: return false
return lhs == rhs
}

fun serverIdsMatch(lhs: String?, rhs: String?): Boolean {
if (lhs.isNullOrEmpty() || rhs.isNullOrEmpty()) return false
if (lhs == rhs) return true
Expand Down
Loading
Loading