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
184 changes: 117 additions & 67 deletions app/src/main/java/to/bitkit/repositories/PubkyRepo.kt

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Expand All @@ -239,6 +240,7 @@ class ProfileViewModel @Inject constructor(
links = profile.links,
tags = tags,
imageUrl = profile.imageUrl,
editBase = editBase,
).onSuccess {
onSuccess()
}.onFailure {
Expand Down
138 changes: 138 additions & 0 deletions app/src/test/java/to/bitkit/repositories/PubkyRepoTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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<PubkyProfileTagsNotSavedError>(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<Unit>()
Expand Down Expand Up @@ -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<Unit>()
val finishRefresh = CompletableDeferred<Unit>()
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<PaykitProfile>()
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)
Expand Down Expand Up @@ -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<PaykitProfile>()
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<PaykitProfile>()
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<Unit>()
val finishLoad = CompletableDeferred<Unit>()
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<PaykitProfile>()
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)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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<CreateProfileEffect>()
val toasts = mutableListOf<Toast>()
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"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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 {
Expand All @@ -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,
)
}

Expand All @@ -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
Expand All @@ -435,6 +440,7 @@ class ProfileViewModelTest : BaseUnitTest() {
links = any(),
tags = eq(listOf("Bitcoin")),
imageUrl = eq("https://example.com/avatar.png"),
editBase = any(),
)
}

Expand All @@ -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<List<String>>(3)
profileFlow.value = requireNotNull(profileFlow.value).copy(tags = tags)
Result.success(Unit)
Expand All @@ -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)
}
Expand All @@ -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<List<String>>(3)
profileFlow.value = requireNotNull(profileFlow.value).copy(tags = tags)
Result.success(Unit)
Expand All @@ -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()

Expand Down Expand Up @@ -519,6 +525,7 @@ class ProfileViewModelTest : BaseUnitTest() {
whenever(context.getString(any<Int>())).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)
Expand All @@ -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))
Expand Down
1 change: 1 addition & 0 deletions changelog.d/next/1884.fixed.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Restoring a Pubky profile preserves its saved tags when the profile initially loads without them.
Loading