@poolse/native 3.3.0 → 3.5.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.
@@ -9,7 +9,7 @@ public class PoolseCallsModule: Module {
9
9
  public func definition() -> ModuleDefinition {
10
10
  Name("PoolseCalls")
11
11
 
12
- Events("onCallState", "onVoipToken", "onPictureInPicture")
12
+ Events("onCallState", "onVoipToken", "onPictureInPicture", "onNotificationAction")
13
13
 
14
14
  // Normally done at launch by PoolseCallsAppDelegateSubscriber; this is
15
15
  // the backstop for a host whose AppDelegate does not forward to Expo.
@@ -31,6 +31,9 @@ public class PoolseCallsModule: Module {
31
31
  CallPictureInPicture.listener = { [weak self] active in
32
32
  self?.sendEvent("onPictureInPicture", ["active": active])
33
33
  }
34
+ MessageNotifications.actionListener = { [weak self] event in
35
+ self?.sendEvent("onNotificationAction", event)
36
+ }
34
37
  }
35
38
  }
36
39
 
@@ -39,6 +42,7 @@ public class PoolseCallsModule: Module {
39
42
  CallCore.listener = nil
40
43
  VoipPush.tokenListener = nil
41
44
  CallPictureInPicture.listener = nil
45
+ MessageNotifications.actionListener = nil
42
46
  }
43
47
  }
44
48
 
@@ -111,6 +115,15 @@ public class PoolseCallsModule: Module {
111
115
  if let conversationId = conversationId { MessageNotifications.clear(conversationId: conversationId) }
112
116
  }
113
117
 
118
+ // Reply / Mark as read done from a notification while JS was not
119
+ // listening (usually: the app was not running). Oldest first, once.
120
+ Function("takeNotificationActions") { () -> [[String: Any]] in
121
+ MessageNotifications.takePending()
122
+ }
123
+ Function("observeNotificationActions") { (on: Bool) in
124
+ DispatchQueue.main.async { MessageNotifications.actionsObserved = on }
125
+ }
126
+
114
127
  // Android-only: CallKit owns the lock screen on iOS.
115
128
  Function("setShowOnLockscreen") { (_: Bool) in }
116
129
 
@@ -61,6 +61,13 @@ final class CallCore {
61
61
  config?.apnsEnvironment ?? defaults.string(forKey: "apnsEnvironment") ?? readConfigFile()?.apnsEnvironment
62
62
  }
63
63
 
