@poolse/native 3.7.1 → 3.8.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 (33) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/README.md +61 -1
  3. package/android/src/main/java/dev/poolse/callcore/CallServers.kt +72 -0
  4. package/android/src/main/java/dev/poolse/callcore/Ports.kt +8 -0
  5. package/android/src/main/java/dev/poolse/callcore/RoutedHttpPort.kt +74 -0
  6. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +3 -3
  7. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +110 -14
  8. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +4 -0
  9. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +1 -1
  10. package/android/src/main/java/dev/poolse/callcore/android/MessageActionWorker.kt +35 -12
  11. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +142 -48
  12. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +8 -0
  13. package/android/src/main/java/dev/poolse/callcore/android/PoolseIncomingCall.kt +16 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +6 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/ServerRegistry.kt +107 -0
  16. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +56 -7
  17. package/dist/index.cjs +68 -24
  18. package/dist/index.cjs.map +1 -1
  19. package/dist/index.d.cts +91 -8
  20. package/dist/index.d.ts +91 -8
  21. package/dist/index.js +64 -25
  22. package/dist/index.js.map +1 -1
  23. package/ios/Core/CallServers.swift +89 -0
  24. package/ios/Core/Ports.swift +10 -1
  25. package/ios/Core/RoutedHttpPort.swift +83 -0
  26. package/ios/Module/PoolseCallsModule.swift +48 -8
  27. package/ios/Platform/CallCore.swift +116 -11
  28. package/ios/Platform/CallKitController.swift +4 -1
  29. package/ios/Platform/MessageNotifications.swift +76 -23
  30. package/ios/Platform/ServerRegistry.swift +90 -0
  31. package/ios/Platform/VoipPush.swift +5 -1
  32. package/package.json +1 -1
  33. package/src/index.ts +187 -30
package/CHANGELOG.md CHANGED
@@ -2,6 +2,34 @@
2
2
 
3
3
  Formerly `@poolse/react-native-calls` (0.x).
4
4
 
5
+ ## 3.8.0 — 2026-11-21
6
+
7
+ - Several workspaces (servers) at once:
8
+ `addServer({ id, apiBaseUrl, tenantId?, name? })`, `removeServer(id)`,
9
+ `listServers()`, `serverOfNotification(data)` and `DEFAULT_SERVER_ID`; `configure(apiBaseUrl, options)` is unchanged and
10
+ sets the `default` server, `configure(options)` sets the options alone.
11
+ Persisted, so a ring or a notification action with the app closed finds its
12
+ server; a single-server install migrates to `default` on upgrade.
13
+ - Calls: a push's `tenant_id` picks its server; answer, decline, busy-decline,
14
+ hang-up and reconnect go to the server the call came from. `place` /
15
+ `startRoom` take `serverId`, `join` a 4th `serverId` argument;
16
+ `ringIntoCall` uses the call's own server. A ring from another workspace
17
+ during a call is call waiting (CallKit End & Accept, Android End & answer).
18
+ Snapshots and `waiting` carry `serverId` and `workspaceName`.
19
+ - With two or more servers, CallKit, the Android ring screen and the
20
+ call-waiting heads-up read "Ana · Acme" (`workspace_name` from the push, else
21
+ the server's `name`). Custom ring Activities get `EXTRA_SERVER_ID` and
22
+ `EXTRA_WORKSPACE_NAME`.
23
+ - Notifications: Reply / Mark as read are sent to the notification's server and
24
+ report `serverId`; Android taps carry `CallAction.serverId`. Android groups
25
+ chats per workspace (own group, summary, and a "Messages" channel in a
26
+ channel group named after it) and shows the workspace as subtext; iOS clears
27
+ per workspace (thread ids may be `<tenant_id>:<conversation_id>`) and a
28
+ failed-reply notice keeps the workspace. `setActiveConversation` takes an
29
+ optional `serverId`; `removeServer` takes the workspace's notifications down.
30
+ - Fix (Android): Mark as read from a notification lost its grant when the
31
+ notification was cleared first, and failed with `no_grant`.
32
+
5
33
  ## 3.7.1 — 2026-11-21
6
34
 
7
35
  - No changes; released with the other `@poolse/*` packages at 3.7.1.
package/README.md CHANGED
@@ -106,6 +106,9 @@ 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).
109
112
  - Socket forwarding (optional): `onCallFinished`, `onRingEnded`. Feed them
110
113
  from `@poolse/sdk` 3.1's user channel:
111
114
 
