-
Notifications
You must be signed in to change notification settings - Fork 20
/
WireActivityViewModel.kt
561 lines (506 loc) · 22.7 KB
/
WireActivityViewModel.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
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
/*
* Wire
* Copyright (C) 2024 Wire Swiss GmbH
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.wire.android.ui
import android.content.Intent
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.wire.android.BuildConfig
import com.wire.android.appLogger
import com.wire.android.datastore.GlobalDataStore
import com.wire.android.di.AuthServerConfigProvider
import com.wire.android.di.KaliumCoreLogic
import com.wire.android.di.ObserveIfE2EIRequiredDuringLoginUseCaseProvider
import com.wire.android.di.ObserveScreenshotCensoringConfigUseCaseProvider
import com.wire.android.di.ObserveSyncStateUseCaseProvider
import com.wire.android.feature.AccountSwitchUseCase
import com.wire.android.feature.SwitchAccountActions
import com.wire.android.feature.SwitchAccountParam
import com.wire.android.feature.SwitchAccountResult
import com.wire.android.migration.MigrationManager
import com.wire.android.services.ServicesManager
import com.wire.android.ui.authentication.devices.model.displayName
import com.wire.android.ui.common.dialogs.CustomServerDialogState
import com.wire.android.ui.joinConversation.JoinConversationViaCodeState
import com.wire.android.ui.theme.ThemeOption
import com.wire.android.util.CurrentScreen
import com.wire.android.util.CurrentScreenManager
import com.wire.android.util.deeplink.DeepLinkProcessor
import com.wire.android.util.deeplink.DeepLinkResult
import com.wire.android.util.dispatchers.DispatcherProvider
import com.wire.android.util.ui.UIText
import com.wire.kalium.logic.CoreLogic
import com.wire.kalium.logic.configuration.server.ServerConfig
import com.wire.kalium.logic.data.auth.AccountInfo
import com.wire.kalium.logic.data.client.Client
import com.wire.kalium.logic.data.id.ConversationId
import com.wire.kalium.logic.data.logout.LogoutReason
import com.wire.kalium.logic.data.sync.SyncState
import com.wire.kalium.logic.data.user.UserId
import com.wire.kalium.logic.feature.appVersioning.ObserveIfAppUpdateRequiredUseCase
import com.wire.kalium.logic.feature.client.ClearNewClientsForUserUseCase
import com.wire.kalium.logic.feature.client.NewClientResult
import com.wire.kalium.logic.feature.client.ObserveNewClientsUseCase
import com.wire.kalium.logic.feature.conversation.CheckConversationInviteCodeUseCase
import com.wire.kalium.logic.feature.server.GetServerConfigResult
import com.wire.kalium.logic.feature.server.GetServerConfigUseCase
import com.wire.kalium.logic.feature.session.CurrentSessionFlowUseCase
import com.wire.kalium.logic.feature.session.CurrentSessionResult
import com.wire.kalium.logic.feature.session.DoesValidSessionExistResult
import com.wire.kalium.logic.feature.session.DoesValidSessionExistUseCase
import com.wire.kalium.logic.feature.session.GetAllSessionsResult
import com.wire.kalium.logic.feature.session.GetSessionsUseCase
import com.wire.kalium.logic.feature.user.screenshotCensoring.ObserveScreenshotCensoringConfigResult
import com.wire.kalium.logic.feature.user.webSocketStatus.ObservePersistentWebSocketConnectionStatusUseCase
import com.wire.kalium.util.DateTimeUtil.toIsoDateTimeString
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.ExperimentalCoroutinesApi
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.distinctUntilChanged
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.flatMapLatest
import kotlinx.coroutines.flow.flowOf
import kotlinx.coroutines.flow.flowOn
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.flow.shareIn
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.withContext
import javax.inject.Inject
@Suppress("LongParameterList", "TooManyFunctions")
@OptIn(ExperimentalCoroutinesApi::class)
@HiltViewModel
class WireActivityViewModel @Inject constructor(
@KaliumCoreLogic private val coreLogic: CoreLogic,
private val dispatchers: DispatcherProvider,
private val currentSessionFlow: CurrentSessionFlowUseCase,
private val doesValidSessionExist: DoesValidSessionExistUseCase,
private val getServerConfigUseCase: GetServerConfigUseCase,
private val deepLinkProcessor: DeepLinkProcessor,
private val authServerConfigProvider: AuthServerConfigProvider,
private val getSessions: GetSessionsUseCase,
private val accountSwitch: AccountSwitchUseCase,
private val migrationManager: MigrationManager,
private val servicesManager: ServicesManager,
private val observeSyncStateUseCaseProviderFactory: ObserveSyncStateUseCaseProvider.Factory,
private val observeIfAppUpdateRequired: ObserveIfAppUpdateRequiredUseCase,
private val observeNewClients: ObserveNewClientsUseCase,
private val clearNewClientsForUser: ClearNewClientsForUserUseCase,
private val currentScreenManager: CurrentScreenManager,
private val observeScreenshotCensoringConfigUseCaseProviderFactory: ObserveScreenshotCensoringConfigUseCaseProvider.Factory,
private val globalDataStore: GlobalDataStore,
private val observeIfE2EIRequiredDuringLoginUseCaseProviderFactory: ObserveIfE2EIRequiredDuringLoginUseCaseProvider.Factory
) : ViewModel() {
var globalAppState: GlobalAppState by mutableStateOf(GlobalAppState())
private set
private val observeUserId = currentSessionFlow()
.distinctUntilChanged()
.onEach {
if (it is CurrentSessionResult.Success) {
if (it.accountInfo.isValid().not()) {
handleInvalidSession((it.accountInfo as AccountInfo.Invalid).logoutReason)
}
}
}
.map { result ->
if (result is CurrentSessionResult.Success) {
if (result.accountInfo.isValid()) {
result.accountInfo.userId
} else {
null
}
} else {
null
}
}
.distinctUntilChanged()
.flowOn(dispatchers.io())
.shareIn(viewModelScope, SharingStarted.WhileSubscribed(), 1)
private val _observeSyncFlowState: MutableStateFlow<SyncState?> = MutableStateFlow(null)
val observeSyncFlowState: StateFlow<SyncState?> = _observeSyncFlowState
private val _observeE2EIState: MutableStateFlow<Boolean?> = MutableStateFlow(null)
private val observeE2EIState: StateFlow<Boolean?> = _observeE2EIState
init {
observeSyncState()
observeUpdateAppState()
observeNewClientState()
observeScreenshotCensoringConfigState()
observeAppThemeState()
observerE2EIState()
}
private fun observeAppThemeState() {
viewModelScope.launch(dispatchers.io()) {
globalDataStore.selectedThemeOptionFlow()
.distinctUntilChanged()
.collect {
globalAppState = globalAppState.copy(themeOption = it)
}
}
}
fun observerE2EIState() {
viewModelScope.launch(dispatchers.io()) {
observeUserId
.flatMapLatest {
it?.let { observeIfE2EIRequiredDuringLoginUseCaseProviderFactory.create(it).observeIfE2EIIsRequiredDuringLogin() }
?: flowOf(null)
}
.distinctUntilChanged()
.collect { _observeE2EIState.emit(it) }
}
}
private fun observeSyncState() {
viewModelScope.launch(dispatchers.io()) {
observeUserId
.flatMapLatest {
it?.let { observeSyncStateUseCaseProviderFactory.create(it).observeSyncState() } ?: flowOf(null)
}
.distinctUntilChanged()
.collect { _observeSyncFlowState.emit(it) }
}
}
private fun observeUpdateAppState() {
viewModelScope.launch(dispatchers.io()) {
observeIfAppUpdateRequired(BuildConfig.VERSION_CODE)
.distinctUntilChanged()
.collect {
globalAppState = globalAppState.copy(updateAppDialog = it)
}
}
}
private fun observeNewClientState() {
viewModelScope.launch(dispatchers.io()) {
currentScreenManager.observeCurrentScreen(this)
.flatMapLatest {
if (it.isGlobalDialogAllowed()) observeNewClients()
else flowOf(NewClientResult.Empty)
}
.collect {
val newClientDialog = NewClientsData.fromUseCaseResul(it)
globalAppState = globalAppState.copy(newClientDialog = newClientDialog)
}
}
}
private fun observeScreenshotCensoringConfigState() {
viewModelScope.launch(dispatchers.io()) {
observeUserId
.flatMapLatest {
it?.let {
observeScreenshotCensoringConfigUseCaseProviderFactory.create(it).observeScreenshotCensoringConfig()
} ?: flowOf(ObserveScreenshotCensoringConfigResult.Disabled)
}.collect {
globalAppState = globalAppState.copy(
screenshotCensoringEnabled = it is ObserveScreenshotCensoringConfigResult.Enabled
)
}
}
}
private suspend fun handleInvalidSession(logoutReason: LogoutReason) {
withContext(dispatchers.main()) {
when (logoutReason) {
LogoutReason.SELF_SOFT_LOGOUT, LogoutReason.SELF_HARD_LOGOUT -> {
// Self logout is handled from the Self user profile screen directly
}
LogoutReason.REMOVED_CLIENT ->
globalAppState = globalAppState.copy(blockUserUI = CurrentSessionErrorState.RemovedClient)
LogoutReason.DELETED_ACCOUNT ->
globalAppState = globalAppState.copy(blockUserUI = CurrentSessionErrorState.DeletedAccount)
LogoutReason.SESSION_EXPIRED ->
globalAppState = globalAppState.copy(blockUserUI = CurrentSessionErrorState.SessionExpired)
}
}
}
val initialAppState: InitialAppState
get() = when {
shouldMigrate() -> InitialAppState.NOT_MIGRATED
shouldLogIn() -> InitialAppState.NOT_LOGGED_IN
blockedByE2EI() -> InitialAppState.ENROLL_E2EI
else -> InitialAppState.LOGGED_IN
}
fun isSharingIntent(intent: Intent?): Boolean {
return intent?.action == Intent.ACTION_SEND || intent?.action == Intent.ACTION_SEND_MULTIPLE
}
@Suppress("ComplexMethod")
fun handleDeepLink(
intent: Intent?,
onIsSharingIntent: () -> Unit,
onOpenConversation: (ConversationId) -> Unit,
onResult: (DeepLinkResult) -> Unit
) {
if (shouldMigrate()) {
// means User is Logged in, but didn't finish the migration yet.
// so we need to finish migration first.
return
}
viewModelScope.launch {
val result = intent?.data?.let { deepLinkProcessor(it) }
when {
result is DeepLinkResult.SSOLogin -> onResult(result)
result is DeepLinkResult.MigrationLogin -> onResult(result)
result is DeepLinkResult.CustomServerConfig -> onCustomServerConfig(result)
isSharingIntent(intent) -> onIsSharingIntent()
shouldLogIn() -> {
// to handle the deepLinks above user needs to be Logged in
// do nothing, already handled by initialAppState
}
result is DeepLinkResult.JoinConversation ->
onConversationInviteDeepLink(result.code, result.key, result.domain, onOpenConversation)
result != null -> onResult(result)
result is DeepLinkResult.Unknown -> appLogger.e("unknown deeplink result $result")
}
}
}
fun dismissCustomBackendDialog() {
globalAppState = globalAppState.copy(customBackendDialog = null)
}
fun customBackendDialogProceedButtonClicked(onProceed: () -> Unit) {
if (globalAppState.customBackendDialog != null) {
viewModelScope.launch {
authServerConfigProvider.updateAuthServer(globalAppState.customBackendDialog!!.serverLinks)
dismissCustomBackendDialog()
if (checkNumberOfSessions() >= BuildConfig.MAX_ACCOUNTS) {
globalAppState = globalAppState.copy(maxAccountDialog = true)
} else {
onProceed()
}
}
}
}
// TODO: needs to be covered with test once hard logout is validated to be used
fun doHardLogout(
clearUserData: (userId: UserId) -> Unit,
switchAccountActions: SwitchAccountActions
) {
viewModelScope.launch {
coreLogic.getGlobalScope().session.currentSession().takeIf {
it is CurrentSessionResult.Success
}?.let {
val currentUserId = (it as CurrentSessionResult.Success).accountInfo.userId
coreLogic.getSessionScope(currentUserId).logout(LogoutReason.SELF_HARD_LOGOUT)
clearUserData(currentUserId)
}
accountSwitch(SwitchAccountParam.TryToSwitchToNextAccount).also {
if (it == SwitchAccountResult.NoOtherAccountToSwitch) {
globalDataStore.clearAppLockPasscode()
}
}.callAction(switchAccountActions)
}
}
fun dismissNewClientsDialog(userId: UserId) {
globalAppState = globalAppState.copy(newClientDialog = null)
viewModelScope.launch {
doesValidSessionExist(userId).let {
if (it is DoesValidSessionExistResult.Success && it.doesValidSessionExist) {
clearNewClientsForUser(userId)
}
}
}
}
fun switchAccount(userId: UserId, actions: SwitchAccountActions, onComplete: () -> Unit) {
viewModelScope.launch {
accountSwitch(SwitchAccountParam.SwitchToAccount(userId))
.callAction(actions)
onComplete()
}
}
fun tryToSwitchAccount(actions: SwitchAccountActions) {
viewModelScope.launch {
globalAppState = globalAppState.copy(blockUserUI = null)
accountSwitch(SwitchAccountParam.TryToSwitchToNextAccount)
.callAction(actions)
}
}
private suspend fun checkNumberOfSessions(): Int {
getSessions().let {
return when (it) {
is GetAllSessionsResult.Success -> {
it.sessions.filterIsInstance<AccountInfo.Valid>().size
}
is GetAllSessionsResult.Failure.Generic -> 0
GetAllSessionsResult.Failure.NoSessionFound -> 0
}
}
}
private suspend fun loadServerConfig(url: String): ServerConfig.Links? = when (val result = getServerConfigUseCase(url)) {
is GetServerConfigResult.Success -> result.serverConfigLinks
// TODO: show error message on failure
is GetServerConfigResult.Failure.Generic -> {
appLogger.e("something went wrong during handling the custom server deep link: ${result.genericFailure}")
null
}
}
private suspend fun onCustomServerConfig(result: DeepLinkResult.CustomServerConfig) {
loadServerConfig(result.url)?.let { serverLinks ->
globalAppState = globalAppState.copy(
customBackendDialog = CustomServerDialogState(
serverLinks = serverLinks
)
)
}
}
private suspend fun onConversationInviteDeepLink(
code: String,
key: String,
domain: String?,
onSuccess: (ConversationId) -> Unit
) = when (val currentSession = coreLogic.getGlobalScope().session.currentSession()) {
is CurrentSessionResult.Failure.Generic -> null
CurrentSessionResult.Failure.SessionNotFound -> null
is CurrentSessionResult.Success -> {
coreLogic.sessionScope(currentSession.accountInfo.userId) {
when (val result = conversations.checkIConversationInviteCode(code, key, domain)) {
is CheckConversationInviteCodeUseCase.Result.Success -> {
if (result.isSelfMember) {
// TODO; display messsage that user is already a member and ask if they want to navigate to the conversation
appLogger.d("user is already a member of the conversation")
onSuccess(result.conversationId)
} else {
globalAppState =
globalAppState.copy(
conversationJoinedDialog = JoinConversationViaCodeState.Show(
result.name,
code,
key,
domain,
result.isPasswordProtected
)
)
}
}
is CheckConversationInviteCodeUseCase.Result.Failure -> globalAppState =
globalAppState.copy(conversationJoinedDialog = JoinConversationViaCodeState.Error(result))
}
}
}
}
fun onJoinConversationFlowCompleted() {
globalAppState = globalAppState.copy(conversationJoinedDialog = null)
}
fun shouldLogIn(): Boolean = !hasValidCurrentSession()
fun blockedByE2EI(): Boolean {
return observeE2EIState.value == true
}
private fun hasValidCurrentSession(): Boolean = runBlocking {
// TODO: the usage of currentSessionFlow is a temporary solution, it should be replaced with a proper solution
currentSessionFlow().first().let {
when (it) {
is CurrentSessionResult.Failure.Generic -> false
CurrentSessionResult.Failure.SessionNotFound -> false
is CurrentSessionResult.Success -> true
}
}
}
fun shouldMigrate(): Boolean = runBlocking {
migrationManager.shouldMigrate()
}
fun dismissMaxAccountDialog() {
globalAppState = globalAppState.copy(maxAccountDialog = false)
}
fun observePersistentConnectionStatus() {
viewModelScope.launch {
coreLogic.getGlobalScope().observePersistentWebSocketConnectionStatus().let { result ->
when (result) {
is ObservePersistentWebSocketConnectionStatusUseCase.Result.Failure -> {
appLogger.e("Failure while fetching persistent web socket status flow from wire activity")
}
is ObservePersistentWebSocketConnectionStatusUseCase.Result.Success -> {
result.persistentWebSocketStatusListFlow.collect { statuses ->
if (statuses.any { it.isPersistentWebSocketEnabled }) {
if (!servicesManager.isPersistentWebSocketServiceRunning()) {
servicesManager.startPersistentWebSocketService()
}
} else {
servicesManager.stopPersistentWebSocketService()
}
}
}
}
}
}
}
private fun CurrentScreen.isGlobalDialogAllowed(): Boolean = when (this) {
CurrentScreen.ImportMedia,
CurrentScreen.DeviceManager -> false
CurrentScreen.InBackground,
is CurrentScreen.Conversation,
CurrentScreen.Home,
is CurrentScreen.CallScreen,
is CurrentScreen.OtherUserProfile,
CurrentScreen.AuthRelated,
CurrentScreen.SomeOther -> true
}
}
sealed class CurrentSessionErrorState {
data object RemovedClient : CurrentSessionErrorState()
data object DeletedAccount : CurrentSessionErrorState()
data object SessionExpired : CurrentSessionErrorState()
}
sealed class NewClientsData(open val clientsInfo: List<NewClientInfo>, open val userId: UserId) {
data class CurrentUser(
override val clientsInfo: List<NewClientInfo>,
override val userId: UserId
) : NewClientsData(clientsInfo, userId)
data class OtherUser(
override val clientsInfo: List<NewClientInfo>,
override val userId: UserId,
val userName: String?,
val userHandle: String?
) : NewClientsData(clientsInfo, userId)
companion object {
fun fromUseCaseResul(result: NewClientResult): NewClientsData? = when (result) {
is NewClientResult.InCurrentAccount -> {
CurrentUser(
result.newClients.map(NewClientInfo::fromClient),
result.userId
)
}
is NewClientResult.InOtherAccount -> {
OtherUser(
result.newClients.map(NewClientInfo::fromClient),
result.userId,
result.userName,
result.userHandle
)
}
else -> null
}
}
}
data class NewClientInfo(val date: String, val deviceInfo: UIText) {
companion object {
fun fromClient(client: Client): NewClientInfo =
NewClientInfo(client.registrationTime?.toIsoDateTimeString() ?: "", client.displayName())
}
}
data class GlobalAppState(
val customBackendDialog: CustomServerDialogState? = null,
val maxAccountDialog: Boolean = false,
val blockUserUI: CurrentSessionErrorState? = null,
val updateAppDialog: Boolean = false,
val conversationJoinedDialog: JoinConversationViaCodeState? = null,
val newClientDialog: NewClientsData? = null,
val screenshotCensoringEnabled: Boolean = true,
val themeOption: ThemeOption = ThemeOption.SYSTEM
)
enum class InitialAppState {
NOT_MIGRATED, NOT_LOGGED_IN, LOGGED_IN, ENROLL_E2EI
}