@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,68 @@
1
+ #if canImport(LiveKitClient)
2
+ import LiveKitClient // CocoaPods module name
3
+ #else
4
+ import LiveKit // SwiftPM module name
5
+ #endif
6
+ import UIKit
7
+
8
+ /// One on-screen video slot over LiveKit's VideoView — LiveKitVideoSurface.kt
9
+ /// for iOS. The port rebinds every live surface whenever a camera may have
10
+ /// appeared, vanished, muted, or the room was replaced (rejoin).
11
+ ///
12
+ /// Main thread only, like the port that owns it.
13
+ final class LiveKitVideoSurface: UIView {
14
+ private weak var port: LiveKitMediaPort?
15
+ private let videoView = VideoView()
16
+ private var released = false
17
+
18
+ private var participantId: String?
19
+ private var local = false
20
+ private var mirror: Bool?
21
+ private var fit = "cover"
22
+
23
+ init(port: LiveKitMediaPort, renderMode: VideoView.RenderMode = .auto) {
24
+ self.port = port
25
+ super.init(frame: .zero)
26
+ videoView.renderMode = renderMode
27
+ backgroundColor = .clear
28
+ clipsToBounds = true
29
+ videoView.frame = bounds
30
+ videoView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
31
+ videoView.isHidden = true
32
+ addSubview(videoView)
33
+ }
34
+
35
+ required init?(coder: NSCoder) { fatalError("init(coder:) is not supported") }
36
+
37
+ /// [participantId] is the remote's userId (SFU identity); [local] shows
38
+ /// the self view. [mirror] nil = mirrored for the local front camera only.
39
+ func configure(participantId: String?, local: Bool, mirror: Bool?, fit: String) {
40
+ self.participantId = participantId
41
+ self.local = local
42
+ self.mirror = mirror
43
+ self.fit = fit
44
+ rebind()
45
+ }
46
+
47
+ func rebind() {
48
+ guard !released else { return }
49
+ let next = port?.cameraTrack(participantId: participantId, local: local)
50
+ if (videoView.track as AnyObject?) !== (next as AnyObject?) {
51
+ videoView.track = next
52
+ }
53
+ // No camera: hide so a last frozen frame never shows; the UI draws
54
+ // the avatar from the snapshot's cameraOn underneath.
55
+ videoView.isHidden = next == nil
56
+ let mirrored = mirror ?? (local && port?.cameraFacing() != "back")
57
+ videoView.mirrorMode = mirrored ? .mirror : .off
58
+ videoView.layoutMode = fit == "contain" ? .fit : .fill
59
+ }
60
+
61
+ /// Detach from any track. Idempotent.
62
+ func release() {
63
+ guard !released else { return }
64
+ released = true
65
+ videoView.track = nil
66
+ port?.unregister(self)
67
+ }
68
+ }
@@ -0,0 +1,163 @@
1
+ import EXNotifications
2
+ import Foundation
3
+ import UIKit
4
+ import UserNotifications
5
+
6
+ /// Chat notifications on iOS (CALL_CONTRACT.md §5.5) — the parts that must work
7
+ /// with the app not running: Reply and Mark as read from the notification,
8
+ /// and clearing a conversation's notifications once it was read elsewhere.
9
+ ///
10
+ /// iOS itself shows the message (an alert push with `thread-id` =
11
+ /// conversation, so a chat's messages stack together). This class only
12
+ /// acts on them. It plugs into expo-notifications rather than taking over
13
+ /// the notification-center delegate: expo-notifications owns that delegate
14
+ /// in an Expo app, and fanning out to registered delegates is its
15
+ /// supported extension point — taking it would break every other
16
+ /// notification feature in the app.
17
+ ///
18
+ /// Reply and Mark as read run natively, authorized by the reply grant the
19
+ /// push carried, so they work from the lock screen with the app killed.
20
+ final class MessageNotifications: NSObject, NotificationDelegate {
21
+ static let shared = MessageNotifications()
22
+
23
+ static let category = "poolse_message"
24
+ static let replyAction = "reply"
25
+ static let markReadAction = "mark_read"
26
+
27
+ private var installed = false
28
+
29
+ /// Main thread, at launch (PoolseCallsSetup.registerVoipEarly).
30
+ func install() {
31
+ guard !installed else { return }
32
+ installed = true
33
+ registerCategory()
34
+ NotificationCenterManager.shared.addDelegate(self)
35
+ }
36
+
37
+ /// Add the message category beside whatever the app (or expo) declared:
38
+ /// setNotificationCategories REPLACES the whole set.
39
+ private func registerCategory() {
40
+ let reply = UNTextInputNotificationAction(
41
+ identifier: Self.replyAction,
42
+ title: "Reply",
43
+ options: [],
44
+ textInputButtonTitle: "Send",
45
+ textInputPlaceholder: "Message"
46
+ )
47
+ let markRead = UNNotificationAction(identifier: Self.markReadAction, title: "Mark as read", options: [])
48
+ let category = UNNotificationCategory(
49
+ identifier: Self.category,
50
+ actions: [reply, markRead],
51
+ intentIdentifiers: [],
52
+ hiddenPreviewsBodyPlaceholder: "New message",
53
+ categorySummaryFormat: "%u more messages from %@",
54
+ options: []
55
+ )
56
+ let center = UNUserNotificationCenter.current()
57
+ center.getNotificationCategories { existing in
58
+ var all = existing.filter { $0.identifier != Self.category }
59
+ all.insert(category)
60
+ center.setNotificationCategories(all)
61
+ }
62
+ }
63
+
64
+ // MARK: - NotificationDelegate (expo-notifications)
65
+
66
+ func didReceive(_ response: UNNotificationResponse, completionHandler: @escaping () -> Void) -> Bool {
67
+ let content = response.notification.request.content
68
+ guard content.categoryIdentifier == Self.category,
69
+ let grant = content.userInfo["reply_grant"] as? String, !grant.isEmpty else { return false }
70
+ let conversationId = content.userInfo["conversation_id"] as? String
71
+
72
+ switch response.actionIdentifier {
73
+ case Self.replyAction:
74
+ let text = (response as? UNTextInputNotificationResponse)?.userText
75
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
76
+ guard !text.isEmpty else { return true }
77
+ post(path: "/v1/notifications/reply", grant: grant,
78
+ body: ["body": text, "id": UUID().uuidString.lowercased()]) { ok in
79
+ if ok, let conversationId = conversationId { Self.clear(conversationId: conversationId) }
80
+ }
81
+ return true
82
+ case Self.markReadAction:
83
+ if let conversationId = conversationId { Self.clear(conversationId: conversationId) }
84
+ post(path: "/v1/notifications/read", grant: grant, body: [:]) { _ in }
85
+ return true
86
+ default:
87
+ // A plain tap opens the app; the host routes it to the conversation.
88
+ return false
89
+ }
90
+ }
91
+
92
+ /// A background push: the conversation was read on another device.
93
+ func didReceive(_ userInfo: [AnyHashable: Any],
94
+ completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Bool {
95
+ guard userInfo["type"] as? String == "message_read",
96
+ let conversationId = userInfo["conversation_id"] as? String else { return false }
97
+ Self.clear(conversationId: conversationId)
98
+ if let unread = (userInfo["unread_total"] as? NSNumber)?.intValue ?? Int(userInfo["unread_total"] as? String ?? "") {
99
+ Self.setBadge(unread)
100
+ }
101
+ completionHandler(.newData)
102
+ return true
103
+ }
104
+
105
+ // MARK: - helpers
106
+
107
+ /// Remove every delivered notification of one conversation.
108
+ static func clear(conversationId: String) {
109
+ let center = UNUserNotificationCenter.current()
110
+ center.getDeliveredNotifications { delivered in
111
+ let ids = delivered
112
+ .filter { $0.request.content.threadIdentifier == conversationId ||
113
+ ($0.request.content.userInfo["conversation_id"] as? String) == conversationId }
114
+ .map { $0.request.identifier }
115
+ if !ids.isEmpty { center.removeDeliveredNotifications(withIdentifiers: ids) }
116
+ }
117
+ }
118
+
119
+ static func setBadge(_ count: Int) {
120
+ if #available(iOS 16.0, *) {
121
+ UNUserNotificationCenter.current().setBadgeCount(max(count, 0))
122
+ } else {
123
+ DispatchQueue.main.async { UIApplication.shared.applicationIconBadgeNumber = max(count, 0) }
124
+ }
125
+ }
126
+
127
+ /// A grant-authorized POST that survives the app being suspended: the
128
+ /// action may have launched the app in the background just for this.
129
+ private func post(path: String, grant: String, body: [String: Any], done: @escaping (Bool) -> Void) {
130
+ guard let base = CallCore.config?.apiBaseUrl, let url = URL(string: base + path) else {
131
+ done(false)
132
+ return
133
+ }
134
+ var request = URLRequest(url: url)
135
+ request.httpMethod = "POST"
136
+ request.setValue("Bearer \(grant)", forHTTPHeaderField: "Authorization")
137
+ request.setValue("application/json", forHTTPHeaderField: "Content-Type")
138
+ request.httpBody = try? JSONSerialization.data(withJSONObject: body)
139
+ request.timeoutInterval = 20
140
+
141
+ var task: UIBackgroundTaskIdentifier = .invalid
142
+ let finish: (Bool) -> Void = { ok in
143
+ done(ok)
144
+ DispatchQueue.main.async {
145
+ if task != .invalid { UIApplication.shared.endBackgroundTask(task) }
146
+ task = .invalid
147
+ }
148
+ }
149
+ DispatchQueue.main.async {
150
+ task = UIApplication.shared.beginBackgroundTask(withName: "poolse-notification-action") {
151
+ if task != .invalid { UIApplication.shared.endBackgroundTask(task) }
152
+ task = .invalid
153
+ }
154
+ URLSession.shared.dataTask(with: request) { _, response, error in
155
+ let status = (response as? HTTPURLResponse)?.statusCode ?? 0
156
+ if error != nil || !(200..<300).contains(status) {
157
+ pcTrace("notification action \(path) failed status=\(status) error=\(String(describing: error))")
158
+ }
159
+ finish(error == nil && (200..<300).contains(status))
160
+ }.resume()
161
+ }
162
+ }
163
+ }
@@ -0,0 +1,61 @@
1
+ import AVFoundation
2
+ import Foundation
3
+
4
+ /// Outgoing ringback. The incoming ringtone is CallKit's own; the caller's
5
+ /// "ring ring" is a host-bundled tone (configure options.ringback, looked
6
+ /// up in the main bundle as mp3/caf/wav), else silence. Played inside the
7
+ /// CallKit-activated session, so it follows the call route (earpiece).
8
+ final class Ringback {
9
+ private var player: AVAudioPlayer?
10
+ private var wanted = false
11
+ var resourceName: () -> String?
12
+
13
+ init(resourceName: @escaping () -> String?) {
14
+ self.resourceName = resourceName
15
+ }
16
+
17
+ func start() {
18
+ wanted = true
19
+ play()
20
+ }
21
+
22
+ func stop() {
23
+ wanted = false
24
+ player?.stop()
25
+ player = nil
26
+ }
27
+
28
+ /// The session just became active: a ringback asked for earlier starts now.
29
+ func sessionActivated() {
30
+ if wanted && player?.isPlaying != true { play() }
31
+ }
32
+
33
+ private func play() {
34
+ guard let url = Ringback.url(for: resourceName()) else { return }
35
+ do {
36
+ if player == nil {
37
+ let p = try AVAudioPlayer(contentsOf: url)
38
+ p.numberOfLoops = -1
39
+ p.volume = 0.6
40
+ p.prepareToPlay()
41
+ player = p
42
+ }
43
+ player?.play()
44
+ } catch {
45
+ NSLog("[PoolseCalls] ringback failed: %@", "\(error)")
46
+ }
47
+ }
48
+
49
+ static func url(for name: String?) -> URL? {
50
+ guard let name = name, !name.isEmpty else { return nil }
51
+ let ns = name as NSString
52
+ if !ns.pathExtension.isEmpty,
53
+ let u = Bundle.main.url(forResource: ns.deletingPathExtension, withExtension: ns.pathExtension) {
54
+ return u
55
+ }
56
+ for ext in ["mp3", "caf", "wav", "m4a"] {
57
+ if let u = Bundle.main.url(forResource: name, withExtension: ext) { return u }
58
+ }
59
+ return nil
60
+ }
61
+ }
@@ -0,0 +1,174 @@
1
+ import CallKit
2
+ import Foundation
3
+ import PushKit
4
+ import UIKit
5
+
6
+ /// Native PushKit intake — the iOS twin of CallMessagingService. The
7
+ /// registry is created at launch (PoolseCallsAppDelegateSubscriber →
8
+ /// `PoolseCallsSetup.registerVoipEarly()`), long before JS, so a VoIP push that
9
+ /// wakes a killed app is reported to CallKit natively within PushKit's
10
+ /// budget.
11
+ ///
12
+ /// Contract with iOS: EVERY VoIP push reports a call to CallKit
13
+ /// synchronously, before `completion()` — stale, duplicate, control or
14
+ /// unparseable ones included (reported, then ended `.failed`). Breaking
15
+ /// it gets the app killed and, repeated, VoIP delivery revoked.
16
+ final class VoipPush: NSObject, PKPushRegistryDelegate {
17
+ static let shared = VoipPush()
18
+
19
+ private var registry: PKPushRegistry?
20
+ private let lock = NSLock()
21
+ private var _token: String?
22
+
23
+ /// The current VoIP token (hex), readable from any thread.
24
+ var token: String? {
25
+ lock.lock(); defer { lock.unlock() }
26
+ return _token
27
+ }
28
+
29
+ /// The bridge's token subscriber (process-level, like CallCore.listener).
30
+ static var tokenListener: ((String) -> Void)?
31
+
32
+ /// Idempotent. Main thread.
33
+ func register() {
34
+ guard registry == nil else { return }
35
+ _ = CallKitController.shared // the provider must exist before any push
36
+ let r = PKPushRegistry(queue: .main)
37
+ r.delegate = self
38
+ r.desiredPushTypes = [.voIP]
39
+ registry = r
40
+ if let data = r.pushToken(for: .voIP) { setToken(data) }
41
+ }
42
+
43
+ private func setToken(_ data: Data) {
44
+ let hex = data.map { String(format: "%02x", $0) }.joined()
45
+ lock.lock(); _token = hex; lock.unlock()
46
+ VoipPush.tokenListener?(hex)
47
+ }
48
+
49
+ // MARK: - PKPushRegistryDelegate
50
+
51
+ func pushRegistry(_ registry: PKPushRegistry, didUpdate pushCredentials: PKPushCredentials, for type: PKPushType) {
52
+ guard type == .voIP else { return }
53
+ setToken(pushCredentials.token)
54
+ }
55
+
56
+ func pushRegistry(_ registry: PKPushRegistry, didInvalidatePushTokenFor type: PKPushType) {
57
+ guard type == .voIP else { return }
58
+ lock.lock(); _token = nil; lock.unlock()
59
+ }
60
+
61
+ func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload,
62
+ for type: PKPushType, completion: @escaping () -> Void) {
63
+ pcTrace("VoIP push received appState=\(UIApplication.shared.applicationState.rawValue)")
64
+ if type == .voIP { handle(payload.dictionaryPayload) }
65
+ completion()
66
+ }
67
+
68
+ // MARK: - handling
69
+
70
+ private func handle(_ raw: [AnyHashable: Any]) {
71
+ let ck = CallKitController.shared
72
+ let p = VoipPayload(raw)
73
+ let core = CallCore.getOrNull()
74
+
75
+ switch p.event {
76
+ case "ring_ended", "finished":
77
+ // A control push on the VoIP channel still has to report a call.
78
+ ck.reportAndFail(callId: p.callId, title: p.title)
79
+ guard let core = core, let callId = p.callId else { return }
80
+ if p.event == "ring_ended" { core.onRingEnded(callId: callId, reason: p.reason ?? "finished") }
81
+ else { core.onCallFinished(callId: callId, reason: p.reason) }
82
+ default:
83
+ guard let ring = p.ringContext() else {
84
+ ck.reportAndFail(callId: p.callId, title: p.title)
85
+ return
86
+ }
87
+ guard let core = core, core.isRingLive(ring) else {
88
+ ck.reportAndFail(callId: ring.callId, title: p.title)
89
+ return
90
+ }
91
+ ck.reportIncoming(ring: ring)
92
+ core.onRing(ring)
93
+ // A ring the machine did not take (busy, superseded) must not stay
94
+ // on the CallKit screen: reconcile once the ring is processed.
95
+ core.reconcileCallKitSoon()
96
+ }
97
+ }
98
+ }
99
+
100
+ /// Lenient VoIP payload reader: top-level keys, or nested under `data` /
101
+ /// `payload` / `call`; strings, numbers or bools for any field.
102
+ struct VoipPayload {
103
+ private let fields: [String: Any]
104
+
105
+ init(_ raw: [AnyHashable: Any]) {
106
+ var out: [String: Any] = [:]
107
+ for nest in ["data", "payload", "call"] {
108
+ if let inner = raw[nest] as? [AnyHashable: Any] {
109
+ for (k, v) in inner { if let k = k as? String { out[k] = v } }
110
+ } else if let s = raw[nest] as? String, let d = s.data(using: .utf8),
111
+ let inner = (try? JSONSerialization.jsonObject(with: d)) as? [String: Any] {
112
+ for (k, v) in inner { out[k] = v }
113
+ }
114
+ }
115
+ for (k, v) in raw { if let k = k as? String, !(v is [AnyHashable: Any]) { out[k] = v } }
116
+ fields = out
117
+ }
118
+
119
+ func string(_ key: String) -> String? {
120
+ switch fields[key] {
121
+ case let s as String: return s.isEmpty ? nil : s
122
+ case let n as NSNumber: return n.stringValue
123
+ default: return nil
124
+ }
125
+ }
126
+
127
+ func int64(_ key: String) -> Int64? {
128
+ switch fields[key] {
129
+ case let n as NSNumber: return n.int64Value
130
+ case let s as String: return Int64(s) ?? Double(s).map { Int64($0) }
131
+ default: return nil
132
+ }
133
+ }
134
+
135
+ func bool(_ key: String) -> Bool? {
136
+ switch fields[key] {
137
+ case let n as NSNumber: return n.boolValue
138
+ case let s as String: return ["1", "true", "yes"].contains(s.lowercased())
139
+ default: return nil
140
+ }
141
+ }
142
+
143
+ var callId: String? { string("call_id") }
144
+ var event: String? { string("event") }
145
+ var reason: String? { string("reason") }
146
+ var title: String? { string("conversation_name") ?? string("caller_name") }
147
+
148
+ var media: String {
149
+ if let m = string("media")?.lowercased(), m == "video" || m == "audio" { return m }
150
+ return bool("has_video") == true ? "video" : "audio"
151
+ }
152
+
153
+ /// Epoch ms; a seconds value (< 1e12) is scaled. Missing: sent_at (or
154
+ /// now) + 60 s — the server's ring_ended(timeout) is the real cut-off.
155
+ private var deadlineMs: Int64 {
156
+ func ms(_ v: Int64) -> Int64 { v < 1_000_000_000_000 ? v * 1000 : v }
157
+ if let d = int64("ring_deadline"), d > 0 { return ms(d) }
158
+ let base = int64("sent_at").map(ms) ?? Int64(Date().timeIntervalSince1970 * 1000)
159
+ return base + 60_000
160
+ }
161
+
162
+ func ringContext() -> RingContext? {
163
+ guard let callId = callId, let conversationId = string("conversation_id"), let grant = string("grant") else { return nil }
164
+ return RingContext(
165
+ callId: callId,
166
+ conversationId: conversationId,
167
+ conversationName: string("conversation_name"),
168
+ callerName: string("caller_name"),
169
+ media: media,
170
+ grant: grant,
171
+ ringDeadlineEpochMs: deadlineMs
172
+ )
173
+ }
174
+ }
@@ -0,0 +1,68 @@
1
+ require 'json'
2
+
3
+ package = JSON.parse(File.read(File.join(__dir__, '..', 'package.json')))
4
+
5
+ # LiveKit's Swift SDK (and its LiveKitUniFFI / collections dependencies)
6
+ # is no longer published to CocoaPods trunk: it lives in LiveKit's own
7
+ # spec repo. A podspec cannot declare a source, and the host's Podfile is
8
+ # generated by `expo prebuild`, so instead of asking every host to add
9
+ #
10
+ # source 'https://cdn.cocoapods.org/'
11
+ # source 'https://github.com/livekit/podspecs.git'
12
+ #
13
+ # we append LiveKit's spec repo to the resolver's sources while this
14
+ # podspec is loaded (autolinking evaluates it inside `pod install`).
15
+ # Trunk stays first, so every other pod resolves exactly as before.
16
+ # Opt out with POOLSE_CALLS_NO_LIVEKIT_SOURCE=1 (then add the lines above).
17
+ LIVEKIT_SPECS_SOURCE = 'https://github.com/livekit/podspecs.git'
18
+ if ENV['POOLSE_CALLS_NO_LIVEKIT_SOURCE'] != '1' &&
19
+ defined?(Pod::Installer::Analyzer) &&
20
+ !Pod::Installer::Analyzer.method_defined?(:poolse_calls_original_sources)
21
+ Pod::Installer::Analyzer.class_eval do
22
+ alias_method :poolse_calls_original_sources, :sources
23
+ def sources
24
+ @poolse_calls_sources ||= begin
25
+ list = poolse_calls_original_sources
26
+ if list.any? { |s| s.respond_to?(:url) && s.url.to_s.sub(/\.git\z/, '') == LIVEKIT_SPECS_SOURCE.sub(/\.git\z/, '') }
27
+ list
28
+ else
29
+ list + [Pod::Config.instance.sources_manager.find_or_create_source_with_url(LIVEKIT_SPECS_SOURCE)]
30
+ end
31
+ end
32
+ end
33
+ end
34
+ end
35
+
36
+ Pod::Spec.new do |s|
37
+ s.name = 'PoolseCalls'
38
+ s.version = package['version']
39
+ s.summary = package['description']
40
+ s.description = package['description']
41
+ s.license = package['license']
42
+ s.author = 'Torsten Labs DOO'
43
+ s.homepage = 'https://poolse.dev'
44
+ s.platforms = { :ios => '15.1' }
45
+ s.swift_version = '5.9'
46
+ s.source = { :git => 'https://github.com/poolse/poolse-js-sdk.git' }
47
+ s.static_framework = true
48
+
49
+ s.dependency 'ExpoModulesCore'
50
+ # 2.15.1: LiveKitWebRTC 144.7559.10 (LKRTC-prefixed symbols in its own
51
+ # LiveKitWebRTC.framework) — links beside react-native-webrtc's
52
+ # WebRTC.framework without duplicate symbols. Not 2.16+: their vendored
53
+ # nanopb headers use <pb.h> angled includes that do not resolve when
54
+ # CocoaPods builds the pod as a static library (Expo's default).
55
+ s.dependency 'LiveKitClient', '= 2.15.1'
56
+ # Chat notifications plug into expo-notifications' notification-center
57
+ # delegate fan-out (MessageNotifications.swift) instead of replacing the
58
+ # delegate, which would break the app's own notifications.
59
+ s.dependency 'EXNotifications'
60
+
61
+ s.pod_target_xcconfig = {
62
+ 'DEFINES_MODULE' => 'YES',
63
+ 'SWIFT_COMPILATION_MODE' => 'wholemodule',
64
+ }
65
+
66
+ s.frameworks = 'CallKit', 'PushKit', 'AVFoundation', 'AVKit', 'UIKit', 'UserNotifications'
67
+ s.source_files = 'Core/**/*.swift', 'Platform/**/*.swift', 'Module/**/*.swift'
68
+ end
package/package.json CHANGED
@@ -1,6 +1,55 @@
1
1
  {
2
2
  "name": "@poolse/native",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "3.0.0",
4
+ "description": "Native call core for poolse \u2014 Kotlin/Swift calling engine with a thin React Native bridge. Ring, answer and carry audio with the app killed and the phone locked.",
5
+ "license": "SEE LICENSE IN LICENSE",
6
+ "type": "module",
7
+ "main": "./dist/index.cjs",
8
+ "module": "./dist/index.js",
9
+ "types": "./dist/index.d.ts",
10
+ "react-native": "./src/index.ts",
11
+ "exports": {
12
+ ".": {
13
+ "types": "./dist/index.d.ts",
14
+ "react-native": "./src/index.ts",
15
+ "import": "./dist/index.js",
16
+ "require": "./dist/index.cjs"
17
+ },
18
+ "./app.plugin.js": "./app.plugin.js",
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "dist",
24
+ "android/build.gradle",
25
+ "android/consumer-rules.pro",
26
+ "android/src",
27
+ "ios/Core",
28
+ "ios/Platform",
29
+ "ios/Module",
30
+ "ios/PoolseCalls.podspec",
31
+ "!ios/CoreTests",
32
+ "!**/.build",
33
+ "app.plugin.js",
34
+ "plugin",
35
+ "expo-module.config.json",
36
+ "README.md",
37
+ "LICENSE",
38
+ "CHANGELOG.md"
39
+ ],
40
+ "scripts": {
41
+ "build": "tsup",
42
+ "prepublishOnly": "tsup",
43
+ "typecheck": "tsc --noEmit"
44
+ },
45
+ "peerDependencies": {
46
+ "expo": "*",
47
+ "expo-notifications": "*",
48
+ "react-native": "*"
49
+ },
50
+ "devDependencies": {
51
+ "expo-modules-core": "*",
52
+ "tsup": "^8.3.5",
53
+ "typescript": "^5.6.0"
54
+ }
55
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * The config plugin for @poolse/native — everything the
3
+ * native core needs from the app's generated projects, in one entry:
4
+ *
5
+ * "plugins": [
6
+ * "expo-notifications",
7
+ * ["@poolse/native", { "ringback": "./assets/sounds/ringback.mp3" }]
8
+ * ]
9
+ *
10
+ * Options (all optional):
11
+ * ringback a sound file shipped in both bundles under its base
12
+ * name; pass that name to configure({ ringback }).
13
+ * Without one the caller hears silence while it rings.
14
+ * pictureInPicture Android: let the activity float during a video call
15
+ * (default true).
16
+ * lockscreen Android: show the app over the lock screen when it
17
+ * is opened for a call (default true).
18
+ *
19
+ * Always applied on Android: the LiveKit media adapter and expo-notifications
20
+ * as the FCM delegate for pushes that are not calls.
21
+ */
22
+ const { createRunOncePlugin } = require('expo/config-plugins');
23
+
24
+ const withCallDelegate = require('./withCallDelegate');
25
+ const withLockscreenCalls = require('./withLockscreenCalls');
26
+ const withNativeCallMedia = require('./withNativeCallMedia');
27
+ const withPictureInPicture = require('./withPictureInPicture');
28
+ const withRingback = require('./withRingback');
29
+
30
+ const pkg = require('../package.json');
31
+
32
+ function withPoolseCalls(config, options = {}) {
33
+ const { ringback, pictureInPicture = true, lockscreen = true } = options ?? {};
34
+ config = withNativeCallMedia(config);
35
+ config = withCallDelegate(config);
36
+ if (lockscreen) config = withLockscreenCalls(config);
37
+ if (pictureInPicture) config = withPictureInPicture(config);
38
+ if (ringback) config = withRingback(config, ringback);
39
+ return config;
40
+ }
41
+
42
+ module.exports = createRunOncePlugin(withPoolseCalls, pkg.name, pkg.version);
@@ -0,0 +1 @@
1
+ { "type": "commonjs" }
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Name expo-notifications as the FCM delegate for the
3
+ * native call core.
4
+ *
5
+ * `@poolse/native` ships its own FirebaseMessagingService
6
+ * (CallMessagingService) so a ring is handled in native code the instant
7
+ * it arrives — no headless-JS boot race. Android delivers every FCM
8
+ * message to exactly ONE service, so the call core becomes the app's
9
+ * primary intake and forwards everything that is NOT a call to the
10
+ * service named here. Without this meta-data, non-call pushes (chat
11
+ * notifications, token rotations) would be dropped on the floor.
12
+ *
13
+ * The value is expo-notifications' own FirebaseMessagingService, so
14
+ * everything the app already relies on keeps working unchanged.
15
+ */
16
+ const { withAndroidManifest } = require('expo/config-plugins');
17
+
18
+ const META_NAME = 'dev.poolse.callcore.delegate';
19
+ const DELEGATE = 'expo.modules.notifications.service.ExpoFirebaseMessagingService';
20
+
21
+ module.exports = function withCallDelegate(config) {
22
+ return withAndroidManifest(config, (cfg) => {
23
+ const app = cfg.modResults.manifest.application?.[0];
24
+ if (!app) throw new Error('withCallDelegate: no <application> in AndroidManifest');
25
+
26
+ app['meta-data'] = app['meta-data'] ?? [];
27
+ const existing = app['meta-data'].find((m) => m.$?.['android:name'] === META_NAME);
28
+ if (existing) {
29
+ existing.$['android:value'] = DELEGATE;
30
+ } else {
31
+ app['meta-data'].push({ $: { 'android:name': META_NAME, 'android:value': DELEGATE } });
32
+ }
33
+ return cfg;
34
+ });
35
+ };