@@ -233,7 +236,8 @@ into a Reply button with a text field and a Mark as read button, and sends
233
236
  them itself — from the lock screen, with the app closed, with no session
234
237
  and no JS — to `POST /v1/notification-actions/reply` and `/read` on the API
235
238
  origin you passed to `configure` (persisted, so call it once on every app
236
- start as usual).
239
+ start as usual), or on the notification's own server with several (see
240
+ [Signed in to several workspaces](#signed-in-to-several-workspaces)).
237
241
 
238
242
  - **iOS**: the core registers the `poolse_message` category (actions `reply`
239
243
  and `mark_read`) beside the app's own categories at launch, and handles the
@@ -285,6 +289,62 @@ expo-notifications also hands these responses to its own JS listeners: in
285
289
  `addNotificationResponseReceivedListener`, ignore an `actionIdentifier` of
286
290
  `reply` or `mark_read` (only the default tap should open the chat).
287
291
 
292
+ ## Signed in to several workspaces
293
+
294
+ The core can serve several API servers at once — one per workspace the user
295
+ is signed in to. `configure(apiBaseUrl)` is still all a single-server app
296
+ needs: that server is `default` (`DEFAULT_SERVER_ID`), and everything below
297
+ is optional. Add the others (or all of them, with `configure(options)` for
298
+ the options alone):
299
+
300
+ ```ts
301
+ await calls.configure({ ringback: 'ringback', apnsEnvironment: 'production' });
302
+ await calls.addServer({
303
+ id: 'acme', // your id: 1–64 of A–Z a–z 0–9 . _ : -
304
+ apiBaseUrl: 'https://chat.acme.example',
305
+ tenantId: me.tenant_id, // the poolse tenant of this sign-in
306
+ name: 'Acme',
307
+ });
308
+ // …and register the device's push tokens with each server's client
309
+ // (`devices.register`, VoIP + alert on iOS, FCM on Android).
310
+
311
+ await calls.place(conversationId, { media: 'audio', sessionToken, serverId: 'acme' });
312
+ await calls.join(callId, conversationId, sessionToken, 'acme');
313
+
314
+ // Signed out of one workspace (unregister its tokens there first):
315
+ await calls.removeServer('acme');
316
+ ```
317
+
318
+ - **Routing.** A push's `tenant_id` picks its server — the one added with that
319
+ `tenantId` (pass it as soon as there are two servers). Rings are answered and
320
+ declined on their own server, with their own grant; place / join / rooms go
321
+ where `serverId` says, and hang-up, reconnect and `ringIntoCall` follow the
322
+ call. A push with no known tenant goes to the only server, else the only one
323
+ without a `tenantId`, else `default`.
324
+ - **One call at a time.** A ring from another workspace during a call is call
325
+ waiting, exactly like one from the same workspace: CallKit's End & Accept /
326
+ Decline, Android's heads-up with End & answer / Decline. Each goes to the
327
+ server the ring came from.
328
+ - **Names.** With two or more servers added, CallKit and the Android ring
329
+ screen, call-waiting heads-up and notifications show the workspace: "Ana ·
330
+ Acme" (the push's `workspace_name`, else the server's `name`).
331
+ `snapshot.serverId` / `snapshot.workspaceName` and the same on
332
+ `snapshot.waiting` tell the app which workspace a call is on. Custom
333
+ incoming-call Activities get `EXTRA_SERVER_ID` (`poolse_server_id`) and
334
+ `EXTRA_WORKSPACE_NAME` (`poolse_workspace_name`, set only with several
335
+ servers).
336
+ - **Notifications.** Reply and Mark as read go to the notification's own
337
+ server; `NotificationActionResult.serverId` says which. Android: a missed call
338
+ or chat tap delivers `CallAction.serverId`; each server other than `default`
339
+ gets its own notification group, summary and "Messages" channel inside a
340
+ channel group named after the workspace (so it can be muted on its own); the
341
+ workspace is the notification's subtext while several are signed in. iOS: the
342
+ tap reaches your notification library — `serverOfNotification(data)` names
343
+ the workspace to open. Pass `setActiveConversation(conversationId, serverId)`.
344
+ - **Upgrading** keeps everything: the server a single-server build configured
345
+ becomes `default`, and its notifications, channel and stored chats are left
346
+ as they are.
347
+
288
348
  ## Links
289
349
 
290
350
  - Docs: <https://poolse.dev/docs/sdk/native>
@@ -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
+ }
@@ -112,6 +112,14 @@ data class RingContext(
112
112
  val ringDeadlineEpochMs: Long,
113
113
  /** The caller's picture for the ring screen, if the push or the app's template gives one. */
114
114
  val callerAvatarUrl: String? = null,
115
+ /**
116
+ * The server (workspace) the ring came from — the host's id from
117
+ * `addServer`, resolved from the push's `tenant_id`. Its answer and
118
+ * decline go to that server. Null: the default server.
119
+ */
120
+ val serverId: String? = null,
121
+ /** The push's `workspace_name`, for "Ana · Acme" when several servers are signed in. */
122
+ val workspaceName: String? = null,
115
123
  )
