react-native-sinch-calling 0.2.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 (40) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/LICENSE +20 -0
  3. package/README.md +239 -0
  4. package/SinchCalling.podspec +28 -0
  5. package/android/build.gradle +52 -0
  6. package/android/src/main/AndroidManifest.xml +19 -0
  7. package/android/src/main/java/com/sinchcalling/SinchCallManager.kt +302 -0
  8. package/android/src/main/java/com/sinchcalling/SinchCallingModule.kt +184 -0
  9. package/android/src/main/java/com/sinchcalling/SinchCallingPackage.kt +31 -0
  10. package/android/src/main/java/com/sinchcalling/telecom/SinchConnection.kt +43 -0
  11. package/android/src/main/java/com/sinchcalling/telecom/SinchConnectionService.kt +37 -0
  12. package/android/src/main/java/com/sinchcalling/telecom/SinchTelecomManager.kt +106 -0
  13. package/ios/Sinch/SinchCallKitManager.swift +154 -0
  14. package/ios/Sinch/SinchCallManager.swift +195 -0
  15. package/ios/Sinch/SinchPushManager.swift +81 -0
  16. package/ios/SinchCalling.h +5 -0
  17. package/ios/SinchCalling.mm +242 -0
  18. package/lib/module/NativeSinchCalling.js +5 -0
  19. package/lib/module/NativeSinchCalling.js.map +1 -0
  20. package/lib/module/SinchCalling.js +185 -0
  21. package/lib/module/SinchCalling.js.map +1 -0
  22. package/lib/module/index.js +4 -0
  23. package/lib/module/index.js.map +1 -0
  24. package/lib/module/package.json +1 -0
  25. package/lib/module/types.js +4 -0
  26. package/lib/module/types.js.map +1 -0
  27. package/lib/typescript/package.json +1 -0
  28. package/lib/typescript/src/NativeSinchCalling.d.ts +69 -0
  29. package/lib/typescript/src/NativeSinchCalling.d.ts.map +1 -0
  30. package/lib/typescript/src/SinchCalling.d.ts +98 -0
  31. package/lib/typescript/src/SinchCalling.d.ts.map +1 -0
  32. package/lib/typescript/src/index.d.ts +4 -0
  33. package/lib/typescript/src/index.d.ts.map +1 -0
  34. package/lib/typescript/src/types.d.ts +9 -0
  35. package/lib/typescript/src/types.d.ts.map +1 -0
  36. package/package.json +179 -0
  37. package/src/NativeSinchCalling.ts +148 -0
  38. package/src/SinchCalling.ts +245 -0
  39. package/src/index.tsx +11 -0
  40. package/src/types.ts +9 -0
