-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPaymentPreferenceViewModel.kt
More file actions
303 lines (276 loc) · 11.9 KB
/
Copy pathPaymentPreferenceViewModel.kt
File metadata and controls
303 lines (276 loc) · 11.9 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
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
package to.bitkit.ui.settings.paymentPreference
import android.content.Context
import androidx.compose.runtime.Immutable
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import dagger.hilt.android.qualifiers.ApplicationContext
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import to.bitkit.R
import to.bitkit.data.SettingsData
import to.bitkit.data.SettingsStore
import to.bitkit.models.Toast
import to.bitkit.repositories.PrivatePaykitRepo
import to.bitkit.repositories.PubkyRepo
import to.bitkit.repositories.PublicPaykitError
import to.bitkit.repositories.PublicPaykitRepo
import to.bitkit.ui.shared.toast.ToastEventBus
import javax.inject.Inject
@HiltViewModel
class PaymentPreferenceViewModel @Inject constructor(
@ApplicationContext private val context: Context,
private val settingsStore: SettingsStore,
private val publicPaykitRepo: PublicPaykitRepo,
private val privatePaykitRepo: PrivatePaykitRepo,
private val pubkyRepo: PubkyRepo,
) : ViewModel() {
private val _uiState = MutableStateFlow(PaymentPreferenceUiState())
val uiState: StateFlow<PaymentPreferenceUiState> = _uiState.asStateFlow()
private val privateContactsPendingValue = MutableStateFlow<Boolean?>(null)
init {
viewModelScope.launch {
combine(
settingsStore.data,
pubkyRepo.isAuthenticated,
privateContactsPendingValue,
) { settings, isAuthenticated, pendingPrivateContactsEnabled ->
val canUsePrivateContacts = isAuthenticated && pubkyRepo.hasSecretKey()
if (!canUsePrivateContacts && settings.sharesPrivatePaykitEndpoints) {
settingsStore.update { it.copy(sharesPrivatePaykitEndpoints = false) }
}
PaymentPreferenceStateSource(
settings = settings,
isAuthenticated = isAuthenticated,
canUsePrivateContacts = canUsePrivateContacts,
pendingPrivateContactsEnabled = pendingPrivateContactsEnabled,
)
}.collect { stateSource ->
_uiState.update { it.from(stateSource) }
}
}
}
fun setLightningEnabled(isEnabled: Boolean) {
updatePaymentMethod(lightningEnabled = isEnabled)
}
fun setOnchainEnabled(isEnabled: Boolean) {
updatePaymentMethod(onchainEnabled = isEnabled)
}
fun setPrivateContactsEnabled(isEnabled: Boolean) {
if (_uiState.value.isUpdatingPrivateContacts) return
if (isEnabled && !_uiState.value.hasPubkyProfile) {
viewModelScope.launch { showSyncError(PublicPaykitError.SessionNotActive) }
return
}
if (isEnabled && !_uiState.value.canUsePrivateContacts) {
viewModelScope.launch { showSyncError(PublicPaykitError.SessionNotActive) }
return
}
viewModelScope.launch {
val previous = settingsStore.data.first()
privateContactsPendingValue.update { _uiState.value.privateContactsEnabled }
_uiState.update { it.copy(isUpdatingPrivateContacts = true) }
val result = runCatching {
settingsStore.update {
it.copy(
hasConfirmedPublicPaykitEndpoints = true,
sharesPrivatePaykitEndpoints = isEnabled,
)
}
}.mapCatching {
if (isEnabled) {
privatePaykitRepo.enableSharingAndPrepareSavedContacts(
publicKeys = contactPublicKeys(),
requireImmediatePublication = true,
).getOrThrow()
} else {
privatePaykitRepo.disableSharingAndPruneUnsavedContactState(contactPublicKeys()).getOrThrow()
}
}
result.exceptionOrNull()?.let {
rollbackPrivateContactsPreference(
requestedEnabled = isEnabled,
previous = previous,
error = it,
)
showSyncError(it)
}
privateContactsPendingValue.update { null }
_uiState.update { it.copy(isUpdatingPrivateContacts = false) }
}
}
fun setPublicContactsEnabled(isEnabled: Boolean) {
if (_uiState.value.isUpdatingPublicContacts) return
if (isEnabled && !_uiState.value.hasPubkyProfile) {
viewModelScope.launch { showSyncError(PublicPaykitError.SessionNotActive) }
return
}
viewModelScope.launch {
_uiState.update { it.copy(isUpdatingPublicContacts = true) }
val previous = settingsStore.data.first()
settingsStore.update {
it.copy(
hasConfirmedPublicPaykitEndpoints = true,
sharesPublicPaykitEndpoints = isEnabled,
)
}
publicPaykitRepo.syncPublishedEndpoints(publish = isEnabled).exceptionOrNull()?.let {
settingsStore.update { settings ->
settings.copy(sharesPublicPaykitEndpoints = previous.sharesPublicPaykitEndpoints)
}
showSyncError(it)
}
_uiState.update { it.copy(isUpdatingPublicContacts = false) }
}
}
private fun updatePaymentMethod(
lightningEnabled: Boolean = _uiState.value.lightningEnabled,
onchainEnabled: Boolean = _uiState.value.onchainEnabled,
) {
if (_uiState.value.isUpdatingPaymentOptions) return
if (!lightningEnabled && !onchainEnabled) {
viewModelScope.launch {
ToastEventBus.send(
type = Toast.ToastType.WARNING,
title = context.getString(R.string.common__error),
description = context.getString(R.string.settings__payment_pref_keep_one),
)
}
return
}
viewModelScope.launch {
_uiState.update { it.copy(isUpdatingPaymentOptions = true) }
val previous = settingsStore.data.first()
settingsStore.update {
it.copy(
publicPaykitLightningEnabled = lightningEnabled,
publicPaykitOnchainEnabled = onchainEnabled,
)
}
val result = refreshPublishedPreferences()
result.exceptionOrNull()?.let {
settingsStore.update { settings ->
settings.copy(
publicPaykitLightningEnabled = previous.publicPaykitLightningEnabled,
publicPaykitOnchainEnabled = previous.publicPaykitOnchainEnabled,
)
}
refreshPublishedPreferences()
showSyncError(it)
}
_uiState.update { it.copy(isUpdatingPaymentOptions = false) }
}
}
private suspend fun refreshPublishedPreferences(): Result<Unit> = runCatching {
val settings = settingsStore.data.first()
if (settings.sharesPublicPaykitEndpoints) {
publicPaykitRepo.syncCurrentPublishedEndpoints(
forceRefreshLightning = true,
requireEndpoint = true,
).getOrThrow()
}
if (settings.sharesPrivatePaykitEndpoints) {
if (pubkyRepo.hasSecretKey()) {
privatePaykitRepo.prepareSavedContacts(
publicKeys = contactPublicKeys(),
requireImmediatePublication = true,
).getOrThrow()
} else {
settingsStore.update { it.copy(sharesPrivatePaykitEndpoints = false) }
}
}
}
private fun contactPublicKeys(): List<String> =
pubkyRepo.contacts.value.map { it.publicKey }
private suspend fun rollbackPrivateContactsPreference(
requestedEnabled: Boolean,
previous: SettingsData,
error: Throwable,
) {
val contacts = contactPublicKeys()
if (!requestedEnabled && previous.sharesPrivatePaykitEndpoints) {
restorePrivateContactsPreference(contacts, error)
return
}
runCatching {
settingsStore.update { it.copy(sharesPrivatePaykitEndpoints = previous.sharesPrivatePaykitEndpoints) }
}.onFailure(error::addSuppressed)
if (requestedEnabled && !previous.sharesPrivatePaykitEndpoints) {
privatePaykitRepo.disableSharingAndPruneUnsavedContactState(contacts)
.onFailure(error::addSuppressed)
}
}
private suspend fun restorePrivateContactsPreference(
contacts: List<String>,
error: Throwable,
) {
val preferenceRestored = updatePrivateContactsPreference(isEnabled = true, error = error)
if (!preferenceRestored) return
privatePaykitRepo.prepareSavedContacts(
publicKeys = contacts,
requireImmediatePublication = true,
).onFailure {
error.addSuppressed(it)
updatePrivateContactsPreference(isEnabled = false, error = error)
return
}
privatePaykitRepo.setContactSharingCleanupPending(false)
.onFailure {
error.addSuppressed(it)
updatePrivateContactsPreference(isEnabled = false, error = error)
}
}
private suspend fun updatePrivateContactsPreference(
isEnabled: Boolean,
error: Throwable,
): Boolean = runCatching {
settingsStore.update { it.copy(sharesPrivatePaykitEndpoints = isEnabled) }
}.onFailure(error::addSuppressed).isSuccess
private suspend fun showSyncError(error: Throwable) {
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.common__error),
description = when (error) {
PublicPaykitError.InvalidPayload ->
context.getString(R.string.profile__pay_contacts_error_invalid_payload)
PublicPaykitError.NoSupportedEndpoint ->
context.getString(R.string.profile__pay_contacts_error_no_endpoint)
PublicPaykitError.SessionNotActive -> context.getString(R.string.profile__session_expired)
PublicPaykitError.WalletNotReady -> context.getString(R.string.profile__pay_contacts_error_wallet)
else -> context.getString(R.string.common__error_body)
},
)
}
}
@Immutable
data class PaymentPreferenceUiState(
val lightningEnabled: Boolean = true,
val onchainEnabled: Boolean = true,
val privateContactsEnabled: Boolean = false,
val publicContactsEnabled: Boolean = false,
val hasPubkyProfile: Boolean = false,
val canUsePrivateContacts: Boolean = false,
val isUpdatingPaymentOptions: Boolean = false,
val isUpdatingPrivateContacts: Boolean = false,
val isUpdatingPublicContacts: Boolean = false,
)
private data class PaymentPreferenceStateSource(
val settings: SettingsData,
val isAuthenticated: Boolean,
val canUsePrivateContacts: Boolean,
val pendingPrivateContactsEnabled: Boolean?,
)
private fun PaymentPreferenceUiState.from(source: PaymentPreferenceStateSource) = copy(
lightningEnabled = source.settings.publicPaykitLightningEnabled,
onchainEnabled = source.settings.publicPaykitOnchainEnabled,
privateContactsEnabled = source.pendingPrivateContactsEnabled
?: (source.settings.sharesPrivatePaykitEndpoints && source.canUsePrivateContacts),
publicContactsEnabled = source.settings.sharesPublicPaykitEndpoints,
hasPubkyProfile = source.isAuthenticated,
canUsePrivateContacts = source.canUsePrivateContacts,
)