@poolse/native 0.0.0-stage → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +206 -0
  3. package/README.md +148 -2
  4. package/android/build.gradle +58 -0
  5. package/android/consumer-rules.pro +11 -0
  6. package/android/src/main/AndroidManifest.xml +46 -0
  7. package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +540 -0
  8. package/android/src/main/java/dev/poolse/callcore/CallMachine.kt +492 -0
  9. package/android/src/main/java/dev/poolse/callcore/Ports.kt +132 -0
  10. package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +383 -0
  11. package/android/src/main/java/dev/poolse/callcore/android/CallActionReceiver.kt +45 -0
  12. package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +578 -0
  13. package/android/src/main/java/dev/poolse/callcore/android/CallForegroundService.kt +294 -0
  14. package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +207 -0
  15. package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +161 -0
  16. package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +36 -0
  17. package/android/src/main/java/dev/poolse/callcore/android/HandlerTimerPort.kt +42 -0
  18. package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +314 -0
  19. package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +353 -0
  20. package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +103 -0
  21. package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +42 -0
  22. package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +99 -0
  23. package/android/src/main/java/expo/modules/poolsecalls/CallLockscreen.kt +42 -0
  24. package/android/src/main/java/expo/modules/poolsecalls/CallPictureInPicture.kt +92 -0
  25. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallVideoView.kt +64 -0
  26. package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +205 -0
  27. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +594 -0
  28. package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitVideoSurface.kt +107 -0
  29. package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +61 -0
  30. package/app.plugin.js +5 -0
  31. package/dist/index.cjs +197 -0
  32. package/dist/index.cjs.map +1 -0
  33. package/dist/index.d.cts +313 -0
  34. package/dist/index.d.ts +313 -0
  35. package/dist/index.js +161 -0
  36. package/dist/index.js.map +1 -0
  37. package/expo-module.config.json +11 -0
  38. package/ios/Core/CallCoreRuntime.swift +543 -0
  39. package/ios/Core/CallHttpClient.swift +213 -0
  40. package/ios/Core/CallMachine.swift +394 -0
  41. package/ios/Core/PORTS_READY.md +93 -0
  42. package/ios/Core/Ports.swift +238 -0
  43. package/ios/Core/SnapshotEncoding.swift +122 -0
  44. package/ios/Module/PoolseCallVideoView.swift +70 -0
  45. package/ios/Module/PoolseCallsAppDelegateSubscriber.swift +16 -0
  46. package/ios/Module/PoolseCallsModule.swift +150 -0
  47. package/ios/Platform/CallCore.swift +623 -0
  48. package/ios/Platform/CallKitController.swift +326 -0
  49. package/ios/Platform/CallPictureInPicture.swift +145 -0
  50. package/ios/Platform/LiveKitMediaPort.swift +798 -0
  51. package/ios/Platform/LiveKitVideoSurface.swift +68 -0
  52. package/ios/Platform/MessageNotifications.swift +163 -0
  53. package/ios/Platform/Ringback.swift +61 -0
  54. package/ios/Platform/VoipPush.swift +174 -0
  55. package/ios/PoolseCalls.podspec +68 -0
  56. package/package.json +53 -4
  57. package/plugin/index.js +42 -0
  58. package/plugin/package.json +1 -0
  59. package/plugin/withCallDelegate.js +35 -0
  60. package/plugin/withLockscreenCalls.js +84 -0
  61. package/plugin/withNativeCallMedia.js +19 -0
  62. package/plugin/withPictureInPicture.js +28 -0
  63. package/plugin/withRingback.js +86 -0
  64. package/src/expo-modules-core.d.ts +16 -0
  65. package/src/index.ts +564 -0
  66. package/src/react-shims.d.ts +22 -0
