-
Notifications
You must be signed in to change notification settings - Fork 167
/
TelecomCallRepository.kt
329 lines (296 loc) · 11.5 KB
/
TelecomCallRepository.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
/*
* Copyright 2023 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.platform.connectivity.telecom.model
import android.content.Context
import android.net.Uri
import android.os.Build
import android.telecom.DisconnectCause
import android.util.Log
import androidx.annotation.RequiresApi
import androidx.core.telecom.CallAttributesCompat
import androidx.core.telecom.CallControlResult
import androidx.core.telecom.CallControlScope
import androidx.core.telecom.CallException
import androidx.core.telecom.CallsManager
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
/**
* The central repository that keeps track of the current call and allows to register new calls.
*
* This class contains the main logic to integrate with Telecom SDK.
*
* @see registerCall
*/
@RequiresApi(Build.VERSION_CODES.O)
class TelecomCallRepository(private val callsManager: CallsManager) {
companion object {
var instance: TelecomCallRepository? = null
private set
/**
* This does not illustrate best practices for instantiating classes in Android but for
* simplicity we use this create method to create a singleton with the CallsManager class.
*/
fun create(context: Context): TelecomCallRepository {
Log.d("MPB", "New instance")
check(instance == null) {
"CallRepository instance already created"
}
// Create the Jetpack Telecom entry point
val callsManager = CallsManager(context).apply {
// Register with the telecom interface with the supported capabilities
registerAppWithTelecom(
capabilities = CallsManager.CAPABILITY_SUPPORTS_CALL_STREAMING and
CallsManager.CAPABILITY_SUPPORTS_VIDEO_CALLING,
)
}
return TelecomCallRepository(
callsManager = callsManager,
).also {
instance = it
}
}
}
// Keeps track of the current TelecomCall state
private val _currentCall: MutableStateFlow<TelecomCall> = MutableStateFlow(TelecomCall.None)
val currentCall = _currentCall.asStateFlow()
/**
* Register a new call with the provided attributes.
* Use the [currentCall] StateFlow to receive status updates and process call related actions.
*/
suspend fun registerCall(displayName: String, address: Uri, isIncoming: Boolean) {
// For simplicity we don't support multiple calls
check(_currentCall.value !is TelecomCall.Registered) {
"There cannot be more than one call at the same time."
}
// Create the call attributes
val attributes = CallAttributesCompat(
displayName = displayName,
address = address,
direction = if (isIncoming) {
CallAttributesCompat.DIRECTION_INCOMING
} else {
CallAttributesCompat.DIRECTION_OUTGOING
},
callType = CallAttributesCompat.CALL_TYPE_AUDIO_CALL,
callCapabilities = (CallAttributesCompat.SUPPORTS_SET_INACTIVE
or CallAttributesCompat.SUPPORTS_STREAM
or CallAttributesCompat.SUPPORTS_TRANSFER),
)
// Creates a channel to send actions to the call scope.
val actionSource = Channel<TelecomCallAction>()
// Register the call and handle actions in the scope
try {
callsManager.addCall(
attributes,
onIsCallAnswered, // Watch needs to know if it can answer the call
onIsCallDisconnected,
onIsCallActive,
onIsCallInactive
) {
// Consume the actions to interact with the call inside the scope
launch {
processCallActions(actionSource.consumeAsFlow())
}
// Update the state to registered with default values while waiting for Telecom updates
_currentCall.value = TelecomCall.Registered(
id = getCallId(),
isActive = false,
isOnHold = false,
callAttributes = attributes,
isMuted = false,
errorCode = null,
currentCallEndpoint = null,
availableCallEndpoints = emptyList(),
actionSource = actionSource,
)
launch {
currentCallEndpoint.collect {
updateCurrentCall {
copy(currentCallEndpoint = it)
}
}
}
launch {
availableEndpoints.collect {
updateCurrentCall {
copy(availableCallEndpoints = it)
}
}
}
launch {
isMuted.collect {
updateCurrentCall {
copy(isMuted = it)
}
}
}
}
} finally {
_currentCall.value = TelecomCall.None
}
}
/**
* Collect the action source to handle client actions inside the call scope
*/
private suspend fun CallControlScope.processCallActions(actionSource: Flow<TelecomCallAction>) {
actionSource.collect { action ->
when (action) {
is TelecomCallAction.Answer -> {
doAnswer()
}
is TelecomCallAction.Disconnect -> {
doDisconnect(action)
}
is TelecomCallAction.SwitchAudioEndpoint -> {
doSwitchEndpoint(action)
}
is TelecomCallAction.TransferCall -> {
val call = _currentCall.value as? TelecomCall.Registered
val endpoints = call?.availableCallEndpoints?.firstOrNull {
it.identifier == action.endpointId
}
requestEndpointChange(
endpoint = endpoints ?: return@collect,
)
}
TelecomCallAction.Hold -> {
when (val result = setInactive()) {
is CallControlResult.Success -> {
onIsCallInactive()
}
is CallControlResult.Error -> {
updateCurrentCall {
copy(errorCode = result.errorCode)
}
}
}
}
TelecomCallAction.Activate -> {
when (val result = setActive()) {
is CallControlResult.Success -> {
onIsCallActive()
}
is CallControlResult.Error -> {
updateCurrentCall {
copy(errorCode = result.errorCode)
}
}
}
}
is TelecomCallAction.ToggleMute -> {
// We cannot programmatically mute the telecom stack. Instead we just update
// the state of the call and this will start/stop audio capturing.
updateCurrentCall {
copy(isMuted = !isMuted)
}
}
}
}
}
/**
* Update the current state of our call applying the transform lambda only if the call is
* registered. Otherwise keep the current state
*/
private fun updateCurrentCall(transform: TelecomCall.Registered.() -> TelecomCall) {
_currentCall.update { call ->
if (call is TelecomCall.Registered) {
call.transform()
} else {
call
}
}
}
private suspend fun CallControlScope.doSwitchEndpoint(action: TelecomCallAction.SwitchAudioEndpoint) {
// TODO once availableCallEndpoints is a state flow we can just get the value
val endpoints = (_currentCall.value as TelecomCall.Registered).availableCallEndpoints
// Switch to the given endpoint or fallback to the best possible one.
val newEndpoint = endpoints.firstOrNull { it.identifier == action.endpointId }
if (newEndpoint != null) {
requestEndpointChange(newEndpoint).also {
Log.d("MPB", "Endpoint ${newEndpoint.name} changed: $it")
}
}
}
private suspend fun CallControlScope.doDisconnect(action: TelecomCallAction.Disconnect) {
disconnect(action.cause)
onIsCallDisconnected(action.cause)
}
private suspend fun CallControlScope.doAnswer() {
when (answer(CallAttributesCompat.CALL_TYPE_AUDIO_CALL)) {
is CallControlResult.Success -> {
onIsCallAnswered(CallAttributesCompat.CALL_TYPE_AUDIO_CALL)
}
is CallControlResult.Error -> {
updateCurrentCall {
TelecomCall.Unregistered(
id = id,
callAttributes = callAttributes,
disconnectCause = DisconnectCause(DisconnectCause.BUSY),
)
}
}
}
}
/**
* Can the call be successfully answered??
* TIP: We would check the connection/call state to see if we can answer a call
* Example you may need to wait for another call to hold.
**/
val onIsCallAnswered: suspend(type: Int) -> Unit = {
updateCurrentCall {
copy(isActive = true, isOnHold = false)
}
}
/**
* Can the call perform a disconnect
*/
val onIsCallDisconnected: suspend (cause: DisconnectCause) -> Unit = {
updateCurrentCall {
TelecomCall.Unregistered(id, callAttributes, it)
}
}
/**
* Check is see if we can make the call active.
* Other calls and state might stop us from activating the call
*/
val onIsCallActive: suspend () -> Unit = {
updateCurrentCall {
copy(
errorCode = null,
isActive = true,
isOnHold = false,
)
}
}
/**
* Check to see if we can make the call inactivate
*/
val onIsCallInactive: suspend () -> Unit = {
updateCurrentCall {
copy(
errorCode = null,
isOnHold = true)
}
}
}