Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,15 @@ private const val MESSAGE_TOO_LARGE_CODE = "message_too_large"
/** Identity error code for a signup code the homeserver refused during sign-up. */
private const val SIGNUP_CODE_REJECTED_CODE = "signup_code_rejected"

/** Storage error code Paykit uses for local and shared state failures. */
private const val STORAGE_ERROR_CODE = "storage_error"

/** Storage error contexts Paykit raises when the identity's shared state was saved by a newer Paykit. */
private val NEWER_STATE_CONTEXTS = listOf(
"SDK state blob contains trailing bytes",
"unsupported SDK state blob version",
)

/** Paykit exception messages are raw SDK details (`code=..., context=...`), so they must not reach a toast. */
fun Throwable.isPaykitError(): Boolean =
generateSequence(this) { it.cause }.any { it is PaykitException }
Expand All @@ -29,3 +38,9 @@ fun Throwable.isPaykitMessageTooLarge(): Boolean =

fun Throwable.isPaykitSignupCodeRejected(): Boolean =
generateSequence(this) { it.cause }.any { it is PaykitException.Identity && it.code == SIGNUP_CODE_REJECTED_CODE }

fun Throwable.isPaykitStateFromNewerVersion(): Boolean =
generateSequence(this) { it.cause }.any { error ->
error is PaykitException.Storage && error.code == STORAGE_ERROR_CODE &&
NEWER_STATE_CONTEXTS.any { error.context.contains(it) }
}
4 changes: 4 additions & 0 deletions app/src/main/java/to/bitkit/models/Toast.kt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,10 @@ data class Toast(
val visibilityTime: Long = VISIBILITY_TIME_DEFAULT,
val testTag: String? = null,
val isLoading: Boolean = false,
/** False for a one-time warning that later toasts wait behind instead of replacing. */
val interruptible: Boolean = true,
/** True for a progress toast that the next toast replaces, even while it waits in the queue. */
val replacedByNext: Boolean = false,
) {
enum class ToastType { SUCCESS, INFO, LIGHTNING, WARNING, ERROR }

Expand Down
66 changes: 51 additions & 15 deletions app/src/main/java/to/bitkit/repositories/PubkyRepo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ import to.bitkit.data.sharedpubky.SharedPubkyContract
import to.bitkit.di.IoDispatcher
import to.bitkit.env.Env
import to.bitkit.ext.isPaykitIdentityError
import to.bitkit.ext.isPaykitStateFromNewerVersion
import to.bitkit.ext.isPaykitTemporarilyUnavailable
import to.bitkit.ext.nowMs
import to.bitkit.ext.runSuspendCatching
Expand Down Expand Up @@ -272,6 +273,9 @@ class PubkyRepo @Inject constructor(
private var restoreBase: RestoreBase? = null
private val signInGeneration = AtomicLong(0L)
private val storedIdentityRevision = AtomicLong(0L)

@Volatile
private var updatePromptIdentityRevision: Long? = null
private val readOnlyProfileGeneration = AtomicLong(0L)
private val readOnlyProfileLock = Any()
private var isServiceInitialized = false
Expand Down Expand Up @@ -308,6 +312,14 @@ class PubkyRepo @Inject constructor(
private val _sessionRestorationFailed = MutableStateFlow(false)
val sessionRestorationFailed: StateFlow<Boolean> = _sessionRestorationFailed.asStateFlow()

private val _sessionRestorationNeedsUpdate = MutableStateFlow(false)
val sessionRestorationNeedsUpdate: StateFlow<Boolean> = _sessionRestorationNeedsUpdate.asStateFlow()

private val _restorationNeedsUpdate = MutableStateFlow(false)

/** Stays set after the one-time prompt, so Profile can show why retrying does not help. */
val restorationNeedsUpdate: StateFlow<Boolean> = _restorationNeedsUpdate.asStateFlow()

private val _adoptedSourceLost = MutableStateFlow(false)
val adoptedSourceLost: StateFlow<Boolean> = _adoptedSourceLost.asStateFlow()

Expand Down Expand Up @@ -362,6 +374,7 @@ class PubkyRepo @Inject constructor(
data class Restored(val publicKey: String) : InitResult
data object RestorationFailed : InitResult
data object RestorationDeferred : InitResult
data object RestorationNeedsUpdate : InitResult
}

private data class SavedContact(
Expand Down Expand Up @@ -540,6 +553,7 @@ class PubkyRepo @Inject constructor(
if (notifyFailure && it.isPaykitIdentityError() && hasSavedSession()) {
_sessionRestorationFailed.update { true }
}
if (it.isPaykitStateFromNewerVersion()) askForUpdateOnce()
}.getOrElse { return false }

if (notifyFailure) _sessionRestorationFailed.update { false }
Expand All @@ -554,13 +568,7 @@ class PubkyRepo @Inject constructor(
)
}.onFailure {
Logger.error("Failed to initialize paykit", it, context = TAG)
}.getOrElse {
if (it.isPaykitTemporarilyUnavailable()) {
InitResult.RestorationDeferred
} else {
InitResult.RestorationFailed
}
}
}.getOrElse { it.toFailedInitResult() }

when (result) {
is InitResult.NoSession -> {
Expand All @@ -569,16 +577,20 @@ class PubkyRepo @Inject constructor(
}
is InitResult.Restored -> {
_sessionRestorationFailed.update { false }
_sessionRestorationNeedsUpdate.update { false }
_restorationNeedsUpdate.update { false }
updatePromptIdentityRevision = null
continueSignIn(result.publicKey)
Logger.info("Restored paykit session for '${redacted(result.publicKey)}'", context = TAG)
}
InitResult.RestorationFailed, InitResult.RestorationDeferred -> {
InitResult.RestorationFailed, InitResult.RestorationDeferred, InitResult.RestorationNeedsUpdate -> {
clearAuthenticatedState(
clearCachedProfile = false,
clearRestorationFailure = notifyFailure,
preserveStoredIdentity = true,
)
if (notifyFailure) _sessionRestorationFailed.update { result == InitResult.RestorationFailed }
if (result == InitResult.RestorationNeedsUpdate) askForUpdateOnce()
}
}
deferredRestoreGeneration = signInGeneration.get().takeIf { result == InitResult.RestorationDeferred }
Expand Down Expand Up @@ -626,6 +638,10 @@ class PubkyRepo @Inject constructor(
Logger.warn("Deferred session restoration, keeping saved session", it, context = TAG)
return@getOrElse InitResult.RestorationDeferred
}
if (it.isPaykitStateFromNewerVersion()) {
Logger.warn("Kept saved session, paykit state needs an app update", it, context = TAG)
return@getOrElse InitResult.RestorationNeedsUpdate
}
Logger.warn("Failed to restore paykit session, attempting re-sign-in", it, context = TAG)
resolveSignedInSession(savedSessionSecret, storedSecretKeyHex ?: adoptedSecretKeyHex())
}
Expand Down Expand Up @@ -654,19 +670,33 @@ class PubkyRepo @Inject constructor(
InitResult.Restored(publicKey)
}.getOrElse {
Logger.error("Failed re-sign-in recovery", it, context = TAG)
if (it.isPaykitTemporarilyUnavailable()) {
InitResult.RestorationDeferred
} else {
InitResult.RestorationFailed
}
it.toFailedInitResult()
}
}
}

private fun Throwable.toFailedInitResult(): InitResult = when {
isPaykitTemporarilyUnavailable() -> InitResult.RestorationDeferred
isPaykitStateFromNewerVersion() -> InitResult.RestorationNeedsUpdate
else -> InitResult.RestorationFailed
}

fun clearSessionRestorationFailed() {
_sessionRestorationFailed.update { false }
}

private fun askForUpdateOnce() {
_restorationNeedsUpdate.update { true }
val revision = storedIdentityRevision.get()
if (updatePromptIdentityRevision == revision) return
Comment thread
ovitrif marked this conversation as resolved.
Resolved
updatePromptIdentityRevision = revision
_sessionRestorationNeedsUpdate.update { true }
}

fun clearSessionRestorationNeedsUpdate() {
_sessionRestorationNeedsUpdate.update { false }
}

// endregion

// region Shared pubky
Expand Down Expand Up @@ -2725,7 +2755,10 @@ class PubkyRepo @Inject constructor(
) = withContext(ioDispatcher) {
// First, so work of the ending sign-in stops before the store reset below, and cannot write after it.
signInGeneration.incrementAndGet()
if (!preserveStoredIdentity) storedIdentityRevision.incrementAndGet()
if (!preserveStoredIdentity) {
storedIdentityRevision.incrementAndGet()
_restorationNeedsUpdate.update { false }
}
if (clearCachedProfile) {
invalidateReadOnlyProfile()
evictPubkyImages()
Expand All @@ -2743,7 +2776,10 @@ class PubkyRepo @Inject constructor(
_contactsLoadVersion.update { 0L }
_contactsLoadCompletionVersion.update { 0L }
clearPendingImport()
if (clearRestorationFailure) _sessionRestorationFailed.update { false }
if (clearRestorationFailure) {
_sessionRestorationFailed.update { false }
_sessionRestorationNeedsUpdate.update { false }
}
}

private fun updateContacts(transform: (List<PubkyProfile>) -> List<PubkyProfile>) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ import to.bitkit.repositories.PubkyProfileTagsNotSavedError
import to.bitkit.repositories.PubkyRepo
import to.bitkit.ui.components.ProfileEditLink
import to.bitkit.ui.shared.toast.ToastEventBus
import to.bitkit.ui.utils.profileErrorDescription
import to.bitkit.utils.Logger
import javax.inject.Inject

Expand Down Expand Up @@ -107,7 +108,7 @@ class CreateProfileViewModel @Inject constructor(
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.common__error),
description = error.message,
description = error.profileErrorDescription(context),
)
}
}
Expand Down Expand Up @@ -216,7 +217,11 @@ class CreateProfileViewModel @Inject constructor(
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.profile__create_error),
description = if (changed) context.getString(R.string.profile__edit_changed_error) else it.message,
description = if (changed) {
context.getString(R.string.profile__edit_changed_error)
} else {
it.profileErrorDescription(context)
},
)
if (changed) deriveAndCheckRemote()
}
Expand Down
22 changes: 21 additions & 1 deletion app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,7 @@ private fun Content(
onRemoveTag = onRemoveTag,
onClickSignOut = onClickSignOut,
onClickRetry = onClickRetry,
needsUpdate = uiState.needsUpdate,
)
topBar(Modifier.background(TopBarGradient))
CopiedPopup(
Expand All @@ -170,7 +171,11 @@ private fun Content(
if (uiState.isLoading) {
LoadingState()
} else {
EmptyState(onClickRetry = onClickRetry, onClickSignOut = onClickSignOut)
EmptyState(
needsUpdate = uiState.needsUpdate,
onClickRetry = onClickRetry,
onClickSignOut = onClickSignOut,
)
}
}
}
Expand Down Expand Up @@ -205,6 +210,7 @@ private fun ProfileBody(
onRemoveTag: (String) -> Unit,
onClickSignOut: () -> Unit,
onClickRetry: () -> Unit,
needsUpdate: Boolean,
) {
Column(
horizontalAlignment = Alignment.CenterHorizontally,
Expand Down Expand Up @@ -332,6 +338,7 @@ private fun ProfileBody(

VerticalSpacer(16.dp)
if (!canEdit) {
if (needsUpdate) UpdateRequiredHint()
SecondaryButton(
text = stringResource(R.string.profile__retry_load),
onClick = onClickRetry,
Expand Down Expand Up @@ -428,8 +435,20 @@ private fun LoadingState() {
}
}

@Composable
private fun UpdateRequiredHint() {
BodyM(
text = stringResource(R.string.profile__update_required),
color = Colors.White64,
textAlign = TextAlign.Center,
modifier = Modifier.testTag("ProfileUpdateRequired")
)
VerticalSpacer(16.dp)
}

@Composable
private fun EmptyState(
needsUpdate: Boolean,
onClickRetry: () -> Unit,
onClickSignOut: () -> Unit,
) {
Expand All @@ -442,6 +461,7 @@ private fun EmptyState(
) {
BodyM(text = stringResource(R.string.profile__empty_state), color = Colors.White64)
VerticalSpacer(16.dp)
if (needsUpdate) UpdateRequiredHint()
SecondaryButton(
text = stringResource(R.string.profile__retry_load),
onClick = onClickRetry,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,9 @@ class ProfileViewModel @Inject constructor(
_isSigningOut,
_showAddTagSheet,
_copiedPublicKey,
) { showSignOutDialog, isSigningOut, showAddTagSheet, copiedPublicKey ->
ProfileControls(showSignOutDialog, isSigningOut, showAddTagSheet, copiedPublicKey)
pubkyRepo.restorationNeedsUpdate,
) { showSignOutDialog, isSigningOut, showAddTagSheet, copiedPublicKey, needsUpdate ->
ProfileControls(showSignOutDialog, isSigningOut, showAddTagSheet, copiedPublicKey, needsUpdate)
}

init {
Expand All @@ -92,7 +93,7 @@ class ProfileViewModel @Inject constructor(
publicKey = pubkyRepo.publicKey.value,
isLoading = pubkyRepo.isLoadingProfile.value || pubkyRepo.isRestoringSession.value || _isRefreshing.value,
cachedProfile = pubkyRepo.cachedProfile.value,
controls = ProfileControls(),
controls = ProfileControls(needsUpdate = pubkyRepo.restorationNeedsUpdate.value),
),
)

Expand Down Expand Up @@ -218,6 +219,7 @@ class ProfileViewModel @Inject constructor(
isSigningOut = controls.isSigningOut,
showAddTagSheet = controls.showAddTagSheet,
copiedPublicKey = controls.copiedPublicKey,
needsUpdate = controls.needsUpdate,
)

private fun updateTags(
Expand Down Expand Up @@ -267,13 +269,15 @@ data class ProfileUiState(
val isSigningOut: Boolean = false,
val showAddTagSheet: Boolean = false,
val copiedPublicKey: String? = null,
val needsUpdate: Boolean = false,
)

private data class ProfileControls(
val showSignOutDialog: Boolean = false,
val isSigningOut: Boolean = false,
val showAddTagSheet: Boolean = false,
val copiedPublicKey: String? = null,
val needsUpdate: Boolean = false,
)

sealed interface ProfileEffect {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import to.bitkit.models.Toast
import to.bitkit.repositories.ContactPaymentSettingsRepo
import to.bitkit.repositories.PubkyRepo
import to.bitkit.ui.shared.toast.ToastEventBus
import to.bitkit.ui.utils.profileErrorDescription
import to.bitkit.utils.Logger
import javax.inject.Inject

Expand Down Expand Up @@ -65,7 +66,7 @@ class PubkyChoiceViewModel @Inject constructor(
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.common__error),
description = it.message,
description = it.profileErrorDescription(context),
)
}
}
Expand All @@ -86,7 +87,7 @@ class PubkyChoiceViewModel @Inject constructor(
ToastEventBus.send(
type = Toast.ToastType.ERROR,
title = context.getString(R.string.profile__auth_error_title),
description = it.message,
description = it.profileErrorDescription(context),
)
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ class AddressTypePreferenceViewModel @Inject constructor(
title = context.getString(R.string.settings__addr_type__applying),
autoHide = false,
testTag = "AddressTypeApplyingToast",
replacedByNext = true,
)

val currentMonitored = _uiState.value.monitoredTypes.toMutableSet()
Expand Down Expand Up @@ -122,6 +123,7 @@ class AddressTypePreferenceViewModel @Inject constructor(
type = Toast.ToastType.INFO,
title = context.getString(R.string.settings__addr_type__applying),
autoHide = false,
replacedByNext = true,
)

val repoResult = lightningRepo.setMonitoring(addressType, enabled)
Expand Down
3 changes: 2 additions & 1 deletion app/src/main/java/to/bitkit/ui/shared/toast/ToastEventBus.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,10 @@ object ToastEventBus {
autoHide: Boolean = true,
visibilityTime: Long = Toast.VISIBILITY_TIME_DEFAULT,
testTag: String? = null,
replacedByNext: Boolean = false,
) {
_events.emit(
Toast(type, title, description, autoHide, visibilityTime, testTag)
Toast(type, title, description, autoHide, visibilityTime, testTag, replacedByNext = replacedByNext)
Comment thread
ovitrif marked this conversation as resolved.
Resolved
)
}

Expand Down
Loading