@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
@@ -11,6 +11,8 @@ import UIKit
11
11
  /// The host-supplied configuration, persisted so a PushKit cold wake
12
12
  /// (no JS, no configure call) rebuilds the same core from disk.
13
13
  struct CallCoreConfig {
14
+ /// The default server's origin ("" when the app only uses `addServer`);
15
+ /// every server, this one included, lives in ServerRegistry.
14
16
  var apiBaseUrl: String
15
17
  var ringback: String?
16
18
  /// `production` | `sandbox` — the APNs environment the VoIP token
@@ -44,9 +46,20 @@ final class CallCore {
44
46
  static var listener: (([String: Any]?) -> Void)?
45
47
 
46
48
  /// Configure and PERSIST (see CallCore.kt). Re-configuring swaps in place:
47
- /// HTTP and the ringback read the config per use.
49
+ /// HTTP and the ringback read the config per use. A non-empty
50
+ /// `apiBaseUrl` is the `default` server; "" sets the options only and
51
+ /// keeps whatever default server there is.
48
52
  static func configure(apiBaseUrl: String, ringback: String?, apnsEnvironment: String?) {
49
- let trimmed = apiBaseUrl.hasSuffix("/") ? String(apiBaseUrl.dropLast()) : apiBaseUrl
53
+ var trimmed = apiBaseUrl
54
+ while trimmed.hasSuffix("/") { trimmed.removeLast() }
55
+ if trimmed.isEmpty {
56
+ trimmed = ServerRegistry.shared.servers.get(CallServers.defaultId)?.apiBaseUrl ?? ""
57
+ } else {
58
+ var server = ServerRegistry.shared.servers.get(CallServers.defaultId)
59
+ ?? CallServer(id: CallServers.defaultId, apiBaseUrl: trimmed)
60
+ server.apiBaseUrl = trimmed
61
+ ServerRegistry.shared.upsert(server)
62
+ }
50
63
  defaults.set(trimmed, forKey: "apiBaseUrl")
51
64
  defaults.set(ringback, forKey: "ringback")
52
65
  defaults.set(apnsEnvironment, forKey: "apnsEnvironment")
@@ -56,6 +69,22 @@ final class CallCore {
56
69
  configLock.unlock()
57
70
  }
58
71
 
72
+ /// `addServer` before any `configure`: the core still has to exist
73
+ /// (it carries the rings), with the default options.
74
+ static func ensureConfigured() {
75
+ restoreConfig()
76
+ if config == nil { configure(apiBaseUrl: "", ringback: nil, apnsEnvironment: nil) }
77
+ }
78
+
79
+ /// A single-server build's persisted origin, for the registry's
80
+ /// one-time migration. Reads the stores directly: the registry is not
81
+ /// loaded yet. Any thread.
82
+ static func persistedLegacyApiBaseUrl() -> String? {
83
+ if let url = defaults.string(forKey: "apiBaseUrl"), !url.isEmpty { return url }
84
+ if let url = readConfigFile()?.apiBaseUrl, !url.isEmpty { return url }
85
+ return nil
86
+ }
87
+
59
88
  /// The APNs environment last configured (persisted), if any.
60
89
  static var apnsEnvironment: String? {
61
90
  config?.apnsEnvironment ?? defaults.string(forKey: "apnsEnvironment") ?? readConfigFile()?.apnsEnvironment
@@ -119,7 +148,7 @@ final class CallCore {
119
148
  private static func readConfigFile() -> CallCoreConfig? {
120
149
  guard let url = configFileURL, let data = try? Data(contentsOf: url),
121
150
  let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
122
- let api = obj["apiBaseUrl"] as? String, !api.isEmpty else { return nil }
151
+ let api = obj["apiBaseUrl"] as? String else { return nil }
123
152
  return CallCoreConfig(apiBaseUrl: api, ringback: obj["ringback"] as? String,
124
153
  apnsEnvironment: obj["apnsEnvironment"] as? String)
125
154
  }
@@ -140,6 +169,7 @@ final class CallCore {
140
169
  // MARK: parts
141
170
 
142
171
  private let callKit = CallKitController.shared
172
+ private var router: RoutedHttpPort!
143
173
  private var mediaPort: LiveKitMediaPort!
144
174
  private var runtime: CallCoreRuntime!
145
175
  private var ringback: Ringback!
@@ -169,14 +199,29 @@ final class CallCore {
169
199
 
170
200
  private let snapshotLock = NSLock()
171
201
  private var lastSnapshot: [String: Any]?
202
+ /// The push's `workspace_name` per ringing call (under snapshotLock).
203
+ private var ringWorkspaces: [String: String] = [:]
204
+
205
+ private func ringWorkspaceName(_ callId: String?) -> String? {
206
+ guard let id = callId else { return nil }
207
+ snapshotLock.lock(); defer { snapshotLock.unlock() }
208
+ return ringWorkspaces[id]
209
+ }
172
210
 
173
211
  private init() {
174
212
  ringback = Ringback(resourceName: { CallCore.config?.ringback })
175
213
  eventsAdapter = EventsAdapter()
176
214
  mediaPort = LiveKitMediaPort(events: eventsAdapter)
177
215
  surfaceAdapter = SurfaceAdapter()
216
+ // One HTTP client per server, each reading its URL per request (a
217
+ // re-added server's new address applies at once); the router picks
218
+ // the one the call belongs to.
219
+ let session = CallHttpClient.defaultSession()
220
+ router = RoutedHttpPort { serverId in
221
+ CallHttpClient(baseUrl: { ServerRegistry.shared.baseUrl(serverId) }, session: session)
222
+ }
178
223
  runtime = CallCoreRuntime(
179
- http: CallHttpClient(baseUrl: { CallCore.config?.apiBaseUrl ?? "" }),
224
+ http: router,
180
225
  media: mediaPort,
181
226
  surface: surfaceAdapter,
182
227
  session: surfaceAdapter,
@@ -199,7 +244,18 @@ final class CallCore {
199
244
 
200
245
  // MARK: - native entry points
201
246
 
202
- func onRing(_ ring: RingContext) { runtime.onRing(ring) }
247
+ /// Bound to its server before the runtime sees it: a busy-decline runs
248
+ /// inside the ring's own dispatch.
249
+ func onRing(_ ring: RingContext) {
250
+ router.bindCall(ring.callId, serverId: ring.serverId)
251
+ if let name = ring.workspaceName {
252
+ snapshotLock.lock()
253
+ ringWorkspaces[ring.callId] = name
254
+ if ringWorkspaces.count > 16 { ringWorkspaces = [ring.callId: name] }
255
+ snapshotLock.unlock()
256
+ }
257
+ runtime.onRing(ring)
258
+ }
203
259
 
204
260
  func onRingEnded(callId: String, reason: String) {
205
261
  onMain { [self] in
@@ -263,20 +319,39 @@ final class CallCore {
263
319
  /// True while `callId` is the call waiting beside the current one. Main thread.
264
320
  func isWaiting(_ callId: String) -> Bool { runtime.currentState().waiting?.callId == callId }
265
321
 
266
- func place(conversationId: String, media: String, sessionToken: String) {
322
+ /// `serverId`: the server the session token is for (nil = the default).
323
+ func place(conversationId: String, media: String, sessionToken: String, serverId: String? = nil) {
267
324
  onMain { [self] in
325
+ // Busy: the runtime ignores it, so the binding must not move either.
326
+ let p = runtime.currentState().phase
327
+ guard p == .idle || p == .ended else { return }
268
328
  localEnd = false
329
+ router.bindPlace(conversationId, serverId: serverId)
269
330
  runtime.place(conversationId: conversationId, media: media, sessionToken: sessionToken)
270
331
  }
271
332
  }
272
333
 
273
- func join(callId: String, conversationId: String?, sessionToken: String) {
334
+ func join(callId: String, conversationId: String?, sessionToken: String, serverId: String? = nil) {
274
335
  onMain { [self] in
336
+ let p = runtime.currentState().phase
337
+ guard p == .idle || p == .ended else { return }
275
338
  localEnd = false
339
+ router.bindCall(callId, serverId: serverId)
276
340
  runtime.join(callId: callId, conversationId: conversationId, sessionToken: sessionToken)
277
341
  }
278
342
  }
279
343
 
344
+ /// The server `callId` runs on: its binding, else the default (when there is one).
345
+ private func server(of callId: String?) -> String? {
346
+ guard let id = callId else { return nil }
347
+ if let bound = router.serverFor(id) { return bound }
348
+ let servers = ServerRegistry.shared.servers
349
+ return servers.get(CallServers.defaultId)?.id ?? (servers.all.count == 1 ? servers.all[0].id : nil)
350
+ }
351
+
352
+ /// The server of the current call (nil = the default). Main thread.
353
+ var currentServerId: String? { server(of: runtime.currentState().callId) }
354
+
280
355
  func setMuted(_ muted: Bool) {
281
356
  onMain { [self] in
282
357
  applyMuted(muted)
@@ -372,10 +447,38 @@ final class CallCore {
372
447
  videoPaused: videoPaused,
373
448
  screenSharing: screenSharing
374
449
  )
375
- snapshotLock.lock(); lastSnapshot = snap; snapshotLock.unlock()
450
+ let snapWithServer = snap.map { withServers($0, state: state) }
451
+ snapshotLock.lock(); lastSnapshot = snapWithServer; snapshotLock.unlock()
376
452
  reconcileCallKit(state)
377
453
  reconcileDevice(state)
378
- CallCore.listener?(snap)
454
+ CallCore.listener?(snapWithServer)
455
+ }
456
+
457
+ /// The workspace each call belongs to: `serverId` and `workspaceName`
458
+ /// on the snapshot and on its waiting call.
459
+ private func withServers(_ snap: [String: Any], state: MachineState) -> [String: Any] {
460
+ var out = snap
461
+ let servers = ServerRegistry.shared.servers
462
+ let serverId = server(of: state.callId)
463
+ let ringName = ringWorkspaceName(state.callId)
464
+ out["serverId"] = serverId ?? NSNull()
465
+ out["workspaceName"] = (ringName ?? servers.get(serverId)?.name) ?? NSNull()
466
+ if var waiting = out["waiting"] as? [String: Any], let w = runtime.waitingRing {
467
+ waiting["serverId"] = (w.serverId ?? server(of: w.callId)) ?? NSNull()
468
+ waiting["workspaceName"] = (w.workspaceName ?? servers.get(w.serverId)?.name) ?? NSNull()
469
+ out["waiting"] = waiting
470
+ }
471
+ return out
472
+ }
473
+
474
+ /// "Ana · Acme" for the system call UI — the workspace only with several
475
+ /// signed in. Nil without a name: there is nothing to retitle with.
476
+ private func callTitle(_ base: String?, callId: String?) -> String? {
477
+ guard base != nil else { return nil }
478
+ let serverId = server(of: callId)
479
+ let label = ServerRegistry.shared.servers.workspaceLabel(serverId: serverId,
480
+ pushName: ringWorkspaceName(callId))
481
+ return CallServers.title(base, workspace: label)
379
482
  }
380
483
 
381
484
  private func resetExtras(_ callId: String?, _ media: String?) {
@@ -415,7 +518,8 @@ final class CallCore {
415
518
  // Answered from the app's own UI: tell CallKit (audio follows).
416
519
  if !t.outgoing && !t.answered && state.direction == .incoming { callKit.requestAnswer(callId: t.callId) }
417
520
  if t.outgoing && state.phase == .active { callKit.reportConnected(callId: t.callId) }
418
- callKit.updateTitle(callId: t.callId, title: conversationName, video: state.media == "video")
521
+ callKit.updateTitle(callId: t.callId, title: callTitle(conversationName, callId: t.callId),
522
+ video: state.media == "video")
419
523
  default:
420
524
  break
421
525
  }
@@ -463,7 +567,8 @@ final class CallCore {
463
567
  fileprivate func sessionStart(callId: String, media: String) {
464
568
  guard callKit.tracked(callId: callId) == nil else { return } // an answered incoming call
465
569
  let state = runtime.currentState()
466
- callKit.startOutgoing(callId: callId, handle: state.conversationId ?? callId, title: runtime.conversationName,
570
+ callKit.startOutgoing(callId: callId, handle: state.conversationId ?? callId,
571
+ title: callTitle(runtime.conversationName, callId: callId),
467
572
  video: media == "video") { [weak self] in
468
573
  // CallKit refused: the call goes on without the system UI.
469
574
  self?.mediaPort.activateAudioWithoutCallKit(media: media)
@@ -127,7 +127,10 @@ final class CallKitController: NSObject, CXProviderDelegate {
127
127
 
128
128
  func reportIncoming(ring: RingContext) {
129
129
  let hasVideo = ring.media == "video"
130
- let title = ring.conversationName ?? ring.callerName
130
+ let title = CallServers.title(
131
+ ring.conversationName ?? ring.callerName,
132
+ workspace: ServerRegistry.shared.servers.workspaceLabel(serverId: ring.serverId, pushName: ring.workspaceName)
133
+ )
131
134
  if let existing = calls.values.first(where: { $0.callId == ring.callId && !$0.ended }) {
132
135
  provider.reportNewIncomingCall(with: existing.uuid, update: update(title: title, handle: ring.conversationId, video: hasVideo)) { _ in }
133
136
  return
@@ -27,6 +27,11 @@ import UserNotifications
27
27
  /// `PoolseMessageReplyRequiresUnlock` (the config plugin's
28
28
  /// `messageReplyRequiresUnlock` option) to make Reply demand Face ID /
29
29
  /// the passcode first.
30
+ ///
31
+ /// Several workspaces: a notification's `tenant_id` picks its server
32
+ /// (ServerRegistry) — the action goes to that server's API, and the
33
+ /// result names it (`serverId`). Clearing a conversation only touches
34
+ /// that workspace's notifications.
30
35
  final class MessageNotifications: NSObject, NotificationDelegate {
31
36
  static let shared = MessageNotifications()
32
37
 
@@ -98,6 +103,14 @@ final class MessageNotifications: NSObject, NotificationDelegate {
98
103
  }
99
104
  let grant = (info["reply_grant"] as? String).flatMap(nilIfEmpty)
100
105
  let payloadUnread = Self.int(info["unread_total"])
106
+ let tenantId = (info["tenant_id"] as? String).flatMap(nilIfEmpty)
107
+ let server = ServerRegistry.shared.servers.resolve(tenantId: tenantId)
108
+ let thread = content.threadIdentifier
109
+ func tagged(_ e: [String: Any]) -> [String: Any] {
110
+ var e = e
111
+ if let id = server?.id { e["serverId"] = id }
112
+ return e
113
+ }
101
114
 
102
115
  // Started before anything async: expo-notifications calls the
103
116
  // completion handler as soon as we return, and iOS may suspend a
@@ -108,14 +121,15 @@ final class MessageNotifications: NSObject, NotificationDelegate {
108
121
  // Optimistic: the notifications go now, the server catches up. A
109
122
  // failed read is only logged — the message stays unread, nothing
110
123
  // was lost.
111
- Self.clear(conversationId: conversationId, fallbackUnread: payloadUnread, adjustBadge: true)
124
+ Self.clear(conversationId: conversationId, tenantId: tenantId, fallbackUnread: payloadUnread, adjustBadge: true)
112
125
  guard let grant = grant else {
113
- Self.report(["action": "mark_read", "conversationId": conversationId, "ok": false, "error": "no_grant"])
126
+ Self.report(tagged(["action": "mark_read", "conversationId": conversationId, "ok": false, "error": "no_grant"]))
114
127
  background.end()
115
128
  return true
116
129
  }
117
- send(path: "/v1/notification-actions/read", grant: grant, body: [:], background: background) { result in
118
- Self.report(result.event(action: "mark_read", conversationId: conversationId))
130
+ send(path: "/v1/notification-actions/read", base: server?.apiBaseUrl, grant: grant, body: [:],
131
+ background: background) { result in
132
+ Self.report(tagged(result.event(action: "mark_read", conversationId: conversationId)))
119
133
  background.end()
120
134
  }
121
135
  return true
@@ -132,25 +146,27 @@ final class MessageNotifications: NSObject, NotificationDelegate {
132
146
  // repeat with the original message (200), never a second one.
133
147
  let clientId = UUID().uuidString.lowercased()
134
148
  guard let grant = grant else {
135
- Self.postFailure(conversationId: conversationId, text: text, reason: "Open the app to reply.", userInfo: info)
136
- Self.report(["action": "reply", "conversationId": conversationId, "ok": false, "text": text,
137
- "clientId": clientId, "error": "no_grant"])
149
+ Self.postFailure(conversationId: conversationId, thread: thread, text: text, reason: "Open the app to reply.",
150
+ userInfo: info)
151
+ Self.report(tagged(["action": "reply", "conversationId": conversationId, "ok": false, "text": text,
152
+ "clientId": clientId, "error": "no_grant"]))
138
153
  background.end()
139
154
  return true
140
155
  }
141
- send(path: "/v1/notification-actions/reply", grant: grant,
156
+ send(path: "/v1/notification-actions/reply", base: server?.apiBaseUrl, grant: grant,
142
157
  body: ["text": text, "id": clientId], background: background) { result in
143
- var event = result.event(action: "reply", conversationId: conversationId)
158
+ var event = tagged(result.event(action: "reply", conversationId: conversationId))
144
159
  event["text"] = text
145
160
  event["clientId"] = clientId
146
161
  if result.ok {
147
162
  event["messageId"] = (result.json?["id"] as? String) ?? clientId
148
163
  // Replying marked the conversation read on the server.
149
- Self.clear(conversationId: conversationId, fallbackUnread: payloadUnread, adjustBadge: true)
164
+ Self.clear(conversationId: conversationId, tenantId: tenantId, fallbackUnread: payloadUnread, adjustBadge: true)
150
165
  Self.report(event)
151
166
  background.end()
152
167
  } else {
153
- Self.postFailure(conversationId: conversationId, text: text, reason: result.reason, userInfo: info)
168
+ Self.postFailure(conversationId: conversationId, thread: thread, text: text, reason: result.reason,
169
+ userInfo: info)
154
170
  Self.report(event)
155
171
  // Give the failure notification a moment to be scheduled.
156
172
  DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { background.end() }
@@ -164,7 +180,8 @@ final class MessageNotifications: NSObject, NotificationDelegate {
164
180
  completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Bool {
165
181
  guard userInfo["type"] as? String == "message_read",
166
182
  let conversationId = userInfo["conversation_id"] as? String else { return false }
167
- Self.clear(conversationId: conversationId, fallbackUnread: nil, adjustBadge: false)
183
+ Self.clear(conversationId: conversationId, tenantId: (userInfo["tenant_id"] as? String).flatMap(nilIfEmpty),
184
+ fallbackUnread: nil, adjustBadge: false)
168
185
  if let unread = Self.int(userInfo["unread_total"]) {
169
186
  Self.setBadge(unread)
170
187
  }
@@ -179,12 +196,24 @@ final class MessageNotifications: NSObject, NotificationDelegate {
179
196
  /// sends in its read-sync push) the badge becomes the newest delivered
180
197
  /// message's `unread_total` less this conversation's notifications — the
181
198
  /// read-sync push, when it reaches a running app, sets the exact value.
182
- static func clear(conversationId: String, fallbackUnread: Int? = nil, adjustBadge: Bool = false) {
199
+ ///
200
+ /// `tenantId`: only that workspace's (a notification without one, from
201
+ /// an older server, still matches). A thread id may be the bare
202
+ /// conversation id or `<tenant_id>:<conversation_id>`.
203
+ static func clear(conversationId: String, tenantId: String? = nil, fallbackUnread: Int? = nil,
204
+ adjustBadge: Bool = false) {
183
205
  let center = UNUserNotificationCenter.current()
184
206
  center.getDeliveredNotifications { delivered in
185
207
  let mine = delivered.filter {
186
- $0.request.content.threadIdentifier == conversationId ||
187
- ($0.request.content.userInfo["conversation_id"] as? String) == conversationId
208
+ let content = $0.request.content
209
+ let thread = content.threadIdentifier
210
+ let sameConversation = thread == conversationId || thread.hasSuffix(":\(conversationId)") ||
211
+ (content.userInfo["conversation_id"] as? String) == conversationId
212
+ guard sameConversation else { return false }
213
+ guard let tenantId = tenantId, let theirs = content.userInfo["tenant_id"] as? String, !theirs.isEmpty else {
214
+ return true
215
+ }
216
+ return theirs == tenantId
188
217
  }
189
218
  let ids = mine.map { $0.request.identifier }
190
219
  if !ids.isEmpty { center.removeDeliveredNotifications(withIdentifiers: ids) }
@@ -198,6 +227,16 @@ final class MessageNotifications: NSObject, NotificationDelegate {
198
227
  }
199
228
  }
200
229
 
230
+ /// A workspace signed out: its notifications go (those of a tenant).
231
+ static func clearTenant(_ tenantId: String) {
232
+ let center = UNUserNotificationCenter.current()
233
+ center.getDeliveredNotifications { delivered in
234
+ let ids = delivered.filter { ($0.request.content.userInfo["tenant_id"] as? String) == tenantId }
235
+ .map { $0.request.identifier }
236
+ if !ids.isEmpty { center.removeDeliveredNotifications(withIdentifiers: ids) }
237
+ }
238
+ }
239
+
201
240
  static func setBadge(_ count: Int) {
202
241
  if #available(iOS 16.0, *) {
203
242
  UNUserNotificationCenter.current().setBadgeCount(max(count, 0))
@@ -209,25 +248,35 @@ final class MessageNotifications: NSObject, NotificationDelegate {
209
248
  /// "Couldn't send" — in the conversation's stack, with the same Reply
210
249
  /// action (and the grant it came with) so the user can try again
211
250
  /// right there, or tap to open the chat.
212
- private static func postFailure(conversationId: String, text: String, reason: String, userInfo: [AnyHashable: Any]) {
251
+ private static func postFailure(conversationId: String, thread: String, text: String, reason: String,
252
+ userInfo: [AnyHashable: Any]) {
213
253
  let content = UNMutableNotificationContent()
214
254
  content.title = "Couldn't send your reply"
215
255
  content.body = "\u{201C}\(text)\u{201D} — \(reason)"
216
- content.threadIdentifier = conversationId
256
+ content.threadIdentifier = thread.isEmpty ? conversationId : thread
217
257
  content.sound = .default
258
+ var body: [String: Any] = ["type": "message", "conversation_id": conversationId]
218
259
  var info: [String: Any] = [
219
260
  "type": "message",
220
261
  "conversation_id": conversationId,
221
262
  "poolse_reply_failed": "1",
222
- // expo-notifications reads a push's data from `body`; keep tap routing working.
223
- "body": ["type": "message", "conversation_id": conversationId],
224
263
  ]
264
+ // The workspace it belongs to, so a tap opens the right one.
265
+ for key in ["tenant_id", "workspace_name", "workspace_icon_url"] {
266
+ if let v = userInfo[key] as? String, !v.isEmpty { info[key] = v; body[key] = v }
267
+ }
268
+ if let name = userInfo["workspace_name"] as? String, !name.isEmpty, ServerRegistry.shared.servers.isMulti {
269
+ content.subtitle = name
270
+ }
271
+ // expo-notifications reads a push's data from `body`; keep tap routing working.
272
+ info["body"] = body
225
273
  if let grant = userInfo["reply_grant"] as? String, !grant.isEmpty {
226
274
  info["reply_grant"] = grant
227
275
  content.categoryIdentifier = Self.category
228
276
  }
229
277
  content.userInfo = info
230
- let request = UNNotificationRequest(identifier: "poolse-reply-failed-\(conversationId)", content: content, trigger: nil)
278
+ let request = UNNotificationRequest(identifier: "poolse-reply-failed-\(content.threadIdentifier)", content: content,
279
+ trigger: nil)
231
280
  UNUserNotificationCenter.current().add(request) { error in
232
281
  if let error = error { pcTrace("reply failure notification refused: \(error)") }
233
282
  }
@@ -303,9 +352,12 @@ final class MessageNotifications: NSObject, NotificationDelegate {
303
352
  /// A grant-authorized POST, retried with the SAME body (so the same
304
353
  /// reply id) on a network error, a 5xx or a 429 while the background
305
354
  /// task has time left. The grant rides as the bearer and as `token`.
306
- private func send(path: String, grant: String, body: [String: Any], background: BackgroundTask,
355
+ /// `base`: the notification's server; nil = the default one.
356
+ private func send(path: String, base: String?, grant: String, body: [String: Any], background: BackgroundTask,
307
357
  attempt: Int = 1, done: @escaping (ActionResult) -> Void) {
308
- guard let base = CallCore.persistedApiBaseUrl(), let url = URL(string: base + path) else {
358
+ var origin = base ?? ServerRegistry.shared.baseUrl(nil)
359
+ if origin.isEmpty { origin = CallCore.persistedApiBaseUrl() ?? "" }
360
+ guard !origin.isEmpty, let url = URL(string: origin + path) else {
309
361
  pcTrace("notification action \(path): never configured")
310
362
  done(ActionResult(ok: false, status: 0, code: "not_configured", json: nil))
311
363
  return
@@ -341,7 +393,8 @@ final class MessageNotifications: NSObject, NotificationDelegate {
341
393
  return
342
394
  }
343
395
  DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
344
- self.send(path: path, grant: grant, body: body, background: background, attempt: attempt + 1, done: done)
396
+ self.send(path: path, base: base, grant: grant, body: body, background: background, attempt: attempt + 1,
397
+ done: done)
345
398
  }
346
399
  }
347
400
  }.resume()
@@ -0,0 +1,90 @@
1
+ import Foundation
2
+
3
+ /// The signed-in servers, persisted — so a PushKit wake or a notification
4
+ /// action with no JS knows where each workspace's API lives.
5
+ ///
6
+ /// Written to Application Support/dev.poolse.callcore/servers.json with
7
+ /// FileProtectionType.none, beside config.json and for the same reason:
8
+ /// a ring while the phone has been locked since reboot must still find
9
+ /// its server. No secrets in it — ids, URLs, tenant ids and names.
10
+ ///
11
+ /// Upgrading from a single-server build: no file yet, so the server
12
+ /// `configure` persisted becomes `default`.
13
+ final class ServerRegistry {
14
+ static let shared = ServerRegistry()
15
+
16
+ private let lock = NSLock()
17
+ private var loaded: CallServers?
18
+
19
+ /// The current list. Any thread.
20
+ var servers: CallServers {
21
+ lock.lock(); defer { lock.unlock() }
22
+ return loadLocked()
23
+ }
24
+
25
+ func upsert(_ server: CallServer) {
26
+ mutate { $0.upsert(server) }
27
+ }
28
+
29
+ func remove(_ id: String) {
30
+ mutate { $0.remove(id) }
31
+ }
32
+
33
+ /// The base URL of `serverId` (nil = the default server); "" when unknown.
34
+ func baseUrl(_ serverId: String?) -> String {
35
+ let s = servers
36
+ if let server = s.get(serverId) { return server.apiBaseUrl }
37
+ // A single-server app that never named its server: whatever it has.
38
+ if serverId == nil, s.all.count == 1 { return s.all[0].apiBaseUrl }
39
+ return ""
40
+ }
41
+
42
+ private func mutate(_ change: (inout CallServers) -> Void) {
43
+ lock.lock()
44
+ var s = loadLocked()
45
+ change(&s)
46
+ loaded = s
47
+ lock.unlock()
48
+ write(s)
49
+ }
50
+
51
+ private func loadLocked() -> CallServers {
52
+ if let l = loaded { return l }
53
+ var s = CallServers()
54
+ if let url = fileURL, let data = try? Data(contentsOf: url),
55
+ let list = (try? JSONSerialization.jsonObject(with: data)) as? [[String: Any]] {
56
+ s = CallServers(list.compactMap(CallServer.init(dict:)))
57
+ } else if let legacy = CallCore.persistedLegacyApiBaseUrl() {
58
+ // Migrate: the one server a single-server build configured.
59
+ s = CallServers([CallServer(id: CallServers.defaultId, apiBaseUrl: legacy)])
60
+ loaded = s
61
+ write(s)
62
+ return s
63
+ } else {
64
+ // Nothing yet — don't cache: configure may still be about to run
65
+ // (or, locked since reboot, the files may just be unreadable).
66
+ return s
67
+ }
68
+ loaded = s
69
+ return s
70
+ }
71
+
72
+ private var fileURL: URL? {
73
+ guard let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { return nil }
74
+ return base.appendingPathComponent("dev.poolse.callcore", isDirectory: true).appendingPathComponent("servers.json")
75
+ }
76
+
77
+ private func write(_ s: CallServers) {
78
+ guard let url = fileURL else { return }
79
+ do {
80
+ let fm = FileManager.default
81
+ try fm.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true,
82
+ attributes: [.protectionKey: FileProtectionType.none])
83
+ let data = try JSONSerialization.data(withJSONObject: s.all.map(\.dict))
84
+ try data.write(to: url, options: [.atomic, .noFileProtection])
85
+ try? fm.setAttributes([.protectionKey: FileProtectionType.none], ofItemAtPath: url.path)
86
+ } catch {
87
+ NSLog("[PoolseCalls] servers file write failed: %@", "\(error)")
88
+ }
89
+ }
90
+ }
@@ -168,7 +168,11 @@ struct VoipPayload {
168
168
  callerName: string("caller_name"),
169
169
  media: media,
170
170
  grant: grant,
171
- ringDeadlineEpochMs: deadlineMs
171
+ ringDeadlineEpochMs: deadlineMs,
172
+ // Signed in to several workspaces: the ring is answered (and
173
+ // declined) on the server of its tenant.
174
+ serverId: ServerRegistry.shared.servers.resolve(tenantId: string("tenant_id"))?.id,
175
+ workspaceName: string("workspace_name")
172
176
  )
173
177
  }
174
178
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@poolse/native",
3
- "version": "3.7.1",
3
+ "version": "3.8.0",
4
4
  "description": "Native call core for poolse — Kotlin/Swift calling engine with a thin React Native bridge. Ring, answer and carry audio with the app killed and the phone locked.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "type": "module",