@poolse/native 0.0.0-stage → 3.0.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 (66) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +206 -0
  3. package/README.md +148 -2
  4. package/android/build.gradle +58 -0
  5. package/android/consumer-rules.pro +11 -0
  6. package/android/src/main/AndroidManifest.xml +46 -0
  7. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +540 -0
  8. package/android/src/main/java/dev/poolse/callcore/CallMachine.kt +492 -0
  9. package/android/src/main/java/dev/poolse/callcore/Ports.kt +132 -0
  10. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +383 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/CallActionReceiver.kt +45 -0
  12. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +578 -0
  13. package/android/src/main/java/dev/poolse/callcore/android/CallForegroundService.kt +294 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +207 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +161 -0
  16. package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +36 -0
  17. package/android/src/main/java/dev/poolse/callcore/android/HandlerTimerPort.kt +42 -0
  18. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +314 -0
  19. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +353 -0
  20. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +103 -0
  21. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +42 -0
  22. package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +99 -0
  23. package/android/src/main/java/expo/modules/poolsecalls/CallLockscreen.kt +42 -0
  24. package/android/src/main/java/expo/modules/poolsecalls/CallPictureInPicture.kt +92 -0
  25. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallVideoView.kt +64 -0
  26. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +205 -0
  27. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +594 -0
  28. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitVideoSurface.kt +107 -0
  29. package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +61 -0
  30. package/app.plugin.js +5 -0
  31. package/dist/index.cjs +197 -0
  32. package/dist/index.cjs.map +1 -0
  33. package/dist/index.d.cts +313 -0
  34. package/dist/index.d.ts +313 -0
  35. package/dist/index.js +161 -0
  36. package/dist/index.js.map +1 -0
  37. package/expo-module.config.json +11 -0
  38. package/ios/Core/CallCoreRuntime.swift +543 -0
  39. package/ios/Core/CallHttpClient.swift +213 -0
  40. package/ios/Core/CallMachine.swift +394 -0
  41. package/ios/Core/PORTS_READY.md +93 -0
  42. package/ios/Core/Ports.swift +238 -0
  43. package/ios/Core/SnapshotEncoding.swift +122 -0
  44. package/ios/Module/PoolseCallVideoView.swift +70 -0
  45. package/ios/Module/PoolseCallsAppDelegateSubscriber.swift +16 -0
  46. package/ios/Module/PoolseCallsModule.swift +150 -0
  47. package/ios/Platform/CallCore.swift +623 -0
  48. package/ios/Platform/CallKitController.swift +326 -0
  49. package/ios/Platform/CallPictureInPicture.swift +145 -0
  50. package/ios/Platform/LiveKitMediaPort.swift +798 -0
  51. package/ios/Platform/LiveKitVideoSurface.swift +68 -0
  52. package/ios/Platform/MessageNotifications.swift +163 -0
  53. package/ios/Platform/Ringback.swift +61 -0
  54. package/ios/Platform/VoipPush.swift +174 -0
  55. package/ios/PoolseCalls.podspec +68 -0
  56. package/package.json +53 -4
  57. package/plugin/index.js +42 -0
  58. package/plugin/package.json +1 -0
  59. package/plugin/withCallDelegate.js +35 -0
  60. package/plugin/withLockscreenCalls.js +84 -0
  61. package/plugin/withNativeCallMedia.js +19 -0
  62. package/plugin/withPictureInPicture.js +28 -0
  63. package/plugin/withRingback.js +86 -0
  64. package/src/expo-modules-core.d.ts +16 -0
  65. package/src/index.ts +564 -0
  66. package/src/react-shims.d.ts +22 -0
