diff --git a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt index fc4c021fb0..63981e5d41 100644 --- a/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt +++ b/app/src/main/java/to/bitkit/repositories/PubkyRepo.kt @@ -132,13 +132,26 @@ class PubkyProfileTagsNotSavedError(val base: ProfileEditBase, cause: Throwable? private class PubkyProfileNotFoundError : AppError("Profile not found") -private class SavedProfile(val profile: PubkyProfile, val revision: String, val tagError: Throwable?) +private class LoadedProfile(val profile: PubkyProfile, val revision: String?, val tagsUnread: Boolean) + +private class SavedProfile( + val profile: PubkyProfile, + val revision: String, + val tagsUnread: Boolean?, + val tagsReadEpoch: Long?, + val tagError: Throwable?, +) private class StoredCopy(val tags: List?, val image: String?) private class FittedProfile(val name: String, val bio: String, val links: List) -private class RestoreBase(val publicKey: String, val profile: PubkyProfile, val revision: String?) +private class RestoreBase( + val publicKey: String, + val profile: PubkyProfile, + val revision: String?, + val tagsUnread: Boolean = false, +) /** Whether a Pubky identity is ready to use once restores already under way have finished. */ enum class PubkyIdentityReadiness { @@ -226,6 +239,7 @@ class PubkyRepo @Inject constructor( private val adoptedSourceCheckMutex = Mutex() private val adoptionMutex = Mutex() private val profileWriteGeneration = AtomicLong(0L) + private val profileStateLock = Any() // Held by each own-profile write and by profile deletion, so a deletion waits for the writes under way. The // deletion moves the generation on, so a load or save that started before or during it writes nothing after. @@ -245,7 +259,7 @@ class PubkyRepo @Inject constructor( @Volatile private var ownProfileRevision: String? = null - /** Whether the last profile load could not read the Paykit copy, so the shown tags are not the stored ones. */ + /** Whether the shown tags may omit tags from the Paykit copy. */ @Volatile private var tagsUnavailable = false @@ -878,26 +892,34 @@ class PubkyRepo @Inject constructor( withContext(ioDispatcher) { loadOwnProfile(signIn.publicKey) ?: throw PubkyProfileNotFoundError() } - }.onSuccess { (loadedProfile, revision) -> - var isCurrent = false - _profile.update { - isCurrent = isCurrentLoad() - if (isCurrent) loadedProfile else it + }.onSuccess { loaded -> + val installed = synchronized(profileStateLock) { + if (!isCurrentLoad()) return@synchronized false + ownProfileRevision = loaded.revision + tagsReadEpoch.incrementAndGet() + tagsUnavailable = loaded.tagsUnread + _profile.value = loaded.profile + true } - if (!isCurrent) { + if (!installed) { Logger.debug("Skipped stale profile load for '${redacted(signIn.publicKey)}'", context = TAG) return@onSuccess } - ownProfileRevision = revision invalidateReadOnlyProfile() - cacheMetadata(loadedProfile, isCurrentLoad) + cacheMetadata(loaded.profile, isCurrentLoad) }.onFailure { Logger.error("Failed to load profile", it, context = TAG) // A profile deleted on pubky.app is set up again rather than left unreachable. - if (it is PubkyProfileNotFoundError && isCurrentLoad()) { - _profile.update { null } - ownProfileRevision = null - settingsStore.setPubkyProfileSetupPending(true) + if (it is PubkyProfileNotFoundError) { + val cleared = synchronized(profileStateLock) { + if (!isCurrentLoad()) return@synchronized false + ownProfileRevision = null + tagsUnavailable = false + tagsReadEpoch.incrementAndGet() + _profile.value = null + true + } + if (cleared) settingsStore.setPubkyProfileSetupPending(true) } } completedProfileSignInGeneration = signIn.generation @@ -951,10 +973,8 @@ class PubkyRepo @Inject constructor( restoreBase = RestoreBase(prefixedKey, it, revision = null) } } - tagsReadEpoch.incrementAndGet() - tagsUnavailable = paykitRead.isFailure PubkyProfile.fromPubkyProfile(prefixedKey, snapshot.profile).copy(tags = paykitData?.tags.orEmpty()).also { - restoreBase = RestoreBase(prefixedKey, it, snapshot.revision) + restoreBase = RestoreBase(prefixedKey, it, snapshot.revision, tagsUnread = paykitRead.isFailure) } } } @@ -996,7 +1016,7 @@ class PubkyRepo @Inject constructor( withContext(ioDispatcher) { val publicKey = requireNotNull(_publicKey.value) { "No active Pubky session" } val saved = publishIdentityProfile(publicKey, name, bio, links, tags, avatarBytes) - finishIdentityCreation(publicKey, saved) + finishIdentityCreation(publicKey, saved) to saved.tagError } } } @@ -1011,7 +1031,7 @@ class PubkyRepo @Inject constructor( val saved = publishIdentityProfile(publicKeyZ32, name, bio, links, tags, avatarBytes) shouldRevokeSessionOnFailure = false - finishIdentityCreation(publicKeyZ32, saved) + finishIdentityCreation(publicKeyZ32, saved) to saved.tagError } } if (creationResult.isFailure) revokeIncompleteIdentitySessionIfNeeded(shouldRevokeSessionOnFailure) @@ -1022,14 +1042,14 @@ class PubkyRepo @Inject constructor( } } - val publicKey = result.getOrElse { return Result.failure(it) } + val (publicKey, tagError) = result.getOrElse { return Result.failure(it) } val signIn = currentSignIn()?.takeIf { it.publicKey == publicKey } if (signIn != null) { scope.launch { if (isCurrent(signIn)) loadContacts() } } - return Result.success(Unit) + return tagError?.let { Result.failure(it) } ?: Result.success(Unit) } private suspend fun createLocalIdentitySession(markSessionCreated: () -> Unit): String { @@ -1067,21 +1087,23 @@ class PubkyRepo @Inject constructor( val imageUrl = avatarBytes?.let { uploadAvatar(it, publicKey).getOrNull() } ?: restore?.profile?.imageUrl val base = restore?.profile?.takeIf { restore.revision != null } val saved = runSuspendCatching { - writeProfile(publicKey, name, bio, links, tags, imageUrl, base, expectedRevision = restore?.revision) + writeProfile( + publicKey, name, bio, links, tags, imageUrl, base, + expectedRevision = restore?.revision, + tagsUnread = restore?.tagsUnread == true, + ) }.getOrElse { if (!it.isConcurrentUpdate()) throw it throw PubkyProfileChangedError(it) } restoreBase = null - saved.tagError?.let { Logger.warn("Created profile without its tag change", it, context = TAG) } return saved } private suspend fun finishIdentityCreation(publicKey: String, saved: SavedProfile): String { val createdProfile = saved.profile startSignIn(publicKey) - ownProfileRevision = saved.revision - setProfile(createdProfile) + installSavedProfile(saved) cacheMetadata(createdProfile) settingsStore.setPubkyProfileSetupPending(false) notifyBackupStateChanged() @@ -1129,7 +1151,9 @@ class PubkyRepo @Inject constructor( } /** The profile and pubky.app revision an edit starts from; its save is checked against that revision. */ - fun profileEditBase() = ProfileEditBase(_profile.value, ownProfileRevision, tagsUnavailable) + fun profileEditBase() = synchronized(profileStateLock) { + ProfileEditBase(_profile.value, ownProfileRevision, tagsUnavailable) + } suspend fun saveProfile( name: String, @@ -1172,9 +1196,7 @@ class PubkyRepo @Inject constructor( throw PubkyProfileChangedError(it) } // A session change while the save ran leaves the new session's profile alone. - if (!isCurrent(signIn)) return@withContext - setProfile(saved.profile) - ownProfileRevision = saved.revision + if (!installSavedProfile(saved, signIn)) return@withContext cacheMetadata(saved.profile) notifyBackupStateChanged() saved.tagError?.let { throw it } @@ -1344,32 +1366,51 @@ class PubkyRepo @Inject constructor( } // Tags live only in the Paykit copy, so a changed tag that it does not take is reported. val copyData = profile.toProfileData().toPaykitProfile() - val writeCopy = suspend { + val copyError = writeProfileCopy(keptTags, baseTags) { runSuspendCatching { profileWrite(generation) { pubkyService.publishPaykitProfile(copyData, publicKey) } } .onFailure { Logger.warn("Failed to update Bitkit profile copy", it, context = TAG) } + .exceptionOrNull() } - val copyError = keptTags?.let { - copyWriteOrder.withLock { - // A copy write left running by an earlier save lands first, so it never overwrites this one. - pendingCopyWrite?.join() - if (it == baseTags) { - // With no tag change to report, the save does not wait for the copy; a deletion refuses or waits - // for it. Its outcome leaves the unread flag alone, which a load may have set since. - pendingCopyWrite = scope.launch { writeCopy() } - markTagsRead(stored, readEpoch) - null - } else { - writeCopy().onSuccess { tagsUnavailable = false }.exceptionOrNull() - } - } - } - val saved = if (keptTags != null && copyError == null) profile else profile.copy(tags = baseTags) - val tagsLost = (keptTags == null || copyError != null) && tags != baseTags + val copySaved = keptTags != null && copyError == null + val saved = if (copySaved) profile else profile.copy(tags = baseTags) + val wroteTags = copySaved && keptTags != baseTags + val tagsUnreadAfterSave = unreadTagsAfterCopy(copyUnread, copySaved, stored?.tags != null, wroteTags) val tagError = PubkyProfileTagsNotSavedError( ProfileEditBase(saved, snapshot.revision, tagsUnread = copyUnread), copyError - ).takeIf { tagsLost } - return SavedProfile(saved, snapshot.revision, tagError) + ).takeIf { !copySaved && tags != baseTags } + return SavedProfile(saved, snapshot.revision, tagsUnreadAfterSave, readEpoch.takeUnless { wroteTags }, tagError) + } + + private fun unreadTagsAfterCopy( + copyUnread: Boolean, + copySaved: Boolean, + readTags: Boolean, + wroteTags: Boolean, + ): Boolean? = when { + !copySaved -> true.takeIf { copyUnread } + readTags || wroteTags -> false + else -> null + } + + private suspend fun writeProfileCopy( + tags: List?, + baseTags: List, + writeCopy: suspend () -> Throwable?, + ): Throwable? { + if (tags == null) return null + return copyWriteOrder.withLock { + // A copy write left running by an earlier save lands first, so it never overwrites this one. + pendingCopyWrite?.join() + if (tags == baseTags) { + // With no tag change to report, the save does not wait for the copy; a deletion refuses or waits + // for it. Its outcome leaves the unread flag alone, which a load may have set since. + pendingCopyWrite = scope.launch { writeCopy() } + null + } else { + writeCopy() + } + } } /** @@ -1383,15 +1424,6 @@ class PubkyRepo @Inject constructor( return StoredCopy(tags = data?.tags.orEmpty(), image = data?.image) } - /** - * Clears the unread flag after a save read the copy itself and kept its tags in the profile it stores, unless a - * load found the copy unreadable since [readEpoch]. A save that writes the copy at once clears it only once that - * write succeeds, since a failed one stores the profile without the copy's tags. - */ - private fun markTagsRead(stored: StoredCopy?, readEpoch: Long) { - if (stored?.tags != null && tagsReadEpoch.get() == readEpoch) tagsUnavailable = false - } - /** [name], [bio] and [links] fitted to pubky.app's limits: one line, cut to length, at most five valid links. */ private fun fitted(name: String, bio: String, links: List) = FittedProfile( name = name.singleLine().takeCodePoints(PUBKY_APP_NAME_MAX_LENGTH), @@ -1405,13 +1437,11 @@ class PubkyRepo @Inject constructor( .take(PUBKY_APP_LINKS_MAX_COUNT), ) - private suspend fun loadOwnProfile(publicKey: String): Pair? { + private suspend fun loadOwnProfile(publicKey: String): LoadedProfile? { val generation = profileDeletionGeneration.get() val saveEpoch = profileSaveEpoch.get() val paykitRead = runSuspendCatching { pubkyService.fetchPaykitProfile(publicKey) } .onFailure { Logger.warn("Failed to read Bitkit profile copy", it, context = TAG) } - tagsReadEpoch.incrementAndGet() - tagsUnavailable = paykitRead.isFailure val paykitData = paykitRead.getOrNull()?.let { PubkyProfileData.fromPaykitProfile(it.profile) } val fetched = readRetryingOnce(publicKey) { pubkyService.fetchPubkyProfileWithRevision(publicKey) } if (fetched == null) paykitRead.getOrThrow() @@ -1420,7 +1450,9 @@ class PubkyRepo @Inject constructor( val migrating = fetched == null && !hadPubkyAppProfile var snapshot = fetched ?: paykitData?.takeIf { migrating }?.let { migrateToPubkyApp(publicKey, it, generation) } // While the move cannot finish, the Bitkit profile is shown and the next save creates the pubky.app profile. - snapshot ?: return paykitData?.takeIf { migrating }?.let { it.toPubkyProfile(publicKey) to null } + snapshot ?: return paykitData?.takeIf { migrating }?.let { + LoadedProfile(it.toPubkyProfile(publicKey), revision = null, tagsUnread = false) + } val pendingAvatar = paykitData?.image?.takeIf { it.isPaykitStorage() } var retryingAvatar = fetched != null && publicKey in stored.pubkyAppAvatarPending val avatarMoveSettled = fetched?.profile?.image != null || (paykitRead.isSuccess && pendingAvatar == null) @@ -1444,7 +1476,7 @@ class PubkyRepo @Inject constructor( if (!avatarPending && paykitData != null && paykitData != profile.toProfileData()) { publishPaykitProfileCopy(publicKey, profile, generation, saveEpoch) } - return profile to snapshot.revision + return LoadedProfile(profile, snapshot.revision, tagsUnread = paykitRead.isFailure) } private suspend fun migrateToPubkyApp( @@ -2584,10 +2616,28 @@ class PubkyRepo @Inject constructor( _backupStateVersion.update { it + 1 } } - private fun setProfile(profile: PubkyProfile?) { + private fun setProfile(profile: PubkyProfile?) = synchronized(profileStateLock) { profileWriteGeneration.incrementAndGet() - if (profile == null) ownProfileRevision = null - _profile.update { profile } + if (profile == null) { + ownProfileRevision = null + tagsUnavailable = false + } + _profile.value = profile + } + + private fun installSavedProfile( + saved: SavedProfile, + signIn: PubkySignIn? = null, + ): Boolean = synchronized(profileStateLock) { + if (signIn != null && !isCurrent(signIn)) return@synchronized false + ownProfileRevision = saved.revision + saved.tagsUnread?.let { unread -> + // A completed copy write has the installed tags. A read alone must respect any newer load. + val currentRead = saved.tagsReadEpoch == null || tagsReadEpoch.get() == saved.tagsReadEpoch + if (unread || currentRead) tagsUnavailable = unread + } + setProfile(saved.profile) + true } private fun startSignIn(publicKey: String, restoringStoredIdentity: Boolean = false) { 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 2daf5d751f..882625b5ae 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 @@ -22,6 +22,7 @@ import to.bitkit.models.PubkyProfileLink import to.bitkit.models.Toast import to.bitkit.models.takeCodePoints import to.bitkit.repositories.PubkyProfileChangedError +import to.bitkit.repositories.PubkyProfileTagsNotSavedError import to.bitkit.repositories.PubkyRepo import to.bitkit.ui.components.ProfileEditLink import to.bitkit.ui.shared.toast.ToastEventBus @@ -199,8 +200,16 @@ class CreateProfileViewModel @Inject constructor( _uiState.update { it.copy(isSaving = false) } _effects.emit(CreateProfileEffect.CreateSuccess) }.onFailure { - Logger.error("Failed to create identity", it, context = TAG) _uiState.update { it.copy(isSaving = false) } + if (it is PubkyProfileTagsNotSavedError) { + ToastEventBus.send( + type = Toast.ToastType.ERROR, + title = context.getString(R.string.profile__edit_tags_error), + ) + _effects.emit(CreateProfileEffect.CreateSuccess) + return@onFailure + } + Logger.error("Failed to create identity", it, context = TAG) val changed = it is PubkyProfileChangedError ToastEventBus.send( type = Toast.ToastType.ERROR, 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 862871d2b4..1089d3f21e 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 @@ -226,7 +226,8 @@ class ProfileViewModel @Inject constructor( ) { viewModelScope.launch { tagUpdateMutex.withLock { - val profile = pubkyRepo.profile.value ?: return@withLock + val editBase = pubkyRepo.profileEditBase() + val profile = editBase.profile ?: return@withLock val tags = transform(profile.tags) if (tags == profile.tags) { onSuccess() @@ -239,6 +240,7 @@ class ProfileViewModel @Inject constructor( links = profile.links, tags = tags, imageUrl = profile.imageUrl, + editBase = editBase, ).onSuccess { onSuccess() }.onFailure { diff --git a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt index 00940b9097..5f117fc08b 100644 --- a/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt +++ b/app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt @@ -821,6 +821,24 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(profileSetupPending.value) } + @Test + fun `createIdentity reports a failed tag write and keeps the new identity`() = test { + val httpClient = identityHttpClient() + sut = createSut(httpClient) + stubSignupKeys() + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { throw TestAppError("offline") } + + val result = sut.createIdentity("Test", "", emptyList(), listOf("vip"), null) + httpClient.close() + + assertIs(result.exceptionOrNull()) + assertEquals(VALID_SELF_KEY, sut.publicKey.value) + assertEquals("Test", sut.profile.value?.name) + assertEquals(emptyList(), sut.profile.value?.tags) + assertFalse(profileSetupPending.value) + verifyBlocking(pubkyService, never()) { signOut() } + } + @Test fun `createIdentity completes while contacts are still loading`() = test { val contactsLoadStarted = CompletableDeferred() @@ -1015,6 +1033,41 @@ class PubkyRepoTest : BaseUnitTest() { assertTrue(sut.profileEditBase().tagsUnread) } + @Test + fun `a failed profile refresh cannot mark the displayed empty tags as read`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + sut.loadProfile() + assertEquals(emptyList(), sut.profile.value?.tags) + assertTrue(sut.profileEditBase().tagsUnread) + + val storedTags = listOf("friend", "work") + val record = paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = storedTags).toPaykitProfile()) + doReturn(record).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + val refreshReading = CompletableDeferred() + val finishRefresh = CompletableDeferred() + whenever(pubkyService.fetchPubkyProfileWithRevision(VALID_SELF_KEY)).doSuspendableAnswer { + refreshReading.complete(Unit) + finishRefresh.await() + throw TestAppError("public profile unavailable") + } + + val refresh = async { sut.loadProfile() } + refreshReading.await() + val editBase = sut.profileEditBase() + assertTrue(editBase.tagsUnread) + finishRefresh.complete(Unit) + refresh.await() + assertTrue(sut.profileEditBase().tagsUnread) + + sut.saveProfile("Test", "", emptyList(), listOf("vip"), null, editBase).getOrThrow() + + val copy = argumentCaptor() + verifyBlocking(pubkyService) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(storedTags + "vip", PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) + } + @Test fun `a save that reads the copy itself lets the next edit remove a tag`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) @@ -1148,6 +1201,91 @@ class PubkyRepoTest : BaseUnitTest() { } } + @Test + fun `createIdentity keeps stored tags when the restore form could not read them`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + val restored = checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + assertTrue(restored.tags.isEmpty()) + + val storedTags = listOf("friend", "work") + doReturn( + paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = storedTags).toPaykitProfile()) + ).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + sut.loadProfile() + clearInvocations(pubkyService) + + sut.createIdentity("Renamed", restored.bio, restored.links, restored.tags, null).getOrThrow() + + assertEquals(storedTags, sut.profile.value?.tags) + val copy = argumentCaptor() + verifyBlocking(pubkyService) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(storedTags, PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) + } + + @Test + fun `an edit after restoring without the Paykit copy keeps the stored tags`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + val restored = checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + val storedTags = listOf("friend", "work") + val record = paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = storedTags).toPaykitProfile()) + doReturn(record).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + sut.loadProfile() + + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).thenAnswer { throw TestAppError("offline") } + clearInvocations(pubkyService) + sut.createIdentity("Renamed", restored.bio, restored.links, restored.tags, null).getOrThrow() + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } + + doReturn(record).whenever(pubkyService).fetchPaykitProfile(VALID_SELF_KEY) + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + sut.saveProfile("Renamed Again", restored.bio, restored.links, restored.tags, null).getOrThrow() + + val copy = argumentCaptor() + verifyBlocking(pubkyService) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(storedTags, PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) + } + + @Test + fun `a stale load cannot mark tags readable after restoring without the Paykit copy`() = test { + authenticateForTesting(publicKey = VALID_SELF_KEY) + val storedTags = listOf("friend", "work") + val record = paykitRecord(PubkyProfileData(name = "Test", bio = "", tags = storedTags).toPaykitProfile()) + val loadReading = CompletableDeferred() + val finishLoad = CompletableDeferred() + var reads = 0 + whenever(pubkyService.fetchPaykitProfile(VALID_SELF_KEY)).doSuspendableAnswer { + when (++reads) { + 1, 4 -> throw TestAppError("offline") + 3 -> { + loadReading.complete(Unit) + finishLoad.await() + } + } + record + } + whenever(pubkyService.publishPaykitProfile(any(), any())).thenAnswer { paykitRecord(it.getArgument(0)) } + val restored = checkNotNull(sut.fetchRemoteProfile(VALID_SELF_KEY).getOrThrow()) + sut.loadProfile() + clearInvocations(pubkyService) + + val staleLoad = async { sut.loadProfile() } + loadReading.await() + sut.createIdentity("Renamed", restored.bio, restored.links, restored.tags, null).getOrThrow() + finishLoad.complete(Unit) + staleLoad.await() + assertEquals("Renamed", sut.profile.value?.name) + verifyBlocking(pubkyService, never()) { publishPaykitProfile(any(), any()) } + + sut.saveProfile("Renamed Again", restored.bio, restored.links, restored.tags, null).getOrThrow() + + val copy = argumentCaptor() + verifyBlocking(pubkyService) { publishPaykitProfile(copy.capture(), any()) } + assertEquals(storedTags, PubkyProfileData.fromPaykitProfile(copy.firstValue).tags) + } + @Test fun `saveProfile reports a tag change it could not store while the tags cannot be read`() = test { authenticateForTesting(publicKey = VALID_SELF_KEY) diff --git a/app/src/test/java/to/bitkit/ui/screens/profile/CreateProfileViewModelTest.kt b/app/src/test/java/to/bitkit/ui/screens/profile/CreateProfileViewModelTest.kt index 28fef51b6e..7bc92a52b6 100644 --- a/app/src/test/java/to/bitkit/ui/screens/profile/CreateProfileViewModelTest.kt +++ b/app/src/test/java/to/bitkit/ui/screens/profile/CreateProfileViewModelTest.kt @@ -15,6 +15,8 @@ import org.mockito.kotlin.verify import org.mockito.kotlin.whenever import to.bitkit.R import to.bitkit.models.Toast +import to.bitkit.repositories.ProfileEditBase +import to.bitkit.repositories.PubkyProfileTagsNotSavedError import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.ui.shared.toast.ToastEventBus @@ -68,6 +70,29 @@ class CreateProfileViewModelTest : BaseUnitTest() { toastJob.cancel() } + @Test + fun `save finishes setup and warns when tags could not be saved`() = test { + val warning = "Your profile was saved. Try saving the tags again." + whenever(context.getString(R.string.profile__edit_tags_error)).thenReturn(warning) + whenever(pubkyRepo.createIdentity(any(), any(), any(), any(), anyOrNull())) + .thenReturn(Result.failure(PubkyProfileTagsNotSavedError(ProfileEditBase(null, "revision")))) + val effects = mutableListOf() + val toasts = mutableListOf() + val effectsJob = launch { sut.effects.collect { effects.add(it) } } + val toastJob = launch { ToastEventBus.events.collect { toasts.add(it) } } + + sut.onNameChange("Alice") + advanceUntilIdle() + sut.save() + advanceUntilIdle() + + assertEquals(CreateProfileEffect.CreateSuccess, effects.single()) + assertEquals(warning, toasts.single().title) + + effectsJob.cancel() + toastJob.cancel() + } + @Test fun `save should not publish after a failed lookup for a signed-in pubky`() = test { whenever(pubkyRepo.publicKey).thenReturn(MutableStateFlow("pubkyalice")) 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 2a45e49029..26523e67d7 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 @@ -23,6 +23,7 @@ import to.bitkit.data.PubkyCachedProfile import to.bitkit.models.PubkyProfile import to.bitkit.models.PubkyProfileLink import to.bitkit.repositories.PrivatePaykitRepo +import to.bitkit.repositories.ProfileEditBase import to.bitkit.repositories.PubkyRepo import to.bitkit.test.BaseUnitTest import to.bitkit.test.forEachCase @@ -66,7 +67,7 @@ class ProfileViewModelTest : BaseUnitTest() { sut.addTag("Bitcoin") sut.removeTag("Founder") advanceUntilIdle() - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any(), any()) restore.complete(false) advanceUntilIdle() @@ -331,7 +332,7 @@ class ProfileViewModelTest : BaseUnitTest() { advanceUntilIdle() assertNull(sut.uiState.value.profile) - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any(), any()) } @Test @@ -382,7 +383,10 @@ class ProfileViewModelTest : BaseUnitTest() { @Test fun `addTag saves the updated profile and closes the sheet`() = test { - val sut = createSut(createProfile()) + val profile = createProfile() + val sut = createSut(profile) + val editBase = ProfileEditBase(profile, "revision", tagsUnread = true) + whenever(pubkyRepo.profileEditBase()).thenReturn(editBase) advanceUntilIdle() sut.uiState.test { @@ -401,6 +405,7 @@ class ProfileViewModelTest : BaseUnitTest() { links = listOf(PubkyProfileLink("Website", "https://example.com")), tags = listOf("Founder", "Bitcoin"), imageUrl = "https://example.com/avatar.png", + editBase = editBase, ) } @@ -418,7 +423,7 @@ class ProfileViewModelTest : BaseUnitTest() { sut.addTag("Founder") assertFalse(awaitItem().showAddTagSheet) } - verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any()) + verify(pubkyRepo, never()).saveProfile(any(), any(), any(), any(), any(), any()) } @Test @@ -435,6 +440,7 @@ class ProfileViewModelTest : BaseUnitTest() { links = any(), tags = eq(listOf("Bitcoin")), imageUrl = eq("https://example.com/avatar.png"), + editBase = any(), ) } @@ -444,7 +450,7 @@ class ProfileViewModelTest : BaseUnitTest() { createProfile(tags = listOf("Founder", "Bitcoin")), ) val sut = createSut(profileFlow = profileFlow) - whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any())).doSuspendableAnswer { + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any(), any())).doSuspendableAnswer { val tags = it.getArgument>(3) profileFlow.value = requireNotNull(profileFlow.value).copy(tags = tags) Result.success(Unit) @@ -456,8 +462,8 @@ class ProfileViewModelTest : BaseUnitTest() { advanceUntilIdle() inOrder(pubkyRepo).apply { - verify(pubkyRepo).saveProfile(any(), any(), any(), eq(listOf("Bitcoin")), any()) - verify(pubkyRepo).saveProfile(any(), any(), any(), eq(emptyList()), any()) + verify(pubkyRepo).saveProfile(any(), any(), any(), eq(listOf("Bitcoin")), any(), any()) + verify(pubkyRepo).saveProfile(any(), any(), any(), eq(emptyList()), any(), any()) } assertEquals(emptyList(), profileFlow.value?.tags) } @@ -468,7 +474,7 @@ class ProfileViewModelTest : BaseUnitTest() { createProfile(tags = listOf("Founder", "Bitcoin")), ) val sut = createSut(profileFlow = profileFlow) - whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any())).doSuspendableAnswer { + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any(), any())).doSuspendableAnswer { val tags = it.getArgument>(3) profileFlow.value = requireNotNull(profileFlow.value).copy(tags = tags) Result.success(Unit) @@ -479,14 +485,14 @@ class ProfileViewModelTest : BaseUnitTest() { sut.removeTag("Founder") advanceUntilIdle() - verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), eq(listOf("Bitcoin")), any()) + verify(pubkyRepo, times(1)).saveProfile(any(), any(), any(), eq(listOf("Bitcoin")), any(), any()) assertEquals(listOf("Bitcoin"), profileFlow.value?.tags) } @Test fun `failed tag save keeps the add sheet open for retry`() = test { val sut = createSut(createProfile()) - whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any())) + whenever(pubkyRepo.saveProfile(any(), any(), any(), any(), any(), any())) .thenReturn(Result.failure(ProfileTestAppError("save failed"))) advanceUntilIdle() @@ -519,6 +525,7 @@ class ProfileViewModelTest : BaseUnitTest() { whenever(context.getString(any())).thenReturn("") whenever { pubkyRepo.forgetUnrestoredIdentity() }.thenReturn(Result.success(false)) whenever(pubkyRepo.profile).thenReturn(profileFlow) + whenever(pubkyRepo.profileEditBase()).thenAnswer { ProfileEditBase(profileFlow.value, "revision") } whenever(pubkyRepo.readOnlyProfile).thenReturn(readOnlyProfileFlow) whenever(pubkyRepo.publicKey).thenReturn(publicKeyFlow) whenever(pubkyRepo.isLoadingProfile).thenReturn(isLoadingFlow) @@ -527,7 +534,7 @@ class ProfileViewModelTest : BaseUnitTest() { whenever { pubkyRepo.restoreSessionIfNeeded() }.doSuspendableAnswer { onRestore() } whenever { pubkyRepo.loadProfile() }.thenAnswer { onLoadProfile() } whenever { pubkyRepo.signOut() }.thenReturn(Result.success(Unit)) - whenever { pubkyRepo.saveProfile(any(), any(), any(), any(), any()) }.thenReturn(Result.success(Unit)) + whenever { pubkyRepo.saveProfile(any(), any(), any(), any(), any(), any()) }.thenReturn(Result.success(Unit)) whenever { privatePaykitRepo.removePublishedEndpointsForCleanup(any()) } .thenReturn(Result.success(Unit)) whenever { privatePaykitRepo.closeAndClear() }.thenReturn(Result.success(Unit)) diff --git a/changelog.d/next/1884.fixed.md b/changelog.d/next/1884.fixed.md new file mode 100644 index 0000000000..40d4cf098a --- /dev/null +++ b/changelog.d/next/1884.fixed.md @@ -0,0 +1 @@ +Restoring a Pubky profile preserves its saved tags when the profile initially loads without them.