-
Notifications
You must be signed in to change notification settings - Fork 57
Expand file tree
/
Copy pathStreamVideoInitHelper.kt
More file actions
237 lines (209 loc) · 8.91 KB
/
StreamVideoInitHelper.kt
File metadata and controls
237 lines (209 loc) · 8.91 KB
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
/*
* Copyright (c) 2014-2024 Stream.io Inc. All rights reserved.
*
* Licensed under the Stream License;
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://github.com/GetStream/stream-video-android/blob/main/LICENSE
*
* 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 io.getstream.video.android.util
import android.annotation.SuppressLint
import android.content.Context
import android.media.AudioAttributes
import android.util.Log
import io.getstream.android.push.firebase.FirebasePushDeviceGenerator
import io.getstream.chat.android.client.ChatClient
import io.getstream.chat.android.client.logger.ChatLogLevel
import io.getstream.chat.android.offline.plugin.factory.StreamOfflinePluginFactory
import io.getstream.chat.android.state.plugin.config.StatePluginConfig
import io.getstream.chat.android.state.plugin.factory.StreamStatePluginFactory
import io.getstream.log.Priority
import io.getstream.video.android.BuildConfig
import io.getstream.video.android.core.StreamVideo
import io.getstream.video.android.core.StreamVideoBuilder
import io.getstream.video.android.core.call.CallType
import io.getstream.video.android.core.logging.LoggingLevel
import io.getstream.video.android.core.notifications.NotificationConfig
import io.getstream.video.android.core.notifications.internal.service.CallServiceConfigRegistry
import io.getstream.video.android.core.notifications.internal.service.DefaultCallConfigurations
import io.getstream.video.android.core.socket.common.token.TokenProvider
import io.getstream.video.android.data.services.stream.GetAuthDataResponse
import io.getstream.video.android.data.services.stream.StreamService
import io.getstream.video.android.datastore.delegate.StreamUserDataStore
import io.getstream.video.android.model.ApiKey
import io.getstream.video.android.model.User
import io.getstream.video.android.noise.cancellation.NoiseCancellation
import io.getstream.video.android.util.config.AppConfig
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.firstOrNull
public enum class InitializedState {
NOT_STARTED, RUNNING, FINISHED, FAILED
}
@SuppressLint("StaticFieldLeak")
object StreamVideoInitHelper {
private var isInitialising = false
private lateinit var context: Context
private val _initState = MutableStateFlow(InitializedState.NOT_STARTED)
public val initializedState: StateFlow<InitializedState> = _initState
fun init(appContext: Context) {
context = appContext.applicationContext
}
suspend fun reloadSdk(
dataStore: StreamUserDataStore,
useRandomUserAsFallback: Boolean = true,
) {
StreamVideo.removeClient()
loadSdk(dataStore, useRandomUserAsFallback)
}
/**
* A helper function that will initialise the [StreamVideo] SDK and also the [ChatClient].
* Set [useRandomUserAsFallback] to true if you want to use a guest fallback if the user is not
* logged in.
*/
suspend fun loadSdk(
dataStore: StreamUserDataStore,
useRandomUserAsFallback: Boolean = true,
) = AppConfig.load(context) {
if (StreamVideo.isInstalled) {
_initState.value = InitializedState.FINISHED
Log.w("StreamVideoInitHelper", "[initStreamVideo] StreamVideo is already initialised.")
return@load
}
if (isInitialising) {
_initState.value = InitializedState.RUNNING
Log.d("StreamVideoInitHelper", "[initStreamVideo] StreamVideo is already initialising")
return@load
}
isInitialising = true
_initState.value = InitializedState.RUNNING
try {
// Load the signed-in user (can be null)
var loggedInUser = dataStore.data.firstOrNull()?.user
var authData: GetAuthDataResponse? = null
// Create and login a random new user if user is null and we allow a random user login
if (loggedInUser == null && useRandomUserAsFallback) {
val userId = UserHelper.generateRandomString()
authData = StreamService.instance.getAuthData(
environment = AppConfig.currentEnvironment.value!!.env,
userId = userId,
)
loggedInUser = User(id = authData.userId, role = "admin")
// Store the data (note that this datastore belongs to the client - it's not
// used by the SDK directly in any way)
dataStore.updateUser(loggedInUser)
}
// If we have a logged in user (from the data store or randomly created above)
// then we can initialise the SDK
if (loggedInUser != null) {
if (authData == null) {
authData = StreamService.instance.getAuthData(
environment = AppConfig.currentEnvironment.value!!.env,
userId = loggedInUser.id,
)
}
initializeStreamChat(
context = context,
apiKey = authData.apiKey,
user = loggedInUser,
token = authData.token,
)
initializeStreamVideo(
context = context,
apiKey = authData.apiKey,
user = loggedInUser,
token = authData.token,
loggingLevel = LoggingLevel(priority = Priority.VERBOSE),
)
}
Log.i("StreamVideoInitHelper", "Init successful.")
_initState.value = InitializedState.FINISHED
} catch (e: Exception) {
_initState.value = InitializedState.FAILED
Log.e("StreamVideoInitHelper", "Init failed.", e)
}
isInitialising = false
}
private fun initializeStreamChat(
context: Context,
apiKey: String,
user: User,
token: String,
) {
val offlinePlugin = StreamOfflinePluginFactory(context)
val statePluginFactory = StreamStatePluginFactory(
config = StatePluginConfig(
backgroundSyncEnabled = true,
userPresence = true,
),
appContext = context,
)
val logLevel = if (BuildConfig.DEBUG) ChatLogLevel.ALL else ChatLogLevel.NOTHING
val chatClient = ChatClient.Builder(apiKey, context)
.withPlugins(offlinePlugin, statePluginFactory)
.logLevel(logLevel)
.build()
val chatUser = io.getstream.chat.android.models.User(
id = user.id,
name = user.name.orEmpty(),
image = user.image.orEmpty(),
)
chatClient.connectUser(
user = chatUser,
token = token,
).enqueue()
}
/** Sets up and returns the [StreamVideo] required to connect to the API. */
private fun initializeStreamVideo(
context: Context,
apiKey: ApiKey,
user: User,
token: String,
loggingLevel: LoggingLevel,
): StreamVideo {
val callServiceConfigRegistry = CallServiceConfigRegistry()
callServiceConfigRegistry.createConfigRegistry {
register(DefaultCallConfigurations.getLivestreamGuestCallServiceConfig())
update(CallType.Default.name) {
setAudioUsage(AudioAttributes.USAGE_MEDIA)
setRunCallServiceInForeground(true)
}
update(CallType.Livestream.name) {
setRunCallServiceInForeground(true)
}
}
return StreamVideoBuilder(
context = context,
apiKey = apiKey,
user = user,
token = token,
loggingLevel = loggingLevel,
ensureSingleInstance = false,
notificationConfig = NotificationConfig(
pushDeviceGenerators = listOf(
FirebasePushDeviceGenerator(providerName = "firebase"),
),
),
tokenProvider = object : TokenProvider {
override suspend fun loadToken(): String {
val email = user.custom?.get("email")
val authData = StreamService.instance.getAuthData(
environment = AppConfig.currentEnvironment.value!!.env,
userId = email,
)
return authData.token
}
},
appName = "Stream Video Demo App",
audioProcessing = NoiseCancellation(context),
callServiceConfigRegistry = callServiceConfigRegistry,
).build()
}
}