@@ -0,0 +1,540 @@
1
+ package dev.poolse.callcore
2
+
3
+ /**
4
+ * The engine around the machine: owns the state, serializes events,
5
+ * executes effects through the ports, runs the timers, and emits a
6
+ * snapshot after every change.
7
+ *
8
+ * The machine decides; this class merely obeys — there is deliberately
9
+ * no call logic here beyond bookkeeping the effects need (which grant
10
+ * answers which call, which control token hangs up, which HTTP answer
11
+ * belongs to which call). If behavior is wrong, the fix is in
12
+ * CallMachine + vectors, not here.
13
+ *
14
+ * Threading: ONE serial queue, no lock. Every input — FCM, binder taps,
15
+ * OkHttp callbacks, SFU events, timers, JS commands — is [post]ed onto
16
+ * [executor] (on Android the main looper). The previous lock let a port
17
+ * that answered synchronously re-enter `dispatch` mid-effect-list, so
18
+ * a later effect ran against a state the earlier one had already moved
19
+ * on. Now a result produced while effects execute is QUEUED behind the
20
+ * current dispatch, never run inside it, and each dispatch emits its
21
+ * snapshot only after its last effect. Tests pass a direct executor;
22
+ * the internal trampoline gives them the same ordering.
23
+ */
24
+ class CallCoreRuntime(
25
+ private val http: HttpPort,
26
+ private val media: MediaPort,
27
+ private val surface: RingSurfacePort,
28
+ private val session: CallSessionPort,
29
+ private val timers: TimerPort,
30
+ private val sink: SnapshotSink,
31
+ /** Runs a task on the single runtime thread. Must be serial. */
32
+ private val executor: (Runnable) -> Unit = { it.run() },
33
+ /** Where a crashing task is reported; the queue keeps draining regardless. */
34
+ private val onError: (Throwable) -> Unit = {},
35
+ ) {
36
+ // Read from any thread (the bridge's getCallState); written only on
37
+ // the runtime thread.
38
+ @Volatile private var state: MachineState = MachineState.IDLE
39
+
40
+ /** The ring being shown (its grant answers/declines it). */
41
+ private var ring: RingContext? = null
42
+
43
+ /** Grants of rings auto-declined busy, kept until the decline fires. */
44
+ private val busyRings = mutableMapOf<String, RingContext>()
45
+
46
+ /** The ring of the call waiting beside the current one (its grant answers or busy-declines it). */
47
+ private var waitingRingCtx: RingContext? = null
48
+
49
+ /** The session bundle of the current call, once the server accepted. */
50
+ // Volatile: [control] is read from the bridge's thread.
51
+ @Volatile private var bundle: CallSessionBundle? = null
52
+
53
+ /** The session token place/join were called with, for one retry. */
54
+ private var sessionToken: String? = null
55
+
56
+ /**
57
+ * Call generation: bumped whenever a call starts CONNECTING and
58
+ * whenever one ends. HTTP callbacks and timers capture it, so a late
59
+ * answer/place response or timer of a call that already ended can
60
+ * never be adopted by — or end — the next one.
61
+ */
62
+ private var gen = 0
63
+
64
+ /**
65
+ * callIds already resolved on this device (ended, declined, timed
66
+ * out, rung-off remotely, busy-declined). Push + socket + FCM's own
67
+ * redelivery can hand us the same ring several times, sometimes after
68
+ * the call is over; a bounded LRU drops those instead of re-ringing.
69
+ */
70
+ /** The call whose media has had someone else in it (for [onRemoteCount]). */
71
+ private var remoteSeenFor: String? = null
72
+
73
+ private val resolved = object : LinkedHashMap<String, Unit>(RESOLVED_LRU, 0.75f, true) {
74
+ override fun removeEldestEntry(eldest: MutableMap.MutableEntry<String, Unit>?) = size > RESOLVED_LRU
75
+ }
76
+
77
+ // ── serial queue ────────────────────────────────────────────────────
78
+
79
+ private val queue = ArrayDeque<() -> Unit>()
80
+ private var draining = false
81
+
82
+ /** Run [block] on the runtime thread, after anything already queued. */
83
+ fun post(block: () -> Unit) {
84
+ executor(Runnable { enqueue(block) })
85
+ }
86
+
87
+ private fun enqueue(block: () -> Unit) {
88
+ queue.addLast(block)
89
+ if (draining) return // a dispatch is executing: run after it, not inside it
90
+ draining = true
91
+ try {
92
+ while (queue.isNotEmpty()) {
93
+ val next = queue.removeFirst()
94
+ try { next() } catch (t: Throwable) { onError(t) }
95
+ }
96
+ } finally {
97
+ draining = false
98
+ }
99
+ }
100
+
101
+ companion object {
102
+ const val ENDED_LINGER_MS = 2_500L
103
+ const val RECONNECT_BUDGET_MS = 25_000L
104
+ /** CONNECTING watchdog: two HTTP attempts plus an SFU connect fit inside. */
105
+ const val CONNECT_WATCHDOG_MS = 20_000L
106
+ /** Caller-side backstop if the server's finish/no-answer never arrives. */
107
+ const val RING_OUT_BACKSTOP_MS = 75_000L
108
+ /**
109
+ * Device clocks drift; the deadline is server epoch. A ring this
110
+ * close past its deadline still shows (for at least this long) —
111
+ * the server's ring_ended(timeout) is the real cut-off.
112
+ */
113
+ const val CLOCK_SLACK_MS = 10_000L
114
+ const val RESOLVED_LRU = 32
115
+ private const val T_DEADLINE = "ring_deadline"
116
+ private const val T_LINGER = "linger"
117
+ private const val T_RECONNECT = "reconnect_budget"
118
+ private const val T_CONNECT = "connect_watchdog"
119
+ private const val T_RING_OUT = "ring_out_backstop"
120
+ private const val T_WAITING = "waiting_deadline"
121
+ private const val T_ALONE = "alone_probe"
122
+ /**
123
+ * Alone in a call: ask the server after a moment (the other side's own
124
+ * reconnect gets that long); still alone this much later, leave — a
125
+ * call with one person in it is over, whatever the server thinks.
126
+ */
127
+ val ALONE_PROBES_MS = longArrayOf(3_000L, 9_000L)
128
+
129
+ /**
130
+ * …unless someone is being rung into it: ask again this often until
131
+ * they pick up or it rings out.
132
+ */
133
+ const val ALONE_RINGING_RECHECK_MS = 5_000L
134
+ }
135
+
136
+ // ── inputs from adapters ────────────────────────────────────────────
137
+
138
+ fun currentState(): MachineState = state
139
+
140
+ /** Best name for the current call: the server's bundle, else the ring's. Runtime thread only. */
141
+ val conversationName: String? get() = bundle?.conversationName ?: ring?.conversationName
142
+
143
+ /** `room` or `call`, once the server's bundle says; null before. Runtime thread only. */
144
+ val callKind: String? get() = bundle?.kind
145
+
146
+ /**
147
+ * The current call's id and control token — what authorizes acting on
148
+ * the call itself (ringing more people in). Null with no session yet.
149
+ * Safe from any thread.
150
+ */
151
+ val control: Pair<String, String>? get() = bundle?.let { it.callId to it.controlToken }
152
+
153
+ /** The call waiting beside the current one, with its caller's names. Runtime thread only. */
154
+ val waitingRing: RingContext? get() = if (state.waiting == null) null else waitingRingCtx
155
+
156
+ /** True if [callId] was already resolved here — its ring must never surface again. */
157
+ fun isResolved(callId: String): Boolean = synchronized(resolved) { resolved.containsKey(callId) }
158
+
159
+ private fun markResolved(callId: String?) {
160
+ if (callId == null || callId.startsWith("pending:")) return
161
+ synchronized(resolved) { resolved[callId] = Unit }
162
+ }
163
+
164
+ /** A ring arrived — push or socket, the machine treats them alike. */
165
+ fun onRing(ctx: RingContext) = post {
166
+ if (isResolved(ctx.callId)) return@post
167
+ // A late duplicate of the ring for the call we are already IN must
168
+ // not reach the machine: it would read as "another call while busy"
169
+ // and busy-decline our own call.
170
+ val s = state
171
+ if (s.callId == ctx.callId && s.phase != Phase.IDLE && s.phase != Phase.RINGING_IN) return@post
172
+
173
+ val stale = ctx.ringDeadlineEpochMs + CLOCK_SLACK_MS <= timers.nowMs()
174
+ // Remember the context BEFORE dispatch: the effects need it —
175
+ // SHOW_RING for this call, or HTTP_DECLINE_BUSY for another.
176
+ if (!stale) busyRings[ctx.callId] = ctx
177
+ dispatch(
178
+ Event.Ring(
179
+ callId = ctx.callId,
180
+ conversationId = ctx.conversationId,
181
+ media = ctx.media,
182
+ stale = stale,
183
+ ),
184
+ ringCtx = ctx,
185
+ )
186
+ busyRings.remove(ctx.callId)
187
+ }
188
+
189
+ fun onRingEnded(callId: String, reason: String) = post {
190
+ dispatch(Event.RingEnded(callId, reason))
191
+ markResolved(callId)
192
+ }
193
+
194
+ fun onCallFinished(callId: String, reason: String? = null) = post {
195
+ dispatch(Event.CallFinished(callId, reason))
196
+ markResolved(callId)
197
+ }
198
+
199
+ fun answer() = post { dispatch(Event.UserAnswer) }
200
+ fun decline() = post { dispatch(Event.UserDecline) }
201
+ fun hangUp() = post { dispatch(Event.UserHangup) }
202
+ /**
203
+ * Call waiting: end this call and answer the one waiting. With
204
+ * [callId], only if that is still the call waiting (a stale tap on a
205
+ * surface for an earlier one must not answer a different call).
206
+ */
207
+ fun answerWaiting(callId: String? = null) = post {
208
+ if (callId == null || state.waiting?.callId == callId) dispatch(Event.UserAnswerWaiting)
209
+ }
210
+ /** Call waiting: turn the waiting call away (its caller hears busy). */
211
+ fun declineWaiting(callId: String? = null) = post {
212
+ if (callId == null || state.waiting?.callId == callId) dispatch(Event.UserDeclineWaiting)
213
+ }
214
+
215
+ fun place(conversationId: String, media: String, sessionToken: String) = post {
216
+ if (state.phase != Phase.IDLE && state.phase != Phase.ENDED) return@post
217
+ this.sessionToken = sessionToken
218
+ // call_id is server-minted on place; a placeholder keys the state
219
+ // until the bundle arrives.
220
+ dispatch(Event.UserPlace(callId = "pending:$conversationId", conversationId = conversationId, media = media))
221
+ }
222
+
223
+ fun join(callId: String, conversationId: String?, sessionToken: String) = post {
224
+ if (state.phase != Phase.IDLE && state.phase != Phase.ENDED) return@post
225
+ this.sessionToken = sessionToken
226
+ dispatch(Event.UserJoin(callId, conversationId))
227
+ }
228
+
229
+ /** Caller-side: the bridge resolved every ring from `ring_states`. */
230
+ fun allRingsResolved(outcome: String) = post { dispatch(Event.AllRingsResolved(outcome)) }
231
+
232
+ fun onMediaConnected() = post { dispatch(Event.MediaConnected) }
233
+ fun onMediaFailed() = post { dispatch(Event.MediaFailed) }
234
+ fun onMediaLost() = post { dispatch(Event.MediaLost) }
235
+ fun onMediaReconnecting() = post { dispatch(Event.MediaReconnecting) }
236
+ fun onMediaRecovered() = post { dispatch(Event.MediaRecovered) }
237
+ fun onRemoteJoined() = post { dispatch(Event.RemoteJoined) }
238
+
239
+ /**
240
+ * The media's remote roster changed: [remotes] other people in it.
241
+ *
242
+ * Everyone else gone from a call (not a room) usually means it is over
243
+ * — and this device may never be told: an iPhone gets no `finished`
244
+ * push, and the conversation channel that carries the socket event can
245
+ * have been left. So, alone, ask the server (the reconnect endpoint
246
+ * answers 410 for a call that is over) and end here as finished if so.
247
+ * If the server still calls it live (it never heard the other side
248
+ * leave), leave anyway shortly after: one person is not a call —
249
+ * unless someone is still being rung, who is worth waiting for.
250
+ * Someone back in the room cancels the check.
251
+ */
252
+ fun onRemoteCount(remotes: Int) = post {
253
+ val callId = state.callId ?: return@post
254
+ if (remotes > 0) {
255
+ remoteSeenFor = callId
256
+ timers.cancel(T_ALONE)
257
+ return@post
258
+ }
259
+ if (state.phase != Phase.ACTIVE || callKind == "room" || remoteSeenFor != callId) return@post
260
+ scheduleAloneProbe(callId, 0)
261
+ }
262
+
263
+ private fun scheduleAloneProbe(callId: String, attempt: Int, delayMs: Long? = null) {
264
+ if (attempt >= ALONE_PROBES_MS.size) return
265
+ val g = gen
266
+ timers.schedule(T_ALONE, delayMs ?: ALONE_PROBES_MS[attempt]) {
267
+ post { if (g == gen && state.callId == callId) probeAlone(callId, attempt) }
268
+ }
269
+ }
270
+
271
+ private fun probeAlone(callId: String, attempt: Int) {
272
+ if (state.phase != Phase.ACTIVE) return
273
+ val b = bundle ?: return
274
+ val g = gen
275
+ val last = attempt == ALONE_PROBES_MS.size - 1
276
+ // A still-live answer carries a fresh bundle; the current one stays
277
+ // in use (its token is still good), so it is dropped.
278
+ http.reconnect(b) { res ->
279
+ post {
280
+ if (g != gen || state.callId != callId) return@post
281
+ when {
282
+ res == HttpResult.Gone -> dispatch(Event.CallFinished(callId, "finished"))
283
+ res is HttpResult.Ok && res.bundle.ringing > 0 ->
284
+ scheduleAloneProbe(callId, 0, ALONE_RINGING_RECHECK_MS)
285
+ last -> leaveAlone(callId)
286
+ else -> scheduleAloneProbe(callId, attempt + 1)
287
+ }
288
+ }
289
+ }
290
+ }
291
+
292
+ private fun leaveAlone(callId: String) {
293
+ if (state.phase != Phase.ACTIVE) return
294
+ val b = bundle ?: return
295
+ http.hangup(b.callId, b.controlToken)
296
+ dispatch(Event.CallFinished(callId, "finished"))
297
+ }
298
+
299
+ fun setMuted(muted: Boolean) = post { media.setMuted(muted) }
300
+ fun setCamera(on: Boolean) = post { media.setCamera(on) }
301
+ fun switchCamera() = post { media.switchCamera() }
302
+ fun setSpeaker(on: Boolean) = post { media.setSpeaker(on) }
303
+ fun setAudioOutput(id: String) = post { media.setAudioOutput(id) }
304
+
305
+ /** Re-emit the current state (the bridge's roster/route changed). */
306
+ fun reemit() = post { if (state.phase != Phase.IDLE) sink.emit(state) }
307
+
308
+ // ── dispatch ────────────────────────────────────────────────────────
309
+
310
+ private fun isTerminal(p: Phase) = p == Phase.IDLE || p == Phase.ENDED
311
+
312
+ private fun dispatch(event: Event, ringCtx: RingContext? = null) {
313
+ val before = state
314
+ val (next, effects) = CallMachine.transition(before, event)
315
+ state = next
316
+ // A new call attempt, or the end of one: old callbacks go stale.
317
+ if (next.phase == Phase.CONNECTING && before.phase != Phase.CONNECTING) gen++
318
+ if (isTerminal(next.phase) && !isTerminal(before.phase)) {
319
+ gen++
320
+ markResolved(before.callId)
321
+ }
322
+ for (effect in effects) execute(effect, ringCtx, before)
323
+ // Retire the ring grant only after EVERY effect has had its chance
324
+ // to use it. CONNECTING keeps it (answer + the no-bundle hangup
325
+ // fallback still need it); CallSessionStop clears it with the rest.
326
+ if (isTerminal(next.phase)) ring = null
327
+ // A bundle never outlives its call — whatever ended it.
328
+ if (isTerminal(next.phase)) { bundle = null; sessionToken = null }
329
+ // A waiting call that went away without becoming the current one
330
+ // (declined, cancelled, timed out) is resolved: its ring never again.
331
+ before.waiting?.let { w ->
332
+ if (next.waiting?.callId != w.callId && next.callId != w.callId) markResolved(w.callId)
333
+ }
334
+ if (next.waiting == null) waitingRingCtx = null
335
+ runTimers(before, next)
336
+ if (next != before || effects.isNotEmpty()) sink.emit(next)
337
+ }
338
+
339
+ private fun execute(effect: Effect, ringCtx: RingContext?, before: MachineState) {
340
+ val g = gen
341
+ when (effect) {
342
+ Effect.ShowRing -> {
343
+ // A promoted waiting call rings with the ring already on file.
344
+ if (ringCtx != null) ring = ringCtx
345
+ ring?.let(surface::show)
346
+ }
347
+ Effect.DismissRing -> {
348
+ (ring ?: ringCtx)?.let { surface.dismiss(it.callId) }
349
+ // The grant is NOT retired here: HTTP_DECLINE may still be
350
+ // later in this very effect list (dismiss-then-decline), and
351
+ // clearing mid-list silently dropped the decline — the exact
352
+ // "rejection never reached the caller" bug, reborn. Retirement
353
+ // happens once, after the whole list, in dispatch().
354
+ }
355
+ Effect.RingtoneStart -> surface.ringtoneStart()
356
+ Effect.RingtoneStop -> surface.ringtoneStop()
357
+ Effect.RingbackStart -> surface.ringbackStart()
358
+ Effect.RingbackStop -> surface.ringbackStop()
359
+
360
+ Effect.HttpAnswer -> {
361
+ val r = ring
362
+ if (r != null) http.answer(r.callId, r.grant) { res -> post { onHttpResult(g, res) } }
363
+ else post { onHttpResult(g, HttpResult.AuthFailed("no_grant")) }
364
+ }
365
+ Effect.HttpJoin -> {
366
+ val callId = state.callId
367
+ val token = sessionToken
368
+ if (callId != null && token != null) http.join(callId, token) { res -> post { onHttpResult(g, res) } }
369
+ else post { onHttpResult(g, HttpResult.AuthFailed("no_session")) }
370
+ }
371
+ Effect.HttpPlace -> {
372
+ val conversationId = state.conversationId
373
+ val token = sessionToken
374
+ if (conversationId != null && token != null) {
375
+ http.place(conversationId, state.media, token) { res -> post { onHttpResult(g, res) } }
376
+ } else post { onHttpResult(g, HttpResult.AuthFailed("no_session")) }
377
+ }
378
+ Effect.HttpDecline -> {
379
+ ring?.let { http.decline(it.callId, it.grant, busy = false) }
380
+ }
381
+ is Effect.HttpDeclineBusy -> {
382
+ val waitingMatch = waitingRingCtx?.takeIf { it.callId == effect.callId }
383
+ (busyRings[effect.callId] ?: waitingMatch)?.let { http.decline(it.callId, it.grant, busy = true) }
384
+ markResolved(effect.callId)
385
+ }
386
+ Effect.HttpHangup -> {
387
+ val b = bundle
388
+ val r = ring
389
+ when {
390
+ b != null -> http.hangup(b.callId, b.controlToken)
391
+ // Hanging up a connecting answer that has no bundle yet:
392
+ // resolve the ring instead, so the caller is not left waiting.
393
+ // (The answer's late 2xx is hung up in onHttpResult.)
394
+ r != null -> http.decline(r.callId, r.grant, busy = false)
395
+ else -> Unit
396
+ }
397
+ }
398
+ Effect.HttpReconnect -> {
399
+ val b = bundle
400
+ if (b != null) http.reconnect(b) { res -> post { onReconnectResult(g, res) } }
401
+ else post { if (g == gen) dispatch(Event.HttpGone) }
402
+ }
403
+
404
+ Effect.MediaJoin -> bundle?.let(media::join)
405
+ Effect.MediaLeave -> media.leave()
406
+
407
+ Effect.CallSessionStart -> session.start(state.callId ?: "", state.media)
408
+ Effect.CallSessionStop -> {
409
+ session.stop()
410
+ bundle = null
411
+ ring = null
412
+ sessionToken = null
413
+ }
414
+
415
+ Effect.ShowWaiting -> {
416
+ waitingRingCtx = ringCtx
417
+ ringCtx?.let(surface::showWaiting)
418
+ }
419
+ // The grant is NOT retired here: HTTP_DECLINE_BUSY may precede or follow.
420
+ Effect.DismissWaiting -> before.waiting?.let { surface.dismissWaiting(it.callId) }
421
+ Effect.PromoteWaiting -> {
422
+ // The old call is over: nothing it started may land on this one.
423
+ markResolved(before.callId)
424
+ gen++
425
+ bundle = null
426
+ sessionToken = null
427
+ ring = waitingRingCtx
428
+ waitingRingCtx = null
429
+ before.waiting?.let { surface.promoteWaiting(it.callId) }
430
+ }
431
+ }
432
+ }
433
+
434
+ private fun onHttpResult(requestGen: Int, result: HttpResult) {
435
+ if (requestGen != gen) {
436
+ // The call this request belonged to is over (the user hung up
437
+ // while it was in flight). The server may still have let us in:
438
+ // leave, with the token it just gave us, and keep nothing.
439
+ if (result is HttpResult.Ok) http.hangup(result.bundle.callId, result.bundle.controlToken)
440
+ return
441
+ }
442
+ when (result) {
443
+ is HttpResult.Ok -> {
444
+ val existing = bundle
445
+ if (existing != null) {
446
+ // The timeout retry's twin answered too. Same call: ignore.
447
+ // Somehow a different one: we are not in it — leave it.
448
+ if (existing.callId != result.bundle.callId) {
449
+ http.hangup(result.bundle.callId, result.bundle.controlToken)
450
+ }
451
+ return
452
+ }
453
+ if (state.phase != Phase.CONNECTING) {
454
+ http.hangup(result.bundle.callId, result.bundle.controlToken)
455
+ return
456
+ }
457
+ bundle = result.bundle
458
+ // The server is the authority on the call's identity: the real
459
+ // id minted on place, and — for a join, which starts with only a
460
+ // call id and an "audio" default — its conversation and media.
461
+ // A video join left as "audio" took the earpiece wake lock, said
462
+ // "Voice call" and hid the camera; a null conversationId broke JS.
463
+ val b = result.bundle
464
+ state = state.copy(callId = b.callId, conversationId = b.conversationId, media = b.media)
465
+ dispatch(Event.HttpOk(created = b.created))
466
+ }
467
+ HttpResult.Gone -> dispatch(Event.HttpGone)
468
+ HttpResult.Timeout -> dispatch(Event.HttpTimeout)
469
+ is HttpResult.AuthFailed -> dispatch(Event.HttpFailed(result.code))
470
+ is HttpResult.Failed -> dispatch(Event.HttpFailed(result.code))
471
+ }
472
+ }
473
+
474
+ private fun onReconnectResult(requestGen: Int, result: HttpResult) {
475
+ if (requestGen != gen || state.phase != Phase.RECONNECTING) return
476
+ when (result) {
477
+ is HttpResult.Ok -> {
478
+ // Fresh token (and possibly URL): rejoin with it. MEDIA_CONNECTED
479
+ // on the new room returns us to ACTIVE.
480
+ bundle = result.bundle
481
+ media.join(result.bundle)
482
+ }
483
+ HttpResult.Gone -> dispatch(Event.HttpGone)
484
+ is HttpResult.AuthFailed -> dispatch(Event.HttpFailed(result.code))
485
+ // Transient: the reconnect budget timer is the backstop.
486
+ HttpResult.Timeout, is HttpResult.Failed -> Unit
487
+ }
488
+ }
489
+
490
+ // ── timers ──────────────────────────────────────────────────────────
491
+
492
+ private fun schedule(key: String, delayMs: Long, event: Event) {
493
+ val g = gen
494
+ // The timer fires on its own thread; hop onto the queue, and only
495
+ // act if it is still the same call (a cancel can lose the race).
496
+ timers.schedule(key, delayMs) { post { if (g == gen) dispatch(event) } }
497
+ }
498
+
499
+ private fun runTimers(before: MachineState, after: MachineState) {
500
+ runWaitingTimer(before, after)
501
+ // A different call in the same phase (end-and-answer while connecting)
502
+ // needs its own timers: the old ones belong to a retired generation.
503
+ if (before.phase == after.phase && before.callId == after.callId) return
504
+ when (before.phase) {
505
+ Phase.RINGING_IN -> timers.cancel(T_DEADLINE)
506
+ Phase.ENDED -> timers.cancel(T_LINGER)
507
+ Phase.RECONNECTING -> timers.cancel(T_RECONNECT)
508
+ Phase.CONNECTING -> timers.cancel(T_CONNECT)
509
+ Phase.RINGING_OUT -> timers.cancel(T_RING_OUT)
510
+ else -> Unit
511
+ }
512
+ when (after.phase) {
513
+ Phase.RINGING_IN -> {
514
+ val deadline = ring?.ringDeadlineEpochMs ?: return
515
+ // Floor at the clock slack: a ring we decided is not stale
516
+ // still gets a moment on screen even if this clock runs ahead.
517
+ val delay = (deadline - timers.nowMs()).coerceAtLeast(CLOCK_SLACK_MS)
518
+ schedule(T_DEADLINE, delay, Event.RingDeadline)
519
+ }
520
+ Phase.ENDED -> schedule(T_LINGER, ENDED_LINGER_MS, Event.LingerElapsed)
521
+ Phase.RECONNECTING -> schedule(T_RECONNECT, RECONNECT_BUDGET_MS, Event.ReconnectBudgetElapsed)
522
+ Phase.CONNECTING -> schedule(T_CONNECT, CONNECT_WATCHDOG_MS, Event.ConnectTimeout)
523
+ Phase.RINGING_OUT -> schedule(T_RING_OUT, RING_OUT_BACKSTOP_MS, Event.AllRingsResolved("no_answer"))
524
+ else -> Unit
525
+ }
526
+ }
527
+
528
+ private fun runWaitingTimer(before: MachineState, after: MachineState) {
529
+ val was = before.waiting?.callId
530
+ val now = after.waiting?.callId
531
+ if (was == now) return
532
+ if (was != null) timers.cancel(T_WAITING)
533
+ val deadline = waitingRingCtx?.ringDeadlineEpochMs
534
+ if (now == null || deadline == null) return
535
+ val delay = (deadline - timers.nowMs()).coerceAtLeast(CLOCK_SLACK_MS)
536
+ // Keyed to the waiting call, not the generation: the current call may
537
+ // move on (connect, reconnect) while this one keeps waiting.
538
+ timers.schedule(T_WAITING, delay) { post { if (state.waiting?.callId == now) dispatch(Event.WaitingDeadline) } }
539
+ }
540
+ }