-
Notifications
You must be signed in to change notification settings - Fork 19
/
AccountSwitchUseCase.kt
183 lines (168 loc) · 7.91 KB
/
AccountSwitchUseCase.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
/*
* 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.feature
import com.wire.android.appLogger
import com.wire.android.di.ApplicationScope
import com.wire.android.di.AuthServerConfigProvider
import com.wire.android.navigation.BackStackMode
import com.wire.android.navigation.NavigationCommand
import com.wire.android.ui.destinations.HomeScreenDestination
import com.wire.android.ui.destinations.WelcomeScreenDestination
import com.wire.kalium.logic.data.auth.AccountInfo
import com.wire.kalium.logic.data.logout.LogoutReason
import com.wire.kalium.logic.data.user.UserId
import com.wire.kalium.logic.feature.server.ServerConfigForAccountUseCase
import com.wire.kalium.logic.feature.session.CurrentSessionResult
import com.wire.kalium.logic.feature.session.CurrentSessionUseCase
import com.wire.kalium.logic.feature.session.DeleteSessionUseCase
import com.wire.kalium.logic.feature.session.GetAllSessionsResult
import com.wire.kalium.logic.feature.session.GetSessionsUseCase
import com.wire.kalium.logic.feature.session.UpdateCurrentSessionUseCase
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withTimeout
import kotlinx.serialization.encodeToString
import kotlinx.serialization.json.Json
import javax.inject.Inject
import javax.inject.Singleton
@Suppress("LongParameterList")
@Singleton
class AccountSwitchUseCase @Inject constructor(
private val updateCurrentSession: UpdateCurrentSessionUseCase,
private val getSessions: GetSessionsUseCase,
private val getCurrentSession: CurrentSessionUseCase,
private val deleteSession: DeleteSessionUseCase,
private val authServerConfigProvider: AuthServerConfigProvider,
private val serverConfigForAccountUseCase: ServerConfigForAccountUseCase,
@ApplicationScope private val coroutineScope: CoroutineScope
) {
val currentAccount
get() = coroutineScope.async {
when (val result = getCurrentSession()) {
is CurrentSessionResult.Failure.Generic -> null
CurrentSessionResult.Failure.SessionNotFound -> null
is CurrentSessionResult.Success -> result.accountInfo
}
}
suspend operator fun invoke(params: SwitchAccountParam): SwitchAccountResult {
val current = currentAccount.await()
appLogger.i("$TAG Switching account invoked: ${params.toLogString()}, current account: ${current?.userId?.toLogString() ?: "-"}")
return when (params) {
is SwitchAccountParam.SwitchToAccount -> switch(params.userId, current)
SwitchAccountParam.TryToSwitchToNextAccount -> getNextAccountIfPossibleAndSwitch(current)
SwitchAccountParam.Clear -> switch(null, current)
}
}
private suspend fun getNextAccountIfPossibleAndSwitch(current: AccountInfo?): SwitchAccountResult {
val nextSessionId: UserId? = getSessions().let {
when (it) {
is GetAllSessionsResult.Failure.Generic -> null
GetAllSessionsResult.Failure.NoSessionFound -> null
is GetAllSessionsResult.Success ->
it.sessions.firstOrNull { accountInfo ->
(accountInfo is AccountInfo.Valid) && (accountInfo.userId != current?.userId)
}?.userId
}
}
if (nextSessionId == null) appLogger.i("$TAG No next account to switch to")
else appLogger.i("$TAG Switching to next account: ${nextSessionId.toLogString()}")
return switch(nextSessionId, current)
}
private suspend fun switch(userId: UserId?, current: AccountInfo?): SwitchAccountResult {
val successResult = (userId?.let { SwitchAccountResult.SwitchedToAnotherAccount }) ?: run {
// if there are no more accounts, we need to change the auth server config to the one of the current user
current?.let { updateAuthServer(it.userId) }
SwitchAccountResult.NoOtherAccountToSwitch
}
return when (updateCurrentSession(userId)) {
is UpdateCurrentSessionUseCase.Result.Success -> {
current?.also {
handleOldSession(it)
}
successResult
}
is UpdateCurrentSessionUseCase.Result.Failure -> SwitchAccountResult.Failure
}
}
private suspend fun updateAuthServer(current: UserId) {
appLogger.i("$TAG Updating auth server config for account: ${current.toLogString()}")
serverConfigForAccountUseCase(current).let {
when (it) {
is ServerConfigForAccountUseCase.Result.Success -> authServerConfigProvider.updateAuthServer(it.config)
is ServerConfigForAccountUseCase.Result.Failure -> return
}
}
}
private fun handleOldSession(oldSession: AccountInfo) {
when (oldSession) {
is AccountInfo.Valid -> {
// do nothing
}
is AccountInfo.Invalid -> coroutineScope.launch {
withTimeout(DELETE_USER_SESSION_TIMEOUT) {
handleInvalidSession(oldSession)
}
}
}
}
private suspend fun handleInvalidSession(invalidAccount: AccountInfo.Invalid) {
appLogger.i("$TAG Handling invalid account: ${invalidAccount.userId.toLogString()}")
when (invalidAccount.logoutReason) {
LogoutReason.SELF_SOFT_LOGOUT, LogoutReason.SELF_HARD_LOGOUT -> {
deleteSession(invalidAccount.userId)
}
LogoutReason.DELETED_ACCOUNT,
LogoutReason.REMOVED_CLIENT,
LogoutReason.SESSION_EXPIRED -> deleteSession(invalidAccount.userId)
}
}
private companion object {
const val TAG = "AccountSwitch"
const val DELETE_USER_SESSION_TIMEOUT = 3000L
}
}
sealed class SwitchAccountParam {
data object TryToSwitchToNextAccount : SwitchAccountParam()
data class SwitchToAccount(val userId: UserId) : SwitchAccountParam()
data object Clear : SwitchAccountParam()
private fun toLogMap(): Map<String, String> = when (this) {
is Clear -> mutableMapOf("value" to "CLEAR")
is SwitchToAccount -> mutableMapOf("value" to "SWITCH_TO_ACCOUNT", "userId" to userId.toLogString())
is TryToSwitchToNextAccount -> mutableMapOf("value" to "TRY_TO_SWITCH_TO_NEXT_ACCOUNT")
}
fun toLogString(): String = Json.encodeToString(toLogMap())
}
sealed class SwitchAccountResult {
object Failure : SwitchAccountResult()
object SwitchedToAnotherAccount : SwitchAccountResult()
object NoOtherAccountToSwitch : SwitchAccountResult()
fun callAction(actions: SwitchAccountActions) = when (this) {
NoOtherAccountToSwitch -> actions.noOtherAccountToSwitch()
SwitchedToAnotherAccount -> actions.switchedToAnotherAccount()
else -> { /* do nothing */ }
}
}
interface SwitchAccountActions {
fun switchedToAnotherAccount()
fun noOtherAccountToSwitch()
}
class NavigationSwitchAccountActions(val navigate: (NavigationCommand) -> Unit) : SwitchAccountActions {
override fun switchedToAnotherAccount() = navigate(NavigationCommand(HomeScreenDestination, BackStackMode.CLEAR_WHOLE))
override fun noOtherAccountToSwitch() = navigate(NavigationCommand(WelcomeScreenDestination, BackStackMode.CLEAR_WHOLE))
}