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
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import org.siloserver.silo.network.ServerRegistry
import org.siloserver.silo.network.TokenManager
import org.siloserver.silo.network.signedInEntries
import org.siloserver.silo.network.api.ServerIdentityApi
import org.siloserver.silo.network.apiv2.ApiV2Gate
import org.siloserver.silo.pairing.PairingEndpoint
import org.siloserver.silo.pairing.PairingFailureCode
import org.siloserver.silo.pairing.PairingMessage
Expand Down Expand Up @@ -289,14 +290,18 @@ class CompanionPairingCoordinator(
var signedInCount = 0
val signedInNames = mutableListOf<String>()
var transport: PairingTransport? = null
var reachedTv = false
try {
_status.value = CompanionPairingStatus.Connecting(target.name)
Log.i(
TAG,
"Connecting to ${target.name} at ${target.host}:${target.port} " +
"(session=${target.sessionId ?: "unknown"})",
)
val connected = transportFactory.connect(target).also { transport = it }
val connected = transportFactory.connect(target).also {
transport = it
reachedTv = true
}
coroutineScope {
val inbox = Channel<PairingMessage>(Channel.UNLIMITED)
val collector = launch {
Expand Down Expand Up @@ -373,7 +378,7 @@ class CompanionPairingCoordinator(
"${target.name} cancelled."
}
is ClosedReceiveChannelException -> "${target.name} closed the connection. Try again."
else -> t.userFacingPairingMessage(target)
else -> t.userFacingPairingMessage(target, reachedTv)
}
_status.value = CompanionPairingStatus.Failed(target.name, message)
return CompanionPairingResult.Failed(message)
Expand All @@ -400,11 +405,19 @@ class CompanionPairingCoordinator(
}
}

private fun Throwable.userFacingPairingMessage(target: CompanionPairingTarget): String {
val detail = generateSequence(this) { it.cause }
.mapNotNull { it.message?.takeIf(String::isNotBlank) }
.firstOrNull()
return detail ?: "Couldn't connect to the ${target.deviceNoun}. Keep its setup screen open and try again."
/**
* The card's text for a failure without its own case. This coordinator's
* own failures (`error(...)`) are already written for the card; anything
* else, such as a TLS or socket error, says what happened rather than
* showing its raw text.
*/
private fun Throwable.userFacingPairingMessage(target: CompanionPairingTarget, reachedTv: Boolean): String {
val own = message?.takeIf { this is IllegalStateException && this !is SiloAuthUnavailableException && it.isNotBlank() }
return when {
own != null -> own
reachedTv -> "Connection to ${target.name} was lost. Try again."
else -> "Couldn't connect to the ${target.deviceNoun}. Keep its setup screen open and try again."
}
}

private suspend fun pushAndApproveServer(
Expand Down Expand Up @@ -441,8 +454,8 @@ class CompanionPairingCoordinator(
}
val lookup = when (val result = deviceLoginApprover.lookup(server, started.userCode)) {
is ApiResult.Success -> result.data
is ApiResult.Error -> error(approverFailure(result, "Unable to verify TV setup code."))
is ApiResult.NetworkError -> error(approverFailure(result, "Unable to verify TV setup code."))
is ApiResult.Error -> error(approverFailure(result, target, server, "${server.displayName} couldn't check the code. Try again."))
is ApiResult.NetworkError -> error(approverFailure(result, server))
}
val serverMatchCode = lookup.matchCode?.takeIf { it.isNotBlank() }
?: error("Server did not return a match code for TV setup.")
Expand Down Expand Up @@ -480,8 +493,8 @@ class CompanionPairingCoordinator(
_status.value = CompanionPairingStatus.Approving(target.name, server.displayName)
when (val approved = deviceLoginApprover.approve(server, started.userCode)) {
is ApiResult.Success -> Unit
is ApiResult.Error -> error(approverFailure(approved, "Unable to approve TV setup."))
is ApiResult.NetworkError -> error(approverFailure(approved, "Unable to approve TV setup."))
is ApiResult.Error -> error(approverFailure(approved, target, server, "${server.displayName} couldn't approve the sign-in. Try again."))
is ApiResult.NetworkError -> error(approverFailure(approved, server))
}
val result = inbox.receiveFirst<PairingMessage.ServerResult>(
timeoutMs = SERVER_RESULT_TIMEOUT_MS,
Expand Down Expand Up @@ -547,24 +560,37 @@ class CompanionPairingCoordinator(
}

/**
* The phone's text for a lookup or approval that failed. The sign-in
* The phone's text for a code lookup or approval that failed, worded like
* the iPhone app's. The server's own error text is never shown. The sign-in
* provider being unreachable (503 `provider_unavailable` on the approver's
* refresh or answer) keeps this phone's session, so it says so instead of a
* raw reason.
* refresh or answer) keeps this phone's session, so it says so.
*/
internal fun approverFailure(result: ApiResult.Error, fallback: String): String =
if (result.code == 503 && result.error == SiloAuthUnavailableException.PROVIDER_UNAVAILABLE_PROBLEM) {
internal fun approverFailure(
result: ApiResult.Error,
target: CompanionPairingTarget,
server: CompanionPairingServer,
otherwise: String,
): String = when {
// The app's own update notice (no request was sent): retrying can't help.
result.code == 0 && result.error == ApiV2Gate.UPDATE_REQUIRED_ERROR -> result.message
result.code == 503 && result.error == SiloAuthUnavailableException.PROVIDER_UNAVAILABLE_PROBLEM ->
APPROVER_PROVIDER_UNAVAILABLE
} else {
result.message.ifBlank { fallback }
}
result.code == 401 -> signInAgain(server)
// Approved, denied, or cancelled on the TV already.
result.code == 409 -> "This sign-in request was already approved or declined. Start again on ${target.name}."
result.code == 404 || result.code == 410 -> "The code expired before it was approved. Start again on ${target.name}."
else -> otherwise
Comment thread
Quick104 marked this conversation as resolved.
Resolved
}

internal fun approverFailure(result: ApiResult.NetworkError, fallback: String): String = when {
internal fun approverFailure(result: ApiResult.NetworkError, server: CompanionPairingServer): String = when {
SiloAuthUnavailableException.isProviderUnavailable(result.exception) -> APPROVER_PROVIDER_UNAVAILABLE
result.exception is SiloAuthUnavailableException -> fallback
else -> result.exception.message ?: fallback
result.exception is SiloAuthUnavailableException -> signInAgain(server)
else -> "Couldn't reach ${server.displayName}. Check your connection and try again."
}

private fun signInAgain(server: CompanionPairingServer) =
"Sign in to ${server.displayName} on this device again, then try again."

internal const val APPROVER_PROVIDER_UNAVAILABLE =
"The sign-in provider can't be reached right now, so this device couldn't confirm your account. " +
"You're still signed in. Try again in a moment."
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,14 @@ import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.test.runTest
import org.siloserver.silo.model.auth.DeviceLoginDecisionResponse
import org.siloserver.silo.model.auth.DeviceLoginLookupResponse
import org.siloserver.silo.model.server.ServerContract
import org.siloserver.silo.network.ApiResult
import org.siloserver.silo.network.apiv2.ApiV2Gate
import org.siloserver.silo.pairing.PairingEndpoint
import org.siloserver.silo.pairing.PairingMessage
import org.siloserver.silo.pairing.PairingReceiverState
import org.siloserver.silo.pairing.PairingServerStatus
import javax.net.ssl.SSLException
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertIs
Expand Down Expand Up @@ -72,6 +75,7 @@ private class FakeCompanionApprover(
private val matchCodes: Map<String, String> = mapOf("ABCD-0001" to "MATCH-1"),
private val onApprove: suspend (String) -> Unit = {},
private val account: String? = "alice",
private val approveFailure: ApiResult<DeviceLoginDecisionResponse>? = null,
) : CompanionDeviceLoginApprover {
override suspend fun accountName(server: CompanionPairingServer): String? = account

Expand Down Expand Up @@ -100,6 +104,7 @@ private class FakeCompanionApprover(
code: String,
): ApiResult<DeviceLoginDecisionResponse> {
approvals += code
approveFailure?.let { return it }
onApprove(code)
return ApiResult.Success(DeviceLoginDecisionResponse(status = "approved"))
}
Expand Down Expand Up @@ -410,6 +415,36 @@ class CompanionPairingCoordinatorTest {
assertIs<CompanionPairingStatus.Failed>(coordinator[0]?.status?.value)
}

/** The card never shows the server's or the socket's own error text. */
@Test
fun failuresAreWordedForPeopleNotCopiedFromTheServerOrSocket() = runTest {
val server = CompanionPairingServer(id = "srv-1", url = "https://lib.example", displayName = "Home")
val approveFailures = mapOf(
ApiResult.Error(410, "device_login_expired", "Device login request has expired.") to
"The code expired before it was approved. Start again on Living Room.",
ApiResult.Error(409, "conflict", "Device login request was canceled on the device") to
"This sign-in request was already approved or declined. Start again on Living Room.",
// The app's own notice for a server it won't call until updated is kept.
ApiResult.Error(0, ApiV2Gate.UPDATE_REQUIRED_ERROR, ServerContract.UPDATE_REQUIRED_MESSAGE) to
ServerContract.UPDATE_REQUIRED_MESSAGE,
)
for ((failure, expected) in approveFailures) {
val transport = ScriptedPhoneTransport()
val coordinator = CompanionPairingCoordinator(
serverStore = FakeCompanionServerStore(CompanionPairingServerSnapshot("srv-1", listOf(server))),
deviceLoginApprover = FakeCompanionApprover(approveFailure = failure),
transportFactory = { transport },
)
val result = coordinator.pair(target = CompanionPairingTarget("tv-1", "Living Room", "127.0.0.1", 9999))
assertEquals(CompanionPairingResult.Failed(expected), result)
}

val lostMidSession = pairWithTvThat { _, _ ->
throw SSLException("Cannot write application data on closed/failed TLS connection")
}
assertEquals(CompanionPairingResult.Failed("Connection to Den TV was lost. Try again."), lostMidSession)
}

/** Pairs with a TV whose reaction to the pushed server is [onPush]. */
private suspend fun pairWithTvThat(
onCoordinator: (CompanionPairingCoordinator) -> Unit = {},
Expand Down
Loading