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
7 changes: 6 additions & 1 deletion example/src/main/java/io/radar/example/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ import io.radar.example.store.PermissionsStore
import io.radar.example.store.ProvideStores
import io.radar.example.store.SettingsStore
import io.radar.example.store.TripBuilderStore
import io.radar.example.store.VerifiedResponse
import io.radar.example.theme.RadarExampleTheme
import io.radar.sdk.Radar
import io.radar.sdk.RadarForegroundService
Expand Down Expand Up @@ -133,7 +134,11 @@ class MainActivity : AppCompatActivity() {

val verifiedReceiver = object : RadarVerifiedReceiver() {
override fun onTokenUpdated(context: Context, token: RadarVerifiedLocationToken) {
logStore.write(ConsoleKind.RESULT, "verified token updated", token.toJson().toString(2))
logStore.writeVerifiedResponse(
Radar.RadarStatus.SUCCESS,
action = "onTokenUpdated",
response = VerifiedResponse(token),
)
}

override fun onIpChanged(context: Context) {
Expand Down
34 changes: 31 additions & 3 deletions example/src/main/java/io/radar/example/console/ConsoleEntryRow.kt
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
package io.radar.example.console

import android.content.ClipData
import android.content.ClipboardManager
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.clickable
import androidx.compose.foundation.combinedClickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
Expand All @@ -10,6 +12,10 @@ import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.ContentCopy
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
Expand All @@ -21,6 +27,7 @@ import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.unit.dp
import io.radar.example.store.ConsoleEntry
Expand All @@ -30,16 +37,24 @@ import java.util.Locale

private val timeFormat = SimpleDateFormat("HH:mm:ss", Locale.US)

/** One row in the console timeline. Tap to expand the monospaced [ConsoleEntry.detail]. */
/** Tap to expand [ConsoleEntry.detail]; long-press verified results to copy their backend relay. */
@Composable
fun ConsoleEntryRow(entry: ConsoleEntry, modifier: Modifier = Modifier) {
val context = LocalContext.current
var expanded by remember { mutableStateOf(false) }
var showRelayMenu by remember { mutableStateOf(false) }
val hasDetail = !entry.detail.isNullOrBlank()
val relayJSON = entry.relayJSON

Column(
modifier = modifier
.fillMaxWidth()
.clickable(enabled = hasDetail) { expanded = !expanded }
.combinedClickable(
enabled = hasDetail || relayJSON != null,
onClick = { if (hasDetail) expanded = !expanded },
onLongClickLabel = if (relayJSON != null) "Copy backend relay JSON" else null,
onLongClick = if (relayJSON != null) ({ showRelayMenu = true }) else null,
)
.padding(horizontal = 12.dp, vertical = 8.dp),
) {
Row(verticalAlignment = Alignment.Top) {
Expand Down Expand Up @@ -83,5 +98,18 @@ fun ConsoleEntryRow(entry: ConsoleEntry, modifier: Modifier = Modifier) {
}
}
}
if (relayJSON != null) {
DropdownMenu(expanded = showRelayMenu, onDismissRequest = { showRelayMenu = false }) {
DropdownMenuItem(
text = { Text("Copy backend relay JSON") },
leadingIcon = { Icon(Icons.Filled.ContentCopy, contentDescription = null) },
onClick = {
context.getSystemService(ClipboardManager::class.java)
?.setPrimaryClip(ClipData.newPlainText("Radar backend relay", relayJSON))
showRelayMenu = false
},
)
}
}
}
}
2 changes: 2 additions & 0 deletions example/src/main/java/io/radar/example/store/ConsoleEntry.kt
Original file line number Diff line number Diff line change
Expand Up @@ -29,13 +29,15 @@ enum class ConsoleKind {
* [summary] is the compact one-line representation; [detail] is the optional multi-line
* payload revealed when the row is expanded (pretty-printed event JSON, formatted SDK
* result, full location vector, etc.).
* [relayJSON] contains the optional backend handoff exposed by the row's long-press action.
*/
data class ConsoleEntry(
val kind: ConsoleKind,
val summary: String,
val detail: String? = null,
val timestamp: Long = System.currentTimeMillis(),
val id: Long = nextId(),
val relayJSON: String? = null,
) {
companion object {
private val counter = AtomicLong(0)
Expand Down
25 changes: 23 additions & 2 deletions example/src/main/java/io/radar/example/store/LogStore.kt
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@ class LogStore : RadarReceiver() {

// MARK: - Public write API (used by ActionButton + the verified/IAM receivers)

fun write(kind: ConsoleKind, summary: String, detail: String? = null) {
append(ConsoleEntry(kind = kind, summary = summary, detail = detail))
fun write(kind: ConsoleKind, summary: String, detail: String? = null, relayJSON: String? = null) {
append(ConsoleEntry(kind = kind, summary = summary, detail = detail, relayJSON = relayJSON))
}

fun writeAction(title: String, detail: String? = null) = write(ConsoleKind.ACTION, title, detail)
Expand All @@ -51,6 +51,27 @@ class LogStore : RadarReceiver() {
if (status == Radar.RadarStatus.SUCCESS) writeResult(summary, detail) else writeError(summary, detail)
}

fun writeVerifiedResponse(
status: Radar.RadarStatus,
action: String,
response: VerifiedResponse?,
elapsedMilliseconds: Long? = null,
includeBeacons: Boolean = false,
) {
val summary = buildString {
append("$action: ${Utils.stringForRadarStatus(status)}")
elapsedMilliseconds?.let { append(" in $it ms") }
response?.let { append(" | ${it.summary}") }
if (includeBeacons && response != null) append(" | ${response.beaconSummary}")
}
write(
kind = if (status == Radar.RadarStatus.SUCCESS) ConsoleKind.RESULT else ConsoleKind.ERROR,
summary = summary,
detail = response?.detail ?: "No response returned.",
relayJSON = if (status == Radar.RadarStatus.SUCCESS) response?.relayJSON else null,
)
}

fun clear() {
entries.clear()
}
Expand Down
92 changes: 92 additions & 0 deletions example/src/main/java/io/radar/example/store/VerifiedResponse.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package io.radar.example.store

import io.radar.sdk.model.RadarResponseFormat
import io.radar.sdk.model.RadarRevealRiskToken
import io.radar.sdk.model.RadarVerifiedLocationToken
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.TimeZone
import org.json.JSONObject

/** Presents SDK results for QA. Access decisions belong to the receiving backend. */
class VerifiedResponse private constructor(
private val format: RadarResponseFormat,
private val evaluationId: String?,
private val token: String?,
private val expiresAt: String?,
private val expiresIn: Int?,
private val passed: Boolean?,
private val beaconCount: Int?,
private val response: JSONObject,
) {
constructor(result: RadarVerifiedLocationToken) : this(
format = result.format,
evaluationId = result._id.takeIf { it.isNotEmpty() },
token = result.token,
expiresAt = result.expiresAt?.let(::formatDate),
expiresIn = result.expiresIn.takeUnless { result.format == RadarResponseFormat.ID },
passed = result.passed.takeUnless { result.format == RadarResponseFormat.ID },
beaconCount = if (result.format == RadarResponseFormat.JWS) result.user?.beacons?.size ?: 0 else null,
response = result.toJson(),
)

constructor(result: RadarRevealRiskToken) : this(
format = result.format,
evaluationId = result.id.takeIf { it.isNotEmpty() },
token = result.token,
expiresAt = result.expiresAt,
expiresIn = result.expiresIn,
passed = null,
beaconCount = null,
response = result.toJson(),
)

/** Every response format relays only the opaque token and/or evaluation ID to the backend. */
val relayJSON: String?
get() {
if (token == null && evaluationId == null) return null
val payload = JSONObject()
token?.let { payload.put("token", it) }
evaluationId?.let { payload.put("_id", it) }
return json(payload)
}

val summary: String
get() = "${format.value}, ID: ${evaluationId ?: "unavailable"}"

val beaconSummary: String
get() = beaconCount?.let { "$it beacons" }
?: "beacons unavailable in ${format.value} responses"

val detail: String
get() = buildList {
add("Format: ${format.value}")
add("Evaluation ID: ${evaluationId ?: "unavailable"}")
add("Expires at: ${expiresAt ?: "unavailable"}")
add("Expires in: ${expiresIn?.let { "$it seconds" } ?: "unavailable"}")
passed?.let { add("Passed (unverified): $it") }
add("The backend must verify the result before allowing access.")
relayJSON?.let {
add("")
add("Backend relay JSON (long-press this entry to copy):")
add(it)
}
add("")
add("SDK response:")
add(json(response) ?: "unavailable")
}.joinToString("\n")

private companion object {
fun formatDate(date: Date): String =
SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.US).apply {
timeZone = TimeZone.getTimeZone("UTC")
}.format(date)

fun json(value: JSONObject): String? = try {
value.toString(2)
} catch (_: Exception) {
null
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@ package io.radar.example.tests.panels

import android.os.SystemClock
import androidx.compose.runtime.Composable
import io.radar.example.Utils
import io.radar.example.components.ActionButton
import io.radar.example.components.ActionButtonStyle
import io.radar.example.components.TogglePanel
import io.radar.example.store.LocalLogStore
import io.radar.example.store.VerifiedResponse
import io.radar.sdk.Radar
import io.radar.sdk.RadarTrackingOptions
import io.radar.sdk.model.RadarVerifiedLocationToken
Expand All @@ -26,24 +26,36 @@ fun VerifiedPanel() {
}
ActionButton("getVerifiedLocationToken") {
Radar.getVerifiedLocationToken { status, token ->
log.writeStatus(status, "getVerifiedLocationToken: ${Utils.stringForRadarStatus(status)}", token?.toJson()?.toString(2))
log.writeVerifiedResponse(
status,
action = "getVerifiedLocationToken",
response = token?.let { VerifiedResponse(it) },
)
}
}
ActionButton("clearVerifiedLocationToken") {
Radar.clearVerifiedLocationToken()
log.writeResult("Verified token cache cleared; the next token request will fetch a fresh response.")
}
ActionButton("trackVerified") {
Radar.trackVerified(false) { status, token ->
log.writeStatus(status, "trackVerified: ${Utils.stringForRadarStatus(status)}", token?.toJson()?.toString(2))
log.writeVerifiedResponse(
status,
action = "trackVerified",
response = token?.let { VerifiedResponse(it) },
)
}
}
ActionButton("trackVerified (beacons)") {
val start = SystemClock.elapsedRealtime()
Radar.trackVerified(true) { status, token ->
val elapsed = SystemClock.elapsedRealtime() - start
val beacons = token?.user?.beacons.orEmpty()
val beaconDesc = beacons.joinToString("\n") { "${it.description ?: it._id ?: "beacon"} (${it.uuid} ${it.major}/${it.minor})" }
log.writeStatus(
log.writeVerifiedResponse(
status,
"trackVerified (beacons): ${Utils.stringForRadarStatus(status)} in $elapsed ms, ${beacons.size} beacons",
beaconDesc
action = "trackVerified (beacons)",
response = token?.let { VerifiedResponse(it) },
elapsedMilliseconds = elapsed,
includeBeacons = true,
)
}
}
Expand All @@ -54,11 +66,11 @@ fun VerifiedPanel() {
RadarTrackingOptions.RadarTrackingOptionsDesiredAccuracy.HIGH,
object : Radar.RadarTrackVerifiedCallback {
override fun onComplete(status: Radar.RadarStatus, token: RadarVerifiedLocationToken?) {
val beacons = token?.user?.beacons.orEmpty()
log.writeStatus(
log.writeVerifiedResponse(
status,
"trackVerified (callback, beacons, HIGH): ${Utils.stringForRadarStatus(status)}, ${beacons.size} beacons",
token?.toJson()?.toString(2)
action = "trackVerified (callback, beacons, HIGH)",
response = token?.let { VerifiedResponse(it) },
includeBeacons = true,
)
}
}
Expand All @@ -85,7 +97,11 @@ fun VerifiedPanel() {
}
ActionButton("revealRisk") {
Radar.revealRisk { status, token ->
log.writeStatus(status, token?.toJson().toString())
log.writeVerifiedResponse(
status,
action = "revealRisk",
response = token?.let { VerifiedResponse(it) },
)
}
}
ActionButton("setExpectedAddress") {
Expand Down
Loading