@poolse/native 3.9.0 → 3.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (37) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +129 -9
  3. package/android/src/main/AndroidManifest.xml +4 -0
  4. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +83 -6
  5. package/android/src/main/java/dev/poolse/callcore/Ports.kt +28 -1
  6. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +3 -3
  7. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +155 -10
  8. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +7 -1
  9. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +21 -1
  10. package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +32 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/EscalationNotification.kt +475 -0
  12. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +9 -4
  13. package/android/src/main/java/dev/poolse/callcore/android/MeetingNotification.kt +127 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/PoolseIncomingCall.kt +9 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +9 -0
  16. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +48 -2
  17. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +121 -6
  18. package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +15 -0
  19. package/dist/index.cjs +108 -0
  20. package/dist/index.cjs.map +1 -1
  21. package/dist/index.d.cts +241 -23
  22. package/dist/index.d.ts +241 -23
  23. package/dist/index.js +98 -1
  24. package/dist/index.js.map +1 -1
  25. package/ios/Core/CallCoreRuntime.swift +79 -5
  26. package/ios/Core/CallHttpClient.swift +9 -2
  27. package/ios/Core/Ports.swift +31 -2
  28. package/ios/Core/SnapshotEncoding.swift +22 -3
  29. package/ios/Module/PoolseCallsModule.swift +48 -1
  30. package/ios/Platform/CallCore.swift +100 -1
  31. package/ios/Platform/CallKitController.swift +1 -1
  32. package/ios/Platform/EscalationNotifications.swift +195 -0
  33. package/ios/Platform/LiveKitMediaPort.swift +127 -3
  34. package/ios/Platform/MessageNotifications.swift +60 -1
  35. package/ios/Platform/VoipPush.swift +11 -2
  36. package/package.json +1 -1
  37. package/src/index.ts +354 -23