64
+ /// The configured API origin, restored from disk when the app was
65
+ /// launched without JS (a notification action, a push). Any thread.
66
+ static func persistedApiBaseUrl() -> String? {
67
+ restoreConfig()
68
+ return config?.apiBaseUrl
69
+ }
70
+
64
71
  private static func restoreConfig() {
65
72
  guard config == nil else { return }
66
73
  let restored: CallCoreConfig
@@ -16,7 +16,17 @@ import UserNotifications
16
16
  /// notification feature in the app.
17
17
  ///
18
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.
19
+ /// push carried (`reply_grant`, kept by iOS in the delivered notification's
20
+ /// userInfo — so no Notification Service Extension is needed to store it),
21
+ /// against the API origin `configure` persisted. They work from the lock
22
+ /// screen with the app killed: iOS launches the app in the background for
23
+ /// the action, and a background task keeps it alive for the request.
24
+ ///
25
+ /// Lock screen: Mark as read never asks for the passcode. Reply does not
26
+ /// either by default (the WhatsApp / Messages behaviour); an app sets
27
+ /// `PoolseMessageReplyRequiresUnlock` (the config plugin's
28
+ /// `messageReplyRequiresUnlock` option) to make Reply demand Face ID /
29
+ /// the passcode first.
20
30
  final class MessageNotifications: NSObject, NotificationDelegate {
21
31
  static let shared = MessageNotifications()
22
32
 
@@ -24,6 +34,16 @@ final class MessageNotifications: NSObject, NotificationDelegate {
24
34
  static let replyAction = "reply"
25
35
  static let markReadAction = "mark_read"
26
36
 
37
+ /// The bridge's subscriber for finished notification actions; main thread.
38
+ static var actionListener: (([String: Any]) -> Void)?
39
+ /// True while JS has an `onNotificationAction` subscriber; until then
40
+ /// results queue, even with the bridge observing other events. Main thread.
41
+ static var actionsObserved = false
42
+
43
+ private static let defaults = UserDefaults(suiteName: "dev.poolse.callcore") ?? .standard
44
+ private static let pendingKey = "notificationActions"
45
+ private static let maxPending = 50
46
+
27
47
  private var installed = false
28
48
 
29
49
  /// Main thread, at launch (PoolseCallsSetup.registerVoipEarly).
@@ -37,10 +57,11 @@ final class MessageNotifications: NSObject, NotificationDelegate {
37
57
  /// Add the message category beside whatever the app (or expo) declared:
38
58
  /// setNotificationCategories REPLACES the whole set.
39
59
  private func registerCategory() {
60
+ let requireUnlock = Bundle.main.object(forInfoDictionaryKey: "PoolseMessageReplyRequiresUnlock") as? Bool ?? false
40
61
  let reply = UNTextInputNotificationAction(
41
62
  identifier: Self.replyAction,
42
63
  title: "Reply",
43
- options: [],
64
+ options: requireUnlock ? [.authenticationRequired] : [],
44
65
  textInputButtonTitle: "Send",
45
66
  textInputPlaceholder: "Message"
46
67
  )
@@ -65,28 +86,77 @@ final class MessageNotifications: NSObject, NotificationDelegate {
65
86
 
66
87
  func didReceive(_ response: UNNotificationResponse, completionHandler: @escaping () -> Void) -> Bool {
67
88
  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) }
89
+ guard content.categoryIdentifier == Self.category else { return false }
90
+ let action = response.actionIdentifier
91
+ guard action == Self.replyAction || action == Self.markReadAction else {
92
+ // A plain tap opens the app; the host routes it to the conversation.
93
+ return false
94
+ }
95
+ let info = content.userInfo
96
+ guard let conversationId = (info["conversation_id"] as? String) ?? nilIfEmpty(content.threadIdentifier) else {
97
+ return true
98
+ }
99
+ let grant = (info["reply_grant"] as? String).flatMap(nilIfEmpty)
100
+ let payloadUnread = Self.int(info["unread_total"])
101
+
102
+ // Started before anything async: expo-notifications calls the
103
+ // completion handler as soon as we return, and iOS may suspend a
104
+ // background-launched app right after it.
105
+ let background = BackgroundTask(name: "poolse-notification-\(action)")
106
+
107
+ if action == Self.markReadAction {
108
+ // Optimistic: the notifications go now, the server catches up. A
109
+ // failed read is only logged — the message stays unread, nothing
110
+ // was lost.
111
+ Self.clear(conversationId: conversationId, fallbackUnread: payloadUnread, adjustBadge: true)
112
+ guard let grant = grant else {
113
+ Self.report(["action": "mark_read", "conversationId": conversationId, "ok": false, "error": "no_grant"])
114
+ background.end()
115
+ return true
116
+ }
117
+ send(path: "/v1/notification-actions/read", grant: grant, body: [:], background: background) { result in
118
+ Self.report(result.event(action: "mark_read", conversationId: conversationId))
119
+ background.end()
80
120
  }
81
121
  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 }
122
+ }
123
+
124
+ // Reply.
125
+ let text = (response as? UNTextInputNotificationResponse)?.userText
126
+ .trimmingCharacters(in: .whitespacesAndNewlines) ?? ""
127
+ guard !text.isEmpty else {
128
+ background.end()
85
129
  return true
86
- default:
87
- // A plain tap opens the app; the host routes it to the conversation.
88
- return false
89
130
  }
131
+ // One id per reply, reused by every retry: the server answers a
132
+ // repeat with the original message (200), never a second one.
133
+ let clientId = UUID().uuidString.lowercased()
134
+ 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"])
138
+ background.end()
139
+ return true
140
+ }
141
+ send(path: "/v1/notification-actions/reply", grant: grant,
142
+ body: ["text": text, "id": clientId], background: background) { result in
143
+ var event = result.event(action: "reply", conversationId: conversationId)
144
+ event["text"] = text
145
+ event["clientId"] = clientId
146
+ if result.ok {
147
+ event["messageId"] = (result.json?["id"] as? String) ?? clientId
148
+ // Replying marked the conversation read on the server.
149
+ Self.clear(conversationId: conversationId, fallbackUnread: payloadUnread, adjustBadge: true)
150
+ Self.report(event)
151
+ background.end()
152
+ } else {
153
+ Self.postFailure(conversationId: conversationId, text: text, reason: result.reason, userInfo: info)
154
+ Self.report(event)
155
+ // Give the failure notification a moment to be scheduled.
156
+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) { background.end() }
157
+ }
158
+ }
159
+ return true
90
160
  }
91
161
 
92
162
  /// A background push: the conversation was read on another device.
@@ -94,8 +164,8 @@ final class MessageNotifications: NSObject, NotificationDelegate {
94
164
  completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Bool {
95
165
  guard userInfo["type"] as? String == "message_read",
96
166
  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 ?? "") {
167
+ Self.clear(conversationId: conversationId, fallbackUnread: nil, adjustBadge: false)
168
+ if let unread = Self.int(userInfo["unread_total"]) {
99
169
  Self.setBadge(unread)
100
170
  }
101
171
  completionHandler(.newData)
@@ -104,15 +174,27 @@ final class MessageNotifications: NSObject, NotificationDelegate {
104
174
 
105
175
  // MARK: - helpers
106
176
 
107
- /// Remove every delivered notification of one conversation.
108
- static func clear(conversationId: String) {
177
+ /// Remove every delivered notification of one conversation. With
178
+ /// `adjustBadge` (a read done here, whose exact count the server only
179
+ /// sends in its read-sync push) the badge becomes the newest delivered
180
+ /// message's `unread_total` less this conversation's notifications — the
181
+ /// 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) {
109
183
  let center = UNUserNotificationCenter.current()
110
184
  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 }
185
+ let mine = delivered.filter {
186
+ $0.request.content.threadIdentifier == conversationId ||
187
+ ($0.request.content.userInfo["conversation_id"] as? String) == conversationId
188
+ }
189
+ let ids = mine.map { $0.request.identifier }
115
190
  if !ids.isEmpty { center.removeDeliveredNotifications(withIdentifiers: ids) }
191
+ guard adjustBadge else { return }
192
+ let newest = delivered
193
+ .filter { $0.request.content.categoryIdentifier == Self.category && Self.int($0.request.content.userInfo["unread_total"]) != nil }
194
+ .max { $0.date < $1.date }
195
+ guard let total = newest.flatMap({ Self.int($0.request.content.userInfo["unread_total"]) }) ?? fallbackUnread else { return }
196
+ let cleared = mine.filter { $0.request.content.userInfo["poolse_reply_failed"] == nil }.count
197
+ Self.setBadge(total - max(cleared, 1))
116
198
  }
117
199
  }
118
200
 
@@ -124,40 +206,181 @@ final class MessageNotifications: NSObject, NotificationDelegate {
124
206
  }
125
207
  }
126
208
 
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)
209
+ /// "Couldn't send" — in the conversation's stack, with the same Reply
210
+ /// action (and the grant it came with) so the user can try again
211
+ /// right there, or tap to open the chat.
212
+ private static func postFailure(conversationId: String, text: String, reason: String, userInfo: [AnyHashable: Any]) {
213
+ let content = UNMutableNotificationContent()
214
+ content.title = "Couldn't send your reply"
215
+ content.body = "\u{201C}\(text)\u{201D} — \(reason)"
216
+ content.threadIdentifier = conversationId
217
+ content.sound = .default
218
+ var info: [String: Any] = [
219
+ "type": "message",
220
+ "conversation_id": conversationId,
221
+ "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
+ ]
225
+ if let grant = userInfo["reply_grant"] as? String, !grant.isEmpty {
226
+ info["reply_grant"] = grant
227
+ content.categoryIdentifier = Self.category
228
+ }
229
+ content.userInfo = info
230
+ let request = UNNotificationRequest(identifier: "poolse-reply-failed-\(conversationId)", content: content, trigger: nil)
231
+ UNUserNotificationCenter.current().add(request) { error in
232
+ if let error = error { pcTrace("reply failure notification refused: \(error)") }
233
+ }
234
+ }
235
+
236
+ // MARK: - JS events
237
+
238
+ /// Hand a finished action to JS — live when the bridge listens, else
239
+ /// queued (persisted) until the app opens and drains it.
240
+ static func report(_ event: [String: Any]) {
241
+ var event = event
242
+ event["at"] = Int(Date().timeIntervalSince1970 * 1000)
243
+ DispatchQueue.main.async {
244
+ if Self.actionsObserved, let listener = Self.actionListener {
245
+ listener(event)
246
+ return
247
+ }
248
+ var queue = Self.defaults.array(forKey: Self.pendingKey) as? [[String: Any]] ?? []
249
+ queue.append(event)
250
+ if queue.count > Self.maxPending { queue.removeFirst(queue.count - Self.maxPending) }
251
+ Self.defaults.set(queue, forKey: Self.pendingKey)
252
+ }
253
+ }
254
+
255
+ /// The queued actions, oldest first, removed. UserDefaults is thread-safe.
256
+ static func takePending() -> [[String: Any]] {
257
+ let queue = defaults.array(forKey: pendingKey) as? [[String: Any]] ?? []
258
+ defaults.removeObject(forKey: pendingKey)
259
+ return queue
260
+ }
261
+
262
+ // MARK: - HTTP
263
+
264
+ struct ActionResult {
265
+ var ok: Bool
266
+ var status: Int
267
+ var code: String?
268
+ var json: [String: Any]?
269
+
270
+ /// What the user reads in the "couldn't send" notification.
271
+ var reason: String {
272
+ switch (status, code) {
273
+ case (0, _): return "No connection. Try again."
274
+ case (401, "device_signed_out"): return "This phone is signed out. Open the app to sign in."
275
+ case (401, "user_blocked"): return "Your account is blocked."
276
+ case (401, _): return "The notification expired. Open the app to reply."
277
+ case (402, _): return "Your workspace is full this month."
278
+ case (403, _): return "You're no longer in this conversation."
279
+ case (404, _): return "This conversation is gone."
280
+ case (422, _): return "The message couldn't be sent."
281
+ case (429, _): return "Too many replies. Try again in a moment."
282
+ default: return "Something went wrong. Try again."
283
+ }
284
+ }
285
+
286
+ func event(action: String, conversationId: String) -> [String: Any] {
287
+ var e: [String: Any] = ["action": action, "conversationId": conversationId, "ok": ok]
288
+ if !ok {
289
+ e["error"] = code ?? (status == 0 ? "network" : "http_\(status)")
290
+ if status != 0 { e["status"] = status }
291
+ }
292
+ return e
293
+ }
294
+ }
295
+
296
+ private let session: URLSession = {
297
+ let config = URLSessionConfiguration.ephemeral
298
+ config.timeoutIntervalForRequest = 15
299
+ config.waitsForConnectivity = false
300
+ return URLSession(configuration: config)
301
+ }()
302
+
303
+ /// A grant-authorized POST, retried with the SAME body (so the same
304
+ /// reply id) on a network error, a 5xx or a 429 while the background
305
+ /// 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,
307
+ attempt: Int = 1, done: @escaping (ActionResult) -> Void) {
308
+ guard let base = CallCore.persistedApiBaseUrl(), let url = URL(string: base + path) else {
309
+ pcTrace("notification action \(path): never configured")
310
+ done(ActionResult(ok: false, status: 0, code: "not_configured", json: nil))
132
311
  return
133
312
  }
313
+ var payload = body
314
+ payload["token"] = grant
134
315
  var request = URLRequest(url: url)
135
316
  request.httpMethod = "POST"
136
317
  request.setValue("Bearer \(grant)", forHTTPHeaderField: "Authorization")
137
318
  request.setValue("application/json", forHTTPHeaderField: "Content-Type")
138
- request.httpBody = try? JSONSerialization.data(withJSONObject: body)
139
- request.timeoutInterval = 20
319
+ request.setValue("application/json", forHTTPHeaderField: "Accept")
320
+ request.httpBody = try? JSONSerialization.data(withJSONObject: payload)
140
321
 
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
322
+ session.dataTask(with: request) { [weak self] data, response, error in
323
+ let http = response as? HTTPURLResponse
324
+ let status = error == nil ? (http?.statusCode ?? 0) : 0
325
+ let json = data.flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]
326
+ let code = (json?["error"] as? [String: Any])?["code"] as? String
327
+ let result = ActionResult(ok: (200..<300).contains(status), status: status, code: code, json: json)
328
+ if result.ok {
329
+ done(result)
330
+ return
147
331
  }
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))")
332
+ pcTrace("notification action \(path) failed status=\(status) code=\(code ?? "-") error=\(String(describing: error))")
333
+
334
+ let retryable = status == 0 || status == 429 || status >= 500
335
+ var delay = attempt == 1 ? 1.0 : 3.0
336
+ if status == 429, let s = http?.value(forHTTPHeaderField: "Retry-After").flatMap(Double.init) { delay = s }
337
+ DispatchQueue.main.async {
338
+ guard let self = self, retryable, attempt < 3,
339
+ background.remaining > delay + 16 else {
340
+ done(result)
341
+ return
342
+ }
343
+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
344
+ self.send(path: path, grant: grant, body: body, background: background, attempt: attempt + 1, done: done)
158
345
  }
