voxels: add deep-link join requests and share links via voxels://join
- Commit
5bf78d7c35c0e07cd6860800f75956245e636409- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-06 22:09 UTC (4 months ago)
- Parents
eb7e0c0
Diff
games/voxels/src/main/AndroidManifest.xml
diff --git a/games/voxels/src/main/AndroidManifest.xml b/games/voxels/src/main/AndroidManifest.xmlindex e312e80ac5..be0427d829 100644--- a/games/voxels/src/main/AndroidManifest.xml+++ b/games/voxels/src/main/AndroidManifest.xml@@ -20,11 +20,23 @@ android:name=".MenuActivity" android:screenOrientation="sensorLandscape" android:exported="true"+ android:launchMode="singleTop" android:theme="@style/Theme.General"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter>++ <!-- Deep-link join request: voxels://join/<worldId>?owner=<ownerDeviceId>. Lands in the+ menu (not the game) and sends a sealed join request to the host. Public ids only. -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />++ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />++ <data android:scheme="voxels" android:host="join" />+ </intent-filter> </activity> <activity android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode"
games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.ktindex bf94a53e7a..b0c1f16453 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/MenuActivity.kt@@ -44,11 +44,33 @@ class MenuActivity : ComponentActivity() { // (keeps last-played ordering fresh). private var resumeTick by mutableStateOf(0) + /**+ * Pending `voxels://join/<worldId>?owner=<id>` link (worldId to ownerId), set on cold start and+ * via [onNewIntent] for warm starts, consumed by a Compose effect that sends the join request.+ */+ private val pendingJoinLink = mutableStateOf<Pair<String, String>?>(null)+ override fun onResume() { super.onResume() resumeTick++ } + override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ // singleTop: warm-start join links land here rather than a fresh onCreate.+ setIntent(intent)+ parseJoinLink(intent)?.let { pendingJoinLink.value = it }+ }++ /** Parses `voxels://join/<worldId>?owner=<ownerDeviceId>`; null for any other intent. */+ private fun parseJoinLink(intent: Intent?): Pair<String, String>? {+ val data = intent?.data ?: return null+ if (data.scheme != "voxels" || data.host != "join") return null+ val worldId = data.lastPathSegment?.takeIf { it.isNotBlank() } ?: return null+ val ownerId = data.getQueryParameter("owner")?.takeIf { it.isNotBlank() } ?: return null+ return worldId to ownerId+ }+ private fun localWorlds() = WorldManager.listWorlds(this).filter { !it.meta.online } private fun onlineWorldList() = WorldManager.onlineWorlds(this) @@ -66,6 +88,35 @@ class MenuActivity : ComponentActivity() { var onlineWorlds by remember { mutableStateOf(onlineWorldList()) } var deviceId by remember { mutableStateOf("") } var shareTarget by remember { mutableStateOf<WorldInfo?>(null) }+ var requests by remember { mutableStateOf<List<VoxelsSync.JoinRequest>>(emptyList()) }++ val ctx = this@MenuActivity+ fun reload() { worlds = localWorlds(); onlineWorlds = onlineWorldList() }++ // Pulls the inbox (from 0): folds invites into the shared-world list and surfaces+ // join requests for worlds this device owns (minus already-approved/denied ones).+ val refreshInbox: suspend () -> Unit = {+ val pending = withContext(Dispatchers.IO) {+ runCatching {+ VoxelsSync.init(ctx)+ val res = VoxelsSync.pullInbox(0)+ for (inv in res.invites) {+ WorldManager.upsertSharedWorld(+ ctx, inv.name, inv.seed, inv.worldId,+ inv.key, inv.ownerDeviceId, inv.role, System.currentTimeMillis(),+ )+ }+ val owned = WorldManager.onlineWorlds(ctx)+ .filter { it.meta.role == VoxelsRoles.OWNER }.map { it.meta.worldId }.toSet()+ val handled = WorldManager.handledRequests(ctx)+ res.requests+ .filter { it.worldId in owned && "${it.worldId}|${it.requesterId}" !in handled }+ .distinctBy { "${it.worldId}|${it.requesterId}" }+ }.getOrDefault(emptyList())+ }+ requests = pending+ reload()+ } LaunchedEffect(resumeTick) { worlds = localWorlds()@@ -76,9 +127,24 @@ class MenuActivity : ComponentActivity() { LaunchedEffect(Unit) { withContext(Dispatchers.IO) { runCatching { VoxelsSync.init(this@MenuActivity) } } deviceId = VoxelsSync.deviceId+ runCatching { refreshInbox() }+ }+ // A tapped voxels://join link sends a sealed join request to the host.+ LaunchedEffect(pendingJoinLink.value) {+ val link = pendingJoinLink.value ?: return@LaunchedEffect+ pendingJoinLink.value = null+ val (worldId, ownerId) = link+ toast(getString(R.string.requesting_access))+ val ok = withContext(Dispatchers.IO) {+ runCatching {+ VoxelsSync.init(ctx)+ val myName = "Player " + VoxelsSync.deviceId.takeLast(4)+ VoxelsSync.sendJoinRequest(ownerId, worldId, VoxelsSync.deviceId, myName)+ }.getOrDefault(false)+ }+ if (deviceId.isEmpty()) deviceId = VoxelsSync.deviceId+ toast(getString(if (ok) R.string.join_request_sent else R.string.invite_failed)) }-- fun reload() { worlds = localWorlds(); onlineWorlds = onlineWorldList() } Surface(Modifier.fillMaxSize()) { Box(Modifier.fillMaxSize()) {@@ -121,25 +187,44 @@ class MenuActivity : ComponentActivity() { } }, onRefresh = {+ scope.launch { refreshInbox() }+ },+ onCopyDeviceId = { copyToClipboard(deviceId) },+ onShare = { shareTarget = it },+ requests = requests,+ onApprove = { req -> scope.launch {- withContext(Dispatchers.IO) {+ val ok = withContext(Dispatchers.IO) { runCatching {- VoxelsSync.init(this@MenuActivity)- // Pull the whole inbox and upsert; dedup is by shared worldId.- val res = VoxelsSync.pullInvites(0)- for (inv in res.invites) {- WorldManager.upsertSharedWorld(- this@MenuActivity, inv.name, inv.seed, inv.worldId,- inv.key, inv.ownerDeviceId, inv.role, System.currentTimeMillis(),- )- }- }+ VoxelsSync.init(ctx)+ val world = WorldManager.onlineWorlds(ctx)+ .firstOrNull { it.meta.worldId == req.worldId && it.meta.role == VoxelsRoles.OWNER }+ ?: return@runCatching false+ val key = Base64.decode(world.meta.keyB64)+ val sent = VoxelsSync.sendInvite(+ req.requesterId, world.meta.worldId, key,+ world.meta.name, world.meta.seed, VoxelsRoles.EDITOR,+ Base64.encode(VoxelsSync.publicBundle), world.meta.ownerDeviceId,+ )+ if (sent) VoxelsSync.recordMembers(+ world.meta.worldId, key,+ listOf(+ VoxelsSync.Member(world.meta.ownerDeviceId, "", VoxelsRoles.OWNER),+ VoxelsSync.Member(req.requesterId, req.name, VoxelsRoles.EDITOR),+ ),+ )+ sent+ }.getOrDefault(false) }- reload()+ if (ok) WorldManager.markRequestHandled(ctx, "${req.worldId}|${req.requesterId}")+ requests = requests.filterNot { it.worldId == req.worldId && it.requesterId == req.requesterId }+ toast(getString(if (ok) R.string.invite_sent else R.string.invite_failed)) } },- onCopyDeviceId = { copyToClipboard(deviceId) },- onShare = { shareTarget = it },+ onDeny = { req ->+ WorldManager.markRequestHandled(ctx, "${req.worldId}|${req.requesterId}")+ requests = requests.filterNot { it.worldId == req.worldId && it.requesterId == req.requesterId }+ }, ) }
games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.ktindex 6d40c65dbb..9e75a5f983 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/ui/MenuScreens.kt@@ -24,15 +24,18 @@ 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.input.KeyboardType import androidx.compose.ui.unit.dp import androidx.compose.ui.window.Dialog import com.vayunmathur.games.voxels.util.WorldInfo import com.vayunmathur.games.voxels.util.VoxelsRoles+import com.vayunmathur.games.voxels.util.VoxelsSync import com.vayunmathur.library.ui.R as UiR import com.vayunmathur.library.ui.EmptyState import com.vayunmathur.library.ui.Button import com.vayunmathur.library.ui.Card+import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.ui.IconButton import com.vayunmathur.library.ui.IconDelete import com.vayunmathur.library.ui.IconPlay@@ -55,6 +58,9 @@ fun MenuScreen( onRefresh: () -> Unit, onCopyDeviceId: () -> Unit, onShare: (WorldInfo) -> Unit,+ requests: List<VoxelsSync.JoinRequest> = emptyList(),+ onApprove: (VoxelsSync.JoinRequest) -> Unit = {},+ onDeny: (VoxelsSync.JoinRequest) -> Unit = {}, ) { Box(Modifier.fillMaxSize().padding(24.dp), contentAlignment = Alignment.TopCenter) { Column(@@ -115,6 +121,25 @@ fun MenuScreen( onShare = if (owner) ({ onShare(world) }) else null) } }++ // --- Inbound join requests (owners only) ---+ if (requests.isNotEmpty()) {+ item {+ Spacer(Modifier.height(16.dp))+ Text(stringResource(R.string.requests_header), style = MaterialTheme.typography.titleMedium,+ color = MaterialTheme.colorScheme.primary)+ Spacer(Modifier.height(8.dp))+ }+ items(requests, key = { "req-${it.worldId}-${it.requesterId}" }) { req ->+ val worldName = onlineWorlds.firstOrNull { it.meta.worldId == req.worldId }?.meta?.name ?: req.worldId.take(8)+ val requester = req.name.ifBlank { req.requesterId.take(8) }+ RequestRow(+ text = stringResource(R.string.request_wants_to_join, requester, worldName),+ onApprove = { onApprove(req) },+ onDeny = { onDeny(req) },+ )+ }+ } } Spacer(Modifier.height(16.dp)) @@ -178,6 +203,19 @@ private fun WorldRow( } } +@Composable+private fun RequestRow(text: String, onApprove: () -> Unit, onDeny: () -> Unit) {+ Card(Modifier.fillMaxWidth()) {+ Row(Modifier.fillMaxWidth().padding(16.dp), verticalAlignment = Alignment.CenterVertically) {+ Text(text, style = MaterialTheme.typography.bodyMedium,+ color = MaterialTheme.colorScheme.onSurface, modifier = Modifier.weight(1f))+ OutlinedButton(onClick = onDeny) { Text(stringResource(R.string.deny)) }+ Spacer(Modifier.width(8.dp))+ Button(onClick = onApprove) { Text(stringResource(R.string.approve)) }+ }+ }+}+ // Owner-only dialog: invite a device by id. Voxels worlds have no viewers — everyone invited can // build — so there's no role choice. Mirrors office's ShareOnlineDialog. @Composable@@ -187,11 +225,27 @@ fun ShareOnlineDialog( onSend: (recipient: String) -> Unit, ) { var recipient by remember { mutableStateOf("") }+ val context = LocalContext.current Dialog(onDismissRequest = onDismiss) { Card(Modifier.fillMaxWidth().padding(8.dp)) { Column(Modifier.padding(20.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { Text(stringResource(R.string.share_world), style = MaterialTheme.typography.titleLarge, color = MaterialTheme.colorScheme.primary) Text(world.meta.name, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurface)+ // Share sheet: sends voxels://join/<worldId>?owner=<ownerId> (public ids only) so the+ // invitee can request access without you typing their device id.+ OutlinedButton(+ onClick = {+ val link = "voxels://join/${world.meta.worldId}?owner=${world.meta.ownerDeviceId}"+ ExternalIntents.shareText(context, link, context.getString(R.string.share_link_chooser))+ },+ modifier = Modifier.fillMaxWidth(),+ ) {+ IconShare()+ Spacer(Modifier.width(8.dp))+ Text(stringResource(R.string.share_link))+ }+ Text(stringResource(R.string.or_add_by_device_id), style = MaterialTheme.typography.labelMedium,+ color = MaterialTheme.colorScheme.onSurface.copy(alpha = 0.7f)) OutlinedTextField( value = recipient, onValueChange = { recipient = it },
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.ktindex 0d1b456c7e..0036651043 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/VoxelsSync.kt@@ -129,12 +129,43 @@ object VoxelsSync { /** Pulls + unseals invites addressed to this device from [since]. */ suspend fun pullInvites(since: Int): InvitesResult {- val p = pull("inbox:$deviceId", since) ?: return InvitesResult(emptyList(), since)- val invites = p.actions.mapNotNull { b ->- val plain = runCatching { identity.decrypt(Base64.decode(b)) }.getOrNull() ?: return@mapNotNull null- runCatching { json.decodeFromString<Invite>(plain.decodeToString()) }.getOrNull()+ val inbox = pullInbox(since)+ return InvitesResult(inbox.invites, inbox.seq)+ }++ /**+ * Sends a PQC-sealed join request to a world owner's inbox. Carries only public ids+ * (never the AES world key); the host approves with one tap, which triggers the+ * existing seal-to-recipient [sendInvite]. Rides the same `inbox:<ownerId>` channel+ * as invites — distinguished by the `kind:"req"` discriminator (see [pullInbox]).+ */+ suspend fun sendJoinRequest(ownerId: String, worldId: String, requesterId: String, name: String): Boolean {+ val ownerBundle = getKey(ownerId) ?: return false+ val req = json.encodeToString(JoinRequest(worldId = worldId, requesterId = requesterId, name = name))+ val blob = Base64.encode(Pqc.encryptTo(ownerBundle, req.encodeToByteArray()))+ return append("inbox:$ownerId", listOf(blob)) != null+ }++ /**+ * Tolerant inbox reader: decrypts each blob and sorts it into invites (default kind,+ * for backward compatibility) vs join requests (`kind:"req"`). Unparseable/foreign+ * blobs are skipped so one bad item never drops the batch.+ */+ suspend fun pullInbox(since: Int): InboxResult {+ val p = pull("inbox:$deviceId", since) ?: return InboxResult(emptyList(), emptyList(), since)+ val invites = mutableListOf<Invite>()+ val requests = mutableListOf<JoinRequest>()+ for (b in p.actions) {+ val plain = runCatching { identity.decrypt(Base64.decode(b)) }.getOrNull() ?: continue+ val text = plain.decodeToString()+ val kind = runCatching { json.decodeFromString<InboxEnvelope>(text).kind }.getOrNull().orEmpty()+ if (kind == "req") {+ runCatching { json.decodeFromString<JoinRequest>(text) }.getOrNull()?.let { requests.add(it) }+ } else {+ runCatching { json.decodeFromString<Invite>(text) }.getOrNull()?.let { invites.add(it) }+ } }- return InvitesResult(invites, p.seq)+ return InboxResult(invites, requests, p.seq) } // --- Owner-signed roster on the (world-key-encrypted) members channel ---@@ -312,6 +343,17 @@ object VoxelsSync { val ownerDeviceId: String = "", ) + /** A request to join a world, sealed to the owner. Public ids only — no key. */+ @Serializable data class JoinRequest(+ val kind: String = "req",+ val worldId: String,+ val requesterId: String,+ val name: String = "",+ )++ /** Peeks the discriminator on an inbox blob so invites and requests can share the channel. */+ @Serializable private data class InboxEnvelope(val kind: String = "")+ /** An author-signed op/snapshot batch: author id, signature over [ops], and the ops JSON. */ @Serializable data class SignedOp(val author: String, val sig: String, val ops: String) @@ -322,6 +364,7 @@ object VoxelsSync { @Serializable data class SignedMember(val member: Member, val sig: String) class InvitesResult(val invites: List<Invite>, val seq: Int)+ class InboxResult(val invites: List<Invite>, val requests: List<JoinRequest>, val seq: Int) class OpsResult(val items: List<String>, val seq: Int) @Serializable private data class SubMsg(val t: String, val channel: String)
games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.kt
diff --git a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.kt b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.ktindex 610091b4b1..1c59281e28 100644--- a/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.kt+++ b/games/voxels/src/main/java/com/vayunmathur/games/voxels/util/WorldManager.kt@@ -136,4 +136,23 @@ object WorldManager { val tier = VoxelsAchievementsManager(ctx, json, "world_$id:") CoroutineScope(Dispatchers.IO).launch { tier.forgetAll() } }++ // --- Handled join requests ---+ //+ // The inbox is always pulled from seq 0, so an approved/denied request would otherwise reappear+ // on every refresh (its sealed blob lives in the log forever). We persist a small set of handled+ // "worldId|requesterId" keys to suppress those, mirroring how shared worlds dedup by worldId.++ private fun handledFile(ctx: Context): File = File(ctx.filesDir, "voxels_handled_requests.json")++ fun handledRequests(ctx: Context): Set<String> {+ val f = handledFile(ctx)+ if (!f.exists()) return emptySet()+ return try { json.decodeFromString<Set<String>>(f.readText()) } catch (_: Exception) { emptySet() }+ }++ fun markRequestHandled(ctx: Context, key: String) {+ val updated = handledRequests(ctx) + key+ runCatching { handledFile(ctx).writeText(json.encodeToString(updated)) }+ } }
games/voxels/src/main/res/values/strings.xml
diff --git a/games/voxels/src/main/res/values/strings.xml b/games/voxels/src/main/res/values/strings.xmlindex cbb844e4e2..8678a04dca 100644--- a/games/voxels/src/main/res/values/strings.xml+++ b/games/voxels/src/main/res/values/strings.xml@@ -72,6 +72,24 @@ <string name="send_invite">Send invite</string> <string name="invite_sent">Invite sent.</string> <string name="invite_failed">Couldn\'t send the invite — check the device ID and your connection.</string>+ <!-- ShareOnlineDialog: Button that opens the share sheet with a join link. Verb phrase -->+ <string name="share_link">Share link</string>+ <!-- ShareOnlineDialog: Title of the share chooser for the join link. Noun phrase -->+ <string name="share_link_chooser">Share Voxels invite</string>+ <!-- ShareOnlineDialog: Separator before the manual device-id fallback. Phrase -->+ <string name="or_add_by_device_id">Or add by device ID</string>+ <!-- MenuScreen: Header for inbound join requests. Noun -->+ <string name="requests_header">Requests</string>+ <!-- MenuScreen: Button to approve a join request. Verb -->+ <string name="approve">Approve</string>+ <!-- MenuScreen: Button to deny a join request. Verb -->+ <string name="deny">Deny</string>+ <!-- MenuScreen: A join request line: %1$s = requester, %2$s = world name. Sentence -->+ <string name="request_wants_to_join">%1$s wants to join \"%2$s\"</string>+ <!-- MenuActivity: Toast while a join request is being sent. Sentence -->+ <string name="requesting_access">Requesting access…</string>+ <!-- MenuActivity: Toast when a join request was sent. Sentence -->+ <string name="join_request_sent">Requested to join — you\'ll get access once the host approves.</string> <string name="connection_lost">Connection lost — waiting to reconnect…</string> <string name="players_online">%1$d online</string> </resources>