@@ -0,0 +1,623 @@
1
+ import AVFoundation
2
+ import CallKit
3
+ import Foundation
4
+ #if canImport(LiveKitClient)
5
+ import LiveKitClient // CocoaPods module name
6
+ #else
7
+ import LiveKit // SwiftPM module name
8
+ #endif
9
+ import UIKit
10
+
11
+ /// The host-supplied configuration, persisted so a PushKit cold wake
12
+ /// (no JS, no configure call) rebuilds the same core from disk.
13
+ struct CallCoreConfig {
14
+ var apiBaseUrl: String
15
+ var ringback: String?
16
+ /// `production` | `sandbox` — the APNs environment the VoIP token
17
+ /// belongs to. Not reliably readable at runtime, so the host says it.
18
+ var apnsEnvironment: String?
19
+ }
20
+
21
+ /// The composition root and the single native entry point — CallCore.kt
22
+ /// for iOS. PushKit, CallKit's provider actions and the React Native
23
+ /// bridge all come through here: one runtime, one answer/decline path.
24
+ ///
25
+ /// It also owns what the pure machine does not carry but a truthful
26
+ /// snapshot needs (roster, conversation name, self mute/camera, audio
27
+ /// route), and reconciles CallKit against every final snapshot.
28
+ ///
29
+ /// Main thread only, except `snapshot()` / `peek()`.
30
+ final class CallCore {
31
+ // MARK: statics
32
+
33
+ private static let defaults = UserDefaults(suiteName: "dev.poolse.callcore") ?? .standard
34
+ private static let configLock = NSLock()
35
+ private static var _config: CallCoreConfig?
36
+ private static var instance: CallCore?
37
+
38
+ static var config: CallCoreConfig? {
39
+ configLock.lock(); defer { configLock.unlock() }
40
+ return _config
41
+ }
42
+
43
+ /// The bridge's snapshot subscriber; process-level so JS may subscribe before configure.
44
+ static var listener: (([String: Any]?) -> Void)?
45
+
46
+ /// Configure and PERSIST (see CallCore.kt). Re-configuring swaps in place:
47
+ /// HTTP and the ringback read the config per use.
48
+ static func configure(apiBaseUrl: String, ringback: String?, apnsEnvironment: String?) {
49
+ let trimmed = apiBaseUrl.hasSuffix("/") ? String(apiBaseUrl.dropLast()) : apiBaseUrl
50
+ defaults.set(trimmed, forKey: "apiBaseUrl")
51
+ defaults.set(ringback, forKey: "ringback")
52
+ defaults.set(apnsEnvironment, forKey: "apnsEnvironment")
53
+ writeConfigFile(apiBaseUrl: trimmed, ringback: ringback, apnsEnvironment: apnsEnvironment)
54
+ configLock.lock()
55
+ _config = CallCoreConfig(apiBaseUrl: trimmed, ringback: ringback, apnsEnvironment: apnsEnvironment)
56
+ configLock.unlock()
57
+ }
58
+
59
+ /// The APNs environment last configured (persisted), if any.
60
+ static var apnsEnvironment: String? {
61
+ config?.apnsEnvironment ?? defaults.string(forKey: "apnsEnvironment") ?? readConfigFile()?.apnsEnvironment
62
+ }
63
+
64
+ private static func restoreConfig() {
65
+ guard config == nil else { return }
66
+ let restored: CallCoreConfig
67
+ if let url = defaults.string(forKey: "apiBaseUrl") {
68
+ restored = CallCoreConfig(apiBaseUrl: url,
69
+ ringback: defaults.string(forKey: "ringback"),
70
+ apnsEnvironment: defaults.string(forKey: "apnsEnvironment"))
71
+ } else if let fromFile = readConfigFile() {
72
+ // Locked since reboot: UserDefaults is unreadable before first
73
+ // unlock, the unprotected file is not.
74
+ restored = fromFile
75
+ } else {
76
+ return
77
+ }
78
+ configLock.lock()
79
+ _config = restored
80
+ configLock.unlock()
81
+ }
82
+
83
+ // MARK: config file (readable before first unlock)
84
+
85
+ /// Application Support/dev.poolse.callcore/config.json, written with
86
+ /// FileProtectionType.none so a PushKit wake while the device has been
87
+ /// locked since reboot can still rebuild the core. Holds no secrets —
88
+ /// only the API origin, a sound name and the APNs environment.
89
+ private static var configFileURL: URL? {
90
+ guard let base = FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask).first else { return nil }
91
+ return base.appendingPathComponent("dev.poolse.callcore", isDirectory: true).appendingPathComponent("config.json")
92
+ }
93
+
94
+ private static func writeConfigFile(apiBaseUrl: String, ringback: String?, apnsEnvironment: String?) {
95
+ guard let url = configFileURL else { return }
96
+ var obj: [String: Any] = ["apiBaseUrl": apiBaseUrl]
97
+ if let ringback = ringback { obj["ringback"] = ringback }
98
+ if let apnsEnvironment = apnsEnvironment { obj["apnsEnvironment"] = apnsEnvironment }
99
+ do {
100
+ let fm = FileManager.default
101
+ let dir = url.deletingLastPathComponent()
102
+ try fm.createDirectory(at: dir, withIntermediateDirectories: true,
103
+ attributes: [.protectionKey: FileProtectionType.none])
104
+ let data = try JSONSerialization.data(withJSONObject: obj)
105
+ try data.write(to: url, options: [.atomic, .noFileProtection])
106
+ try? fm.setAttributes([.protectionKey: FileProtectionType.none], ofItemAtPath: url.path)
107
+ } catch {
108
+ NSLog("[PoolseCalls] config file write failed: %@", "\(error)")
109
+ }
110
+ }
111
+
112
+ private static func readConfigFile() -> CallCoreConfig? {
113
+ guard let url = configFileURL, let data = try? Data(contentsOf: url),
114
+ let obj = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any],
115
+ let api = obj["apiBaseUrl"] as? String, !api.isEmpty else { return nil }
116
+ return CallCoreConfig(apiBaseUrl: api, ringback: obj["ringback"] as? String,
117
+ apnsEnvironment: obj["apnsEnvironment"] as? String)
118
+ }
119
+
120
+ /// The core, or nil if this install was never configured. Main thread.
121
+ static func getOrNull() -> CallCore? {
122
+ if let i = instance { return i }
123
+ restoreConfig()
124
+ guard config != nil else { return nil }
125
+ let core = CallCore()
126
+ instance = core
127
+ return core
128
+ }
129
+
130
+ /// The live core if one exists — never creates.
131
+ static func peek() -> CallCore? { instance }
132
+
133
+ // MARK: parts
134
+
135
+ private let callKit = CallKitController.shared
136
+ private var mediaPort: LiveKitMediaPort!
137
+ private var runtime: CallCoreRuntime!
138
+ private var ringback: Ringback!
139
+ private var surfaceAdapter: SurfaceAdapter!
140
+ private var eventsAdapter: EventsAdapter!
141
+
142
+ // Snapshot extras (main thread).
143
+ private var extrasCallId: String?
144
+ private var extrasMedia: String?
145
+ private var roster: [SnapshotParticipant] = []
146
+ private var conversationName: String?
147
+ private var callKind = "call"
148
+ private var mutedSelf = false
149
+ private var cameraOn = false
150
+ private var cameraFacing: String?
151
+ private var audioRoute: String?
152
+ private var audioOutputs: [AudioOutput] = []
153
+ private var audioOutputId: String?
154
+ private var connectionQuality = "unknown"
155
+ private var videoPaused = false
156
+
157
+ /// ring_ended reasons seen per call — the CallKit end reason.
158
+ private var ringEndReasons: [String: String] = [:]
159
+ /// The user ended from our UI (JS): end CallKit with a transaction.
160
+ private var localEnd = false
161
+
162
+ private let snapshotLock = NSLock()
163
+ private var lastSnapshot: [String: Any]?
164
+
165
+ private init() {
166
+ ringback = Ringback(resourceName: { CallCore.config?.ringback })
167
+ eventsAdapter = EventsAdapter()
168
+ mediaPort = LiveKitMediaPort(events: eventsAdapter)
169
+ surfaceAdapter = SurfaceAdapter()
170
+ runtime = CallCoreRuntime(
171
+ http: CallHttpClient(baseUrl: { CallCore.config?.apiBaseUrl ?? "" }),
172
+ media: mediaPort,
173
+ surface: surfaceAdapter,
174
+ session: surfaceAdapter,
175
+ timers: MainQueueTimerPort(),
176
+ sink: BlockSnapshotSink { [weak self] state in self?.onState(state) }
177
+ )
178
+ eventsAdapter.core = self
179
+ surfaceAdapter.core = self
180
+ callKit.actions = self
181
+ // LiveKit's audio stays off until CallKit activates the session —
182
+ // configured now, at launch, before any activation can happen.
183
+ mediaPort.prepareAudio()
184
+ // A no-op mute transaction (same state) makes CallKit retry a failed
185
+ // audio-session activation.
186
+ mediaPort.requestAudioActivation = { [weak self] in
187
+ guard let self = self, let callId = self.runtime.currentState().callId else { return }
188
+ self.callKit.requestMute(callId: callId, muted: self.mutedSelf)
189
+ }
190
+ }
191
+
192
+ // MARK: - native entry points
193
+
194
+ func onRing(_ ring: RingContext) { runtime.onRing(ring) }
195
+
196
+ func onRingEnded(callId: String, reason: String) {
197
+ onMain { [self] in
198
+ ringEndReasons[callId] = reason
199
+ runtime.onRingEnded(callId: callId, reason: reason)
200
+ reconcileCallKitSoon()
201
+ }
202
+ }
203
+
204
+ func onCallFinished(callId: String, reason: String?) {
205
+ onMain { [self] in
206
+ runtime.onCallFinished(callId: callId, reason: reason)
207
+ reconcileCallKitSoon()
208
+ }
209
+ }
210
+
211
+ /// False once this ring is resolved here or past its deadline (+ clock slack).
212
+ func isRingLive(_ ring: RingContext) -> Bool {
213
+ let now = Int64(Date().timeIntervalSince1970 * 1000)
214
+ return !runtime.isResolved(ring.callId) && ring.ringDeadlineEpochMs + CallCoreRuntime.CLOCK_SLACK_MS > now
215
+ }
216
+
217
+ /// Reconcile CallKit after everything queued so far has run.
218
+ func reconcileCallKitSoon() {
219
+ runtime.post { [weak self] in
220
+ guard let self = self else { return }
221
+ self.reconcileCallKit(self.runtime.currentState())
222
+ }
223
+ }
224
+
225
+ // MARK: - bridge-driven actions (any thread)
226
+
227
+ func answer() { runtime.answer() }
228
+
229
+ func decline() {
230
+ onMain { [self] in
231
+ localEnd = true
232
+ runtime.decline()
233
+ }
234
+ }
235
+
236
+ func hangUp() {
237
+ onMain { [self] in
238
+ localEnd = true
239
+ runtime.hangUp()
240
+ }
241
+ }
242
+
243
+ /// Call waiting: end this call, answer the waiting one. CallKit follows
244
+ /// from the resulting state: reconcileCallKit reports the old call
245
+ /// ended, then answers the new one.
246
+ func answerWaiting(callId: String? = nil) {
247
+ onMain { [self] in runtime.answerWaiting(callId: callId) }
248
+ }
249
+
250
+ /// Call waiting: turn the waiting call away (its caller hears busy).
251
+ func declineWaiting(callId: String? = nil) {
252
+ onMain { [self] in runtime.declineWaiting(callId: callId) }
253
+ }
254
+
255
+ /// True while `callId` is the call waiting beside the current one. Main thread.
256
+ func isWaiting(_ callId: String) -> Bool { runtime.currentState().waiting?.callId == callId }
257
+
258
+ func place(conversationId: String, media: String, sessionToken: String) {
259
+ onMain { [self] in
260
+ localEnd = false
261
+ runtime.place(conversationId: conversationId, media: media, sessionToken: sessionToken)
262
+ }
263
+ }
264
+
265
+ func join(callId: String, conversationId: String?, sessionToken: String) {
266
+ onMain { [self] in
267
+ localEnd = false
268
+ runtime.join(callId: callId, conversationId: conversationId, sessionToken: sessionToken)
269
+ }
270
+ }
271
+
272
+ func setMuted(_ muted: Bool) {
273
+ onMain { [self] in
274
+ applyMuted(muted)
275
+ if let id = runtime.currentState().callId { callKit.requestMute(callId: id, muted: muted) }
276
+ }
277
+ }
278
+
279
+ private func applyMuted(_ muted: Bool) {
280
+ mutedSelf = muted
281
+ runtime.setMuted(muted)
282
+ runtime.reemit()
283
+ }
284
+
285
+ /// Not optimistic: cameraOn flips when the media adapter reports it published.
286
+ func setCamera(_ on: Bool) { runtime.setCamera(on) }
287
+
288
+ func switchCamera() { runtime.switchCamera() }
289
+
290
+ func setSpeaker(_ on: Bool) {
291
+ onMain { [self] in
292
+ audioRoute = on ? "speaker" : "earpiece" // optimistic; the adapter reports the real one
293
+ runtime.setSpeaker(on)
294
+ runtime.reemit()
295
+ }
296
+ }
297
+
298
+ /// Not optimistic: the adapter reports the route once iOS has moved it.
299
+ func setAudioOutput(_ id: String) { runtime.setAudioOutput(id) }
300
+
301
+ /// The current call's id and control token (main thread).
302
+ var control: (callId: String, controlToken: String)? { runtime.control }
303
+
304
+ /// A video slot for the native view. Main thread.
305
+ func createVideoSurface(renderMode: VideoView.RenderMode = .auto) -> LiveKitVideoSurface {
306
+ mediaPort.createVideoSurface(renderMode: renderMode)
307
+ }
308
+
309
+ /// The contract Snapshot (nil = idle), safe from any thread.
310
+ func snapshot() -> [String: Any]? {
311
+ snapshotLock.lock(); defer { snapshotLock.unlock() }
312
+ return lastSnapshot
313
+ }
314
+
315
+ private func onMain(_ block: @escaping () -> Void) {
316
+ if Thread.isMainThread { block() } else { DispatchQueue.main.async(execute: block) }
317
+ }
318
+
319
+ // MARK: - snapshot assembly (main)
320
+
321
+ fileprivate func onState(_ state: MachineState) {
322
+ if state.phase == .idle {
323
+ if extrasCallId != nil { mediaPort.leave() }
324
+ resetExtras(nil, nil)
325
+ } else if state.callId != extrasCallId {
326
+ // `pending:<conv>` → the server-minted id is the same call — but only
327
+ // for that conversation's own placed call: a waiting call promoted
328
+ // over a still-pending one is a different call (renaming would give
329
+ // CallKit two calls with one id, and the incoming one never answered).
330
+ if let old = extrasCallId, old.hasPrefix("pending:"), state.direction != .incoming,
331
+ old == "pending:\(state.conversationId ?? "")" {
332
+ if let new = state.callId { callKit.rename(from: old, to: new) }
333
+ extrasCallId = state.callId
334
+ } else {
335
+ // A different call (a waiting one promoted): nothing of the last
336
+ // carries over — not even "the user ended it here".
337
+ if extrasCallId != nil { localEnd = false }
338
+ resetExtras(state.callId, state.media)
339
+ }
340
+ }
341
+ if state.phase != .idle && state.media != extrasMedia {
342
+ if extrasMedia != nil { audioRoute = nil }
343
+ extrasMedia = state.media
344
+ }
345
+ if let name = runtime.conversationName { conversationName = name }
346
+ if let kind = runtime.callKind { callKind = kind }
347
+
348
+ let snap = state.toSnapshot(
349
+ conversationName: conversationName,
350
+ kind: callKind,
351
+ participants: roster,
352
+ // Video calls and rooms default to the speaker (the media port agrees).
353
+ audioRoute: audioRoute ?? (state.media == "video" || callKind == "room" ? "speaker" : "earpiece"),
354
+ audioOutputs: audioOutputs,
355
+ audioOutputId: audioOutputId,
356
+ mutedSelf: mutedSelf,
357
+ cameraOn: cameraOn,
358
+ cameraFacing: cameraFacing,
359
+ waiting: runtime.waitingRing,
360
+ connectionQuality: connectionQuality,
361
+ videoPaused: videoPaused
362
+ )
363
+ snapshotLock.lock(); lastSnapshot = snap; snapshotLock.unlock()
364
+ reconcileCallKit(state)
365
+ reconcileDevice(state)
366
+ CallCore.listener?(snap)
367
+ }
368
+
369
+ private func resetExtras(_ callId: String?, _ media: String?) {
370
+ extrasCallId = callId
371
+ extrasMedia = media
372
+ roster = []
373
+ conversationName = nil
374
+ callKind = "call"
375
+ mutedSelf = false
376
+ cameraOn = false
377
+ cameraFacing = nil
378
+ audioRoute = nil
379
+ audioOutputs = []
380
+ audioOutputId = nil
381
+ connectionQuality = "unknown"
382
+ videoPaused = false
383
+ }
384
+
385
+ /// CallKit follows the FINAL state of each dispatch.
386
+ private func reconcileCallKit(_ state: MachineState) {
387
+ let terminal = state.phase == .idle || state.phase == .ended
388
+ // The call waiting beside this one stays on CallKit's call-waiting UI.
389
+ let live = callKit.liveCalls.filter { terminal || $0.callId != state.waiting?.callId }
390
+ // Ends first: answering the next call (end-and-answer) while CallKit
391
+ // still holds the last one would ask it for two calls at once.
392
+ for t in live where terminal || t.callId != state.callId {
393
+ // Not the call the machine is in (ended, busy-declined, superseded).
394
+ // Terminal: whatever CallKit still shows is the call that just ended.
395
+ let reason = endReason(for: t, state: state, current: terminal || t.callId == state.callId)
396
+ pcTrace("reconcile end \(t.callId) reason=\(reason.map { "\($0.rawValue)" } ?? "local") phase=\(state.phase)")
397
+ callKit.end(t, reason: reason)
398
+ }
399
+ for t in live where !terminal && t.callId == state.callId {
400
+ switch state.phase {
401
+ case .connecting, .active, .reconnecting, .ringingOut:
402
+ // Answered from the app's own UI: tell CallKit (audio follows).
403
+ if !t.outgoing && !t.answered && state.direction == .incoming { callKit.requestAnswer(callId: t.callId) }
404
+ if t.outgoing && state.phase == .active { callKit.reportConnected(callId: t.callId) }
405
+ callKit.updateTitle(callId: t.callId, title: conversationName, video: state.media == "video")
406
+ default:
407
+ break
408
+ }
409
+ }
410
+ if terminal {
411
+ localEnd = false
412
+ if let id = state.callId { ringEndReasons.removeValue(forKey: id) }
413
+ if ringEndReasons.count > 16 { ringEndReasons.removeAll() }
414
+ }
415
+ }
416
+
417
+ /// nil = ended locally (end transaction); else how it ended remotely.
418
+ private func endReason(for t: CallKitController.Tracked, state: MachineState, current: Bool) -> CXCallEndedReason? {
419
+ if current && localEnd && state.reason != .failed && state.reason != .connectionLost { return nil }
420
+ if !t.answered && !t.outgoing {
421
+ switch ringEndReasons[t.callId] {
422
+ case "answered_elsewhere": return .answeredElsewhere
423
+ case "declined": return .declinedElsewhere
424
+ case "timeout": return .unanswered
425
+ case "cancelled", "finished": return .remoteEnded
426
+ default: break
427
+ }
428
+ if !current { return .unanswered } // busy-declined / never taken
429
+ }
430
+ guard current else { return .remoteEnded }
431
+ switch state.reason {
432
+ case .noAnswer?, .busyAll?: return .unanswered
433
+ case .connectionLost?, .failed?: return .failed
434
+ case .left?: return localEnd ? nil : .remoteEnded
435
+ default: return .remoteEnded
436
+ }
437
+ }
438
+
439
+ /// Screen off at the ear: only for an audio call on the earpiece.
440
+ private func reconcileDevice(_ state: MachineState) {
441
+ let inCall = state.phase == .active || state.phase == .reconnecting ||
442
+ state.phase == .ringingOut || state.phase == .connecting
443
+ let route = audioRoute ?? (state.media == "video" ? "speaker" : "earpiece")
444
+ let want = inCall && state.media == "audio" && route == "earpiece"
445
+ if UIDevice.current.isProximityMonitoringEnabled != want { UIDevice.current.isProximityMonitoringEnabled = want }
446
+ }
447
+
448
+ // MARK: - ports' callbacks
449
+
450
+ fileprivate func sessionStart(callId: String, media: String) {
451
+ guard callKit.tracked(callId: callId) == nil else { return } // an answered incoming call
452
+ let state = runtime.currentState()
453
+ callKit.startOutgoing(callId: callId, handle: state.conversationId ?? callId, title: runtime.conversationName,
454
+ video: media == "video") { [weak self] in
455
+ // CallKit refused: the call goes on without the system UI.
456
+ self?.mediaPort.activateAudioWithoutCallKit(media: media)
457
+ }
458
+ }
459
+
460
+ fileprivate func showRing(_ ring: RingContext) {
461
+ // Usually already reported by the push path; idempotent.
462
+ callKit.reportIncoming(ring: ring)
463
+ }
464
+
465
+ /// CallKit shows a second incoming call over a live one as call
466
+ /// waiting (End & Accept / Decline). Usually already reported by the
467
+ /// push path; idempotent.
468
+ fileprivate func showWaiting(_ ring: RingContext) {
469
+ callKit.reportIncoming(ring: ring)
470
+ }
471
+
472
+ fileprivate var ringbackPlayer: Ringback { ringback }
473
+
474
+ // MediaEvents → runtime
475
+ fileprivate func mediaConnected() { runtime.onMediaConnected() }
476
+ fileprivate func mediaFailed() { runtime.onMediaFailed() }
477
+ fileprivate func mediaLost() { runtime.onMediaLost() }
478
+ fileprivate func mediaReconnecting() { runtime.onMediaReconnecting() }
479
+ fileprivate func mediaRecovered() { runtime.onMediaRecovered() }
480
+ fileprivate func remoteJoined() { runtime.onRemoteJoined() }
481
+ fileprivate func participants(_ p: [SnapshotParticipant]) {
482
+ runtime.post { [weak self] in self?.roster = p }
483
+ runtime.onRemoteCount(p.count)
484
+ runtime.reemit()
485
+ }
486
+ fileprivate func route(_ r: String) {
487
+ runtime.post { [weak self] in self?.audioRoute = r }
488
+ runtime.reemit()
489
+ }
490
+ fileprivate func outputs(_ list: [AudioOutput], selected: String?) {
491
+ runtime.post { [weak self] in self?.audioOutputs = list; self?.audioOutputId = selected }
492
+ runtime.reemit()
493
+ }
494
+ fileprivate func network(quality: String, videoPaused paused: Bool) {
495
+ runtime.post { [weak self] in self?.connectionQuality = quality; self?.videoPaused = paused }
496
+ runtime.reemit()
497
+ }
498
+ fileprivate func localCamera(on: Bool, facing: String?) {
499
+ runtime.post { [weak self] in self?.cameraOn = on; self?.cameraFacing = facing }
500
+ runtime.reemit()
501
+ }
502
+ }
503
+
504
+ // MARK: - CallKit actions
505
+
506
+ extension CallCore: CallKitActions {
507
+ func callKitAnswer(callId: String) {
508
+ let s = runtime.currentState()
509
+ pcTrace("callKitAnswer \(callId) phase=\(s.phase) current=\(s.callId ?? "-") waiting=\(s.waiting?.callId ?? "-")")
510
+ // End & Accept may answer the waiting call before ending the current
511
+ // one: answering it ends the current call itself.
512
+ if s.waiting?.callId == callId {
513
+ runtime.answerWaiting(callId: callId)
514
+ return
515
+ }
516
+ guard s.callId == callId, s.phase == .ringingIn else { return }
517
+ runtime.answer()
518
+ }
519
+
520
+ func callKitEnd(callId: String) {
521
+ let s = runtime.currentState()
522
+ pcTrace("callKitEnd \(callId) phase=\(s.phase) current=\(s.callId ?? "-") waiting=\(s.waiting?.callId ?? "-")")
523
+ // Decline on CallKit's call-waiting UI.
524
+ if s.waiting?.callId == callId {
525
+ runtime.declineWaiting(callId: callId)
526
+ return
527
+ }
528
+ guard s.callId == callId || (s.callId?.hasPrefix("pending:") == true) else { return }
529
+ localEnd = true
530
+ if s.phase == .ringingIn { runtime.decline() } else { runtime.hangUp() }
531
+ }
532
+
533
+ func callKitSetMuted(callId: String, muted: Bool) {
534
+ guard muted != mutedSelf else { return }
535
+ applyMuted(muted)
536
+ }
537
+
538
+ func callKitAudioActivated(_ session: AVAudioSession) {
539
+ mediaPort.audioActivated(session, media: runtime.currentState().media)
540
+ ringback.sessionActivated()
541
+ }
542
+
543
+ func callKitAudioDeactivated(_ session: AVAudioSession) {
544
+ ringback.stop()
545
+ mediaPort.audioDeactivated()
546
+ }
547
+
548
+ func callKitHoldForWaiting(callId: String) -> Bool {
549
+ let s = runtime.currentState()
550
+ return s.callId == callId && s.waiting != nil
551
+ }
552
+
553
+ func callKitReset() {
554
+ let s = runtime.currentState()
555
+ guard s.phase != .idle && s.phase != .ended else { return }
556
+ // CallKit dropped every call, the waiting one included: turn it away
557
+ // first, or ending the current call would ring it afresh.
558
+ if let w = s.waiting { runtime.declineWaiting(callId: w.callId) }
559
+ localEnd = true
560
+ if s.phase == .ringingIn { runtime.decline() } else { runtime.hangUp() }
561
+ }
562
+ }
563
+
564
+ // MARK: - port adapters
565
+
566
+ /// RingSurfacePort + CallSessionPort: CallKit. The ringtone is CallKit's;
567
+ /// dismissal and session end are reconciled from the final state.
568
+ private final class SurfaceAdapter: RingSurfacePort, CallSessionPort {
569
+ weak var core: CallCore?
570
+
571
+ func show(ring: RingContext) { core?.showRing(ring) }
572
+ func dismiss(callId: String) {}
573
+ func showWaiting(ring: RingContext) { core?.showWaiting(ring) }
574
+ // Dismissal is reconciled from the final state; promotion keeps the
575
+ // CallKit call, which SHOW_RING then finds already reported.
576
+ func dismissWaiting(callId: String) {}
577
+ func promoteWaiting(callId: String) {}
578
+ func ringtoneStart() {}
579
+ func ringtoneStop() {}
580
+ func ringbackStart() { core?.ringbackPlayer.start() }
581
+ func ringbackStop() { core?.ringbackPlayer.stop() }
582
+
583
+ func start(callId: String, media: String) { core?.sessionStart(callId: callId, media: media) }
584
+ func stop() { core?.ringbackPlayer.stop() }
585
+ }
586
+
587
+ private final class EventsAdapter: MediaEvents {
588
+ weak var core: CallCore?
589
+
590
+ func onConnected() { core?.mediaConnected() }
591
+ func onFailed() { core?.mediaFailed() }
592
+ func onLost() { core?.mediaLost() }
593
+ func onReconnecting() { core?.mediaReconnecting() }
594
+ func onRecovered() { core?.mediaRecovered() }
595
+ func onRemoteJoined() { core?.remoteJoined() }
596
+ func onParticipants(_ participants: [SnapshotParticipant]) { core?.participants(participants) }
597
+ func onAudioRoute(_ route: String) { core?.route(route) }
598
+ func onLocalCamera(on: Bool, facing: String?) { core?.localCamera(on: on, facing: facing) }
599
+ func onAudioOutputs(_ outputs: [AudioOutput], selectedId: String?) { core?.outputs(outputs, selected: selectedId) }
600
+ func onNetwork(quality: String, videoPaused: Bool) { core?.network(quality: quality, videoPaused: videoPaused) }
601
+ }
602
+
603
+ /// Host-facing entry points.
604
+ @objc(PoolseCalls)
605
+ public final class PoolseCallsSetup: NSObject {
606
+ /// Create the PushKit registry (and the CallKit provider, and the core
607
+ /// if this install was ever configured). Idempotent; main thread.
608
+ ///
609
+ /// Called automatically from `PoolseCallsAppDelegateSubscriber`'s
610
+ /// didFinishLaunching (registered through expo-module.config.json), so
611
+ /// an Expo host needs NO AppDelegate edit. A non-Expo host calls this
612
+ /// from its own `application(_:didFinishLaunchingWithOptions:)`.
613
+ @objc public static func registerVoipEarly() {
614
+ if !Thread.isMainThread {
615
+ DispatchQueue.main.async { registerVoipEarly() }
616
+ return
617
+ }
618
+ _ = CallKitController.shared
619
+ _ = CallCore.getOrNull()
620
+ VoipPush.shared.register()
621
+ MessageNotifications.shared.install()
622
+ }
623
+ }