159
- finish(error == nil && (200..<300).contains(status))
160
- }.resume()
346
+ }
347
+ }.resume()
348
+ }
349
+
350
+ static func int(_ value: Any?) -> Int? {
351
+ if let n = value as? NSNumber { return n.intValue }
352
+ if let s = value as? String { return Int(s) }
353
+ return nil
354
+ }
355
+ }
356
+
357
+ private func nilIfEmpty(_ s: String) -> String? { s.isEmpty ? nil : s }
358
+
359
+ /// UIApplication's background task, begun at once (on main) and ended
360
+ /// exactly once — by `end()` or by iOS's expiry.
361
+ final class BackgroundTask {
362
+ private var id: UIBackgroundTaskIdentifier = .invalid
363
+
364
+ init(name: String) {
365
+ let begin = {
366
+ self.id = UIApplication.shared.beginBackgroundTask(withName: name) { [weak self] in self?.endNow() }
161
367
  }
368
+ if Thread.isMainThread { begin() } else { DispatchQueue.main.sync(execute: begin) }
369
+ }
370
+
371
+ /// Seconds iOS still grants; generous while the app is in the foreground. Main thread.
372
+ var remaining: TimeInterval {
373
+ let r = UIApplication.shared.backgroundTimeRemaining
374
+ return r.isFinite ? r : 60
375
+ }
376
+
377
+ func end() {
378
+ if Thread.isMainThread { endNow() } else { DispatchQueue.main.async { self.endNow() } }
379
+ }
380
+
381
+ private func endNow() {
382
+ guard id != .invalid else { return }
383
+ UIApplication.shared.endBackgroundTask(id)
384
+ id = .invalid
162
385
  }
163
386
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@poolse/native",
3
- "version": "3.3.0",
3
+ "version": "3.5.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",
package/plugin/index.js CHANGED
@@ -19,6 +19,10 @@
19
19
  * the screen needs (default false). `true`, or
20
20
  * `{ appGroup }` to use your own app group instead of
21
21
  * `group.<bundle id>`. Android needs nothing extra.
22
+ * messageReplyRequiresUnlock
23
+ * both: a chat notification's Reply asks for the
24
+ * passcode / biometrics first (default false: Reply
25
+ * works straight from the lock screen).
22
26
  *
23
27
  * Always applied on Android: the LiveKit media adapter and expo-notifications
24
28
  * as the FCM delegate for pushes that are not calls.
@@ -27,6 +31,7 @@ const { createRunOncePlugin } = require('expo/config-plugins');
27
31
 
28
32
  const withCallDelegate = require('./withCallDelegate');
29
33
  const withLockscreenCalls = require('./withLockscreenCalls');
34
+ const withMessageReplyUnlock = require('./withMessageReplyUnlock');
30
35
  const withNativeCallMedia = require('./withNativeCallMedia');
31
36
  const withPictureInPicture = require('./withPictureInPicture');
32
37
  const withRingback = require('./withRingback');
@@ -40,12 +45,14 @@ function withPoolseCalls(config, options = {}) {
40
45
  pictureInPicture = true,
41
46
  lockscreen = true,
42
47
  screenShare = false,
48
+ messageReplyRequiresUnlock = false,
43
49
  } = options ?? {};
44
50
  config = withNativeCallMedia(config);
45
51
  config = withCallDelegate(config);
46
52
  if (lockscreen) config = withLockscreenCalls(config);
47
53
  if (pictureInPicture) config = withPictureInPicture(config);
48
54
  if (ringback) config = withRingback(config, ringback);
55
+ config = withMessageReplyUnlock(config, messageReplyRequiresUnlock);
49
56
  if (screenShare) config = withScreenShare(config, screenShare === true ? {} : screenShare);
50
57
  return config;
51
58
  }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * `messageReplyRequiresUnlock`: make a chat notification's Reply ask for
