diff --git a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt index b5e2159e3d..0676c1c624 100644 --- a/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt +++ b/app/src/main/java/to/bitkit/ext/PaykitExceptionExt.kt @@ -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 } @@ -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) } + } diff --git a/app/src/main/java/to/bitkit/models/Toast.kt b/app/src/main/java/to/bitkit/models/Toast.kt index c4bed3e31d..9243d5c349 100644 --- a/app/src/main/java/to/bitkit/models/Toast.kt +++ b/app/src/main/java/to/bitkit/models/Toast.kt @@ -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 } diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index ba513ed4ce..1efe4815aa 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -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 @@ -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 @@ -308,6 +312,14 @@ class PubkyRepo @Inject constructor( private val _sessionRestorationFailed = MutableStateFlow(false) val sessionRestorationFailed: StateFlow = _sessionRestorationFailed.asStateFlow() + private val _sessionRestorationNeedsUpdate = MutableStateFlow(false) + val sessionRestorationNeedsUpdate: StateFlow = _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 = _restorationNeedsUpdate.asStateFlow() + private val _adoptedSourceLost = MutableStateFlow(false) val adoptedSourceLost: StateFlow = _adoptedSourceLost.asStateFlow() @@ -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( @@ -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 } @@ -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 -> { @@ -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 } @@ -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()) } @@ -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 + updatePromptIdentityRevision = revision + _sessionRestorationNeedsUpdate.update { true } + } + + fun clearSessionRestorationNeedsUpdate() { + _sessionRestorationNeedsUpdate.update { false } + } + // endregion // region Shared pubky @@ -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() @@ -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) -> List) { diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt index 9ed6be1921..a87b632ce9 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/CreateProfileViewModel.kt @@ -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 @@ -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), ) } } @@ -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() } diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt index 5958a0adab..46c536f1a8 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileScreen.kt @@ -151,6 +151,7 @@ private fun Content( onRemoveTag = onRemoveTag, onClickSignOut = onClickSignOut, onClickRetry = onClickRetry, + needsUpdate = uiState.needsUpdate, ) topBar(Modifier.background(TopBarGradient)) CopiedPopup( @@ -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, + ) } } } @@ -205,6 +210,7 @@ private fun ProfileBody( onRemoveTag: (String) -> Unit, onClickSignOut: () -> Unit, onClickRetry: () -> Unit, + needsUpdate: Boolean, ) { Column( horizontalAlignment = Alignment.CenterHorizontally, @@ -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, @@ -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, ) { @@ -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, diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt index 1089d3f21e..8b2d5b3592 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/ProfileViewModel.kt @@ -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 { @@ -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), ), ) @@ -218,6 +219,7 @@ class ProfileViewModel @Inject constructor( isSigningOut = controls.isSigningOut, showAddTagSheet = controls.showAddTagSheet, copiedPublicKey = controls.copiedPublicKey, + needsUpdate = controls.needsUpdate, ) private fun updateTags( @@ -267,6 +269,7 @@ data class ProfileUiState( val isSigningOut: Boolean = false, val showAddTagSheet: Boolean = false, val copiedPublicKey: String? = null, + val needsUpdate: Boolean = false, ) private data class ProfileControls( @@ -274,6 +277,7 @@ private data class ProfileControls( val isSigningOut: Boolean = false, val showAddTagSheet: Boolean = false, val copiedPublicKey: String? = null, + val needsUpdate: Boolean = false, ) sealed interface ProfileEffect { diff --git a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyChoiceViewModel.kt b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyChoiceViewModel.kt index 5cff374ff4..6df42ceb08 100644 --- a/app/src/main/java/to/bitkit/ui/screens/profile/PubkyChoiceViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/screens/profile/PubkyChoiceViewModel.kt @@ -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 @@ -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), ) } } @@ -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), ) } } diff --git a/app/src/main/java/to/bitkit/ui/settings/advanced/AddressTypePreferenceViewModel.kt b/app/src/main/java/to/bitkit/ui/settings/advanced/AddressTypePreferenceViewModel.kt index 69a33290ff..d767199927 100644 --- a/app/src/main/java/to/bitkit/ui/settings/advanced/AddressTypePreferenceViewModel.kt +++ b/app/src/main/java/to/bitkit/ui/settings/advanced/AddressTypePreferenceViewModel.kt @@ -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() @@ -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) diff --git a/app/src/main/java/to/bitkit/ui/shared/toast/ToastEventBus.kt b/app/src/main/java/to/bitkit/ui/shared/toast/ToastEventBus.kt index c67604294b..fce89497c8 100644 --- a/app/src/main/java/to/bitkit/ui/shared/toast/ToastEventBus.kt +++ b/app/src/main/java/to/bitkit/ui/shared/toast/ToastEventBus.kt @@ -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) ) } diff --git a/app/src/main/java/to/bitkit/ui/shared/toast/ToastQueueManager.kt b/app/src/main/java/to/bitkit/ui/shared/toast/ToastQueueManager.kt index eabf11320d..337b07507d 100644 --- a/app/src/main/java/to/bitkit/ui/shared/toast/ToastQueueManager.kt +++ b/app/src/main/java/to/bitkit/ui/shared/toast/ToastQueueManager.kt @@ -37,16 +37,20 @@ class ToastQueueManager(private val scope: CoroutineScope) { private var isPaused = false /** - * Add toast to queue. If queue is full, drops oldest. A shown or queued loading toast returns after the new one. + * Add toast to queue. If queue is full, drops oldest. A shown or queued loading toast returns after the new one, + * and a shown toast that is not interruptible stays until it hides. A queued progress toast is replaced by the new + * one, as it would have been on screen. */ fun enqueue(toast: Toast) { - val interruptedLoading = _currentToast.value?.takeIf { it.isLoading } + val isCurrentInterruptible = _currentToast.value?.interruptible != false + val interruptedLoading = _currentToast.value?.takeIf { it.isLoading && isCurrentInterruptible } _queue.update { current -> val (loading, others) = current.partition { it.isLoading } // Drop oldest when queue full - (others + toast + loading + listOfNotNull(interruptedLoading)).takeLast(MAX_QUEUE_SIZE) + val waiting = others.filterNot { it.replacedByNext } + (waiting + toast + loading + listOfNotNull(interruptedLoading)).takeLast(MAX_QUEUE_SIZE) } - dismissCurrentToast() + if (isCurrentInterruptible) dismissCurrentToast() } /** diff --git a/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt b/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt index cd1b15e547..e01f2bc32d 100644 --- a/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt +++ b/app/src/main/java/to/bitkit/ui/utils/PubkyAuthErrorMessage.kt @@ -4,6 +4,7 @@ import android.content.Context import com.synonym.paykit.PaykitException import to.bitkit.R import to.bitkit.ext.isPaykitSignupCodeRejected +import to.bitkit.ext.isPaykitStateFromNewerVersion import to.bitkit.models.PubkyAuthRequestError import to.bitkit.repositories.WatchOnlyAccountError import to.bitkit.services.PubkyRingAuthTimeoutError @@ -20,6 +21,10 @@ fun Throwable.localizedPubkyAuthMessage(context: Context): String? { return context.getString(R.string.common__error_body) } +/** Shared Paykit state saved by a newer Bitkit is unreadable until an update, so it replaces the raw storage error. */ +fun Throwable.profileErrorDescription(context: Context): String? = + if (isPaykitStateFromNewerVersion()) context.getString(R.string.profile__update_required) else message + private fun Throwable.pubkyAuthMessageResource() = when (this) { is PubkyRingAuthTimeoutError -> R.string.profile__auth_error_timeout is PubkyAuthRequestError.InvalidUrl -> R.string.profile__auth_error_invalid_url diff --git a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt index c4fed67217..7d4832b714 100644 --- a/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt +++ b/app/src/main/java/to/bitkit/viewmodels/AppViewModel.kt @@ -266,6 +266,7 @@ import to.bitkit.services.PaykitSdkOperationLock.Priority import to.bitkit.services.PubkyService import to.bitkit.services.SparkError import to.bitkit.ui.ID_NOTIFICATION_SKIPPED +import to.bitkit.ui.MainActivity import to.bitkit.ui.Routes import to.bitkit.ui.components.AllowanceRoute import to.bitkit.ui.components.Sheet @@ -860,6 +861,11 @@ class AppViewModel @Inject constructor( } } } + viewModelScope.launch { + pubkyRepo.sessionRestorationNeedsUpdate.collect { + if (it && App.currentActivity?.value is MainActivity) showPaykitUpdatePrompt() + } + } viewModelScope.launch { pubkyRepo.adoptedSourceLost.collect { lost -> if (lost) { @@ -9377,16 +9383,7 @@ class AppViewModel @Inject constructor( ) } - fun toast(toast: Toast) { - toast( - type = toast.type, - title = toast.title, - description = toast.description, - autoHide = toast.autoHide, - visibilityTime = toast.visibilityTime, - testTag = toast.testTag, - ) - } + fun toast(toast: Toast) = toastManager.enqueue(toast) fun hideToast() = toastManager.dismissCurrentToast() @@ -10502,10 +10499,24 @@ class AppViewModel @Inject constructor( fun onAppResumed() { viewModelScope.launch { + if (pubkyRepo.sessionRestorationNeedsUpdate.value) showPaykitUpdatePrompt() if (isOnline.value == ConnectivityState.CONNECTED) pubkyRepo.restoreSessionIfNeeded() } } + private fun showPaykitUpdatePrompt() { + pubkyRepo.clearSessionRestorationNeedsUpdate() + toastManager.enqueue( + Toast( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.common__error), + description = context.getString(R.string.profile__update_required), + autoHide = true, + interruptible = false, + ) + ) + } + fun onHomeResumed() { checkTimedSheets() hwWalletRepo.onAppForegrounded() diff --git a/app/src/main/res/values-ar/strings.xml b/app/src/main/res/values-ar/strings.xml index 519cc21883..a0b6470800 100644 --- a/app/src/main/res/values-ar/strings.xml +++ b/app/src/main/res/values-ar/strings.xml @@ -563,6 +563,7 @@ الملف الشخصي حاول مرة أخرى اقتراحات + يحتاج هذا الملف الشخصي إلى إصدار أحدث من Bitkit. حدّث التطبيق لاستخدامه. نسخ احتياطي الآن بعد أن لديك بعض الأموال في محفظتك، حان وقت عمل نسخة احتياطية! لا توجد أموال في محفظتك بعد، لكن يمكنك إنشاء نسخة احتياطية إذا أردت. diff --git a/app/src/main/res/values-b+es+419/strings.xml b/app/src/main/res/values-b+es+419/strings.xml index 2c0359bd0c..a8c1f16322 100644 --- a/app/src/main/res/values-b+es+419/strings.xml +++ b/app/src/main/res/values-b+es+419/strings.xml @@ -583,6 +583,7 @@ No se pudo desvincular el pubky Desvincular pubky Pubky desvinculado + Este perfil necesita una versión más reciente de Bitkit. Actualice la app para usarlo. Su Nombre Realizar copia de seguridad Ahora que tiene fondos en su cartera, ¡és momento de hacer una copia de seguridad de su dinero! diff --git a/app/src/main/res/values-ca/strings.xml b/app/src/main/res/values-ca/strings.xml index 745b66514c..3ddd9ef3a3 100644 --- a/app/src/main/res/values-ca/strings.xml +++ b/app/src/main/res/values-ca/strings.xml @@ -577,6 +577,7 @@ No s\'ha pogut desvincular el pubky Desvincular el pubky Pubky desvinculat + Aquest perfil necessita una versió més recent de Bitkit. Actualitza l\'aplicació per fer-lo servir. El teu Nom Còpia de seguretat Ara que tens alguns fons a la teva cartera, és hora de fer una còpia de seguretat dels teus diners! diff --git a/app/src/main/res/values-cs/strings.xml b/app/src/main/res/values-cs/strings.xml index 069e3d7aea..46094c4347 100644 --- a/app/src/main/res/values-cs/strings.xml +++ b/app/src/main/res/values-cs/strings.xml @@ -582,6 +582,7 @@ Propojení pubky nelze zrušit Zrušit propojení pubky Propojení pubky zrušeno + Tento profil vyžaduje novější verzi Bitkitu. Aktualizujte aplikaci, abyste ho mohli používat. Vaše jméno Zálohování Nyní, když máte v peněžence nějaké prostředky, je čas je zálohovat! diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xml index 0529225082..99df20258c 100644 --- a/app/src/main/res/values-de/strings.xml +++ b/app/src/main/res/values-de/strings.xml @@ -563,6 +563,7 @@ pubky-Verknüpfung kann nicht aufgehoben werden pubky-Verknüpfung aufheben pubky-Verknüpfung aufgehoben + Dieses Profil benötigt eine neuere Version von Bitkit. Aktualisiere die App, um es zu verwenden. Dein Name Bitte aktualisiere Bitkit auf die neueste Version für neue Funktionen und Fehlerbehebungen! Aktualisieren diff --git a/app/src/main/res/values-el/strings.xml b/app/src/main/res/values-el/strings.xml index 4e4484778e..d4d1696d82 100644 --- a/app/src/main/res/values-el/strings.xml +++ b/app/src/main/res/values-el/strings.xml @@ -563,6 +563,7 @@ Προφίλ Προσπαθήστε Ξανά Προτάσεις + Αυτό το προφίλ χρειάζεται νεότερη έκδοση του Bitkit. Ενημέρωσε την εφαρμογή για να το χρησιμοποιήσεις. Αντίγραφο ασφαλείας Τώρα που έχεις κεφάλαια στο πορτοφόλι σου, ήρθε η ώρα να δημιουργήσεις αντίγραφο ασφαλείας των χρημάτων σου! Δεν υπάρχουν ακόμα κεφάλαια στο πορτοφόλι σου, αλλά μπορείς να δημιουργήσεις αντίγραφο ασφαλείας αν το επιθυμείς. diff --git a/app/src/main/res/values-es-rES/strings.xml b/app/src/main/res/values-es-rES/strings.xml index 4cffc2f39f..fb013aa0b1 100644 --- a/app/src/main/res/values-es-rES/strings.xml +++ b/app/src/main/res/values-es-rES/strings.xml @@ -580,6 +580,7 @@ No se pudo desvincular el pubky Desvincular pubky Pubky desvinculado + Este perfil necesita una versión más reciente de Bitkit. Actualice la app para usarlo. Su Nombre Realizar copia de seguridad Ahora que tiene fondos en su cartera, ¡és el momento de hacer una copia de seguridad de su dinero! diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xml index 2f69d5c1d2..c9aba9b795 100644 --- a/app/src/main/res/values-es/strings.xml +++ b/app/src/main/res/values-es/strings.xml @@ -577,6 +577,7 @@ No se pudo desvincular el pubky Desvincular pubky Pubky desvinculado + Este perfil necesita una versión más reciente de Bitkit. Actualice la app para usarlo. Su Nombre Por favor, ¡actualice Bitkit a la última versión para nuevas funciones y corregir errores! Copia de seguridad de la cartera diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xml index 2a8923048c..4ada8c0003 100644 --- a/app/src/main/res/values-fr/strings.xml +++ b/app/src/main/res/values-fr/strings.xml @@ -563,6 +563,7 @@ Impossible de dissocier le pubky Dissocier le pubky Pubky dissocié + Ce profil nécessite une version plus récente de Bitkit. Mettez l\'application à jour pour l\'utiliser. Votre nom Veuillez mettre à jour Bitkit à la dernière version pour bénéficier des nouvelles fonctionnalités et des corrections de bugs ! Mise à jour diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xml index 88a2ba5341..72e79113ba 100644 --- a/app/src/main/res/values-it/strings.xml +++ b/app/src/main/res/values-it/strings.xml @@ -579,6 +579,7 @@ Impossibile Scollegare il Pubky Scollega pubky Pubky scollegato + Questo profilo richiede una versione più recente di Bitkit. Aggiorna l\'app per usarlo. Tuo Nome Backup Ora che ha dei fondi nel tuo wallet, è il momento di fare il backup! diff --git a/app/src/main/res/values-nl/strings.xml b/app/src/main/res/values-nl/strings.xml index ccdab9c374..f0b0c9377a 100644 --- a/app/src/main/res/values-nl/strings.xml +++ b/app/src/main/res/values-nl/strings.xml @@ -577,6 +577,7 @@ Kan pubky niet ontkoppelen pubky ontkoppelen pubky ontkoppeld + Dit profiel vereist een nieuwere versie van Bitkit. Werk de app bij om het te gebruiken. Uw Naam Back-up maken Nu je wat geld in je wallet hebt, is het tijd om een back-up te maken van je geld! diff --git a/app/src/main/res/values-pl/strings.xml b/app/src/main/res/values-pl/strings.xml index 7e7eb0c1d8..8ca5822c46 100644 --- a/app/src/main/res/values-pl/strings.xml +++ b/app/src/main/res/values-pl/strings.xml @@ -564,6 +564,7 @@ Nie można odłączyć pubky Odłącz pubky Pubky odłączony + Ten profil wymaga nowszej wersji Bitkit. Zaktualizuj aplikację, aby go używać. Twoje imię Zaktualizuj proszę aplikację Bitkit do najnowszej wersji aby cieszyć się nowymi funkcjami i poprawkami. Aktualizacja diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xml index e117e7bcea..b57bcf2425 100644 --- a/app/src/main/res/values-pt-rBR/strings.xml +++ b/app/src/main/res/values-pt-rBR/strings.xml @@ -584,6 +584,7 @@ Não Foi Possível Desvincular a Pubky Desvincular pubky Pubky desvinculada + Este perfil precisa de uma versão mais recente do Bitkit. Atualize o app para usá-lo. Seu Nome Cópia de Segurança Agora que o você tem fundos na sua carteira, é hora de fazer o backup do seu dinheiro! diff --git a/app/src/main/res/values-pt/strings.xml b/app/src/main/res/values-pt/strings.xml index 7f33fb21a6..97b011177e 100644 --- a/app/src/main/res/values-pt/strings.xml +++ b/app/src/main/res/values-pt/strings.xml @@ -563,6 +563,7 @@ Recarregar seu telefone Viagem Suas férias ₿ + Este perfil precisa de uma versão mais recente da Bitkit. Atualize a app para o utilizar. Backup da Carteira <accent>Armazene</accent> seu Bitcoin com segurança Agora que o você tem fundos na sua carteira, é hora de fazer o backup do seu dinheiro! diff --git a/app/src/main/res/values-ru/strings.xml b/app/src/main/res/values-ru/strings.xml index 4440419aab..6870c6c5b5 100644 --- a/app/src/main/res/values-ru/strings.xml +++ b/app/src/main/res/values-ru/strings.xml @@ -595,6 +595,7 @@ Не Удалось Отвязать pubky Отвязать pubky pubky отвязан + Для этого профиля нужна более новая версия Bitkit. Обновите приложение, чтобы использовать его. Ваше Имя Создать Теперь, когда у вас есть средства в кошельке, пришло время создать их резервную копию! diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index aaf1b64921..e2417a9070 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -859,6 +859,7 @@ Unable to Unlink Pubky Unlink pubky Pubky unlinked + This profile needs a newer version of Bitkit. Update the app to use it. Your Name Your Pubky Already signed in diff --git a/app/src/test/java/to/bitkit/ext/PaykitExceptionExtTest.kt b/app/src/test/java/to/bitkit/ext/PaykitExceptionExtTest.kt index 205836061a..869e83ce67 100644 --- a/app/src/test/java/to/bitkit/ext/PaykitExceptionExtTest.kt +++ b/app/src/test/java/to/bitkit/ext/PaykitExceptionExtTest.kt @@ -60,4 +60,25 @@ class PaykitExceptionExtTest { assertFalse(transport.isPaykitRecoveryRequired()) assertTrue(transport.isPaykitTemporarilyUnavailable()) } + + @Test + fun `shared state from a newer paykit is detected`() { + val newerVersion = AppError( + PaykitException.Storage("storage_error", "unsupported SDK state blob version 6, expected 4"), + ) + val trailingBytes = AppError(PaykitException.Storage("storage_error", "SDK state blob contains trailing bytes")) + + assertTrue(newerVersion.isPaykitStateFromNewerVersion()) + assertTrue(trailingBytes.isPaykitStateFromNewerVersion()) + } + + @Test + fun `other storage failures are not newer paykit state`() { + val corrupted = AppError( + PaykitException.Storage("storage_error", "SDK state blob version 2 contains trailing bytes"), + ) + + assertFalse(corrupted.isPaykitStateFromNewerVersion()) + assertFalse(AppError("SDK state blob contains trailing bytes").isPaykitStateFromNewerVersion()) + } } diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index cd7454e4dc..43a2124b81 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -3403,6 +3403,43 @@ class PubkyRepoTest : BaseUnitTest() { verify(pubkyService, never()).importSession(any()) } + @Test + fun `initialize should flag an update when the saved session hits newer paykit state`() = test { + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("saved_session") + whenever(keychain.loadString(Keychain.Key.PUBKY_SECRET_KEY.name)).thenReturn("secret_key") + whenever(pubkyService.importSession("saved_session")).thenAnswer { + throw AppError(PaykitException.Storage("storage_error", "unsupported SDK state blob version 6, expected 4")) + } + val repo = createSut() + + repo.awaitInitialization() + + assertTrue(repo.sessionRestorationNeedsUpdate.value) + assertFalse(repo.sessionRestorationFailed.value) + assertFalse(repo.isAuthenticated.value) + verify(pubkyService, never()).signIn(any()) + verifyBlocking(keychain, never()) { delete(Keychain.Key.PAYKIT_SESSION.name) } + } + + @Test + fun `later restores of the same identity keep the update reason without repeating the prompt`() = test { + whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn("saved_session") + whenever(pubkyService.importSession("saved_session")).thenAnswer { + throw AppError(PaykitException.Storage("storage_error", "unsupported SDK state blob version 6, expected 4")) + } + val repo = createSut() + repo.awaitInitialization() + assertTrue(repo.sessionRestorationNeedsUpdate.value) + repo.clearSessionRestorationNeedsUpdate() + + repo.restoreSessionIfNeeded() + + verify(pubkyService, times(2)).importSession("saved_session") + assertFalse(repo.sessionRestorationNeedsUpdate.value) + assertTrue(repo.restorationNeedsUpdate.value) + assertFalse(repo.sessionRestorationFailed.value) + } + @Test fun `initialize should not flag session restoration failure on identity error without saved session`() = test { whenever(keychain.loadString(Keychain.Key.PAYKIT_SESSION.name)).thenReturn(null) @@ -3681,6 +3718,22 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(sut.restoreSessionIfNeeded()) } + @Test + fun `deferred restoration asks for an update when it finds newer paykit state`() = test { + val restore = stubSavedSessionRestore() + restore.answer = { throw PaykitException.SharedStateBusy("shared_state_busy", "Locked") } + sut.initialize() + restore.answer = { + throw PaykitException.Storage("storage_error", "unsupported SDK state blob version 6, expected 4") + } + + sut.retryDeferredSessionRestoration() + + assertTrue(sut.sessionRestorationNeedsUpdate.value) + assertFalse(sut.sessionRestorationFailed.value) + assertNull(sut.publicKey.value) + } + @Test fun `deferred restoration shares in-flight work with foreground callers`() = test { val restore = stubSavedSessionRestore() diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt index 26523e67d7..bed0ba19f2 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/ProfileViewModelTest.kt @@ -88,6 +88,20 @@ class ProfileViewModelTest : BaseUnitTest() { } } + @Test + fun `profile shows the update reason while restoration needs an update`() = test { + val needsUpdate = MutableStateFlow(true) + val sut = createSut(publicKey = null, restorationNeedsUpdate = needsUpdate) + sut.uiState.test { + advanceUntilIdle() + assertTrue(expectMostRecentItem().needsUpdate) + + needsUpdate.value = false + advanceUntilIdle() + assertFalse(expectMostRecentItem().needsUpdate) + } + } + @Test fun `init loads the profile unless a profile load is in flight`() = test { val loaded = createProfile() @@ -519,6 +533,7 @@ class ProfileViewModelTest : BaseUnitTest() { isLoadingFlow: MutableStateFlow = MutableStateFlow(isLoading), isRestoringFlow: MutableStateFlow = MutableStateFlow(false), cachedProfile: PubkyCachedProfile? = null, + restorationNeedsUpdate: MutableStateFlow = MutableStateFlow(false), onLoadProfile: () -> Unit = {}, onRestore: suspend () -> Boolean = { false }, ): ProfileViewModel { @@ -531,6 +546,7 @@ class ProfileViewModelTest : BaseUnitTest() { whenever(pubkyRepo.isLoadingProfile).thenReturn(isLoadingFlow) whenever(pubkyRepo.isRestoringSession).thenReturn(isRestoringFlow) whenever(pubkyRepo.cachedProfile).thenReturn(MutableStateFlow(cachedProfile)) + whenever(pubkyRepo.restorationNeedsUpdate).thenReturn(restorationNeedsUpdate) whenever { pubkyRepo.restoreSessionIfNeeded() }.doSuspendableAnswer { onRestore() } whenever { pubkyRepo.loadProfile() }.thenAnswer { onLoadProfile() } whenever { pubkyRepo.signOut() }.thenReturn(Result.success(Unit)) diff --git a/app/src/test/java/to/bitkit/ui/shared/toast/ToastQueueManagerTest.kt b/app/src/test/java/to/bitkit/ui/shared/toast/ToastQueueManagerTest.kt index e3962d86a0..d0946eb8ca 100644 --- a/app/src/test/java/to/bitkit/ui/shared/toast/ToastQueueManagerTest.kt +++ b/app/src/test/java/to/bitkit/ui/shared/toast/ToastQueueManagerTest.kt @@ -36,6 +36,86 @@ class ToastQueueManagerTest : BaseUnitTest() { assertNull(sut.currentToast.value) } + @Test + fun `a toast waits behind a shown toast that is not interruptible`() = test { + val sut = ToastQueueManager(backgroundScope) + val updateToast = Toast(type = Toast.ToastType.ERROR, title = "Update", autoHide = true, interruptible = false) + val infoToast = Toast(type = Toast.ToastType.SUCCESS, title = "Back online", autoHide = true) + sut.enqueue(updateToast) + sut.enqueue(infoToast) + assertEquals(updateToast, sut.currentToast.value) + + advanceTimeBy(Toast.VISIBILITY_TIME_DEFAULT + 1) + + assertEquals(infoToast, sut.currentToast.value) + } + + @Test + fun `a result replaces its queued progress toast behind a toast that is not interruptible`() = test { + val sut = ToastQueueManager(backgroundScope) + val updateToast = Toast(type = Toast.ToastType.ERROR, title = "Update", autoHide = true, interruptible = false) + val progressToast = Toast( + type = Toast.ToastType.INFO, + title = "Applying changes", + autoHide = false, + replacedByNext = true, + ) + val resultToast = Toast(type = Toast.ToastType.SUCCESS, title = "Settings updated", autoHide = true) + sut.enqueue(updateToast) + sut.enqueue(progressToast) + sut.enqueue(resultToast) + + advanceTimeBy(Toast.VISIBILITY_TIME_DEFAULT + 1) + + assertEquals(resultToast, sut.currentToast.value) + advanceTimeBy(Toast.VISIBILITY_TIME_DEFAULT + 1) + assertNull(sut.currentToast.value) + } + + @Test + fun `a result replaces its queued progress toast after the warning hides`() = test { + val sut = ToastQueueManager(backgroundScope) + val updateToast = Toast(type = Toast.ToastType.ERROR, title = "Update", autoHide = true, interruptible = false) + val onlineToast = Toast(type = Toast.ToastType.SUCCESS, title = "Back online", autoHide = true) + val progressToast = Toast( + type = Toast.ToastType.INFO, + title = "Applying changes", + autoHide = false, + replacedByNext = true, + ) + val resultToast = Toast(type = Toast.ToastType.SUCCESS, title = "Settings updated", autoHide = true) + sut.enqueue(updateToast) + sut.enqueue(onlineToast) + sut.enqueue(progressToast) + advanceTimeBy(Toast.VISIBILITY_TIME_DEFAULT + 1) + assertEquals(onlineToast, sut.currentToast.value) + + sut.enqueue(resultToast) + + assertEquals(resultToast, sut.currentToast.value) + advanceTimeBy(Toast.VISIBILITY_TIME_DEFAULT + 1) + assertNull(sut.currentToast.value) + } + + @Test + fun `a toast that stays until dismissed keeps its place behind a toast that is not interruptible`() = test { + val sut = ToastQueueManager(backgroundScope) + val updateToast = Toast(type = Toast.ToastType.ERROR, title = "Update", autoHide = true, interruptible = false) + val returnedToast = Toast(type = Toast.ToastType.INFO, title = "Payment returned", autoHide = false) + val onlineToast = Toast(type = Toast.ToastType.SUCCESS, title = "Back online", autoHide = true) + sut.enqueue(updateToast) + sut.enqueue(returnedToast) + sut.enqueue(onlineToast) + + advanceTimeBy(Toast.VISIBILITY_TIME_DEFAULT + 1) + + assertEquals(returnedToast, sut.currentToast.value) + advanceTimeBy(Toast.VISIBILITY_TIME_DEFAULT + 1) + assertEquals(returnedToast, sut.currentToast.value) + sut.dismissCurrentToast() + assertEquals(onlineToast, sut.currentToast.value) + } + @Test fun `loading toast returns after a toast that interrupts it`() = test { val sut = ToastQueueManager(backgroundScope) diff --git a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt index 4a2c1961e9..8ecfc6cdf2 100644 --- a/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt +++ b/app/src/test/java/to/bitkit/viewmodels/AppViewModelSendFlowTest.kt @@ -828,6 +828,7 @@ class AppViewModelSendFlowTest : BaseUnitTest() { whenever { migrationService.isMigrationChecked() }.thenReturn(true) whenever { widgetsRepo.refreshEnabledWidgets() }.thenReturn(Unit) whenever(pubkyRepo.sessionRestorationFailed).thenReturn(MutableStateFlow(false)) + whenever(pubkyRepo.sessionRestorationNeedsUpdate).thenReturn(MutableStateFlow(false)) whenever(pubkyRepo.adoptedSourceLost).thenReturn(MutableStateFlow(false)) whenever(pubkyRepo.contactImportFailure).thenReturn(pubkyContactImportFailure) whenever(pubkyRepo.publicKey).thenReturn(pubkyPublicKey) @@ -1117,6 +1118,36 @@ class AppViewModelSendFlowTest : BaseUnitTest() { verify(pubkyRepo).restoreSessionIfNeeded() } + @Test + fun `app resume shows a pending paykit update prompt`() = test { + val needsUpdate = MutableStateFlow(true) + whenever(pubkyRepo.sessionRestorationNeedsUpdate).thenReturn(needsUpdate) + whenever(pubkyRepo.clearSessionRestorationNeedsUpdate()).thenAnswer { needsUpdate.value = false } + whenever(context.getString(R.string.profile__update_required)).thenReturn("Update Bitkit") + clearInvocations(toastManager) + + sut.onAppResumed() + runCurrent() + + verify(toastManager).enqueue(check { assertEquals("Update Bitkit", it.description) }) + assertFalse(needsUpdate.value) + } + + @Test + fun `a sent toast reaches the queue with its progress flag`() = test { + val progressToast = Toast( + type = Toast.ToastType.INFO, + title = "Applying changes", + autoHide = false, + replacedByNext = true, + ) + clearInvocations(toastManager) + + sut.toast(progressToast) + + verify(toastManager).enqueue(progressToast) + } + @Test fun `foreground refreshes contacts once and repeats only after resume or reconnect`() = test { enablePaykitUi() diff --git a/changelog.d/next/2022.fixed.md b/changelog.d/next/2022.fixed.md new file mode 100644 index 0000000000..f55b778af5 --- /dev/null +++ b/changelog.d/next/2022.fixed.md @@ -0,0 +1 @@ +Bitkit now asks you to update the app when a profile was saved by a newer version, instead of showing a raw error.