@poolse/native 0.0.0-stage → 3.1.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 +31 -0
  2. package/LICENSE +206 -0
  3. package/README.md +116 -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 +52 -3
  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,353 @@
1
+ package dev.poolse.callcore.android
2
+
3
+ import android.app.NotificationChannel
4
+ import android.app.NotificationManager
5
+ import android.app.PendingIntent
6
+ import android.content.BroadcastReceiver
7
+ import android.content.Context
8
+ import android.content.Intent
9
+ import android.os.Build
10
+ import android.util.Log
11
+ import androidx.core.app.NotificationCompat
12
+ import androidx.core.app.NotificationManagerCompat
13
+ import androidx.core.app.Person
14
+ import androidx.core.app.RemoteInput
15
+ import okhttp3.MediaType.Companion.toMediaType
16
+ import okhttp3.Request
17
+ import okhttp3.RequestBody.Companion.toRequestBody
18
+ import org.json.JSONArray
19
+ import org.json.JSONObject
20
+ import java.util.UUID
21
+
22
+ /**
23
+ * Chat notifications on Android (CALL_CONTRACT.md §5.5), WhatsApp-style.
24
+ *
25
+ * One notification per conversation, in MessagingStyle: each new message
26
+ * becomes a line in it ("Ana: on my way") rather than a new card, and a
27
+ * group summary collects every chat. Reply (inline text) and Mark as
28
+ * read run natively, authorized by the reply grant the push carried, so
29
+ * they work with the app killed and the phone locked.
30
+ *
31
+ * Android cannot read back the lines of a posted notification, so the
32
+ * last few lines per conversation are kept in a small preferences file
33
+ * and the notification is rebuilt from them on every message. They are
34
+ * dropped the moment the conversation is read, here or elsewhere.
35
+ */
36
+ object MessageNotifications {
37
+ const val CHANNEL_ID = "poolse_messages"
38
+ private const val GROUP_KEY = "dev.poolse.messages"
39
+ private const val SUMMARY_ID = 0x504F4F4C // "POOL"
40
+ private const val PREFS = "dev.poolse.messages"
41
+ private const val MAX_LINES = 7
42
+ internal const val KEY_REPLY = "poolse_reply_text"
43
+ internal const val ACTION_REPLY = "dev.poolse.callcore.message.REPLY"
44
+ internal const val ACTION_READ = "dev.poolse.callcore.message.READ"
45
+ internal const val EXTRA_CONVERSATION = "poolse_message_conversation"
46
+ private const val TAG = "PoolseMessages"
47
+
48
+ // A message notification that waited this long for the phone to come
49
+ // online is history.
50
+ private const val STALE_MS = 24 * 60 * 60 * 1000L
51
+
52
+ /**
53
+ * The conversation on screen in the app, set by the host. Its messages
54
+ * are not notified — the user is reading them.
55
+ */
56
+ @Volatile var activeConversationId: String? = null
57
+
58
+ /** A `type: "message", event: "new"` push. */
59
+ fun onNew(context: Context, data: Map<String, String>, smallIcon: Int) {
60
+ val conversationId = data["conversation_id"] ?: return
61
+ if (conversationId == activeConversationId) return
62
+ val sentAt = data["sent_at"]?.toLongOrNull() ?: System.currentTimeMillis()
63
+ if (System.currentTimeMillis() - sentAt > STALE_MS) return
64
+
65
+ val state = load(context, conversationId) ?: Conversation(conversationId)
66
+ state.title = data["conversation_name"]?.ifBlank { null } ?: state.title
67
+ state.group = data["group"] == "1"
68
+ state.hidden = data["private"] == "1"
69
+ data["reply_grant"]?.ifBlank { null }?.let { state.grant = it }
70
+ val messageId = data["message_id"]
71
+ if (messageId == null || state.lines.none { it.id == messageId }) {
72
+ state.lines += Line(
73
+ id = messageId,
74
+ sender = data["sender_name"]?.ifBlank { null } ?: "Someone",
75
+ senderKey = data["sender_user_id"],
76
+ text = data["text"] ?: "",
77
+ at = sentAt,
78
+ self = false,
79
+ )
80
+ while (state.lines.size > MAX_LINES) state.lines.removeAt(0)
81
+ }
82
+ save(context, state)
83
+ post(context, state, smallIcon, alert = true)
84
+ }
85
+
86
+ /** The conversation was read (here, or on another device): clear it. */
87
+ fun clear(context: Context, conversationId: String) {
88
+ prefs(context).edit().remove(key(conversationId)).apply()
89
+ runCatching { NotificationManagerCompat.from(context).cancel(notificationId(conversationId)) }
90
+ refreshSummary(context, CallCore.smallIcon(context))
91
+ }
92
+
93
+ /** The reply went through: show it as the user's line and stop the spinner. */
94
+ internal fun onReplied(context: Context, conversationId: String, text: String, ok: Boolean) {
95
+ val state = load(context, conversationId) ?: return
96
+ state.lines += Line(
97
+ id = null,
98
+ sender = "You",
99
+ senderKey = null,
100
+ text = if (ok) text else "Not sent: $text",
101
+ at = System.currentTimeMillis(),
102
+ self = true,
103
+ )
104
+ while (state.lines.size > MAX_LINES) state.lines.removeAt(0)
105
+ save(context, state)
106
+ post(context, state, CallCore.smallIcon(context), alert = false)
107
+ }
108
+
109
+ internal fun grantFor(context: Context, conversationId: String): String? =
110
+ load(context, conversationId)?.grant
111
+
112
+ // ── building ────────────────────────────────────────────────────────
113
+
114
+ private fun post(context: Context, state: Conversation, smallIcon: Int, alert: Boolean) {
115
+ ensureChannel(context)
116
+ val me = Person.Builder().setName("You").build()
117
+ val style = NotificationCompat.MessagingStyle(me)
118
+ .setGroupConversation(state.group)
119
+ if (state.group) style.conversationTitle = state.title
120
+ for (line in state.lines) {
121
+ val person = if (line.self) null else Person.Builder().setName(line.sender).setKey(line.senderKey).build()
122
+ style.addMessage(NotificationCompat.MessagingStyle.Message(line.text, line.at, person))
123
+ }
124
+
125
+ val id = notificationId(state.id)
126
+ val builder = NotificationCompat.Builder(context, CHANNEL_ID)
127
+ .setSmallIcon(smallIcon)
128
+ .setCategory(NotificationCompat.CATEGORY_MESSAGE)
129
+ .setPriority(NotificationCompat.PRIORITY_HIGH)
130
+ .setGroup(GROUP_KEY)
131
+ .setAutoCancel(true)
132
+ .setOnlyAlertOnce(!alert)
133
+ .setWhen(state.lines.lastOrNull()?.at ?: System.currentTimeMillis())
134
+ .setNumber(state.lines.count { !it.self })
135
+ if (state.hidden) {
136
+ // The tenant hides previews: nothing about who or what — the app's
137
+ // name and a count. The server never sent the text anyway.
138
+ val unread = state.lines.count { !it.self }
139
+ builder
140
+ .setContentTitle(context.applicationInfo.loadLabel(context.packageManager))
141
+ .setContentText(if (unread <= 1) "New message" else "$unread new messages")
142
+ } else {
143
+ builder.setStyle(style)
144
+ }
145
+ openIntent(context, state.id, id)?.let(builder::setContentIntent)
146
+
147
+ if (state.grant != null) {
148
+ val remoteInput = RemoteInput.Builder(KEY_REPLY).setLabel("Message").build()
149
+ val reply = NotificationCompat.Action.Builder(0, "Reply", actionIntent(context, ACTION_REPLY, state.id, id + 1, mutable = true))
150
+ .addRemoteInput(remoteInput)
151
+ .setAllowGeneratedReplies(true)
152
+ .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
153
+ .setShowsUserInterface(false)
154
+ .build()
155
+ val read = NotificationCompat.Action.Builder(0, "Mark as read", actionIntent(context, ACTION_READ, state.id, id + 2, mutable = false))
156
+ .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_MARK_AS_READ)
157
+ .setShowsUserInterface(false)
158
+ .build()
159
+ builder.addAction(reply).addAction(read)
160
+ }
161
+
162
+ try {
163
+ NotificationManagerCompat.from(context).notify(id, builder.build())
164
+ } catch (e: SecurityException) {
165
+ Log.w(TAG, "message notification refused (POST_NOTIFICATIONS?)", e)
166
+ return
167
+ }
168
+ refreshSummary(context, smallIcon)
169
+ }
170
+
171
+ /** The group's summary: "5 messages from 2 chats". Gone with the last chat. */
172
+ private fun refreshSummary(context: Context, smallIcon: Int) {
173
+ val all = prefs(context).all.keys.filter { it.startsWith("conv:") }
174
+ .mapNotNull { load(context, it.removePrefix("conv:")) }
175
+ val manager = NotificationManagerCompat.from(context)
176
+ if (all.isEmpty()) {
177
+ runCatching { manager.cancel(SUMMARY_ID) }
178
+ return
179
+ }
180
+ val messages = all.sumOf { c -> c.lines.count { !it.self } }
181
+ val text = if (all.size == 1) "$messages new messages" else "$messages messages from ${all.size} chats"
182
+ val summary = NotificationCompat.Builder(context, CHANNEL_ID)
183
+ .setSmallIcon(smallIcon)
184
+ .setContentTitle(text)
185
+ .setStyle(NotificationCompat.InboxStyle().setSummaryText(text))
186
+ .setGroup(GROUP_KEY)
187
+ .setGroupSummary(true)
188
+ .setGroupAlertBehavior(NotificationCompat.GROUP_ALERT_CHILDREN)
189
+ .setAutoCancel(true)
190
+ .build()
191
+ runCatching { manager.notify(SUMMARY_ID, summary) }
192
+ }
193
+
194
+ private fun openIntent(context: Context, conversationId: String, requestCode: Int): PendingIntent? {
195
+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
196
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
197
+ .putExtra(MissedCallNotification.EXTRA_ACTION, MissedCallNotification.ACTION_OPEN)
198
+ .putExtra(MissedCallNotification.EXTRA_CONVERSATION_ID, conversationId)
199
+ return PendingIntent.getActivity(
200
+ context,
201
+ requestCode,
202
+ intent,
203
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
204
+ )
205
+ }
206
+
207
+ private fun actionIntent(context: Context, action: String, conversationId: String, requestCode: Int, mutable: Boolean): PendingIntent {
208
+ val intent = Intent(context, MessageActionReceiver::class.java)
209
+ .setAction(action)
210
+ .putExtra(EXTRA_CONVERSATION, conversationId)
211
+ // RemoteInput writes the typed text into the intent: it must be mutable.
212
+ val mutability = if (mutable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
213
+ PendingIntent.FLAG_MUTABLE
214
+ } else {
215
+ PendingIntent.FLAG_IMMUTABLE
216
+ }
217
+ return PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or mutability)
218
+ }
219
+
220
+ private fun ensureChannel(context: Context) {
221
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
222
+ val manager = context.getSystemService(NotificationManager::class.java)
223
+ if (manager.getNotificationChannel(CHANNEL_ID) != null) return
224
+ manager.createNotificationChannel(
225
+ NotificationChannel(CHANNEL_ID, "Messages", NotificationManager.IMPORTANCE_HIGH).apply {
226
+ lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE
227
+ },
228
+ )
229
+ }
230
+
231
+ private fun notificationId(conversationId: String) = ("msg:$conversationId").hashCode()
232
+
233
+ // ── storage ─────────────────────────────────────────────────────────
234
+
235
+ internal data class Line(
236
+ val id: String?,
237
+ val sender: String,
238
+ val senderKey: String?,
239
+ val text: String,
240
+ val at: Long,
241
+ val self: Boolean,
242
+ )
243
+
244
+ internal class Conversation(
245
+ val id: String,
246
+ var title: String? = null,
247
+ var group: Boolean = false,
248
+ var grant: String? = null,
249
+ val lines: MutableList<Line> = mutableListOf(),
250
+ var hidden: Boolean = false,
251
+ )
252
+
253
+ private fun prefs(context: Context) =
254
+ context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
255
+
256
+ private fun key(conversationId: String) = "conv:$conversationId"
257
+
258
+ private fun load(context: Context, conversationId: String): Conversation? {
259
+ val raw = prefs(context).getString(key(conversationId), null) ?: return null
260
+ return runCatching {
261
+ val o = JSONObject(raw)
262
+ val lines = o.optJSONArray("lines") ?: JSONArray()
263
+ Conversation(
264
+ id = conversationId,
265
+ title = o.optString("title").ifBlank { null },
266
+ group = o.optBoolean("group"),
267
+ grant = o.optString("grant").ifBlank { null },
268
+ hidden = o.optBoolean("hidden"),
269
+ lines = MutableList(lines.length()) { i ->
270
+ val l = lines.getJSONObject(i)
271
+ Line(
272
+ id = l.optString("id").ifBlank { null },
273
+ sender = l.optString("sender"),
274
+ senderKey = l.optString("key").ifBlank { null },
275
+ text = l.optString("text"),
276
+ at = l.optLong("at"),
277
+ self = l.optBoolean("self"),
278
+ )
279
+ },
280
+ )
281
+ }.getOrNull()
282
+ }
283
+
284
+ private fun save(context: Context, c: Conversation) {
285
+ val lines = JSONArray()
286
+ for (l in c.lines) {
287
+ lines.put(
288
+ JSONObject()
289
+ .put("id", l.id ?: "")
290
+ .put("sender", l.sender)
291
+ .put("key", l.senderKey ?: "")
292
+ .put("text", l.text)
293
+ .put("at", l.at)
294
+ .put("self", l.self),
295
+ )
296
+ }
297
+ val o = JSONObject()
298
+ .put("title", c.title ?: "")
299
+ .put("group", c.group)
300
+ .put("grant", c.grant ?: "")
301
+ .put("hidden", c.hidden)
302
+ .put("lines", lines)
303
+ prefs(context).edit().putString(key(c.id), o.toString()).apply()
304
+ }
305
+ }
306
+
307
+ /**
308
+ * Reply / Mark as read, tapped on a message notification. Posts to the
309
+ * notification-action endpoints with the conversation's reply grant —
310
+ * no app, no session — on a background thread kept alive by goAsync().
311
+ */
312
+ class MessageActionReceiver : BroadcastReceiver() {
313
+ override fun onReceive(context: Context, intent: Intent) {
314
+ val conversationId = intent.getStringExtra(MessageNotifications.EXTRA_CONVERSATION) ?: return
315
+ val app = context.applicationContext
316
+ val grant = MessageNotifications.grantFor(app, conversationId)
317
+ val base = CallCore.apiBaseUrl(app)
318
+
319
+ when (intent.action) {
320
+ MessageNotifications.ACTION_REPLY -> {
321
+ val text = RemoteInput.getResultsFromIntent(intent)
322
+ ?.getCharSequence(MessageNotifications.KEY_REPLY)?.toString()?.trim().orEmpty()
323
+ if (text.isEmpty() || grant == null || base == null) return
324
+ val pending = goAsync()
325
+ Thread {
326
+ val body = JSONObject().put("body", text).put("id", UUID.randomUUID().toString())
327
+ val ok = post("$base/v1/notifications/reply", grant, body)
328
+ MessageNotifications.onReplied(app, conversationId, text, ok)
329
+ pending.finish()
330
+ }.start()
331
+ }
332
+ MessageNotifications.ACTION_READ -> {
333
+ // Optimistic: the notification goes now; the server catches up.
334
+ MessageNotifications.clear(app, conversationId)
335
+ if (grant == null || base == null) return
336
+ val pending = goAsync()
337
+ Thread {
338
+ post("$base/v1/notifications/read", grant, JSONObject())
339
+ pending.finish()
340
+ }.start()
341
+ }
342
+ }
343
+ }
344
+
345
+ private fun post(url: String, grant: String, body: JSONObject): Boolean = runCatching {
346
+ val request = Request.Builder()
347
+ .url(url)
348
+ .header("Authorization", "Bearer $grant")
349
+ .post(body.toString().toRequestBody("application/json".toMediaType()))
350
+ .build()
351
+ CallHttpClient.defaultClient().newCall(request).execute().use { it.isSuccessful }
352
+ }.onFailure { Log.w("PoolseMessages", "notification action failed", it) }.getOrDefault(false)
353
+ }
@@ -0,0 +1,103 @@
1
+ package dev.poolse.callcore.android
2
+
3
+ import android.app.NotificationChannel
4
+ import android.app.NotificationManager
5
+ import android.app.PendingIntent
6
+ import android.content.Context
7
+ import android.content.Intent
8
+ import android.os.Build
9
+ import android.util.Log
10
+ import androidx.core.app.NotificationCompat
11
+ import androidx.core.app.NotificationManagerCompat
12
+
13
+ /**
14
+ * "Jasir — Missed voice call [Call back]", posted natively from the
15
+ * missed-call push (`event: "missed"`) so it shows with the app closed.
16
+ *
17
+ * Both the tap and Call back open the app through its launch activity,
18
+ * carrying the action in extras ([EXTRA_ACTION] …). The bridge reads
19
+ * them — `takeCallAction()` on a cold start, `onCallAction` while
20
+ * running — and the host opens the conversation or places the call.
21
+ * Placing needs the user's session, which only the app has; that is
22
+ * why Call back does not dial from here.
23
+ */
24
+ object MissedCallNotification {
25
+ const val CHANNEL_ID = "poolse_missed_calls"
26
+ const val EXTRA_ACTION = "poolse_call_action"
27
+ const val EXTRA_CONVERSATION_ID = "poolse_call_action_conversation"
28
+ const val EXTRA_CALL_ID = "poolse_call_action_call"
29
+ const val EXTRA_MEDIA = "poolse_call_action_media"
30
+ const val ACTION_OPEN = "open"
31
+ const val ACTION_CALL_BACK = "call_back"
32
+ private const val TAG = "PoolseMissedCall"
33
+
34
+ // A missed call FCM held while the phone was off for days is history.
35
+ private const val STALE_MS = 24 * 60 * 60 * 1000L
36
+
37
+ fun show(context: Context, data: Map<String, String>, smallIcon: Int) {
38
+ val callId = data["call_id"] ?: return
39
+ val conversationId = data["conversation_id"] ?: return
40
+ val sentAt = data["sent_at"]?.toLongOrNull()
41
+ if (sentAt != null && System.currentTimeMillis() - sentAt > STALE_MS) return
42
+ val media = if (data["media"] == "video") "video" else "audio"
43
+ val title = data["title"]?.ifBlank { null }
44
+ ?: data["caller_name"]?.ifBlank { null }
45
+ ?: "Missed call"
46
+ val body = data["body"]?.ifBlank { null }
47
+ ?: if (media == "video") "Missed video call" else "Missed voice call"
48
+
49
+ ensureChannel(context)
50
+ val id = notificationId(callId)
51
+
52
+ fun launch(action: String, requestOffset: Int): PendingIntent? {
53
+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
54
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
55
+ .putExtra(EXTRA_ACTION, action)
56
+ .putExtra(EXTRA_CONVERSATION_ID, conversationId)
57
+ .putExtra(EXTRA_CALL_ID, callId)
58
+ .putExtra(EXTRA_MEDIA, media)
59
+ return PendingIntent.getActivity(
60
+ context,
61
+ id + requestOffset,
62
+ intent,
63
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
64
+ )
65
+ }
66
+
67
+ val builder = NotificationCompat.Builder(context, CHANNEL_ID)
68
+ .setSmallIcon(smallIcon)
69
+ .setContentTitle(title)
70
+ .setContentText(body)
71
+ .setCategory(NotificationCompat.CATEGORY_MISSED_CALL)
72
+ .setPriority(NotificationCompat.PRIORITY_DEFAULT)
73
+ .setAutoCancel(true)
74
+ .setWhen(sentAt ?: System.currentTimeMillis())
75
+ .setShowWhen(true)
76
+ launch(ACTION_OPEN, 0)?.let(builder::setContentIntent)
77
+ launch(ACTION_CALL_BACK, 1)?.let { builder.addAction(0, "Call back", it) }
78
+
79
+ try {
80
+ NotificationManagerCompat.from(context).notify(id, builder.build())
81
+ } catch (e: SecurityException) {
82
+ Log.w(TAG, "missed-call notification refused (POST_NOTIFICATIONS?)", e)
83
+ }
84
+ }
85
+
86
+ /** Clear it once the user acted on it from the app (its buttons do not auto-cancel). */
87
+ fun cancel(context: Context, callId: String) {
88
+ runCatching { NotificationManagerCompat.from(context).cancel(notificationId(callId)) }
89
+ }
90
+
91
+ private fun notificationId(callId: String) = ("missed:$callId").hashCode()
92
+
93
+ private fun ensureChannel(context: Context) {
94
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
95
+ val manager = context.getSystemService(NotificationManager::class.java)
96
+ if (manager.getNotificationChannel(CHANNEL_ID) != null) return
97
+ manager.createNotificationChannel(
98
+ NotificationChannel(CHANNEL_ID, "Missed calls", NotificationManager.IMPORTANCE_DEFAULT).apply {
99
+ lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE
100
+ },
101
+ )
102
+ }
103
+ }
@@ -0,0 +1,42 @@
1
+ package dev.poolse.callcore.android
2
+
3
+ import android.os.Bundle
4
+ import dev.poolse.callcore.RingContext
5
+
6
+ /**
7
+ * [RingContext] ⇄ [Bundle]. A ring crosses process boundaries as
8
+ * PendingIntent extras (the notification lives on even when our process
9
+ * is dead), so it must round-trip through a Bundle losslessly.
10
+ */
11
+ internal fun RingContext.toBundle(): Bundle = Bundle().apply {
12
+ putString(K_CALL_ID, callId)
13
+ putString(K_CONVERSATION_ID, conversationId)
14
+ putString(K_CONVERSATION_NAME, conversationName)
15
+ putString(K_CALLER_NAME, callerName)
16
+ putString(K_MEDIA, media)
17
+ putString(K_GRANT, grant)
18
+ putLong(K_DEADLINE, ringDeadlineEpochMs)
19
+ }
20
+
21
+ internal fun Bundle.toRingContext(): RingContext? {
22
+ val callId = getString(K_CALL_ID) ?: return null
23
+ val conversationId = getString(K_CONVERSATION_ID) ?: return null
24
+ val grant = getString(K_GRANT) ?: return null
25
+ return RingContext(
26
+ callId = callId,
27
+ conversationId = conversationId,
28
+ conversationName = getString(K_CONVERSATION_NAME),
29
+ callerName = getString(K_CALLER_NAME),
30
+ media = getString(K_MEDIA) ?: "audio",
31
+ grant = grant,
32
+ ringDeadlineEpochMs = getLong(K_DEADLINE),
33
+ )
34
+ }
35
+
36
+ private const val K_CALL_ID = "callId"
37
+ private const val K_CONVERSATION_ID = "conversationId"
38
+ private const val K_CONVERSATION_NAME = "conversationName"
39
+ private const val K_CALLER_NAME = "callerName"
40
+ private const val K_MEDIA = "media"
41
+ private const val K_GRANT = "grant"
42
+ private const val K_DEADLINE = "ringDeadline"
@@ -0,0 +1,99 @@
1
+ package dev.poolse.callcore.android
2
+
3
+ import dev.poolse.callcore.Direction
4
+ import dev.poolse.callcore.MachineState
5
+ import dev.poolse.callcore.Phase
6
+
7
+ /**
8
+ * The one place a [MachineState] becomes the contract's `Snapshot`
9
+ * (CALL_CONTRACT.md §8). Both the Android bridge and — mirrored — the JS
10
+ * machine produce this exact shape, so a UI reads identically wherever
11
+ * it runs. Returns `null` for idle: the bridge maps that to a cleared
12
+ * call state.
13
+ *
14
+ * The participant roster is merged in by the bridge from the media
15
+ * adapter's reports; the machine itself does not carry it.
16
+ */
17
+ internal fun MachineState.toSnapshot(
18
+ conversationName: String? = null,
19
+ kind: String = "call",
20
+ participants: List<Map<String, Any>> = emptyList(),
21
+ audioRoute: String = "earpiece",
22
+ audioOutputs: List<Map<String, Any>> = emptyList(),
23
+ audioOutputId: String? = null,
24
+ mutedSelf: Boolean = false,
25
+ cameraOn: Boolean = false,
26
+ cameraFacing: String? = null,
27
+ /** The waiting call's ring (names); the machine's [MachineState.waiting] says whether there is one. */
28
+ waitingRing: dev.poolse.callcore.RingContext? = null,
29
+ /** Our own link to the SFU: `good` | `poor` | `lost` | `unknown`. */
30
+ connectionQuality: String = "unknown",
31
+ /** Incoming video switched off to keep the audio going. */
32
+ videoPaused: Boolean = false,
33
+ ): Map<String, Any?>? {
34
+ if (phase == Phase.IDLE) return null
35
+ return buildMap {
36
+ putAll(snapshotCore(conversationName, participants, audioRoute, mutedSelf, cameraOn))
37
+ put("kind", kind)
38
+ put("connectionQuality", connectionQuality)
39
+ put("videoPaused", videoPaused)
40
+ put("audioOutputs", audioOutputs)
41
+ put("audioOutputId", audioOutputId)
42
+ // Optional in the contract: present only while a camera is published.
43
+ if (cameraFacing != null) put("cameraFacing", cameraFacing)
44
+ // The call waiting beside this one: null when none.
45
+ put(
46
+ "waiting",
47
+ waiting?.let { w ->
48
+ mapOf(
49
+ "callId" to w.callId,
50
+ "conversationId" to (waitingRing?.conversationId ?: w.conversationId),
51
+ "conversationName" to waitingRing?.conversationName,
52
+ "callerName" to waitingRing?.callerName,
53
+ "media" to w.media,
54
+ )
55
+ },
56
+ )
57
+ }
58
+ }
59
+
60
+ private fun MachineState.snapshotCore(
61
+ conversationName: String?,
62
+ participants: List<Map<String, Any>>,
63
+ audioRoute: String,
64
+ mutedSelf: Boolean,
65
+ cameraOn: Boolean,
66
+ ): Map<String, Any?> {
67
+ return mapOf(
68
+ "cv" to 1,
69
+ "callId" to callId,
70
+ "conversationId" to conversationId,
71
+ "conversationName" to conversationName,
72
+ "direction" to (direction?.wire ?: Direction.INCOMING.wire),
73
+ "media" to media,
74
+ "phase" to phase.wire,
75
+ "reason" to reason?.wire,
76
+ "participants" to participants,
77
+ "audioRoute" to audioRoute,
78
+ "mutedSelf" to mutedSelf,
79
+ "cameraOn" to cameraOn,
80
+ )
81
+ }
82
+
83
+ private val Phase.wire: String
84
+ get() = when (this) {
85
+ Phase.IDLE -> "idle"
86
+ Phase.RINGING_IN -> "ringing_in"
87
+ Phase.RINGING_OUT -> "ringing_out"
88
+ Phase.CONNECTING -> "connecting"
89
+ Phase.ACTIVE -> "active"
90
+ Phase.RECONNECTING -> "reconnecting"
91
+ Phase.ENDED -> "ended"
92
+ }
93
+
94
+ private val Direction.wire: String
95
+ get() = when (this) {
96
+ Direction.INCOMING -> "incoming"
97
+ Direction.OUTGOING -> "outgoing"
98
+ Direction.JOINED -> "joined"
99
+ }
@@ -0,0 +1,42 @@
1
+ package expo.modules.poolsecalls
2
+
3
+ import android.app.Activity
4
+ import android.os.Build
5
+ import android.view.WindowManager
6
+
7
+ /**
8
+ * Lets the app's own activity show over the lock screen while a call
9
+ * rings or runs, so answering never demands an unlock. Cleared when the
10
+ * call ends, so the app never lingers above the keyguard.
11
+ *
12
+ * [showOverKeyguard] outlives the activity: a MainActivity recreated mid-call
13
+ * (or launched by the core with `poolse_launch_call`) re-applies it from
14
+ * its onCreate / onNewIntent — the host's config plugin patches those in.
15
+ *
16
+ * Only show-when-locked, never dismiss-keyguard: dismissing a secure lock
17
+ * would throw up the PIN bouncer.
18
+ */
19
+ object CallLockscreen {
20
+ @JvmStatic
21
+ @Volatile
22
+ var showOverKeyguard = false
23
+
24
+ @JvmStatic
25
+ fun apply(activity: Activity, enabled: Boolean) {
26
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O_MR1) {
27
+ activity.setShowWhenLocked(enabled)
28
+ activity.setTurnScreenOn(enabled)
29
+ } else {
30
+ @Suppress("DEPRECATION")
31
+ val flags = WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED or
32
+ WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
33
+ if (enabled) activity.window.addFlags(flags) else activity.window.clearFlags(flags)
34
+ }
35
+ }
36
+
37
+ fun set(activity: Activity?, enabled: Boolean) {
38
+ showOverKeyguard = enabled
39
+ activity ?: return
40
+ activity.runOnUiThread { runCatching { apply(activity, enabled) } }
41
+ }
42
+ }