116
124
 
117
125
  /** 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) },
@@ -92,8 +103,26 @@ class CallCore private constructor(context: Context) {
92
103
 
93
104
  // ── native entry points ─────────────────────────────────────────────
94
105
 
95
- /** A ring arrived — from FCM (closed app) or the socket (open app). */
96
- fun onRing(ring: RingContext) = runtime.onRing(ring)
106
+ /** The push's `workspace_name` per ringing call. */
107
+ private val ringWorkspaces = java.util.concurrent.ConcurrentHashMap<String, String>()
108
+
109
+ /**
110
+ * A ring arrived — from FCM (closed app) or the socket (open app).
111
+ * Bound to its server before the runtime sees it: a busy-decline runs
112
+ * inside the ring's own dispatch.
113
+ */
114
+ fun onRing(ring: RingContext) {
115
+ bind(ring)
116
+ runtime.onRing(ring)
117
+ }
118
+
119
+ private fun bind(ring: RingContext) {
120
+ router.bindCall(ring.callId, ring.serverId)
121
+ ring.workspaceName?.let {
122
+ if (ringWorkspaces.size > 16) ringWorkspaces.clear()
123
+ ringWorkspaces[ring.callId] = it
124
+ }
125
+ }
97
126
 
98
127
  /**
99
128
  * The caller withdrew, or the ring resolved elsewhere. Beyond the
@@ -120,7 +149,7 @@ class CallCore private constructor(context: Context) {
120
149
  * Android 10+ and left audio connected behind the lock screen.
121
150
  */
122
151
  fun onUserAnswer(ring: RingContext, from: Context? = null): Boolean {
123
- runtime.onRing(ring) // idempotent: dedupes if already showing
152
+ onRing(ring) // idempotent: dedupes if already showing
124
153
  runtime.answer()
125
154
  return bringAppToFront(ring.callId, from)
126
155
  }
@@ -138,17 +167,18 @@ class CallCore private constructor(context: Context) {
138
167
  }
139
168
  return false
140
169
  }
170
+ bind(ring)
141
171
  runtime.answerWaiting(ring.callId)
142
172
  return bringAppToFront(ring.callId, from)
143
173
  }
144
174
 
145
175
  fun onUserDecline(ring: RingContext) {
146
- runtime.onRing(ring)
176
+ onRing(ring)
147
177
  runtime.decline()
148
178
  }
149
179
 
150
180
  fun onUserOpen(ring: RingContext, from: Context? = null) {
151
- runtime.onRing(ring)
181
+ onRing(ring)
152
182
  bringAppToFront(ring.callId, from)
153
183
  }
154
184
 
@@ -166,10 +196,35 @@ class CallCore private constructor(context: Context) {
166
196
  fun answerWaiting(callId: String? = null) = runtime.answerWaiting(callId)
167
197
  /** Call waiting: turn the waiting call away — its caller hears busy. */
168
198
  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)
199
+ /** [serverId]: the server the session token is for (null = the default). */
200
+ fun place(conversationId: String, media: String, sessionToken: String, serverId: String? = null) =
201
+ runtime.post {
202
+ // Busy: the runtime ignores it, so the binding must not move either.
203
+ if (!idle()) return@post
204
+ router.bindPlace(conversationId, serverId)
205
+ runtime.place(conversationId, media, sessionToken)
206
+ }
207
+
208
+ fun join(callId: String, conversationId: String?, sessionToken: String, serverId: String? = null) =
209
+ runtime.post {
210
+ if (!idle()) return@post
211
+ router.bindCall(callId, serverId)
212
+ runtime.join(callId, conversationId, sessionToken)
213
+ }
214
+
215
+ private fun idle() = runtime.currentState().phase.let { it == Phase.IDLE || it == Phase.ENDED }
216
+
217
+ /** The server [callId] runs on: its binding, else the default (when there is one). */
218
+ private fun serverOf(callId: String?): String? {
219
+ val id = callId ?: return null
220
+ router.serverFor(id)?.let { return it }
221
+ val servers = ServerRegistry.servers(appContext)
222
+ return servers.get(CallServers.DEFAULT_ID)?.id ?: servers.all.singleOrNull()?.id
223
+ }
224
+
225
+ /** The server of the current call (null = the default). Any thread. */
226
+ val currentServerId: String? get() = serverOf(runtime.currentState().callId)
227
+
173
228
 
