@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,294 @@
1
+ package dev.poolse.callcore.android
2
+
3
+ import android.Manifest
4
+ import android.app.Notification
5
+ import android.app.PendingIntent
6
+ import android.app.Service
7
+ import android.content.Context
8
+ import android.content.Intent
9
+ import android.content.pm.PackageManager
10
+ import android.content.pm.ServiceInfo
11
+ import android.os.Build
12
+ import android.os.Handler
13
+ import android.os.IBinder
14
+ import android.os.Looper
15
+ import android.util.Log
16
+ import androidx.core.app.NotificationCompat
17
+ import androidx.core.content.ContextCompat
18
+ import dev.poolse.callcore.CallSessionPort
19
+
20
+ /**
21
+ * Keeps the process alive while a call needs it:
22
+ *
23
+ * - **ring** mode (`phoneCall` type only) for the length of an incoming
24
+ * ring, so an OEM freezer (Samsung, Android 14 cached-app freezer)
25
+ * does not kill the ringtone and the ring-deadline timer of a closed
26
+ * app;
27
+ * - **call** mode (`phoneCall|microphone`) for a live call's whole
28
+ * lifetime, so media keeps flowing with the screen off.
29
+ *
30
+ * [CallSessionPort] is driven by the runtime (CALL_SESSION_START/STOP),
31
+ * ring mode by [CallCore]'s state reconcile; the service itself holds no
32
+ * call logic — it is the OS contract that says "a call is happening".
33
+ *
34
+ * Robustness rules, each one a crash seen in the field:
35
+ * - every `startForegroundService` MUST be answered by `startForeground`,
36
+ * even if the call already ended before `onStartCommand` ran — so a
37
+ * stop never calls `stopService` on a not-yet-started service; the
38
+ * service starts foreground and then stops itself;
39
+ * - the microphone type is claimed only with RECORD_AUDIO granted
40
+ * (Android 14 throws otherwise);
41
+ * - `startForeground` failures are caught and the service stops, never
42
+ * taking the app down with it.
43
+ */
44
+ class CallForegroundService : Service() {
45
+
46
+ override fun onBind(intent: Intent?): IBinder? = null
47
+
48
+ override fun onCreate() {
49
+ super.onCreate()
50
+ instance = this
51
+ }
52
+
53
+ override fun onDestroy() {
54
+ if (instance === this) instance = null
55
+ super.onDestroy()
56
+ }
57
+
58
+ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {
59
+ pendingStarts = (pendingStarts - 1).coerceAtLeast(0)
60
+ reconcile(desired)
61
+ // Sticky-less: if the system kills us, the call is already gone with
62
+ // the process; a relaunched empty service would be a ghost.
63
+ return START_NOT_STICKY
64
+ }
65
+
66
+ /** Bring the service in line with [want]; null = stop (after honouring the start). */
67
+ internal fun reconcile(want: Desired?) {
68
+ // Always answer the start with startForeground — a placeholder ring
69
+ // notification if the call is already gone.
70
+ val ok = tryStartForeground(want ?: Desired(Mode.RING, "", "audio"))
71
+ if (want == null || !ok) {
72
+ if (pendingStarts == 0) stopNow()
73
+ }
74
+ }
75
+
76
+ internal fun stopNow() {
77
+ runCatching { stopForeground(STOP_FOREGROUND_REMOVE) }
78
+ shownId = null
79
+ stopSelf()
80
+ }
81
+
82
+ /** The notification id we are currently foreground with. */
83
+ private var shownId: Int? = null
84
+
85
+ /**
86
+ * Start (or switch) foreground. If the full type is refused — the
87
+ * microphone type can be, on Android 14, when the app is not in a
88
+ * while-in-use state — fall back to phoneCall only rather than stop:
89
+ * stopping dropped the ring-mode service that was already working.
90
+ * Stop only when even that fails.
91
+ */
92
+ private fun tryStartForeground(want: Desired): Boolean {
93
+ val (id, notification) = notificationFor(want)
94
+ val full = typeFor(want.mode)
95
+ val attempts = if (full != ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL) {
96
+ listOf(full, ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL)
97
+ } else listOf(full)
98
+ for (type in attempts) {
99
+ try {
100
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) startForeground(id, notification, type)
101
+ else startForeground(id, notification)
102
+ // Switching id (ring → call) leaves the old one as a plain
103
+ // notification; the ring is over, so remove it.
104
+ shownId?.takeIf { it != id }?.let { old ->
105
+ runCatching { getSystemService(android.app.NotificationManager::class.java).cancel(old) }
106
+ }
107
+ shownId = id
108
+ return true
109
+ } catch (t: Throwable) {
110
+ // ForegroundServiceStartNotAllowedException, SecurityException
111
+ // (missing type permission), InvalidForegroundServiceTypeException…
112
+ Log.e(TAG, "startForeground(${want.mode}, type=$type) failed", t)
113
+ }
114
+ }
115
+ return false
116
+ }
117
+
118
+ /**
119
+ * Ring mode wears the CallStyle ring notification itself (same id),
120
+ * so a ringing phone shows ONE notification, not the ring plus an
121
+ * "Incoming call" service notice. Falls back to our own if the ring
122
+ * surface has not posted yet.
123
+ */
124
+ private fun notificationFor(want: Desired): Pair<Int, Notification> {
125
+ if (want.mode == Mode.RING) {
126
+ AndroidRingSurface.shownRing?.let { (callId, n) ->
127
+ if (callId == want.callId) {
128
+ return with(AndroidRingSurface) { callId.notificationId() } to n
129
+ }
130
+ }
131
+ }
132
+ return NOTIFICATION_ID to buildNotification(want)
133
+ }
134
+
135
+ private fun typeFor(mode: Mode): Int {
136
+ var type = ServiceInfo.FOREGROUND_SERVICE_TYPE_PHONE_CALL
137
+ if (mode == Mode.CALL && Build.VERSION.SDK_INT >= Build.VERSION_CODES.R && micGranted()) {
138
+ type = type or ServiceInfo.FOREGROUND_SERVICE_TYPE_MICROPHONE
139
+ }
140
+ return type
141
+ }
142
+
143
+ private fun micGranted() =
144
+ ContextCompat.checkSelfPermission(this, Manifest.permission.RECORD_AUDIO) ==
145
+ PackageManager.PERMISSION_GRANTED
146
+
147
+ private fun buildNotification(want: Desired): Notification {
148
+ ensureChannel()
149
+ val config = CallCore.peekConfig()
150
+ val title: String
151
+ val text: String
152
+ if (want.mode == Mode.RING) {
153
+ title = "Incoming call"; text = "Ringing…"
154
+ } else {
155
+ title = "Ongoing call"; text = if (want.media == "video") "Video call" else "Voice call"
156
+ }
157
+ val builder = NotificationCompat.Builder(this, CHANNEL_ID)
158
+ .setSmallIcon(config?.smallIcon ?: android.R.drawable.sym_call_outgoing)
159
+ .setContentTitle(title)
160
+ .setContentText(text)
161
+ .setOngoing(true)
162
+ .setCategory(NotificationCompat.CATEGORY_CALL)
163
+ .setPriority(NotificationCompat.PRIORITY_LOW)
164
+ // Tapping the ongoing-call notification returns to the call.
165
+ if (want.mode == Mode.CALL) launchIntent(want.callId)?.let(builder::setContentIntent)
166
+ return builder.build()
167
+ }
168
+
169
+ private fun launchIntent(callId: String): PendingIntent? {
170
+ val launch = packageManager.getLaunchIntentForPackage(packageName) ?: return null
171
+ launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
172
+ launch.putExtra(CallCore.EXTRA_LAUNCH_CALL, callId)
173
+ return PendingIntent.getActivity(
174
+ this,
175
+ NOTIFICATION_ID,
176
+ launch,
177
+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,
178
+ )
179
+ }
180
+
181
+ // The ongoing-call notification has its own channel, created here so it
182
+ // exists on an OUTGOING call too — the incoming ring surface's channel
183
+ // is only made when a ring shows, so a placed call would otherwise post
184
+ // to a missing channel and startForeground would crash.
185
+ private fun ensureChannel() {
186
+ if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O) return
187
+ val manager = getSystemService(android.app.NotificationManager::class.java)
188
+ if (manager.getNotificationChannel(CHANNEL_ID) != null) return
189
+ manager.createNotificationChannel(
190
+ android.app.NotificationChannel(
191
+ CHANNEL_ID,
192
+ "Ongoing calls",
193
+ android.app.NotificationManager.IMPORTANCE_LOW,
194
+ ).apply { setSound(null, null) },
195
+ )
196
+ }
197
+
198
+ internal enum class Mode { RING, CALL }
199
+ internal data class Desired(val mode: Mode, val callId: String, val media: String)
200
+
201
+ /**
202
+ * All companion state is touched on the main thread only (the
203
+ * runtime's thread and the service lifecycle's), so no locking.
204
+ */
205
+ companion object : CallSessionPort {
206
+ private const val TAG = "PoolseCallFgs"
207
+ private const val NOTIFICATION_ID = 0x9C0FE
208
+ private const val CHANNEL_ID = "poolse_ongoing_call"
209
+
210
+ private lateinit var appContext: Context
211
+ private val main by lazy { Handler(Looper.getMainLooper()) }
212
+
213
+ private var desired: Desired? = null
214
+ private var instance: CallForegroundService? = null
215
+ /** startForegroundService calls not yet delivered to onStartCommand. */
216
+ private var pendingStarts = 0
217
+
218
+ /** Wired once by [CallCore] so the port can start/stop the service. */
219
+ fun attach(context: Context) { appContext = context.applicationContext }
220
+
221
+ override fun start(callId: String, media: String) = onMain {
222
+ desired = Desired(Mode.CALL, callId, media)
223
+ launchOrSwitch()
224
+ }
225
+
226
+ override fun stop() = onMain {
227
+ desired = null
228
+ // Deferred to the end of this main-thread turn: a call handing over
229
+ // to the next (call waiting: end & answer, or a promoted ring) stops
230
+ // and starts in one dispatch, and must switch the RUNNING service
231
+ // in place — a fresh start from the background is refused on
232
+ // Android 12+ (and loses the microphone type on 14+). A start in
233
+ // the same turn sets `desired` again and this does nothing.
234
+ main.post {
235
+ // Only a started instance with nothing pending may stop now; a
236
+ // pending start stops itself after startForeground.
237
+ if (desired == null && pendingStarts == 0) instance?.stopNow()
238
+ }
239
+ }
240
+
241
+ /** Ring mode for [callId]; a no-op while a call holds the service. */
242
+ fun startRing(callId: String) = onMain {
243
+ val d = desired
244
+ if (d?.mode == Mode.CALL) return@onMain
245
+ if (d?.mode == Mode.RING && d.callId == callId) return@onMain
246
+ desired = Desired(Mode.RING, callId, "audio")
247
+ launchOrSwitch()
248
+ }
249
+
250
+ /**
251
+ * The call's media became known/changed (a join's bundle said video):
252
+ * refresh the notification and type in place — no new start needed.
253
+ */
254
+ fun updateCall(callId: String, media: String) = onMain {
255
+ val d = desired
256
+ if (d?.mode != Mode.CALL || (d.callId == callId && d.media == media)) return@onMain
257
+ desired = d.copy(callId = callId, media = media)
258
+ if (pendingStarts == 0) instance?.reconcile(desired)
259
+ }
260
+
261
+ /** Leave ring mode — never touches a call that took the service over. */
262
+ fun stopRing() = onMain {
263
+ if (desired?.mode == Mode.RING) stop()
264
+ }
265
+
266
+ /** A running, settled instance switches in place; otherwise start one. */
267
+ private fun launchOrSwitch() {
268
+ val running = instance
269
+ if (running != null && pendingStarts == 0) running.reconcile(desired) else launch()
270
+ }
271
+
272
+ private fun launch() {
273
+ if (!::appContext.isInitialized) return
274
+ val intent = Intent(appContext, CallForegroundService::class.java)
275
+ try {
276
+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
277
+ appContext.startForegroundService(intent)
278
+ } else {
279
+ appContext.startService(intent)
280
+ }
281
+ pendingStarts++
282
+ } catch (t: Throwable) {
283
+ // Background-start restriction (no FCM/user exemption at hand).
284
+ // A running instance can still switch type in place.
285
+ Log.w(TAG, "could not start the call service", t)
286
+ instance?.reconcile(desired)
287
+ }
288
+ }
289
+
290
+ private inline fun onMain(crossinline block: () -> Unit) {
291
+ if (Looper.myLooper() == Looper.getMainLooper()) block() else main.post { block() }
292
+ }
293
+ }
294
+ }
@@ -0,0 +1,207 @@
1
+ package dev.poolse.callcore.android
2
+
3
+ import dev.poolse.callcore.CallSessionBundle
4
+ import dev.poolse.callcore.HttpPort
5
+ import dev.poolse.callcore.HttpResult
6
+ import java.io.IOException
7
+ import okhttp3.Call
8
+ import okhttp3.Callback
9
+ import okhttp3.MediaType.Companion.toMediaType
10
+ import okhttp3.OkHttpClient
11
+ import okhttp3.Request
12
+ import okhttp3.RequestBody.Companion.toRequestBody
13
+ import okhttp3.Response
14
+ import org.json.JSONObject
15
+
16
+ /**
17
+ * The HTTP adapter for the contract's three token doors
18
+ * (CALL_CONTRACT.md §4). Every call is a bare REST request with a bearer
19
+ * token — no session state, no SDK coupling — so the core can answer a
20
+ * call on a cold process with nothing but the grant from the push.
21
+ *
22
+ * Fire-and-forget methods (`decline`, `hangup`) retry transient
23
+ * failures a few times on OkHttp's dispatcher; request/response methods
24
+ * surface `HttpResult` to the runtime, which owns the retry policy for
25
+ * those (one retry, then media decides).
26
+ */
27
+ internal class CallHttpClient(
28
+ /**
29
+ * Read per request, not captured: a later `configure()` with another
30
+ * API origin (staging ↔ prod switch) takes effect on the next call
31
+ * without rebuilding the process-wide runtime.
32
+ */
33
+ private val baseUrl: () -> String,
34
+ private val client: OkHttpClient = defaultClient(),
35
+ ) : HttpPort {
36
+
37
+ override fun answer(callId: String, grant: String, cb: (HttpResult) -> Unit) =
38
+ post("calls/$callId/answer", grant, body = null, cb = cb)
39
+
40
+ override fun join(callId: String, sessionToken: String, cb: (HttpResult) -> Unit) =
41
+ post("calls/$callId/join", sessionToken, body = null, cb = cb)
42
+
43
+ override fun place(
44
+ conversationId: String,
45
+ media: String,
46
+ sessionToken: String,
47
+ cb: (HttpResult) -> Unit,
48
+ ) = post(
49
+ "conversations/$conversationId/calls",
50
+ sessionToken,
51
+ body = JSONObject().put("media", media),
52
+ cb = cb,
53
+ )
54
+
55
+ override fun reconnect(current: CallSessionBundle, cb: (HttpResult) -> Unit) =
56
+ post("calls/${current.callId}/reconnect", current.controlToken, body = null, current = current, cb = cb)
57
+
58
+ override fun decline(callId: String, auth: String, busy: Boolean) =
59
+ postBestEffort(
60
+ "calls/$callId/decline",
61
+ auth,
62
+ JSONObject().put("reason", if (busy) "busy" else "declined"),
63
+ )
64
+
65
+ override fun hangup(callId: String, controlToken: String) =
66
+ postBestEffort("calls/$callId/hangup", controlToken, body = null)
67
+
68
+ // ── request/response ────────────────────────────────────────────────
69
+
70
+ private fun post(
71
+ path: String,
72
+ token: String,
73
+ body: JSONObject?,
74
+ current: CallSessionBundle? = null,
75
+ cb: (HttpResult) -> Unit,
76
+ ) {
77
+ val req = runCatching { request(path, token, body) }.getOrElse {
78
+ // A malformed base URL is a configuration error, not a timeout:
79
+ // retrying cannot fix it.
80
+ cb(HttpResult.Failed("bad_url")); return
81
+ }
82
+ client.newCall(req).enqueue(object : Callback {
83
+ override fun onFailure(call: Call, e: IOException) = cb(HttpResult.Timeout)
84
+
85
+ override fun onResponse(call: Call, response: Response) {
86
+ val result = runCatching {
87
+ response.use { classify(it.code, it.body?.string(), current) }
88
+ }.getOrElse { HttpResult.Timeout } // body read failed mid-stream: transient
89
+ cb(result)
90
+ }
91
+ })
92
+ }
93
+
94
+ // ── fire-and-forget with bounded retry ──────────────────────────────
95
+
96
+ private fun postBestEffort(path: String, token: String, body: JSONObject?, attempt: Int = 0) {
97
+ val req = runCatching { request(path, token, body) }.getOrNull() ?: return
98
+ client.newCall(req).enqueue(object : Callback {
99
+ override fun onFailure(call: Call, e: IOException) {
100
+ if (attempt < MAX_BEST_EFFORT_RETRIES) postBestEffort(path, token, body, attempt + 1)
101
+ }
102
+
103
+ override fun onResponse(call: Call, response: Response) {
104
+ response.use {
105
+ // 2xx and 4xx are both terminal here — the server either acted
106
+ // or will never act. Only transient 5xx/timeout retries.
107
+ if ((it.code == 408 || it.code == 429 || it.code in 500..599) &&
108
+ attempt < MAX_BEST_EFFORT_RETRIES
109
+ ) {
110
+ postBestEffort(path, token, body, attempt + 1)
111
+ }
112
+ }
113
+ }
114
+ })
115
+ }
116
+
117
+ private fun request(path: String, token: String, body: JSONObject?): Request =
118
+ Request.Builder()
119
+ .url("${baseUrl().trimEnd('/')}/v1/$path")
120
+ .header("Authorization", "Bearer $token")
121
+ .header("Accept", "application/json")
122
+ .post((body?.toString() ?: "{}").toRequestBody(JSON))
123
+ .build()
124
+
125
+ internal companion object {
126
+ const val MAX_BEST_EFFORT_RETRIES = 3
127
+ val JSON = "application/json; charset=utf-8".toMediaType()
128
+
129
+ fun defaultClient(): OkHttpClient = OkHttpClient.Builder()
130
+ // A call action must not hang the ring surface. Short, deliberate
131
+ // ceilings; the runtime retries answer/place once on top of these,
132
+ // and both attempts fit inside its 20 s CONNECTING watchdog.
133
+ .callTimeout(java.time.Duration.ofSeconds(9))
134
+ .connectTimeout(java.time.Duration.ofSeconds(6))
135
+ .build()
136
+
137
+ /**
138
+ * Status + body → [HttpResult] (CALL_CONTRACT.md §4). Pure, so it is unit
139
+ * tested without a network.
140
+ *
141
+ * - 2xx that will not parse is [HttpResult.Failed], NOT a timeout:
142
+ * retrying an identical request returns the identical body, and
143
+ * treating it as transient left the UI stuck in connecting.
144
+ * - 404/410: the call (or this device's place in it) is gone.
145
+ * - 401/403: auth refused — `failed`, never `finished`.
146
+ * - 503: no SFU capacity / maintenance — terminal for this attempt.
147
+ */
148
+ fun classify(code: Int, payload: String?, current: CallSessionBundle? = null): HttpResult =
149
+ when (code) {
150
+ in 200..299 -> runCatching { HttpResult.Ok(parseBundle(payload, current)) }
151
+ .getOrElse { HttpResult.Failed("bad_body") }
152
+ 404, 410 -> HttpResult.Gone
153
+ 401, 403 -> HttpResult.AuthFailed(errorCode(payload) ?: "http_$code")
154
+ 503 -> HttpResult.Failed(errorCode(payload) ?: "http_503")
155
+ 408, 429, in 500..599 -> HttpResult.Timeout
156
+ else -> HttpResult.Failed(errorCode(payload) ?: "http_$code")
157
+ }
158
+
159
+ /**
160
+ * One parser for answer, join, place AND reconnect: the server now
161
+ * returns the full bundle on reconnect too. An older server's
162
+ * reconnect answered only `{livekit:{url,token}}` (maybe a fresh
163
+ * `control_token`); with [current] given, that is applied onto the
164
+ * existing bundle instead of failing.
165
+ */
166
+ fun parseBundle(payload: String?, current: CallSessionBundle? = null): CallSessionBundle {
167
+ val root = JSONObject(requireNotNull(payload) { "empty success body" })
168
+ val livekit = root.getJSONObject("livekit")
169
+ val call = root.optJSONObject("call")
170
+ if (call == null) {
171
+ requireNotNull(current) { "bundle without call" }
172
+ return current.copy(
173
+ livekitUrl = livekit.optStringOrNull("url") ?: current.livekitUrl,
174
+ livekitToken = livekit.getString("token"),
175
+ controlToken = root.optStringOrNull("control_token") ?: current.controlToken,
176
+ ringing = 0,
177
+ )
178
+ }
179
+ return CallSessionBundle(
180
+ callId = call.getString("id"),
181
+ conversationId = call.getString("conversation_id"),
182
+ conversationName = call.optStringOrNull("conversation_name") ?: current?.conversationName,
183
+ media = call.optStringOrNull("media") ?: current?.media ?: "audio",
184
+ created = root.optBoolean("created", true),
185
+ livekitUrl = livekit.getString("url"),
186
+ livekitToken = livekit.getString("token"),
187
+ controlToken = root.optStringOrNull("control_token")
188
+ ?: requireNotNull(current?.controlToken) { "bundle without control_token" },
189
+ kind = call.optStringOrNull("kind") ?: current?.kind ?: "call",
190
+ ringing = call.optJSONObject("ring_states")?.let { states ->
191
+ states.keys().asSequence().count { states.optString(it) == "ringing" }
192
+ } ?: 0,
193
+ )
194
+ }
195
+
196
+ /** The server's envelope is `{"error":{"code":"…"}}`; tolerate a bare string too. */
197
+ fun errorCode(payload: String?): String? = payload?.let {
198
+ runCatching {
199
+ val root = JSONObject(it)
200
+ root.optJSONObject("error")?.optStringOrNull("code") ?: root.optStringOrNull("error")
201
+ }.getOrNull()
202
+ }
203
+
204
+ private fun JSONObject.optStringOrNull(key: String): String? =
205
+ if (!has(key) || isNull(key)) null else (opt(key) as? String)?.ifEmpty { null }
206
+ }
207
+ }
@@ -0,0 +1,161 @@
1
+ package dev.poolse.callcore.android
2
+
3
+ import com.google.firebase.messaging.FirebaseMessagingService
4
+ import com.google.firebase.messaging.RemoteMessage
5
+ import dev.poolse.callcore.RingContext
6
+
7
+ /**
8
+ * Native FCM intake — the point of the whole architecture. A call data
9
+ * message is handled here, in native code, the instant it arrives: no
10
+ * headless JS, no boot race, no millisecond budget spent waiting for
11
+ * Hermes. Non-call messages are forwarded to the host app's own
12
+ * messaging service (declared via metadata), so chat notifications and
13
+ * everything else keep working unchanged.
14
+ *
15
+ * Contract: data-only messages — rings with `type: "call"`, control
16
+ * pushes (`ring_ended`, `finished`) and the missed-call notification
17
+ * (`missed`) with `type: "call_event"` (CALL_CONTRACT.md §5).
18
+ */
19
+ class CallMessagingService : FirebaseMessagingService() {
20
+
21
+ override fun onNewToken(token: String) {
22
+ // Registration is the app's concern (it knows the session); it reads
23
+ // the fresh token from the bridge's token API. Nothing to do here.
24
+ forwardToHost { it.onNewToken(token) }
25
+ }
26
+
27
+ override fun onDeletedMessages() {
28
+ // FCM dropped queued messages; the host's own sync logic needs to know.
29
+ forwardToHost { it.onDeletedMessages() }
30
+ }
31
+
32
+ override fun onMessageReceived(message: RemoteMessage) {
33
+ val data = message.data
34
+ // Rings ride type=call; control pushes (ring_ended, finished) ride
35
+ // type=call_event so old JS Android builds — which ring on ANY
36
+ // type=call — ignore them. Everything else belongs to the host.
37
+ val type = data["type"]
38
+ if (type == "message") {
39
+ // Chat notifications (§5.5): posted here so they appear with the
40
+ // app killed, grouped per conversation.
41
+ if (CallCore.getOrNull(this) == null) return
42
+ val conversationId = data["conversation_id"] ?: return
43
+ when (data["event"]) {
44
+ "new" -> MessageNotifications.onNew(this, data, CallCore.smallIcon(this))
45
+ "read" -> MessageNotifications.clear(this, conversationId)
46
+ }
47
+ return
48
+ }
49
+ if (type != "call" && type != "call_event") {
50
+ forwardToHost { it.onMessageReceived(message) }
51
+ return
52
+ }
53
+
54
+ // Never configured on this install: nothing can answer a call, and
55
+ // throwing here would crash the messaging process.
56
+ val core = CallCore.getOrNull(this) ?: return
57
+ if (data["event"] == "missed") {
58
+ // A notification, not call state: the call is already over.
59
+ MissedCallNotification.show(this, data, CallCore.smallIcon(this))
60
+ return
61
+ }
62
+ // A type=call push without an event is a legacy-shaped ring.
63
+ val event = data["event"]?.ifEmpty { null } ?: if (type == "call") "ring" else return
64
+ when (event) {
65
+ // ring_ended reasons: cancelled | answered_elsewhere | declined |
66
+ // timeout | finished. The machine only lets them end a RINGING_IN,
67
+ // so an answered_elsewhere echo of THIS device's own answer
68
+ // (optional device_id) can never end a call we already answered.
69
+ "ring" -> data.toRingContext()?.let(core::onRing)
70
+ "ring_ended" -> {
71
+ val callId = data["call_id"] ?: return
72
+ core.onRingEnded(callId, data["reason"] ?: "finished")
73
+ }
74
+ // The call is over for everyone (CALL_CONTRACT.md §5.3). Ends an active
75
+ // or ringing-out call, and tears down any ring surface still up.
76
+ "finished" -> {
77
+ val callId = data["call_id"] ?: return
78
+ core.onCallFinished(callId, data["reason"]?.ifEmpty { null })
79
+ }
80
+ }
81
+ }
82
+
83
+ private fun Map<String, String>.toRingContext(): RingContext? {
84
+ val callId = this["call_id"] ?: return null
85
+ val conversationId = this["conversation_id"] ?: return null
86
+ val grant = this["grant"] ?: return null
87
+ return RingContext(
88
+ callId = callId,
89
+ conversationId = conversationId,
90
+ conversationName = this["conversation_name"]?.ifEmpty { null },
91
+ callerName = this["caller_name"]?.ifEmpty { null },
92
+ media = this["media"] ?: "audio",
93
+ grant = grant,
94
+ ringDeadlineEpochMs = this["ring_deadline"]?.toLongOrNull() ?: 0L,
95
+ )
96
+ }
97
+
98
+ /**
99
+ * Forward to the host app's declared FirebaseMessagingService so its
100
+ * own (non-call) pushes still arrive. The host names its class in the
101
+ * manifest: `<meta-data android:name="dev.poolse.callcore.delegate"
102
+ * android:value="com.app.MyMessagingService"/>` — on `<application>`
103
+ * (where config plugins put it), or on this service.
104
+ *
105
+ * Reading only the SERVICE's meta-data missed the application-level
106
+ * entry, so every chat push was silently dropped.
107
+ */
108
+ private fun forwardToHost(block: (FirebaseMessagingService) -> Unit) {
109
+ val name = delegateName() ?: run {
110
+ android.util.Log.w(TAG, "no $DELEGATE_META meta-data: non-call push dropped")
111
+ return
112
+ }
113
+
114
+ runCatching {
115
+ val delegate = Class.forName(name).getDeclaredConstructor().newInstance()
116
+ if (delegate is FirebaseMessagingService) {
117
+ // The delegate needs our context to do anything useful; FCM's
118
+ // base class resolves it from the running service, so we attach
119
+ // ours. Kept behind runCatching: a misconfigured delegate must
120
+ // never crash the call path.
121
+ delegate.attachForDelegation(this)
122
+ block(delegate)
123
+ } else {
124
+ android.util.Log.w(TAG, "$name is not a FirebaseMessagingService")
125
+ }
126
+ }.onFailure { android.util.Log.e(TAG, "delegate $name failed", it) }
127
+ }
128
+
129
+ private fun delegateName(): String? {
130
+ val pm = packageManager
131
+ val fromApp = runCatching {
132
+ pm.getApplicationInfo(packageName, android.content.pm.PackageManager.GET_META_DATA)
133
+ .metaData?.getString(DELEGATE_META)
134
+ }.getOrNull()
135
+ if (!fromApp.isNullOrEmpty()) return fromApp
136
+ return runCatching {
137
+ pm.getServiceInfo(
138
+ android.content.ComponentName(this, CallMessagingService::class.java),
139
+ android.content.pm.PackageManager.GET_META_DATA,
140
+ ).metaData?.getString(DELEGATE_META)
141
+ }.getOrNull()?.ifEmpty { null }
142
+ }
143
+
144
+ private companion object {
145
+ const val TAG = "PoolseCallFcm"
146
+ const val DELEGATE_META = "dev.poolse.callcore.delegate"
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Minimal context attach so a delegated [FirebaseMessagingService] can
152
+ * run outside its own lifecycle. Uses the base ContextWrapper hook.
153
+ */
154
+ private fun FirebaseMessagingService.attachForDelegation(host: FirebaseMessagingService) {
155
+ runCatching {
156
+ val m = android.content.ContextWrapper::class.java
157
+ .getDeclaredMethod("attachBaseContext", android.content.Context::class.java)
158
+ m.isAccessible = true
159
+ m.invoke(this, host.applicationContext)
160
+ }
161
+ }