diff --git a/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt b/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt index c5733f31..6074b443 100644 --- a/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt +++ b/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt @@ -63,6 +63,16 @@ interface ChatRepository { caption: String? = null, ) + /** + * Deletes the signed-in user's photo message with this ID, for a [sendPhoto] that failed and that + * they no longer want sent, so that it does not stay pending for the other participant. Like + * [markRead], the delete is queued without waiting for the server, so it works offline, and it + * never throws: a failure is only logged. The rules only let the sender delete a message whose + * photo is still pending, and refuse to delete one that was never written, which is then only + * logged. The conversation's preview of it stays until the next message. + */ + fun deletePhotoMessage(conversationId: String, messageId: String) + /** * Downloads the photo of a message, from its [ChatMessage.imagePath], as the signed-in user. * Fails with PERMISSION_DENIED for a user who is not a participant of the conversation, with an diff --git a/app/src/main/java/com/android/polybazaar/chat/model/FirebaseChatRepository.kt b/app/src/main/java/com/android/polybazaar/chat/model/FirebaseChatRepository.kt index ae6e09a2..6049bfeb 100644 --- a/app/src/main/java/com/android/polybazaar/chat/model/FirebaseChatRepository.kt +++ b/app/src/main/java/com/android/polybazaar/chat/model/FirebaseChatRepository.kt @@ -161,6 +161,15 @@ class FirebaseChatRepository( storage.reference.child(imagePath).getBytes(PhotoStorage.MAX_PHOTO_BYTES).await() } + override fun deletePhotoMessage(conversationId: String, messageId: String) { + // Not awaited, like markRead: the delete is queued offline and the listener sees it at once. + conversationDocument(conversationId) + .collection(MESSAGES) + .document(messageId) + .delete() + .addOnFailureListener(Executor { it.run() }) { logWriteFailure(it) } + } + override fun markRead(conversationId: String) { val uid = auth.currentUser?.uid ?: return // Not awaited, like sendMessage: the write is queued offline and the listener sees it at once. diff --git a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt index 1bbdd0e2..3efe6947 100644 --- a/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt +++ b/app/src/main/java/com/android/polybazaar/chat/ui/ConversationScreen.kt @@ -1,11 +1,17 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.ui +import android.net.Uri +import androidx.activity.compose.rememberLauncherForActivityResult +import androidx.activity.result.PickVisualMediaRequest +import androidx.activity.result.contract.ActivityResultContracts +import androidx.compose.foundation.Image import androidx.compose.foundation.background import androidx.compose.foundation.border import androidx.compose.foundation.layout.Arrangement import androidx.compose.foundation.layout.Box import androidx.compose.foundation.layout.Column +import androidx.compose.foundation.layout.ColumnScope import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.layout.Row import androidx.compose.foundation.layout.Spacer @@ -16,25 +22,39 @@ import androidx.compose.foundation.layout.heightIn import androidx.compose.foundation.layout.padding import androidx.compose.foundation.layout.safeDrawingPadding import androidx.compose.foundation.layout.size +import androidx.compose.foundation.layout.width import androidx.compose.foundation.layout.widthIn import androidx.compose.foundation.lazy.LazyColumn import androidx.compose.foundation.lazy.items import androidx.compose.foundation.lazy.rememberLazyListState +import androidx.compose.foundation.shape.CircleShape import androidx.compose.foundation.shape.RoundedCornerShape import androidx.compose.foundation.text.BasicTextField import androidx.compose.foundation.text.KeyboardOptions import androidx.compose.material3.CircularProgressIndicator +import androidx.compose.material3.DropdownMenu +import androidx.compose.material3.DropdownMenuItem import androidx.compose.material3.HorizontalDivider import androidx.compose.material3.Icon +import androidx.compose.material3.IconButton import androidx.compose.material3.Text import androidx.compose.material3.TextButton import androidx.compose.runtime.Composable import androidx.compose.runtime.LaunchedEffect import androidx.compose.runtime.collectAsState import androidx.compose.runtime.getValue +import androidx.compose.runtime.mutableStateOf +import androidx.compose.runtime.produceState +import androidx.compose.runtime.remember +import androidx.compose.runtime.setValue import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.draw.alpha +import androidx.compose.ui.draw.clip +import androidx.compose.ui.graphics.ImageBitmap import androidx.compose.ui.graphics.SolidColor +import androidx.compose.ui.layout.ContentScale +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.painterResource import androidx.compose.ui.res.pluralStringResource @@ -64,8 +84,13 @@ import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.viewmodel.ConversationListingStatus import com.android.polybazaar.chat.viewmodel.ConversationUiState import com.android.polybazaar.chat.viewmodel.ConversationViewModel +import com.android.polybazaar.chat.viewmodel.PendingPhoto +import com.android.polybazaar.chat.viewmodel.PendingPhotoStatus import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message +import com.android.polybazaar.listing.ui.CameraPermissionDialog +import com.android.polybazaar.listing.ui.loadPhotoPreview +import com.android.polybazaar.listing.ui.rememberPhotoCamera import java.time.Instant import java.time.ZoneId import java.time.ZoneOffset @@ -88,12 +113,27 @@ object ConversationScreenTags { const val SEND_BUTTON = "conversation_send_button" const val SEND_ERROR = "conversation_send_error" const val LENGTH_COUNTER = "conversation_length_counter" + const val PHOTO_BUTTON = "conversation_photo_button" + const val PHOTO_MENU = "conversation_photo_menu" + const val TAKE_PHOTO = "conversation_take_photo" + const val CHOOSE_PHOTO = "conversation_choose_photo" + const val ATTACHED_PHOTO = "conversation_attached_photo" + const val REMOVE_ATTACHED_PHOTO = "conversation_remove_attached_photo" /** Tag of the bubble of the signed-in user's message with [id]. */ fun myMessage(id: String) = "conversation_my_message_$id" /** Tag of the bubble of the other participant's message with [id]. */ fun theirMessage(id: String) = "conversation_their_message_$id" + + /** Tag of the bubble of the photo being sent, or that failed, with message ID [id]. */ + fun pendingPhoto(id: String) = "conversation_pending_photo_$id" + + /** Tag of Retry on the failed photo with message ID [id]. */ + fun retryPhoto(id: String) = "conversation_retry_photo_$id" + + /** Tag of Remove on the failed photo with message ID [id]. */ + fun discardPhoto(id: String) = "conversation_discard_photo_$id" } /** What the screen shows between the header and the composer, decided by [conversationBody]. */ @@ -124,6 +164,12 @@ private val PageMargin = 18.dp /** Widest a bubble gets, so a long message wraps instead of spanning the screen. */ private val MaxBubbleWidth = 300.dp +/** + * Height of a photo in its bubble, the same while it loads, so the list does not jump when it + * arrives. + */ +private val BubblePhotoHeight = 200.dp + private val TimeFormat = DateTimeFormatter.ofPattern("HH:mm") /** @@ -142,6 +188,17 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { viewModel.setVisible(true) onStopOrDispose { viewModel.setVisible(false) } } + val galleryPicker = + rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri -> + if (uri != null) viewModel.attachPhoto(uri) + } + // The ViewModel keeps the photo file in its saved state, so it survives the activity being + // recreated meanwhile, and Android killing the app while the camera app is in front. + val camera = + rememberPhotoCamera( + startTakingPhoto = { _ -> viewModel.startTakingPhoto() }, + finishTakingPhoto = viewModel::finishTakingPhoto, + ) ConversationContent( uiState = uiState, onBack = onBack, @@ -149,7 +206,19 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { onSend = viewModel::send, onRetry = viewModel::retry, onDismissSendError = viewModel::dismissSendError, + onTakePhoto = camera::takePhoto, + onChoosePhoto = { + galleryPicker.launch( + PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly) + ) + }, + onRemoveAttachedPhoto = viewModel::removeAttachedPhoto, + onRetryPhoto = viewModel::retryPhoto, + onDiscardPhoto = viewModel::discardPhoto, ) + if (camera.showPermissionExplanation) { + CameraPermissionDialog(onDismiss = camera::dismissPermissionExplanation) + } } /** @@ -165,6 +234,11 @@ fun ConversationScreen(viewModel: ConversationViewModel, onBack: () -> Unit) { * @param onRetry called when the user taps Retry after a load failed. * @param onDismissSendError called before [onDraftChange] when the user edits the draft while a * send error shows. + * @param onTakePhoto called when the user picks "Take photo" in the photo menu. + * @param onChoosePhoto called when the user picks "Choose from gallery" in the photo menu. + * @param onRemoveAttachedPhoto called when the user taps ✕ on the attached photo. + * @param onRetryPhoto called with the message ID of a failed photo when the user taps Retry. + * @param onDiscardPhoto called with the message ID of a failed photo when the user taps Remove. * @param zone time zone of the message times. */ @Composable @@ -175,6 +249,11 @@ fun ConversationContent( onSend: () -> Unit = {}, onRetry: () -> Unit = {}, onDismissSendError: () -> Unit = {}, + onTakePhoto: () -> Unit = {}, + onChoosePhoto: () -> Unit = {}, + onRemoveAttachedPhoto: () -> Unit = {}, + onRetryPhoto: (String) -> Unit = {}, + onDiscardPhoto: (String) -> Unit = {}, zone: ZoneId = ZoneId.systemDefault(), ) { val body = conversationBody(uiState) @@ -183,7 +262,11 @@ fun ConversationContent( // canSend decides when Send works. val composerOpen = !deleted val placeholder = - if (deleted) R.string.conversation_placeholder_closed else R.string.conversation_placeholder + when { + deleted -> R.string.conversation_placeholder_closed + uiState.attachedPhoto != null -> R.string.conversation_placeholder_caption + else -> R.string.conversation_placeholder + } Column( modifier = Modifier.fillMaxSize() @@ -204,7 +287,13 @@ fun ConversationContent( listingTitle = uiState.listingTitle, listingStatus = uiState.listingStatus, ) - ConversationBody.MESSAGES -> MessageList(uiState = uiState, zone = zone, onRetry = onRetry) + ConversationBody.MESSAGES -> + MessageList( + uiState = uiState, + zone = zone, + onRetry = onRetry, + photoActions = PhotoActions(onRetryPhoto, onDiscardPhoto), + ) } } Composer( @@ -218,6 +307,14 @@ fun ConversationContent( onDraftChange(text) }, onSend = onSend, + photo = + ComposerPhoto( + attached = uiState.attachedPhoto, + canAttach = uiState.canAttachPhoto, + onTake = onTakePhoto, + onChoose = onChoosePhoto, + onRemove = onRemoveAttachedPhoto, + ), ) } } @@ -407,15 +504,31 @@ private fun EmptyState( } } +/** What the user can do with the photos being sent. */ +private class PhotoActions( + val retry: (messageId: String) -> Unit, + val discard: (messageId: String) -> Unit, +) + /** - * The messages, oldest at the top, with the load error and Retry above them when a reload failed. + * The messages, oldest at the top, then the photos being sent, with the load error and Retry above + * them when a reload failed. */ @Composable -private fun MessageList(uiState: ConversationUiState, zone: ZoneId, onRetry: () -> Unit) { - val messages = uiState.messages +private fun MessageList( + uiState: ConversationUiState, + zone: ZoneId, + onRetry: () -> Unit, + photoActions: PhotoActions, +) { + val messages = uiState.shownMessages + val pendingPhotos = uiState.pendingPhotos val listState = rememberLazyListState() - // The list keeps its place by key, so a new message would arrive below the view without this. - LaunchedEffect(messages.lastOrNull()?.id) { listState.scrollToItem(0) } + // The list keeps its place by key, so a new message or photo would arrive below the view without + // this. + LaunchedEffect(messages.lastOrNull()?.id, pendingPhotos.lastOrNull()?.messageId) { + listState.scrollToItem(0) + } Column(modifier = Modifier.fillMaxSize()) { uiState.loadError?.let { LoadErrorRow(text = it.message(), onRetry = onRetry) } // Laid out from the bottom, newest first, so the newest message stays in view, footer @@ -427,6 +540,14 @@ private fun MessageList(uiState: ConversationUiState, zone: ZoneId, onRetry: () reverseLayout = true, verticalArrangement = Arrangement.spacedBy(8.dp), ) { + // Prefixed: once sent, a photo's message arrives with the same ID. + items(pendingPhotos.asReversed(), key = { "pending_${it.messageId}" }) { pending -> + PendingPhotoBubble( + pending = pending, + onRetry = { photoActions.retry(pending.messageId) }, + onDiscard = { photoActions.discard(pending.messageId) }, + ) + } items(messages.asReversed(), key = { it.id }) { message -> MessageBubble( message = message, @@ -489,6 +610,37 @@ private fun MessageBubble( stringResource(R.string.conversation_their_message_footer, otherUsername, time) else -> time } + Bubble( + isMine = isMine, + tag = + if (isMine) ConversationScreenTags.myMessage(message.id) + else ConversationScreenTags.theirMessage(message.id), + fixedWidth = false, + ) { + Text( + text = message.text, + color = AuthColors.TextPrimary, + fontSize = 14.sp, + lineHeight = 19.sp, + ) + BubbleFooter(text = footer) + } +} + +/** + * A message bubble: the user's own at the end of the row, the other participant's at the start. One + * TalkBack item: its photo, its text, then who sent it and when. + * + * @param fixedWidth whether the bubble is always [MaxBubbleWidth] wide, as for a photo, rather than + * as wide as its text. + */ +@Composable +private fun Bubble( + isMine: Boolean, + tag: String, + fixedWidth: Boolean, + content: @Composable ColumnScope.() -> Unit, +) { val shape = RoundedCornerShape(16.dp) Box( modifier = Modifier.fillMaxWidth(), @@ -496,14 +648,10 @@ private fun MessageBubble( ) { Column( modifier = - Modifier.widthIn(max = MaxBubbleWidth) - // One TalkBack item per message, the whole bubble: its text, then who sent it and - // when. + (if (fixedWidth) Modifier.width(MaxBubbleWidth) + else Modifier.widthIn(max = MaxBubbleWidth)) .semantics(mergeDescendants = true) {} - .testTag( - if (isMine) ConversationScreenTags.myMessage(message.id) - else ConversationScreenTags.theirMessage(message.id) - ) + .testTag(tag) .background( if (isMine) AuthColors.AccentContainer else AuthColors.CardBackground, shape, @@ -513,25 +661,111 @@ private fun MessageBubble( .padding(horizontal = 12.dp, vertical = 8.dp), verticalArrangement = Arrangement.spacedBy(4.dp), ) { - Text( - text = message.text, - color = AuthColors.TextPrimary, - fontSize = 14.sp, - lineHeight = 19.sp, + content() + } + } +} + +@Composable +private fun ColumnScope.BubbleFooter(text: String) { + Text( + text = text, + color = AuthColors.TextSecondary, + fontSize = 11.sp, + modifier = Modifier.align(Alignment.End), + ) +} + +/** + * A photo the user sent that is not in the conversation yet, as their own bubble: faded with a + * spinner while it uploads; faded with why it failed, Retry and Remove once it failed. + */ +@Composable +private fun PendingPhotoBubble(pending: PendingPhoto, onRetry: () -> Unit, onDiscard: () -> Unit) { + val description = stringResource(R.string.conversation_photo) + val uploading = pending.status == PendingPhotoStatus.UPLOADING + Bubble( + isMine = true, + tag = ConversationScreenTags.pendingPhoto(pending.messageId), + fixedWidth = true, + ) { + Box(contentAlignment = Alignment.Center) { + // The placeholder shows when the photo on the device can no longer be read. + PhotoOrPlaceholder( + photo = rememberLocalPhoto(pending.photo), + description = description, + modifier = + Modifier.fillMaxWidth() + .height(BubblePhotoHeight) + .clip(RoundedCornerShape(10.dp)) + .alpha(0.6f), ) + if (uploading) { + CircularProgressIndicator( + color = AuthColors.CardBackground, + strokeWidth = 2.dp, + modifier = Modifier.size(24.dp), + ) + } + } + pending.caption?.let { + Text(text = it, color = AuthColors.TextPrimary, fontSize = 14.sp, lineHeight = 19.sp) + } + if (uploading) { + BubbleFooter(text = stringResource(R.string.conversation_photo_sending)) + } else { Text( - text = footer, - color = AuthColors.TextSecondary, - fontSize = 11.sp, - modifier = Modifier.align(Alignment.End), + text = + stringResource( + R.string.conversation_photo_not_sent, + (pending.error ?: AppError.UNKNOWN).message(), + ), + color = AuthColors.Danger, + fontSize = 12.sp, + // Announced when it fails: TalkBack's focus is elsewhere, on Send or the field. + modifier = Modifier.semantics { liveRegion = LiveRegionMode.Polite }, ) + Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + TextButton( + onClick = onRetry, + modifier = Modifier.testTag(ConversationScreenTags.retryPhoto(pending.messageId)), + ) { + Text( + text = stringResource(R.string.conversation_retry), + color = AuthColors.Accent, + fontWeight = FontWeight.SemiBold, + ) + } + TextButton( + onClick = onDiscard, + modifier = Modifier.testTag(ConversationScreenTags.discardPhoto(pending.messageId)), + ) { + Text( + text = stringResource(R.string.conversation_photo_remove), + color = AuthColors.TextSecondary, + ) + } + } } } } /** - * The message field and Send, with why the last send failed under them and, once the draft is too - * long, a counter that explains why Send is disabled. The text is kept as typed. + * The composer's photo: the one attached, whether one can be attached, and what the user does with + * it. + */ +private class ComposerPhoto( + val attached: Uri?, + val canAttach: Boolean, + val onTake: () -> Unit, + val onChoose: () -> Unit, + val onRemove: () -> Unit, +) + +/** + * The photo button, the message field and Send, with the attached photo above them, and under them + * why the last send failed and, once the draft is too long, a counter that explains why Send is + * disabled. The text is kept as typed. * * @param open whether the user can type; Send also needs [canSend]. */ @@ -544,6 +778,7 @@ private fun Composer( sendError: AppError?, onDraftChange: (String) -> Unit, onSend: () -> Unit, + photo: ComposerPhoto, ) { val length = ChatRules.countedLength(draft) val tooLong = open && length > ChatRules.MAX_MESSAGE_LENGTH @@ -563,10 +798,12 @@ private fun Composer( .padding(horizontal = PageMargin, vertical = 10.dp), verticalArrangement = Arrangement.spacedBy(6.dp), ) { + photo.attached?.let { AttachedPhoto(photo = it, onRemove = photo.onRemove) } Row( horizontalArrangement = Arrangement.spacedBy(10.dp), verticalAlignment = Alignment.Bottom, ) { + PhotoButton(enabled = photo.canAttach, onTake = photo.onTake, onChoose = photo.onChoose) MessageField( value = draft, onValueChange = onDraftChange, @@ -626,6 +863,145 @@ private fun Composer( } } +/** The camera button left of the field, opening a menu to take a photo or choose one. */ +@Composable +private fun PhotoButton(enabled: Boolean, onTake: () -> Unit, onChoose: () -> Unit) { + var menuOpen by remember { mutableStateOf(false) } + val shape = RoundedCornerShape(14.dp) + Box { + IconButton( + onClick = { menuOpen = true }, + enabled = enabled, + modifier = + Modifier.size(48.dp) + .border(1.dp, AuthColors.Outline, shape) + .testTag(ConversationScreenTags.PHOTO_BUTTON), + ) { + Icon( + painter = painterResource(R.drawable.ic_camera), + contentDescription = stringResource(R.string.conversation_photo_button), + tint = if (enabled) AuthColors.TextPrimary else AuthColors.TextSecondary, + modifier = Modifier.size(20.dp), + ) + } + DropdownMenu( + expanded = menuOpen, + onDismissRequest = { menuOpen = false }, + containerColor = AuthColors.CardBackground, + modifier = Modifier.testTag(ConversationScreenTags.PHOTO_MENU), + ) { + PhotoMenuItem( + text = stringResource(R.string.conversation_take_photo), + icon = R.drawable.ic_camera, + tag = ConversationScreenTags.TAKE_PHOTO, + onClick = { + menuOpen = false + onTake() + }, + ) + PhotoMenuItem( + text = stringResource(R.string.conversation_choose_photo), + icon = R.drawable.ic_image, + tag = ConversationScreenTags.CHOOSE_PHOTO, + onClick = { + menuOpen = false + onChoose() + }, + ) + } + } +} + +@Composable +private fun PhotoMenuItem(text: String, icon: Int, tag: String, onClick: () -> Unit) { + DropdownMenuItem( + text = { Text(text = text, color = AuthColors.TextPrimary, fontSize = 14.sp) }, + // Decorative: the text says what the item does. + leadingIcon = { + Icon( + painter = painterResource(icon), + contentDescription = null, + tint = AuthColors.TextPrimary, + modifier = Modifier.size(20.dp), + ) + }, + onClick = onClick, + modifier = Modifier.testTag(tag), + ) +} + +/** The photo attached to the draft, as a thumbnail with ✕ in its corner to remove it. */ +@Composable +private fun AttachedPhoto(photo: Uri, onRemove: () -> Unit) { + val shape = RoundedCornerShape(12.dp) + val description = stringResource(R.string.conversation_attached_photo) + // The thumbnail with room around it for ✕, which overlaps its top-right corner. + Box(modifier = Modifier.size(80.dp)) { + PhotoOrPlaceholder( + photo = rememberLocalPhoto(photo), + description = description, + modifier = + Modifier.align(Alignment.BottomStart) + .size(64.dp) + .clip(shape) + .testTag(ConversationScreenTags.ATTACHED_PHOTO), + ) + IconButton( + onClick = onRemove, + modifier = + Modifier.align(Alignment.TopEnd) + .size(32.dp) + .testTag(ConversationScreenTags.REMOVE_ATTACHED_PHOTO), + ) { + Box( + modifier = + Modifier.size(20.dp) + .background(AuthColors.TextPrimary.copy(alpha = 0.7f), CircleShape), + contentAlignment = Alignment.Center, + ) { + Icon( + painter = painterResource(R.drawable.ic_close), + contentDescription = stringResource(R.string.conversation_remove_attached_photo), + tint = AuthColors.CardBackground, + modifier = Modifier.size(12.dp), + ) + } + } + } +} + +/** [photo] filling its bounds, or a plain placeholder of the same size until it is decoded. */ +@Composable +private fun PhotoOrPlaceholder(photo: ImageBitmap?, description: String, modifier: Modifier) { + if (photo != null) { + Image( + bitmap = photo, + contentDescription = description, + contentScale = ContentScale.Crop, + modifier = modifier, + ) + } else { + Box( + modifier = + modifier.background(AuthColors.Outline).semantics { contentDescription = description } + ) + } +} + +/** + * A photo on the device, decoded off the main thread and scaled down, or null while it decodes or + * when it cannot be read. + */ +@Composable +private fun rememberLocalPhoto(photo: Uri): ImageBitmap? { + val contentResolver = LocalContext.current.contentResolver + val bitmap by + produceState(initialValue = null, photo) { + value = loadPhotoPreview(contentResolver, photo) + } + return bitmap +} + /** A field styled like LabeledField's, that grows up to five lines as the message gets longer. */ @Composable private fun MessageField( diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt index 56bc3770..211d8019 100644 --- a/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/ConversationViewModel.kt @@ -1,6 +1,8 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.viewmodel +import android.net.Uri +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.ViewModel import androidx.lifecycle.viewModelScope import com.android.polybazaar.auth.model.User @@ -14,10 +16,12 @@ import com.android.polybazaar.error.model.toAppError import com.android.polybazaar.listing.model.Listing import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.listing.model.ObservedListing +import com.android.polybazaar.listing.model.PhotoStorage import com.android.polybazaar.profile.model.ProfileRepository import java.time.Instant import java.util.concurrent.atomic.AtomicBoolean import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Job import kotlinx.coroutines.flow.MutableStateFlow import kotlinx.coroutines.flow.StateFlow @@ -33,6 +37,28 @@ enum class ConversationListingStatus { DELETED, } +/** Where a photo being sent is. */ +enum class PendingPhotoStatus { + UPLOADING, + FAILED, +} + +/** + * A photo the user sent that is not in the conversation yet: still uploading, or failed. + * + * @property messageId the ID of its message, kept so a retry reuses what is already on the server. + * @property photo the photo on the device. + * @property caption the trimmed caption, or null for a photo alone. + * @property error why it failed, when [status] is [PendingPhotoStatus.FAILED]. + */ +data class PendingPhoto( + val messageId: String, + val photo: Uri, + val caption: String?, + val status: PendingPhotoStatus, + val error: AppError? = null, +) + /** * State of the conversation screen. * @@ -45,11 +71,16 @@ enum class ConversationListingStatus { * null until it is known. * @property otherUser profile of the other participant, or null while it loads, after a failure, or * when they have no profile. - * @property draft the message being typed. - * @property canSend whether the draft can be sent now. + * @property draft the message being typed, or the caption of [attachedPhoto] when there is one. + * @property attachedPhoto the photo picked or taken to send with the draft as its caption, if any. + * @property canAttachPhoto whether a photo can be attached: only once the conversation exists, + * since a photo cannot be its first message, and while the listing is known and not deleted. + * @property canSend whether the draft, or the attached photo with its caption, can be sent now. * @property firstMessageBlockedByPause true when the renter has no conversation yet and the listing * is paused: the rules refuse a first message until it is active again. False while the * conversation loads and after it failed to load, when whether it exists is unknown. + * @property pendingPhotos the photos sent that are still uploading or failed, oldest first. Their + * message may already be in [messages], since it is written before the photo is uploaded. * @property isLoading true until the listing, the conversation and the messages have each been * loaded or failed, and again while a retry reloads any of them. * @property loadError why the conversation could not be loaded; the screen offers Retry. What is @@ -64,12 +95,26 @@ data class ConversationUiState( val listingStatus: ConversationListingStatus? = null, val otherUser: User? = null, val draft: String = "", + val attachedPhoto: Uri? = null, + val canAttachPhoto: Boolean = false, val canSend: Boolean = false, val firstMessageBlockedByPause: Boolean = false, + val pendingPhotos: List = emptyList(), val isLoading: Boolean = true, val loadError: AppError? = null, val sendError: AppError? = null, -) +) { + /** + * The [messages] to show: those of [pendingPhotos] are left out, as their pending bubble already + * shows them, so a photo shows once while it uploads or after it failed. + */ + val shownMessages: List = + if (pendingPhotos.isEmpty()) messages + else { + val pendingIds = pendingPhotos.mapTo(HashSet()) { it.messageId } + messages.filterNot { it.id in pendingIds } + } +} /** The listing as last observed, kept in one reference so other threads never see half of it. */ private data class LoadedListing( @@ -81,6 +126,17 @@ private data class LoadedListing( * Shows and sends the messages between the renter [renterUid] and the owner of the listing * [listingId], as seen by [myUid], the signed-in user. * + * [photoStorage] keeps the photos taken with the camera until they are sent; photos picked from the + * gallery belong to the user and are never deleted. + * + * [savedStateHandle] keeps the photo the camera app is taking when Android kills the app, which can + * happen while the camera app is in front. Pass `createSavedStateHandle()` from the factory: a + * handle made by hand is not saved by Android. + * + * [uploadScope] runs the photo uploads, so that closing the screen does not cancel them: pass + * [photoUploadScope]. Once the screen is closed, an upload that ends deletes its photo if it was + * taken with the camera, whether it was sent or not, as nothing can retry it any more. + * * The lender must only be routed here for a conversation that already exists: until then the * security rules refuse them the conversation and its messages, which shows as a load error. */ @@ -91,6 +147,9 @@ class ConversationViewModel( private val chatRepository: ChatRepository, private val profileRepository: ProfileRepository, private val listingRepository: ListingRepository, + private val photoStorage: PhotoStorage, + private val savedStateHandle: SavedStateHandle, + private val uploadScope: CoroutineScope, ) : ViewModel() { private val _uiState = MutableStateFlow(ConversationUiState(myUid = myUid)) @@ -113,6 +172,18 @@ class ConversationViewModel( private var sendInFlight = false private var lastMarkedReadAt: Instant? = null private var isVisible = false + // Whether the screen is closed, so an upload that fails afterwards deletes its photo. + private var cleared = false + // The photo the camera app is taking, until it closes. Saved, so that it is still attached when + // the camera app returns to an app that Android killed meanwhile. + private var photoBeingTaken: Uri? + get() = savedStateHandle[PHOTO_BEING_TAKEN] + set(value) { + savedStateHandle[PHOTO_BEING_TAKEN] = value + } + + // Photos taken with the camera and not deleted yet, so gallery photos are never deleted. + private val takenPhotos = mutableSetOf() init { observeListing() @@ -135,13 +206,69 @@ class ConversationViewModel( _uiState.update { it.copy(draft = text).derived() } } + /** + * Attaches [photo], picked from the gallery, replacing the photo attached before. Ignored when a + * photo cannot be attached; while the screen is still loading, it is attached and can be sent + * once the conversation is known to allow it. + */ + fun attachPhoto(photo: Uri) { + if (!_uiState.value.mayReceivePhoto()) return + replaceAttachedPhoto(photo) + } + + /** + * Prepares a photo for the camera app to take and returns where it should write it, or null when + * a photo cannot be attached or the file cannot be created. Call [finishTakingPhoto] once the + * camera app closes. + */ + fun startTakingPhoto(): Uri? { + if (!_uiState.value.canAttachPhoto) return null + // A second tap before the camera app opened replaces the first photo, which stays empty. + photoBeingTaken?.let(photoStorage::delete) + photoBeingTaken = null + val photo = photoStorage.newPhoto() ?: return null + photoBeingTaken = photo.uri + return photo.cameraUri + } + + /** + * Attaches the photo the camera app took, or deletes its empty file if [saved] is false or a + * photo can no longer be attached. While the screen is still loading, it is attached as in + * [attachPhoto]. + */ + fun finishTakingPhoto(saved: Boolean) { + val photo = photoBeingTaken ?: return + photoBeingTaken = null + if (!saved || !_uiState.value.mayReceivePhoto()) { + photoStorage.delete(photo) + return + } + takenPhotos += photo + replaceAttachedPhoto(photo) + } + + /** Removes the attached photo, deleting it if it was taken with the camera. */ + fun removeAttachedPhoto() { + val photo = _uiState.value.attachedPhoto ?: return + _uiState.update { it.copy(attachedPhoto = null).derived() } + deleteIfTaken(photo) + } + /** * Queues the draft as a message: the first one creates the conversation, later ones reply in it. - * Ignored when it cannot be sent or while the previous send call is still running. + * With a photo attached, sends the photo with the draft as its caption instead. Ignored when it + * cannot be sent or while the previous text send call is still running. */ fun send() { val state = _uiState.value + // Also for a photo: until the text sent before returns, the draft still holds it, and the photo + // would send it again as its caption. if (!state.canSend || sendInFlight) return + val photo = state.attachedPhoto + if (photo != null) { + sendPhoto(state, photo) + return + } // Before the conversation has loaded, a renter's message is sent as a first one: the merge // write becomes an update when the conversation exists, and the rules accept it. val target = state.conversation ?: firstConversation() ?: return @@ -189,10 +316,151 @@ class ConversationViewModel( if (messages) observeMessages() } + /** + * Sends the attached [photo] with the draft as its caption. Both are cleared at once, so a second + * tap on Send finds nothing to send, and the photo shows as uploading until it is sent. + */ + private fun sendPhoto(state: ConversationUiState, photo: Uri) { + // canSend only allows a photo once the conversation exists. + val conversation = state.conversation ?: return + val pending = + PendingPhoto( + messageId = chatRepository.newMessageId(conversation.id), + photo = photo, + caption = state.draft.trim().ifEmpty { null }, + status = PendingPhotoStatus.UPLOADING, + ) + _uiState.update { + it.copy(draft = "", attachedPhoto = null, pendingPhotos = it.pendingPhotos + pending) + .derived() + } + upload(conversation, pending) + } + + /** + * Sends [pending], then removes it once the server has its message and photo, or marks it failed. + */ + private fun upload(conversation: Conversation, pending: PendingPhoto) { + uploadScope.launch { + try { + chatRepository.sendPhoto(conversation, pending.messageId, pending.photo, pending.caption) + _uiState.update { + it.copy(pendingPhotos = it.pendingPhotos.filterNot { p -> p.isSameAs(pending) }) + } + // Sent: nothing can fail any more, so the taken photo is no longer needed. + deleteIfTaken(pending.photo) + } catch (exception: Exception) { + if (exception is CancellationException) throw exception + // A refusal from a pause or deletion of the listing also reaches its observation, which + // then stops new photos from being attached. + _uiState.update { it.withPendingPhoto(pending.failed(exception.toAppError())) } + // Closed: no one can retry it, so it is removed as by Remove. + if (cleared) abandon(pending) + } + } + } + + /** + * Sends the failed photo of [messageId] again, with the same message ID: a message or photo + * already on the server is reused, since the rules refuse to write either twice. Ignored unless + * it failed. + */ + fun retryPhoto(messageId: String) { + val state = _uiState.value + val failed = state.failedPhoto(messageId) ?: return + val conversation = state.conversation ?: return + val retried = failed.copy(status = PendingPhotoStatus.UPLOADING, error = null) + _uiState.update { it.withPendingPhoto(retried) } + upload(conversation, retried) + } + + /** + * Removes the failed photo of [messageId], deleting it if it was taken with the camera, and + * deletes its message, which may already be on the server with its photo pending, so the other + * participant no longer sees it. Ignored unless it failed: an upload under way cannot be taken + * back. + */ + fun discardPhoto(messageId: String) { + val failed = _uiState.value.failedPhoto(messageId) ?: return + _uiState.update { + it.copy(pendingPhotos = it.pendingPhotos.filterNot { p -> p.isSameAs(failed) }) + } + abandon(failed) + } + fun dismissSendError() { _uiState.update { it.copy(sendError = null) } } + /** + * Deletes the photos taken with the camera that were not sent: the one being taken, the attached + * one and the failed ones. Gallery photos are left alone. A failed photo can no longer be + * retried, so it is removed as by [discardPhoto], deleting its message too: it would otherwise + * stay pending for the other participant. The uploads under way keep running in [uploadScope] + * and, when they end, delete their photo, and their message too if they failed. + */ + override fun onCleared() { + cleared = true + photoBeingTaken?.let(photoStorage::delete) + val pending = _uiState.value.pendingPhotos + pending.filter { it.status == PendingPhotoStatus.FAILED }.forEach(::abandon) + val uploading = + pending.filter { it.status == PendingPhotoStatus.UPLOADING }.mapTo(HashSet()) { it.photo } + takenPhotos.filterNot { it in uploading }.forEach(::deleteIfTaken) + } + + /** + * Gives up on [photo], which failed: deletes its message, which may be on the server with its + * photo pending, and its file if it was taken with the camera. + */ + private fun abandon(photo: PendingPhoto) { + chatRepository.deletePhotoMessage(conversationId(listingId, renterUid), photo.messageId) + deleteIfTaken(photo.photo) + } + + private fun replaceAttachedPhoto(photo: Uri) { + val replaced = _uiState.value.attachedPhoto + _uiState.update { it.copy(attachedPhoto = photo).derived() } + if (replaced != null && replaced != photo) deleteIfTaken(replaced) + } + + /** + * Whether a photo picked or taken can be attached: when it can be, and also while the screen is + * loading, as when it was just recreated and the result arrives before the conversation. Then + * [ConversationUiState.canSend] waits for the conversation to allow it. + */ + private fun ConversationUiState.mayReceivePhoto(): Boolean = + canAttachPhoto || (isLoading && listingStatus != ConversationListingStatus.DELETED) + + private fun ConversationUiState.failedPhoto(messageId: String): PendingPhoto? = + pendingPhotos.find { + it.messageId == messageId && it.status == PendingPhotoStatus.FAILED + } + + private fun PendingPhoto.isSameAs(other: PendingPhoto) = messageId == other.messageId + + private fun PendingPhoto.failed(error: AppError) = + copy(status = PendingPhotoStatus.FAILED, error = error) + + /** + * This state with [photo] in place of the pending photo with its message ID, or added after the + * others when it was already removed, as after a late rejection. + */ + private fun ConversationUiState.withPendingPhoto(photo: PendingPhoto): ConversationUiState { + val photos = + if (pendingPhotos.any { it.isSameAs(photo) }) { + pendingPhotos.map { if (it.isSameAs(photo)) photo else it } + } else { + pendingPhotos + photo + } + return copy(pendingPhotos = photos) + } + + /** Deletes [photo] if it was taken with the camera; a gallery photo is left alone. */ + private fun deleteIfTaken(photo: Uri) { + if (takenPhotos.remove(photo)) photoStorage.delete(photo) + } + /** * The conversation the first message creates, or null when it cannot be created: the rules only * let the renter named in its ID create it. The repository sends the listing's current title in @@ -361,20 +629,28 @@ class ConversationViewModel( } /** - * This state with the fields that derive from the observed listing, the conversation and the - * draft recomputed. + * This state with the fields that derive from the observed listing, the conversation, the draft + * and the attached photo recomputed. */ private fun ConversationUiState.derived(): ConversationUiState { val (listing, status) = loaded + val listingOpen = status != null && status != ConversationListingStatus.DELETED + val canAttach = listingOpen && conversation != null val sendable = - ChatRules.isSendable(draft) && - status != null && - status != ConversationListingStatus.DELETED && - (conversation != null || - (status == ConversationListingStatus.ACTIVE && firstConversation(listing) != null)) + if (attachedPhoto != null) { + // A photo can be sent alone: a blank caption is no caption. + canAttach && (draft.isBlank() || ChatRules.isSendable(draft)) + } else { + ChatRules.isSendable(draft) && + listingOpen && + (conversation != null || + (status == ConversationListingStatus.ACTIVE && + firstConversation(listing) != null)) + } return copy( listingTitle = listing?.title ?: conversation?.listingTitle, listingStatus = status, + canAttachPhoto = canAttach, canSend = sendable, firstMessageBlockedByPause = status == ConversationListingStatus.PAUSED && @@ -383,4 +659,8 @@ class ConversationViewModel( conversationKnown, ) } + + private companion object { + const val PHOTO_BEING_TAKEN = "photoBeingTaken" + } } diff --git a/app/src/main/java/com/android/polybazaar/chat/viewmodel/PhotoUploadScope.kt b/app/src/main/java/com/android/polybazaar/chat/viewmodel/PhotoUploadScope.kt new file mode 100644 index 00000000..1ee54706 --- /dev/null +++ b/app/src/main/java/com/android/polybazaar/chat/viewmodel/PhotoUploadScope.kt @@ -0,0 +1,13 @@ +// Co-authored-by: Claude Code (Claude Opus 5.5) +package com.android.polybazaar.chat.viewmodel + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob + +/** + * Runs the photo uploads of [ConversationViewModel] for as long as the app's process lives, so that + * leaving a conversation does not cancel an upload after its message is written, which would leave + * the photo pending for both participants. On the main thread, like viewModelScope. + */ +val photoUploadScope: CoroutineScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate) diff --git a/app/src/main/java/com/android/polybazaar/listing/model/PhotoStorage.kt b/app/src/main/java/com/android/polybazaar/listing/model/PhotoStorage.kt index 155ce207..6ec81743 100644 --- a/app/src/main/java/com/android/polybazaar/listing/model/PhotoStorage.kt +++ b/app/src/main/java/com/android/polybazaar/listing/model/PhotoStorage.kt @@ -95,6 +95,9 @@ class FilePhotoStorage(context: Context, private val form: String) : PhotoStorag /** The folder of the form that edits a saved listing. */ const val EDIT_FORM = "edit" + /** The folder of the photos taken in a conversation, kept until they are sent. */ + const val CHAT_FORM = "chat" + /** * Both the name and the path of the files-path declared in res/xml/file_paths.xml. The * FileProvider shares its subfolders too, so each form's folder lives under it. diff --git a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt index a9b25926..ff23ea63 100644 --- a/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt +++ b/app/src/main/java/com/android/polybazaar/ui/navigation/AppNavHost.kt @@ -25,6 +25,7 @@ import androidx.compose.runtime.remember import androidx.compose.runtime.rememberCoroutineScope import androidx.compose.ui.Alignment import androidx.compose.ui.Modifier +import androidx.compose.ui.platform.LocalContext import androidx.compose.ui.platform.testTag import androidx.compose.ui.res.stringResource import androidx.compose.ui.text.font.FontWeight @@ -67,8 +68,10 @@ import com.android.polybazaar.chat.ui.ConversationScreen import com.android.polybazaar.chat.ui.InboxScreen import com.android.polybazaar.chat.viewmodel.ConversationViewModel import com.android.polybazaar.chat.viewmodel.InboxViewModel +import com.android.polybazaar.chat.viewmodel.photoUploadScope import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.ui.message +import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ListingRepository import com.android.polybazaar.listing.model.PhotoStorage import com.android.polybazaar.listing.ui.CreateListingScreen @@ -447,6 +450,9 @@ fun AppNavHost( // The route requires both, so they are always there. val listingId = entry.arguments!!.getString(Routes.LISTING_ID)!! val renterUid = entry.arguments!!.getString(Routes.RENTER_UID)!! + val appContext = LocalContext.current.applicationContext + val chatPhotoStorage = + remember(appContext) { FilePhotoStorage(appContext, FilePhotoStorage.CHAT_FORM) } // Scoped to this entry: each conversation opened gets its own ViewModel. val conversationViewModel: ConversationViewModel = viewModel( @@ -460,6 +466,9 @@ fun AppNavHost( chatRepository = chatRepository, profileRepository = profileRepository, listingRepository = listingRepository, + photoStorage = chatPhotoStorage, + savedStateHandle = createSavedStateHandle(), + uploadScope = photoUploadScope, ) } } diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xml index ac2de988..d62ee84e 100644 --- a/app/src/main/res/values/strings.xml +++ b/app/src/main/res/values/strings.xml @@ -92,6 +92,16 @@ Write a message… Conversation closed Send + Add a caption… + Add a photo + Take photo + Choose from gallery + Attached photo + Remove photo + Photo + Sending… + Not sent. %1$s + Remove %1$d/%2$d Message too long: at most %d character diff --git a/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt index a84845c0..6bbb1cb8 100644 --- a/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt +++ b/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt @@ -28,7 +28,8 @@ import kotlinx.coroutines.flow.map * * [sendPhoto] records every call in [sentPhotos], then waits for [gate] and throws [sendFailure] * like [sendMessage]; it has no later rejection, since a photo send waits for the server. - * [newMessageId] returns "m1", "m2", … in call order. + * [newMessageId] returns "m1", "m2", … in call order. [deletePhotoMessage] records every call in + * [deletedPhotoMessages] and removes the message from [messages]. * * [loadMessagePhoto] returns the bytes stored in [photos] for the path, and throws * [photoLoadFailure] if set, or when the path is not in [photos]. @@ -66,6 +67,9 @@ class FakeChatRepository( /** The calls to [sendPhoto], in order. */ val sentPhotos = mutableListOf() + /** The calls to [deletePhotoMessage], as (conversation id, message id), in order. */ + val deletedPhotoMessages = mutableListOf>() + /** The photos [loadMessagePhoto] returns, by Storage path. */ val photos = mutableMapOf() @@ -112,6 +116,13 @@ class FakeChatRepository( sendFailure?.let { throw it } } + override fun deletePhotoMessage(conversationId: String, messageId: String) { + deletedPhotoMessages += conversationId to messageId + val conversationMessages = messages.value[conversationId] ?: return + messages.value = + messages.value + (conversationId to conversationMessages.filterNot { it.id == messageId }) + } + override suspend fun loadMessagePhoto(imagePath: String): ByteArray { photoLoadFailure?.let { throw it } return photos[imagePath] ?: throw NoSuchElementException("No photo at $imagePath") diff --git a/app/src/test/java/com/android/polybazaar/chat/model/FirebaseChatRepositoryTest.kt b/app/src/test/java/com/android/polybazaar/chat/model/FirebaseChatRepositoryTest.kt index 593eb03f..bbe5a7ca 100644 --- a/app/src/test/java/com/android/polybazaar/chat/model/FirebaseChatRepositoryTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/model/FirebaseChatRepositoryTest.kt @@ -1049,6 +1049,40 @@ class FirebaseChatRepositoryTest { assertEquals(5_000L, testScheduler.currentTime) } + @Test + fun deletePhotoMessageDeletesTheMessageWithoutWaitingForTheServer() { + val pendingDelete = TaskCompletionSource() + whenever(photoMessageRef.delete()).thenReturn(pendingDelete.task) + var reportedFailure: Exception? = null + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } + + repository.deletePhotoMessage("listing_renter", PHOTO_ID) + + verify(photoMessageRef).delete() + assertFalse(pendingDelete.task.isComplete) + assertNull(reportedFailure) + } + + @Test + fun deletePhotoMessageLogsALaterRefusal() { + val pendingDelete = TaskCompletionSource() + whenever(photoMessageRef.delete()).thenReturn(pendingDelete.task) + var reportedFailure: Exception? = null + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } + + repository.deletePhotoMessage("listing_renter", PHOTO_ID) + val refused = + FirebaseFirestoreException( + "Missing or insufficient permissions", + FirebaseFirestoreException.Code.PERMISSION_DENIED, + ) + pendingDelete.setException(refused) + + assertSame(refused, reportedFailure) + } + @Test fun markReadSetsOnlyMyReadTimeToServerTime() { whenever(conversationRef.update(any(), any(), anyVararg())) diff --git a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt index e2a27c36..62dfbec5 100644 --- a/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/ui/ConversationScreenTest.kt @@ -1,11 +1,21 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.ui +import android.Manifest +import android.app.Application import android.content.Context +import android.net.Uri +import androidx.activity.compose.LocalActivityResultRegistryOwner +import androidx.activity.result.ActivityResultRegistry +import androidx.activity.result.ActivityResultRegistryOwner +import androidx.activity.result.contract.ActivityResultContract +import androidx.activity.result.contract.ActivityResultContracts import androidx.compose.runtime.CompositionLocalProvider import androidx.compose.runtime.getValue import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.setValue +import androidx.compose.ui.graphics.Color +import androidx.compose.ui.graphics.toPixelMap import androidx.compose.ui.semantics.LiveRegionMode import androidx.compose.ui.semantics.SemanticsProperties import androidx.compose.ui.test.SemanticsMatcher @@ -19,6 +29,7 @@ import androidx.compose.ui.test.assertIsNotDisplayed import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.assertTextEquals import androidx.compose.ui.test.assertWidthIsEqualTo +import androidx.compose.ui.test.captureToImage import androidx.compose.ui.test.getBoundsInRoot import androidx.compose.ui.test.hasAnyAncestor import androidx.compose.ui.test.hasTestTag @@ -31,9 +42,11 @@ import androidx.compose.ui.test.performTextInput import androidx.compose.ui.test.performTextReplacement import androidx.compose.ui.text.AnnotatedString import androidx.compose.ui.unit.dp +import androidx.core.app.ActivityOptionsCompat import androidx.lifecycle.Lifecycle import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.LifecycleRegistry +import androidx.lifecycle.SavedStateHandle import androidx.lifecycle.compose.LocalLifecycleOwner import androidx.test.core.app.ApplicationProvider import androidx.test.ext.junit.runners.AndroidJUnit4 @@ -46,21 +59,33 @@ import com.android.polybazaar.chat.model.FakeChatRepository import com.android.polybazaar.chat.viewmodel.ConversationListingStatus import com.android.polybazaar.chat.viewmodel.ConversationUiState import com.android.polybazaar.chat.viewmodel.ConversationViewModel +import com.android.polybazaar.chat.viewmodel.PendingPhoto +import com.android.polybazaar.chat.viewmodel.PendingPhotoStatus import com.android.polybazaar.error.model.AppError import com.android.polybazaar.listing.model.FakeListingRepository +import com.android.polybazaar.listing.model.FilePhotoStorage import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.ListingCategory +import com.android.polybazaar.listing.model.PhotoStorage +import com.android.polybazaar.listing.model.TakenPhoto +import com.android.polybazaar.listing.ui.CreateListingScreenTags import com.android.polybazaar.profile.model.FakeProfileRepository +import com.android.polybazaar.profile.ui.redPhoto +import java.io.File import java.net.UnknownHostException import java.time.Instant import java.time.ZoneOffset import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob import org.junit.Assert.assertEquals import org.junit.Assert.assertFalse import org.junit.Assert.assertTrue import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith +import org.robolectric.Shadows.shadowOf import org.robolectric.annotation.Config import org.robolectric.annotation.GraphicsMode @@ -106,6 +131,11 @@ class ConversationScreenTest { onSend: () -> Unit = {}, onRetry: () -> Unit = {}, onDismissSendError: () -> Unit = {}, + onTakePhoto: () -> Unit = {}, + onChoosePhoto: () -> Unit = {}, + onRemoveAttachedPhoto: () -> Unit = {}, + onRetryPhoto: (String) -> Unit = {}, + onDiscardPhoto: (String) -> Unit = {}, ) { composeTestRule.setContent { ConversationContent( @@ -115,6 +145,11 @@ class ConversationScreenTest { onSend = onSend, onRetry = onRetry, onDismissSendError = onDismissSendError, + onTakePhoto = onTakePhoto, + onChoosePhoto = onChoosePhoto, + onRemoveAttachedPhoto = onRemoveAttachedPhoto, + onRetryPhoto = onRetryPhoto, + onDiscardPhoto = onDiscardPhoto, zone = ZoneOffset.UTC, ) } @@ -187,6 +222,8 @@ class ConversationScreenTest { chat: FakeChatRepository, listings: FakeListingRepository = FakeListingRepository(allListings = listOf(drill)), lifecycleOwner: LifecycleOwner? = null, + photoStorage: PhotoStorage = NoPhotoStorage, + launchers: FakeLaunchers = FakeLaunchers(), ): ConversationViewModel { val viewModel = ConversationViewModel( @@ -196,10 +233,19 @@ class ConversationScreenTest { chatRepository = chat, profileRepository = FakeProfileRepository(mapOf(james.uid to james)), listingRepository = listings, + photoStorage = photoStorage, + savedStateHandle = SavedStateHandle(), + uploadScope = CoroutineScope(SupervisorJob() + Dispatchers.Main.immediate), ) + val launcherOwner = + object : ActivityResultRegistryOwner { + override val activityResultRegistry = launchers + } composeTestRule.setContent { CompositionLocalProvider( - LocalLifecycleOwner provides (lifecycleOwner ?: LocalLifecycleOwner.current) + LocalLifecycleOwner provides (lifecycleOwner ?: LocalLifecycleOwner.current), + // rememberLauncherForActivityResult reads its registry from this composition local. + LocalActivityResultRegistryOwner provides launcherOwner, ) { ConversationScreen(viewModel = viewModel, onBack = {}) } @@ -207,6 +253,26 @@ class ConversationScreenTest { return viewModel } + /** + * Stands in for the gallery, the camera app and the permission request: answers each launch at + * once with the next of [results] (a picked URI or null, or a Boolean for the camera and the + * permission), and records each contract launched in [launched]. + */ + private class FakeLaunchers : ActivityResultRegistry() { + val results = ArrayDeque() + val launched = mutableListOf>() + + override fun onLaunch( + requestCode: Int, + contract: ActivityResultContract, + input: I, + options: ActivityOptionsCompat?, + ) { + launched += contract + dispatchResult(requestCode, results.removeFirst()) + } + } + /** A lifecycle a test moves by hand, to put the screen in the background and back. */ private class ManualLifecycleOwner : LifecycleOwner { val registry = @@ -830,4 +896,260 @@ class ConversationScreenTest { node(ConversationScreenTags.SEND_ERROR).assertDoesNotExist() node(ConversationScreenTags.MESSAGE_FIELD).assert(hasDraft("Is it free on Saturday?!")) } + + // Photo button and attached photo + + // A photo that cannot be read, which shows the placeholder: Robolectric throws for an unknown + // content:// URI, where a device answers FileNotFoundException. + private val galleryPhoto = Uri.parse("file:///missing/photo_1.jpg") + + /** The loaded conversation, where a photo can be attached. */ + private val canAttach = loaded.copy(canAttachPhoto = true) + + @Test + fun photoButton_isEnabledWhenAPhotoCanBeAttached_andSaysWhatItDoes() { + setContent(canAttach) + + node(ConversationScreenTags.PHOTO_BUTTON) + .assertIsEnabled() + .assertContentDescriptionEquals(string(R.string.conversation_photo_button)) + } + + @Test + fun photoButton_isDisabledWhenNoPhotoCanBeAttached() { + setContent(loaded.copy(canAttachPhoto = false)) + + node(ConversationScreenTags.PHOTO_BUTTON).assertIsNotEnabled() + } + + @Test + fun photoMenu_takePhoto_opensTheCamera_andClosesTheMenu() { + var takes = 0 + var chooses = 0 + setContent(canAttach, onTakePhoto = { takes++ }, onChoosePhoto = { chooses++ }) + node(ConversationScreenTags.TAKE_PHOTO).assertDoesNotExist() + + node(ConversationScreenTags.PHOTO_BUTTON).performClick() + node(ConversationScreenTags.TAKE_PHOTO) + .assertTextEquals(string(R.string.conversation_take_photo)) + .performClick() + + assertEquals(1, takes) + assertEquals(0, chooses) + node(ConversationScreenTags.PHOTO_MENU).assertDoesNotExist() + } + + @Test + fun photoMenu_choosePhoto_opensTheGallery_andClosesTheMenu() { + var takes = 0 + var chooses = 0 + setContent(canAttach, onTakePhoto = { takes++ }, onChoosePhoto = { chooses++ }) + + node(ConversationScreenTags.PHOTO_BUTTON).performClick() + node(ConversationScreenTags.CHOOSE_PHOTO) + .assertTextEquals(string(R.string.conversation_choose_photo)) + .performClick() + + assertEquals(0, takes) + assertEquals(1, chooses) + node(ConversationScreenTags.PHOTO_MENU).assertDoesNotExist() + } + + @Test + fun noAttachedPhoto_showsNoPreview_andTheMessagePlaceholder() { + setContent(canAttach) + + node(ConversationScreenTags.ATTACHED_PHOTO).assertDoesNotExist() + node(ConversationScreenTags.REMOVE_ATTACHED_PHOTO).assertDoesNotExist() + text(string(R.string.conversation_placeholder)).assertIsDisplayed() + } + + @Test + fun attachedPhoto_showsAboveTheField_andAsksForACaption() { + setContent(canAttach.copy(attachedPhoto = galleryPhoto)) + + node(ConversationScreenTags.ATTACHED_PHOTO) + .assertIsDisplayed() + .assertContentDescriptionEquals(string(R.string.conversation_attached_photo)) + text(string(R.string.conversation_placeholder_caption)).assertIsDisplayed() + text(string(R.string.conversation_placeholder)).assertDoesNotExist() + val photo = node(ConversationScreenTags.ATTACHED_PHOTO).getBoundsInRoot() + val field = node(ConversationScreenTags.MESSAGE_FIELD).getBoundsInRoot() + assertTrue(photo.bottom <= field.top) + } + + @Test + fun removeAttachedPhoto_callsTheCallback() { + var removals = 0 + setContent( + canAttach.copy(attachedPhoto = galleryPhoto), + onRemoveAttachedPhoto = { removals++ }, + ) + + node(ConversationScreenTags.REMOVE_ATTACHED_PHOTO) + .assertContentDescriptionEquals(string(R.string.conversation_remove_attached_photo)) + .performClick() + + assertEquals(1, removals) + } + + @Test + fun attachedPhotoWithoutACaption_canBeSent() { + var sends = 0 + setContent(canAttach.copy(attachedPhoto = galleryPhoto, canSend = true), onSend = { sends++ }) + + node(ConversationScreenTags.MESSAGE_FIELD).assert(hasDraft("")) + node(ConversationScreenTags.SEND_BUTTON).assertIsEnabled().performClick() + + assertEquals(1, sends) + } + + // Photos being sent + + private val photoTime = Instant.parse("2026-11-11T09:16:00Z") + + /** A photo message [id] from [senderUid], with [caption] as its text ("" for none). */ + private fun photoMessage(id: String, senderUid: String, caption: String = "") = + ChatMessage(id, senderUid, caption, photoTime, imagePath = "conversations/drill_renter/$id") + + private fun pending(status: PendingPhotoStatus, error: AppError? = null) = + PendingPhoto("m5", galleryPhoto, "And the shelf", status, error) + + @Test + fun pendingPhoto_whoseMessageArrived_showsOnce() { + setContent( + loaded.copy( + messages = loaded.messages + photoMessage("m5", "renter", caption = "And the shelf"), + pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING)), + ) + ) + + node(ConversationScreenTags.pendingPhoto("m5")).assertIsDisplayed() + node(ConversationScreenTags.myMessage("m5")).assertDoesNotExist() + } + + @Test + fun uploadingPhoto_saysSending_withoutRetryOrRemove() { + setContent(loaded.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING)))) + + node(ConversationScreenTags.pendingPhoto("m5")) + .assertContentDescriptionEquals(string(R.string.conversation_photo)) + .assertTextEquals("And the shelf", string(R.string.conversation_photo_sending)) + node(ConversationScreenTags.retryPhoto("m5")).assertDoesNotExist() + node(ConversationScreenTags.discardPhoto("m5")).assertDoesNotExist() + } + + @Test + fun failedPhoto_saysWhy_andOffersRetryAndRemove() { + val retried = mutableListOf() + val discarded = mutableListOf() + setContent( + loaded.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.FAILED, AppError.NETWORK))), + onRetryPhoto = { retried += it }, + onDiscardPhoto = { discarded += it }, + ) + + text(string(R.string.conversation_photo_not_sent, string(R.string.error_network))) + .assertIsDisplayed() + .assert(isPoliteLiveRegion()) + text(string(R.string.conversation_photo_sending)).assertDoesNotExist() + node(ConversationScreenTags.retryPhoto("m5")).performClick() + node(ConversationScreenTags.discardPhoto("m5")).performClick() + + assertEquals(listOf("m5"), retried) + assertEquals(listOf("m5"), discarded) + } + + @Test + fun pendingPhotos_showBelowTheMessages_asMyOwnBubbles() { + setContent(loaded.copy(pendingPhotos = listOf(pending(PendingPhotoStatus.UPLOADING)))) + + val pending = node(ConversationScreenTags.pendingPhoto("m5")).getBoundsInRoot() + val answer = node(ConversationScreenTags.theirMessage("m2")).getBoundsInRoot() + val mine = node(ConversationScreenTags.myMessage("m1")).getBoundsInRoot() + assertTrue(answer.bottom <= pending.top) + assertEquals(mine.right.value, pending.right.value, 0.5f) + } + + // The screen wires the photo menu to the gallery, the camera and the ViewModel. + + /** A chat whose conversation exists, so a photo can be attached. */ + private fun existingConversation() = FakeChatRepository(listOf(conversation)) + + private fun openPhotoMenuAndPick(tag: String) { + node(ConversationScreenTags.PHOTO_BUTTON).assertIsEnabled().performClick() + node(tag).performClick() + } + + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) // Real decoding and drawing of the thumbnail. + fun screen_choosingFromTheGallery_attachesThePickedPhoto_andShowsIt() { + val picked = File(context.cacheDir, "picked.png").apply { writeBytes(redPhoto()) } + val launchers = FakeLaunchers().apply { results.add(Uri.fromFile(picked)) } + val viewModel = showScreen(existingConversation(), launchers = launchers) + + openPhotoMenuAndPick(ConversationScreenTags.CHOOSE_PHOTO) + + assertTrue(launchers.launched.single() is ActivityResultContracts.PickVisualMedia) + assertEquals(Uri.fromFile(picked), viewModel.uiState.value.attachedPhoto) + composeTestRule.waitUntil(5_000) { + val image = + composeTestRule + .onNodeWithTag(ConversationScreenTags.ATTACHED_PHOTO, useUnmergedTree = true) + .captureToImage() + image.toPixelMap()[image.width / 2, image.height / 2] == Color.Red + } + } + + @Test + fun screen_closingTheGalleryWithoutAPhoto_attachesNothing() { + val launchers = FakeLaunchers().apply { results.add(null) } + val viewModel = showScreen(existingConversation(), launchers = launchers) + + openPhotoMenuAndPick(ConversationScreenTags.CHOOSE_PHOTO) + + assertEquals(null, viewModel.uiState.value.attachedPhoto) + node(ConversationScreenTags.ATTACHED_PHOTO).assertDoesNotExist() + } + + // The camera app leaves its file empty; native graphics fail to decode it cleanly. + @Test + @GraphicsMode(GraphicsMode.Mode.NATIVE) + fun screen_takingAPhoto_withPermission_attachesTheTakenFile() { + shadowOf(context as Application).grantPermissions(Manifest.permission.CAMERA) + val launchers = FakeLaunchers().apply { results.add(true) } // The camera app saved it. + val storage = FilePhotoStorage(context, FilePhotoStorage.CHAT_FORM) + val viewModel = + showScreen(existingConversation(), photoStorage = storage, launchers = launchers) + + openPhotoMenuAndPick(ConversationScreenTags.TAKE_PHOTO) + + assertTrue(launchers.launched.single() is ActivityResultContracts.TakePicture) + val attached = viewModel.uiState.value.attachedPhoto + assertTrue(attached != null && File(attached.path!!).exists()) + node(ConversationScreenTags.ATTACHED_PHOTO).assertIsDisplayed() + } + + @Test + fun screen_refusingTheCamera_explainsWhy_andCancelClosesIt() { + val launchers = FakeLaunchers().apply { results.add(false) } // The user refuses. + val viewModel = showScreen(existingConversation(), launchers = launchers) + + openPhotoMenuAndPick(ConversationScreenTags.TAKE_PHOTO) + + assertTrue(launchers.launched.single() is ActivityResultContracts.RequestPermission) + node(CreateListingScreenTags.CAMERA_PERMISSION_DIALOG).assertIsDisplayed() + node(CreateListingScreenTags.CAMERA_PERMISSION_CANCEL).performClick() + node(CreateListingScreenTags.CAMERA_PERMISSION_DIALOG).assertDoesNotExist() + assertEquals(null, viewModel.uiState.value.attachedPhoto) + } + + /** No test of the screen takes a photo yet. */ + private object NoPhotoStorage : PhotoStorage { + override fun newPhoto(): TakenPhoto? = null + + override fun delete(photo: Uri) = Unit + + override fun deleteAllExcept(keep: List) = Unit + } } diff --git a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt index bb884ba0..cb21bac2 100644 --- a/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt +++ b/app/src/test/java/com/android/polybazaar/chat/viewmodel/ConversationViewModelTest.kt @@ -1,22 +1,34 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.viewmodel +import android.net.Uri +import androidx.lifecycle.SavedStateHandle +import androidx.lifecycle.ViewModelProvider +import androidx.lifecycle.ViewModelStore +import androidx.lifecycle.viewmodel.initializer +import androidx.lifecycle.viewmodel.viewModelFactory +import androidx.test.ext.junit.runners.AndroidJUnit4 import com.android.polybazaar.auth.model.User import com.android.polybazaar.chat.model.ChatMessage import com.android.polybazaar.chat.model.ChatRules import com.android.polybazaar.chat.model.Conversation import com.android.polybazaar.chat.model.FakeChatRepository import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.error.model.AppException import com.android.polybazaar.listing.model.FakeListingRepository import com.android.polybazaar.listing.model.ItemListing import com.android.polybazaar.listing.model.ListingCategory +import com.android.polybazaar.listing.model.PhotoStorage +import com.android.polybazaar.listing.model.TakenPhoto import com.android.polybazaar.profile.model.FakeProfileRepository import com.google.firebase.firestore.FirebaseFirestoreException import java.net.UnknownHostException import java.time.Instant import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.ExperimentalCoroutinesApi +import kotlinx.coroutines.SupervisorJob import kotlinx.coroutines.test.StandardTestDispatcher import kotlinx.coroutines.test.resetMain import kotlinx.coroutines.test.setMain @@ -28,14 +40,19 @@ import org.junit.Assert.assertNull import org.junit.Assert.assertTrue import org.junit.Before import org.junit.Test +import org.junit.runner.RunWith @OptIn(ExperimentalCoroutinesApi::class) +@RunWith(AndroidJUnit4::class) class ConversationViewModelTest { private val testDispatcher = StandardTestDispatcher() + // Outlives the ViewModels, like photoUploadScope. + private val uploadScope = CoroutineScope(SupervisorJob() + testDispatcher) private lateinit var chat: FakeChatRepository private lateinit var profiles: FakeProfileRepository private lateinit var listings: FakeListingRepository + private lateinit var photoStorage: FakePhotoStorage private val lender = User(uid = "lender", email = "", username = "Lena") private val renter = User(uid = "renter", email = "", username = "Remi") @@ -69,6 +86,7 @@ class ConversationViewModelTest { chat = FakeChatRepository() profiles = FakeProfileRepository(listOf(lender, renter).associateBy { it.uid }) listings = FakeListingRepository(allListings = listOf(listing)) + photoStorage = FakePhotoStorage() } @After @@ -78,9 +96,25 @@ class ConversationViewModelTest { private fun advance() = testDispatcher.scheduler.advanceUntilIdle() - /** Creates the ViewModel for the drill conversation, seen by [myUid], without running it. */ - private fun viewModel(myUid: String = renter.uid) = - ConversationViewModel(listing.listingId!!, renter.uid, myUid, chat, profiles, listings) + /** + * Creates the ViewModel for the drill conversation, seen by [myUid], without running it. + * [savedState] is what Android restores after it killed the app. + */ + private fun viewModel( + myUid: String = renter.uid, + savedState: SavedStateHandle = SavedStateHandle(), + ) = + ConversationViewModel( + listing.listingId!!, + renter.uid, + myUid, + chat, + profiles, + listings, + photoStorage, + savedState, + uploadScope, + ) /** Creates the ViewModel and lets its loads finish. */ private fun loadedViewModel(myUid: String = renter.uid) = viewModel(myUid).also { advance() } @@ -966,4 +1000,782 @@ class ConversationViewModelTest { assertEquals(listOf(unreadReply.id), chat.markedRead) } + + // Photos + + private val galleryPhoto = Uri.parse("content://media/picker/1") + private val otherGalleryPhoto = Uri.parse("content://media/picker/2") + + /** Creates the ViewModel on the existing drill conversation and lets it load. */ + private fun inConversation(myUid: String = renter.uid): ConversationViewModel { + givenConversation() + return loadedViewModel(myUid) + } + + /** Takes a photo with the camera and attaches it; returns its file. */ + private fun ConversationViewModel.takePhoto(): Uri { + assertNotNull(startTakingPhoto()) + finishTakingPhoto(saved = true) + return photoStorage.taken.last().uri + } + + /** Closes the screen: clears the ViewModel the way its ViewModelStore does. */ + private fun ConversationViewModel.close() { + val store = ViewModelStore() + val factory = viewModelFactory { initializer { this@close } } + ViewModelProvider.create(store, factory)[ConversationViewModel::class] + store.clear() + } + + @Test + fun attachPhoto_fromTheGallery_attachesIt_andItCanBeSentWithoutACaption() { + val viewModel = inConversation() + assertTrue(viewModel.uiState.value.canAttachPhoto) + + viewModel.attachPhoto(galleryPhoto) + + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + assertTrue(viewModel.uiState.value.canSend) + } + + @Test + fun send_aPhotoWhileATextSendIsInFlight_doesNothing_soTheTextIsNotSentAgainAsItsCaption() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.onDraftChange("Hello") + viewModel.send() + advance() + + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + assertEquals(emptyList(), chat.sentPhotos) + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + + chat.gate!!.complete(Unit) + advance() + viewModel.send() + advance() + assertEquals( + listOf(FakeChatRepository.SentPhoto(conversation, "m1", galleryPhoto, null)), + chat.sentPhotos, + ) + assertEquals(listOf(conversation to "Hello"), chat.sentMessages) + } + + @Test + fun attachPhoto_beforeTheConversationExists_isIgnored() { + val viewModel = loadedViewModel() + + viewModel.attachPhoto(galleryPhoto) + + assertFalse(viewModel.uiState.value.canAttachPhoto) + assertNull(viewModel.uiState.value.attachedPhoto) + assertFalse(viewModel.uiState.value.canSend) + } + + @Test + fun attachPhoto_toADeletedListing_isIgnored() { + listings.allListings = emptyList() + val viewModel = inConversation() + + viewModel.attachPhoto(galleryPhoto) + + assertFalse(viewModel.uiState.value.canAttachPhoto) + assertNull(viewModel.uiState.value.attachedPhoto) + } + + @Test + fun attachPhoto_whileTheScreenLoads_attachesIt_andItCanBeSentOnceTheConversationIsKnown() { + listings.gate = CompletableDeferred() + val viewModel = inConversation() + assertTrue(viewModel.uiState.value.isLoading) + + viewModel.attachPhoto(galleryPhoto) + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + assertFalse(viewModel.uiState.value.canSend) + + listings.gate!!.complete(Unit) + advance() + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + assertTrue(viewModel.uiState.value.canSend) + } + + @Test + fun attachPhoto_whileTheScreenLoads_staysUnsendableWhenTheConversationTurnsOutMissing() { + chat.conversationGate = CompletableDeferred() + val viewModel = loadedViewModel() + assertTrue(viewModel.uiState.value.isLoading) + + viewModel.attachPhoto(galleryPhoto) + chat.conversationGate!!.complete(Unit) + advance() + + assertFalse(viewModel.uiState.value.isLoading) + assertFalse(viewModel.uiState.value.canAttachPhoto) + assertFalse(viewModel.uiState.value.canSend) + // Still shown, so the user can remove it. + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + } + + @Test + fun attachPhoto_whileTheScreenLoads_toADeletedListing_isIgnored() { + listings.allListings = emptyList() + chat.conversationGate = CompletableDeferred() + val viewModel = loadedViewModel() + assertTrue(viewModel.uiState.value.isLoading) + assertEquals(ConversationListingStatus.DELETED, viewModel.uiState.value.listingStatus) + + viewModel.attachPhoto(galleryPhoto) + + assertNull(viewModel.uiState.value.attachedPhoto) + } + + @Test + fun takePhoto_saved_attachesTheTakenFile() { + val viewModel = inConversation() + + val cameraUri = viewModel.startTakingPhoto() + viewModel.finishTakingPhoto(saved = true) + + val taken = photoStorage.taken.single() + assertEquals(taken.cameraUri, cameraUri) + assertEquals(taken.uri, viewModel.uiState.value.attachedPhoto) + assertEquals(emptyList(), photoStorage.deleted) + } + + /** The state Android saves for this ViewModel, as restored into a new process. */ + private fun SavedStateHandle.restored() = SavedStateHandle(keys().associateWith { get(it) }) + + @Test + fun takePhoto_afterAndroidKilledTheApp_attachesItToTheNewViewModel() { + val savedState = SavedStateHandle() + givenConversation() + viewModel(savedState = savedState).also { advance() }.startTakingPhoto() + val taken = photoStorage.taken.single().uri + + // The camera result reaches the new process before the conversation has loaded again. + val restarted = viewModel(savedState = savedState.restored()) + restarted.finishTakingPhoto(saved = true) + advance() + + assertEquals(taken, restarted.uiState.value.attachedPhoto) + assertTrue(restarted.uiState.value.canSend) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun takePhoto_cancelledAfterAndroidKilledTheApp_deletesTheFile() { + val savedState = SavedStateHandle() + givenConversation() + viewModel(savedState = savedState).also { advance() }.startTakingPhoto() + val taken = photoStorage.taken.single().uri + + val restarted = viewModel(savedState = savedState.restored()) + restarted.finishTakingPhoto(saved = false) + advance() + + assertNull(restarted.uiState.value.attachedPhoto) + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun takePhoto_cancelled_deletesTheFile_andAttachesNothing() { + val viewModel = inConversation() + + viewModel.startTakingPhoto() + viewModel.finishTakingPhoto(saved = false) + + assertNull(viewModel.uiState.value.attachedPhoto) + assertEquals(listOf(photoStorage.taken.single().uri), photoStorage.deleted) + } + + @Test + fun startTakingPhoto_againBeforeTheCameraCloses_deletesTheFirstFile() { + val viewModel = inConversation() + + viewModel.startTakingPhoto() + viewModel.startTakingPhoto() + viewModel.finishTakingPhoto(saved = true) + + val (first, second) = photoStorage.taken + assertEquals(listOf(first.uri), photoStorage.deleted) + assertEquals(second.uri, viewModel.uiState.value.attachedPhoto) + } + + @Test + fun startTakingPhoto_beforeTheConversationExists_returnsNullAndCreatesNoFile() { + val viewModel = loadedViewModel() + + assertNull(viewModel.startTakingPhoto()) + assertEquals(emptyList(), photoStorage.taken) + } + + @Test + fun startTakingPhoto_whenTheFileCannotBeCreated_returnsNull() { + photoStorage.full = true + val viewModel = inConversation() + + assertNull(viewModel.startTakingPhoto()) + viewModel.finishTakingPhoto(saved = true) + + assertNull(viewModel.uiState.value.attachedPhoto) + } + + @Test + fun finishTakingPhoto_withoutAPhotoBeingTaken_doesNothing() { + val viewModel = inConversation() + + viewModel.finishTakingPhoto(saved = true) + + assertNull(viewModel.uiState.value.attachedPhoto) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun finishTakingPhoto_onceAPhotoCanNoLongerBeAttached_deletesIt() { + val viewModel = inConversation() + viewModel.startTakingPhoto() + + chat.myConversations.value = Result.success(emptyList()) + advance() + viewModel.finishTakingPhoto(saved = true) + + assertNull(viewModel.uiState.value.attachedPhoto) + assertEquals(listOf(photoStorage.taken.single().uri), photoStorage.deleted) + } + + @Test + fun attachingAnotherPhoto_replacesATakenOne_andDeletesIt() { + val viewModel = inConversation() + val taken = viewModel.takePhoto() + + viewModel.attachPhoto(galleryPhoto) + + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun attachingAnotherPhoto_replacesAGalleryOne_withoutDeletingIt() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.attachPhoto(otherGalleryPhoto) + + assertEquals(otherGalleryPhoto, viewModel.uiState.value.attachedPhoto) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun attachingTheSamePhotoAgain_keepsIt() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.attachPhoto(galleryPhoto) + + assertEquals(galleryPhoto, viewModel.uiState.value.attachedPhoto) + } + + @Test + fun removeAttachedPhoto_deletesATakenPhoto() { + val viewModel = inConversation() + val taken = viewModel.takePhoto() + + viewModel.removeAttachedPhoto() + + assertNull(viewModel.uiState.value.attachedPhoto) + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun removeAttachedPhoto_keepsAGalleryPhoto() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.removeAttachedPhoto() + + assertNull(viewModel.uiState.value.attachedPhoto) + assertFalse(viewModel.uiState.value.canSend) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun canSend_withAPhoto_acceptsNoCaptionOrAValidOne_butNotATooLongOne() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + fun canSend(caption: String): Boolean { + viewModel.onDraftChange(caption) + return viewModel.uiState.value.canSend + } + + assertTrue(canSend("")) + assertTrue(canSend(" ")) + assertTrue(canSend("Here it is")) + assertTrue(canSend("a".repeat(ChatRules.MAX_MESSAGE_LENGTH))) + assertFalse(canSend("a".repeat(ChatRules.MAX_MESSAGE_LENGTH + 1))) + } + + @Test + fun closing_whileTheCameraIsOpen_deletesThePhotoBeingTaken() { + val viewModel = inConversation() + viewModel.startTakingPhoto() + + viewModel.close() + + assertEquals(listOf(photoStorage.taken.single().uri), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) + } + + @Test + fun closing_deletesTheAttachedTakenPhoto() { + val viewModel = inConversation() + val taken = viewModel.takePhoto() + + viewModel.close() + + assertEquals(listOf(taken), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) + } + + @Test + fun closing_keepsAnAttachedGalleryPhoto() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.close() + + assertEquals(emptyList(), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) + } + + @Test + fun sendPhoto_sendsTheConversationAFreshIdThePhotoAndTheTrimmedCaption() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + viewModel.onDraftChange(" Here it is ") + + viewModel.send() + advance() + + assertEquals( + listOf(FakeChatRepository.SentPhoto(conversation, "m1", galleryPhoto, "Here it is")), + chat.sentPhotos, + ) + assertEquals(emptyList>(), chat.sentMessages) + } + + @Test + fun sendPhoto_withABlankCaption_sendsNoCaption() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + viewModel.onDraftChange(" ") + + viewModel.send() + advance() + + assertNull(chat.sentPhotos.single().caption) + } + + @Test + fun sendPhoto_clearsTheAttachmentAndTheDraftAtOnce() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + viewModel.onDraftChange("Here it is") + + viewModel.send() + + val state = viewModel.uiState.value + assertNull(state.attachedPhoto) + assertEquals("", state.draft) + assertFalse(state.canSend) + assertEquals( + listOf(PendingPhoto("m1", galleryPhoto, "Here it is", PendingPhotoStatus.UPLOADING)), + state.pendingPhotos, + ) + } + + @Test + fun sendPhoto_staysUploadingUntilTheSendReturns_thenIsRemoved() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + assertEquals( + listOf(PendingPhotoStatus.UPLOADING), + viewModel.uiState.value.pendingPhotos.map { it.status }, + ) + + chat.gate!!.complete(Unit) + advance() + + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + } + + @Test + fun sendPhoto_hidesItsMessageUntilSent_soThePhotoShowsOnce() { + val viewModel = inConversation() + val sent = ChatMessage("m1", renter.uid, "", Instant.ofEpochSecond(300), imagePath = "chats/m1") + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + + // The message reaches the conversation before its photo is uploaded. + chat.messages.value = mapOf(conversation.id to listOf(sent)) + advance() + assertEquals(listOf(sent), viewModel.uiState.value.messages) + assertEquals(emptyList(), viewModel.uiState.value.shownMessages) + + chat.gate!!.complete(Unit) + advance() + assertEquals(listOf(sent), viewModel.uiState.value.shownMessages) + } + + @Test + fun sendPhoto_tappedTwice_sendsOnce() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.send() + viewModel.send() + advance() + + assertEquals(1, chat.sentPhotos.size) + } + + @Test + fun sendPhoto_whileAnotherUploads_sendsBothWithTheirOwnIds() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + viewModel.attachPhoto(otherGalleryPhoto) + viewModel.send() + advance() + + assertEquals(listOf("m1", "m2"), chat.sentPhotos.map { it.messageId }) + assertEquals( + listOf(galleryPhoto, otherGalleryPhoto), + viewModel.uiState.value.pendingPhotos.map { it.photo }, + ) + } + + @Test + fun sentTakenPhoto_isDeletedOnceSent() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + val taken = viewModel.takePhoto() + viewModel.send() + advance() + assertEquals(emptyList(), photoStorage.deleted) + + chat.gate!!.complete(Unit) + advance() + + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun sentGalleryPhoto_isNotDeleted() { + val viewModel = inConversation() + viewModel.attachPhoto(galleryPhoto) + + viewModel.send() + advance() + + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun send_withoutAPhoto_stillSendsTheText() { + val viewModel = inConversation() + viewModel.onDraftChange("Hello") + + viewModel.send() + advance() + + assertEquals(listOf(conversation to "Hello"), chat.sentMessages) + assertEquals(emptyList(), chat.sentPhotos) + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + } + + @Test + fun closing_whileAPhotoUploads_letsItFinish_thenDeletesItsPhoto() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + val sending = viewModel.takePhoto() + viewModel.send() + advance() + val attached = viewModel.takePhoto() + + viewModel.close() + // The attached photo is deleted at once; the one uploading is still being read. + assertEquals(listOf(attached), photoStorage.deleted) + + chat.gate!!.complete(Unit) + advance() + assertEquals(1, chat.sentPhotos.size) + assertEquals(listOf(attached, sending), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) + } + + @Test + fun closing_whileAPhotoUploads_deletesItsPhotoAndItsMessageWhenItFails() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + val sending = viewModel.takePhoto() + viewModel.send() + advance() + + viewModel.close() + assertEquals(emptyList(), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) + + chat.sendFailure = offline + chat.gate!!.complete(Unit) + advance() + assertEquals(listOf(sending), photoStorage.deleted) + // No one can retry it any more, so it must not stay pending for the other participant. + assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) + } + + @Test + fun closing_whileAGalleryPhotoUploads_neverDeletesIt() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + + viewModel.close() + chat.gate!!.complete(Unit) + advance() + + assertEquals(1, chat.sentPhotos.size) + assertEquals(emptyList(), photoStorage.deleted) + assertEquals(emptyList>(), chat.deletedPhotoMessages) + } + + private val offline = AppException(AppError.NETWORK) + private val refused = firestoreError(FirebaseFirestoreException.Code.PERMISSION_DENIED) + + /** Attaches the gallery photo and sends it, failing with [failure]; returns the ViewModel. */ + private fun failedPhotoSend(failure: Exception): ConversationViewModel { + val viewModel = inConversation() + chat.sendFailure = failure + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + return viewModel + } + + @Test + fun sendPhoto_offline_failsWithNetwork() { + val viewModel = failedPhotoSend(offline) + + assertEquals( + listOf(PendingPhoto("m1", galleryPhoto, null, PendingPhotoStatus.FAILED, AppError.NETWORK)), + viewModel.uiState.value.pendingPhotos, + ) + assertNull(viewModel.uiState.value.sendError) + } + + @Test + fun sendPhoto_refused_failsWithPermissionDenied() { + val viewModel = failedPhotoSend(refused) + + val pending = viewModel.uiState.value.pendingPhotos.single() + assertEquals(PendingPhotoStatus.FAILED, pending.status) + assertEquals(AppError.PERMISSION_DENIED, pending.error) + } + + @Test + fun sendPhoto_toADeletedListing_failsAndTheDeletionStopsAttachingPhotos() { + val viewModel = inConversation() + listings.allListings = emptyList() + chat.sendFailure = firestoreError(FirebaseFirestoreException.Code.NOT_FOUND) + viewModel.attachPhoto(galleryPhoto) + + viewModel.send() + advance() + + val state = viewModel.uiState.value + assertEquals(AppError.NOT_FOUND, state.pendingPhotos.single().error) + assertEquals(ConversationListingStatus.DELETED, state.listingStatus) + assertFalse(state.canAttachPhoto) + } + + @Test + fun retryPhoto_sendsAgainWithTheSameMessageId_andRemovesItOnceSent() { + val viewModel = failedPhotoSend(offline) + chat.sendFailure = null + chat.gate = CompletableDeferred() + + viewModel.retryPhoto("m1") + advance() + val retried = viewModel.uiState.value.pendingPhotos.single() + assertEquals(PendingPhotoStatus.UPLOADING, retried.status) + assertNull(retried.error) + + chat.gate!!.complete(Unit) + advance() + assertEquals(listOf("m1", "m1"), chat.sentPhotos.map { it.messageId }) + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + } + + @Test + fun retryPhoto_failingAgain_isFailedAgainWithTheNewError() { + val viewModel = failedPhotoSend(offline) + chat.sendFailure = refused + + viewModel.retryPhoto("m1") + advance() + + val pending = viewModel.uiState.value.pendingPhotos.single() + assertEquals(PendingPhotoStatus.FAILED, pending.status) + assertEquals(AppError.PERMISSION_DENIED, pending.error) + } + + @Test + fun retryPhoto_whileItUploads_doesNotSendItTwice() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + + viewModel.retryPhoto("m1") + advance() + + assertEquals(1, chat.sentPhotos.size) + } + + @Test + fun retryPhoto_ofAnUnknownId_doesNothing() { + val viewModel = failedPhotoSend(offline) + + viewModel.retryPhoto("m9") + advance() + + assertEquals(1, chat.sentPhotos.size) + assertEquals(PendingPhotoStatus.FAILED, viewModel.uiState.value.pendingPhotos.single().status) + } + + @Test + fun discardPhoto_removesAFailedTakenPhoto_andDeletesItsFile() { + val viewModel = inConversation() + chat.sendFailure = offline + val taken = viewModel.takePhoto() + viewModel.send() + advance() + + viewModel.discardPhoto("m1") + + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + assertEquals(listOf(taken), photoStorage.deleted) + } + + @Test + fun discardPhoto_removesAFailedGalleryPhoto_withoutDeletingIt() { + val viewModel = failedPhotoSend(offline) + + viewModel.discardPhoto("m1") + + assertEquals(emptyList(), viewModel.uiState.value.pendingPhotos) + assertEquals(emptyList(), photoStorage.deleted) + } + + @Test + fun discardPhoto_deletesItsMessage_soTheOtherParticipantNoLongerSeesIt() { + val viewModel = failedPhotoSend(refused) + // The message was written before the upload failed. + val written = + ChatMessage( + "m1", + renter.uid, + "", + Instant.ofEpochSecond(300), + imagePath = "conversations/${conversation.id}/m1.jpg", + photoPending = true, + ) + chat.messages.value = mapOf(conversation.id to listOf(hi, written)) + advance() + + viewModel.discardPhoto("m1") + advance() + + assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) + assertEquals(listOf(hi), viewModel.uiState.value.messages) + assertEquals(listOf(hi), viewModel.uiState.value.shownMessages) + } + + @Test + fun discardPhoto_whileItUploads_isIgnored() { + val viewModel = inConversation() + chat.gate = CompletableDeferred() + viewModel.attachPhoto(galleryPhoto) + viewModel.send() + advance() + + viewModel.discardPhoto("m1") + + assertEquals( + listOf(PendingPhotoStatus.UPLOADING), + viewModel.uiState.value.pendingPhotos.map { it.status }, + ) + assertEquals(emptyList>(), chat.deletedPhotoMessages) + } + + @Test + fun closing_withAFailedTakenPhoto_deletesItAndItsMessage() { + val viewModel = inConversation() + chat.sendFailure = offline + val taken = viewModel.takePhoto() + viewModel.send() + advance() + + viewModel.close() + + assertEquals(listOf(taken), photoStorage.deleted) + assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) + } + + @Test + fun closing_withAFailedGalleryPhoto_deletesItsMessage_butNotThePhoto() { + val viewModel = failedPhotoSend(refused) + + viewModel.close() + + assertEquals(emptyList(), photoStorage.deleted) + assertEquals(listOf(conversation.id to "m1"), chat.deletedPhotoMessages) + } + + /** + * Creates photos like the camera folder: "taken_0", "taken_1", … in [taken], or none while + * [full]. Records the photos deleted. + */ + private class FakePhotoStorage : PhotoStorage { + var full = false + val taken = mutableListOf() + val deleted = mutableListOf() + + override fun newPhoto(): TakenPhoto? { + if (full) return null + val index = taken.size + return TakenPhoto( + uri = Uri.parse("file:///chat/taken_$index.jpg"), + cameraUri = Uri.parse("content://camera/taken_$index.jpg"), + ) + .also(taken::add) + } + + override fun delete(photo: Uri) { + deleted += photo + } + + override fun deleteAllExcept(keep: List) = Unit + } } diff --git a/firestore.rules b/firestore.rules index 0d238c9d..853ed2e5 100644 --- a/firestore.rules +++ b/firestore.rules @@ -278,7 +278,12 @@ service cloud.firestore { allow update: if isVerified() && isPhotoUploaded(); - allow delete: if false; + // The sender can take back a photo message whose photo never arrived: the app's Remove after + // a failed send. Once photoPending is false the photo is delivered and the message stays. A + // text never has photoPending, so it cannot be deleted. + allow delete: if isVerified() + && resource.data.senderUid == request.auth.uid + && resource.data.get('photoPending', false) == true; } } diff --git a/rules-tests/firestore.test.js b/rules-tests/firestore.test.js index 26bd7ee8..6ea4f189 100644 --- a/rules-tests/firestore.test.js +++ b/rules-tests/firestore.test.js @@ -1681,8 +1681,37 @@ describe("pending photos", () => { await assertFails(updateDoc(ref, { photoPending: deleteField() })); }); - test("a pending photo message cannot be deleted", async () => { + test("the sender can delete their message while its photo is pending", async () => { await seedPhotoMessage(); + await assertSucceeds(deleteDoc(doc(verified(BOB), PATH))); + }); + + test("a pending photo with a caption can be deleted", async () => { + await seedPhotoMessage({ photoPending: true, text: "The drill bits" }); + await assertSucceeds(deleteDoc(doc(verified(BOB), PATH))); + }); + + test("only the sender can delete their pending photo message", async () => { + await seedPhotoMessage(); + await assertFails(deleteDoc(doc(verified(ALICE), PATH))); + await assertFails(deleteDoc(doc(verified(EVE), PATH))); + await assertFails(deleteDoc(doc(unverified(BOB), PATH))); + await assertFails(deleteDoc(doc(signedOut(), PATH))); + }); + + test("a photo message cannot be deleted once its photo is uploaded", async () => { + await seedPhotoMessage({ photoPending: false }); + await assertFails(deleteDoc(doc(verified(BOB), PATH))); + }); + + test("a photo sent before photoPending existed cannot be deleted", async () => { + await seedPhotoMessage({}); await assertFails(deleteDoc(doc(verified(BOB), PATH))); }); + + // The app's Remove also deletes a message that was never written; the rules refuse it. + test("a missing message cannot be deleted", async () => { + await seedConversation(); + await assertFails(deleteDoc(doc(verified(BOB), `${CONVERSATION}/messages/m9`))); + }); });