3
+ * the passcode / Face ID / fingerprint before it sends, so nobody can
4
+ * answer as the user from a locked phone. Off by default — replying from
5
+ * the lock screen is what WhatsApp and Messages do. Mark as read never
6
+ * asks.
7
+ *
8
+ * iOS: `PoolseMessageReplyRequiresUnlock` in Info.plist — the core then
9
+ * registers the Reply action with `.authenticationRequired`.
10
+ * Android: application meta-data `dev.poolse.messages.reply_requires_unlock`
11
+ * — the core marks the Reply action `setAuthenticationRequired` (Android
12
+ * 12+; older versions ignore it).
13
+ */
14
+ const { withAndroidManifest, withInfoPlist } = require('expo/config-plugins');
15
+
16
+ const PLIST_KEY = 'PoolseMessageReplyRequiresUnlock';
17
+ const META_NAME = 'dev.poolse.messages.reply_requires_unlock';
18
+
19
+ module.exports = function withMessageReplyUnlock(config, required) {
20
+ const on = required === true;
21
+ config = withInfoPlist(config, (cfg) => {
22
+ if (on) cfg.modResults[PLIST_KEY] = true;
23
+ else delete cfg.modResults[PLIST_KEY];
24
+ return cfg;
25
+ });
26
+ return withAndroidManifest(config, (cfg) => {
27
+ const app = cfg.modResults.manifest.application?.[0];
28
+ if (!app) throw new Error('withMessageReplyUnlock: no <application> in AndroidManifest');
29
+ app['meta-data'] = (app['meta-data'] ?? []).filter((m) => m.$?.['android:name'] !== META_NAME);
30
+ if (on) app['meta-data'].push({ $: { 'android:name': META_NAME, 'android:value': 'true' } });
31
+ return cfg;
32
+ });
33
+ };
package/src/index.ts CHANGED
@@ -164,6 +164,38 @@ export interface CallAction {
164
164
  media: 'audio' | 'video';
165
165
  }
