@poolse/native 3.8.0 → 3.10.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 (37) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +127 -9
  3. package/android/src/main/AndroidManifest.xml +4 -0
  4. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +8 -0
  5. package/android/src/main/java/dev/poolse/callcore/Ports.kt +47 -1
  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 +112 -10
  8. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +3 -0
  9. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +21 -1
  10. package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +14 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/EscalationNotification.kt +475 -0
  12. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +9 -4
  13. package/android/src/main/java/dev/poolse/callcore/android/MeetingNotification.kt +127 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/PoolseIncomingCall.kt +9 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +9 -0
  16. package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +23 -0
  17. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +17 -1
  18. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +174 -11
  19. package/dist/index.cjs +33 -0
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +197 -23
  22. package/dist/index.d.ts +197 -23
  23. package/dist/index.js +26 -1
  24. package/dist/index.js.map +1 -1
  25. package/ios/Core/CallCoreRuntime.swift +8 -0
  26. package/ios/Core/CallHttpClient.swift +11 -1
  27. package/ios/Core/Ports.swift +47 -2
  28. package/ios/Core/SnapshotEncoding.swift +39 -4
  29. package/ios/Module/PoolseCallsModule.swift +28 -1
  30. package/ios/Platform/CallCore.swift +68 -2
  31. package/ios/Platform/CallKitController.swift +1 -1
  32. package/ios/Platform/EscalationNotifications.swift +195 -0
  33. package/ios/Platform/LiveKitMediaPort.swift +178 -15
  34. package/ios/Platform/MessageNotifications.swift +60 -1
  35. package/ios/Platform/VoipPush.swift +11 -2
  36. package/package.json +1 -1
  37. package/src/index.ts +231 -23