@@ -0,0 +1,475 @@
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.RemoteInput
14
+ import androidx.work.BackoffPolicy
15
+ import androidx.work.Constraints
16
+ import androidx.work.CoroutineWorker
17
+ import androidx.work.Data
18
+ import androidx.work.ExistingWorkPolicy
19
+ import androidx.work.ForegroundInfo
20
+ import androidx.work.NetworkType
21
+ import androidx.work.OneTimeWorkRequestBuilder
22
+ import androidx.work.OutOfQuotaPolicy
23
+ import androidx.work.WorkManager
24
+ import androidx.work.WorkerParameters
25
+ import kotlinx.coroutines.Dispatchers
26
+ import kotlinx.coroutines.withContext
27
+ import okhttp3.MediaType.Companion.toMediaType
28
+ import okhttp3.OkHttpClient
29
+ import okhttp3.Request
30
+ import okhttp3.RequestBody.Companion.toRequestBody
31
+ import org.json.JSONObject
32
+ import java.text.SimpleDateFormat
33
+ import java.util.Locale
34
+ import java.util.concurrent.TimeUnit
35
+
36
+ /**
37
+ * An agent attending a meeting for the user asks them something its brief
38
+ * doesn't cover (server docs/AGENTS_IN_CALLS.md §5): the FCM data push
39
+ * `type: "agent_escalation"`, posted here natively so it shows with the
40
+ * app killed — "Jasir's agent asks: They ask for 10% off, accept?" with
41
+ * Approve, Decline and Answer (inline text).
42
+ *
43
+ * The actions reply natively, authorized by the push's short-lived
44
+ * `reply_token` (that escalation only, once, until `expires_at`) in the
45
+ * body — `POST /v1/agent-escalations/:id/reply`, no session, no JS — so
46
+ * they work from the lock screen. The app's `messageReplyRequiresUnlock`
47
+ * setting asks for the unlock first here too.
48
+ *
49
+ * Results reach JS like chat replies: `onNotificationAction` with
50
+ * `action: "escalation"` (queued while nobody listens).
51
+ */
52
+ object EscalationNotification {
53
+ const val CHANNEL_ID = "poolse_agent_escalations"
54
+ internal const val KEY_ANSWER = "poolse_escalation_answer"
55
+ internal const val ACTION_APPROVE = "dev.poolse.callcore.escalation.APPROVE"
56
+ internal const val ACTION_DECLINE = "dev.poolse.callcore.escalation.DECLINE"
57
+ internal const val ACTION_ANSWER = "dev.poolse.callcore.escalation.ANSWER"
58
+ internal const val EXTRA_ID = "poolse_escalation_id"
59
+ private const val PREFS = "dev.poolse.escalations"
60
+ private const val TAG = "PoolseEscalation"
61
+ private const val META_UNLOCK = "dev.poolse.messages.reply_requires_unlock"
62
+
63
+ /** A `type: "agent_escalation"` push. */
64
+ fun show(context: Context, data: Map<String, String>, smallIcon: Int) {
65
+ val id = data["escalation_id"]?.ifBlank { null } ?: return
66
+ val token = data["reply_token"]?.ifBlank { null } ?: return
67
+ val expiresAt = parseTime(data["expires_at"])
68
+ if (expiresAt != null && expiresAt <= System.currentTimeMillis()) return
69
+ val server = ServerRegistry.resolve(context, data["tenant_id"]?.ifBlank { null })
70
+ val e = Escalation(
71
+ id = id,
72
+ token = token,
73
+ serverId = server?.id,
74
+ replyUrl = data["reply_url"]?.ifBlank { null },
75
+ callId = data["call_id"]?.ifBlank { null },
76
+ conversationId = data["conversation_id"]?.ifBlank { null },
77
+ title = data["title"]?.ifBlank { null }
78
+ ?: "${data["agent_name"]?.ifBlank { null } ?: "Your agent"} asks",
79
+ question = data["question"]?.ifBlank { null } ?: data["body"].orEmpty(),
80
+ options = (data["options"] ?: "approve,decline,answer").split(',').map { it.trim() }.filter { it.isNotEmpty() },
81
+ workspace = ServerRegistry.servers(context).workspaceLabel(server?.id, data["workspace_name"]),
82
+ expiresAt = expiresAt,
83
+ )
84
+ save(context, e)
85
+ post(context, e, smallIcon, status = null, alert = true)
86
+ }
87
+
88
+ /** The user acted: show "Sending…" now (Android spins the reply field until the notification changes). */
89
+ internal fun onSending(context: Context, id: String) {
90
+ val e = load(context, id) ?: return
91
+ post(context, e, CallCore.smallIcon(context), status = "Sending…", alert = false, actions = false)
92
+ }
93
+
94
+ /**
95
+ * The reply's outcome. Sent: "Approved" (or what you answered), then gone
96
+ * after a moment. Not sent: why, with the actions back when trying again
97
+ * can still work.
98
+ */
99
+ internal fun onReplied(context: Context, id: String, ok: Boolean, label: String, retryable: Boolean) {
100
+ val e = load(context, id) ?: return
101
+ if (ok) {
102
+ post(context, e, CallCore.smallIcon(context), status = label, alert = false, actions = false, timeoutMs = 4_000L)
103
+ remove(context, id)
104
+ } else {
105
+ post(context, e, CallCore.smallIcon(context), status = label, alert = true, actions = retryable)
106
+ if (!retryable) remove(context, id)
107
+ }
108
+ }
109
+
110
+ internal fun find(context: Context, id: String): Escalation? = load(context, id)
111
+
112
+ // ── building ────────────────────────────────────────────────────────
113
+
114
+ private fun post(
115
+ context: Context,
116
+ e: Escalation,
117
+ smallIcon: Int,
118
+ status: String?,
119
+ alert: Boolean,
120
+ actions: Boolean = true,
121
+ timeoutMs: Long? = null,
122
+ ) {
123
+ ensureChannel(context)
124
+ val nid = notificationId(e.id)
125
+ val body = if (status != null) "${e.question}\n\n$status" else e.question
126
+ val builder = NotificationCompat.Builder(context, CHANNEL_ID)
127
+ .setSmallIcon(smallIcon)
128
+ .setContentTitle(e.title)
129
+ .setContentText(status ?: e.question)
130
+ .setStyle(NotificationCompat.BigTextStyle().bigText(body))
131
+ .setCategory(NotificationCompat.CATEGORY_MESSAGE)
132
+ .setPriority(NotificationCompat.PRIORITY_HIGH)
133
+ .setOnlyAlertOnce(!alert)
134
+ .setAutoCancel(true)
135
+ .apply { if (e.workspace != null) setSubText(e.workspace) }
136
+ val left = e.expiresAt?.let { it - System.currentTimeMillis() }
137
+ (timeoutMs ?: left?.takeIf { it > 0 })?.let(builder::setTimeoutAfter)
138
+ openIntent(context, e, nid)?.let(builder::setContentIntent)
139
+
140
+ if (actions) {
141
+ val unlock = requiresUnlock(context)
142
+ if ("approve" in e.options) {
143
+ builder.addAction(
144
+ NotificationCompat.Action.Builder(0, "Approve", actionIntent(context, ACTION_APPROVE, e.id, nid + 1, mutable = false))
145
+ .setShowsUserInterface(false)
146
+ .setAuthenticationRequired(unlock)
147
+ .build(),
148
+ )
149
+ }
150
+ if ("decline" in e.options) {
151
+ builder.addAction(
152
+ NotificationCompat.Action.Builder(0, "Decline", actionIntent(context, ACTION_DECLINE, e.id, nid + 2, mutable = false))
153
+ .setShowsUserInterface(false)
154
+ .setAuthenticationRequired(unlock)
155
+ .build(),
156
+ )
157
+ }
158
+ if ("answer" in e.options) {
159
+ val input = RemoteInput.Builder(KEY_ANSWER).setLabel("Your answer").build()
160
+ builder.addAction(
161
+ NotificationCompat.Action.Builder(0, "Answer", actionIntent(context, ACTION_ANSWER, e.id, nid + 3, mutable = true))
162
+ .addRemoteInput(input)
163
+ .setAllowGeneratedReplies(false)
164
+ .setSemanticAction(NotificationCompat.Action.SEMANTIC_ACTION_REPLY)
165
+ .setShowsUserInterface(false)
166
+ .setAuthenticationRequired(unlock)
167
+ .build(),
168
+ )
169
+ }
170
+ }
171
+ try {
172
+ NotificationManagerCompat.from(context).notify(nid, builder.build())
173
+ } catch (err: SecurityException) {
174
+ Log.w(TAG, "escalation notification refused (POST_NOTIFICATIONS?)", err)
175
+ }
176
+ }
177
+
178
+ /** A tap opens the app on the call's conversation (`open` CallAction). */
179
+ private fun openIntent(context: Context, e: Escalation, requestCode: Int): PendingIntent? {
180
+ val conversationId = e.conversationId ?: return null
181
+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
182
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
183
+ .putExtra(MissedCallNotification.EXTRA_ACTION, MissedCallNotification.ACTION_OPEN)
184
+ .putExtra(MissedCallNotification.EXTRA_CONVERSATION_ID, conversationId)
185
+ .putExtra(MissedCallNotification.EXTRA_CALL_ID, e.callId)
186
+ .putExtra(MissedCallNotification.EXTRA_SERVER_ID, e.serverId)
187
+ return PendingIntent.getActivity(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)
188
+ }
189
+
190
+ private fun actionIntent(context: Context, action: String, id: String, requestCode: Int, mutable: Boolean): PendingIntent {
191
+ val intent = Intent(context, EscalationActionReceiver::class.java).setAction(action).putExtra(EXTRA_ID, id)
192
+ // RemoteInput writes the typed text into the intent: it must be mutable.
193
+ val mutability = if (mutable && Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
194
+ PendingIntent.FLAG_MUTABLE
195
+ } else {
196
+ PendingIntent.FLAG_IMMUTABLE
197
+ }
198
+ return PendingIntent.getBroadcast(context, requestCode, intent, PendingIntent.FLAG_UPDATE_CURRENT or mutability)
199
+ }
200
+
201
+ private fun requiresUnlock(context: Context): Boolean = runCatching {
202
+ context.packageManager
203
+ .getApplicationInfo(context.packageName, android.content.pm.PackageManager.GET_META_DATA)
204
+ .metaData?.getBoolean(META_UNLOCK, false) ?: false
205
+ }.getOrDefault(false)
206
+
207
+ private fun ensureChannel(context: Context) {
208
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
209
+ val manager = context.getSystemService(NotificationManager::class.java)
210
+ if (manager.getNotificationChannel(CHANNEL_ID) != null) return
211
+ manager.createNotificationChannel(
212
+ NotificationChannel(CHANNEL_ID, "Questions from your agent", NotificationManager.IMPORTANCE_HIGH).apply {
213
+ lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE
214
+ },
215
+ )
216
+ }
217
+
218
+ private fun notificationId(id: String) = ("escalation:$id").hashCode()
219
+
220
+ private fun parseTime(v: String?): Long? {
221
+ if (v.isNullOrBlank()) return null
222
+ v.toLongOrNull()?.let { return it }
223
+ // ISO 8601 ("2026-11-22T10:00:00.123Z"); java.time needs API 26.
224
+ val iso = v.trim().replace(Regex("\\.\\d+"), "").replace(Regex("Z$"), "+00:00")
225
+ return runCatching {
226
+ SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.US).parse(iso)?.time
227
+ }.getOrNull()
228
+ }
229
+
230
+ // ── storage (the token outlives the push: actions read it from here) ─
231
+
232
+ internal class Escalation(
233
+ val id: String,
234
+ val token: String,
235
+ val serverId: String?,
236
+ val replyUrl: String?,
237
+ val callId: String?,
238
+ val conversationId: String?,
239
+ val title: String,
240
+ val question: String,
241
+ val options: List<String>,
242
+ val workspace: String?,
243
+ val expiresAt: Long?,
244
+ )
245
+
246
+ private fun prefs(context: Context) = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
247
+
248
+ private fun save(context: Context, e: Escalation) {
249
+ val o = JSONObject()
250
+ .put("token", e.token)
251
+ .put("server", e.serverId ?: "")
252
+ .put("url", e.replyUrl ?: "")
253
+ .put("call", e.callId ?: "")
254
+ .put("conversation", e.conversationId ?: "")
255
+ .put("title", e.title)
256
+ .put("question", e.question)
257
+ .put("options", e.options.joinToString(","))
258
+ .put("workspace", e.workspace ?: "")
259
+ .put("expires", e.expiresAt ?: 0L)
260
+ val p = prefs(context)
261
+ val edit = p.edit().putString(e.id, o.toString())
262
+ // Drop the long-expired ones so the file never grows.
263
+ val now = System.currentTimeMillis()
264
+ for ((k, v) in p.all) {
265
+ val exp = runCatching { JSONObject(v as String).optLong("expires") }.getOrDefault(0L)
266
+ if (k != e.id && exp in 1 until now - 60 * 60 * 1000L) edit.remove(k)
267
+ }
268
+ edit.apply()
269
+ }
270
+
271
+ private fun load(context: Context, id: String): Escalation? {
272
+ val raw = prefs(context).getString(id, null) ?: return null
273
+ return runCatching {
274
+ val o = JSONObject(raw)
275
+ Escalation(
276
+ id = id,
277
+ token = o.getString("token"),
278
+ serverId = o.optString("server").ifBlank { null },
279
+ replyUrl = o.optString("url").ifBlank { null },
280
+ callId = o.optString("call").ifBlank { null },
281
+ conversationId = o.optString("conversation").ifBlank { null },
282
+ title = o.optString("title"),
283
+ question = o.optString("question"),
284
+ options = o.optString("options").split(',').filter { it.isNotEmpty() },
285
+ workspace = o.optString("workspace").ifBlank { null },
286
+ expiresAt = o.optLong("expires").takeIf { it > 0 },
287
+ )
288
+ }.getOrNull()
289
+ }
290
+
291
+ private fun remove(context: Context, id: String) {
292
+ prefs(context).edit().remove(id).apply()
293
+ }
294
+ }
295
+
296
+ /** Approve / Decline / Answer tapped on an escalation notification. */
297
+ class EscalationActionReceiver : BroadcastReceiver() {
298
+ override fun onReceive(context: Context, intent: Intent) {
299
+ val id = intent.getStringExtra(EscalationNotification.EXTRA_ID) ?: return
300
+ val app = context.applicationContext
301
+ val decision = when (intent.action) {
302
+ EscalationNotification.ACTION_APPROVE -> "approve"
303
+ EscalationNotification.ACTION_DECLINE -> "decline"
304
+ EscalationNotification.ACTION_ANSWER -> "answer"
305
+ else -> return
306
+ }
307
+ val answer = if (decision == "answer") {
308
+ RemoteInput.getResultsFromIntent(intent)
309
+ ?.getCharSequence(EscalationNotification.KEY_ANSWER)?.toString()?.trim().orEmpty().take(1000)
310
+ } else {
311
+ null
312
+ }
313
+ if (decision == "answer" && answer.isNullOrEmpty()) {
314
+ // Nothing typed: repost so the field stops spinning.
315
+ EscalationNotification.onReplied(app, id, ok = false, label = "Type an answer to send it.", retryable = true)
316
+ return
317
+ }
318
+ EscalationNotification.onSending(app, id)
319
+ EscalationActionWorker.enqueue(app, id, decision, answer)
320
+ }
321
+ }
322
+
323
+ /**
324
+ * The HTTP side: `POST /v1/agent-escalations/:id/reply` `{token,
325
+ * decision}` / `{token, answer}`, no Authorization header, against the
326
+ * escalation's own server. The token works once, so only a request that
327
+ * never got an answer (no connection) is retried; a 5xx or 429 is retried
328
+ * briefly too (the server did not take it).
329
+ */
330
+ class EscalationActionWorker(context: Context, params: WorkerParameters) : CoroutineWorker(context, params) {
331
+
332
+ override suspend fun doWork(): Result = withContext(Dispatchers.IO) {
333
+ val app = applicationContext
334
+ val id = inputData.getString(KEY_ID) ?: return@withContext Result.failure()
335
+ val decision = inputData.getString(KEY_DECISION) ?: return@withContext Result.failure()
336
+ val answer = inputData.getString(KEY_ANSWER)
337
+ val e = EscalationNotification.find(app, id)
338
+ val url = e?.let { urlOf(app, it) }
339
+ val expired = e?.expiresAt?.let { it + 60_000L < System.currentTimeMillis() } ?: false
340
+
341
+ val outcome = when {
342
+ e == null -> Outcome(0, "no_token", null)
343
+ url == null -> Outcome(0, "not_configured", null)
344
+ expired -> Outcome(410, "expired", null)
345
+ else -> {
346
+ val body = JSONObject().put("token", e.token)
347
+ if (decision == "answer") body.put("answer", answer.orEmpty()) else body.put("decision", decision)
348
+ post(url, body)
349
+ }
350
+ }
351
+ val ok = outcome.status in 200..299
352
+ val retryable = !ok && e != null && url != null && !expired &&
353
+ (outcome.status == 0 || outcome.status == 429 || outcome.status >= 500)
354
+ if (retryable && runAttemptCount + 1 < MAX_ATTEMPTS) return@withContext Result.retry()
355
+
356
+ val label = if (ok) {
357
+ when (decision) {
358
+ "approve" -> "Approved — your agent will say so."
359
+ "decline" -> "Declined — your agent will say so."
360
+ else -> "Sent: “${answer.orEmpty()}”"
361
+ }
362
+ } else {
363
+ reason(outcome)
364
+ }
365
+ // Trying again from the notification still works only while it's pending.
366
+ val canRetry = !ok && outcome.status !in setOf(401, 404, 409, 410) && outcome.code != "no_token"
367
+ EscalationNotification.onReplied(app, id, ok, label, canRetry)
368
+
369
+ val event = mutableMapOf<String, Any?>(
370
+ "action" to "escalation",
371
+ "escalationId" to id,
372
+ "decision" to decision,
373
+ "conversationId" to (e?.conversationId ?: ""),
374
+ "callId" to e?.callId,
375
+ "ok" to ok,
376
+ "serverId" to (e?.serverId ?: ServerRegistry.servers(app).get(null)?.id),
377
+ )
378
+ if (decision == "answer") event["text"] = answer
379
+ if (!ok) {
380
+ event["error"] = outcome.code ?: if (outcome.status == 0) "network" else "http_${outcome.status}"
381
+ if (outcome.status != 0) event["status"] = outcome.status
382
+ }
383
+ MessageNotifications.report(app, event)
384
+ if (ok) Result.success() else Result.failure()
385
+ }
386
+
387
+ override suspend fun getForegroundInfo(): ForegroundInfo {
388
+ val notification = NotificationCompat.Builder(applicationContext, EscalationNotification.CHANNEL_ID)
389
+ .setSmallIcon(CallCore.smallIcon(applicationContext))
390
+ .setContentTitle("Sending your answer…")
391
+ .setPriority(NotificationCompat.PRIORITY_LOW)
392
+ .setSilent(true)
393
+ .setOngoing(true)
394
+ .build()
395
+ return ForegroundInfo(FOREGROUND_ID, notification)
396
+ }
397
+
398
+ /** Its own server's API (the one the push came from); the push's URL only when none is configured. */
399
+ private fun urlOf(context: Context, e: EscalationNotification.Escalation): String? {
400
+ val base = if (e.serverId != null) {
401
+ ServerRegistry.baseUrl(context, e.serverId).ifEmpty { null }
402
+ } else {
403
+ ServerRegistry.baseUrl(context, null).ifEmpty { null } ?: CallCore.apiBaseUrl(context)
404
+ }
405
+ if (base != null) return "$base/v1/agent-escalations/${android.net.Uri.encode(e.id)}/reply"
406
+ return e.replyUrl?.takeIf { it.startsWith("https://") || it.startsWith("http://") }
407
+ }
408
+
409
+ private class Outcome(val status: Int, val code: String?, val json: JSONObject?)
410
+
411
+ private fun post(url: String, body: JSONObject): Outcome = runCatching {
412
+ val request = Request.Builder()
413
+ .url(url)
414
+ .header("Accept", "application/json")
415
+ .post(body.toString().toRequestBody("application/json".toMediaType()))
416
+ .build()
417
+ client.newCall(request).execute().use { res ->
418
+ val json = runCatching { JSONObject(res.body?.string().orEmpty()) }.getOrNull()
419
+ val code = json?.optJSONObject("error")?.optString("code")?.ifBlank { null }
420
+ if (!res.isSuccessful) Log.w(TAG, "escalation reply ${res.code} ${code ?: ""}")
421
+ Outcome(res.code, code, json)
422
+ }
423
+ }.getOrElse {
424
+ Log.w(TAG, "escalation reply failed", it)
425
+ Outcome(0, null, null)
426
+ }
427
+
428
+ private fun reason(o: Outcome): String = when {
429
+ o.code == "not_configured" || o.code == "no_token" -> "Open the app to answer."
430
+ o.status == 0 -> "No connection — try again."
431
+ o.status == 409 -> "Already answered."
432
+ o.status == 410 -> "Too late — the question expired."
433
+ o.status == 401 -> "This notification expired. Open the app to answer."
434
+ o.status == 404 -> "This question is gone."
435
+ o.status == 422 -> "The answer couldn't be sent (1 to 1000 characters)."
436
+ o.status == 429 -> "Too many tries — wait a moment."
437
+ else -> "Couldn't send — try again."
438
+ }
439
+
440
+ companion object {
441
+ private const val KEY_ID = "id"
442
+ private const val KEY_DECISION = "decision"
443
+ private const val KEY_ANSWER = "answer"
444
+ private const val MAX_ATTEMPTS = 4
445
+ private const val FOREGROUND_ID = 0x504F4F45
446
+ private const val TAG = "PoolseEscalation"
447
+
448
+ private val client: OkHttpClient by lazy {
449
+ OkHttpClient.Builder()
450
+ .connectTimeout(10, TimeUnit.SECONDS)
451
+ .readTimeout(15, TimeUnit.SECONDS)
452
+ .callTimeout(20, TimeUnit.SECONDS)
453
+ .build()
454
+ }
455
+
456
+ internal fun enqueue(context: Context, id: String, decision: String, answer: String?) {
457
+ val data = Data.Builder()
458
+ .putString(KEY_ID, id)
459
+ .putString(KEY_DECISION, decision)
460
+ .putString(KEY_ANSWER, answer)
461
+ .build()
462
+ val request = OneTimeWorkRequestBuilder<EscalationActionWorker>()
463
+ .setInputData(data)
464
+ .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
465
+ .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)
466
+ .setBackoffCriteria(BackoffPolicy.EXPONENTIAL, 10, TimeUnit.SECONDS)
467
+ .addTag("poolse-notification-action")
468
+ .build()
469
+ runCatching {
470
+ // One reply per escalation: a second tap while the first is on its way is dropped.
471
+ WorkManager.getInstance(context).enqueueUniqueWork("poolse-escalation-$id", ExistingWorkPolicy.KEEP, request)
472
+ }.onFailure { Log.e(TAG, "could not queue the escalation reply", it) }
473
+ }
474
+ }
475
+ }
@@ -121,8 +121,13 @@ class IncomingCallActivity : Activity() {
121
121
  ring = next
122
122
  awaitingForward = false
123
123
  pulse?.cancel()
124
- val title = ServerRegistry.ringTitle(this, next, next.conversationName ?: next.callerName) ?: "Incoming call"
125
- val body = if (next.media == "video") "Incoming video call" else "Incoming call"
124
+ val title = ServerRegistry.ringTitle(this, next, next.displayTitle) ?: "Incoming call"
125
+ val body = when {
126
+ next.isMeeting && next.media == "video" -> "Video meeting"
127
+ next.isMeeting -> "Meeting"
128
+ next.media == "video" -> "Incoming video call"
129
+ else -> "Incoming call"
130
+ }
126
131
  setContentView(buildScene(title, body, next))
127
132
  }
