Modern Apps git
git clone https://git.maproj.org/Modern-Apps.git
dependencies ▾

Modern-Apps.git / communicate-dev / src / main / java / com / vayunmathur / communicate / data / rcs / RcsSessionFocus.kt

RcsSessionFocus.kt339 lines · 14.1 KiBRaw
1package com.vayunmathur.communicate.data.rcs
2
3import com.vayunmathur.library.log.Log
4import java.util.UUID
5import java.util.concurrent.ConcurrentHashMap
6
7/**
8 * Conference focus management for [RcsSessionManager], split for file length.
9 * Extension functions + focus-owned state (member sets, event subscriptions,
10 * subscriber lists, version counters). The dialog/session core stays in the
11 * manager; everything focus-shaped lives here.
12 */
13
14/** Participants of hosted foci: focus URI → member E.164 set. */
15private val focusMembersMap = ConcurrentHashMap<String, MutableSet<String>>()
16
17/**
18 * Conference-event subscriptions WE hold (focus URI → dialog data for
19 * the SUBSCRIBE dialog to a carrier focus, §3.1).
20 */
21private data class EventSubscription(
22 val focusUri: String,
23 val callId: String,
24 val localTag: String,
25 val remoteTag: String = "",
26 val lastVersion: Int = -1,
27)
28
29private val eventSubs = ConcurrentHashMap<String, EventSubscription>()
30
31/**
32 * SUBSCRIBE dialogs on hosted foci (subscriber Call-ID → focus URI, §3.1
33 * publish side). NOTIFYs go out on each membership change.
34 */
35private val focusSubscribers = ConcurrentHashMap<String, String>()
36
37/** Conference-info version counter per hosted focus. */
38private val focusVersions = ConcurrentHashMap<String, Int>()
39
40/**
41 * Host a group conference (focus role, UP 3.x conference model).
42 *
43 * Unlike joining a carrier focus via [RcsSessionManager.startGroupSession],
44 * this makes US the focus: we allocate a local `conf:` URI, invite each
45 * participant with a REFER to it (their clients INVITE back and join — see
46 * the inbound INVITE-to-focus path in `onSipRequest`), and relay
47 * in-conference messages to the other participants (see
48 * `RcsSyncService.handleInbound` — relay happens there, keyed off the
49 * focus session map below).
50 *
51 * Focus INVITEs carry the `isfocus` Contact parameter (RFC 4354) + the CPM
52 * group tag so peers treat us as the conference server rather than a 1:1
53 * caller. Returns the focus URI on success, null otherwise.
54 *
55 * v1 limits: relay is pager-mode MESSAGE fan-out (no MSRP media mixing);
56 * MLS E2EE still terminates per-member via the conversation's MLS group —
57 * the focus relays opaque ciphertext, never plaintext.
58 */
59suspend fun RcsSessionManager.hostGroupFocus(
60 conversationId: String,
61 subject: String,
62 participants: List<String>,
63): String? {
64 if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return null
65 val distinct = participants.map { it.trim() }.filter { it.isNotEmpty() }.distinct()
66 if (distinct.isEmpty()) return null
67 val focusUri = "conf:${UUID.randomUUID()}@rcs.local"
68 val localTag = UUID.randomUUID().toString().take(8)
69 sessionsMutable.value = sessionsMutable.value + (conversationId to RcsSession(
70 dialogId = "focus:$focusUri",
71 callId = "focus-${UUID.randomUUID()}",
72 localTag = localTag,
73 remoteTag = "",
74 remoteUri = focusUri,
75 conversationId = conversationId,
76 isGroup = true,
77 isFocus = true,
78 ))
79 focusMembersMap[focusUri] = distinct.toMutableSet()
80 var invited = false
81 for (peer in distinct) {
82 if (sendReferToFocus(peer, focusUri, subject)) invited = true
83 }
84 if (!invited) {
85 sessionsMutable.value = sessionsMutable.value - conversationId
86 focusMembersMap.remove(focusUri)
87 return null
88 }
89 Log.status(TAG, "Hosting focus $focusUri for $conversationId (${distinct.size} invited)")
90 return focusUri
91}
92
93/** Members of the hosted focus [focusUri], or null when not ours. */
94fun RcsSessionManager.focusMembers(focusUri: String): Set<String>? =
95 focusMembersMap[focusUri]?.toSet()
96
97/** Focus URI we host for [conversationId], or null when we don't host it. */
98fun RcsSessionManager.hostedFocusFor(conversationId: String): String? {
99 val session = sessionsMutable.value[conversationId] ?: return null
100 return if (session.isFocus) session.remoteUri else null
101}
102
103/** Track a joiner that INVITEd our focus URI (no REFER needed — direct dial). */
104fun RcsSessionManager.noteFocusJoin(focusUri: String, member: String) {
105 focusMembersMap[focusUri]?.add(member.trim())
106}
107
108/** Drop a member from a hosted focus (BYE / removal). */
109fun RcsSessionManager.noteFocusLeave(focusUri: String, member: String) {
110 focusMembersMap[focusUri]?.remove(member.trim())
111}
112
113/** Tear down a hosted focus: BYE every joined member dialog, drop state. */
114suspend fun RcsSessionManager.destroyHostedFocus(conversationId: String): Boolean {
115 val session = sessionsMutable.value[conversationId] ?: return true
116 if (!session.isFocus) return terminateSession(conversationId)
117 val focusUri = session.remoteUri
118 // BYE every joined member dialog first (§3.2), best-effort.
119 val members = focusMembersMap.remove(focusUri)?.toList().orEmpty()
120 for (member in members) {
121 runCatching {
122 val dialogEntry = sessionsMutable.value.entries.firstOrNull {
123 it.value.callId.endsWith(member.hashCode().toString()) ||
124 it.value.remoteUri == member
125 }
126 if (dialogEntry != null) terminateSession(dialogEntry.key)
127 }
128 }
129 focusSubscribers.entries.removeIf { it.value == focusUri }
130 focusVersions.remove(focusUri)
131 sessionsMutable.value = sessionsMutable.value - conversationId
132 RcsMsrpListen.dropPending(conversationId)
133 return true
134}
135
136/**
137 * Invite [peer] to our hosted [focusUri]: REFER + member-set add (§3.2).
138 * Returns true when the REFER was accepted by the transport. Publishes a
139 * conference-info NOTIFY to subscribers on change.
140 */
141suspend fun RcsSessionManager.inviteFocusMember(
142 conversationId: String,
143 peer: String,
144 subject: String = "",
145): Boolean {
146 if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false
147 val session = sessionsMutable.value[conversationId]?.takeIf { it.isFocus } ?: return false
148 val member = peer.trim()
149 if (member.isEmpty()) return false
150 val ok = sendReferToFocus(member, session.remoteUri, subject)
151 if (ok) {
152 focusMembersMap[session.remoteUri]?.add(member)
153 publishConferenceInfo(session.remoteUri)
154 }
155 return ok
156}
157
158/**
159 * Remove [peer] from our hosted focus: BYE their dialog + member-set
160 * drop (§3.2). Returns true when the member was tracked (BYE itself is
161 * best-effort). Publishes a conference-info NOTIFY to subscribers.
162 */
163suspend fun RcsSessionManager.removeFocusMember(conversationId: String, peer: String): Boolean {
164 if (!RcsFeature.enabled) return false
165 val session = sessionsMutable.value[conversationId]?.takeIf { it.isFocus } ?: return false
166 val member = peer.trim()
167 val removed = focusMembersMap[session.remoteUri]?.remove(member) == true
168 // BYE any dialog joined by this member.
169 val dialogEntry = sessionsMutable.value.entries.firstOrNull {
170 !it.value.isFocus && it.value.remoteUri == member &&
171 it.value.conversationId == conversationId
172 }
173 if (dialogEntry != null && RcsSipTransport.canSend()) {
174 runCatching { terminateSession(dialogEntry.key) }
175 }
176 noteFocusLeave(session.remoteUri, member)
177 publishConferenceInfo(session.remoteUri)
178 return removed
179}
180
181/**
182 * SUBSCRIBE to `Event: conference` at a carrier [focusUri] (§3.1) so
183 * participant joins/parts arrive as NOTIFYs. Out-of-dialog subscription;
184 * refresh is the caller's job (see [refreshEventSubscriptions]).
185 */
186suspend fun RcsSessionManager.subscribeConferenceEvents(focusUri: String, conversationId: String): Boolean {
187 if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return false
188 if (eventSubs.containsKey(conversationId)) return true
189 val cfg = RcsSipTransport.lastConfigSnapshot()
190 val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"
191 val callId = "${UUID.randomUUID()}@rcs-sub"
192 val localTag = UUID.randomUUID().toString().take(8)
193 val branch = RcsSipDialog.newBranch()
194 val startLine = "SUBSCRIBE $focusUri SIP/2.0"
195 val headers = buildString {
196 append("Via: SIP/2.0/TCP local;branch=$branch\r\n")
197 append("Max-Forwards: 70\r\n")
198 append("From: <$from>;tag=$localTag\r\n")
199 append("To: <$focusUri>\r\n")
200 append("Call-ID: $callId\r\n")
201 append("CSeq: 1 SUBSCRIBE\r\n")
202 append("Event: conference\r\n")
203 append("Accept: application/conference-info+xml\r\n")
204 append("Expires: 3600\r\n")
205 append("Contact: <$from>\r\n")
206 append("Content-Length: 0\r\n")
207 }
208 val ok = RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0))
209 if (ok) {
210 eventSubs[conversationId] = EventSubscription(focusUri, callId, localTag)
211 }
212 return ok
213}
214
215/**
216 * Refresh conference-event subscriptions (re-SUBSCRIBE before expiry).
217 * Called periodically by the sync service; each refresh bumps CSeq.
218 */
219suspend fun RcsSessionManager.refreshEventSubscriptions() {
220 if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return
221 for ((conversationId, sub) in eventSubs) {
222 runCatching {
223 val cfg = RcsSipTransport.lastConfigSnapshot()
224 val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"
225 val branch = RcsSipDialog.newBranch()
226 val headers = buildString {
227 append("Via: SIP/2.0/TCP local;branch=$branch\r\n")
228 append("Max-Forwards: 70\r\n")
229 append("From: <$from>;tag=${sub.localTag}\r\n")
230 append("To: <${sub.focusUri}>;tag=${sub.remoteTag}\r\n")
231 append("Call-ID: ${sub.callId}\r\n")
232 append("CSeq: 2 SUBSCRIBE\r\n")
233 append("Event: conference\r\n")
234 append("Accept: application/conference-info+xml\r\n")
235 append("Expires: 3600\r\n")
236 append("Contact: <$from>\r\n")
237 append("Content-Length: 0\r\n")
238 }
239 RcsSipTransport.sendSipMessage("SUBSCRIBE ${sub.focusUri} SIP/2.0", headers, ByteArray(0))
240 }
241 }
242}
243
244/**
245 * Route an inbound conference-info NOTIFY body for [conversationId]:
246 * reconcile added members in + deleted members out, returning the added
247 * + removed URI lists. Stale versions (≤ last seen) are ignored.
248 */
249fun RcsSessionManager.onConferenceNotify(conversationId: String, body: String): Pair<List<String>, List<String>> {
250 val info = RcsConferenceEvents.parseConferenceInfo(body) ?: return emptyList<String>() to emptyList()
251 val sub = eventSubs[conversationId]
252 if (sub != null && info.version <= sub.lastVersion) return emptyList<String>() to emptyList()
253 if (sub != null) eventSubs[conversationId] = sub.copy(lastVersion = info.version)
254 val added = info.users.map { it.uri }.filter { it.isNotBlank() }
255 val removed = RcsConferenceEvents.deletedUris(body)
256 // Reconcile hosted-focus membership when the NOTIFY targets our focus.
257 val hosted = sessionsMutable.value[conversationId]?.takeIf { it.isFocus }
258 if (hosted != null) {
259 focusMembersMap[hosted.remoteUri]?.let { set ->
260 set.removeAll(removed.toSet())
261 set.addAll(added)
262 }
263 }
264 return added to removed
265}
266
267/** Record an inbound SUBSCRIBE to our hosted focus (NOTIFY target). */
268fun RcsSessionManager.noteFocusSubscriber(subscriberCallId: String, focusUri: String) {
269 focusSubscribers[subscriberCallId] = focusUri
270}
271
272/** Drop a focus subscriber (unsubscribe / expiry). */
273fun RcsSessionManager.dropFocusSubscriber(subscriberCallId: String) {
274 focusSubscribers.remove(subscriberCallId)
275}
276
277/**
278 * Publish `conference-info` NOTIFYs to all subscribers of [focusUri]
279 * (§3.1 publish side). Best-effort per subscriber; never throws.
280 */
281suspend fun RcsSessionManager.publishConferenceInfo(focusUri: String) {
282 if (!RcsFeature.enabled || !RcsSipTransport.canSend()) return
283 val members = focusMembersMap[focusUri]?.toList() ?: return
284 val subscribers = focusSubscribers.entries.filter { it.value == focusUri }
285 if (subscribers.isEmpty()) return
286 val version = (focusVersions[focusUri] ?: 0) + 1
287 focusVersions[focusUri] = version
288 val body = RcsConferenceEvents.buildConferenceInfo(focusUri, version, members)
289 .toByteArray(Charsets.UTF_8)
290 val cfg = RcsSipTransport.lastConfigSnapshot()
291 val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"
292 for ((subCallId, _) in subscribers) {
293 runCatching {
294 val branch = RcsSipDialog.newBranch()
295 val headers = buildString {
296 append("Via: SIP/2.0/TCP local;branch=$branch\r\n")
297 append("Max-Forwards: 70\r\n")
298 append("From: <$from>;tag=${UUID.randomUUID().toString().take(8)}\r\n")
299 append("To: <$focusUri>\r\n")
300 append("Call-ID: $subCallId\r\n")
301 append("CSeq: 1 NOTIFY\r\n")
302 append("Event: conference\r\n")
303 append("Subscription-State: active;expires=3600\r\n")
304 append("Content-Type: application/conference-info+xml\r\n")
305 append("Content-Length: ${body.size}\r\n")
306 }
307 RcsSipTransport.sendSipMessage("NOTIFY $focusUri SIP/2.0", headers, body)
308 }
309 }
310}
311
312/**
313 * REFER one peer to our hosted focus: `REFER sip:peer` with `Refer-To:
314 * <focusUri>` + `Referred-By` us. Their client INVITEs the focus URI back.
315 */
316internal suspend fun RcsSessionManager.sendReferToFocus(
317 peer: String,
318 focusUri: String,
319 subject: String,
320): Boolean {
321 val cfg = RcsSipTransport.lastConfigSnapshot()
322 val from = cfg?.publicUserId?.takeIf { it.isNotBlank() } ?: "sip:local@rcs"
323 val branch = RcsSipDialog.newBranch()
324 val startLine = "REFER sip:$peer@rcs SIP/2.0"
325 val headers = buildString {
326 append("Via: SIP/2.0/TCP local;branch=$branch\r\n")
327 append("Max-Forwards: 70\r\n")
328 append("From: <$from>;tag=${UUID.randomUUID().toString().take(8)}\r\n")
329 append("To: <sip:$peer@rcs>\r\n")
330 append("Call-ID: ${UUID.randomUUID()}@rcs-refer\r\n")
331 append("CSeq: 1 REFER\r\n")
332 append("Refer-To: <$focusUri>\r\n")
333 append("Referred-By: <$from>\r\n")
334 if (subject.isNotBlank()) append("Subject: $subject\r\n")
335 append("Contact: <$from>;isfocus\r\n")
336 append("Content-Length: 0\r\n")
337 }
338 return RcsSipTransport.sendSipMessage(startLine, headers, ByteArray(0))
339}