@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.
- package/CHANGELOG.md +25 -0
- package/LICENSE +206 -0
- package/README.md +148 -2
- package/android/build.gradle +58 -0
- package/android/consumer-rules.pro +11 -0
- package/android/src/main/AndroidManifest.xml +46 -0
- package/android/src/main/java/dev/poolse/callcore/CallCoreRuntime.kt +540 -0
- package/android/src/main/java/dev/poolse/callcore/CallMachine.kt +492 -0
- package/android/src/main/java/dev/poolse/callcore/Ports.kt +132 -0
- package/android/src/main/java/dev/poolse/callcore/android/AndroidRingSurface.kt +383 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallActionReceiver.kt +45 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallCore.kt +578 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallForegroundService.kt +294 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallHttpClient.kt +207 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallMessagingService.kt +161 -0
- package/android/src/main/java/dev/poolse/callcore/android/CallVideo.kt +36 -0
- package/android/src/main/java/dev/poolse/callcore/android/HandlerTimerPort.kt +42 -0
- package/android/src/main/java/dev/poolse/callcore/android/IncomingCallActivity.kt +314 -0
- package/android/src/main/java/dev/poolse/callcore/android/MessageNotifications.kt +353 -0
- package/android/src/main/java/dev/poolse/callcore/android/MissedCallNotification.kt +103 -0
- package/android/src/main/java/dev/poolse/callcore/android/RingBundle.kt +42 -0
- package/android/src/main/java/dev/poolse/callcore/android/SnapshotJson.kt +99 -0
- package/android/src/main/java/expo/modules/poolsecalls/CallLockscreen.kt +42 -0
- package/android/src/main/java/expo/modules/poolsecalls/CallPictureInPicture.kt +92 -0
- package/android/src/main/java/expo/modules/poolsecalls/PoolseCallVideoView.kt +64 -0
- package/android/src/main/java/expo/modules/poolsecalls/PoolseCallsModule.kt +205 -0
- package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitMediaPort.kt +594 -0
- package/android/src/main/livekit/java/dev/poolse/callcore/livekit/LiveKitVideoSurface.kt +107 -0
- package/android/src/test/java/dev/poolse/callcore/android/CallHttpClientTest.kt +61 -0
- package/app.plugin.js +5 -0
- package/dist/index.cjs +197 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +313 -0
- package/dist/index.d.ts +313 -0
- package/dist/index.js +161 -0
- package/dist/index.js.map +1 -0
- package/expo-module.config.json +11 -0
- package/ios/Core/CallCoreRuntime.swift +543 -0
- package/ios/Core/CallHttpClient.swift +213 -0
- package/ios/Core/CallMachine.swift +394 -0
- package/ios/Core/PORTS_READY.md +93 -0
- package/ios/Core/Ports.swift +238 -0
- package/ios/Core/SnapshotEncoding.swift +122 -0
- package/ios/Module/PoolseCallVideoView.swift +70 -0
- package/ios/Module/PoolseCallsAppDelegateSubscriber.swift +16 -0
- package/ios/Module/PoolseCallsModule.swift +150 -0
- package/ios/Platform/CallCore.swift +623 -0
- package/ios/Platform/CallKitController.swift +326 -0
- package/ios/Platform/CallPictureInPicture.swift +145 -0
- package/ios/Platform/LiveKitMediaPort.swift +798 -0
- package/ios/Platform/LiveKitVideoSurface.swift +68 -0
- package/ios/Platform/MessageNotifications.swift +163 -0
- package/ios/Platform/Ringback.swift +61 -0
- package/ios/Platform/VoipPush.swift +174 -0
- package/ios/PoolseCalls.podspec +68 -0
- package/package.json +53 -4
- package/plugin/index.js +42 -0
- package/plugin/package.json +1 -0
- package/plugin/withCallDelegate.js +35 -0
- package/plugin/withLockscreenCalls.js +84 -0
- package/plugin/withNativeCallMedia.js +19 -0
- package/plugin/withPictureInPicture.js +28 -0
- package/plugin/withRingback.js +86 -0
- package/src/expo-modules-core.d.ts +16 -0
- package/src/index.ts +564 -0
- package/src/react-shims.d.ts +22 -0
|
@@ -0,0 +1,578 @@
|
|
|
1
|
+
package dev.poolse.callcore.android
|
|
2
|
+
|
|
3
|
+
import android.content.Context
|
|
4
|
+
import android.content.Intent
|
|
5
|
+
import android.os.Handler
|
|
6
|
+
import android.os.Looper
|
|
7
|
+
import android.os.PowerManager
|
|
8
|
+
import android.util.Log
|
|
9
|
+
import dev.poolse.callcore.CallCoreRuntime
|
|
10
|
+
import dev.poolse.callcore.MachineState
|
|
11
|
+
import dev.poolse.callcore.MediaPort
|
|
12
|
+
import dev.poolse.callcore.Phase
|
|
13
|
+
import dev.poolse.callcore.RingContext
|
|
14
|
+
import dev.poolse.callcore.SnapshotSink
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* The composition root and the single native entry point.
|
|
18
|
+
*
|
|
19
|
+
* Everything that can originate a call action — the FCM service, the
|
|
20
|
+
* notification receiver, the full-screen activity, the React Native
|
|
21
|
+
* bridge — comes through here, so there is exactly one runtime and one
|
|
22
|
+
* answer/decline path on the device. Process-singleton, created lazily
|
|
23
|
+
* from the first caller's application context.
|
|
24
|
+
*
|
|
25
|
+
* It also owns what the pure machine deliberately does not carry but a
|
|
26
|
+
* truthful snapshot needs: the remote roster, the conversation name,
|
|
27
|
+
* self mute/camera, and the audio route. All of it lives on the
|
|
28
|
+
* runtime's single thread and is merged into every snapshot.
|
|
29
|
+
*/
|
|
30
|
+
class CallCore private constructor(context: Context) {
|
|
31
|
+
|
|
32
|
+
private val appContext = context.applicationContext
|
|
33
|
+
private val main = Handler(Looper.getMainLooper())
|
|
34
|
+
|
|
35
|
+
// The SFU is injected, not baked in: the core stays media-engine
|
|
36
|
+
// agnostic (CALL_CONTRACT.md — "LiveKit or any SFU"), and the library
|
|
37
|
+
// compiles without a specific media SDK on the classpath. The host
|
|
38
|
+
// supplies the factory; LiveKitMediaPort is the first implementation.
|
|
39
|
+
private val media: MediaPort = requireConfig().mediaFactory(appContext, mediaEvents())
|
|
40
|
+
|
|
41
|
+
// Surface + HTTP read the config on every use, so a later configure()
|
|
42
|
+
// (another API origin, icon, ringback) applies without a rebuild.
|
|
43
|
+
private val surface = AndroidRingSurface(appContext) {
|
|
44
|
+
peekConfig()?.ringSurface ?: RingSurfaceConfig(appContext.applicationInfo.icon, 0)
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
private val runtime = CallCoreRuntime(
|
|
48
|
+
http = CallHttpClient({ peekConfig()?.apiBaseUrl ?: "" }),
|
|
49
|
+
media = media,
|
|
50
|
+
surface = surface,
|
|
51
|
+
session = CallForegroundService.also { it.attach(appContext) },
|
|
52
|
+
timers = HandlerTimerPort(main),
|
|
53
|
+
sink = SnapshotSink { onState(it) },
|
|
54
|
+
// One thread for every input: the main looper — where LiveKit,
|
|
55
|
+
// the timers, the notification and the service lifecycle already
|
|
56
|
+
// live. Already on it? Run now; the runtime's trampoline still
|
|
57
|
+
// queues anything produced mid-dispatch.
|
|
58
|
+
executor = { r -> if (Looper.myLooper() == Looper.getMainLooper()) r.run() else main.post(r) },
|
|
59
|
+
onError = { Log.e(TAG, "call runtime task failed", it) },
|
|
60
|
+
)
|
|
61
|
+
|
|
62
|
+
// ── snapshot extras (runtime thread only) ───────────────────────────
|
|
63
|
+
|
|
64
|
+
private var extrasCallId: String? = null
|
|
65
|
+
private var extrasMedia: String? = null
|
|
66
|
+
private var roster: List<MediaParticipant> = emptyList()
|
|
67
|
+
private var conversationName: String? = null
|
|
68
|
+
private var callKind: String = "call"
|
|
69
|
+
|
|
70
|
+
// Video calls and rooms default to the speaker (the media port agrees).
|
|
71
|
+
private fun loud(state: MachineState) = state.media == "video" || callKind == "room"
|
|
72
|
+
private var mutedSelf = false
|
|
73
|
+
private var cameraOn = false
|
|
74
|
+
private var cameraFacing: String? = null
|
|
75
|
+
private var audioRoute: String? = null
|
|
76
|
+
private var audioOutputs: List<AudioOutput> = emptyList()
|
|
77
|
+
private var audioOutputId: String? = null
|
|
78
|
+
private var connectionQuality = "unknown"
|
|
79
|
+
private var videoPaused = false
|
|
80
|
+
|
|
81
|
+
/** Last snapshot emitted; read by the bridge's getCallState from any thread. */
|
|
82
|
+
@Volatile private var lastSnapshot: Map<String, Any?>? = null
|
|
83
|
+
|
|
84
|
+
private val proximity: PowerManager.WakeLock? = runCatching {
|
|
85
|
+
val pm = appContext.getSystemService(PowerManager::class.java)
|
|
86
|
+
if (pm.isWakeLockLevelSupported(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK)) {
|
|
87
|
+
pm.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "poolse:call-proximity")
|
|
88
|
+
.apply { setReferenceCounted(false) }
|
|
89
|
+
} else null
|
|
90
|
+
}.getOrNull()
|
|
91
|
+
|
|
92
|
+
// ── native entry points ─────────────────────────────────────────────
|
|
93
|
+
|
|
94
|
+
/** A ring arrived — from FCM (closed app) or the socket (open app). */
|
|
95
|
+
fun onRing(ring: RingContext) = runtime.onRing(ring)
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The caller withdrew, or the ring resolved elsewhere. Beyond the
|
|
99
|
+
* machine (which only knows the ring it is showing), ALWAYS tear down
|
|
100
|
+
* any surface for this call: after a process restart the notification
|
|
101
|
+
* and full-screen activity outlive the in-memory state that would
|
|
102
|
+
* otherwise dismiss them.
|
|
103
|
+
*/
|
|
104
|
+
fun onRingEnded(callId: String, reason: String) {
|
|
105
|
+
runtime.onRingEnded(callId, reason)
|
|
106
|
+
runtime.post { tearDownRing(callId) }
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** The server finished the call (push `finished` or socket `call:finished`). */
|
|
110
|
+
fun onCallFinished(callId: String, reason: String? = null) {
|
|
111
|
+
runtime.onCallFinished(callId, reason)
|
|
112
|
+
runtime.post { tearDownRing(callId) }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/**
|
|
116
|
+
* Answer from a native surface. [from] is the activity the tap
|
|
117
|
+
* landed in: the app must be brought forward from THAT context — a
|
|
118
|
+
* background start from the application context is blocked on
|
|
119
|
+
* Android 10+ and left audio connected behind the lock screen.
|
|
120
|
+
*/
|
|
121
|
+
fun onUserAnswer(ring: RingContext, from: Context? = null): Boolean {
|
|
122
|
+
runtime.onRing(ring) // idempotent: dedupes if already showing
|
|
123
|
+
runtime.answer()
|
|
124
|
+
return bringAppToFront(ring.callId, from)
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/**
|
|
128
|
+
* End & answer from the call-waiting heads-up. Only for the call still
|
|
129
|
+
* waiting (a stale notification is just taken down); brings the app
|
|
130
|
+
* forward from [from], like [onUserAnswer].
|
|
131
|
+
*/
|
|
132
|
+
fun onUserAnswerWaiting(ring: RingContext, from: Context? = null): Boolean {
|
|
133
|
+
if (runtime.currentState().waiting?.callId != ring.callId) {
|
|
134
|
+
runCatching {
|
|
135
|
+
androidx.core.app.NotificationManagerCompat.from(appContext)
|
|
136
|
+
.cancel(with(AndroidRingSurface) { ring.callId.notificationId() })
|
|
137
|
+
}
|
|
138
|
+
return false
|
|
139
|
+
}
|
|
140
|
+
runtime.answerWaiting(ring.callId)
|
|
141
|
+
return bringAppToFront(ring.callId, from)
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
fun onUserDecline(ring: RingContext) {
|
|
145
|
+
runtime.onRing(ring)
|
|
146
|
+
runtime.decline()
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
fun onUserOpen(ring: RingContext, from: Context? = null) {
|
|
150
|
+
runtime.onRing(ring)
|
|
151
|
+
bringAppToFront(ring.callId, from)
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
/** False once this ring is resolved here or past its deadline (+ clock slack). */
|
|
155
|
+
fun isRingLive(ring: RingContext): Boolean =
|
|
156
|
+
!runtime.isResolved(ring.callId) &&
|
|
157
|
+
ring.ringDeadlineEpochMs + CallCoreRuntime.CLOCK_SLACK_MS > System.currentTimeMillis()
|
|
158
|
+
|
|
159
|
+
// ── bridge-driven actions ───────────────────────────────────────────
|
|
160
|
+
|
|
161
|
+
fun answer() = runtime.answer()
|
|
162
|
+
fun decline() = runtime.decline()
|
|
163
|
+
fun hangUp() = runtime.hangUp()
|
|
164
|
+
/** Call waiting: end this call, answer the waiting one ([callId]: only if still that one). */
|
|
165
|
+
fun answerWaiting(callId: String? = null) = runtime.answerWaiting(callId)
|
|
166
|
+
/** Call waiting: turn the waiting call away — its caller hears busy. */
|
|
167
|
+
fun declineWaiting(callId: String? = null) = runtime.declineWaiting(callId)
|
|
168
|
+
fun place(conversationId: String, media: String, sessionToken: String) =
|
|
169
|
+
runtime.place(conversationId, media, sessionToken)
|
|
170
|
+
fun join(callId: String, conversationId: String?, sessionToken: String) =
|
|
171
|
+
runtime.join(callId, conversationId, sessionToken)
|
|
172
|
+
|
|
173
|
+
fun setMuted(muted: Boolean) {
|
|
174
|
+
runtime.post { mutedSelf = muted }
|
|
175
|
+
runtime.setMuted(muted)
|
|
176
|
+
runtime.reemit()
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Not optimistic: `cameraOn` in the snapshot flips only when the
|
|
181
|
+
* media adapter reports the local camera track actually published
|
|
182
|
+
* (it may be refused — e.g. no CAMERA permission).
|
|
183
|
+
*/
|
|
184
|
+
fun setCamera(on: Boolean) = runtime.setCamera(on)
|
|
185
|
+
|
|
186
|
+
fun switchCamera() = runtime.switchCamera()
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* A video slot for `<CallVideoView>`, or null when the media engine
|
|
190
|
+
* renders no video (signalling-only build). Main thread.
|
|
191
|
+
*/
|
|
192
|
+
fun createVideoSurface(context: Context): CallVideoSurface? =
|
|
193
|
+
(media as? CallVideoSource)?.createVideoSurface(context)
|
|
194
|
+
|
|
195
|
+
fun setSpeaker(on: Boolean) {
|
|
196
|
+
// Optimistic; the media adapter reports the route it actually got.
|
|
197
|
+
runtime.post { audioRoute = if (on) "speaker" else "earpiece" }
|
|
198
|
+
runtime.setSpeaker(on)
|
|
199
|
+
runtime.reemit()
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Play through one output from the snapshot's `audioOutputs`. Not
|
|
204
|
+
* optimistic: the adapter reports the route once the OS has moved it.
|
|
205
|
+
*/
|
|
206
|
+
fun setAudioOutput(id: String) = runtime.setAudioOutput(id)
|
|
207
|
+
|
|
208
|
+
/** The current call's id and control token. Any thread. */
|
|
209
|
+
val control: Pair<String, String>? get() = runtime.control
|
|
210
|
+
|
|
211
|
+
fun allRingsResolved(outcome: String) = runtime.allRingsResolved(outcome)
|
|
212
|
+
|
|
213
|
+
fun state(): MachineState = runtime.currentState()
|
|
214
|
+
|
|
215
|
+
/** The contract Snapshot (`null` = idle), safe from any thread. */
|
|
216
|
+
fun snapshot(): Map<String, Any?>? = lastSnapshot
|
|
217
|
+
|
|
218
|
+
// ── snapshot assembly (runtime thread) ──────────────────────────────
|
|
219
|
+
|
|
220
|
+
private fun onState(state: MachineState) {
|
|
221
|
+
if (state.phase == Phase.IDLE) {
|
|
222
|
+
if (extrasCallId != null) {
|
|
223
|
+
// Idle: no call owns media any more. Clears the port's per-call
|
|
224
|
+
// mute/camera/speaker choices even when the call ended on a path
|
|
225
|
+
// with no MEDIA_LEAVE (e.g. refused while connecting).
|
|
226
|
+
media.leave()
|
|
227
|
+
}
|
|
228
|
+
resetExtras(null, null)
|
|
229
|
+
} else if (state.callId != extrasCallId) {
|
|
230
|
+
// `pending:<conv>` → the server-minted id is the same call — but
|
|
231
|
+
// only for that conversation's own placed call: a waiting call
|
|
232
|
+
// promoted over a still-pending one is a different call.
|
|
233
|
+
if (isRenameOfPending(extrasCallId, state)) extrasCallId = state.callId
|
|
234
|
+
else resetExtras(state.callId, state.media)
|
|
235
|
+
}
|
|
236
|
+
if (state.phase != Phase.IDLE && state.media != extrasMedia) {
|
|
237
|
+
// The server corrected the media (a join defaults to audio until
|
|
238
|
+
// its bundle says otherwise): re-derive what depends on it.
|
|
239
|
+
if (extrasMedia != null) {
|
|
240
|
+
audioRoute = null
|
|
241
|
+
CallForegroundService.updateCall(state.callId ?: "", state.media)
|
|
242
|
+
}
|
|
243
|
+
extrasMedia = state.media
|
|
244
|
+
}
|
|
245
|
+
runtime.conversationName?.let { conversationName = it }
|
|
246
|
+
runtime.callKind?.let { callKind = it }
|
|
247
|
+
|
|
248
|
+
val snap = state.toSnapshot(
|
|
249
|
+
conversationName = conversationName,
|
|
250
|
+
kind = callKind,
|
|
251
|
+
participants = roster.map {
|
|
252
|
+
mapOf(
|
|
253
|
+
"userId" to it.identity,
|
|
254
|
+
"externalId" to it.externalId,
|
|
255
|
+
"speaking" to it.speaking,
|
|
256
|
+
"muted" to it.muted,
|
|
257
|
+
"cameraOn" to it.cameraOn,
|
|
258
|
+
"connectionQuality" to it.connectionQuality,
|
|
259
|
+
)
|
|
260
|
+
},
|
|
261
|
+
audioRoute = audioRoute ?: if (loud(state)) "speaker" else "earpiece",
|
|
262
|
+
audioOutputs = audioOutputs.map { mapOf("id" to it.id, "kind" to it.kind, "name" to it.name) },
|
|
263
|
+
audioOutputId = audioOutputId,
|
|
264
|
+
mutedSelf = mutedSelf,
|
|
265
|
+
cameraOn = cameraOn,
|
|
266
|
+
cameraFacing = cameraFacing,
|
|
267
|
+
waitingRing = runtime.waitingRing,
|
|
268
|
+
connectionQuality = connectionQuality,
|
|
269
|
+
videoPaused = videoPaused,
|
|
270
|
+
)
|
|
271
|
+
lastSnapshot = snap
|
|
272
|
+
reconcileAndroid(state)
|
|
273
|
+
runCatching { listener?.invoke(snap) }.onFailure { Log.w(TAG, "snapshot listener failed", it) }
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
private fun isRenameOfPending(previous: String?, state: MachineState): Boolean =
|
|
277
|
+
previous != null && previous.startsWith("pending:") &&
|
|
278
|
+
state.direction != dev.poolse.callcore.Direction.INCOMING &&
|
|
279
|
+
previous == "pending:${state.conversationId}"
|
|
280
|
+
|
|
281
|
+
private fun resetExtras(callId: String?, media: String?) {
|
|
282
|
+
extrasCallId = callId
|
|
283
|
+
extrasMedia = media
|
|
284
|
+
roster = emptyList()
|
|
285
|
+
conversationName = null
|
|
286
|
+
callKind = "call"
|
|
287
|
+
mutedSelf = false
|
|
288
|
+
// Reported by the media adapter once the camera is really published.
|
|
289
|
+
cameraOn = false
|
|
290
|
+
cameraFacing = null
|
|
291
|
+
audioRoute = null
|
|
292
|
+
audioOutputs = emptyList()
|
|
293
|
+
audioOutputId = null
|
|
294
|
+
connectionQuality = "unknown"
|
|
295
|
+
videoPaused = false
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
/**
|
|
299
|
+
* OS-level consequences of the state, applied after the FINAL state
|
|
300
|
+
* of each dispatch — so an answer's DISMISS_RING → CALL_SESSION_START
|
|
301
|
+
* hands the foreground service from ring to call without a gap.
|
|
302
|
+
*/
|
|
303
|
+
private fun reconcileAndroid(state: MachineState) {
|
|
304
|
+
// Keep the process alive while ringing (OEM freezers otherwise kill
|
|
305
|
+
// the ringtone and the deadline timer of a closed app).
|
|
306
|
+
if (state.phase == Phase.RINGING_IN) {
|
|
307
|
+
CallForegroundService.startRing(state.callId ?: "")
|
|
308
|
+
} else {
|
|
309
|
+
CallForegroundService.stopRing()
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
if (state.phase == Phase.IDLE || state.phase == Phase.ENDED) surface.setCommunicationReady(false)
|
|
313
|
+
|
|
314
|
+
// Screen off at the ear: only for an audio call on the earpiece.
|
|
315
|
+
val inCall = state.phase == Phase.ACTIVE || state.phase == Phase.RECONNECTING ||
|
|
316
|
+
state.phase == Phase.RINGING_OUT || state.phase == Phase.CONNECTING
|
|
317
|
+
val earpiece = (audioRoute ?: if (loud(state)) "speaker" else "earpiece") == "earpiece"
|
|
318
|
+
setProximity(inCall && state.media == "audio" && earpiece)
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
private fun setProximity(on: Boolean) {
|
|
322
|
+
val lock = proximity ?: return
|
|
323
|
+
runCatching {
|
|
324
|
+
if (on && !lock.isHeld) lock.acquire(4 * 60 * 60 * 1000L)
|
|
325
|
+
else if (!on && lock.isHeld) lock.release(PowerManager.RELEASE_FLAG_WAIT_FOR_NO_PROXIMITY)
|
|
326
|
+
}.onFailure { Log.w(TAG, "proximity wake lock", it) }
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
private fun tearDownRing(callId: String) {
|
|
330
|
+
val s = runtime.currentState()
|
|
331
|
+
surface.dismiss(callId)
|
|
332
|
+
// Never silence a DIFFERENT call that is ringing right now.
|
|
333
|
+
if (!(s.phase == Phase.RINGING_IN && s.callId != callId)) surface.ringtoneStop()
|
|
334
|
+
if (s.phase != Phase.RINGING_IN) CallForegroundService.stopRing()
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
private fun mediaEvents() = object : MediaEvents {
|
|
338
|
+
override fun onConnected() {
|
|
339
|
+
// The communication audio mode is set by now: ringback may play
|
|
340
|
+
// through the call route (earpiece), not the loudspeaker.
|
|
341
|
+
runtime.post { surface.setCommunicationReady(true) }
|
|
342
|
+
runtime.onMediaConnected()
|
|
343
|
+
}
|
|
344
|
+
override fun onFailed() = runtime.onMediaFailed()
|
|
345
|
+
override fun onLost() = runtime.onMediaLost()
|
|
346
|
+
override fun onReconnecting() = runtime.onMediaReconnecting()
|
|
347
|
+
override fun onRecovered() = runtime.onMediaRecovered()
|
|
348
|
+
override fun onRemoteJoined() = runtime.onRemoteJoined()
|
|
349
|
+
override fun onParticipants(participants: List<MediaParticipant>) {
|
|
350
|
+
runtime.post { roster = participants }
|
|
351
|
+
runtime.onRemoteCount(participants.size)
|
|
352
|
+
runtime.reemit()
|
|
353
|
+
}
|
|
354
|
+
override fun onAudioRoute(route: String) {
|
|
355
|
+
runtime.post { audioRoute = route }
|
|
356
|
+
runtime.reemit()
|
|
357
|
+
}
|
|
358
|
+
override fun onLocalCamera(on: Boolean, facing: String?) {
|
|
359
|
+
runtime.post { cameraOn = on; cameraFacing = facing }
|
|
360
|
+
runtime.reemit()
|
|
361
|
+
}
|
|
362
|
+
override fun onAudioOutputs(outputs: List<AudioOutput>, selectedId: String?) {
|
|
363
|
+
runtime.post { audioOutputs = outputs; audioOutputId = selectedId }
|
|
364
|
+
runtime.reemit()
|
|
365
|
+
}
|
|
366
|
+
override fun onNetwork(quality: String, videoPaused: Boolean) {
|
|
367
|
+
runtime.post { connectionQuality = quality; this@CallCore.videoPaused = videoPaused }
|
|
368
|
+
runtime.reemit()
|
|
369
|
+
}
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
private fun bringAppToFront(callId: String, from: Context?): Boolean {
|
|
373
|
+
val launch = appContext.packageManager.getLaunchIntentForPackage(appContext.packageName)
|
|
374
|
+
?: return false
|
|
375
|
+
launch.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_SINGLE_TOP)
|
|
376
|
+
// The host's MainActivity reads this to show over the keyguard and
|
|
377
|
+
// dismiss it, and to route straight to the call screen.
|
|
378
|
+
launch.putExtra(EXTRA_LAUNCH_CALL, callId)
|
|
379
|
+
return runCatching { (from ?: appContext).startActivity(launch) }
|
|
380
|
+
.onFailure { Log.w(TAG, "could not bring the app forward", it) }
|
|
381
|
+
.isSuccess
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
companion object {
|
|
385
|
+
const val EXTRA_LAUNCH_CALL = "poolse_launch_call"
|
|
386
|
+
private const val TAG = "PoolseCallCore"
|
|
387
|
+
private const val PREFS = "dev.poolse.callcore"
|
|
388
|
+
|
|
389
|
+
@Volatile private var instance: CallCore? = null
|
|
390
|
+
@Volatile private var config: CallCoreConfig? = null
|
|
391
|
+
|
|
392
|
+
/**
|
|
393
|
+
* The bridge's snapshot subscriber. Process-level (not per instance)
|
|
394
|
+
* so the JS side may subscribe before configure() — the core picks
|
|
395
|
+
* it up when it is created.
|
|
396
|
+
*/
|
|
397
|
+
@Volatile var listener: ((Map<String, Any?>?) -> Unit)? = null
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* Configure the core and PERSIST the inputs. A ring can wake a killed
|
|
401
|
+
* app: the OS spawns the process cold to run [CallMessagingService],
|
|
402
|
+
* with no React context and no chance for the JS bridge to call this.
|
|
403
|
+
* Persisting lets [restoreConfig] rebuild the same config from disk on
|
|
404
|
+
* that cold start, so closed-app ringing works. The bridge calls this
|
|
405
|
+
* each time the app opens; the resource names (not the resolved ids)
|
|
406
|
+
* are stored, since ids are not stable across installs.
|
|
407
|
+
*
|
|
408
|
+
* Re-configuring a live core swaps the config in place: HTTP and the
|
|
409
|
+
* ring surface read it per use, so a new API origin takes effect on
|
|
410
|
+
* the next request.
|
|
411
|
+
*/
|
|
412
|
+
fun configure(context: Context, apiBaseUrl: String, smallIconName: String?, ringbackName: String?) {
|
|
413
|
+
val ctx = context.applicationContext
|
|
414
|
+
ctx.getSharedPreferences(PREFS, Context.MODE_PRIVATE).edit()
|
|
415
|
+
.putString("apiBaseUrl", apiBaseUrl)
|
|
416
|
+
.putString("smallIcon", smallIconName)
|
|
417
|
+
.putString("ringback", ringbackName)
|
|
418
|
+
.apply()
|
|
419
|
+
config = build(ctx, apiBaseUrl, smallIconName, ringbackName)
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/** The core; throws if never configured (not even persisted). Prefer [getOrNull]. */
|
|
423
|
+
fun get(context: Context): CallCore =
|
|
424
|
+
getOrNull(context) ?: error("CallCore.configure() must be called before use")
|
|
425
|
+
|
|
426
|
+
/** The core, or null if this install was never configured — callers no-op. */
|
|
427
|
+
fun getOrNull(context: Context): CallCore? =
|
|
428
|
+
instance ?: synchronized(this) {
|
|
429
|
+
instance ?: run {
|
|
430
|
+
if (config == null) restoreConfig(context.applicationContext)
|
|
431
|
+
if (config == null) null else CallCore(context).also { instance = it }
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
|
|
435
|
+
/** The live core if one exists — never creates (cheap reads, e.g. getCallState). */
|
|
436
|
+
fun peek(): CallCore? = instance
|
|
437
|
+
|
|
438
|
+
/** The configured API origin (restored from disk on a cold start), or null. */
|
|
439
|
+
fun apiBaseUrl(context: Context): String? {
|
|
440
|
+
if (config == null) restoreConfig(context.applicationContext)
|
|
441
|
+
return config?.apiBaseUrl?.ifEmpty { null }
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/** The configured notification icon (restored from disk on a cold start). */
|
|
445
|
+
fun smallIcon(context: Context): Int {
|
|
446
|
+
if (config == null) restoreConfig(context.applicationContext)
|
|
447
|
+
return config?.smallIcon ?: context.applicationInfo.icon
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
internal fun peekConfig(): CallCoreConfig? = config
|
|
451
|
+
|
|
452
|
+
internal fun requireConfig(): CallCoreConfig =
|
|
453
|
+
config ?: error("CallCore.configure() must be called before use")
|
|
454
|
+
|
|
455
|
+
// Rebuild config from the persisted inputs on a cold start. Leaves
|
|
456
|
+
// config null if the app was never configured — impossible in
|
|
457
|
+
// practice, since registering for pushes requires opening the app.
|
|
458
|
+
private fun restoreConfig(context: Context) {
|
|
459
|
+
val p = context.getSharedPreferences(PREFS, Context.MODE_PRIVATE)
|
|
460
|
+
val url = p.getString("apiBaseUrl", null) ?: return
|
|
461
|
+
config = build(context, url, p.getString("smallIcon", null), p.getString("ringback", null))
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
private fun build(
|
|
465
|
+
context: Context,
|
|
466
|
+
apiBaseUrl: String,
|
|
467
|
+
smallIconName: String?,
|
|
468
|
+
ringbackName: String?,
|
|
469
|
+
): CallCoreConfig {
|
|
470
|
+
val iconId = smallIconName
|
|
471
|
+
?.let { context.resources.getIdentifier(it, "drawable", context.packageName) } ?: 0
|
|
472
|
+
val ringbackId = ringbackName
|
|
473
|
+
?.let { context.resources.getIdentifier(it, "raw", context.packageName) } ?: 0
|
|
474
|
+
return CallCoreConfig(
|
|
475
|
+
apiBaseUrl = apiBaseUrl.trimEnd('/'),
|
|
476
|
+
// Fall back to the app's launcher icon rather than crash on a typo.
|
|
477
|
+
smallIcon = if (iconId != 0) iconId else context.applicationInfo.icon,
|
|
478
|
+
ringbackRawRes = ringbackId,
|
|
479
|
+
mediaFactory = resolveMediaFactory(),
|
|
480
|
+
)
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* The shipped LiveKit adapter is loaded reflectively so the core
|
|
485
|
+
* library carries no static dependency on the SFU source set. Absent
|
|
486
|
+
* (LiveKit not built in), calls still ring and signal; there is just
|
|
487
|
+
* no media — a supported degraded mode, not a crash.
|
|
488
|
+
*/
|
|
489
|
+
@Suppress("UNCHECKED_CAST")
|
|
490
|
+
private fun resolveMediaFactory(): (Context, MediaEvents) -> MediaPort =
|
|
491
|
+
runCatching {
|
|
492
|
+
val companion = Class.forName("dev.poolse.callcore.livekit.LiveKitMediaPort\$Companion")
|
|
493
|
+
val livekit = Class.forName("dev.poolse.callcore.livekit.LiveKitMediaPort")
|
|
494
|
+
.getField("Companion").get(null)
|
|
495
|
+
companion.getMethod("getFactory").invoke(livekit) as (Context, MediaEvents) -> MediaPort
|
|
496
|
+
}.getOrElse {
|
|
497
|
+
{ _, _ -> NoMediaPort }
|
|
498
|
+
}
|
|
499
|
+
|
|
500
|
+
/** Signalling-only fallback: the call rings and the state machine
|
|
501
|
+
* runs, there is simply no audio/video transport. */
|
|
502
|
+
private object NoMediaPort : MediaPort {
|
|
503
|
+
override fun join(bundle: dev.poolse.callcore.CallSessionBundle) {}
|
|
504
|
+
override fun leave() {}
|
|
505
|
+
override fun setMuted(muted: Boolean) {}
|
|
506
|
+
override fun setCamera(on: Boolean) {}
|
|
507
|
+
override fun switchCamera() {}
|
|
508
|
+
override fun setSpeaker(on: Boolean) {}
|
|
509
|
+
}
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
/**
|
|
514
|
+
* The host-supplied configuration: the API base URL the HTTP doors
|
|
515
|
+
* target, and the drawable/raw resources the surfaces need. Everything
|
|
516
|
+
* here is knowable only by the app, never by the library.
|
|
517
|
+
*/
|
|
518
|
+
data class CallCoreConfig(
|
|
519
|
+
val apiBaseUrl: String,
|
|
520
|
+
val smallIcon: Int,
|
|
521
|
+
val ringbackRawRes: Int,
|
|
522
|
+
/**
|
|
523
|
+
* Builds the media engine for a call. Injected so the core carries no
|
|
524
|
+
* SFU dependency; pass `::LiveKitMediaPortFactory` (the shipped
|
|
525
|
+
* implementation) or your own.
|
|
526
|
+
*/
|
|
527
|
+
val mediaFactory: (Context, MediaEvents) -> MediaPort,
|
|
528
|
+
) {
|
|
529
|
+
internal val ringSurface get() = RingSurfaceConfig(smallIcon, ringbackRawRes)
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
/** Media-level signals the SFU adapter reports back to the core. */
|
|
533
|
+
interface MediaEvents {
|
|
534
|
+
fun onConnected()
|
|
535
|
+
fun onFailed()
|
|
536
|
+
/** Unexpected disconnect — the SFU gave up; the core asks the server and rejoins. */
|
|
537
|
+
fun onLost()
|
|
538
|
+
/** The SFU is resuming the session itself; only reflected in the UI. */
|
|
539
|
+
fun onReconnecting()
|
|
540
|
+
fun onRecovered()
|
|
541
|
+
fun onRemoteJoined()
|
|
542
|
+
/** The REMOTE roster (the local participant excluded). */
|
|
543
|
+
fun onParticipants(participants: List<MediaParticipant>)
|
|
544
|
+
/** `earpiece` | `speaker` | `bluetooth` | `headset`. */
|
|
545
|
+
fun onAudioRoute(route: String)
|
|
546
|
+
/** The local camera track is (not) published + enabled; [facing] `front` | `back`. */
|
|
547
|
+
fun onLocalCamera(on: Boolean, facing: String?) {}
|
|
548
|
+
/** Every output call audio can play through right now, and the one it does. */
|
|
549
|
+
fun onAudioOutputs(outputs: List<AudioOutput>, selectedId: String?) {}
|
|
550
|
+
/**
|
|
551
|
+
* Our own link to the SFU (`good` | `poor` | `lost` | `unknown`), and
|
|
552
|
+
* whether incoming video is paused to keep the audio going.
|
|
553
|
+
*/
|
|
554
|
+
fun onNetwork(quality: String, videoPaused: Boolean) {}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
/** One place call audio can play — a snapshot `audioOutputs[]` entry. */
|
|
558
|
+
data class AudioOutput(
|
|
559
|
+
/** Passed back to `setAudioOutput`; stable while the device stays connected. */
|
|
560
|
+
val id: String,
|
|
561
|
+
/** `earpiece` | `speaker` | `bluetooth` | `headset`. */
|
|
562
|
+
val kind: String,
|
|
563
|
+
/** What the device calls itself ("Galaxy Buds2"), or a plain default for built-ins. */
|
|
564
|
+
val name: String,
|
|
565
|
+
)
|
|
566
|
+
|
|
567
|
+
data class MediaParticipant(
|
|
568
|
+
/** The SFU identity — the poolse user id. */
|
|
569
|
+
val identity: String,
|
|
570
|
+
val speaking: Boolean,
|
|
571
|
+
val muted: Boolean,
|
|
572
|
+
/** True only with a published, subscribed, unmuted camera track — a frame to draw. */
|
|
573
|
+
val cameraOn: Boolean = false,
|
|
574
|
+
/** The host app's own id for the user, when the SFU carries it; else the identity. */
|
|
575
|
+
val externalId: String = identity,
|
|
576
|
+
/** Their link to the SFU: `good` | `poor` | `lost` (dropped, coming back) | `unknown`. */
|
|
577
|
+
val connectionQuality: String = "unknown",
|
|
578
|
+
)
|