174
229
  fun setMuted(muted: Boolean) {
175
230
  runtime.post { mutedSelf = muted }
@@ -286,9 +341,32 @@ class CallCore private constructor(context: Context) {
286
341
  videoPaused = videoPaused,
287
342
  screenSharing = screenSharing,
288
343
  )
289
- lastSnapshot = snap
344
+ val withServers = snap?.let { withServers(it, state) }
345
+ lastSnapshot = withServers
290
346
  reconcileAndroid(state)
291
- runCatching { listener?.invoke(snap) }.onFailure { Log.w(TAG, "snapshot listener failed", it) }
347
+ runCatching { listener?.invoke(withServers) }.onFailure { Log.w(TAG, "snapshot listener failed", it) }
348
+ }
349
+
350
+ /**
351
+ * The workspace each call belongs to: `serverId` and `workspaceName`
352
+ * on the snapshot and on its waiting call.
353
+ */
354
+ private fun withServers(snap: Map<String, Any?>, state: MachineState): Map<String, Any?> {
355
+ val servers = ServerRegistry.servers(appContext)
356
+ val serverId = serverOf(state.callId)
357
+ val out = snap.toMutableMap()
358
+ out["serverId"] = serverId
359
+ out["workspaceName"] = state.callId?.let { ringWorkspaces[it] } ?: servers.get(serverId)?.name
360
+ val waiting = snap["waiting"] as? Map<*, *>
361
+ val ring = runtime.waitingRing
362
+ if (waiting != null && ring != null) {
363
+ val waitingServer = ring.serverId ?: serverOf(ring.callId)
364
+ out["waiting"] = waiting.entries.associate { (k, v) -> k.toString() to v } + mapOf(
365
+ "serverId" to waitingServer,
366
+ "workspaceName" to (ring.workspaceName ?: servers.get(waitingServer)?.name),
367
+ )
368
+ }
369
+ return out
292
370
  }
293
371
 
294
372
  private fun isRenameOfPending(previous: String?, state: MachineState): Boolean =
@@ -446,14 +524,32 @@ class CallCore private constructor(context: Context) {
446
524
  incomingCall: Map<String, String?> = emptyMap(),
447
525
  ) {
448
526
  val ctx = context.applicationContext
527
+ // A URL is the `default` server; "" sets the options only and keeps
528
+ // whatever default server there is.
529
+ val url = apiBaseUrl.trimEnd('/').ifEmpty {
530
+ ServerRegistry.servers(ctx).get(CallServers.DEFAULT_ID)?.apiBaseUrl.orEmpty()
531
+ }
532
+ if (apiBaseUrl.isNotBlank()) {
533
+ val current = ServerRegistry.servers(ctx).get(CallServers.DEFAULT_ID)
534
+ ServerRegistry.upsert(ctx, current?.copy(apiBaseUrl = url) ?: CallServer(CallServers.DEFAULT_ID, url))
535
+ }
449
536
  val edit = ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
450
- .putString("apiBaseUrl", apiBaseUrl)
537
+ .putString("apiBaseUrl", url)
451
538
  .putString("smallIcon", smallIconName)
452
539
  .putString("ringback", ringbackName)
453
540
  .putString("ringtone", ringtoneName)
454
541
  for (key in INCOMING_KEYS) edit.putString("incoming.$key", incomingCall[key])
455
542
  edit.apply()
456
- config = build(ctx, apiBaseUrl, smallIconName, ringbackName, ringtoneName, incomingCall)
543
+ config = build(ctx, url, smallIconName, ringbackName, ringtoneName, incomingCall)
544
+ }
545
+
546
+ /**
547
+ * `addServer` before any `configure`: the core still has to exist (it
548
+ * carries the rings), with the default options.
549
+ */
550
+ fun ensureConfigured(context: Context) {
551
+ if (config == null) restoreConfig(context.applicationContext)
552
+ if (config == null) configure(context, "", null, null)
457
553
  }
