@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
@@ -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.9.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",