@poolse/native 3.7.1 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +43 -0
  2. package/README.md +94 -1
  3. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +8 -0
  4. package/android/src/main/java/dev/poolse/callcore/CallServers.kt +72 -0
  5. package/android/src/main/java/dev/poolse/callcore/Ports.kt +34 -0
  6. package/android/src/main/java/dev/poolse/callcore/RoutedHttpPort.kt +74 -0
  7. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +3 -3
  8. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +131 -14
  9. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +3 -0
  10. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +4 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +1 -1
  12. package/android/src/main/java/dev/poolse/callcore/android/MessageActionWorker.kt +35 -12
  13. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +142 -48
  14. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +8 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/PoolseIncomingCall.kt +16 -0
  16. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +6 -0
  17. package/android/src/main/java/dev/poolse/callcore/android/ServerRegistry.kt +107 -0
  18. package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +23 -0
  19. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +58 -7
  20. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +96 -9
  21. package/dist/index.cjs +83 -24
  22. package/dist/index.cjs.map +1 -1
  23. package/dist/index.d.cts +156 -9
  24. package/dist/index.d.ts +156 -9
  25. package/dist/index.js +77 -25
  26. package/dist/index.js.map +1 -1
  27. package/ios/Core/CallCoreRuntime.swift +8 -0
  28. package/ios/Core/CallHttpClient.swift +11 -1
  29. package/ios/Core/CallServers.swift +89 -0
  30. package/ios/Core/Ports.swift +35 -2
  31. package/ios/Core/RoutedHttpPort.swift +83 -0
  32. package/ios/Core/SnapshotEncoding.swift +17 -1
  33. package/ios/Module/PoolseCallsModule.swift +50 -8
  34. package/ios/Platform/CallCore.swift +132 -12
  35. package/ios/Platform/CallKitController.swift +4 -1
  36. package/ios/Platform/LiveKitMediaPort.swift +103 -14
  37. package/ios/Platform/MessageNotifications.swift +76 -23
  38. package/ios/Platform/ServerRegistry.swift +90 -0
  39. package/ios/Platform/VoipPush.swift +5 -1
  40. package/package.json +1 -1
  41. package/src/index.ts +265 -31
package/CHANGELOG.md CHANGED
@@ -2,6 +2,49 @@
2
2
 
3
3
  Formerly `@poolse/react-native-calls` (0.x).
4
4
 