128
133
 
@@ -340,10 +345,10 @@ class IncomingCallActivity : Activity() {
340
345
  gravity = Gravity.CENTER
341
346
  layoutParams = LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, wrap())
342
347
  }
343
- val decline = actionButton("Decline", "✕", "#EF4444") {
348
+ val decline = actionButton(if (ring.isMeeting) "Not now" else "Decline", "✕", "#EF4444") {
344
349
  CallCore.getOrNull(this)?.onUserDecline(ring); finish()
345
350
  }
346
- val accept = actionButton("Answer", "✓", "#22C55E") {
351
+ val accept = actionButton(if (ring.isMeeting) "Join" else "Answer", "✓", "#22C55E") {
347
352
  val core = CallCore.getOrNull(this)
348
353
  if (core == null) finish() else answerAndForward { core.onUserAnswer(ring, this) }
349
354
  }
@@ -0,0 +1,127 @@
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
+ * Scheduled-meeting notices (server docs/MEETINGS.md §11.3), posted natively
15
+ * from the FCM data push `type: "meeting"` so they show with the app
16
+ * closed: `event: "starting"` ("Weekly sync is starting [Join]") and
17
+ * `event: "brief"` (the agenda and who's coming, a few minutes before).
18
+ *
19
+ * The tap and Join open the app through its launch activity, carrying the
20
+ * action in [MissedCallNotification]'s extras — the same `CallAction`
21
+ * plumbing: `takeCallAction()` on a cold start, `onCallAction` while
22
+ * running. A tap is `open` (the conversation), Join is `join_meeting`; the
23
+ * app joins the room with the user's session (only it has one), so Join
24
+ * never connects from here.
25
+ *
26
+ * One notification per meeting: `starting` replaces that meeting's brief,
27
+ * and a repeat of the same event is not alerted again.
28
+ */
29
+ object MeetingNotification {
30
+ const val CHANNEL_ID = "poolse_meetings"
31
+ /** The scheduled meeting the action is for, beside [MissedCallNotification]'s extras. */
32
+ const val EXTRA_SCHEDULED_MEETING_ID = "poolse_call_action_meeting"
33
+ const val ACTION_JOIN = "join_meeting"
34
+ private const val TAG = "PoolseMeeting"
35
+
36
+ // A notice FCM held while the phone was off is about a meeting long over.
37
+ private const val STALE_MS = 6 * 60 * 60 * 1000L
38
+
39
+ /** Event + meeting already shown, so a redelivered push is not posted twice. */
40
+ private val shown = java.util.Collections.synchronizedSet(LinkedHashSet<String>())
41
+
42
+ fun show(context: Context, data: Map<String, String>, smallIcon: Int) {
43
+ val meetingId = data["scheduled_meeting_id"]?.ifBlank { null } ?: return
44
+ val conversationId = data["conversation_id"]?.ifBlank { null } ?: return
45
+ val event = data["event"] ?: return
46
+ if (event != "starting" && event != "brief") return
47
+ val sentAt = data["sent_at"]?.toLongOrNull()
48
+ if (sentAt != null && System.currentTimeMillis() - sentAt > STALE_MS) return
49
+ if (!shown.add("$meetingId:$event")) return
50
+ if (shown.size > 64) shown.iterator().let { it.next(); it.remove() }
51
+
52
+ val callId = data["call_id"]?.ifBlank { null }
53
+ val media = if (data["media"] == "video") "video" else "audio"
54
+ val name = data["conversation_name"]?.ifBlank { null }
55
+ val title = data["title"]?.ifBlank { null }
56
+ ?: if (event == "starting") "${name ?: "Your meeting"} is starting" else name ?: "Meeting soon"
57
+ val body = data["body"]?.ifBlank { null }
58
+ val servers = ServerRegistry.servers(context)
59
+ val server = servers.resolve(data["tenant_id"]?.ifBlank { null })
60
+ // Several workspaces signed in: say which one it is in.
61
+ val workspace = servers.workspaceLabel(server?.id, data["workspace_name"])
62
+
63
+ ensureChannel(context)
64
+ val id = notificationId(meetingId)
65
+
66
+ fun launch(action: String, requestOffset: Int): PendingIntent? {
67
+ val intent = context.packageManager.getLaunchIntentForPackage(context.packageName) ?: return null
68
+ intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
69
+ .putExtra(MissedCallNotification.EXTRA_ACTION, action)
70
+ .putExtra(MissedCallNotification.EXTRA_CONVERSATION_ID, conversationId)
71
+ .putExtra(MissedCallNotification.EXTRA_CALL_ID, callId)
72
+ .putExtra(MissedCallNotification.EXTRA_MEDIA, media)
73
+ .putExtra(MissedCallNotification.EXTRA_SERVER_ID, server?.id)
74
+ .putExtra(EXTRA_SCHEDULED_MEETING_ID, meetingId)
75
+ return PendingIntent.getActivity(
76
+ context,
77
+ id + requestOffset,
78
+ intent,
79
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
80
+ )
81
+ }
82
+
83
+ val builder = NotificationCompat.Builder(context, CHANNEL_ID)
84
+ .setSmallIcon(smallIcon)
85
+ .setContentTitle(title)
86
+ .setCategory(NotificationCompat.CATEGORY_EVENT)
87
+ .setPriority(
88
+ if (event == "starting") NotificationCompat.PRIORITY_HIGH else NotificationCompat.PRIORITY_DEFAULT,
89
+ )
90
+ .setAutoCancel(true)
91
+ .setWhen(sentAt ?: System.currentTimeMillis())
92
+ .setShowWhen(true)
93
+ .apply {
94
+ if (body != null) {
95
+ setContentText(body)
96
+ setStyle(NotificationCompat.BigTextStyle().bigText(body))
97
+ }
98
+ if (workspace != null) setSubText(workspace)
99
+ }
100
+ launch(MissedCallNotification.ACTION_OPEN, 0)?.let(builder::setContentIntent)
101
+ if (event == "starting") launch(ACTION_JOIN, 1)?.let { builder.addAction(0, "Join", it) }
102
+
103
+ try {
104
+ NotificationManagerCompat.from(context).notify(id, builder.build())
105
+ } catch (e: SecurityException) {
106
+ Log.w(TAG, "meeting notification refused (POST_NOTIFICATIONS?)", e)
107
+ }
108
+ }
109
+
110
+ /** Clear it once the user acted on it from the app (its buttons do not auto-cancel). */
111
+ fun cancel(context: Context, meetingId: String) {
112
+ runCatching { NotificationManagerCompat.from(context).cancel(notificationId(meetingId)) }
113
+ }
114
+
115
+ private fun notificationId(meetingId: String) = ("meeting:$meetingId").hashCode()
116
+
117
+ private fun ensureChannel(context: Context) {
118
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
119
+ val manager = context.getSystemService(NotificationManager::class.java)
120
+ if (manager.getNotificationChannel(CHANNEL_ID) != null) return
121
+ manager.createNotificationChannel(
122
+ NotificationChannel(CHANNEL_ID, "Meetings", NotificationManager.IMPORTANCE_HIGH).apply {
123
+ lockscreenVisibility = NotificationCompat.VISIBILITY_PRIVATE
124
+ },
125
+ )
126
+ }
127
+ }
@@ -59,6 +59,12 @@ object PoolseIncomingCall {
59
59
  const val EXTRA_MEDIA = "poolse_media"
60
60
  /** Epoch ms the ring gives up at. */
61
61
  const val EXTRA_RING_DEADLINE = "poolse_ring_deadline"
62
+ /** `"meeting"` for a scheduled meeting starting (CA4), else `"call"`. */
63
+ const val EXTRA_RING_TYPE = "poolse_ring_type"
64
+ /** The meeting's title ("Weekly sync"), meeting rings only. */
65
+ const val EXTRA_MEETING_TITLE = "poolse_meeting_title"
66
+ /** What to show as the ring's headline: "Weekly sync is starting", or the conversation / caller. */
67
+ const val EXTRA_TITLE = "poolse_title"
62
68
  /** Package-local broadcast with [EXTRA_CALL_ID]: that ring is over (cancelled, answered elsewhere, timed out). */
63
69
  const val ACTION_RING_CLOSED = AndroidRingSurface.ACTION_RING_CLOSED
64
70
 
@@ -104,6 +110,9 @@ object PoolseIncomingCall {
104
110
  .putExtra(EXTRA_MEDIA, ring.media)
105
111
  .putExtra(EXTRA_RING_DEADLINE, ring.ringDeadlineEpochMs)
106
112
  .putExtra(EXTRA_SERVER_ID, ring.serverId)
113
+ .putExtra(EXTRA_RING_TYPE, ring.ringType ?: "call")
114
+ .putExtra(EXTRA_MEETING_TITLE, ring.meetingTitle)
115
+ .putExtra(EXTRA_TITLE, ring.displayTitle)
107
116
 
108
117
  /** [fill] plus the workspace label, which needs the server list. */
109
118
  internal fun fill(context: Context, intent: Intent, ring: RingContext): Intent = fill(intent, ring)
@@ -19,6 +19,9 @@ internal fun RingContext.toBundle(): Bundle = Bundle().apply {
19
19
  putString(K_AVATAR, callerAvatarUrl)
20
20
  putString(K_SERVER, serverId)
21
21
  putString(K_WORKSPACE, workspaceName)
22
+ putString(K_RING_TYPE, ringType)
23
+ putString(K_MEETING_TITLE, meetingTitle)
24
+ putString(K_MEETING_ID, meetingId)
22
25
  }
23
26
 
24
27
  internal fun Bundle.toRingContext(): RingContext? {
@@ -36,6 +39,9 @@ internal fun Bundle.toRingContext(): RingContext? {
36
39
  callerAvatarUrl = getString(K_AVATAR),
37
40
  serverId = getString(K_SERVER),
38
41
  workspaceName = getString(K_WORKSPACE),
42
+ ringType = getString(K_RING_TYPE),
43
+ meetingTitle = getString(K_MEETING_TITLE),
44
+ meetingId = getString(K_MEETING_ID),
39
45
  )
40
46
  }
41
47
 
@@ -49,3 +55,6 @@ private const val K_DEADLINE = "ringDeadline"
49
55
  private const val K_AVATAR = "callerAvatarUrl"
50
56
  private const val K_SERVER = "serverId"
51
57
  private const val K_WORKSPACE = "workspaceName"
58
+ private const val K_RING_TYPE = "ringType"
59
+ private const val K_MEETING_TITLE = "meetingTitle"
60
+ private const val K_MEETING_ID = "meetingId"