166
166
 
167
+ /**
168
+ * A Reply or Mark as read the user did from a chat notification, after
169
+ * the native core sent it (or gave up). The server has already posted
170
+ * the reply and marked the conversation read; use this to refresh what
171
+ * the app shows (insert the message, drop the unread count) without
172
+ * waiting for the socket, or to tell the user a reply did not go out.
173
+ */
174
+ export interface NotificationActionResult {
175
+ action: 'reply' | 'mark_read';
176
+ conversationId: string;
177
+ /** Whether the server accepted it. */
178
+ ok: boolean;
179
+ /** Reply only: what the user typed. */
180
+ text?: string;
181
+ /** Reply only: the idempotency id sent with it — the message's id once posted. */
182
+ clientId?: string;
183
+ /** Reply, `ok` only: the posted message's id (equals `clientId`). */
184
+ messageId?: string;
185
+ /**
186
+ * When not `ok`: the server's error code (`unauthorized`,
187
+ * `device_signed_out`, `user_blocked`, `forbidden`, `not_found`,
188
+ * `mau_cap_exceeded`, `validation_failed`, `rate_limited`), or
189
+ * `network`, `no_grant` (the push carried no reply grant),
190
+ * `not_configured` (never `configure`d), `http_<status>`.
191
+ */
192
+ error?: string;
193
+ /** The HTTP status when the server answered with an error. */
194
+ status?: number;
195
+ /** When it finished, epoch ms. */
196
+ at: number;
197
+ }
198
+
167
199
  type NativeSnapshot = { snapshot: Snapshot | null };