@@ -0,0 +1,302 @@
1
+ package com.sinchcalling
2
+
3
+ import android.content.Context
4
+ import com.sinch.android.rtc.AudioController
5
+ import com.sinch.android.rtc.ClientRegistration
6
+ import com.sinch.android.rtc.PushConfiguration
7
+ import com.sinch.android.rtc.SinchClient
8
+ import com.sinch.android.rtc.SinchClientListener
9
+ import com.sinch.android.rtc.SinchError
10
+ import com.sinch.android.rtc.SinchPush
11
+ import com.sinch.android.rtc.calling.Call
12
+ import com.sinch.android.rtc.calling.CallController
13
+ import com.sinch.android.rtc.calling.CallControllerListener
14
+ import com.sinch.android.rtc.calling.CallEndCause
15
+ import com.sinch.android.rtc.calling.CallListener
16
+ import com.sinch.android.rtc.calling.MediaConstraints
17
+ import com.sinchcalling.telecom.SinchTelecomListener
18
+ import com.sinchcalling.telecom.SinchTelecomManager
19
+ import java.io.IOException
20
+
21
+ interface SinchCallManagerListener {
22
+ fun onClientStarted()
23
+ fun onClientFailed(message: String, code: Int)
24
+ fun onRegistrationCredentialsRequired()
25
+
26
+ fun onIncomingCall(callId: String, remoteUserId: String)
27
+ fun onCallProgressing(callId: String)
28
+ fun onCallEstablished(callId: String)
29
+ fun onCallEnded(callId: String, endCause: String)
30
+
31
+ fun onPushTokenRegistered()
32
+ fun onPushTokenRegistrationFailed(message: String, code: Int)
33
+
34
+ // A system call UI was reported — either the consumer app called
35
+ // `reportIncomingCallUI` directly, or a configured custom push was
36
+ // auto-detected (see `configureCustomIncomingCallPush`). Distinct from a
37
+ // Sinch-relayed push (e.g. an app-to-app incoming call), which instead
38
+ // surfaces as `onIncomingCall`.
39
+ fun onIncomingCallUIShown(callId: String, displayName: String)
40
+ fun onCallUIAnswered(callId: String)
41
+ fun onCallUIDeclined(callId: String)
42
+ }
43
+
44
+ private fun endCauseString(endCause: CallEndCause): String = when (endCause) {
45
+ CallEndCause.NONE -> "none"
46
+ CallEndCause.TIMEOUT -> "timeout"
47
+ CallEndCause.DENIED -> "denied"
48
+ CallEndCause.NO_ANSWER -> "noAnswer"
49
+ CallEndCause.FAILURE -> "error"
50
+ CallEndCause.HUNG_UP -> "hungUp"
51
+ CallEndCause.CANCELED -> "canceled"
52
+ CallEndCause.OTHER_DEVICE_ANSWERED -> "otherDeviceAnswered"
53
+ CallEndCause.INACTIVE -> "inactive"
54
+ CallEndCause.VOIP_CALL_DETECTED -> "voipCallDetected"
55
+ CallEndCause.GSM_CALL_DETECTED -> "gsmCallDetected"
56
+ else -> "none"
57
+ }
58
+
59
+ class SinchCallManager(private val context: Context) {
60
+ var listener: SinchCallManagerListener? = null
61
+
62
+ private var client: SinchClient? = null
63
+ private var pendingRegistration: ClientRegistration? = null
64
+ private var pendingPushConfiguration: PushConfiguration? = null
65
+ private val calls = mutableMapOf<String, Call>()
66
+ private var customPushIdField: String? = null
67
+ private var customPushDisplayField: String? = null
68
+
69
+ private val callListener = object : CallListener {
70
+ override fun onCallProgressing(call: Call) {
71
+ listener?.onCallProgressing(call.callId)
72
+ }
73
+
74
+ override fun onCallEstablished(call: Call) {
75
+ SinchTelecomManager.reportCallActive(call.callId)
76
+ listener?.onCallEstablished(call.callId)
77
+ }
78
+
79
+ override fun onCallEnded(call: Call) {
80
+ calls.remove(call.callId)
81
+ SinchTelecomManager.reportCallEnded(call.callId)
82
+ listener?.onCallEnded(call.callId, endCauseString(call.details.endCause))
83
+ }
84
+ }
85
+
86
+ init {
87
+ SinchTelecomManager.registerPhoneAccount(context.applicationContext)
88
+ SinchTelecomManager.listener = object : SinchTelecomListener {
89
+ override fun onAnswer(callId: String) {
90
+ answerCall(callId)
91
+ }
92
+
93
+ override fun onReject(callId: String) {
94
+ hangupCall(callId)
95
+ }
96
+
97
+ override fun onDisconnect(callId: String) {
98
+ hangupCall(callId)
99
+ }
100
+
101
+ override fun onAnswerExternal(callId: String) {
102
+ listener?.onCallUIAnswered(callId)
103
+ }
104
+
105
+ override fun onDeclineExternal(callId: String) {
106
+ listener?.onCallUIDeclined(callId)
107
+ }
108
+ }
109
+ }
110
+
111
+ fun registerFcmPush(senderId: String, token: String) {
112
+ pendingPushConfiguration = PushConfiguration.fcmPushConfigurationBuilder()
113
+ .senderID(senderId)
114
+ .registrationToken(token)
115
+ .build()
116
+ }
117
+
118
+ // Opts into recognizing the consumer app's own backend's incoming-call
119
+ // push payloads. Until called, every payload is relayed straight to
120
+ // Sinch (see `relayRemotePushNotification`).
121
+ fun configureCustomIncomingCallPush(idField: String, displayField: String) {
122
+ customPushIdField = idField
123
+ customPushDisplayField = displayField
124
+ }
125
+
126
+ fun relayRemotePushNotification(payload: Map<String, String>) {
127
+ val idField = customPushIdField
128
+ val callId = idField?.let { payload[it] }
129
+ if (callId != null) {
130
+ val displayName = customPushDisplayField?.let { payload[it] } ?: ""
131
+ reportIncomingCallUI(callId, displayName)
132
+ return
133
+ }
134
+
135
+ val result = SinchPush.queryPushNotificationPayload(context.applicationContext, payload)
136
+ client?.relayRemotePushNotification(result)
137
+ }
138
+
139
+ // Reports a system call UI (CallKit / Telecom) for a call the consumer
140
+ // app decided to show — from a custom push, a Socket.IO event, or
141
+ // anything else. Independent of `configureCustomIncomingCallPush`.
142
+ fun reportIncomingCallUI(callId: String, displayName: String) {
143
+ SinchTelecomManager.reportExternalIncomingCall(context.applicationContext, callId, displayName)
144
+ listener?.onIncomingCallUIShown(callId, displayName)
145
+ }
146
+
147
+ fun configure(appKey: String, environmentHost: String, userId: String) {
148
+ val builder = SinchClient.builder()
149
+ .context(context.applicationContext)
150
+ .applicationKey(appKey)
151
+ .environmentHost(environmentHost)
152
+ .userId(userId)
153
+
154
+ pendingPushConfiguration?.let { builder.pushConfiguration(it) }
155
+
156
+ val sinchClient = try {
157
+ builder.build()
158
+ } catch (error: IOException) {
159
+ listener?.onClientFailed(error.message ?: "Failed to build Sinch client", -1)
160
+ return
161
+ }
162
+
163
+ sinchClient.audioController.enableAutomaticAudioRouting(
164
+ AudioController.AudioRoutingConfig(AudioController.UseSpeakerphone.SPEAKERPHONE_AUTO, true)
165
+ )
166
+
167
+ sinchClient.addSinchClientListener(object : SinchClientListener {
168
+ override fun onClientStarted(client: SinchClient) {
169
+ listener?.onClientStarted()
170
+ }
171
+
172
+ override fun onClientFailed(client: SinchClient, error: SinchError) {
173
+ listener?.onClientFailed(error.message ?: "Unknown Sinch client error", error.code)
174
+ }
175
+
176
+ override fun onCredentialsRequired(clientRegistration: ClientRegistration) {
177
+ pendingRegistration = clientRegistration
178
+ listener?.onRegistrationCredentialsRequired()
179
+ }
180
+
181
+ override fun onPushTokenRegistered() {
182
+ listener?.onPushTokenRegistered()
183
+ }
184
+
185
+ override fun onPushTokenRegistrationFailed(error: SinchError) {
186
+ listener?.onPushTokenRegistrationFailed(error.message ?: "Unknown Sinch push error", error.code)
187
+ }
188
+
189
+ override fun onPushTokenUnregistered() {}
190
+ override fun onPushTokenUnregistrationFailed(error: SinchError) {}
191
+
192
+ override fun onUserRegistered() {}
193
+ override fun onUserRegistrationFailed(error: SinchError) {}
194
+ })
195
+
196
+ sinchClient.callController.addCallControllerListener(object : CallControllerListener {
197
+ override fun onIncomingCall(callController: CallController, call: Call) {
198
+ track(call)
199
+ SinchTelecomManager.reportIncomingCall(
200
+ context.applicationContext,
201
+ call.callId,
202
+ call.remoteUserId
203
+ )
204
+ listener?.onIncomingCall(call.callId, call.remoteUserId)
205
+ }
206
+ })
207
+
208
+ client = sinchClient
209
+ }
210
+
211
+ fun start() {
212
+ client?.start()
213
+ }
214
+
215
+ fun stop() {
216
+ client?.terminateGracefully()
217
+ client = null
218
+ calls.clear()
219
+ }
220
+
221
+ fun provideRegistrationCredentials(jwt: String) {
222
+ pendingRegistration?.register(jwt)
223
+ pendingRegistration = null
224
+ }
225
+
226
+ fun failRegistration() {
227
+ pendingRegistration?.registerFailed()
228
+ pendingRegistration = null
229
+ }
230
+
231
+ fun callUser(userId: String): String {
232
+ val call = client?.callController?.callUser(userId, MediaConstraints(false)) ?: return ""
233
+ track(call)
234
+ return call.callId
235
+ }
236
+
237
+ fun callPhoneNumber(phoneNumber: String, callerId: String): String {
238
+ val call = client?.callController?.callPhoneNumber(phoneNumber, callerId) ?: return ""
239
+ track(call)
240
+ return call.callId
241
+ }
242
+
243
+ fun callConference(conferenceId: String, callerId: String): String {
244
+ val call = client?.callController?.callConference(conferenceId, callerId) ?: return ""
245
+ track(call)
246
+ return call.callId
247
+ }
248
+
249
+ // Turns a call shown via `reportIncomingCallUI` into a real call once you
250
+ // know which Sinch conference to join: joins the conference and
251
+ // re-associates the already-visible system call UI with the resulting
252
+ // real callId. Returns the real callId, or "" on failure.
253
+ fun resolveCallUIToConference(callId: String, conferenceId: String, callerId: String): String {
254
+ val call = client?.callController?.callConference(conferenceId, callerId)
255
+ if (call == null) {
256
+ SinchTelecomManager.reportCallEnded(callId)
257
+ return ""
258
+ }
259
+ track(call)
260
+ SinchTelecomManager.remapCallId(callId, call.callId)
261
+ return call.callId
262
+ }
263
+
264
+ // Cleans up a system call UI reported via `reportIncomingCallUI` that
265
+ // couldn't be resolved into a real call.
266
+ fun dismissCallUI(callId: String) {
267
+ SinchTelecomManager.reportCallEnded(callId)
268
+ }
269
+
270
+ fun updateIncomingCallDisplayName(callId: String, displayName: String) {
271
+ SinchTelecomManager.updateCallerDisplayName(callId, displayName)
272
+ }
273
+
274
+ fun answerCall(callId: String) {
275
+ calls[callId]?.answer()
276
+ }
277
+
278
+ fun hangupCall(callId: String) {
279
+ calls[callId]?.hangup()
280
+ }
281
+
282
+ fun sendDTMF(callId: String, key: String): Boolean {
283
+ val call = calls[callId] ?: return false
284
+ call.sendDTMF(key)
285
+ return true
286
+ }
287
+
288
+ fun setMuted(muted: Boolean) {
289
+ val audioController = client?.audioController ?: return
290
+ if (muted) audioController.mute() else audioController.unmute()
291
+ }
292
+
293
+ fun setSpeakerEnabled(enabled: Boolean) {
294
+ val audioController = client?.audioController ?: return
295
+ if (enabled) audioController.enableSpeaker() else audioController.disableSpeaker()
296
+ }
297
+
298
+ private fun track(call: Call) {
299
+ calls[call.callId] = call
300
+ call.addCallListener(callListener)
301
+ }
302
+ }
@@ -0,0 +1,184 @@
1
+ package com.sinchcalling
2
+
3
+ import com.facebook.react.bridge.Arguments
4
+ import com.facebook.react.bridge.ReactApplicationContext
5
+ import com.facebook.react.bridge.ReadableMap
6
+
7
+ class SinchCallingModule(reactContext: ReactApplicationContext) :
8
+ NativeSinchCallingSpec(reactContext) {
9
+
10
+ private val callManager = SinchCallManager(reactContext).apply {
11
+ listener = object : SinchCallManagerListener {
12
+ override fun onClientStarted() {
13
+ emitOnClientStarted()
14
+ }
15
+
16
+ override fun onClientFailed(message: String, code: Int) {
17
+ emitOnClientStartFailed(
18
+ Arguments.createMap().apply {
19
+ putString("message", message)
20
+ putInt("code", code)
21
+ }
22
+ )
23
+ }
24
+
25
+ override fun onRegistrationCredentialsRequired() {
26
+ emitOnRegistrationCredentialsRequired()
27
+ }
28
+
29
+ override fun onIncomingCall(callId: String, remoteUserId: String) {
30
+ emitOnIncomingCall(
31
+ Arguments.createMap().apply {
32
+ putString("callId", callId)
33
+ putString("remoteUserId", remoteUserId)
34
+ }
35
+ )
36
+ }
37
+
38
+ override fun onCallProgressing(callId: String) {
39
+ emitOnCallProgressing(Arguments.createMap().apply { putString("callId", callId) })
40
+ }
41
+
42
+ override fun onCallEstablished(callId: String) {
43
+ emitOnCallEstablished(Arguments.createMap().apply { putString("callId", callId) })
44
+ }
45
+
46
+ override fun onCallEnded(callId: String, endCause: String) {
47
+ emitOnCallEnded(
48
+ Arguments.createMap().apply {
49
+ putString("callId", callId)
50
+ putString("endCause", endCause)
51
+ }
52
+ )
53
+ }
54
+
55
+ override fun onPushTokenRegistered() {
56
+ emitOnPushTokenRegistered()
57
+ }
58
+
59
+ override fun onPushTokenRegistrationFailed(message: String, code: Int) {
60
+ emitOnPushTokenRegistrationFailed(
61
+ Arguments.createMap().apply {
62
+ putString("message", message)
63
+ putInt("code", code)
64
+ }
65
+ )
66
+ }
67
+
68
+ override fun onIncomingCallUIShown(callId: String, displayName: String) {
69
+ emitOnIncomingCallUIShown(
70
+ Arguments.createMap().apply {
71
+ putString("callId", callId)
72
+ putString("displayName", displayName)
73
+ }
74
+ )
75
+ }
76
+
77
+ override fun onCallUIAnswered(callId: String) {
78
+ emitOnCallUIAnswered(Arguments.createMap().apply { putString("callId", callId) })
79
+ }
80
+
81
+ override fun onCallUIDeclined(callId: String) {
82
+ emitOnCallUIDeclined(Arguments.createMap().apply { putString("callId", callId) })
83
+ }
84
+ }
85
+ }
86
+
87
+ override fun configure(appKey: String, environmentHost: String, userId: String) {
88
+ callManager.configure(appKey, environmentHost, userId)
89
+ }
90
+
91
+ override fun start() {
92
+ callManager.start()
93
+ }
94
+
95
+ override fun stop() {
96
+ callManager.stop()
97
+ }
98
+
99
+ override fun provideRegistrationCredentials(jwt: String) {
100
+ callManager.provideRegistrationCredentials(jwt)
101
+ }
102
+
103
+ override fun failRegistration(message: String) {
104
+ callManager.failRegistration()
105
+ }
106
+
107
+ override fun callUser(userId: String): String {
108
+ return callManager.callUser(userId)
109
+ }
110
+
111
+ override fun callPhoneNumber(phoneNumber: String, callerId: String): String {
112
+ return callManager.callPhoneNumber(phoneNumber, callerId)
113
+ }
114
+
115
+ override fun callConference(conferenceId: String, callerId: String): String {
116
+ return callManager.callConference(conferenceId, callerId)
117
+ }
118
+
119
+ override fun configureCustomIncomingCallPush(idField: String, displayField: String) {
120
+ callManager.configureCustomIncomingCallPush(idField, displayField)
121
+ }
122
+
123
+ override fun reportIncomingCallUI(callId: String, displayName: String) {
124
+ callManager.reportIncomingCallUI(callId, displayName)
125
+ }
126
+
127
+ override fun resolveCallUIToConference(
128
+ callId: String,
129
+ conferenceId: String,
130
+ callerId: String
131
+ ): String {
132
+ return callManager.resolveCallUIToConference(callId, conferenceId, callerId)
133
+ }
134
+
135
+ override fun dismissCallUI(callId: String) {
136
+ callManager.dismissCallUI(callId)
137
+ }
138
+
139
+ override fun updateIncomingCallDisplayName(callId: String, displayName: String) {
140
+ callManager.updateIncomingCallDisplayName(callId, displayName)
141
+ }
142
+
143
+ override fun answerCall(callId: String) {
144
+ callManager.answerCall(callId)
145
+ }
146
+
147
+ override fun hangupCall(callId: String) {
148
+ callManager.hangupCall(callId)
149
+ }
150
+
151
+ override fun sendDTMF(callId: String, key: String): Boolean {
152
+ return callManager.sendDTMF(callId, key)
153
+ }
154
+
155
+ override fun setMuted(muted: Boolean) {
156
+ callManager.setMuted(muted)
157
+ }
158
+
159
+ override fun setSpeakerEnabled(enabled: Boolean) {
160
+ callManager.setSpeakerEnabled(enabled)
161
+ }
162
+
163
+ override fun registerFcmPush(senderId: String, token: String) {
164
+ callManager.registerFcmPush(senderId, token)
165
+ }
166
+
167
+ override fun enablePushNotifications(useProductionAps: Boolean) {
168
+ // iOS only — Android push is wired via registerFcmPush + relayRemotePushNotification.
169
+ }
170
+
171
+ override fun relayRemotePushNotification(payload: ReadableMap) {
172
+ val data = mutableMapOf<String, String>()
173
+ val iterator = payload.keySetIterator()
174
+ while (iterator.hasNextKey()) {
175
+ val key = iterator.nextKey()
176
+ data[key] = payload.getString(key) ?: continue
177
+ }
178
+ callManager.relayRemotePushNotification(data)
179
+ }
180
+
181
+ companion object {
182
+ const val NAME = NativeSinchCallingSpec.NAME
183
+ }
184
+ }
@@ -0,0 +1,31 @@
1
+ package com.sinchcalling
2
+
3
+ import com.facebook.react.BaseReactPackage
4
+ import com.facebook.react.bridge.NativeModule
5
+ import com.facebook.react.bridge.ReactApplicationContext
6
+ import com.facebook.react.module.model.ReactModuleInfo
7
+ import com.facebook.react.module.model.ReactModuleInfoProvider
8
+ import java.util.HashMap
9
+
10
+ class SinchCallingPackage : BaseReactPackage() {
11
+ override fun getModule(name: String, reactContext: ReactApplicationContext): NativeModule? {
12
+ return if (name == SinchCallingModule.NAME) {
13
+ SinchCallingModule(reactContext)
14
+ } else {
15
+ null
16
+ }
17
+ }
18
+
19
+ override fun getReactModuleInfoProvider() = ReactModuleInfoProvider {
20
+ mapOf(
21
+ SinchCallingModule.NAME to ReactModuleInfo(
22
+ name = SinchCallingModule.NAME,
23
+ className = SinchCallingModule.NAME,
24
+ canOverrideExistingModule = false,
25
+ needsEagerInit = false,
26
+ isCxxModule = false,
27
+ isTurboModule = true
28
+ )
29
+ )
30
+ }
31
+ }
@@ -0,0 +1,43 @@
1
+ package com.sinchcalling.telecom
2
+
3
+ import android.telecom.Connection
4
+ import android.telecom.DisconnectCause
5
+
6
+ class SinchConnection(var callId: String) : Connection() {
7
+ init {
8
+ setConnectionProperties(PROPERTY_SELF_MANAGED)
9
+ setAudioModeIsVoip(true)
10
+ }
11
+
12
+ override fun onAnswer() {
13
+ if (SinchTelecomManager.isExternallyReported(callId)) {
14
+ // Not a real call yet — stay ringing until the consumer app resolves
15
+ // it and `remapCallId` + `reportCallActive` bring it to the active state.
16
+ SinchTelecomManager.listener?.onAnswerExternal(callId)
17
+ } else {
18
+ setActive()
19
+ SinchTelecomManager.listener?.onAnswer(callId)
20
+ }
21
+ }
22
+
23
+ override fun onReject() {
24
+ setDisconnected(DisconnectCause(DisconnectCause.REJECTED))
25
+ destroy()
26
+ val wasExternallyReported = SinchTelecomManager.isExternallyReported(callId)
27
+ SinchTelecomManager.unregisterConnection(callId)
28
+ SinchTelecomManager.clearExternallyReported(callId)
29
+ if (wasExternallyReported) {
30
+ SinchTelecomManager.listener?.onDeclineExternal(callId)
31
+ } else {
32
+ SinchTelecomManager.listener?.onReject(callId)
33
+ }
34
+ }
35
+
36
+ override fun onDisconnect() {
37
+ setDisconnected(DisconnectCause(DisconnectCause.LOCAL))
38
+ destroy()
39
+ SinchTelecomManager.unregisterConnection(callId)
40
+ SinchTelecomManager.clearExternallyReported(callId)
41
+ SinchTelecomManager.listener?.onDisconnect(callId)
42
+ }
43
+ }
@@ -0,0 +1,37 @@
1
+ package com.sinchcalling.telecom
2
+
3
+ import android.net.Uri
4
+ import android.telecom.Connection
5
+ import android.telecom.ConnectionRequest
6
+ import android.telecom.ConnectionService
7
+ import android.telecom.PhoneAccount
8
+ import android.telecom.PhoneAccountHandle
9
+ import android.telecom.TelecomManager
10
+
11
+ // A PSTN incoming call's remote id is the caller's phone number; an
12
+ // app-to-app call's is our own opaque Sinch userId. Distinguishing them lets
13
+ // the system dialer show/format the caller ID correctly.
14
+ private val PHONE_NUMBER_REGEX = Regex("^\\+?[0-9]{6,15}$")
15
+
16
+ class SinchConnectionService : ConnectionService() {
17
+ override fun onCreateIncomingConnection(
18
+ connectionManagerPhoneAccount: PhoneAccountHandle,
19
+ request: ConnectionRequest
20
+ ): Connection {
21
+ val callId = request.extras?.getString(SinchTelecomManager.EXTRA_CALL_ID) ?: ""
22
+ val remoteUserId = request.extras?.getString(SinchTelecomManager.EXTRA_REMOTE_USER_ID) ?: ""
23
+
24
+ val connection = SinchConnection(callId)
25
+ connection.setCallerDisplayName(remoteUserId, TelecomManager.PRESENTATION_ALLOWED)
26
+ val addressUri = if (PHONE_NUMBER_REGEX.matches(remoteUserId)) {
27
+ Uri.fromParts(PhoneAccount.SCHEME_TEL, remoteUserId, null)
28
+ } else {
29
+ Uri.fromParts("sinch", remoteUserId, null)
30
+ }
31
+ connection.setAddress(addressUri, TelecomManager.PRESENTATION_ALLOWED)
32
+ connection.setRinging()
33
+
34
+ SinchTelecomManager.registerConnection(callId, connection)
35
+ return connection
36
+ }
37
+ }
@@ -0,0 +1,106 @@
1
+ package com.sinchcalling.telecom
2
+
3
+ import android.content.ComponentName
4
+ import android.content.Context
5
+ import android.os.Bundle
6
+ import android.telecom.DisconnectCause
7
+ import android.telecom.PhoneAccount
8
+ import android.telecom.PhoneAccountHandle
9
+ import android.telecom.TelecomManager
10
+
11
+ interface SinchTelecomListener {
12
+ fun onAnswer(callId: String)
13
+ fun onReject(callId: String)
14
+ fun onDisconnect(callId: String)
15
+ // Fired instead of the three methods above when the call was reported via
16
+ // `reportExternalIncomingCall` and hasn't been resolved into a real Sinch
17
+ // call yet (see `remapCallId`) — answering/declining it is the consumer
18
+ // app's business, not the native call API's.
19
+ fun onAnswerExternal(callId: String)
20
+ fun onDeclineExternal(callId: String)
21
+ }
22
+
23
+ object SinchTelecomManager {
24
+ const val EXTRA_CALL_ID = "com.sinchcalling.EXTRA_CALL_ID"
25
+ const val EXTRA_REMOTE_USER_ID = "com.sinchcalling.EXTRA_REMOTE_USER_ID"
26
+ private const val ACCOUNT_ID = "sinch_calling_account"
27
+
28
+ var listener: SinchTelecomListener? = null
29
+
30
+ private val connections = mutableMapOf<String, SinchConnection>()
31
+ private val externallyReportedCallIds = mutableSetOf<String>()
32
+
33
+ fun phoneAccountHandle(context: Context): PhoneAccountHandle {
34
+ val componentName = ComponentName(context, SinchConnectionService::class.java)
35
+ return PhoneAccountHandle(componentName, ACCOUNT_ID)
36
+ }
37
+
38
+ fun registerPhoneAccount(context: Context) {
39
+ val telecomManager = context.getSystemService(TelecomManager::class.java) ?: return
40
+ val account = PhoneAccount.builder(phoneAccountHandle(context), "SinchCalling")
41
+ .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
42
+ .build()
43
+ telecomManager.registerPhoneAccount(account)
44
+ }
45
+
46
+ fun reportIncomingCall(context: Context, callId: String, remoteUserId: String) {
47
+ val telecomManager = context.getSystemService(TelecomManager::class.java) ?: return
48
+ val extras = Bundle().apply {
49
+ putString(EXTRA_CALL_ID, callId)
50
+ putString(EXTRA_REMOTE_USER_ID, remoteUserId)
51
+ }
52
+ telecomManager.addNewIncomingCall(phoneAccountHandle(context), extras)
53
+ }
54
+
55
+ // A call the consumer app decided to show a system call UI for (a custom
56
+ // push, a socket event, anything) — not a Sinch-native incoming call.
57
+ // Answering/declining goes through the app's own logic instead of the
58
+ // native call API until `remapCallId` ties it to a real call.
59
+ fun reportExternalIncomingCall(context: Context, callId: String, displayName: String) {
60
+ externallyReportedCallIds.add(callId)
61
+ reportIncomingCall(context, callId, displayName)
62
+ }
63
+
64
+ internal fun isExternallyReported(callId: String): Boolean = externallyReportedCallIds.contains(callId)
65
+
66
+ internal fun clearExternallyReported(callId: String) {
67
+ externallyReportedCallIds.remove(callId)
68
+ }
69
+
70
+ // Re-associates the system call UI already showing for `oldCallId` (an
71
+ // externally-reported, not-yet-real call) with the real Sinch call
72
+ // created once the consumer app resolved it.
73
+ fun remapCallId(oldCallId: String, newCallId: String) {
74
+ val connection = connections.remove(oldCallId) ?: return
75
+ connection.callId = newCallId
76
+ connections[newCallId] = connection
77
+ externallyReportedCallIds.remove(oldCallId)
78
+ }
79
+
80
+ // Overrides the caller name shown on the system call UI (e.g. once a
81
+ // caller-ID lookup resolves).
82
+ fun updateCallerDisplayName(callId: String, displayName: String) {
83
+ connections[callId]?.setCallerDisplayName(displayName, TelecomManager.PRESENTATION_ALLOWED)
84
+ }
85
+
86
+ fun reportCallActive(callId: String) {
87
+ connections[callId]?.setActive()
88
+ }
89
+
90
+ fun reportCallEnded(callId: String) {
91
+ connections[callId]?.let {
92
+ it.setDisconnected(DisconnectCause(DisconnectCause.REMOTE))
93
+ it.destroy()
94
+ }
95
+ connections.remove(callId)
96
+ externallyReportedCallIds.remove(callId)
97
+ }
98
+
99
+ internal fun registerConnection(callId: String, connection: SinchConnection) {
100
+ connections[callId] = connection
101
+ }
102
+
103
+ internal fun unregisterConnection(callId: String) {
104
+ connections.remove(callId)
105
+ }
106
+ }