458
554
 
459
555
  /** The core; throws if never configured (not even persisted). Prefer [getOrNull]. */
@@ -99,6 +99,10 @@ class CallMessagingService : FirebaseMessagingService() {
99
99
  externalId = this["caller_external_id"],
100
100
  userId = this["caller_user_id"],
101
101
  ),
102
+ // Signed in to several workspaces: the ring is answered (and
103
+ // declined) on the server of its tenant.
104
+ serverId = ServerRegistry.resolve(this@CallMessagingService, this["tenant_id"])?.id,
105
+ workspaceName = this["workspace_name"]?.ifEmpty { null },
102
106
  )
103
107
  }
104
108
 
@@ -121,7 +121,7 @@ class IncomingCallActivity : Activity() {
121
121
  ring = next
122
122
  awaitingForward = false
123
123
  pulse?.cancel()
124
- val title = next.conversationName ?: next.callerName ?: "Incoming call"
124
+ val title = ServerRegistry.ringTitle(this, next, next.conversationName ?: next.callerName) ?: "Incoming call"
125
125
  val body = if (next.media == "video") "Incoming video call" else "Incoming call"
126
126
  setContentView(buildScene(title, body, next))
127
127
  }
@@ -37,6 +37,8 @@ import java.util.concurrent.TimeUnit
37
37
  class MessageActionReceiver : BroadcastReceiver() {
38
38
  override fun onReceive(context: Context, intent: Intent) {
39
39
  val conversationId = intent.getStringExtra(MessageNotifications.EXTRA_CONVERSATION) ?: return
40
+ // Null on a notification posted before servers (the default one).
41
+ val serverId = intent.getStringExtra(MessageNotifications.EXTRA_SERVER)
40
42
  val app = context.applicationContext
41
43
 
42
44
  when (intent.action) {
@@ -45,19 +47,21 @@ class MessageActionReceiver : BroadcastReceiver() {
45
47
  ?.getCharSequence(MessageNotifications.KEY_REPLY)?.toString()?.trim().orEmpty()
46
48
  if (text.isEmpty()) {
47
49
  // Nothing typed; still repost so the field stops spinning.
48
- MessageNotifications.refresh(app, conversationId)
50
+ MessageNotifications.refresh(app, serverId, conversationId)
49
51
  return
50
52
  }
51
53
  // One id per reply, reused by every retry of it: the server
52
54
  // answers a repeat with the original message, never a second one.
53
55
  val clientId = UUID.randomUUID().toString()
54
- MessageNotifications.onReplying(app, conversationId, clientId, text)
55
- MessageActionWorker.enqueue(app, MessageActionWorker.REPLY, conversationId, text, clientId)
56
+ MessageNotifications.onReplying(app, serverId, conversationId, clientId, text)
57
+ MessageActionWorker.enqueue(app, MessageActionWorker.REPLY, serverId, conversationId, text, clientId)
56
58
  }
57
59
  MessageNotifications.ACTION_READ -> {
58
60
  // Optimistic: the notification goes now; the server catches up.
59
- MessageNotifications.clear(app, conversationId)
60
- MessageActionWorker.enqueue(app, MessageActionWorker.READ, conversationId, null, null)
61
+ // Grant first: clearing drops it with the conversation.
62
+ val grant = MessageNotifications.grantFor(app, serverId, conversationId)
63
+ MessageNotifications.clear(app, conversationId, serverId ?: dev.poolse.callcore.CallServers.DEFAULT_ID)
64
+ MessageActionWorker.enqueue(app, MessageActionWorker.READ, serverId, conversationId, null, null, grant)
61
65
  }
62
66
  }
63
67
  }
@@ -66,7 +70,8 @@ class MessageActionReceiver : BroadcastReceiver() {
66
70
  /**
67
71
  * The HTTP side of a notification action: `POST /v1/notification-actions/
68
72
  * {reply,read}` with the conversation's reply grant (bearer and `token`),
69
- * against the API origin `configure` persisted — no app, no session, no JS.
73
+ * against its server's API origin (persisted by `configure` / `addServer`)
74
+ * — no app, no session, no JS.
70
75
  *
71
76
  * WorkManager, expedited: it runs at once when there is a network, waits
72
77
  * for one when there is not, survives the process being killed, and
@@ -82,9 +87,16 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
82
87
  val conversationId = inputData.getString(KEY_CONVERSATION) ?: return@withContext Result.failure()
83
88
  val text = inputData.getString(KEY_TEXT).orEmpty()
84
89
  val clientId = inputData.getString(KEY_CLIENT_ID).orEmpty()
90
+ val serverId = inputData.getString(KEY_SERVER)
85
91
  // The newest grant this conversation got, else the one at tap time.
86
- val grant = MessageNotifications.grantFor(app, conversationId) ?: inputData.getString(KEY_GRANT)
87
- val base = CallCore.apiBaseUrl(app)
92
+ val grant = MessageNotifications.grantFor(app, serverId, conversationId) ?: inputData.getString(KEY_GRANT)
93
+ // Its own server; one signed out since has no address (never another
94
+ // server's: the grant is for this one).
95
+ val base = if (serverId != null) {
96
+ ServerRegistry.baseUrl(app, serverId).ifEmpty { null }
97
+ } else {
98
+ ServerRegistry.baseUrl(app, null).ifEmpty { null } ?: CallCore.apiBaseUrl(app)
99
+ }
88
100
 
89
101
  val outcome = when {
90
102
  base == null -> Outcome(0, "not_configured", null)
@@ -103,6 +115,7 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
103
115
  "action" to if (action == REPLY) "reply" else "mark_read",
104
116
  "conversationId" to conversationId,
105
117
  "ok" to ok,
118
+ "serverId" to (serverId ?: ServerRegistry.servers(app).get(null)?.id),
106
119
  )
107
120
  if (!ok) {
108
121
  event["error"] = outcome.code ?: if (outcome.status == 0) "network" else "http_${outcome.status}"
@@ -112,7 +125,7 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
112
125
  event["text"] = text
113
126
  event["clientId"] = clientId
114
127
  if (ok) event["messageId"] = outcome.json?.optString("id")?.ifBlank { null } ?: clientId
115
- MessageNotifications.onReplied(app, conversationId, clientId, text, ok, if (ok) null else reason(outcome), grant)
128
+ MessageNotifications.onReplied(app, serverId, conversationId, clientId, text, ok, if (ok) null else reason(outcome), grant)
116
129
  } else if (!ok) {
117
130
  // A failed read is only logged: the message stays unread, nothing is lost.
118
131
  Log.w(TAG, "mark read failed status=${outcome.status} code=${outcome.code}")
@@ -172,6 +185,7 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
172
185
  internal const val READ = "read"
173
186
  private const val KEY_ACTION = "action"
174
187
  private const val KEY_CONVERSATION = "conversation_id"
188
+ private const val KEY_SERVER = "server_id"
175
189
  private const val KEY_TEXT = "text"
176
190
  private const val KEY_CLIENT_ID = "client_id"
177
191
  private const val KEY_GRANT = "grant"
@@ -190,13 +204,22 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
190
204
  .build()
191
205
  }
192
206
 
193
- internal fun enqueue(context: Context, action: String, conversationId: String, text: String?, clientId: String?) {
207
+ internal fun enqueue(
208
+ context: Context,
209
+ action: String,
210
+ serverId: String?,
211
+ conversationId: String,
212
+ text: String?,
213
+ clientId: String?,
214
+ grant: String? = MessageNotifications.grantFor(context, serverId, conversationId),
215
+ ) {
194
216
  val data = Data.Builder()
195
217
  .putString(KEY_ACTION, action)
196
218
  .putString(KEY_CONVERSATION, conversationId)
219
+ .putString(KEY_SERVER, serverId)
197
220
  .putString(KEY_TEXT, text)
198
221
  .putString(KEY_CLIENT_ID, clientId)
199
- .putString(KEY_GRANT, MessageNotifications.grantFor(context, conversationId))
222
+ .putString(KEY_GRANT, grant)
200
223
  .putLong(KEY_AT, System.currentTimeMillis())
201
224
  .build()
202
225
  val request = OneTimeWorkRequestBuilder<MessageActionWorker>()
@@ -206,7 +229,7 @@ class MessageActionWorker(context: Context, params: WorkerParameters) : Coroutin
206
229
  .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
207
230
  .addTag("poolse-notification-action")
208
231
  .build()
209
- val name = "poolse-$action-" + (clientId ?: conversationId)
232
+ val name = "poolse-$action-" + (clientId ?: listOfNotNull(serverId, conversationId).joinToString("/"))
210
233
  runCatching {
211
234
  WorkManager.getInstance(context).enqueueUniqueWork(name, ExistingWorkPolicy.KEEP, request)
212
235
  }.onFailure { Log.e(TAG, "could not queue the notification action", it) }