@@ -191,6 +191,11 @@ final class CallCore {
191
191
  private var audioOutputId: String?
192
192
  private var connectionQuality = "unknown"
193
193
  private var videoPaused = false
194
+ /// False while the server holds our media back (recording consent).
195
+ private var canPublish = true
196
+ /// Taken over by the same user on another device (CL11): the end that
197
+ /// follows reads `reason: 'moved'`.
198
+ private var movedElsewhere = false
194
199
 
195
200
  /// ring_ended reasons seen per call — the CallKit end reason.
196
201
  private var ringEndReasons: [String: String] = [:]
@@ -201,6 +206,16 @@ final class CallCore {
201
206
  private var lastSnapshot: [String: Any]?
202
207
  /// The push's `workspace_name` per ringing call (under snapshotLock).
203
208
  private var ringWorkspaces: [String: String] = [:]
209
+ /// Meeting rings (CA4) per call: the meeting's title, "" when it has
210
+ /// none (under snapshotLock). Absent: a person calling.
211
+ private var ringMeetings: [String: String] = [:]
212
+
213
+ private func ringMeetingTitle(_ callId: String?) -> String?? {
214
+ guard let id = callId else { return nil }
215
+ snapshotLock.lock(); defer { snapshotLock.unlock() }
216
+ guard let title = ringMeetings[id] else { return nil }
217
+ return .some(title.isEmpty ? nil : title)
218
+ }
204
219
 
205
220
  private func ringWorkspaceName(_ callId: String?) -> String? {
206
221
  guard let id = callId else { return nil }
@@ -254,6 +269,12 @@ final class CallCore {
254
269
  if ringWorkspaces.count > 16 { ringWorkspaces = [ring.callId: name] }
255
270
  snapshotLock.unlock()
256
271
  }
272
+ if ring.isMeeting {
273
+ snapshotLock.lock()
274
+ if ringMeetings.count > 16 { ringMeetings = [:] }
275
+ ringMeetings[ring.callId] = ring.meetingTitle ?? ""
276
+ snapshotLock.unlock()
277
+ }
257
278
  runtime.onRing(ring)
258
279
  }
259
280
 
@@ -373,6 +394,16 @@ final class CallCore {
373
394
  /// Not optimistic: screenSharing flips when the screen is published.
374
395
  func setScreenShare(_ on: Bool) { onMain { [self] in mediaPort.setScreenShare(on) } }
375
396
 
397
+ /// Noise suppression (CL7), on by default; see LiveKitMediaPort.
398
+ func setNoiseSuppression(_ on: Bool) {
399
+ onMain { [self] in mediaPort.setNoiseSuppression(on); runtime.reemit() }
400
+ }
401
+
402
+ /// Background blur on the camera (CL7).
403
+ func setBackgroundBlur(_ on: Bool) {
404
+ onMain { [self] in mediaPort.setBackgroundBlur(on); runtime.reemit() }
405
+ }
406
+
376
407
  func setSpeaker(_ on: Bool) {
377
408
  onMain { [self] in
378
409
  audioRoute = on ? "speaker" : "earpiece" // optimistic; the adapter reports the real one
@@ -384,6 +415,10 @@ final class CallCore {
384
415
  /// Not optimistic: the adapter reports the route once iOS has moved it.
385
416
  func setAudioOutput(_ id: String) { runtime.setAudioOutput(id) }
386
417
 
418
+ /// Consent given: publish the mic and camera again as the user last had
419
+ /// them. Also happens by itself once the server lets us publish.
420
+ func republish() { runtime.republish() }
421
+
387
422
  /// The current call's id and control token (main thread).
388
423
  var control: (callId: String, controlToken: String)? { runtime.control }
389
424
 
@@ -445,7 +480,10 @@ final class CallCore {
445
480
  waiting: runtime.waitingRing,
446
481
  connectionQuality: connectionQuality,
447
482
  videoPaused: videoPaused,
448
- screenSharing: screenSharing
483
+ screenSharing: screenSharing,
484
+ canPublish: canPublish,
485
+ recording: runtime.capture.recording,
486
+ transcription: runtime.capture.transcription
449
487
  )
450
488
  let snapWithServer = snap.map { withServers($0, state: state) }
451
489
  snapshotLock.lock(); lastSnapshot = snapWithServer; snapshotLock.unlock()
@@ -463,9 +501,25 @@ final class CallCore {
463
501
  let ringName = ringWorkspaceName(state.callId)
464
502
  out["serverId"] = serverId ?? NSNull()
465
503
  out["workspaceName"] = (ringName ?? servers.get(serverId)?.name) ?? NSNull()
504
+ out["noiseSuppression"] = mediaPort.noiseSuppression
505
+ out["backgroundBlur"] = mediaPort.backgroundBlur
506
+ out["movedElsewhere"] = movedElsewhere
507
+ // Taken over by another of this user's devices: the machine ends it
508
+ // as `left` (CALL_CONTRACT.md §9); the app is told why.
509
+ if movedElsewhere && state.phase == .ended { out["reason"] = "moved" }
510
+ // A scheduled meeting that rang this device (CA4).
511
+ if let meeting = ringMeetingTitle(state.callId) {
512
+ out["ringType"] = "meeting"
513
+ out["meetingTitle"] = meeting ?? NSNull()
514
+ } else {
515
+ out["ringType"] = "call"
516
+ out["meetingTitle"] = NSNull()
517
+ }
466
518
  if var waiting = out["waiting"] as? [String: Any], let w = runtime.waitingRing {
467
519
  waiting["serverId"] = (w.serverId ?? server(of: w.callId)) ?? NSNull()
468
520
  waiting["workspaceName"] = (w.workspaceName ?? servers.get(w.serverId)?.name) ?? NSNull()
521
+ waiting["ringType"] = w.isMeeting ? "meeting" : "call"
522
+ waiting["meetingTitle"] = w.meetingTitle ?? NSNull()
469
523
  out["waiting"] = waiting
470
524
  }
471
525
  return out
@@ -496,6 +550,8 @@ final class CallCore {
496
550
  audioOutputId = nil
497
551
  connectionQuality = "unknown"
498
552
  videoPaused = false
553
+ canPublish = true
554
+ movedElsewhere = false
499
555
  }
500
556
 
501
557
  /// CallKit follows the FINAL state of each dispatch.
@@ -598,7 +654,8 @@ final class CallCore {
598
654
  fileprivate func remoteJoined() { runtime.onRemoteJoined() }
599
655
  fileprivate func participants(_ p: [SnapshotParticipant]) {
600
656
  runtime.post { [weak self] in self?.roster = p }
601
- runtime.onRemoteCount(p.count)
657
+ // An agent keeps nobody company: a call left with only agents is over.
658
+ runtime.onRemoteCount(p.filter { !$0.isAgent }.count)
602
659
  runtime.reemit()
603
660
  }
604
661
  fileprivate func route(_ r: String) {
@@ -621,6 +678,13 @@ final class CallCore {
621
678
  runtime.post { [weak self] in self?.screenSharing = on }
622
679
  runtime.reemit()
623
680
  }
681
+ fileprivate func publishAllowed(_ allowed: Bool) {
682
+ runtime.post { [weak self] in self?.canPublish = allowed }
683
+ runtime.reemit()
684
+ }
685
+ fileprivate func movedAway() {
686
+ runtime.post { [weak self] in self?.movedElsewhere = true }
687
+ }
624
688
  }
625
689
 
626
690
  // MARK: - CallKit actions
@@ -721,6 +785,8 @@ private final class EventsAdapter: MediaEvents {
721
785
  func onLocalScreen(_ on: Bool) { core?.localScreen(on) }
722
786
  func onAudioOutputs(_ outputs: [AudioOutput], selectedId: String?) { core?.outputs(outputs, selected: selectedId) }
723
787
  func onNetwork(quality: String, videoPaused: Bool) { core?.network(quality: quality, videoPaused: videoPaused) }
788
+ func onCanPublish(_ allowed: Bool) { core?.publishAllowed(allowed) }
789
+ func onMovedElsewhere() { core?.movedAway() }
724
790
  }
725
791
 
726
792
  /// Host-facing entry points.
@@ -128,7 +128,7 @@ final class CallKitController: NSObject, CXProviderDelegate {
128
128
  func reportIncoming(ring: RingContext) {
129
129
  let hasVideo = ring.media == "video"
130
130
  let title = CallServers.title(
131
- ring.conversationName ?? ring.callerName,
131
+ ring.displayTitle,
132
132
  workspace: ServerRegistry.shared.servers.workspaceLabel(serverId: ring.serverId, pushName: ring.workspaceName)
133
133
  )
134
134
  if let existing = calls.values.first(where: { $0.callId == ring.callId && !$0.ended }) {
@@ -0,0 +1,195 @@
1
+ import Foundation
2
+ import UIKit
3
+ import UserNotifications
4
+
5
+ /// An agent attending a meeting for the user asks them something its brief
6
+ /// doesn't cover (server docs/AGENTS_IN_CALLS.md §5). The server sends an
7
+ /// alert push with category `poolse_agent_escalation`; iOS shows it, and
8
+ /// this answers its actions natively — Approve, Decline, and Answer (an
9
+ /// inline text field) — from the lock screen with the app killed.
10
+ ///
11
+ /// The reply is `POST /v1/agent-escalations/:id/reply` with the push's
12
+ /// `reply_token` in the body and no Authorization header: the token names
13
+ /// that escalation and person only, works once, until `expires_at`. It
14
+ /// goes to the push's own server (its `tenant_id`), the push's
15
+ /// `reply_url` only when that server isn't configured here.
16
+ ///
17
+ /// A failure posts "Couldn't send your answer" with the same actions
18
+ /// (while trying again can still work). Results reach JS as
19
+ /// `onNotificationAction` with `action: "escalation"`.
20
+ ///
21
+ /// `PoolseMessageReplyRequiresUnlock` (the config plugin's
22
+ /// `messageReplyRequiresUnlock`) makes these actions ask for Face ID / the
23
+ /// passcode first too.
24
+ enum EscalationNotifications {
25
+ static let category = "poolse_agent_escalation"
26
+ static let approveAction = "poolse_escalation_approve"
27
+ static let declineAction = "poolse_escalation_decline"
28
+ static let answerAction = "poolse_escalation_answer"
29
+
30
+ /// The category, registered with the message one (MessageNotifications).
31
+ static func makeCategory(requireUnlock: Bool) -> UNNotificationCategory {
32
+ let options: UNNotificationActionOptions = requireUnlock ? [.authenticationRequired] : []
33
+ let approve = UNNotificationAction(identifier: approveAction, title: "Approve", options: options)
34
+ let decline = UNNotificationAction(identifier: declineAction, title: "Decline", options: options)
35
+ let answer = UNTextInputNotificationAction(
36
+ identifier: answerAction,
37
+ title: "Answer",
38
+ options: options,
39
+ textInputButtonTitle: "Send",
40
+ textInputPlaceholder: "Your answer"
41
+ )
42
+ return UNNotificationCategory(
43
+ identifier: category,
44
+ actions: [approve, decline, answer],
45
+ intentIdentifiers: [],
46
+ hiddenPreviewsBodyPlaceholder: "Your agent has a question",
47
+ options: []
48
+ )
49
+ }
50
+
51
+ /// An action on an escalation notification. False for a plain tap (the
52
+ /// host opens the conversation) or a dismissal.
53
+ static func didReceive(_ response: UNNotificationResponse) -> Bool {
54
+ let decision: String
55
+ switch response.actionIdentifier {
56
+ case approveAction: decision = "approve"
57
+ case declineAction: decision = "decline"
58
+ case answerAction: decision = "answer"
59
+ default: return false
60
+ }
61
+ let content = response.notification.request.content
62
+ let info = content.userInfo
63
+ func str(_ key: String) -> String? { (info[key] as? String).flatMap { $0.isEmpty ? nil : $0 } }
64
+ guard let id = str("escalation_id") else { return true }
65
+ let server = ServerRegistry.shared.servers.resolve(tenantId: str("tenant_id"))
66
+ var event: [String: Any] = [
67
+ "action": "escalation",
68
+ "escalationId": id,
69
+ "decision": decision,
70
+ "conversationId": str("conversation_id") ?? "",
71
+ "callId": str("call_id") ?? NSNull(),
72
+ ]
73
+ if let sid = server?.id { event["serverId"] = sid }
74
+
75
+ var body: [String: Any] = [:]
76
+ if decision == "answer" {
77
+ let text = String(((response as? UNTextInputNotificationResponse)?.userText ?? "")
78
+ .trimmingCharacters(in: .whitespacesAndNewlines).prefix(1000))
79
+ guard !text.isEmpty else { return true }
80
+ body["answer"] = text
81
+ event["text"] = text
82
+ } else {
83
+ body["decision"] = decision
84
+ }
85
+
86
+ guard let token = str("reply_token") else {
87
+ event["ok"] = false
88
+ event["error"] = "no_token"
89
+ MessageNotifications.report(event)
90
+ postFailure(content, reason: "Open the app to answer.", retry: false)
91
+ return true
92
+ }
93
+ body["token"] = token
94
+
95
+ var origin = server?.apiBaseUrl ?? ServerRegistry.shared.baseUrl(nil)
96
+ if origin.isEmpty { origin = CallCore.persistedApiBaseUrl() ?? "" }
97
+ let encodedId = id.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) ?? id
98
+ let url = !origin.isEmpty
99
+ ? URL(string: "\(origin)/v1/agent-escalations/\(encodedId)/reply")
100
+ : str("reply_url").flatMap(URL.init(string:))
101
+ guard let url = url else {
102
+ event["ok"] = false
103
+ event["error"] = "not_configured"
104
+ MessageNotifications.report(event)
105
+ postFailure(content, reason: "Open the app to answer.", retry: false)
106
+ return true
107
+ }
108
+
109
+ // Started before anything async: iOS may suspend a background-launched
110
+ // app right after the delegate returns.
111
+ let background = BackgroundTask(name: "poolse-escalation-\(decision)")
112
+ send(url: url, body: body, background: background) { status, code in
113
+ let ok = (200..<300).contains(status)
114
+ event["ok"] = ok
115
+ if !ok {
116
+ event["error"] = code ?? (status == 0 ? "network" : "http_\(status)")
117
+ if status != 0 { event["status"] = status }
118
+ let retry = ![401, 404, 409, 410].contains(status)
119
+ postFailure(content, reason: reason(status), retry: retry)
120
+ }
121
+ MessageNotifications.report(event)
122
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { background.end() }
123
+ }
124
+ return true
125
+ }
126
+
127
+ /// "Couldn't send your answer" — with the same actions and token while
128
+ /// trying again can still work.
129
+ private static func postFailure(_ original: UNNotificationContent, reason: String, retry: Bool) {
130
+ let content = UNMutableNotificationContent()
131
+ content.title = "Couldn't send your answer"
132
+ content.body = "\(original.body)\n\(reason)"
133
+ content.threadIdentifier = original.threadIdentifier
134
+ content.sound = .default
135
+ var info = original.userInfo
136
+ info["poolse_escalation_failed"] = "1"
137
+ if !retry { info.removeValue(forKey: "reply_token") }
138
+ content.userInfo = info
139
+ if retry { content.categoryIdentifier = category }
140
+ let id = (original.userInfo["escalation_id"] as? String) ?? UUID().uuidString
141
+ let request = UNNotificationRequest(identifier: "poolse-escalation-failed-\(id)", content: content, trigger: nil)
142
+ UNUserNotificationCenter.current().add(request) { error in
143
+ if let error = error { pcTrace("escalation failure notification refused: \(error)") }
144
+ }
145
+ }
146
+
147
+ private static func reason(_ status: Int) -> String {
148
+ switch status {
149
+ case 0: return "No connection. Try again."
150
+ case 401: return "This notification expired. Open the app to answer."
151
+ case 404: return "This question is gone."
152
+ case 409: return "It was already answered."
153
+ case 410: return "Too late — the question expired."
154
+ case 422: return "The answer couldn't be sent (1 to 1000 characters)."
155
+ case 429: return "Too many tries. Wait a moment."
156
+ default: return "Something went wrong. Try again."
157
+ }
158
+ }
159
+
160
+ private static let session: URLSession = {
161
+ let config = URLSessionConfiguration.ephemeral
162
+ config.timeoutIntervalForRequest = 15
163
+ config.waitsForConnectivity = false
164
+ return URLSession(configuration: config)
165
+ }()
166
+
167
+ /// The POST, retried once after a second only when nothing came back
168
+ /// (the token works once: an answered request is never sent again).
169
+ private static func send(url: URL, body: [String: Any], background: BackgroundTask, attempt: Int = 1,
170
+ done: @escaping (Int, String?) -> Void) {
171
+ var request = URLRequest(url: url)
172
+ request.httpMethod = "POST"
173
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
174
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
175
+ request.httpBody = try? JSONSerialization.data(withJSONObject: body)
176
+ session.dataTask(with: request) { data, response, error in
177
+ let status = error == nil ? ((response as? HTTPURLResponse)?.statusCode ?? 0) : 0
178
+ let json = data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]
179
+ let code = (json?["error"] as? [String: Any])?["code"] as? String
180
+ if status == 0 && attempt < 2 {
181
+ DispatchQueue.main.async {
182
+ guard background.remaining > 20 else { return done(status, code) }
183
+ DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
184
+ send(url: url, body: body, background: background, attempt: attempt + 1, done: done)
185
+ }
186
+ }
187
+ return
188
+ }
189
+ if !(200..<300).contains(status) {
190
+ pcTrace("escalation reply failed status=\(status) code=\(code ?? "-") error=\(String(describing: error))")
191
+ }
192
+ done(status, code)
193
+ }.resume()
194
+ }
195
+ }