office: add deep-link join requests and share links via office://join
- Commit
eb7e0c002a660198c1be17a26fd3693e5b15d088- Author
- Vayun Mathur <[email protected]>
- When
- 2026-08-06 22:09 UTC (4 months ago)
- Parents
3c6d247
Diff
office/src/main/AndroidManifest.xml
diff --git a/office/src/main/AndroidManifest.xml b/office/src/main/AndroidManifest.xmlindex 1cee023883..58a7eecb3a 100644--- a/office/src/main/AndroidManifest.xml+++ b/office/src/main/AndroidManifest.xml@@ -16,6 +16,7 @@ android:configChanges="mcc|mnc|colorMode|density|fontScale|fontWeightAdjustment|keyboard|keyboardHidden|layoutDirection|navigation|orientation|screenLayout|screenSize|smallestScreenSize|touchscreen|uiMode" android:name=".MainActivity" android:exported="true"+ android:launchMode="singleTop" android:resizeableActivity="true" android:theme="@style/Theme.General"> <intent-filter>@@ -23,6 +24,17 @@ <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> + <!-- Deep-link join request: office://join/<docId>?owner=<ownerDeviceId>. Carries+ only non-secret directory ids; tapping sends a sealed join request to the owner. -->+ <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="office" android:host="join" />+ </intent-filter>+ <intent-filter> <action android:name="android.intent.action.VIEW" /> <category android:name="android.intent.category.DEFAULT" />
office/src/main/java/com/vayunmathur/office/MainActivity.kt
diff --git a/office/src/main/java/com/vayunmathur/office/MainActivity.kt b/office/src/main/java/com/vayunmathur/office/MainActivity.ktindex b0ae61928d..bc0d52e741 100644--- a/office/src/main/java/com/vayunmathur/office/MainActivity.kt+++ b/office/src/main/java/com/vayunmathur/office/MainActivity.kt@@ -7,6 +7,7 @@ import android.print.PrintAttributes import android.print.PrintManager import android.webkit.WebView import android.webkit.WebViewClient+import android.widget.Toast import androidx.activity.ComponentActivity import androidx.activity.compose.BackHandler import com.vayunmathur.library.ui.R as UiR@@ -54,6 +55,7 @@ import com.vayunmathur.library.ui.DropdownMenu import com.vayunmathur.library.ui.DropdownMenuItem import com.vayunmathur.library.ui.DrawerValue import com.vayunmathur.library.ui.ExperimentalMaterial3Api+import com.vayunmathur.library.ui.ExternalIntents import com.vayunmathur.library.ui.HorizontalDivider import com.vayunmathur.library.ui.IconRedo import com.vayunmathur.library.ui.IconButton@@ -162,7 +164,11 @@ class MainActivity : ComponentActivity() { enableEdgeToEdge() viewModel.loadSettings(this) - val intentUri: Uri? = intent.data+ // office://join links request access to someone else's doc — handle them here and keep+ // them out of the document-loading path (their scheme isn't content/file).+ val joinLink = parseJoinLink(intent)+ if (joinLink != null) handleJoinLink(joinLink)+ val intentUri: Uri? = intent.data?.takeIf { joinLink == null } setContent { val startedWithIntent = intentUri != null@@ -274,6 +280,35 @@ class MainActivity : ComponentActivity() { runCatching { contentResolver.takePersistableUriPermission(uri, Intent.FLAG_GRANT_READ_URI_PERMISSION) } } }++ override fun onNewIntent(intent: Intent) {+ super.onNewIntent(intent)+ // singleTop: warm-start join links arrive here rather than through a fresh onCreate.+ setIntent(intent)+ parseJoinLink(intent)?.let { handleJoinLink(it) }+ }++ /** Fires a sealed join request to the owner and confirms with a toast. */+ private fun handleJoinLink(link: Pair<String, String>) {+ val (docId, ownerId) = link+ Toast.makeText(this, getString(R.string.join_request_sending), Toast.LENGTH_SHORT).show()+ viewModel.requestToJoin(docId, ownerId) { ok ->+ Toast.makeText(+ this,+ getString(if (ok) R.string.join_request_sent else R.string.join_request_failed),+ Toast.LENGTH_LONG,+ ).show()+ }+ }++ /** Parses `office://join/<docId>?owner=<ownerDeviceId>`; null for any other intent. */+ private fun parseJoinLink(intent: Intent?): Pair<String, String>? {+ val data = intent?.data ?: return null+ if (data.scheme != "office" || data.host != "join") return null+ val docId = data.lastPathSegment?.takeIf { it.isNotBlank() } ?: return null+ val ownerId = data.getQueryParameter("owner")?.takeIf { it.isNotBlank() } ?: return null+ return docId to ownerId+ } } /**@@ -393,6 +428,7 @@ fun ShareOnlineDialog( initialName: String, myRole: String, members: List<com.vayunmathur.office.util.OfficeMember>,+ shareLink: String? = null, onShare: (String, String, String, (String?) -> Unit) -> Unit, onSetRole: (String, String) -> Unit, onTransferOwner: (String) -> Unit,@@ -410,6 +446,7 @@ fun ShareOnlineDialog( var status by remember { mutableStateOf<String?>(null) } var memberMenu by remember { mutableStateOf<String?>(null) } val clipboard = LocalClipboard.current+ val context = LocalContext.current val scope = rememberCoroutineScope() AlertDialog( onDismissRequest = onDismiss,@@ -464,6 +501,19 @@ fun ShareOnlineDialog( TextButton(enabled = docName.isNotBlank() && docName.trim() != initialName, onClick = { onRename(docName.trim()) }) { Text(stringResource(UiR.string.rename)) } Spacer(Modifier.height(8.dp)) }+ // Share sheet: sends office://join/<docId>?owner=<deviceId> (public ids only) so+ // the recipient can request access without you typing their device id.+ shareLink?.let { link ->+ OutlinedButton(+ onClick = { 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))+ }+ Spacer(Modifier.height(8.dp))+ } Text(stringResource(R.string.add_someone_by_device_id_copies_this_doc)) Spacer(Modifier.height(8.dp)) OutlinedTextField(@@ -530,10 +580,12 @@ fun OnlineTab(viewModel: OfficeViewModel, onOpenDoc: (com.vayunmathur.office.uti } OnlineInit(viewModel) val docs by viewModel.onlineDocs.collectAsState()+ val requests by viewModel.pendingRequests.collectAsState() val deviceId = viewModel.syncDeviceId val clipboard = LocalClipboard.current val scope = rememberCoroutineScope() val online by rememberIsOnline()+ val context = LocalContext.current Scaffold( topBar = { TopAppBar(@@ -556,16 +608,45 @@ fun OnlineTab(viewModel: OfficeViewModel, onOpenDoc: (com.vayunmathur.office.uti TextButton(onClick = { if (deviceId.isNotEmpty()) scope.launch { clipboard.setClipEntry(ClipEntry(ClipData.newPlainText("device id", deviceId))) } }) { Text(stringResource(R.string.copy)) } } Spacer(Modifier.height(12.dp))- if (docs.isEmpty()) {+ if (docs.isEmpty() && requests.isEmpty()) { Text(stringResource(R.string.no_online_documents_yet_open_a_document), style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant) } else { LazyColumn(verticalArrangement = Arrangement.spacedBy(8.dp)) {- items(docs) { meta ->+ // Inbound join requests (from tapped share links) for docs you own.+ if (requests.isNotEmpty()) {+ item {+ Text(stringResource(R.string.requests_header),+ style = MaterialTheme.typography.titleSmall,+ color = MaterialTheme.colorScheme.primary)+ }+ items(requests, key = { "req-${it.docId}-${it.requesterId}" }) { req ->+ val docTitle = docs.firstOrNull { it.docId == req.docId }?.title ?: req.docId.take(8)+ val requester = req.name.ifBlank { req.requesterId.take(8) }+ Card(Modifier.fillMaxWidth()) {+ ListItem(+ content = { Text(stringResource(R.string.request_wants_to_join, requester, docTitle)) },+ trailingContent = {+ Row {+ TextButton(onClick = { viewModel.approveJoinRequest(req.docId, req.requesterId, req.name) }) { Text(stringResource(R.string.approve)) }+ TextButton(onClick = { viewModel.denyRequest(req.docId, req.requesterId) }) { Text(stringResource(R.string.deny)) }+ }+ }+ )+ }+ }+ }+ items(docs, key = { it.docId }) { meta -> Card(Modifier.fillMaxWidth().clickable { onOpenDoc(meta) }) { ListItem( content = { Text(meta.title) },- supportingContent = { Text(if (meta.owner) stringResource(R.string.shared_by_you) else stringResource(R.string.shared_with_you)) }+ supportingContent = { Text(if (meta.owner) stringResource(R.string.shared_by_you) else stringResource(R.string.shared_with_you)) },+ trailingContent = {+ // Owners can share a tappable invite link (public ids only).+ if (meta.owner) IconButton(onClick = {+ ExternalIntents.shareText(context, viewModel.shareLinkFor(meta.docId), context.getString(R.string.share_link_chooser))+ }) { IconShare() }+ } ) } }@@ -1113,6 +1194,7 @@ fun DocumentScreen(document: OdfDocument, viewModel: OfficeViewModel, activity: initialName = document.title, myRole = viewModel.currentDocRole(), members = members,+ shareLink = if (isOnline) viewModel.currentOnlineDocId()?.let { viewModel.shareLinkFor(it) } else null, onShare = { recipientId, role, name, cb -> viewModel.shareCurrentDocument(recipientId, role, name) { err -> if (err == null) {
office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeSync.ktindex f6cfc1f419..c672dd877e 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeSync.kt@@ -92,13 +92,44 @@ object OfficeSync { return append("inbox:$recipientId", listOf(blob)) != null } + /**+ * Sends a PQC-sealed join request to a document owner's inbox. Carries only public+ * ids (never the content key); the owner 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, docId: String, requesterId: String, name: String): Boolean {+ val ownerBundle = getKey(ownerId) ?: return false+ val req = json.encodeToString(JoinRequest(docId = docId, requesterId = requesterId, name = name))+ val blob = Base64.encode(Pqc.encryptTo(ownerBundle, req.encodeToByteArray()))+ return append("inbox:$ownerId", listOf(blob)) != null+ }+ 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)+ }++ /**+ * Tolerant inbox reader: decrypts each blob and sorts it into invites (default kind,+ * for backward compatibility with existing installs) 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) } suspend fun securityCode(peerBundle: ByteArray): String? =@@ -225,7 +256,19 @@ object OfficeSync { val charKind: String = "", ) + /** A request to join a document, sealed to the owner. Public ids only — no key. */+ @Serializable data class JoinRequest(+ val kind: String = "req",+ val docId: 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 = "")+ class InvitesResult(val invites: List<Invite>, val seq: Int)+ class InboxResult(val invites: List<Invite>, val requests: List<JoinRequest>, val seq: Int) class DocActionsResult(val items: List<String>, val seq: Int) @Serializable private data class SubMsg(val t: String, val channel: String)
office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt
diff --git a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.ktindex 0389b13eb2..0e7edc48be 100644--- a/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt+++ b/office/src/main/java/com/vayunmathur/office/util/OfficeViewModel.kt@@ -2030,6 +2030,11 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) /** Documents in the "online" folder: created/shared by you or shared with you. */ val onlineDocs: StateFlow<List<OfficeDocMeta>> = _onlineDocs.asStateFlow() + private val _pendingRequests = MutableStateFlow<List<OfficeSync.JoinRequest>>(emptyList())+ /** Inbound join requests (from tapped share links) for documents this device owns. */+ val pendingRequests: StateFlow<List<OfficeSync.JoinRequest>> = _pendingRequests.asStateFlow()+ private val requestsMutex = Mutex()+ /** The online doc id/key of the currently open document, if it lives online. */ private var currentDocId: String? = null private var currentDocKey: ByteArray? = null@@ -2253,7 +2258,9 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) if (!_onlineEnabled.value) _onlineEnabled.value = true runCatching { OfficeSync.init(getApplication())- _onlineDocs.value = loadIndex(DataStoreUtils.getInstance(getApplication()))+ val ds = DataStoreUtils.getInstance(getApplication())+ _onlineDocs.value = loadIndex(ds)+ _pendingRequests.value = loadRequests(ds) } refreshOnline() }@@ -2269,6 +2276,67 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) _onlineDocs.value = list } + private suspend fun loadRequests(ds: DataStoreUtils): List<OfficeSync.JoinRequest> =+ ds.getString("officePendingRequests")+ ?.let { runCatching { syncJson.decodeFromString<List<OfficeSync.JoinRequest>>(it) }.getOrNull() }+ ?: emptyList()++ private suspend fun saveRequests(ds: DataStoreUtils, list: List<OfficeSync.JoinRequest>) {+ ds.setString("officePendingRequests", syncJson.encodeToString(list))+ _pendingRequests.value = list+ }++ private suspend fun removePendingRequest(docId: String, requesterId: String) {+ val ds = DataStoreUtils.getInstance(getApplication())+ requestsMutex.withLock {+ saveRequests(ds, loadRequests(ds).filterNot { it.docId == docId && it.requesterId == requesterId })+ }+ }++ /** Builds a tappable invite link for a document this device owns (public ids only). */+ fun shareLinkFor(docId: String): String = "office://join/$docId?owner=${OfficeSync.deviceId}"++ /**+ * Sends a PQC-sealed join request to [ownerId]'s inbox after ensuring this device is registered.+ * Called when the user taps an `office://join` link. [onResult] receives whether it was delivered.+ */+ fun requestToJoin(docId: String, ownerId: String, onResult: (Boolean) -> Unit = {}) {+ viewModelScope.launch(Dispatchers.IO) {+ val ok = runCatching {+ if (!_onlineEnabled.value) _onlineEnabled.value = true+ OfficeSync.init(getApplication())+ OfficeSync.sendJoinRequest(ownerId, docId, OfficeSync.deviceId, myName())+ }.getOrDefault(false)+ withContext(Dispatchers.Main) { onResult(ok) }+ }+ }++ /**+ * Approves a pending join request by sealing the existing invite to the requester (reusing the+ * stored [OfficeDocMeta], so the document need not be open) and recording them on the roster.+ */+ fun approveJoinRequest(docId: String, requesterId: String, name: String = "", onResult: (Boolean) -> Unit = {}) {+ viewModelScope.launch(Dispatchers.IO) {+ val ok = runCatching {+ OfficeSync.init(getApplication())+ val ds = DataStoreUtils.getInstance(getApplication())+ val meta = indexMutex.withLock { loadIndex(ds) }.firstOrNull { it.docId == docId }+ if (meta == null || !meta.owner) return@runCatching false+ val key = Base64.decode(meta.keyB64)+ // Record the new member on the owner-signed roster, then seal the invite to them.+ writeMembers(docId, key, listOf(OfficeMember(requesterId, name, OfficeRoles.EDITOR)))+ OfficeSync.sendInvite(requesterId, docId, key, meta.title, meta.charMode, OfficeRoles.EDITOR, meta.ownerKeyB64, meta.charKind)+ }.getOrDefault(false)+ if (ok) removePendingRequest(docId, requesterId)+ withContext(Dispatchers.Main) { onResult(ok) }+ }+ }++ /** Drops a pending join request locally without granting access. */+ fun denyRequest(docId: String, requesterId: String) {+ viewModelScope.launch(Dispatchers.IO) { removePendingRequest(docId, requesterId) }+ }+ /** Pulls new invites from this device's inbox and merges them into the online list; refreshes titles. */ fun refreshOnline() { if (!_onlineEnabled.value && !hasOnlineIdentity()) return@@ -2277,7 +2345,7 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) OfficeSync.init(getApplication()) val ds = DataStoreUtils.getInstance(getApplication()) val cursor = ds.getLong("officeInboxCursor")?.toInt() ?: 0- val res = OfficeSync.pullInvites(cursor)+ val res = OfficeSync.pullInbox(cursor) if (res.invites.isNotEmpty()) { indexMutex.withLock { val index = loadIndex(ds).associateBy { it.docId }.toMutableMap()@@ -2287,6 +2355,19 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) saveIndex(ds, index.values.toList()) } }+ if (res.requests.isNotEmpty()) {+ // Only surface requests for docs this device owns; dedup by (docId, requesterId).+ val owned = indexMutex.withLock { loadIndex(ds) }.filter { it.owner }.map { it.docId }.toSet()+ requestsMutex.withLock {+ val existing = loadRequests(ds).toMutableList()+ for (r in res.requests) {+ if (r.docId in owned && existing.none { it.docId == r.docId && it.requesterId == r.requesterId }) {+ existing.add(r)+ }+ }+ saveRequests(ds, existing)+ }+ } ds.setLong("officeInboxCursor", res.seq.toLong()) // Pick up any owner rename for docs we already have (network done outside the lock). val current = indexMutex.withLock { loadIndex(ds) }@@ -2538,6 +2619,12 @@ class OfficeViewModel(application: Application) : AndroidViewModel(application) /** Owner-signs and appends member records to the (encrypted) members channel. Owner only. */ private suspend fun recordMembers(docId: String, key: ByteArray, members: List<OfficeMember>) { if (currentRole != OfficeRoles.OWNER) return+ writeMembers(docId, key, members)+ }++ /** Signs + appends member records without the open-doc owner guard. Callers must be the owner+ * (e.g. verified via the stored meta's `owner` flag) since signing uses this device's key. */+ private suspend fun writeMembers(docId: String, key: ByteArray, members: List<OfficeMember>) { runCatching { val items = members.map { m -> val sig = Base64.encode(OfficeSync.sign(memberSigningBytes(docId, m)))
office/src/main/res/values/strings.xml
diff --git a/office/src/main/res/values/strings.xml b/office/src/main/res/values/strings.xmlindex 361937c6d6..9a2b010198 100644--- a/office/src/main/res/values/strings.xml+++ b/office/src/main/res/values/strings.xml@@ -212,6 +212,24 @@ <string name="make_viewer">Make viewer</string> <!-- MainActivity: Menu share online with ellipsis alternative --> <string name="share_online_1">Share online…</string>+ <!-- OnlineTab/ShareOnlineDialog: Button that opens the share sheet with a join link. Verb phrase -->+ <string name="share_link">Share link</string>+ <!-- OnlineTab/ShareOnlineDialog: Title of the share chooser for the join link. Noun phrase -->+ <string name="share_link_chooser">Share Office invite</string>+ <!-- OnlineTab: Header for the inbound join-requests section. Noun -->+ <string name="requests_header">Requests</string>+ <!-- OnlineTab: Button to approve a join request. Verb -->+ <string name="approve">Approve</string>+ <!-- OnlineTab: Button to deny a join request. Verb -->+ <string name="deny">Deny</string>+ <!-- OnlineTab: A join request line: %1$s = requester, %2$s = document title. Sentence -->+ <string name="request_wants_to_join">%1$s wants to join \"%2$s\"</string>+ <!-- MainActivity: Toast while a join request is being sent. Sentence -->+ <string name="join_request_sending">Requesting access…</string>+ <!-- MainActivity: Toast when a join request was delivered. Sentence -->+ <string name="join_request_sent">Request sent — you\'ll get access once the owner approves.</string>+ <!-- MainActivity: Toast when a join request could not be delivered. Sentence -->+ <string name="join_request_failed">Couldn\'t send request — check your connection and try again.</string> <!-- MainActivity: Menu image with ellipsis --> <string name="image_1">Image…</string> <!-- MainActivity: Menu insert time field -->