-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathPayContactsViewModel.kt
More file actions
230 lines (202 loc) · 8.48 KB
/
Copy pathPayContactsViewModel.kt
File metadata and controls
230 lines (202 loc) · 8.48 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
package to.bitkit.ui.screens.profile
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.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.asStateFlow
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 PayContactsViewModel @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(PayContactsUiState())
val uiState: StateFlow<PayContactsUiState> = _uiState.asStateFlow()
private val _effects = MutableSharedFlow<PayContactsEffect>(extraBufferCapacity = 1)
val effects = _effects.asSharedFlow()
init {
viewModelScope.launch {
val settings = settingsStore.data.first()
val hasLocalSecretKey = pubkyRepo.hasSecretKey()
_uiState.update {
it.copy(
isPaymentSharingEnabled = resolvedSharingDefault(settings, hasLocalSecretKey),
)
}
}
}
fun setPaymentSharingEnabled(isEnabled: Boolean) {
_uiState.update { it.copy(isPaymentSharingEnabled = isEnabled) }
}
fun continueToProfile() {
viewModelScope.launch {
val shouldPublish = _uiState.value.isPaymentSharingEnabled
val contacts = pubkyRepo.contacts.value.map { it.publicKey }
_uiState.update { it.copy(isLoading = true) }
val result = if (shouldPublish) {
enableContactPayments(contacts)
} else {
disableContactPayments(contacts)
}
result
.onSuccess {
_uiState.update { it.copy(isLoading = false) }
_effects.emit(PayContactsEffect.Continue)
}
.onFailure {
val settings = settingsStore.data.first()
val persistedValue = resolvedSharingDefault(settings, pubkyRepo.hasSecretKey())
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.common__error),
description = syncErrorMessage(it),
)
_uiState.update {
it.copy(
isLoading = false,
isPaymentSharingEnabled = persistedValue,
)
}
}
}
}
private suspend fun enableContactPayments(contacts: List<String>): Result<Unit> {
publicPaykitRepo.syncPublishedEndpoints(publish = true)
.onFailure { return Result.failure(it) }
val canUsePrivateContactPayments = pubkyRepo.hasSecretKey()
if (canUsePrivateContactPayments) {
privatePaykitRepo.setContactSharingCleanupPending(false)
.onFailure {
publicPaykitRepo.syncPublishedEndpoints(publish = false)
return Result.failure(it)
}
}
runCatching {
settingsStore.update {
it.copy(
hasConfirmedPublicPaykitEndpoints = true,
sharesPublicPaykitEndpoints = true,
sharesPrivatePaykitEndpoints = canUsePrivateContactPayments,
)
}
}.onFailure {
return Result.failure(it)
}
if (canUsePrivateContactPayments) {
privatePaykitRepo.prepareSavedContacts(contacts)
}
return Result.success(Unit)
}
private suspend fun disableContactPayments(contacts: List<String>): Result<Unit> {
val previous = settingsStore.data.first()
runCatching {
settingsStore.update {
it.copy(
hasConfirmedPublicPaykitEndpoints = true,
sharesPublicPaykitEndpoints = false,
sharesPrivatePaykitEndpoints = false,
)
}
}.onFailure {
return Result.failure(it)
}
var publicCleanupError: Throwable? = null
var privateCleanupError: Throwable? = null
publicPaykitRepo.syncPublishedEndpoints(publish = false)
.onFailure { publicCleanupError = it }
privatePaykitRepo.disableSharingAndPruneUnsavedContactState(contacts)
.onFailure { privateCleanupError = it }
publicCleanupError?.let { error ->
runCatching {
settingsStore.update { settings ->
settings.copy(sharesPublicPaykitEndpoints = previous.sharesPublicPaykitEndpoints)
}
}.onFailure { rollbackError ->
error.addSuppressed(rollbackError)
}
}
privateCleanupError?.let { error ->
if (previous.sharesPrivatePaykitEndpoints) {
restorePrivateContactPayments(contacts, error)
} else {
updatePrivateContactsPreference(isEnabled = false, error = error)
}
}
val cleanupError = publicCleanupError ?: privateCleanupError
publicCleanupError?.let { publicError ->
privateCleanupError?.let { privateError -> publicError.addSuppressed(privateError) }
}
cleanupError?.let {
return Result.failure(it)
}
privatePaykitRepo.setContactSharingCleanupPending(false)
.onFailure { return Result.failure(it) }
return Result.success(Unit)
}
private suspend fun restorePrivateContactPayments(
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 fun syncErrorMessage(error: Throwable): String = 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__pay_contacts_error_session)
PublicPaykitError.WalletNotReady -> context.getString(R.string.profile__pay_contacts_error_wallet)
else -> context.getString(R.string.common__error_body)
}
private fun resolvedSharingDefault(settings: SettingsData, hasLocalSecretKey: Boolean): Boolean =
settings.sharesPublicPaykitEndpoints ||
(settings.sharesPrivatePaykitEndpoints && hasLocalSecretKey) ||
!settings.hasConfirmedPublicPaykitEndpoints
}
@Immutable
data class PayContactsUiState(
val isPaymentSharingEnabled: Boolean = true,
val isLoading: Boolean = false,
)
sealed interface PayContactsEffect {
data object Continue : PayContactsEffect
}