5
+ ## 3.9.0 — 2026-11-22
6
+
7
+ - Recording and transcripts (server docs/RECORDING.md). poolse's transcript
8
+ assistant (`poolse:…`, LiveKit kind agent) and LiveKit Egress's recorder
9
+ (`EG_…`, kind egress) are no longer reported as people: they are left out of
10
+ `participants`, video tiles, "someone answered" and the count that ends a
11
+ call left alone (SIP participants stay).
12
+ - Snapshots carry `canPublish`, `recording` and `transcription` (the
13
+ CallSummary's objects from answer / join / place / reconnect; `null` from a
14
+ server without them). New types `CallRecordingState`, `CallTranscriptionState`.
15
+ - Recording consent: when the server revokes publishing, the core stops
16
+ publishing without errors and keeps the mic / camera choices; when it comes
17
+ back it republishes them. `republish()` (for ConsentPrompt's `onAccepted`)
18
+ and `onCanPublishChange(cb)`.
19
+
20
+ ## 3.8.0 — 2026-11-21
21
+
22
+ - Several workspaces (servers) at once:
23
+ `addServer({ id, apiBaseUrl, tenantId?, name? })`, `removeServer(id)`,
24
+ `listServers()`, `serverOfNotification(data)` and `DEFAULT_SERVER_ID`; `configure(apiBaseUrl, options)` is unchanged and
25
+ sets the `default` server, `configure(options)` sets the options alone.
26
+ Persisted, so a ring or a notification action with the app closed finds its
27
+ server; a single-server install migrates to `default` on upgrade.
28
+ - Calls: a push's `tenant_id` picks its server; answer, decline, busy-decline,
29
+ hang-up and reconnect go to the server the call came from. `place` /
30
+ `startRoom` take `serverId`, `join` a 4th `serverId` argument;
31
+ `ringIntoCall` uses the call's own server. A ring from another workspace
32
+ during a call is call waiting (CallKit End & Accept, Android End & answer).
33
+ Snapshots and `waiting` carry `serverId` and `workspaceName`.
34
+ - With two or more servers, CallKit, the Android ring screen and the
35
+ call-waiting heads-up read "Ana · Acme" (`workspace_name` from the push, else
36
+ the server's `name`). Custom ring Activities get `EXTRA_SERVER_ID` and
37
+ `EXTRA_WORKSPACE_NAME`.
38
+ - Notifications: Reply / Mark as read are sent to the notification's server and
39
+ report `serverId`; Android taps carry `CallAction.serverId`. Android groups
40
+ chats per workspace (own group, summary, and a "Messages" channel in a
41
+ channel group named after it) and shows the workspace as subtext; iOS clears
42
+ per workspace (thread ids may be `<tenant_id>:<conversation_id>`) and a
43
+ failed-reply notice keeps the workspace. `setActiveConversation` takes an
44
+ optional `serverId`; `removeServer` takes the workspace's notifications down.
45
+ - Fix (Android): Mark as read from a notification lost its grant when the
46
+ notification was cleared first, and failed with `no_grant`.
47
+
5
48
  ## 3.7.1 — 2026-11-21
6
49
 
7
50
  - No changes; released with the other `@poolse/*` packages at 3.7.1.
package/README.md CHANGED
@@ -106,6 +106,12 @@ The full API:
106
106
  - Chat notifications: `setActiveConversation`, `shouldPresentMessage`,
107
107
  `conversationOfNotification`, `onNotificationAction`,
108
108
  `onNotificationReply`, `takeNotificationActions` (see below).
109
+ - Several workspaces: `addServer`, `removeServer`, `listServers`,
110
+ `serverOfNotification`, `DEFAULT_SERVER_ID`, `serverId` on `place` / `join`
111
+ / `startRoom` and in snapshots, taps and action results (see below).
112
+ - Recording and transcripts: `snapshot.recording` / `snapshot.transcription`
113
+ (the server's state as of joining), `snapshot.canPublish`,
114
+ `onCanPublishChange`, `republish` (see below).
109
115
  - Socket forwarding (optional): `onCallFinished`, `onRingEnded`. Feed them
110
116
  from `@poolse/sdk` 3.1's user channel:
111
117
 
@@ -115,6 +121,36 @@ The full API:
115
121
  userChannel.onCallFinished((e) => calls.onCallFinished(e.call_id, e.reason));
116
122
  ```
117
123
 
124
+ ## Recording, consent and transcripts
125
+
126
+ When the server records or transcribes a call (docs/RECORDING.md on the
127
+ server), the core:
128
+
129
+ - leaves poolse's own participants out of everything it reports — the
130
+ transcript assistant (`poolse:assistant:…`, LiveKit kind agent) and the
131
+ recorder (LiveKit Egress, `EG_…`). They are never in
132
+ `snapshot.participants`, never get a video tile, never count as someone
133
+ answering, and don't keep a call alive when everyone else has left.
134
+ Phone (SIP) participants are listed as usual.
135
+ - carries the call's `recording` and `transcription` objects into the
136
+ snapshot, as the server sent them on answer / join / place and each
137
+ reconnect, so the indicator shows without another request. Later changes
138
+ come on the conversation socket (`recording:*`, `transcript:*`): use those
139
+ for anything after joining.
140
+ - follows the server's publish permission. With `consent: "required"`, the
141
+ server turns publishing off until you accept: `snapshot.canPublish` turns
142
+ `false`, nothing of yours goes out (you still hear and see the call), and
143
+ mute / camera taps are remembered rather than refused. Once you accept,
144
+ the server turns it back on and the core publishes the mic and camera as
145
+ you last had them. Call `republish()` from ConsentPrompt's `onAccepted` as
146
+ well; it is harmless before the permission is back.
147
+
148
+ ```ts
149
+ <ConsentPrompt onAccepted={() => calls.republish()} … />
150
+
151
+ const off = calls.onCanPublishChange((allowed) => setListenOnly(!allowed));
152
+ ```
153
+
118
154
  ## Ringtone
119
155
 
120
156
  ```json
@@ -233,7 +269,8 @@ into a Reply button with a text field and a Mark as read button, and sends
233
269
  them itself — from the lock screen, with the app closed, with no session
234
270
  and no JS — to `POST /v1/notification-actions/reply` and `/read` on the API
235
271
  origin you passed to `configure` (persisted, so call it once on every app
236
- start as usual).
272
+ start as usual), or on the notification's own server with several (see
273
+ [Signed in to several workspaces](#signed-in-to-several-workspaces)).
237
274
 
238
275
  - **iOS**: the core registers the `poolse_message` category (actions `reply`
239
276
  and `mark_read`) beside the app's own categories at launch, and handles the
@@ -285,6 +322,62 @@ expo-notifications also hands these responses to its own JS listeners: in
285
322
  `addNotificationResponseReceivedListener`, ignore an `actionIdentifier` of
286
323
  `reply` or `mark_read` (only the default tap should open the chat).
287
324
 
325
+ ## Signed in to several workspaces
326
+
327
+ The core can serve several API servers at once — one per workspace the user
328
+ is signed in to. `configure(apiBaseUrl)` is still all a single-server app
329
+ needs: that server is `default` (`DEFAULT_SERVER_ID`), and everything below
330
+ is optional. Add the others (or all of them, with `configure(options)` for
331
+ the options alone):
332
+
333
+ ```ts
334
+ await calls.configure({ ringback: 'ringback', apnsEnvironment: 'production' });
335
+ await calls.addServer({
336
+ id: 'acme', // your id: 1–64 of A–Z a–z 0–9 . _ : -
337
+ apiBaseUrl: 'https://chat.acme.example',
338
+ tenantId: me.tenant_id, // the poolse tenant of this sign-in
339
+ name: 'Acme',
340
+ });
341
+ // …and register the device's push tokens with each server's client
342
+ // (`devices.register`, VoIP + alert on iOS, FCM on Android).
343
+
344
+ await calls.place(conversationId, { media: 'audio', sessionToken, serverId: 'acme' });
345
+ await calls.join(callId, conversationId, sessionToken, 'acme');
346
+
347
+ // Signed out of one workspace (unregister its tokens there first):
348
+ await calls.removeServer('acme');
349
+ ```
350
+
351
+ - **Routing.** A push's `tenant_id` picks its server — the one added with that
352
+ `tenantId` (pass it as soon as there are two servers). Rings are answered and
353
+ declined on their own server, with their own grant; place / join / rooms go
354
+ where `serverId` says, and hang-up, reconnect and `ringIntoCall` follow the
355
+ call. A push with no known tenant goes to the only server, else the only one
356
+ without a `tenantId`, else `default`.
357
+ - **One call at a time.** A ring from another workspace during a call is call
358
+ waiting, exactly like one from the same workspace: CallKit's End & Accept /
359
+ Decline, Android's heads-up with End & answer / Decline. Each goes to the
360
+ server the ring came from.
361
+ - **Names.** With two or more servers added, CallKit and the Android ring
362
+ screen, call-waiting heads-up and notifications show the workspace: "Ana ·
363
+ Acme" (the push's `workspace_name`, else the server's `name`).
364
+ `snapshot.serverId` / `snapshot.workspaceName` and the same on
365
+ `snapshot.waiting` tell the app which workspace a call is on. Custom
366
+ incoming-call Activities get `EXTRA_SERVER_ID` (`poolse_server_id`) and
367
+ `EXTRA_WORKSPACE_NAME` (`poolse_workspace_name`, set only with several
368
+ servers).
369
+ - **Notifications.** Reply and Mark as read go to the notification's own
370
+ server; `NotificationActionResult.serverId` says which. Android: a missed call
371
+ or chat tap delivers `CallAction.serverId`; each server other than `default`
372
+ gets its own notification group, summary and "Messages" channel inside a
373
+ channel group named after the workspace (so it can be muted on its own); the
374
+ workspace is the notification's subtext while several are signed in. iOS: the
375
+ tap reaches your notification library — `serverOfNotification(data)` names
376
+ the workspace to open. Pass `setActiveConversation(conversationId, serverId)`.
377
+ - **Upgrading** keeps everything: the server a single-server build configured
378
+ becomes `default`, and its notifications, channel and stored chats are left
379
+ as they are.
380
+
288
381
  ## Links
289
382
 
290
383
  - Docs: <https://poolse.dev/docs/sdk/native>
@@ -143,6 +143,12 @@ class CallCoreRuntime(
143
143
  /** `room` or `call`, once the server's bundle says; null before. Runtime thread only. */
144
144
  val callKind: String? get() = bundle?.kind
145
145
 
146
+ /**
147
+ * The bundle's capture state (`recording`, `transcription` as JSON
148
+ * text), as of the last answer/join/place/reconnect. Runtime thread only.
149
+ */
150
+ val capture: Pair<String?, String?> get() = bundle?.recording to bundle?.transcription
151
+
146
152
  /**
147
153
  * The current call's id and control token — what authorizes acting on
148
154
  * the call itself (ringing more people in). Null with no session yet.
@@ -301,6 +307,8 @@ class CallCoreRuntime(
301
307
  fun switchCamera() = post { media.switchCamera() }
302
308
  fun setSpeaker(on: Boolean) = post { media.setSpeaker(on) }
303
309
  fun setAudioOutput(id: String) = post { media.setAudioOutput(id) }
310
+ /** Consent given: publish the mic/camera again (a no-op until the server allows it). */
311
+ fun republish() = post { media.republish() }
304
312
 
305
313
  /** Re-emit the current state (the bridge's roster/route changed). */
306
314
  fun reemit() = post { if (state.phase != Phase.IDLE) sink.emit(state) }
@@ -0,0 +1,72 @@
1
+ package dev.poolse.callcore
2
+
3
+ /**
4
+ * One API server the app is signed in to — a workspace. Holds no
5
+ * secrets: the push brings each ring's grant, and JS passes session
6
+ * tokens per place/join.
7
+ */
8
+ data class CallServer(
9
+ /** The host's own id for it (`addServer({ id })`); `default` is the one `configure(apiBaseUrl)` sets. */
10
+ val id: String,
11
+ val apiBaseUrl: String,
12
+ /** The poolse tenant it signs in to: how a push (`tenant_id`) finds its server. */
13
+ val tenantId: String? = null,
14
+ /** The workspace's name, when the push carries none ("Ana · Acme"). */
15
+ val name: String? = null,
16
+ )
17
+
18
+ /**
19
+ * The signed-in servers, in the order they were added, and the rules
20
+ * that route a push to one of them. Pure (no Android): the iOS twin is
21
+ * CallServers.swift.
22
+ */
23
+ data class CallServers(val all: List<CallServer> = emptyList()) {
24
+
25
+ val isMulti: Boolean get() = all.size > 1
26
+
27
+ fun get(id: String?): CallServer? = all.firstOrNull { it.id == (id ?: DEFAULT_ID) }
28
+
29
+ /** Adds or replaces (by id), keeping its place in the order. */
30
+ fun upsert(server: CallServer): CallServers {
31
+ val i = all.indexOfFirst { it.id == server.id }
32
+ return CallServers(if (i < 0) all + server else all.toMutableList().also { it[i] = server })
33
+ }
34
+
35
+ fun remove(id: String): CallServers = CallServers(all.filter { it.id != id })
36
+
37
+ /**
38
+ * The server a push belongs to: the one signed in to its `tenant_id`;
39
+ * else — an older server's push, or a host that left `tenantId` out —
40
+ * the only server, the only one without a tenant, the default, the
41
+ * first. Null only with no server at all. Never drops a ring: a wrong
42
+ * guess fails its answer, a dropped one never rings.
43
+ */
44
+ fun resolve(tenantId: String?): CallServer? {
45
+ if (tenantId != null) all.firstOrNull { it.tenantId == tenantId }?.let { return it }
46
+ if (all.size <= 1) return all.firstOrNull()
47
+ val untagged = all.filter { it.tenantId == null }
48
+ if (untagged.size == 1) return untagged[0]
49
+ return get(DEFAULT_ID) ?: untagged.firstOrNull() ?: all.firstOrNull()
50
+ }
51
+
52
+ /**
53
+ * The workspace a ring / notification is labelled with: the push's
54
+ * name, else the server's own. Null while only one server is signed in
55
+ * — a single-workspace app looks exactly as before.
56
+ */
57
+ fun workspaceLabel(serverId: String?, pushName: String?): String? {
58
+ if (!isMulti) return null
59
+ return pushName?.ifBlank { null } ?: get(serverId)?.name
60
+ }
61
+
62
+ companion object {
63
+ const val DEFAULT_ID = "default"
64
+
65
+ /** "Ana · Acme" — [base] with the workspace, when there is one to show (alone when the push named nobody). */
66
+ fun title(base: String?, workspace: String?): String? {
67
+ val w = workspace?.ifBlank { null } ?: return base
68
+ val b = base?.ifBlank { null } ?: return w
69
+ return "$b · $w"
70
+ }
71
+ }
72
+ }
@@ -57,6 +57,13 @@ data class CallSessionBundle(
57
57
  val kind: String = "call",
58
58
  /** How many people the server says are being rung right now. */
59
59
  val ringing: Int = 0,
60
+ /**
61
+ * The CallSummary's `recording` / `transcription` objects as JSON text
62
+ * (docs/RECORDING.md), carried to the snapshot untouched; null from a
63
+ * server before them.
64
+ */
65
+ val recording: String? = null,
66
+ val transcription: String? = null,
60
67
  )
61
68
 
62
69
  /** LiveKit (or any SFU) — media only, no lifecycle opinions. */
@@ -78,6 +85,25 @@ interface MediaPort {
78
85
  * speaker toggle.
79
86
  */
80
87
  fun setAudioOutput(id: String) = setSpeaker(id == "speaker")
88
+
89
+ /**
90
+ * Publish the mic and camera again as the user last had them, once the
91
+ * server lets this participant publish (consent given, docs/RECORDING.md §5).
92
+ */
93
+ fun republish() {}
94
+ }
95
+
96
+ /**
97
+ * poolse's own participants in a room — the transcript assistant
98
+ * (`poolse:assistant:<call>`, kind AGENT) and LiveKit Egress's recorder
99
+ * (`EG_…`, kind EGRESS). They are not people: never in the roster, never
100
+ * counted as someone in the call (docs/RECORDING.md §7). SIP (phone)
101
+ * participants are people and stay.
102
+ */
103
+ object ServiceParticipants {
104
+ /** [kind]: LiveKit's participant kind, lowercased (`agent`, `egress`, `sip`, …). */
105
+ fun isService(identity: String, kind: String?): Boolean =
106
+ identity.startsWith("poolse:") || identity.startsWith("EG_") || kind == "agent" || kind == "egress"
81
107
  }
82
108
 
83
109
  /** The ring UX: CallStyle notification + full-screen activity + tones. */
@@ -112,6 +138,14 @@ data class RingContext(
112
138
  val ringDeadlineEpochMs: Long,
113
139
  /** The caller's picture for the ring screen, if the push or the app's template gives one. */
114
140
  val callerAvatarUrl: String? = null,
141
+ /**
142
+ * The server (workspace) the ring came from — the host's id from
143
+ * `addServer`, resolved from the push's `tenant_id`. Its answer and
144
+ * decline go to that server. Null: the default server.
145
+ */
146
+ val serverId: String? = null,
147
+ /** The push's `workspace_name`, for "Ana · Acme" when several servers are signed in. */
148
+ val workspaceName: String? = null,
115
149
  )
116
150
 
117
151
  /** Android: the phoneCall foreground service. iOS: the CallKit session. */
@@ -0,0 +1,74 @@
1
+ package dev.poolse.callcore
2
+
3
+ /**
4
+ * One [HttpPort] for several API servers (signed in to several
5
+ * workspaces): each request goes to the server its call belongs to.
6
+ *
7
+ * The runtime stays single-server — it only knows call ids. The platform
8
+ * binds each call to its server as it enters (a ring's [RingContext.serverId],
9
+ * a place/join with the host's server id), and this port looks the call
10
+ * up per request. A placed call is keyed by its conversation until the
11
+ * server mints its id; the answer binds that id too. Unbound calls go to
12
+ * the default server (`null`), which is all a single-server app ever has.
13
+ *
14
+ * Thread-safe: rings are bound from the push thread, requests run on the
15
+ * runtime's.
16
+ */
17
+ class RoutedHttpPort(
18
+ /** The HTTP port of one server (`null` = the default one). */
19
+ private val portFor: (serverId: String?) -> HttpPort,
20
+ ) : HttpPort {
21
+
22
+ private val calls = LinkedHashMap<String, String>()
23
+ private val places = HashMap<String, String>()
24
+
25
+ /** The call [callId] belongs to [serverId] (`null` forgets it: the default server). */
26
+ @Synchronized
27
+ fun bindCall(callId: String, serverId: String?) {
28
+ calls.remove(callId)
29
+ if (serverId == null) return
30
+ calls[callId] = serverId
31
+ while (calls.size > MAX_BOUND) calls.remove(calls.keys.first())
32
+ }
33
+
34
+ /** The next call placed on [conversationId] goes to [serverId]. */
35
+ @Synchronized
36
+ fun bindPlace(conversationId: String, serverId: String?) {
37
+ if (serverId == null) places.remove(conversationId) else places[conversationId] = serverId
38
+ while (places.size > MAX_BOUND) places.remove(places.keys.first())
39
+ }
40
+
41
+ /** The server [callId] is bound to (a `pending:<conversation>` id: its place); null = the default. */
42
+ @Synchronized
43
+ fun serverFor(callId: String): String? =
44
+ if (callId.startsWith(PENDING)) places[callId.removePrefix(PENDING)] else calls[callId]
45
+
46
+ override fun answer(callId: String, grant: String, cb: (HttpResult) -> Unit) =
47
+ portFor(serverFor(callId)).answer(callId, grant, cb)
48
+
49
+ override fun join(callId: String, sessionToken: String, cb: (HttpResult) -> Unit) =
50
+ portFor(serverFor(callId)).join(callId, sessionToken, cb)
51
+
52
+ override fun place(conversationId: String, media: String, sessionToken: String, cb: (HttpResult) -> Unit) {
53
+ val server = synchronized(this) { places[conversationId] }
54
+ portFor(server).place(conversationId, media, sessionToken) { result ->
55
+ // Everything after the answer (hangup, reconnect) names the minted id.
56
+ if (result is HttpResult.Ok) bindCall(result.bundle.callId, server)
57
+ cb(result)
58
+ }
59
+ }
60
+
61
+ override fun decline(callId: String, auth: String, busy: Boolean) =
62
+ portFor(serverFor(callId)).decline(callId, auth, busy)
63
+
64
+ override fun hangup(callId: String, controlToken: String) =
65
+ portFor(serverFor(callId)).hangup(callId, controlToken)
66
+
67
+ override fun reconnect(current: CallSessionBundle, cb: (HttpResult) -> Unit) =
68
+ portFor(serverFor(current.callId)).reconnect(current, cb)
69
+
70
+ private companion object {
71
+ const val PENDING = "pending:"
72
+ const val MAX_BOUND = 64
73
+ }
74
+ }
@@ -115,7 +115,7 @@ internal class AndroidRingSurface(
115
115
  PendingIntent.getActivity(
116
116
  context,
117
117
  ring.callId.hashCode() + 6,
118
- PoolseIncomingCall.fill(custom, ring)
118
+ PoolseIncomingCall.fill(context, custom, ring)
119
119
  .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP),
120
120
  PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
121
121
  )
@@ -130,7 +130,7 @@ internal class AndroidRingSurface(
130
130
  val answer = incomingActivity(autoAnswer = true, requestOffset = 2)
131
131
 
132
132
  val caller = Person.Builder()
133
- .setName(ring.conversationName ?: ring.callerName ?: "Incoming call")
133
+ .setName(ServerRegistry.ringTitle(context, ring, ring.conversationName ?: ring.callerName) ?: "Incoming call")
134
134
  .setImportant(true)
135
135
  .build()
136
136
 
@@ -210,7 +210,7 @@ internal class AndroidRingSurface(
210
210
  PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
211
211
  )
212
212
 
213
- val who = ring.conversationName ?: ring.callerName ?: "Someone"
213
+ val who = ServerRegistry.ringTitle(context, ring, ring.conversationName ?: ring.callerName) ?: "Someone"
214
214
  val what = if (ring.media == "video") "video call" else "call"
215
215
  val notification = NotificationCompat.Builder(context, WAITING_CHANNEL_ID)
216
216
  .setSmallIcon(config.smallIcon)
@@ -10,7 +10,10 @@ import dev.poolse.callcore.CallCoreRuntime
10
10
  import dev.poolse.callcore.MachineState
11
11
  import dev.poolse.callcore.MediaPort
12
12
  import dev.poolse.callcore.Phase
13
+ import dev.poolse.callcore.CallServer
14
+ import dev.poolse.callcore.CallServers
13
15
  import dev.poolse.callcore.RingContext
16
+ import dev.poolse.callcore.RoutedHttpPort
14
17
  import dev.poolse.callcore.SnapshotSink
15
18
 
16
19
  /**
@@ -44,8 +47,16 @@ class CallCore private constructor(context: Context) {
44
47
  peekConfig()?.ringSurface ?: RingSurfaceConfig(appContext.applicationInfo.icon, 0)
45
48
  }
46
49
 
50
+ // One HTTP client per server, each reading its URL per request (a
51
+ // re-added server's new address applies at once); the router picks the
52
+ // one the call belongs to. A single-server app only ever uses `default`.
53
+ private val httpClient = CallHttpClient.defaultClient()
54
+ private val router = RoutedHttpPort { serverId ->
55
+ CallHttpClient({ ServerRegistry.baseUrl(appContext, serverId) }, httpClient)
56
+ }
57
+
47
58
  private val runtime = CallCoreRuntime(
48
- http = CallHttpClient({ peekConfig()?.apiBaseUrl ?: "" }),
59
+ http = router,
49
60
  media = media,
50
61
  surface = surface,
51
62
  session = CallForegroundService.also { it.attach(appContext) },
@@ -78,6 +89,8 @@ class CallCore private constructor(context: Context) {
78
89
  private var audioOutputId: String? = null
79
90
  private var connectionQuality = "unknown"
80
91
  private var videoPaused = false
92
+ /** False while the server holds our media back (recording consent). */
93
+ private var canPublish = true
81
94
 
82
95
  /** Last snapshot emitted; read by the bridge's getCallState from any thread. */
83
96
  @Volatile private var lastSnapshot: Map<String, Any?>? = null
@@ -92,8 +105,26 @@ class CallCore private constructor(context: Context) {
92
105
 
93
106
  // ── native entry points ─────────────────────────────────────────────
94
107
 
95
- /** A ring arrived — from FCM (closed app) or the socket (open app). */
96
- fun onRing(ring: RingContext) = runtime.onRing(ring)
108
+ /** The push's `workspace_name` per ringing call. */
109
+ private val ringWorkspaces = java.util.concurrent.ConcurrentHashMap<String, String>()
110
+
111
+ /**
112
+ * A ring arrived — from FCM (closed app) or the socket (open app).
113
+ * Bound to its server before the runtime sees it: a busy-decline runs
114
+ * inside the ring's own dispatch.
115
+ */
116
+ fun onRing(ring: RingContext) {
117
+ bind(ring)
118
+ runtime.onRing(ring)
119
+ }
120
+
121
+ private fun bind(ring: RingContext) {
122
+ router.bindCall(ring.callId, ring.serverId)
123
+ ring.workspaceName?.let {
124
+ if (ringWorkspaces.size > 16) ringWorkspaces.clear()
125
+ ringWorkspaces[ring.callId] = it
126
+ }
127
+ }
97
128
 
98
129
  /**
99
130
  * The caller withdrew, or the ring resolved elsewhere. Beyond the
@@ -120,7 +151,7 @@ class CallCore private constructor(context: Context) {
120
151
  * Android 10+ and left audio connected behind the lock screen.
121
152
  */
122
153
  fun onUserAnswer(ring: RingContext, from: Context? = null): Boolean {
123
- runtime.onRing(ring) // idempotent: dedupes if already showing
154
+ onRing(ring) // idempotent: dedupes if already showing
124
155
  runtime.answer()
125
156
  return bringAppToFront(ring.callId, from)
126
157
  }
@@ -138,17 +169,18 @@ class CallCore private constructor(context: Context) {
138
169
  }
139
170
  return false
140
171
  }
172
+ bind(ring)
141
173
  runtime.answerWaiting(ring.callId)
142
174
  return bringAppToFront(ring.callId, from)
143
175
  }
144
176
 
145
177
  fun onUserDecline(ring: RingContext) {
146
- runtime.onRing(ring)
178
+ onRing(ring)
147
179
  runtime.decline()
148
180
  }
149
181
 
150
182
  fun onUserOpen(ring: RingContext, from: Context? = null) {
151
- runtime.onRing(ring)
183
+ onRing(ring)
152
184
  bringAppToFront(ring.callId, from)
153
185
  }
154
186
 
@@ -166,10 +198,35 @@ class CallCore private constructor(context: Context) {
166
198
  fun answerWaiting(callId: String? = null) = runtime.answerWaiting(callId)
167
199
  /** Call waiting: turn the waiting call away — its caller hears busy. */
168
200
  fun declineWaiting(callId: String? = null) = runtime.declineWaiting(callId)
169
- fun place(conversationId: String, media: String, sessionToken: String) =
170
- runtime.place(conversationId, media, sessionToken)
171
- fun join(callId: String, conversationId: String?, sessionToken: String) =
172
- runtime.join(callId, conversationId, sessionToken)
201
+ /** [serverId]: the server the session token is for (null = the default). */
202
+ fun place(conversationId: String, media: String, sessionToken: String, serverId: String? = null) =
203
+ runtime.post {
204
+ // Busy: the runtime ignores it, so the binding must not move either.
205
+ if (!idle()) return@post
206
+ router.bindPlace(conversationId, serverId)
207
+ runtime.place(conversationId, media, sessionToken)
208
+ }
209
+
210
+ fun join(callId: String, conversationId: String?, sessionToken: String, serverId: String? = null) =
211
+ runtime.post {
212
+ if (!idle()) return@post
213
+ router.bindCall(callId, serverId)
214
+ runtime.join(callId, conversationId, sessionToken)
215
+ }
216
+
217
+ private fun idle() = runtime.currentState().phase.let { it == Phase.IDLE || it == Phase.ENDED }
218
+
219
+ /** The server [callId] runs on: its binding, else the default (when there is one). */
220
+ private fun serverOf(callId: String?): String? {
221
+ val id = callId ?: return null
222
+ router.serverFor(id)?.let { return it }
223
+ val servers = ServerRegistry.servers(appContext)
224
+ return servers.get(CallServers.DEFAULT_ID)?.id ?: servers.all.singleOrNull()?.id
225
+ }
226
+
227
+ /** The server of the current call (null = the default). Any thread. */
228
+ val currentServerId: String? get() = serverOf(runtime.currentState().callId)
229
+
173
230
 
174
231
  fun setMuted(muted: Boolean) {
175
232
  runtime.post { mutedSelf = muted }
@@ -221,6 +278,12 @@ class CallCore private constructor(context: Context) {
221
278
  */
222
279
  fun setAudioOutput(id: String) = runtime.setAudioOutput(id)
223
280
 
281
+ /**
282
+ * Consent given: publish the mic and camera again as the user last had
283
+ * them. Also happens by itself once the server lets us publish.
284
+ */
285
+ fun republish() = runtime.republish()
286
+
224
287
  /** The current call's id and control token. Any thread. */
225
288
  val control: Pair<String, String>? get() = runtime.control
226
289
 
@@ -285,10 +348,36 @@ class CallCore private constructor(context: Context) {
285
348
  connectionQuality = connectionQuality,
286
349
  videoPaused = videoPaused,
287
350
  screenSharing = screenSharing,
351
+ canPublish = canPublish,
352
+ recording = runtime.capture.first,
353
+ transcription = runtime.capture.second,
288
354
  )
289
- lastSnapshot = snap
355
+ val withServers = snap?.let { withServers(it, state) }
356
+ lastSnapshot = withServers
290
357
  reconcileAndroid(state)
291
- runCatching { listener?.invoke(snap) }.onFailure { Log.w(TAG, "snapshot listener failed", it) }
358
+ runCatching { listener?.invoke(withServers) }.onFailure { Log.w(TAG, "snapshot listener failed", it) }
359
+ }
360
+
361
+ /**
362
+ * The workspace each call belongs to: `serverId` and `workspaceName`
363
+ * on the snapshot and on its waiting call.
364
+ */
365
+ private fun withServers(snap: Map<String, Any?>, state: MachineState): Map<String, Any?> {
366
+ val servers = ServerRegistry.servers(appContext)
367
+ val serverId = serverOf(state.callId)
368
+ val out = snap.toMutableMap()
369
+ out["serverId"] = serverId
370
+ out["workspaceName"] = state.callId?.let { ringWorkspaces[it] } ?: servers.get(serverId)?.name
371
+ val waiting = snap["waiting"] as? Map<*, *>
372
+ val ring = runtime.waitingRing
373
+ if (waiting != null && ring != null) {
374
+ val waitingServer = ring.serverId ?: serverOf(ring.callId)
375
+ out["waiting"] = waiting.entries.associate { (k, v) -> k.toString() to v } + mapOf(
376
+ "serverId" to waitingServer,
377
+ "workspaceName" to (ring.workspaceName ?: servers.get(waitingServer)?.name),
378
+ )
379
+ }
380
+ return out
292
381
  }
293
382
 
294
383
  private fun isRenameOfPending(previous: String?, state: MachineState): Boolean =
@@ -312,6 +401,7 @@ class CallCore private constructor(context: Context) {
312
401
  audioOutputId = null
313
402
  connectionQuality = "unknown"
314
403
  videoPaused = false
404
+ canPublish = true
315
405
  }
316
406
 
317
407
  /**
@@ -378,6 +468,10 @@ class CallCore private constructor(context: Context) {
378
468
  runtime.post { cameraOn = on; cameraFacing = facing }
379
469
  runtime.reemit()
380
470
  }
471
+ override fun onCanPublish(allowed: Boolean) {
472
+ runtime.post { canPublish = allowed }
473
+ runtime.reemit()
474
+ }
381
475
  override fun onLocalScreen(on: Boolean) {
382
476
  runtime.post { screenSharing = on }
383
477
  runtime.reemit()
@@ -446,14 +540,32 @@ class CallCore private constructor(context: Context) {
446
540
  incomingCall: Map<String, String?> = emptyMap(),
447
541
  ) {
448
542
  val ctx = context.applicationContext
543
+ // A URL is the `default` server; "" sets the options only and keeps
544
+ // whatever default server there is.
545
+ val url = apiBaseUrl.trimEnd('/').ifEmpty {
546
+ ServerRegistry.servers(ctx).get(CallServers.DEFAULT_ID)?.apiBaseUrl.orEmpty()
547
+ }
548
+ if (apiBaseUrl.isNotBlank()) {
549
+ val current = ServerRegistry.servers(ctx).get(CallServers.DEFAULT_ID)
550
+ ServerRegistry.upsert(ctx, current?.copy(apiBaseUrl = url) ?: CallServer(CallServers.DEFAULT_ID, url))
551
+ }
449
552
  val edit = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
450
- .putString("apiBaseUrl", apiBaseUrl)
553
+ .putString("apiBaseUrl", url)
451
554
  .putString("smallIcon", smallIconName)
452
555
  .putString("ringback", ringbackName)
453
556
  .putString("ringtone", ringtoneName)
454
557
  for (key in INCOMING_KEYS) edit.putString("incoming.$key", incomingCall[key])
455
558
  edit.apply()
456
- config = build(ctx, apiBaseUrl, smallIconName, ringbackName, ringtoneName, incomingCall)
559
+ config = build(ctx, url, smallIconName, ringbackName, ringtoneName, incomingCall)
560
+ }
561
+
562
+ /**
563
+ * `addServer` before any `configure`: the core still has to exist (it
564
+ * carries the rings), with the default options.
565
+ */
566
+ fun ensureConfigured(context: Context) {
567
+ if (config == null) restoreConfig(context.applicationContext)
568
+ if (config == null) configure(context, "", null, null)
457
569
  }
458
570
 
459
571
  /** The core; throws if never configured (not even persisted). Prefer [getOrNull]. */
@@ -630,6 +742,11 @@ interface MediaEvents {
630
742
  * whether incoming video is paused to keep the audio going.
631
743
  */
632
744
  fun onNetwork(quality: String, videoPaused: Boolean) {}
745
+ /**
746
+ * Whether the server lets us publish (false: recording consent not
747
+ * given yet, docs/RECORDING.md §5). Sent on every change.
748
+ */
749
+ fun onCanPublish(allowed: Boolean) {}
633
750
  }
634
751
 
635
752
  /** One place call audio can play — a snapshot `audioOutputs[]` entry. */