168
200
 
169
201
  interface PoolseCallsNative {
@@ -196,9 +228,15 @@ interface PoolseCallsNative {
196
228
  getVoipToken?(): VoipToken | null;
197
229
  takeCallAction?(): CallAction | null;
198
230
  setActiveConversation?(conversationId: string | null): void;
231
+ takeNotificationActions?(): NotificationActionResult[];
232
+ observeNotificationActions?(on: boolean): void;
199
233
  addListener(event: 'onCallState', cb: (payload: NativeSnapshot) => void): { remove(): void };
200
234
  addListener(event: 'onVoipToken', cb: (payload: VoipToken) => void): { remove(): void };
201
235
  addListener(event: 'onCallAction', cb: (payload: CallAction) => void): { remove(): void };
236
+ addListener(
237
+ event: 'onNotificationAction',
238
+ cb: (payload: NotificationActionResult) => void,
239
+ ): { remove(): void };
202
240
  addListener(
203
241
  event: 'onPictureInPicture',
204
242
  cb: (payload: { active: boolean }) => void,
@@ -495,6 +533,45 @@ export function conversationOfNotification(
495
533
  return typeof data['conversation_id'] === 'string' ? data['conversation_id'] : null;
496
534
  }
497
535
 
536
+ /**
537
+ * Reply and Mark as read from a chat notification are handled natively —
538
+ * from the lock screen, with the app closed — using the grant the push
539
+ * carried and the API origin given to `configure` (which persists it).
540
+ * This fires once each finishes while the app is running. Read the ones
541
+ * that finished while it was not with `takeNotificationActions` on mount.
542
+ */
543
+ export function onNotificationAction(cb: (result: NotificationActionResult) => void): Unsubscribe {
544
+ if (!native?.takeNotificationActions) return () => undefined;
545
+ const sub = native.addListener('onNotificationAction', cb);
546
+ if (actionObservers++ === 0) native.observeNotificationActions?.(true);
547
+ let removed = false;
548
+ return () => {
549
+ if (removed) return;
550
+ removed = true;
551
+ sub.remove();
552
+ if (--actionObservers === 0) native?.observeNotificationActions?.(false);
553
+ };
554
+ }
555
+
556
+ // Native queues results until someone listens for them specifically.
557
+ let actionObservers = 0;
558
+
559
+ /** `onNotificationAction`, replies only. */
560
+ export function onNotificationReply(cb: (result: NotificationActionResult) => void): Unsubscribe {
561
+ return onNotificationAction((result) => {
562
+ if (result.action === 'reply') cb(result);
563
+ });
564
+ }
565
+
566
+ /**
567
+ * The notification actions that finished while no `onNotificationAction`
568
+ * listener was attached (usually: the app was not running), oldest
569
+ * first, each returned once. Up to the last 50 are kept.
570
+ */
571
+ export function takeNotificationActions(): NotificationActionResult[] {
572
+ return native?.takeNotificationActions?.() ?? [];
573
+ }
574
+
498
575
  // ── VoIP push (iOS) ───────────────────────────────────────────────────
499
576
 
500
577
  /**