From 2e4ff12cab71c5a3f42d8dfe1ca94da73934b748 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:23:46 +0100 Subject: [PATCH 01/27] refactor(chat): give the chat repository Storage and a photo compressor Co-Authored-By: Claude Opus 5.5 --- .../com/android/polybazaar/MainActivity.kt | 5 ++++- .../chat/model/FirebaseChatRepository.kt | 11 +++++++++++ .../chat/model/FirebaseChatRepositoryTest.kt | 18 +++++++++++++----- 3 files changed, 28 insertions(+), 6 deletions(-) diff --git a/app/src/main/java/com/android/polybazaar/MainActivity.kt b/app/src/main/java/com/android/polybazaar/MainActivity.kt index 1ebd5993..43c009ec 100644 --- a/app/src/main/java/com/android/polybazaar/MainActivity.kt +++ b/app/src/main/java/com/android/polybazaar/MainActivity.kt @@ -57,7 +57,10 @@ class MainActivity : ComponentActivity() { remember { FilePhotoStorage(applicationContext, FilePhotoStorage.CREATE_FORM) }, editPhotoStorage = remember { FilePhotoStorage(applicationContext, FilePhotoStorage.EDIT_FORM) }, - chatRepository = remember { FirebaseChatRepository() }, + chatRepository = + remember { + FirebaseChatRepository(JpegPhotoCompressor(applicationContext.contentResolver)) + }, bookingRepository = remember { FirebaseBookingRepository() }, ) } 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 989d44e2..4eab7a50 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 @@ -2,6 +2,7 @@ package com.android.polybazaar.chat.model import android.util.Log +import com.android.polybazaar.photo.PhotoCompressor import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FieldPath @@ -10,16 +11,26 @@ import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.Query import com.google.firebase.firestore.SetOptions +import com.google.firebase.storage.FirebaseStorage import java.time.Instant import java.util.concurrent.Executor +import kotlin.time.Duration +import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.tasks.await +/** + * @param uploadTimeout how long a photo upload may take before it fails with NETWORK, rather than + * the Storage SDK retrying for minutes while offline. + */ class FirebaseChatRepository( + private val photoCompressor: PhotoCompressor, private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance(), private val auth: FirebaseAuth = FirebaseAuth.getInstance(), + private val storage: FirebaseStorage = FirebaseStorage.getInstance(), + private val uploadTimeout: Duration = 30.seconds, private val logWriteFailure: (Exception) -> Unit = { Log.e("ChatRepository", "Chat write failed", it) }, 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 88ff57b6..7133fef3 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 @@ -1,6 +1,7 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.model +import com.android.polybazaar.photo.PhotoCompressor import com.google.android.gms.tasks.TaskCompletionSource import com.google.android.gms.tasks.Tasks import com.google.firebase.Timestamp @@ -19,6 +20,7 @@ import com.google.firebase.firestore.Query import com.google.firebase.firestore.QuerySnapshot import com.google.firebase.firestore.SetOptions import com.google.firebase.firestore.WriteBatch +import com.google.firebase.storage.FirebaseStorage import java.time.Instant import kotlinx.coroutines.async import kotlinx.coroutines.flow.first @@ -59,7 +61,9 @@ class FirebaseChatRepositoryTest { private val listings = mock() private val listingRef = mock() private val listing = mock() - private val repository = FirebaseChatRepository(firestore, auth) + private val storage = mock() + private val photoCompressor = PhotoCompressor { byteArrayOf(1) } + private val repository = FirebaseChatRepository(photoCompressor, firestore, auth, storage) private val conversation = Conversation( listingId = "listing", @@ -267,7 +271,8 @@ class FirebaseChatRepositoryTest { val pendingWrite = TaskCompletionSource() whenever(batch.commit()).thenReturn(pendingWrite.task) var reportedFailure: Exception? = null - val repository = FirebaseChatRepository(firestore, auth) { reportedFailure = it } + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } var reportedToCaller: Exception? = null repository.sendMessage(conversation, "Hi") { reportedToCaller = it } @@ -294,7 +299,8 @@ class FirebaseChatRepositoryTest { @Test fun sendMessageDoesNotReportSuccessfulWrites() = runTest { var reportedFailure: Exception? = null - val repository = FirebaseChatRepository(firestore, auth) { reportedFailure = it } + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } var reportedToCaller: Exception? = null repository.sendMessage(conversation, "Hi") { reportedToCaller = it } @@ -383,7 +389,8 @@ class FirebaseChatRepositoryTest { whenever(conversationRef.update(any(), any(), anyVararg())) .thenReturn(pendingWrite.task) var reportedFailure: Exception? = null - val repository = FirebaseChatRepository(firestore, auth) { reportedFailure = it } + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } repository.markRead("listing_renter") @@ -397,7 +404,8 @@ class FirebaseChatRepositoryTest { whenever(conversationRef.update(any(), any(), anyVararg())) .thenReturn(pendingWrite.task) var reportedFailure: Exception? = null - val repository = FirebaseChatRepository(firestore, auth) { reportedFailure = it } + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } repository.markRead("listing_renter") val failure = IllegalStateException("Write rejected") From 583764ec167520df1aa471e92464c9a597a512ed Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:27:41 +0100 Subject: [PATCH 02/27] feat(chat): send a photo message Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/ChatRepository.kt | 32 ++++ .../chat/model/FirebaseChatRepository.kt | 170 +++++++++++++----- .../chat/model/FakeChatRepository.kt | 35 ++++ 3 files changed, 190 insertions(+), 47 deletions(-) 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 d84b79fe..1a8ce1d2 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 @@ -1,6 +1,7 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.model +import android.net.Uri import kotlinx.coroutines.flow.Flow interface ChatRepository { @@ -22,6 +23,37 @@ interface ChatRepository { onWriteFailure: (Exception) -> Unit = {}, ) + /** + * Returns a new message ID for the conversation with this ID, without any network access. Keep it + * to retry a failed [sendPhoto] with the same ID. + */ + fun newMessageId(conversationId: String): String + + /** + * Sends a photo message from the signed-in participant. The photo is compressed and uploaded + * first, and this waits for the upload, so it needs a connection. Then, like [sendMessage], the + * message and the conversation update are queued without waiting for the server, and a later + * rejection is reported through [onWriteFailure]. + * + * Throws when signed out (UNAUTHENTICATED), when the upload fails (a Storage error, to map with + * toAppError), and IllegalArgumentException when the user is not a participant, when the + * conversation has no message yet (a photo cannot open a conversation), or when the caption is + * not sendable. When it throws, nothing is written. + * + * @param conversation the conversation from [observeConversation]. + * @param messageId from [newMessageId]; pass the same one to retry a failed send. + * @param caption optional text sent with the photo; null or blank sends the photo alone, which + * previews as an empty lastMessageText. + * @param onWriteFailure as for [sendMessage]. + */ + suspend fun sendPhoto( + conversation: Conversation, + messageId: String, + photo: Uri, + caption: String? = null, + onWriteFailure: (Exception) -> Unit = {}, + ) + /** * Marks the conversation with this ID as read by the signed-in user: sets only their lastReadAt * to the server time. Like [sendMessage], the write is queued without waiting for the server, so 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 4eab7a50..ad41b92c 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 @@ -1,9 +1,12 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.model +import android.net.Uri import android.util.Log import com.android.polybazaar.photo.PhotoCompressor +import com.android.polybazaar.photo.PhotoStorage import com.google.firebase.auth.FirebaseAuth +import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot import com.google.firebase.firestore.FieldPath import com.google.firebase.firestore.FieldValue @@ -41,58 +44,65 @@ class FirebaseChatRepository( text: String, onWriteFailure: (Exception) -> Unit, ) { - val senderUid = - auth.currentUser?.uid - ?: throw FirebaseFirestoreException( - "Sign in to send a message", - FirebaseFirestoreException.Code.UNAUTHENTICATED, - ) - require(senderUid in conversation.participants) { "Only participants can send messages" } + val senderUid = participantUid(conversation) require(ChatRules.isSendable(text)) { "A message must have 1 to ${ChatRules.MAX_MESSAGE_LENGTH} characters" } - val conversationRef = conversationDocument(conversation.id) - val messageRef = conversationRef.collection(MESSAGES).document() + val messageRef = conversationDocument(conversation.id).collection(MESSAGES).document() val trimmed = text.trim() - val conversationFields = - mutableMapOf( - "listingId" to conversation.listingId, - "renterUid" to conversation.renterUid, - "lenderUid" to conversation.lenderUid, - "participants" to conversation.participants, - "lastMessageAt" to FieldValue.serverTimestamp(), - "lastMessageId" to messageRef.id, - "lastMessageText" to trimmed, - "lastMessageSenderUid" to senderUid, - // The merge sets only my key, so the other participant's read time is kept, and my own - // message never shows as unread to me. - "lastReadAt" to mapOf(senderUid to FieldValue.serverTimestamp()), - ) - // A reply leaves the title as stored, so an outdated title on this device cannot get the - // reply rejected. - if (conversation.lastMessageAt == null) { - // The rules require the listing's current title, and the one this screen loaded may be - // outdated. - conversationFields["listingTitle"] = currentListingTitle(conversation.listingId) + writeMessage( + conversation, + messageRef, + senderUid, + preview = trimmed, + messageFields = mapOf("text" to trimmed), + onWriteFailure, + ) + } + + override fun newMessageId(conversationId: String): String = + conversationDocument(conversationId).collection(MESSAGES).document().id + + override suspend fun sendPhoto( + conversation: Conversation, + messageId: String, + photo: Uri, + caption: String?, + onWriteFailure: (Exception) -> Unit, + ) { + val senderUid = participantUid(conversation) + // Storage only accepts a chat photo once the conversation exists. + require(conversation.lastMessageAt != null) { + "A photo cannot be the first message of a conversation" } - firestore - .batch() - // A merge leaves unchanged fields out of the rules' affected keys, so the same write - // creates the conversation on the first message and only bumps it on later ones. - .set(conversationRef, conversationFields, SetOptions.merge()) - .set( - messageRef, - mapOf( - "senderUid" to senderUid, - "text" to trimmed, - "sentAt" to FieldValue.serverTimestamp(), - ), - ) - .commit() - .addOnFailureListener(Executor { it.run() }) { - logWriteFailure(it) - onWriteFailure(it) - } + val trimmedCaption = + caption + ?.takeIf { it.isNotBlank() } + ?.also { + require(ChatRules.isSendable(it)) { + "A caption must have 1 to ${ChatRules.MAX_MESSAGE_LENGTH} characters" + } + } + ?.trim() + val path = photoPath(conversation.id, messageId) + // Awaited: the message must not point to a photo that was never uploaded. + storage.reference + .child(path) + .putBytes(photoCompressor.compress(photo), PhotoStorage.JPEG_METADATA) + .await() + writeMessage( + conversation, + conversationDocument(conversation.id).collection(MESSAGES).document(messageId), + senderUid, + // A photo alone previews as an empty text. + preview = trimmedCaption ?: "", + messageFields = + buildMap { + put("imagePath", path) + trimmedCaption?.let { put("text", it) } + }, + onWriteFailure, + ) } override fun markRead(conversationId: String) { @@ -178,6 +188,68 @@ class FirebaseChatRepository( awaitClose { listener.remove() } } + /** The signed-in user's uid, who must be one of the [conversation]'s participants. */ + private fun participantUid(conversation: Conversation): String { + val senderUid = + auth.currentUser?.uid + ?: throw FirebaseFirestoreException( + "Sign in to send a message", + FirebaseFirestoreException.Code.UNAUTHENTICATED, + ) + require(senderUid in conversation.participants) { "Only participants can send messages" } + return senderUid + } + + /** + * Queues the message at [messageRef] with [messageFields], plus its sender and time, and updates + * the conversation's preview to [preview], in one batch that is not awaited. + */ + private suspend fun writeMessage( + conversation: Conversation, + messageRef: DocumentReference, + senderUid: String, + preview: String, + messageFields: Map, + onWriteFailure: (Exception) -> Unit, + ) { + val conversationFields = + mutableMapOf( + "listingId" to conversation.listingId, + "renterUid" to conversation.renterUid, + "lenderUid" to conversation.lenderUid, + "participants" to conversation.participants, + "lastMessageAt" to FieldValue.serverTimestamp(), + "lastMessageId" to messageRef.id, + "lastMessageText" to preview, + "lastMessageSenderUid" to senderUid, + // The merge sets only my key, so the other participant's read time is kept, and my own + // message never shows as unread to me. + "lastReadAt" to mapOf(senderUid to FieldValue.serverTimestamp()), + ) + // A reply leaves the title as stored, so an outdated title on this device cannot get the + // reply rejected. + if (conversation.lastMessageAt == null) { + // The rules require the listing's current title, and the one this screen loaded may be + // outdated. + conversationFields["listingTitle"] = currentListingTitle(conversation.listingId) + } + firestore + .batch() + // A merge leaves unchanged fields out of the rules' affected keys, so the same write + // creates the conversation on the first message and only bumps it on later ones. + .set(conversationDocument(conversation.id), conversationFields, SetOptions.merge()) + .set( + messageRef, + mapOf("senderUid" to senderUid, "sentAt" to FieldValue.serverTimestamp()) + + messageFields, + ) + .commit() + .addOnFailureListener(Executor { it.run() }) { + logWriteFailure(it) + onWriteFailure(it) + } + } + private suspend fun currentListingTitle(listingId: String): String { val listing = firestore.collection(LISTINGS).document(listingId).get().await() return listing.takeIf { it.exists() }?.getString("title") @@ -189,6 +261,10 @@ class FirebaseChatRepository( private fun conversationDocument(id: String) = firestore.collection(CONVERSATIONS).document(id) + /** Where a message's photo is stored; storage.rules only accept a participant's upload there. */ + private fun photoPath(conversationId: String, messageId: String) = + "$CONVERSATIONS/$conversationId/$messageId.jpg" + // A write not yet confirmed by the server has no sentAt or lastMessageAt; ESTIMATE gives it the // local time. private fun DocumentSnapshot.instant(field: String): Instant? = 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 82ce8d71..846007b8 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 @@ -1,6 +1,7 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.model +import android.net.Uri import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.MutableStateFlow @@ -25,6 +26,9 @@ import kotlinx.coroutines.flow.map * look at a send in progress, and throws [sendFailure] if set, like a send refused before queuing; * such a call is still recorded. * + * [sendPhoto] works the same way with [sentPhotos] and [photoWriteFailureCallbacks], sharing [gate] + * and [sendFailure]. [newMessageId] returns "m1", "m2", … in call order. + * * [markRead] records every id in [markedRead]. When [myUid] is set and the conversation is in * [myConversations] with a last message, it also sets [myUid]'s lastReadAt to that message's time * and emits the updated list, like a local write the listener sees at once. @@ -47,6 +51,20 @@ class FakeChatRepository( /** The `onWriteFailure` callbacks passed to [sendMessage], in order. */ val writeFailureCallbacks = mutableListOf<(Exception) -> Unit>() + /** A call to [sendPhoto]. */ + data class SentPhoto( + val conversation: Conversation, + val messageId: String, + val photo: Uri, + val caption: String?, + ) + + /** The calls to [sendPhoto], in order. */ + val sentPhotos = mutableListOf() + + /** The `onWriteFailure` callbacks passed to [sendPhoto], in order. */ + val photoWriteFailureCallbacks = mutableListOf<(Exception) -> Unit>() + /** The ids passed to [markRead], in order. */ val markedRead = mutableListOf() @@ -55,6 +73,8 @@ class FakeChatRepository( var conversationGate: CompletableDeferred? = null var messagesGate: CompletableDeferred? = null + private var messageIds = 0 + var observeConversationCalls = 0 private set @@ -72,6 +92,21 @@ class FakeChatRepository( sendFailure?.let { throw it } } + override fun newMessageId(conversationId: String): String = "m${++messageIds}" + + override suspend fun sendPhoto( + conversation: Conversation, + messageId: String, + photo: Uri, + caption: String?, + onWriteFailure: (Exception) -> Unit, + ) { + sentPhotos += SentPhoto(conversation, messageId, photo, caption) + photoWriteFailureCallbacks += onWriteFailure + gate?.await() + sendFailure?.let { throw it } + } + override fun markRead(conversationId: String) { markedRead += conversationId val uid = myUid ?: return From 8e9f5b0f8a280915ca10d889d12f4f2798c6f488 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:29:35 +0100 Subject: [PATCH 03/27] feat(chat): reuse a photo already uploaded when retrying Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepository.kt | 24 +++++++++++++++---- 1 file changed, 20 insertions(+), 4 deletions(-) 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 ad41b92c..1457d5b2 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 @@ -15,6 +15,8 @@ import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.Query import com.google.firebase.firestore.SetOptions import com.google.firebase.storage.FirebaseStorage +import com.google.firebase.storage.StorageException +import com.google.firebase.storage.StorageReference import java.time.Instant import java.util.concurrent.Executor import kotlin.time.Duration @@ -85,11 +87,11 @@ class FirebaseChatRepository( } ?.trim() val path = photoPath(conversation.id, messageId) + val photoRef = storage.reference.child(path) // Awaited: the message must not point to a photo that was never uploaded. - storage.reference - .child(path) - .putBytes(photoCompressor.compress(photo), PhotoStorage.JPEG_METADATA) - .await() + if (!exists(photoRef)) { + photoRef.putBytes(photoCompressor.compress(photo), PhotoStorage.JPEG_METADATA).await() + } writeMessage( conversation, conversationDocument(conversation.id).collection(MESSAGES).document(messageId), @@ -261,6 +263,20 @@ class FirebaseChatRepository( private fun conversationDocument(id: String) = firestore.collection(CONVERSATIONS).document(id) + /** + * Whether a file is already at [ref], like a photo uploaded by a send whose batch then failed. + * The rules allow a chat photo to be created only once, so a retry with the same message ID must + * reuse that file rather than upload it again. + */ + private suspend fun exists(ref: StorageReference): Boolean = + try { + ref.metadata.await() + true + } catch (e: StorageException) { + if (e.errorCode != StorageException.ERROR_OBJECT_NOT_FOUND) throw e + false + } + /** Where a message's photo is stored; storage.rules only accept a participant's upload there. */ private fun photoPath(conversationId: String, messageId: String) = "$CONVERSATIONS/$conversationId/$messageId.jpg" From da1d4b1593a963d9fdc0f53dda1ff39a0ec79101 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:31:14 +0100 Subject: [PATCH 04/27] feat(chat): fail a photo upload quickly when offline Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/ChatRepository.kt | 7 ++--- .../chat/model/FirebaseChatRepository.kt | 27 ++++++++++++++++--- 2 files changed, 28 insertions(+), 6 deletions(-) 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 1a8ce1d2..d636b2ec 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 @@ -36,9 +36,10 @@ interface ChatRepository { * rejection is reported through [onWriteFailure]. * * Throws when signed out (UNAUTHENTICATED), when the upload fails (a Storage error, to map with - * toAppError), and IllegalArgumentException when the user is not a participant, when the - * conversation has no message yet (a photo cannot open a conversation), or when the caption is - * not sendable. When it throws, nothing is written. + * toAppError) or takes too long, as offline (an AppException with NETWORK), and + * IllegalArgumentException when the user is not a participant, when the conversation has no + * message yet (a photo cannot open a conversation), or when the caption is not sendable. When it + * throws, nothing is written. * * @param conversation the conversation from [observeConversation]. * @param messageId from [newMessageId]; pass the same one to retry a failed send. 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 1457d5b2..7235d33e 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 @@ -3,6 +3,8 @@ package com.android.polybazaar.chat.model import android.net.Uri import android.util.Log +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.error.model.AppException import com.android.polybazaar.photo.PhotoCompressor import com.android.polybazaar.photo.PhotoStorage import com.google.firebase.auth.FirebaseAuth @@ -21,10 +23,13 @@ import java.time.Instant import java.util.concurrent.Executor import kotlin.time.Duration import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.channels.awaitClose import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.callbackFlow import kotlinx.coroutines.tasks.await +import kotlinx.coroutines.withTimeout /** * @param uploadTimeout how long a photo upload may take before it fails with NETWORK, rather than @@ -88,9 +93,13 @@ class FirebaseChatRepository( ?.trim() val path = photoPath(conversation.id, messageId) val photoRef = storage.reference.child(path) - // Awaited: the message must not point to a photo that was never uploaded. - if (!exists(photoRef)) { - photoRef.putBytes(photoCompressor.compress(photo), PhotoStorage.JPEG_METADATA).await() + // Awaited: the message must not point to a photo that was never uploaded. Offline, the Storage + // SDK keeps retrying for minutes, so the user is told sooner that the photo was not sent. + try { + withTimeout(uploadTimeout) { if (!exists(photoRef)) upload(photoRef, photo) } + } catch (e: TimeoutCancellationException) { + // A CancellationException, which callers would take for their own cancellation and ignore. + throw AppException(AppError.NETWORK, e) } writeMessage( conversation, @@ -277,6 +286,18 @@ class FirebaseChatRepository( false } + /** Uploads the compressed [photo] to [ref], and cancels the upload if the caller is cancelled. */ + private suspend fun upload(ref: StorageReference, photo: Uri) { + val task = ref.putBytes(photoCompressor.compress(photo), PhotoStorage.JPEG_METADATA) + try { + task.await() + } catch (e: CancellationException) { + // await() stops waiting but leaves the upload running. + task.cancel() + throw e + } + } + /** Where a message's photo is stored; storage.rules only accept a participant's upload there. */ private fun photoPath(conversationId: String, messageId: String) = "$CONVERSATIONS/$conversationId/$messageId.jpg" From 5615cfbee157411032aeff1d00c481612eae1591 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:33:26 +0100 Subject: [PATCH 05/27] feat(chat): load a photo message Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/ChatRepository.kt | 7 +++++++ .../chat/model/FirebaseChatRepository.kt | 3 +++ .../polybazaar/chat/model/FakeChatRepository.kt | 14 ++++++++++++++ 3 files changed, 24 insertions(+) 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 d636b2ec..59971711 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 @@ -55,6 +55,13 @@ interface ChatRepository { onWriteFailure: (Exception) -> Unit = {}, ) + /** + * 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, and with + * a Storage error to map with toAppError otherwise. + */ + suspend fun loadMessagePhoto(imagePath: String): ByteArray + /** * Marks the conversation with this ID as read by the signed-in user: sets only their lastReadAt * to the server time. Like [sendMessage], the write is queued without waiting for the server, so 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 7235d33e..7326f853 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 @@ -116,6 +116,9 @@ class FirebaseChatRepository( ) } + override suspend fun loadMessagePhoto(imagePath: String): ByteArray = + storage.reference.child(imagePath).getBytes(PhotoStorage.MAX_PHOTO_BYTES).await() + 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/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt index 846007b8..f28a452e 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 @@ -29,6 +29,9 @@ import kotlinx.coroutines.flow.map * [sendPhoto] works the same way with [sentPhotos] and [photoWriteFailureCallbacks], sharing [gate] * and [sendFailure]. [newMessageId] returns "m1", "m2", … in call order. * + * [loadMessagePhoto] returns the bytes stored in [photos] for the path, and throws + * [photoLoadFailure] if set, or when the path is not in [photos]. + * * [markRead] records every id in [markedRead]. When [myUid] is set and the conversation is in * [myConversations] with a last message, it also sets [myUid]'s lastReadAt to that message's time * and emits the updated list, like a local write the listener sees at once. @@ -65,6 +68,12 @@ class FakeChatRepository( /** The `onWriteFailure` callbacks passed to [sendPhoto], in order. */ val photoWriteFailureCallbacks = mutableListOf<(Exception) -> Unit>() + /** The photos [loadMessagePhoto] returns, by Storage path. */ + val photos = mutableMapOf() + + /** When set, [loadMessagePhoto] throws it. */ + var photoLoadFailure: Exception? = null + /** The ids passed to [markRead], in order. */ val markedRead = mutableListOf() @@ -107,6 +116,11 @@ class FakeChatRepository( sendFailure?.let { throw it } } + override suspend fun loadMessagePhoto(imagePath: String): ByteArray { + photoLoadFailure?.let { throw it } + return photos[imagePath] ?: throw NoSuchElementException("No photo at $imagePath") + } + override fun markRead(conversationId: String) { markedRead += conversationId val uid = myUid ?: return From 9e81c6cd0f2cbe2038aab705a865d0c8fe7df8cc Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:41:21 +0100 Subject: [PATCH 06/27] test(chat): cover sending a photo message Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 219 +++++++++++++++++- 1 file changed, 218 insertions(+), 1 deletion(-) 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 7133fef3..74ac7e8d 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 @@ -1,6 +1,7 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) package com.android.polybazaar.chat.model +import android.net.Uri import com.android.polybazaar.photo.PhotoCompressor import com.google.android.gms.tasks.TaskCompletionSource import com.google.android.gms.tasks.Tasks @@ -21,6 +22,10 @@ import com.google.firebase.firestore.QuerySnapshot import com.google.firebase.firestore.SetOptions import com.google.firebase.firestore.WriteBatch import com.google.firebase.storage.FirebaseStorage +import com.google.firebase.storage.StorageException +import com.google.firebase.storage.StorageMetadata +import com.google.firebase.storage.StorageReference +import com.google.firebase.storage.UploadTask import java.time.Instant import kotlinx.coroutines.async import kotlinx.coroutines.flow.first @@ -38,11 +43,13 @@ import org.junit.Test import org.mockito.kotlin.any import org.mockito.kotlin.anyVararg import org.mockito.kotlin.argumentCaptor +import org.mockito.kotlin.doReturn import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @@ -62,7 +69,18 @@ class FirebaseChatRepositoryTest { private val listingRef = mock() private val listing = mock() private val storage = mock() - private val photoCompressor = PhotoCompressor { byteArrayOf(1) } + private val storageRoot = mock() + private val photoRef = mock() + // A separate mock from messageRef, so a test fails if a photo is written to a new document + // instead of the one its ID names. + private val photoMessageRef = mock() + private val uploadTask = mock() + private val photo = mock() + private val compressedPhoto = byteArrayOf(4, 2) + private val photoCompressor = PhotoCompressor { + assertSame(photo, it) + compressedPhoto + } private val repository = FirebaseChatRepository(photoCompressor, firestore, auth, storage) private val conversation = Conversation( @@ -71,6 +89,8 @@ class FirebaseChatRepositoryTest { renterUid = "renter", lenderUid = "lender", ) + // A photo can't be the first message, so photo tests send to a conversation that has one. + private val replied = conversation.copy(lastMessageAt = Instant.ofEpochSecond(1_700_000_000)) @Before fun setUp() { @@ -93,6 +113,16 @@ class FirebaseChatRepositoryTest { whenever(listingRef.get()).thenReturn(Tasks.forResult(listing)) whenever(listing.exists()).thenReturn(true) whenever(listing.getString("title")).thenReturn("Drill") + whenever(messages.document(PHOTO_ID)).thenReturn(photoMessageRef) + whenever(photoMessageRef.id).thenReturn(PHOTO_ID) + whenever(storage.reference).thenReturn(storageRoot) + whenever(storageRoot.child(PHOTO_PATH)).thenReturn(photoRef) + val notUploaded = storageException(StorageException.ERROR_OBJECT_NOT_FOUND) + whenever(photoRef.metadata).thenReturn(Tasks.forException(notUploaded)) + whenever(photoRef.putBytes(any(), any())).thenReturn(uploadTask) + whenever(uploadTask.isComplete).thenReturn(true) + val uploaded = mock() + whenever(uploadTask.result).thenReturn(uploaded) } @Test @@ -360,6 +390,154 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).batch() } + @Test + fun newMessageIdIsTheIdOfANewMessageDocument() { + assertEquals("message-id", repository.newMessageId("listing_renter")) + + verify(messages).document() + } + + @Test + fun sendPhotoUploadsCompressedPhotoAsJpegToTheMessagePath() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + val metadata = argumentCaptor() + verify(storageRoot).child(PHOTO_PATH) + verify(photoRef).putBytes(eq(compressedPhoto), metadata.capture()) + assertEquals("image/jpeg", metadata.firstValue.contentType) + } + + @Test + fun sendPhotoUploadsBeforeCommittingTheBatch() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + val order = inOrder(photoRef, batch) + order.verify(photoRef).putBytes(any(), any()) + order.verify(batch).commit() + } + + @Test + fun sendPhotoWithoutCaptionWritesImagePathWithoutTextAndEmptyPreview() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + verifyPhotoBatch( + preview = "", + message = + mapOf( + "senderUid" to "renter", + "sentAt" to FieldValue.serverTimestamp(), + "imagePath" to PHOTO_PATH, + ), + ) + } + + @Test + fun sendPhotoWithCaptionWritesTrimmedCaptionAsTextAndPreview() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo, caption = " The drill bits ") + + verifyPhotoBatch( + preview = "The drill bits", + message = + mapOf( + "senderUid" to "renter", + "sentAt" to FieldValue.serverTimestamp(), + "imagePath" to PHOTO_PATH, + "text" to "The drill bits", + ), + ) + } + + @Test + fun sendPhotoTreatsBlankCaptionAsNoCaption() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo, caption = " ") + + verifyPhotoBatch( + preview = "", + message = + mapOf( + "senderUid" to "renter", + "sentAt" to FieldValue.serverTimestamp(), + "imagePath" to PHOTO_PATH, + ), + ) + } + + @Test + fun sendPhotoFromLenderIsSentAndReadByLenderOnly() = runTest { + signInAs("lender") + + repository.sendPhoto(replied, PHOTO_ID, photo) + + val fields = argumentCaptor>() + verify(batch).set(eq(conversationRef), fields.capture(), eq(SetOptions.merge())) + assertEquals("lender", fields.firstValue["lastMessageSenderUid"]) + assertEquals(mapOf("lender" to FieldValue.serverTimestamp()), fields.firstValue["lastReadAt"]) + val message = argumentCaptor>() + verify(batch).set(eq(photoMessageRef), message.capture()) + assertEquals("lender", message.firstValue["senderUid"]) + } + + @Test + fun sendPhotoReportsLaterWriteFailuresToBothCallbacks() = runTest { + val pendingWrite = TaskCompletionSource() + whenever(batch.commit()).thenReturn(pendingWrite.task) + var reportedFailure: Exception? = null + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } + var reportedToCaller: Exception? = null + + repository.sendPhoto(replied, PHOTO_ID, photo) { reportedToCaller = it } + assertNull(reportedFailure) + val failure = IllegalStateException("Write rejected") + pendingWrite.setException(failure) + + assertSame(failure, reportedFailure) + assertSame(failure, reportedToCaller) + } + + @Test + fun sendPhotoRejectsSignedOutUser() = runTest { + whenever(auth.currentUser).thenReturn(null) + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertTrue(error is FirebaseFirestoreException) + assertEquals( + FirebaseFirestoreException.Code.UNAUTHENTICATED, + (error as FirebaseFirestoreException).code, + ) + verifyNothingSent() + } + + @Test + fun sendPhotoRejectsNonParticipant() = runTest { + signInAs("stranger") + + assertTrue( + runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + is IllegalArgumentException + ) + verifyNothingSent() + } + + @Test + fun sendPhotoRejectsConversationWithoutMessages() = runTest { + assertTrue( + runCatching { repository.sendPhoto(conversation, PHOTO_ID, photo) }.exceptionOrNull() + is IllegalArgumentException + ) + verifyNothingSent() + } + + @Test + fun sendPhotoRejectsTooLongCaption() = runTest { + assertTrue( + runCatching { repository.sendPhoto(replied, PHOTO_ID, photo, "a".repeat(1001)) } + .exceptionOrNull() is IllegalArgumentException + ) + verifyNothingSent() + } + @Test fun markReadSetsOnlyMyReadTimeToServerTime() { whenever(conversationRef.update(any(), any(), anyVararg())) @@ -723,6 +901,40 @@ class FirebaseChatRepositoryTest { assertEquals("Conversation listing_renter is missing listingId", error?.message) } + /** Checks the one batch of a photo reply: the conversation merge and the photo's message. */ + private fun verifyPhotoBatch(preview: String, message: Map) { + verify(batch) + .set( + eq(conversationRef), + eq( + mapOf( + "listingId" to "listing", + "renterUid" to "renter", + "lenderUid" to "lender", + "participants" to listOf("renter", "lender"), + "lastMessageAt" to FieldValue.serverTimestamp(), + "lastMessageId" to PHOTO_ID, + "lastMessageText" to preview, + "lastMessageSenderUid" to "renter", + "lastReadAt" to mapOf("renter" to FieldValue.serverTimestamp()), + ) + ), + eq(SetOptions.merge()), + ) + verify(batch).set(eq(photoMessageRef), eq(message)) + verify(batch).commit() + verify(listingRef, never()).get() + } + + private fun verifyNothingSent() { + verifyNoInteractions(storage) + verify(firestore, never()).batch() + } + + private fun storageException(errorCode: Int): StorageException = mock { + on { this.errorCode } doReturn errorCode + } + private fun signInAs(uid: String) { val user = mock() whenever(user.uid).thenReturn(uid) @@ -794,4 +1006,9 @@ class FirebaseChatRepositoryTest { private fun TestScope.observeMyConversationsFailure() = async { runCatching { repository.observeMyConversations().first() }.exceptionOrNull() } + + private companion object { + const val PHOTO_ID = "photo-id" + const val PHOTO_PATH = "conversations/listing_renter/photo-id.jpg" + } } From c4963be286e6c61375b5b53547a50e6613cea298 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:42:47 +0100 Subject: [PATCH 07/27] test(chat): cover a failed photo upload Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 51 +++++++++++++++++++ 1 file changed, 51 insertions(+) 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 74ac7e8d..42c91b52 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 @@ -2,6 +2,8 @@ package com.android.polybazaar.chat.model import android.net.Uri +import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.error.model.toAppError import com.android.polybazaar.photo.PhotoCompressor import com.google.android.gms.tasks.TaskCompletionSource import com.google.android.gms.tasks.Tasks @@ -538,6 +540,49 @@ class FirebaseChatRepositoryTest { verifyNothingSent() } + @Test + fun sendPhotoOfflineUploadFailureIsNetworkAndWritesNoBatch() = runTest { + val failure = storageException(StorageException.ERROR_RETRY_LIMIT_EXCEEDED) + failUpload(failure) + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertSame(failure, error) + assertEquals(AppError.NETWORK, error?.toAppError()) + verify(firestore, never()).batch() + } + + @Test + fun sendPhotoRefusedUploadIsPermissionDeniedAndWritesNoBatch() = runTest { + val failure = storageException(StorageException.ERROR_NOT_AUTHORIZED) + failUpload(failure) + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertSame(failure, error) + assertEquals(AppError.PERMISSION_DENIED, error?.toAppError()) + verify(firestore, never()).batch() + } + + @Test + fun sendPhotoCompressionFailureUploadsAndWritesNothing() = runTest { + val repository = + FirebaseChatRepository( + { throw IllegalStateException("Unreadable photo") }, + firestore, + auth, + storage, + ) + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + // Not assertSame: coroutine stack-trace recovery may rethrow a copy of it. + assertTrue(error is IllegalStateException) + assertEquals("Unreadable photo", error?.message) + verify(photoRef, never()).putBytes(any(), any()) + verify(firestore, never()).batch() + } + @Test fun markReadSetsOnlyMyReadTimeToServerTime() { whenever(conversationRef.update(any(), any(), anyVararg())) @@ -931,6 +976,12 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).batch() } + /** Makes the photo upload end with [failure]. */ + private fun failUpload(failure: Exception) { + whenever(uploadTask.isSuccessful).thenReturn(false) + whenever(uploadTask.exception).thenReturn(failure) + } + private fun storageException(errorCode: Int): StorageException = mock { on { this.errorCode } doReturn errorCode } From 90243ce9f76c62ea0508c1abd774091c5e7965be Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:43:46 +0100 Subject: [PATCH 08/27] test(chat): cover retrying a photo message Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 53 +++++++++++++++++++ 1 file changed, 53 insertions(+) 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 42c91b52..845f0275 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 @@ -583,6 +583,59 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).batch() } + @Test + fun sendPhotoRetryReusesStoredPhotoWithoutCompressingOrUploading() = runTest { + val stored = mock() + whenever(photoRef.metadata).thenReturn(Tasks.forResult(stored)) + var compressions = 0 + val repository = + FirebaseChatRepository( + { + compressions++ + compressedPhoto + }, + firestore, + auth, + storage, + ) + + repository.sendPhoto(replied, PHOTO_ID, photo, caption = "The drill bits") + + assertEquals(0, compressions) + verify(photoRef, never()).putBytes(any(), any()) + verifyPhotoBatch( + preview = "The drill bits", + message = + mapOf( + "senderUid" to "renter", + "sentAt" to FieldValue.serverTimestamp(), + "imagePath" to PHOTO_PATH, + "text" to "The drill bits", + ), + ) + } + + @Test + fun sendPhotoUploadsOnlyAfterCheckingNoPhotoIsStored() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + val order = inOrder(photoRef) + order.verify(photoRef).metadata + order.verify(photoRef).putBytes(any(), any()) + } + + @Test + fun sendPhotoRethrowsOtherStoredPhotoCheckFailuresAndSendsNothing() = runTest { + val failure = storageException(StorageException.ERROR_NOT_AUTHORIZED) + whenever(photoRef.metadata).thenReturn(Tasks.forException(failure)) + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertSame(failure, error) + verify(photoRef, never()).putBytes(any(), any()) + verify(firestore, never()).batch() + } + @Test fun markReadSetsOnlyMyReadTimeToServerTime() { whenever(conversationRef.update(any(), any(), anyVararg())) From b58f084b27d058938387c272511261fbd46e92e2 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:58:20 +0100 Subject: [PATCH 09/27] test(chat): cover a photo upload that times out Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 63 +++++++++++++++++++ 1 file changed, 63 insertions(+) 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 845f0275..75de013c 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 @@ -3,6 +3,7 @@ package com.android.polybazaar.chat.model import android.net.Uri import com.android.polybazaar.error.model.AppError +import com.android.polybazaar.error.model.AppException import com.android.polybazaar.error.model.toAppError import com.android.polybazaar.photo.PhotoCompressor import com.google.android.gms.tasks.TaskCompletionSource @@ -29,8 +30,12 @@ import com.google.firebase.storage.StorageMetadata import com.google.firebase.storage.StorageReference import com.google.firebase.storage.UploadTask import java.time.Instant +import kotlin.time.Duration.Companion.seconds +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async import kotlinx.coroutines.flow.first +import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest @@ -636,6 +641,61 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).batch() } + @Test + fun sendPhotoUploadWithNoAnswerFailsWithNetworkAfterTimeoutAndCancelsIt() = runTest { + whenever(uploadTask.isComplete).thenReturn(false) + + val error = runCatching { + shortTimeoutRepository().sendPhoto(replied, PHOTO_ID, photo) + } + .exceptionOrNull() + + assertEquals(AppError.NETWORK, (error as AppException).error) + assertTrue(error.cause is TimeoutCancellationException) + assertEquals(5_000L, testScheduler.currentTime) + verify(uploadTask).cancel() + verify(firestore, never()).batch() + } + + @Test + fun sendPhotoStoredPhotoCheckWithNoAnswerFailsWithNetworkWithoutUploading() = runTest { + whenever(photoRef.metadata).thenReturn(TaskCompletionSource().task) + + val error = runCatching { + shortTimeoutRepository().sendPhoto(replied, PHOTO_ID, photo) + } + .exceptionOrNull() + + assertEquals(AppError.NETWORK, (error as AppException).error) + verify(photoRef, never()).putBytes(any(), any()) + verify(firestore, never()).batch() + } + + @Test + fun sendPhotoCancelledByCallerCancelsUploadAndPropagatesCancellation() = runTest { + whenever(uploadTask.isComplete).thenReturn(false) + var thrown: Throwable? = null + val sending = launch { + try { + repository.sendPhoto(replied, PHOTO_ID, photo) + } catch (e: Throwable) { + thrown = e + throw e + } + } + runCurrent() + verify(photoRef).putBytes(any(), any()) + + sending.cancel() + runCurrent() + + // What sendPhoto itself threw: a cancelled job always ends with a CancellationException. + assertTrue(thrown is CancellationException) + assertFalse(thrown is TimeoutCancellationException) + verify(uploadTask).cancel() + verify(firestore, never()).batch() + } + @Test fun markReadSetsOnlyMyReadTimeToServerTime() { whenever(conversationRef.update(any(), any(), anyVararg())) @@ -1029,6 +1089,9 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).batch() } + private fun shortTimeoutRepository() = + FirebaseChatRepository(photoCompressor, firestore, auth, storage, uploadTimeout = 5.seconds) + /** Makes the photo upload end with [failure]. */ private fun failUpload(failure: Exception) { whenever(uploadTask.isSuccessful).thenReturn(false) From dce6f252c74cc77a1f7afe3716d9a5b22eb40e26 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Mon, 16 Nov 2026 10:58:47 +0100 Subject: [PATCH 10/27] test(chat): cover loading a photo message Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) 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 75de013c..8fc552b7 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 @@ -696,6 +696,37 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).batch() } + @Test + fun loadMessagePhotoDownloadsUpToTenMegabytesFromItsPath() = runTest { + val bytes = byteArrayOf(7, 7) + whenever(photoRef.getBytes(10L * 1024 * 1024)).thenReturn(Tasks.forResult(bytes)) + + assertSame(bytes, repository.loadMessagePhoto(PHOTO_PATH)) + verify(storageRoot).child(PHOTO_PATH) + } + + @Test + fun loadMessagePhotoPropagatesMissingPhotoAsNotFound() = runTest { + val failure = storageException(StorageException.ERROR_OBJECT_NOT_FOUND) + whenever(photoRef.getBytes(any())).thenReturn(Tasks.forException(failure)) + + val error = runCatching { repository.loadMessagePhoto(PHOTO_PATH) }.exceptionOrNull() + + assertSame(failure, error) + assertEquals(AppError.NOT_FOUND, error?.toAppError()) + } + + @Test + fun loadMessagePhotoPropagatesRefusalAsPermissionDenied() = runTest { + val failure = storageException(StorageException.ERROR_NOT_AUTHORIZED) + whenever(photoRef.getBytes(any())).thenReturn(Tasks.forException(failure)) + + val error = runCatching { repository.loadMessagePhoto(PHOTO_PATH) }.exceptionOrNull() + + assertSame(failure, error) + assertEquals(AppError.PERMISSION_DENIED, error?.toAppError()) + } + @Test fun markReadSetsOnlyMyReadTimeToServerTime() { whenever(conversationRef.update(any(), any(), anyVararg())) From ab068e2ef5676baea478a738a59b648487952e27 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Tue, 17 Nov 2026 23:37:46 +0100 Subject: [PATCH 11/27] fix(chat): write a photo's message before uploading it storage.rules only accept a chat photo once the server has the message that names it, so sendPhoto now reads the message from the server, writes and confirms it if missing, then uploads. Offline the server read fails at once with NETWORK, so nothing is queued. A retry with the same message ID only uploads. sendPhoto throws every failure, so its onWriteFailure callback is removed. Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/ChatRepository.kt | 23 +-- .../chat/model/FirebaseChatRepository.kt | 93 +++++++----- .../chat/model/FakeChatRepository.kt | 10 +- .../chat/model/FirebaseChatRepositoryTest.kt | 140 +++++++++++++----- 4 files changed, 171 insertions(+), 95 deletions(-) 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 59971711..9cae988d 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 @@ -30,29 +30,30 @@ interface ChatRepository { fun newMessageId(conversationId: String): String /** - * Sends a photo message from the signed-in participant. The photo is compressed and uploaded - * first, and this waits for the upload, so it needs a connection. Then, like [sendMessage], the - * message and the conversation update are queued without waiting for the server, and a later - * rejection is reported through [onWriteFailure]. + * Sends a photo message from the signed-in participant, and returns once the server has both the + * message and the photo, so it needs a connection. Storage only accepts the photo once its + * message is on the server, so the message and the conversation update are written first, then + * the photo is compressed and uploaded. Until the upload ends, the other participant may see the + * message before its photo can be downloaded. * - * Throws when signed out (UNAUTHENTICATED), when the upload fails (a Storage error, to map with - * toAppError) or takes too long, as offline (an AppException with NETWORK), and - * IllegalArgumentException when the user is not a participant, when the conversation has no - * message yet (a photo cannot open a conversation), or when the caption is not sendable. When it - * throws, nothing is written. + * Throws when signed out (UNAUTHENTICATED), when offline or when the send takes too long (an + * error that maps to NETWORK with toAppError), when the server rejects the message (a Firestore + * error) or the upload (a Storage error), and IllegalArgumentException when the user is not a + * participant, when the conversation has no message yet (a photo cannot open a conversation), or + * when the caption is not sendable. Signed out, offline, or for an IllegalArgumentException, + * nothing is written. After a failed upload the message stays: retrying with the same [messageId] + * only uploads the photo. * * @param conversation the conversation from [observeConversation]. * @param messageId from [newMessageId]; pass the same one to retry a failed send. * @param caption optional text sent with the photo; null or blank sends the photo alone, which * previews as an empty lastMessageText. - * @param onWriteFailure as for [sendMessage]. */ suspend fun sendPhoto( conversation: Conversation, messageId: String, photo: Uri, caption: String? = null, - onWriteFailure: (Exception) -> Unit = {}, ) /** 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 7326f853..a44db631 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 @@ -16,6 +16,8 @@ import com.google.firebase.firestore.FirebaseFirestore import com.google.firebase.firestore.FirebaseFirestoreException import com.google.firebase.firestore.Query import com.google.firebase.firestore.SetOptions +import com.google.firebase.firestore.Source +import com.google.firebase.firestore.WriteBatch import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageException import com.google.firebase.storage.StorageReference @@ -32,15 +34,15 @@ import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withTimeout /** - * @param uploadTimeout how long a photo upload may take before it fails with NETWORK, rather than - * the Storage SDK retrying for minutes while offline. + * @param photoSendTimeout how long sending a photo (its message, then its upload) may take before + * it fails with NETWORK, rather than the Storage SDK retrying for minutes while offline. */ class FirebaseChatRepository( private val photoCompressor: PhotoCompressor, private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance(), private val auth: FirebaseAuth = FirebaseAuth.getInstance(), private val storage: FirebaseStorage = FirebaseStorage.getInstance(), - private val uploadTimeout: Duration = 30.seconds, + private val photoSendTimeout: Duration = 30.seconds, private val logWriteFailure: (Exception) -> Unit = { Log.e("ChatRepository", "Chat write failed", it) }, @@ -57,14 +59,19 @@ class FirebaseChatRepository( } val messageRef = conversationDocument(conversation.id).collection(MESSAGES).document() val trimmed = text.trim() - writeMessage( - conversation, - messageRef, - senderUid, - preview = trimmed, - messageFields = mapOf("text" to trimmed), - onWriteFailure, - ) + // Not awaited: the write is queued, so a text can be sent offline. + messageBatch( + conversation, + messageRef, + senderUid, + preview = trimmed, + messageFields = mapOf("text" to trimmed), + ) + .commit() + .addOnFailureListener(Executor { it.run() }) { + logWriteFailure(it) + onWriteFailure(it) + } } override fun newMessageId(conversationId: String): String = @@ -75,7 +82,6 @@ class FirebaseChatRepository( messageId: String, photo: Uri, caption: String?, - onWriteFailure: (Exception) -> Unit, ) { val senderUid = participantUid(conversation) // Storage only accepts a chat photo once the conversation exists. @@ -92,28 +98,43 @@ class FirebaseChatRepository( } ?.trim() val path = photoPath(conversation.id, messageId) + val messageRef = conversationDocument(conversation.id).collection(MESSAGES).document(messageId) val photoRef = storage.reference.child(path) - // Awaited: the message must not point to a photo that was never uploaded. Offline, the Storage - // SDK keeps retrying for minutes, so the user is told sooner that the photo was not sent. + // storage.rules only accept the upload once the server has the message that names the photo, + // so the message is written and confirmed first. Offline, the Storage SDK keeps retrying for + // minutes, so the user is told sooner that the photo was not sent. try { - withTimeout(uploadTimeout) { if (!exists(photoRef)) upload(photoRef, photo) } + withTimeout(photoSendTimeout) { + // Read from the server: offline it fails at once with UNAVAILABLE, rather than queuing a + // message that would reach the server later without its photo. A retry finds the message + // already written, and only uploads. + if (!messageRef.get(Source.SERVER).await().exists()) { + val batch = + messageBatch( + conversation, + messageRef, + senderUid, + // A photo alone previews as an empty text. + preview = trimmedCaption ?: "", + messageFields = + buildMap { + put("imagePath", path) + trimmedCaption?.let { put("text", it) } + }, + ) + try { + batch.commit().await() + } catch (e: FirebaseFirestoreException) { + logWriteFailure(e) + throw e + } + } + if (!exists(photoRef)) upload(photoRef, photo) + } } catch (e: TimeoutCancellationException) { // A CancellationException, which callers would take for their own cancellation and ignore. throw AppException(AppError.NETWORK, e) } - writeMessage( - conversation, - conversationDocument(conversation.id).collection(MESSAGES).document(messageId), - senderUid, - // A photo alone previews as an empty text. - preview = trimmedCaption ?: "", - messageFields = - buildMap { - put("imagePath", path) - trimmedCaption?.let { put("text", it) } - }, - onWriteFailure, - ) } override suspend fun loadMessagePhoto(imagePath: String): ByteArray = @@ -215,17 +236,16 @@ class FirebaseChatRepository( } /** - * Queues the message at [messageRef] with [messageFields], plus its sender and time, and updates - * the conversation's preview to [preview], in one batch that is not awaited. + * The batch that writes the message at [messageRef] with [messageFields], plus its sender and + * time, and updates the conversation's preview to [preview]. Not committed yet. */ - private suspend fun writeMessage( + private suspend fun messageBatch( conversation: Conversation, messageRef: DocumentReference, senderUid: String, preview: String, messageFields: Map, - onWriteFailure: (Exception) -> Unit, - ) { + ): WriteBatch { val conversationFields = mutableMapOf( "listingId" to conversation.listingId, @@ -247,7 +267,7 @@ class FirebaseChatRepository( // outdated. conversationFields["listingTitle"] = currentListingTitle(conversation.listingId) } - firestore + return firestore .batch() // A merge leaves unchanged fields out of the rules' affected keys, so the same write // creates the conversation on the first message and only bumps it on later ones. @@ -257,11 +277,6 @@ class FirebaseChatRepository( mapOf("senderUid" to senderUid, "sentAt" to FieldValue.serverTimestamp()) + messageFields, ) - .commit() - .addOnFailureListener(Executor { it.run() }) { - logWriteFailure(it) - onWriteFailure(it) - } } private suspend fun currentListingTitle(listingId: String): String { 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 f28a452e..a84845c0 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 @@ -26,8 +26,9 @@ import kotlinx.coroutines.flow.map * look at a send in progress, and throws [sendFailure] if set, like a send refused before queuing; * such a call is still recorded. * - * [sendPhoto] works the same way with [sentPhotos] and [photoWriteFailureCallbacks], sharing [gate] - * and [sendFailure]. [newMessageId] returns "m1", "m2", … in call order. + * [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. * * [loadMessagePhoto] returns the bytes stored in [photos] for the path, and throws * [photoLoadFailure] if set, or when the path is not in [photos]. @@ -65,9 +66,6 @@ class FakeChatRepository( /** The calls to [sendPhoto], in order. */ val sentPhotos = mutableListOf() - /** The `onWriteFailure` callbacks passed to [sendPhoto], in order. */ - val photoWriteFailureCallbacks = mutableListOf<(Exception) -> Unit>() - /** The photos [loadMessagePhoto] returns, by Storage path. */ val photos = mutableMapOf() @@ -108,10 +106,8 @@ class FakeChatRepository( messageId: String, photo: Uri, caption: String?, - onWriteFailure: (Exception) -> Unit, ) { sentPhotos += SentPhoto(conversation, messageId, photo, caption) - photoWriteFailureCallbacks += onWriteFailure gate?.await() sendFailure?.let { throw it } } 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 8fc552b7..670397d4 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 @@ -23,6 +23,7 @@ import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.Query import com.google.firebase.firestore.QuerySnapshot import com.google.firebase.firestore.SetOptions +import com.google.firebase.firestore.Source import com.google.firebase.firestore.WriteBatch import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageException @@ -122,6 +123,10 @@ class FirebaseChatRepositoryTest { whenever(listing.getString("title")).thenReturn("Drill") whenever(messages.document(PHOTO_ID)).thenReturn(photoMessageRef) whenever(photoMessageRef.id).thenReturn(PHOTO_ID) + // By default the photo's message is not on the server yet, as for a first try. + val notWritten = mock() + whenever(notWritten.exists()).thenReturn(false) + whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(notWritten)) whenever(storage.reference).thenReturn(storageRoot) whenever(storageRoot.child(PHOTO_PATH)).thenReturn(photoRef) val notUploaded = storageException(StorageException.ERROR_OBJECT_NOT_FOUND) @@ -415,12 +420,28 @@ class FirebaseChatRepositoryTest { } @Test - fun sendPhotoUploadsBeforeCommittingTheBatch() = runTest { + fun sendPhotoChecksTheServerThenCommitsTheMessageBeforeUploading() = runTest { repository.sendPhoto(replied, PHOTO_ID, photo) - val order = inOrder(photoRef, batch) - order.verify(photoRef).putBytes(any(), any()) + // storage.rules only accept the upload once the server has the message. + val order = inOrder(photoMessageRef, batch, photoRef) + order.verify(photoMessageRef).get(Source.SERVER) order.verify(batch).commit() + order.verify(photoRef).putBytes(any(), any()) + } + + @Test + fun sendPhotoWaitsForTheServerToConfirmTheMessageBeforeUploading() = runTest { + val pendingWrite = TaskCompletionSource() + whenever(batch.commit()).thenReturn(pendingWrite.task) + val sending = async { repository.sendPhoto(replied, PHOTO_ID, photo) } + runCurrent() + + verify(photoRef, never()).putBytes(any(), any()) + pendingWrite.setResult(null) + sending.await() + + verify(photoRef).putBytes(any(), any()) } @Test @@ -485,21 +506,64 @@ class FirebaseChatRepositoryTest { } @Test - fun sendPhotoReportsLaterWriteFailuresToBothCallbacks() = runTest { - val pendingWrite = TaskCompletionSource() - whenever(batch.commit()).thenReturn(pendingWrite.task) - var reportedFailure: Exception? = null + fun sendPhotoRejectedMessageIsLoggedAndThrownAndNothingIsUploaded() = runTest { + val failure = + FirebaseFirestoreException( + "Missing or insufficient permissions.", + FirebaseFirestoreException.Code.PERMISSION_DENIED, + ) + whenever(batch.commit()).thenReturn(Tasks.forException(failure)) + var logged: Exception? = null val repository = - FirebaseChatRepository(photoCompressor, firestore, auth, storage) { reportedFailure = it } - var reportedToCaller: Exception? = null + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { logged = it } - repository.sendPhoto(replied, PHOTO_ID, photo) { reportedToCaller = it } - assertNull(reportedFailure) - val failure = IllegalStateException("Write rejected") - pendingWrite.setException(failure) + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() - assertSame(failure, reportedFailure) - assertSame(failure, reportedToCaller) + assertSame(failure, logged) + assertEquals(AppError.PERMISSION_DENIED, error?.toAppError()) + verify(photoRef, never()).putBytes(any(), any()) + } + + @Test + fun sendPhotoOfflineFailsWithNetworkBeforeWritingOrUploadingAnything() = runTest { + val offline = + FirebaseFirestoreException( + "Failed to get document from server.", + FirebaseFirestoreException.Code.UNAVAILABLE, + ) + whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forException(offline)) + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertEquals(AppError.NETWORK, error?.toAppError()) + // Nothing queued: an offline write would reach the server later without its photo. + verify(firestore, never()).batch() + verify(photoRef, never()).putBytes(any(), any()) + } + + @Test + fun sendPhotoMessageWithNoServerAnswerFailsWithNetworkAfterTimeoutWithoutUploading() = runTest { + whenever(batch.commit()).thenReturn(TaskCompletionSource().task) + + val error = runCatching { + shortTimeoutRepository().sendPhoto(replied, PHOTO_ID, photo) + } + .exceptionOrNull() + + assertEquals(AppError.NETWORK, (error as AppException).error) + assertEquals(5_000L, testScheduler.currentTime) + verify(photoRef, never()).putBytes(any(), any()) + } + + @Test + fun sendPhotoRetryAfterFailedUploadOnlyUploadsWithoutRewritingTheMessage() = runTest { + messageAlreadyOnServer() + + repository.sendPhoto(replied, PHOTO_ID, photo) + + // The rules refuse rewriting a message, and the conversation already names it. + verify(firestore, never()).batch() + verify(photoRef).putBytes(eq(compressedPhoto), any()) } @Test @@ -546,7 +610,7 @@ class FirebaseChatRepositoryTest { } @Test - fun sendPhotoOfflineUploadFailureIsNetworkAndWritesNoBatch() = runTest { + fun sendPhotoUploadFailureOfflineIsNetworkAfterTheMessageIsWritten() = runTest { val failure = storageException(StorageException.ERROR_RETRY_LIMIT_EXCEEDED) failUpload(failure) @@ -554,11 +618,12 @@ class FirebaseChatRepositoryTest { assertSame(failure, error) assertEquals(AppError.NETWORK, error?.toAppError()) - verify(firestore, never()).batch() + // Kept: a retry with the same ID only uploads. + verify(batch).commit() } @Test - fun sendPhotoRefusedUploadIsPermissionDeniedAndWritesNoBatch() = runTest { + fun sendPhotoRefusedUploadIsPermissionDenied() = runTest { val failure = storageException(StorageException.ERROR_NOT_AUTHORIZED) failUpload(failure) @@ -566,11 +631,10 @@ class FirebaseChatRepositoryTest { assertSame(failure, error) assertEquals(AppError.PERMISSION_DENIED, error?.toAppError()) - verify(firestore, never()).batch() } @Test - fun sendPhotoCompressionFailureUploadsAndWritesNothing() = runTest { + fun sendPhotoCompressionFailureUploadsNothing() = runTest { val repository = FirebaseChatRepository( { throw IllegalStateException("Unreadable photo") }, @@ -585,11 +649,11 @@ class FirebaseChatRepositoryTest { assertTrue(error is IllegalStateException) assertEquals("Unreadable photo", error?.message) verify(photoRef, never()).putBytes(any(), any()) - verify(firestore, never()).batch() } @Test - fun sendPhotoRetryReusesStoredPhotoWithoutCompressingOrUploading() = runTest { + fun sendPhotoRetryWithMessageAndPhotoStoredWritesAndUploadsNothing() = runTest { + messageAlreadyOnServer() val stored = mock() whenever(photoRef.metadata).thenReturn(Tasks.forResult(stored)) var compressions = 0 @@ -608,16 +672,7 @@ class FirebaseChatRepositoryTest { assertEquals(0, compressions) verify(photoRef, never()).putBytes(any(), any()) - verifyPhotoBatch( - preview = "The drill bits", - message = - mapOf( - "senderUid" to "renter", - "sentAt" to FieldValue.serverTimestamp(), - "imagePath" to PHOTO_PATH, - "text" to "The drill bits", - ), - ) + verify(firestore, never()).batch() } @Test @@ -630,7 +685,7 @@ class FirebaseChatRepositoryTest { } @Test - fun sendPhotoRethrowsOtherStoredPhotoCheckFailuresAndSendsNothing() = runTest { + fun sendPhotoRethrowsOtherStoredPhotoCheckFailuresWithoutUploading() = runTest { val failure = storageException(StorageException.ERROR_NOT_AUTHORIZED) whenever(photoRef.metadata).thenReturn(Tasks.forException(failure)) @@ -638,7 +693,6 @@ class FirebaseChatRepositoryTest { assertSame(failure, error) verify(photoRef, never()).putBytes(any(), any()) - verify(firestore, never()).batch() } @Test @@ -654,7 +708,6 @@ class FirebaseChatRepositoryTest { assertTrue(error.cause is TimeoutCancellationException) assertEquals(5_000L, testScheduler.currentTime) verify(uploadTask).cancel() - verify(firestore, never()).batch() } @Test @@ -668,7 +721,6 @@ class FirebaseChatRepositoryTest { assertEquals(AppError.NETWORK, (error as AppException).error) verify(photoRef, never()).putBytes(any(), any()) - verify(firestore, never()).batch() } @Test @@ -693,7 +745,6 @@ class FirebaseChatRepositoryTest { assertTrue(thrown is CancellationException) assertFalse(thrown is TimeoutCancellationException) verify(uploadTask).cancel() - verify(firestore, never()).batch() } @Test @@ -1121,7 +1172,20 @@ class FirebaseChatRepositoryTest { } private fun shortTimeoutRepository() = - FirebaseChatRepository(photoCompressor, firestore, auth, storage, uploadTimeout = 5.seconds) + FirebaseChatRepository( + photoCompressor, + firestore, + auth, + storage, + photoSendTimeout = 5.seconds, + ) + + /** Puts the photo's message on the server, as after a send whose upload failed. */ + private fun messageAlreadyOnServer() { + val written = mock() + whenever(written.exists()).thenReturn(true) + whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(written)) + } /** Makes the photo upload end with [failure]. */ private fun failUpload(failure: Exception) { From 96f3d61fb69dd05bf18fdb32f358e6a9a0006ca0 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 02:26:22 +0100 Subject: [PATCH 12/27] fix(chat): compress a photo before sending its message A photo that can't be read now sends nothing, and a slow compression no longer counts against the 30 s network timeout. Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepository.kt | 11 +++++--- .../chat/model/FirebaseChatRepositoryTest.kt | 27 ++++++++++++------- 2 files changed, 25 insertions(+), 13 deletions(-) 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 a44db631..ddd2df46 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 @@ -97,6 +97,9 @@ class FirebaseChatRepository( } } ?.trim() + // First, so a photo that can't be compressed sends nothing. Outside the timeout, which is for + // the network: a large photo compressing slowly must not be reported as offline. + val compressed = photoCompressor.compress(photo) val path = photoPath(conversation.id, messageId) val messageRef = conversationDocument(conversation.id).collection(MESSAGES).document(messageId) val photoRef = storage.reference.child(path) @@ -129,7 +132,7 @@ class FirebaseChatRepository( throw e } } - if (!exists(photoRef)) upload(photoRef, photo) + if (!exists(photoRef)) upload(photoRef, compressed) } } catch (e: TimeoutCancellationException) { // A CancellationException, which callers would take for their own cancellation and ignore. @@ -304,9 +307,9 @@ class FirebaseChatRepository( false } - /** Uploads the compressed [photo] to [ref], and cancels the upload if the caller is cancelled. */ - private suspend fun upload(ref: StorageReference, photo: Uri) { - val task = ref.putBytes(photoCompressor.compress(photo), PhotoStorage.JPEG_METADATA) + /** Uploads the [jpeg] bytes to [ref], and cancels the upload if the caller is cancelled. */ + private suspend fun upload(ref: StorageReference, jpeg: ByteArray) { + val task = ref.putBytes(jpeg, PhotoStorage.JPEG_METADATA) try { task.await() } catch (e: CancellationException) { 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 670397d4..66792ceb 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 @@ -35,6 +35,7 @@ import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CancellationException import kotlinx.coroutines.TimeoutCancellationException import kotlinx.coroutines.async +import kotlinx.coroutines.delay import kotlinx.coroutines.flow.first import kotlinx.coroutines.launch import kotlinx.coroutines.test.TestScope @@ -634,7 +635,7 @@ class FirebaseChatRepositoryTest { } @Test - fun sendPhotoCompressionFailureUploadsNothing() = runTest { + fun sendPhotoCompressionFailureWritesAndUploadsNothing() = runTest { val repository = FirebaseChatRepository( { throw IllegalStateException("Unreadable photo") }, @@ -648,29 +649,37 @@ class FirebaseChatRepositoryTest { // Not assertSame: coroutine stack-trace recovery may rethrow a copy of it. assertTrue(error is IllegalStateException) assertEquals("Unreadable photo", error?.message) - verify(photoRef, never()).putBytes(any(), any()) + verify(photoMessageRef, never()).get(any()) + verifyNothingSent() } @Test - fun sendPhotoRetryWithMessageAndPhotoStoredWritesAndUploadsNothing() = runTest { - messageAlreadyOnServer() - val stored = mock() - whenever(photoRef.metadata).thenReturn(Tasks.forResult(stored)) - var compressions = 0 + fun sendPhotoSlowCompressionDoesNotCountAgainstTheTimeout() = runTest { val repository = FirebaseChatRepository( { - compressions++ + delay(10.seconds) compressedPhoto }, firestore, auth, storage, + photoSendTimeout = 5.seconds, ) + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(photoRef).putBytes(eq(compressedPhoto), any()) + } + + @Test + fun sendPhotoRetryWithMessageAndPhotoStoredWritesAndUploadsNothing() = runTest { + messageAlreadyOnServer() + val stored = mock() + whenever(photoRef.metadata).thenReturn(Tasks.forResult(stored)) + repository.sendPhoto(replied, PHOTO_ID, photo, caption = "The drill bits") - assertEquals(0, compressions) verify(photoRef, never()).putBytes(any(), any()) verify(firestore, never()).batch() } From a0c453d2816c32fd2d3192b24a163a3ee78969f2 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 02:28:08 +0100 Subject: [PATCH 13/27] fix(chat): report a photo that can't be read as not found A deleted photo, one that isn't an image, or one the app can no longer read now fails sendPhoto with NOT_FOUND instead of an unmapped error. Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/ChatRepository.kt | 11 ++++--- .../chat/model/FirebaseChatRepository.kt | 12 ++++++- .../chat/model/FirebaseChatRepositoryTest.kt | 32 +++++++++++++++++++ 3 files changed, 49 insertions(+), 6 deletions(-) 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 9cae988d..f0e60719 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 @@ -38,11 +38,12 @@ interface ChatRepository { * * Throws when signed out (UNAUTHENTICATED), when offline or when the send takes too long (an * error that maps to NETWORK with toAppError), when the server rejects the message (a Firestore - * error) or the upload (a Storage error), and IllegalArgumentException when the user is not a - * participant, when the conversation has no message yet (a photo cannot open a conversation), or - * when the caption is not sendable. Signed out, offline, or for an IllegalArgumentException, - * nothing is written. After a failed upload the message stays: retrying with the same [messageId] - * only uploads the photo. + * error) or the upload (a Storage error), when the photo can't be read, as when it was deleted or + * is not an image (an AppException with NOT_FOUND), and IllegalArgumentException when the user is + * not a participant, when the conversation has no message yet (a photo cannot open a + * conversation), or when the caption is not sendable. Signed out, offline, for an unreadable + * photo, or for an IllegalArgumentException, nothing is written. After a failed upload the + * message stays: retrying with the same [messageId] only uploads the photo. * * @param conversation the conversation from [observeConversation]. * @param messageId from [newMessageId]; pass the same one to retry a failed send. 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 ddd2df46..9f611df3 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 @@ -21,6 +21,7 @@ import com.google.firebase.firestore.WriteBatch import com.google.firebase.storage.FirebaseStorage import com.google.firebase.storage.StorageException import com.google.firebase.storage.StorageReference +import java.io.IOException import java.time.Instant import java.util.concurrent.Executor import kotlin.time.Duration @@ -99,7 +100,16 @@ class FirebaseChatRepository( ?.trim() // First, so a photo that can't be compressed sends nothing. Outside the timeout, which is for // the network: a large photo compressing slowly must not be reported as offline. - val compressed = photoCompressor.compress(photo) + val compressed = + try { + photoCompressor.compress(photo) + } catch (e: IOException) { + // Deleted, on storage that's gone, or not an image. + throw AppException(AppError.NOT_FOUND, e) + } catch (e: SecurityException) { + // The app lost its permission to read the photo. + throw AppException(AppError.NOT_FOUND, e) + } val path = photoPath(conversation.id, messageId) val messageRef = conversationDocument(conversation.id).collection(MESSAGES).document(messageId) val photoRef = storage.reference.child(path) 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 66792ceb..e9cc4e26 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 @@ -30,6 +30,7 @@ import com.google.firebase.storage.StorageException import com.google.firebase.storage.StorageMetadata import com.google.firebase.storage.StorageReference import com.google.firebase.storage.UploadTask +import java.io.FileNotFoundException import java.time.Instant import kotlin.time.Duration.Companion.seconds import kotlinx.coroutines.CancellationException @@ -653,6 +654,34 @@ class FirebaseChatRepositoryTest { verifyNothingSent() } + @Test + fun sendPhotoUnreadablePhotoIsNotFoundAndSendsNothing() = runTest { + val failure = FileNotFoundException("Deleted photo") + + val error = runCatching { + compressorFailing(failure).sendPhoto(replied, PHOTO_ID, photo) + } + .exceptionOrNull() + + assertEquals(AppError.NOT_FOUND, (error as AppException).error) + assertSame(failure, error.cause) + verifyNothingSent() + } + + @Test + fun sendPhotoWithoutPermissionToReadThePhotoIsNotFoundAndSendsNothing() = runTest { + val failure = SecurityException("Permission revoked") + + val error = runCatching { + compressorFailing(failure).sendPhoto(replied, PHOTO_ID, photo) + } + .exceptionOrNull() + + assertEquals(AppError.NOT_FOUND, (error as AppException).error) + assertSame(failure, error.cause) + verifyNothingSent() + } + @Test fun sendPhotoSlowCompressionDoesNotCountAgainstTheTimeout() = runTest { val repository = @@ -1180,6 +1209,9 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).batch() } + private fun compressorFailing(failure: Exception) = + FirebaseChatRepository({ throw failure }, firestore, auth, storage) + private fun shortTimeoutRepository() = FirebaseChatRepository( photoCompressor, From cb3713fdf6dcaeeedc6e1882387cb7d0e8a52e0a Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 02:29:31 +0100 Subject: [PATCH 14/27] docs(chat): say which rules order a photo message's writes The comments still described the rules from before #350 changed: a photo can't open a conversation because of firestore.rules, and Storage only accepts the upload from the sender of the message that names it. Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/FirebaseChatRepository.kt | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) 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 9f611df3..5522d520 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 @@ -85,7 +85,7 @@ class FirebaseChatRepository( caption: String?, ) { val senderUid = participantUid(conversation) - // Storage only accepts a chat photo once the conversation exists. + // firestore.rules only accept a message with a photo in a conversation that already exists. require(conversation.lastMessageAt != null) { "A photo cannot be the first message of a conversation" } @@ -304,7 +304,7 @@ class FirebaseChatRepository( private fun conversationDocument(id: String) = firestore.collection(CONVERSATIONS).document(id) /** - * Whether a file is already at [ref], like a photo uploaded by a send whose batch then failed. + * Whether a file is already at [ref], like a photo whose upload ended after its send timed out. * The rules allow a chat photo to be created only once, so a retry with the same message ID must * reuse that file rather than upload it again. */ @@ -329,7 +329,10 @@ class FirebaseChatRepository( } } - /** Where a message's photo is stored; storage.rules only accept a participant's upload there. */ + /** + * Where a message's photo is stored: the imagePath its message names. storage.rules only accept + * an upload there from that message's sender. + */ private fun photoPath(conversationId: String, messageId: String) = "$CONVERSATIONS/$conversationId/$messageId.jpg" From fecfb37848e160b2dd929b158f7272a3de1f93c1 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 02:31:50 +0100 Subject: [PATCH 15/27] fix(chat): stop loading a photo after 30 s offline loadMessagePhoto now fails with NETWORK after the same timeout as sendPhoto, instead of waiting through the Storage SDK's retries. Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/ChatRepository.kt | 5 +- .../chat/model/FirebaseChatRepository.kt | 77 +++++++++++-------- .../chat/model/FirebaseChatRepositoryTest.kt | 18 ++++- 3 files changed, 62 insertions(+), 38 deletions(-) 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 f0e60719..60ff036d 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 @@ -59,8 +59,9 @@ interface ChatRepository { /** * 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, and with - * a Storage error to map with toAppError otherwise. + * Fails with PERMISSION_DENIED for a user who is not a participant of the conversation, with an + * AppException with NETWORK when it takes too long, as offline, and with a Storage error to map + * with toAppError otherwise. */ suspend fun loadMessagePhoto(imagePath: String): ByteArray 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 5522d520..4a31bfec 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 @@ -35,15 +35,16 @@ import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withTimeout /** - * @param photoSendTimeout how long sending a photo (its message, then its upload) may take before - * it fails with NETWORK, rather than the Storage SDK retrying for minutes while offline. + * @param photoTimeout how long sending a photo (its message, then its upload) or loading one may + * take before it fails with NETWORK, rather than the Storage SDK retrying for minutes while + * offline. */ class FirebaseChatRepository( private val photoCompressor: PhotoCompressor, private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance(), private val auth: FirebaseAuth = FirebaseAuth.getInstance(), private val storage: FirebaseStorage = FirebaseStorage.getInstance(), - private val photoSendTimeout: Duration = 30.seconds, + private val photoTimeout: Duration = 30.seconds, private val logWriteFailure: (Exception) -> Unit = { Log.e("ChatRepository", "Chat write failed", it) }, @@ -116,42 +117,38 @@ class FirebaseChatRepository( // storage.rules only accept the upload once the server has the message that names the photo, // so the message is written and confirmed first. Offline, the Storage SDK keeps retrying for // minutes, so the user is told sooner that the photo was not sent. - try { - withTimeout(photoSendTimeout) { - // Read from the server: offline it fails at once with UNAVAILABLE, rather than queuing a - // message that would reach the server later without its photo. A retry finds the message - // already written, and only uploads. - if (!messageRef.get(Source.SERVER).await().exists()) { - val batch = - messageBatch( - conversation, - messageRef, - senderUid, - // A photo alone previews as an empty text. - preview = trimmedCaption ?: "", - messageFields = - buildMap { - put("imagePath", path) - trimmedCaption?.let { put("text", it) } - }, - ) - try { - batch.commit().await() - } catch (e: FirebaseFirestoreException) { - logWriteFailure(e) - throw e - } + withNetworkTimeout { + // Read from the server: offline it fails at once with UNAVAILABLE, rather than queuing a + // message that would reach the server later without its photo. A retry finds the message + // already written, and only uploads. + if (!messageRef.get(Source.SERVER).await().exists()) { + val batch = + messageBatch( + conversation, + messageRef, + senderUid, + // A photo alone previews as an empty text. + preview = trimmedCaption ?: "", + messageFields = + buildMap { + put("imagePath", path) + trimmedCaption?.let { put("text", it) } + }, + ) + try { + batch.commit().await() + } catch (e: FirebaseFirestoreException) { + logWriteFailure(e) + throw e } - if (!exists(photoRef)) upload(photoRef, compressed) } - } catch (e: TimeoutCancellationException) { - // A CancellationException, which callers would take for their own cancellation and ignore. - throw AppException(AppError.NETWORK, e) + if (!exists(photoRef)) upload(photoRef, compressed) } } - override suspend fun loadMessagePhoto(imagePath: String): ByteArray = - storage.reference.child(imagePath).getBytes(PhotoStorage.MAX_PHOTO_BYTES).await() + override suspend fun loadMessagePhoto(imagePath: String): ByteArray = withNetworkTimeout { + storage.reference.child(imagePath).getBytes(PhotoStorage.MAX_PHOTO_BYTES).await() + } override fun markRead(conversationId: String) { val uid = auth.currentUser?.uid ?: return @@ -317,6 +314,18 @@ class FirebaseChatRepository( false } + /** + * Runs [block], and fails with NETWORK if it takes longer than [photoTimeout], as offline when + * the Storage SDK keeps retrying. + */ + private suspend fun withNetworkTimeout(block: suspend () -> T): T = + try { + withTimeout(photoTimeout) { block() } + } catch (e: TimeoutCancellationException) { + // A CancellationException, which callers would take for their own cancellation and ignore. + throw AppException(AppError.NETWORK, e) + } + /** Uploads the [jpeg] bytes to [ref], and cancels the upload if the caller is cancelled. */ private suspend fun upload(ref: StorageReference, jpeg: ByteArray) { val task = ref.putBytes(jpeg, PhotoStorage.JPEG_METADATA) 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 e9cc4e26..3d39aa7c 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 @@ -693,7 +693,7 @@ class FirebaseChatRepositoryTest { firestore, auth, storage, - photoSendTimeout = 5.seconds, + photoTimeout = 5.seconds, ) repository.sendPhoto(replied, PHOTO_ID, photo) @@ -816,6 +816,20 @@ class FirebaseChatRepositoryTest { assertEquals(AppError.PERMISSION_DENIED, error?.toAppError()) } + @Test + fun loadMessagePhotoWithNoAnswerFailsWithNetworkAfterTimeout() = runTest { + whenever(photoRef.getBytes(any())).thenReturn(TaskCompletionSource().task) + + val error = runCatching { + shortTimeoutRepository().loadMessagePhoto(PHOTO_PATH) + } + .exceptionOrNull() + + assertEquals(AppError.NETWORK, (error as AppException).error) + assertTrue(error.cause is TimeoutCancellationException) + assertEquals(5_000L, testScheduler.currentTime) + } + @Test fun markReadSetsOnlyMyReadTimeToServerTime() { whenever(conversationRef.update(any(), any(), anyVararg())) @@ -1218,7 +1232,7 @@ class FirebaseChatRepositoryTest { firestore, auth, storage, - photoSendTimeout = 5.seconds, + photoTimeout = 5.seconds, ) /** Puts the photo's message on the server, as after a send whose upload failed. */ From c14b569c46425a1666562431be53275a2cb75d64 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:29:42 +0100 Subject: [PATCH 16/27] feat(chat): let the sender mark a photo message's photo as uploaded Co-Authored-By: Claude Opus 5.5 --- firestore.rules | 24 ++++++++-- rules-tests/firestore.test.js | 86 ++++++++++++++++++++++++++++++++++- 2 files changed, 105 insertions(+), 5 deletions(-) diff --git a/firestore.rules b/firestore.rules index e9a4ba70..0d238c9d 100644 --- a/firestore.rules +++ b/firestore.rules @@ -240,29 +240,45 @@ service cloud.firestore { // getAfter, because the first message creates the conversation in the same batch. Requiring // the conversation to name this message allows one message per batch. A message has a text, // a photo, or both (a photo with a caption). exists sees the state before the batch, so a - // photo cannot open a conversation; the app sends a text first. + // photo cannot open a conversation; the app sends a text first. A photo message is written + // before its photo is uploaded, so it starts with photoPending true; a text never has it. function validMessage(data) { let conversation = getAfter(conversationPath()).data; return request.auth.uid in conversation.participants && conversation.lastMessageAt == request.time && conversation.lastMessageId == messageId && data.keys().hasAll(['senderUid', 'sentAt']) - && data.keys().hasOnly(['senderUid', 'text', 'sentAt', 'imagePath']) + && data.keys().hasOnly(['senderUid', 'text', 'sentAt', 'imagePath', 'photoPending']) && data.keys().hasAny(['text', 'imagePath']) && data.senderUid == request.auth.uid && data.sentAt == request.time && (!('text' in data) || validText(data.text)) + && ('imagePath' in data) == ('photoPending' in data) && (!('imagePath' in data) - || (exists(conversationPath()) && validImagePath(data.imagePath))) + || (exists(conversationPath()) + && validImagePath(data.imagePath) + && data.photoPending == true)) && listingData(conversation.listingId).ownerUid == conversation.lenderUid; } + // Once the photo is uploaded, its sender marks it so, once: photoPending goes from true to + // false and nothing else changes. Rules cannot see Storage, so the app marks it only after + // the upload ends. + function isPhotoUploaded() { + return resource.data.senderUid == request.auth.uid + && resource.data.get('photoPending', false) == true + && request.resource.data.diff(resource.data).affectedKeys().hasOnly(['photoPending']) + && request.resource.data.photoPending == false; + } + allow read: if isVerified() && (isRenterInId() || get(conversationPath()).data.lenderUid == request.auth.uid); allow create: if isVerified() && validMessage(request.resource.data); - allow update, delete: if false; + allow update: if isVerified() && isPhotoUploaded(); + + allow delete: if false; } } diff --git a/rules-tests/firestore.test.js b/rules-tests/firestore.test.js index c2ab2f82..26bd7ee8 100644 --- a/rules-tests/firestore.test.js +++ b/rules-tests/firestore.test.js @@ -946,7 +946,8 @@ const photoPath = (conversationId, messageId) => `conversations/${conversationId /** * A photo message for sendMessage: no text unless it has a caption, and by default the photo at - * the message's own path in Bob's conversation. `imagePath` maps the message id to the stored path. + * the message's own path in Bob's conversation, still being uploaded. `imagePath` maps the message + * id to the stored path. */ function photoMessage( senderUid, @@ -956,6 +957,7 @@ function photoMessage( senderUid, sentAt: serverTimestamp(), imagePath: imagePath(messageId), + photoPending: true, ...(caption === undefined ? {} : { text: caption }), ...extra, }); @@ -1601,4 +1603,86 @@ describe("photo messages", () => { await assertFails(updateDoc(ref, { text: "Caption" })); await assertFails(deleteDoc(ref)); }); + + test("a photo message is sent with its photo pending", async () => { + await seedConversation(); + const db = verified(BOB); + for (const photoPending of [false, "true", null]) { + const message = photoMessage(BOB, { extra: { photoPending } }); + await assertFails(sendMessage(db, BOB, { message })); + } + const withoutPending = (messageId) => { + const { photoPending, ...message } = photoMessage(BOB)(messageId); + return message; + }; + await assertFails(sendMessage(db, BOB, { message: withoutPending })); + }); + + test("a text message has no pending photo", async () => { + await seedConversation(); + for (const photoPending of [true, false]) { + await assertFails(sendMessage(verified(BOB), BOB, { message: { photoPending } })); + } + }); +}); + +describe("pending photos", () => { + const PATH = `${CONVERSATION}/messages/m2`; + + /** Seeds Bob's photo message m2, sent earlier, with its photo still pending unless told so. */ + async function seedPhotoMessage(fields = { photoPending: true }) { + await seedConversation(); + await seed(PATH, { + senderUid: BOB, + imagePath: photoPath(CONVERSATION_ID, "m2"), + sentAt: new Date(0), + ...fields, + }); + } + + test("the sender can mark their photo uploaded", async () => { + await seedPhotoMessage(); + await assertSucceeds(updateDoc(doc(verified(BOB), PATH), { photoPending: false })); + }); + + test("a photo with a caption can be marked uploaded", async () => { + await seedPhotoMessage({ photoPending: true, text: "The drill bits" }); + await assertSucceeds(updateDoc(doc(verified(BOB), PATH), { photoPending: false })); + }); + + test("only the sender can mark their photo uploaded", async () => { + await seedPhotoMessage(); + await assertFails(updateDoc(doc(verified(ALICE), PATH), { photoPending: false })); + await assertFails(updateDoc(doc(verified(EVE), PATH), { photoPending: false })); + await assertFails(updateDoc(doc(unverified(BOB), PATH), { photoPending: false })); + }); + + test("a photo is marked uploaded only once", async () => { + await seedPhotoMessage({ photoPending: false }); + const ref = doc(verified(BOB), PATH); + await assertFails(updateDoc(ref, { photoPending: true })); + await assertFails(updateDoc(ref, { photoPending: false, text: "Caption" })); + }); + + test("a photo sent before photoPending existed cannot be marked", async () => { + await seedPhotoMessage({}); + await assertFails(updateDoc(doc(verified(BOB), PATH), { photoPending: false })); + }); + + test("marking a photo uploaded changes nothing else", async () => { + await seedPhotoMessage(); + const ref = doc(verified(BOB), PATH); + await assertFails(updateDoc(ref, { photoPending: false, text: "Caption" })); + await assertFails( + updateDoc(ref, { photoPending: false, imagePath: photoPath(CONVERSATION_ID, "m3") }), + ); + await assertFails(updateDoc(ref, { photoPending: false, sentAt: serverTimestamp() })); + await assertFails(updateDoc(ref, { photoPending: "false" })); + await assertFails(updateDoc(ref, { photoPending: deleteField() })); + }); + + test("a pending photo message cannot be deleted", async () => { + await seedPhotoMessage(); + await assertFails(deleteDoc(doc(verified(BOB), PATH))); + }); }); From f232a90375affbc4e3e7b44a1d95712266a9647d Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:31:20 +0100 Subject: [PATCH 17/27] feat(chat): read whether a message's photo is still uploading Co-Authored-By: Claude Opus 5.5 --- .../main/java/com/android/polybazaar/chat/model/ChatMessage.kt | 3 +++ .../android/polybazaar/chat/model/FirebaseChatRepository.kt | 2 ++ 2 files changed, 5 insertions(+) diff --git a/app/src/main/java/com/android/polybazaar/chat/model/ChatMessage.kt b/app/src/main/java/com/android/polybazaar/chat/model/ChatMessage.kt index ba272680..2f6bc056 100644 --- a/app/src/main/java/com/android/polybazaar/chat/model/ChatMessage.kt +++ b/app/src/main/java/com/android/polybazaar/chat/model/ChatMessage.kt @@ -11,6 +11,8 @@ import java.time.Instant * @property text trimmed message text, or "" for a photo-only message. * @property sentAt when the message was sent. * @property imagePath Storage path of the message's photo, or null for a text message. + * @property photoPending true while the sender has not finished uploading the photo: it can't be + * downloaded yet. It stays true if the upload never ends, as when the sender's app was closed. */ data class ChatMessage( val id: String, @@ -18,4 +20,5 @@ data class ChatMessage( val text: String, val sentAt: Instant, val imagePath: String? = null, + val photoPending: Boolean = false, ) 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 4a31bfec..fcf02a44 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 @@ -385,6 +385,8 @@ class FirebaseChatRepository( text = getString("text") ?: if (imagePath != null) "" else throw missing("text"), sentAt = instant("sentAt") ?: throw missing("sentAt"), imagePath = imagePath, + // Photos sent before the flag existed have none, and were uploaded. + photoPending = getBoolean("photoPending") ?: false, ) } From bff3b09af3446156493faf8c2b3ef7a39641fe2e Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:31:20 +0100 Subject: [PATCH 18/27] test(chat): cover reading a photo that is still uploading Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 31 +++++++++++++++++++ 1 file changed, 31 insertions(+) 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 3d39aa7c..5c62fdca 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 @@ -1097,6 +1097,35 @@ class FirebaseChatRepositoryTest { assertEquals(path, observed.imagePath) } + @Test + fun observeMessagesMapsPhotoStillUploadingAsPending() = runTest { + val path = "conversations/listing_renter/m1.jpg" + + val observed = + observeOnlyMessage(message("m1", "lender", null, 1_700_000_000, path, photoPending = true)) + + assertTrue(observed.photoPending) + } + + @Test + fun observeMessagesMapsUploadedPhotoAsNotPending() = runTest { + val path = "conversations/listing_renter/m1.jpg" + + val observed = + observeOnlyMessage(message("m1", "lender", null, 1_700_000_000, path, photoPending = false)) + + assertFalse(observed.photoPending) + } + + @Test + fun observeMessagesMapsPhotoWithoutPendingFieldAsNotPending() = runTest { + val path = "conversations/listing_renter/m1.jpg" + + val observed = observeOnlyMessage(message("m1", "lender", null, 1_700_000_000, path)) + + assertFalse(observed.photoPending) + } + @Test fun observeMessagesMapsTextMessageWithoutPhoto() = runTest { val observed = observeOnlyMessage(message("m1", "renter", "Hi", 1_700_000_000)) @@ -1274,12 +1303,14 @@ class FirebaseChatRepositoryTest { text: String?, sentAt: Long, imagePath: String? = null, + photoPending: Boolean? = null, ) = mock().also { whenever(it.id).thenReturn(id) whenever(it.getString("senderUid")).thenReturn(senderUid) whenever(it.getString("text")).thenReturn(text) whenever(it.getString("imagePath")).thenReturn(imagePath) + whenever(it.getBoolean("photoPending")).thenReturn(photoPending) whenever(timestampOf(it, "sentAt")).thenReturn(Timestamp(sentAt, 0)) } From ff14e21c69206bd4a8ba12442bc9d947cb123e56 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:35:10 +0100 Subject: [PATCH 19/27] feat(chat): mark a photo message's photo uploaded after sending it Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepository.kt | 30 ++++++++++++++----- .../chat/model/FirebaseChatRepositoryTest.kt | 5 ++++ 2 files changed, 27 insertions(+), 8 deletions(-) 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 fcf02a44..5b358cf2 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 @@ -7,6 +7,7 @@ import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.AppException import com.android.polybazaar.photo.PhotoCompressor import com.android.polybazaar.photo.PhotoStorage +import com.google.android.gms.tasks.Task import com.google.firebase.auth.FirebaseAuth import com.google.firebase.firestore.DocumentReference import com.google.firebase.firestore.DocumentSnapshot @@ -121,7 +122,10 @@ class FirebaseChatRepository( // Read from the server: offline it fails at once with UNAVAILABLE, rather than queuing a // message that would reach the server later without its photo. A retry finds the message // already written, and only uploads. - if (!messageRef.get(Source.SERVER).await().exists()) { + val onServer = messageRef.get(Source.SERVER).await() + // A new message's photo is pending until it is uploaded and marked so below. + val pending = !onServer.exists() || onServer.getBoolean(PHOTO_PENDING) == true + if (!onServer.exists()) { val batch = messageBatch( conversation, @@ -132,17 +136,16 @@ class FirebaseChatRepository( messageFields = buildMap { put("imagePath", path) + put(PHOTO_PENDING, true) trimmedCaption?.let { put("text", it) } }, ) - try { - batch.commit().await() - } catch (e: FirebaseFirestoreException) { - logWriteFailure(e) - throw e - } + batch.commit().awaitLoggingFailure() } if (!exists(photoRef)) upload(photoRef, compressed) + // Tells the other participant the photo can be downloaded. The rules allow this only once, + // so a retry after it reached the server skips it. + if (pending) messageRef.update(PHOTO_PENDING, false).awaitLoggingFailure() } } @@ -289,6 +292,16 @@ class FirebaseChatRepository( ) } + /** Waits for the server to confirm a write; a rejection is logged, then thrown. */ + private suspend fun Task.awaitLoggingFailure() { + try { + await() + } catch (e: FirebaseFirestoreException) { + logWriteFailure(e) + throw e + } + } + private suspend fun currentListingTitle(listingId: String): String { val listing = firestore.collection(LISTINGS).document(listingId).get().await() return listing.takeIf { it.exists() }?.getString("title") @@ -386,7 +399,7 @@ class FirebaseChatRepository( sentAt = instant("sentAt") ?: throw missing("sentAt"), imagePath = imagePath, // Photos sent before the flag existed have none, and were uploaded. - photoPending = getBoolean("photoPending") ?: false, + photoPending = getBoolean(PHOTO_PENDING) ?: false, ) } @@ -394,5 +407,6 @@ class FirebaseChatRepository( const val CONVERSATIONS = "conversations" const val MESSAGES = "messages" const val LISTINGS = "listings" + const val PHOTO_PENDING = "photoPending" } } 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 5c62fdca..66abf170 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 @@ -129,6 +129,7 @@ class FirebaseChatRepositoryTest { val notWritten = mock() whenever(notWritten.exists()).thenReturn(false) whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(notWritten)) + whenever(photoMessageRef.update("photoPending", false)).thenReturn(Tasks.forResult(null)) whenever(storage.reference).thenReturn(storageRoot) whenever(storageRoot.child(PHOTO_PATH)).thenReturn(photoRef) val notUploaded = storageException(StorageException.ERROR_OBJECT_NOT_FOUND) @@ -457,6 +458,7 @@ class FirebaseChatRepositoryTest { "senderUid" to "renter", "sentAt" to FieldValue.serverTimestamp(), "imagePath" to PHOTO_PATH, + "photoPending" to true, ), ) } @@ -472,6 +474,7 @@ class FirebaseChatRepositoryTest { "senderUid" to "renter", "sentAt" to FieldValue.serverTimestamp(), "imagePath" to PHOTO_PATH, + "photoPending" to true, "text" to "The drill bits", ), ) @@ -488,6 +491,7 @@ class FirebaseChatRepositoryTest { "senderUid" to "renter", "sentAt" to FieldValue.serverTimestamp(), "imagePath" to PHOTO_PATH, + "photoPending" to true, ), ) } @@ -1268,6 +1272,7 @@ class FirebaseChatRepositoryTest { private fun messageAlreadyOnServer() { val written = mock() whenever(written.exists()).thenReturn(true) + whenever(written.getBoolean("photoPending")).thenReturn(true) whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(written)) } From ef67ab9f5db1f152a9bc3ae15a65379ab0d01fd9 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:35:10 +0100 Subject: [PATCH 20/27] test(chat): cover marking a photo uploaded Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 106 +++++++++++++++++- 1 file changed, 103 insertions(+), 3 deletions(-) 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 66abf170..a74c0a88 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 @@ -717,6 +717,103 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).batch() } + @Test + fun sendPhotoMarksThePhotoUploadedOnlyAfterUploadingIt() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + val order = inOrder(batch, photoRef, photoMessageRef) + order.verify(batch).commit() + order.verify(photoRef).putBytes(any(), any()) + order.verify(photoMessageRef).update("photoPending", false) + } + + @Test + fun sendPhotoWaitsForTheServerToConfirmTheMarkBeforeReturning() = runTest { + val pendingMark = TaskCompletionSource() + whenever(photoMessageRef.update("photoPending", false)).thenReturn(pendingMark.task) + val sending = async { repository.sendPhoto(replied, PHOTO_ID, photo) } + runCurrent() + + assertFalse(sending.isCompleted) + pendingMark.setResult(null) + sending.await() + } + + @Test + fun sendPhotoRetryWithPhotoStoredButNotMarkedOnlyMarksIt() = runTest { + messageAlreadyOnServer() + whenever(photoRef.metadata).thenReturn(Tasks.forResult(mock())) + + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(firestore, never()).batch() + verify(photoRef, never()).putBytes(any(), any()) + verify(photoMessageRef).update("photoPending", false) + } + + @Test + fun sendPhotoRetryWithPhotoAlreadyMarkedUploadedWritesNothing() = runTest { + messageAlreadyOnServer(pending = false) + whenever(photoRef.metadata).thenReturn(Tasks.forResult(mock())) + + repository.sendPhoto(replied, PHOTO_ID, photo) + + // The rules allow the mark only once. + verify(photoMessageRef, never()).update(any(), any()) + verify(firestore, never()).batch() + } + + @Test + fun sendPhotoRetryForMessageWithoutPendingFieldDoesNotMarkIt() = runTest { + messageAlreadyOnServer(pending = null) + whenever(photoRef.metadata).thenReturn(Tasks.forResult(mock())) + + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(photoMessageRef, never()).update(any(), any()) + } + + @Test + fun sendPhotoFailedUploadLeavesThePhotoPending() = runTest { + failUpload(storageException(StorageException.ERROR_RETRY_LIMIT_EXCEEDED)) + + runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) } + + verify(photoMessageRef, never()).update(any(), any()) + } + + @Test + fun sendPhotoRejectedMarkIsLoggedAndThrown() = runTest { + val failure = + FirebaseFirestoreException( + "Missing or insufficient permissions.", + FirebaseFirestoreException.Code.PERMISSION_DENIED, + ) + whenever(photoMessageRef.update("photoPending", false)).thenReturn(Tasks.forException(failure)) + var logged: Exception? = null + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { logged = it } + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertSame(failure, logged) + assertSame(failure, error) + } + + @Test + fun sendPhotoMarkWithNoServerAnswerFailsWithNetworkAfterTimeout() = runTest { + whenever(photoMessageRef.update("photoPending", false)) + .thenReturn(TaskCompletionSource().task) + + val error = runCatching { + shortTimeoutRepository().sendPhoto(replied, PHOTO_ID, photo) + } + .exceptionOrNull() + + assertEquals(AppError.NETWORK, (error as AppException).error) + assertEquals(5_000L, testScheduler.currentTime) + } + @Test fun sendPhotoUploadsOnlyAfterCheckingNoPhotoIsStored() = runTest { repository.sendPhoto(replied, PHOTO_ID, photo) @@ -1268,11 +1365,14 @@ class FirebaseChatRepositoryTest { photoTimeout = 5.seconds, ) - /** Puts the photo's message on the server, as after a send whose upload failed. */ - private fun messageAlreadyOnServer() { + /** + * Puts the photo's message on the server, as after a send whose upload failed. With [pending] + * false its photo was already marked uploaded; null is a message from before the flag existed. + */ + private fun messageAlreadyOnServer(pending: Boolean? = true) { val written = mock() whenever(written.exists()).thenReturn(true) - whenever(written.getBoolean("photoPending")).thenReturn(true) + whenever(written.getBoolean("photoPending")).thenReturn(pending) whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(written)) } From 0f2e7f3f92eea5d958c158e43688d2a7644d5c42 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:37:26 +0100 Subject: [PATCH 21/27] fix(chat): wait for a queued photo message instead of writing it again Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepository.kt | 19 ++++++++++++++++++- .../chat/model/FirebaseChatRepositoryTest.kt | 7 +++++++ 2 files changed, 25 insertions(+), 1 deletion(-) 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 5b358cf2..dae57586 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 @@ -122,7 +122,14 @@ class FirebaseChatRepository( // Read from the server: offline it fails at once with UNAVAILABLE, rather than queuing a // message that would reach the server later without its photo. A retry finds the message // already written, and only uploads. - val onServer = messageRef.get(Source.SERVER).await() + var onServer = messageRef.get(Source.SERVER).await() + // After a send that timed out while writing, the write can still be queued on this device and + // reach the server later. Writing the message again would then count as an update, which the + // rules refuse, so wait for the queued write instead. + if (!onServer.exists() && hasQueuedWrite(messageRef)) { + firestore.waitForPendingWrites().await() + onServer = messageRef.get(Source.SERVER).await() + } // A new message's photo is pending until it is uploaded and marked so below. val pending = !onServer.exists() || onServer.getBoolean(PHOTO_PENDING) == true if (!onServer.exists()) { @@ -292,6 +299,16 @@ class FirebaseChatRepository( ) } + /** Whether this device has a write to [ref] that the server has not confirmed yet. */ + private suspend fun hasQueuedWrite(ref: DocumentReference): Boolean = + try { + ref.get(Source.CACHE).await().metadata.hasPendingWrites() + } catch (e: FirebaseFirestoreException) { + // UNAVAILABLE: the document is not in the cache, so nothing is queued for it. + if (e.code != FirebaseFirestoreException.Code.UNAVAILABLE) throw e + false + } + /** Waits for the server to confirm a write; a rejection is logged, then thrown. */ private suspend fun Task.awaitLoggingFailure() { try { 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 a74c0a88..cf401c34 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 @@ -130,6 +130,13 @@ class FirebaseChatRepositoryTest { whenever(notWritten.exists()).thenReturn(false) whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(notWritten)) whenever(photoMessageRef.update("photoPending", false)).thenReturn(Tasks.forResult(null)) + // Nor in this device's cache: no write of it is queued. + val notCached = + FirebaseFirestoreException( + "Failed to get document from cache.", + FirebaseFirestoreException.Code.UNAVAILABLE, + ) + whenever(photoMessageRef.get(Source.CACHE)).thenReturn(Tasks.forException(notCached)) whenever(storage.reference).thenReturn(storageRoot) whenever(storageRoot.child(PHOTO_PATH)).thenReturn(photoRef) val notUploaded = storageException(StorageException.ERROR_OBJECT_NOT_FOUND) From f5d171801ca7dc325bbbbc054e3cb4fb003dbd26 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:37:26 +0100 Subject: [PATCH 22/27] test(chat): cover retrying a photo whose message is still queued Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 92 +++++++++++++++++++ 1 file changed, 92 insertions(+) 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 cf401c34..4963c37c 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 @@ -6,6 +6,7 @@ import com.android.polybazaar.error.model.AppError import com.android.polybazaar.error.model.AppException import com.android.polybazaar.error.model.toAppError import com.android.polybazaar.photo.PhotoCompressor +import com.google.android.gms.tasks.Task import com.google.android.gms.tasks.TaskCompletionSource import com.google.android.gms.tasks.Tasks import com.google.firebase.Timestamp @@ -23,6 +24,7 @@ import com.google.firebase.firestore.ListenerRegistration import com.google.firebase.firestore.Query import com.google.firebase.firestore.QuerySnapshot import com.google.firebase.firestore.SetOptions +import com.google.firebase.firestore.SnapshotMetadata import com.google.firebase.firestore.Source import com.google.firebase.firestore.WriteBatch import com.google.firebase.storage.FirebaseStorage @@ -821,6 +823,83 @@ class FirebaseChatRepositoryTest { assertEquals(5_000L, testScheduler.currentTime) } + @Test + fun sendPhotoFirstTryDoesNotWaitForOtherWrites() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(firestore, never()).waitForPendingWrites() + } + + @Test + fun sendPhotoRetryAfterQueuedMessageWaitsForItInsteadOfRewritingIt() = runTest { + val written = TaskCompletionSource() + messageQueuedOnDevice(written.task) + val sending = async { repository.sendPhoto(replied, PHOTO_ID, photo) } + runCurrent() + + verify(photoRef, never()).putBytes(any(), any()) + messageAlreadyOnServer() + written.setResult(null) + sending.await() + + // Writing it again would be an update once the queued write lands, which the rules refuse. + verify(firestore, never()).batch() + verify(photoRef).putBytes(eq(compressedPhoto), any()) + verify(photoMessageRef).update("photoPending", false) + } + + @Test + fun sendPhotoRetryAfterQueuedMessageWasRefusedWritesItAgain() = runTest { + // The queued write ended, but the server refused it: the message is still not there. + messageQueuedOnDevice(Tasks.forResult(null)) + + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(batch).commit() + verify(photoRef).putBytes(eq(compressedPhoto), any()) + } + + @Test + fun sendPhotoCachedMessageWithoutQueuedWriteDoesNotWait() = runTest { + val cached = mock() + val metadata = mock() + whenever(metadata.hasPendingWrites()).thenReturn(false) + whenever(cached.metadata).thenReturn(metadata) + whenever(photoMessageRef.get(Source.CACHE)).thenReturn(Tasks.forResult(cached)) + + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(firestore, never()).waitForPendingWrites() + verify(batch).commit() + } + + @Test + fun sendPhotoRethrowsOtherCacheReadFailuresWithoutWriting() = runTest { + val failure = + FirebaseFirestoreException("Internal error.", FirebaseFirestoreException.Code.INTERNAL) + whenever(photoMessageRef.get(Source.CACHE)).thenReturn(Tasks.forException(failure)) + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertSame(failure, error) + verify(firestore, never()).batch() + } + + @Test + fun sendPhotoQueuedMessageNeverSentFailsWithNetworkAfterTimeout() = runTest { + messageQueuedOnDevice(TaskCompletionSource().task) + + val error = runCatching { + shortTimeoutRepository().sendPhoto(replied, PHOTO_ID, photo) + } + .exceptionOrNull() + + assertEquals(AppError.NETWORK, (error as AppException).error) + assertEquals(5_000L, testScheduler.currentTime) + verify(firestore, never()).batch() + verify(photoRef, never()).putBytes(any(), any()) + } + @Test fun sendPhotoUploadsOnlyAfterCheckingNoPhotoIsStored() = runTest { repository.sendPhoto(replied, PHOTO_ID, photo) @@ -1383,6 +1462,19 @@ class FirebaseChatRepositoryTest { whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(written)) } + /** + * Leaves a write of the photo's message queued on this device, as after a send that timed out + * while writing it. [written] ends once this device's queued writes have reached the server. + */ + private fun messageQueuedOnDevice(written: Task) { + val cached = mock() + val metadata = mock() + whenever(metadata.hasPendingWrites()).thenReturn(true) + whenever(cached.metadata).thenReturn(metadata) + whenever(photoMessageRef.get(Source.CACHE)).thenReturn(Tasks.forResult(cached)) + whenever(firestore.waitForPendingWrites()).thenReturn(written) + } + /** Makes the photo upload end with [failure]. */ private fun failUpload(failure: Exception) { whenever(uploadTask.isSuccessful).thenReturn(false) From 4ee4e3ac84549a20d1c3c383e07cc31212f6f0da Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 13:41:32 +0100 Subject: [PATCH 23/27] docs(chat): describe the pending photo and retries in sendPhoto Co-Authored-By: Claude Opus 5.5 --- .../polybazaar/chat/model/ChatRepository.kt | 24 ++++++++++++------- .../chat/model/FirebaseChatRepository.kt | 6 ++--- 2 files changed, 18 insertions(+), 12 deletions(-) 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 60ff036d..c5733f31 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 @@ -30,20 +30,26 @@ interface ChatRepository { fun newMessageId(conversationId: String): String /** - * Sends a photo message from the signed-in participant, and returns once the server has both the - * message and the photo, so it needs a connection. Storage only accepts the photo once its - * message is on the server, so the message and the conversation update are written first, then - * the photo is compressed and uploaded. Until the upload ends, the other participant may see the - * message before its photo can be downloaded. + * Sends a photo message from the signed-in participant, and returns once the server has the + * message and the photo, so it needs a connection. The photo is compressed first. Storage only + * accepts the photo once its message is on the server, so the message and the conversation update + * are written next, with [ChatMessage.photoPending] true; then the photo is uploaded, and the + * message is marked as no longer pending. Until then, the other participant sees the message with + * its photo pending, which can't be downloaded yet. * * Throws when signed out (UNAUTHENTICATED), when offline or when the send takes too long (an - * error that maps to NETWORK with toAppError), when the server rejects the message (a Firestore + * error that maps to NETWORK with toAppError), when the server rejects a write (a Firestore * error) or the upload (a Storage error), when the photo can't be read, as when it was deleted or * is not an image (an AppException with NOT_FOUND), and IllegalArgumentException when the user is * not a participant, when the conversation has no message yet (a photo cannot open a - * conversation), or when the caption is not sendable. Signed out, offline, for an unreadable - * photo, or for an IllegalArgumentException, nothing is written. After a failed upload the - * message stays: retrying with the same [messageId] only uploads the photo. + * conversation), or when the caption is not sendable. + * + * Signed out, offline when the send starts, for an unreadable photo, or for an + * IllegalArgumentException, nothing is written. Any other failure can leave the message written, + * or queued on this device to be written once the connection is back, with its photo pending. + * Keep the [messageId] after a failure and retry with it: a retry waits for a queued message + * rather than writing it again, uploads the photo only if it is not stored yet, and marks it + * uploaded. A message whose send is never retried, as when the app is closed, stays pending. * * @param conversation the conversation from [observeConversation]. * @param messageId from [newMessageId]; pass the same one to retry a failed send. 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 dae57586..a755a196 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 @@ -36,9 +36,9 @@ import kotlinx.coroutines.tasks.await import kotlinx.coroutines.withTimeout /** - * @param photoTimeout how long sending a photo (its message, then its upload) or loading one may - * take before it fails with NETWORK, rather than the Storage SDK retrying for minutes while - * offline. + * @param photoTimeout how long sending a photo (its message, its upload, then marking it uploaded) + * or loading one may take before it fails with NETWORK, rather than the Storage SDK retrying for + * minutes while offline. */ class FirebaseChatRepository( private val photoCompressor: PhotoCompressor, From cc55d4232f0a9aaa317f28415d5cbd3068a09583 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 14:43:41 +0100 Subject: [PATCH 24/27] fix(chat): wait for a queued photo message seen in the server read Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepository.kt | 19 ++--- .../chat/model/FirebaseChatRepositoryTest.kt | 81 ++++++++----------- 2 files changed, 38 insertions(+), 62 deletions(-) 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 a755a196..cac84fd2 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 @@ -123,10 +123,11 @@ class FirebaseChatRepository( // message that would reach the server later without its photo. A retry finds the message // already written, and only uploads. var onServer = messageRef.get(Source.SERVER).await() - // After a send that timed out while writing, the write can still be queued on this device and - // reach the server later. Writing the message again would then count as an update, which the - // rules refuse, so wait for the queued write instead. - if (!onServer.exists() && hasQueuedWrite(messageRef)) { + // After a send that timed out, its write can still be queued on this device. A server read + // includes this device's queued writes, so the message then looks written while the server + // does not have it yet: wait until it does, then read it again. Checked on this one read, so + // a write landing meanwhile cannot make the message look missing and get it written twice. + if (onServer.metadata.hasPendingWrites()) { firestore.waitForPendingWrites().await() onServer = messageRef.get(Source.SERVER).await() } @@ -299,16 +300,6 @@ class FirebaseChatRepository( ) } - /** Whether this device has a write to [ref] that the server has not confirmed yet. */ - private suspend fun hasQueuedWrite(ref: DocumentReference): Boolean = - try { - ref.get(Source.CACHE).await().metadata.hasPendingWrites() - } catch (e: FirebaseFirestoreException) { - // UNAVAILABLE: the document is not in the cache, so nothing is queued for it. - if (e.code != FirebaseFirestoreException.Code.UNAVAILABLE) throw e - false - } - /** Waits for the server to confirm a write; a rejection is logged, then thrown. */ private suspend fun Task.awaitLoggingFailure() { try { 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 4963c37c..ff731ce8 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 @@ -128,17 +128,9 @@ class FirebaseChatRepositoryTest { whenever(messages.document(PHOTO_ID)).thenReturn(photoMessageRef) whenever(photoMessageRef.id).thenReturn(PHOTO_ID) // By default the photo's message is not on the server yet, as for a first try. - val notWritten = mock() - whenever(notWritten.exists()).thenReturn(false) + val notWritten = messageSnapshot(exists = false) whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(notWritten)) whenever(photoMessageRef.update("photoPending", false)).thenReturn(Tasks.forResult(null)) - // Nor in this device's cache: no write of it is queued. - val notCached = - FirebaseFirestoreException( - "Failed to get document from cache.", - FirebaseFirestoreException.Code.UNAVAILABLE, - ) - whenever(photoMessageRef.get(Source.CACHE)).thenReturn(Tasks.forException(notCached)) whenever(storage.reference).thenReturn(storageRoot) whenever(storageRoot.child(PHOTO_PATH)).thenReturn(photoRef) val notUploaded = storageException(StorageException.ERROR_OBJECT_NOT_FOUND) @@ -833,12 +825,13 @@ class FirebaseChatRepositoryTest { @Test fun sendPhotoRetryAfterQueuedMessageWaitsForItInsteadOfRewritingIt() = runTest { val written = TaskCompletionSource() - messageQueuedOnDevice(written.task) + // A server read includes this device's queued write: the message looks written already. + messageQueuedOnDevice(written.task, then = messageSnapshot(exists = true, pending = true)) val sending = async { repository.sendPhoto(replied, PHOTO_ID, photo) } runCurrent() + // storage.rules would refuse the upload until the server has the message. verify(photoRef, never()).putBytes(any(), any()) - messageAlreadyOnServer() written.setResult(null) sending.await() @@ -851,7 +844,7 @@ class FirebaseChatRepositoryTest { @Test fun sendPhotoRetryAfterQueuedMessageWasRefusedWritesItAgain() = runTest { // The queued write ended, but the server refused it: the message is still not there. - messageQueuedOnDevice(Tasks.forResult(null)) + messageQueuedOnDevice(Tasks.forResult(null), then = messageSnapshot(exists = false)) repository.sendPhoto(replied, PHOTO_ID, photo) @@ -859,32 +852,6 @@ class FirebaseChatRepositoryTest { verify(photoRef).putBytes(eq(compressedPhoto), any()) } - @Test - fun sendPhotoCachedMessageWithoutQueuedWriteDoesNotWait() = runTest { - val cached = mock() - val metadata = mock() - whenever(metadata.hasPendingWrites()).thenReturn(false) - whenever(cached.metadata).thenReturn(metadata) - whenever(photoMessageRef.get(Source.CACHE)).thenReturn(Tasks.forResult(cached)) - - repository.sendPhoto(replied, PHOTO_ID, photo) - - verify(firestore, never()).waitForPendingWrites() - verify(batch).commit() - } - - @Test - fun sendPhotoRethrowsOtherCacheReadFailuresWithoutWriting() = runTest { - val failure = - FirebaseFirestoreException("Internal error.", FirebaseFirestoreException.Code.INTERNAL) - whenever(photoMessageRef.get(Source.CACHE)).thenReturn(Tasks.forException(failure)) - - val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() - - assertSame(failure, error) - verify(firestore, never()).batch() - } - @Test fun sendPhotoQueuedMessageNeverSentFailsWithNetworkAfterTimeout() = runTest { messageQueuedOnDevice(TaskCompletionSource().task) @@ -1451,27 +1418,45 @@ class FirebaseChatRepositoryTest { photoTimeout = 5.seconds, ) + /** + * The photo's message as a server read returns it: missing unless it [exists], with [pending] as + * its photoPending, and [queued] when this device has a write of it the server does not have yet. + */ + private fun messageSnapshot( + exists: Boolean, + pending: Boolean? = null, + queued: Boolean = false, + ): DocumentSnapshot { + val metadata = mock() + whenever(metadata.hasPendingWrites()).thenReturn(queued) + return mock().also { + whenever(it.exists()).thenReturn(exists) + whenever(it.getBoolean("photoPending")).thenReturn(pending) + whenever(it.metadata).thenReturn(metadata) + } + } + /** * Puts the photo's message on the server, as after a send whose upload failed. With [pending] * false its photo was already marked uploaded; null is a message from before the flag existed. */ private fun messageAlreadyOnServer(pending: Boolean? = true) { - val written = mock() - whenever(written.exists()).thenReturn(true) - whenever(written.getBoolean("photoPending")).thenReturn(pending) + val written = messageSnapshot(exists = true, pending = pending) whenever(photoMessageRef.get(Source.SERVER)).thenReturn(Tasks.forResult(written)) } /** * Leaves a write of the photo's message queued on this device, as after a send that timed out - * while writing it. [written] ends once this device's queued writes have reached the server. + * while writing it: the first server read returns [queued], which includes it. [written] ends + * once this device's queued writes have reached the server; reads after that return [then]. */ - private fun messageQueuedOnDevice(written: Task) { - val cached = mock() - val metadata = mock() - whenever(metadata.hasPendingWrites()).thenReturn(true) - whenever(cached.metadata).thenReturn(metadata) - whenever(photoMessageRef.get(Source.CACHE)).thenReturn(Tasks.forResult(cached)) + private fun messageQueuedOnDevice( + written: Task, + queued: DocumentSnapshot = messageSnapshot(exists = true, pending = true, queued = true), + then: DocumentSnapshot = messageSnapshot(exists = true, pending = true), + ) { + whenever(photoMessageRef.get(Source.SERVER)) + .thenReturn(Tasks.forResult(queued), Tasks.forResult(then)) whenever(firestore.waitForPendingWrites()).thenReturn(written) } From d3748b4877c80c9ebaf49e769bf1a57729461492 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 14:43:41 +0100 Subject: [PATCH 25/27] test(chat): cover retries that find a queued write on the server read Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) 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 ff731ce8..a20ae121 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 @@ -822,6 +822,15 @@ class FirebaseChatRepositoryTest { verify(firestore, never()).waitForPendingWrites() } + @Test + fun sendPhotoRetryWithMessageOnServerDoesNotWaitForOtherWrites() = runTest { + messageAlreadyOnServer() + + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(firestore, never()).waitForPendingWrites() + } + @Test fun sendPhotoRetryAfterQueuedMessageWaitsForItInsteadOfRewritingIt() = runTest { val written = TaskCompletionSource() @@ -852,6 +861,23 @@ class FirebaseChatRepositoryTest { verify(photoRef).putBytes(eq(compressedPhoto), any()) } + @Test + fun sendPhotoRetryAfterQueuedMarkWaitsForItInsteadOfMarkingAgain() = runTest { + // The photo was uploaded and its mark queued, then the send timed out. + messageQueuedOnDevice( + Tasks.forResult(null), + queued = messageSnapshot(exists = true, pending = false, queued = true), + then = messageSnapshot(exists = true, pending = false), + ) + whenever(photoRef.metadata).thenReturn(Tasks.forResult(mock())) + + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(firestore).waitForPendingWrites() + verify(photoMessageRef, never()).update(any(), any()) + verify(photoRef, never()).putBytes(any(), any()) + } + @Test fun sendPhotoQueuedMessageNeverSentFailsWithNetworkAfterTimeout() = runTest { messageQueuedOnDevice(TaskCompletionSource().task) From f5d14c96bb09420e3611a288045f72156e4941a3 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 14:45:21 +0100 Subject: [PATCH 26/27] fix(chat): accept a refused photo mark once the server has it Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepository.kt | 22 ++++++++++++++++++- .../chat/model/FirebaseChatRepositoryTest.kt | 6 ++++- 2 files changed, 26 insertions(+), 2 deletions(-) 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 cac84fd2..ae6e09a2 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 @@ -153,7 +153,7 @@ class FirebaseChatRepository( if (!exists(photoRef)) upload(photoRef, compressed) // Tells the other participant the photo can be downloaded. The rules allow this only once, // so a retry after it reached the server skips it. - if (pending) messageRef.update(PHOTO_PENDING, false).awaitLoggingFailure() + if (pending) markPhotoUploaded(messageRef) } } @@ -300,6 +300,26 @@ class FirebaseChatRepository( ) } + /** + * Sets photoPending to false on the message at [ref] and waits for the server. The rules allow + * this once, so a mark sent twice, as when a mark that timed out still reached the server, is + * refused: that refusal counts as done when the server shows the photo as uploaded. + */ + private suspend fun markPhotoUploaded(ref: DocumentReference) { + try { + ref.update(PHOTO_PENDING, false).await() + } catch (e: FirebaseFirestoreException) { + if ( + e.code == FirebaseFirestoreException.Code.PERMISSION_DENIED && + ref.get(Source.SERVER).await().getBoolean(PHOTO_PENDING) == false + ) { + return + } + logWriteFailure(e) + throw e + } + } + /** Waits for the server to confirm a write; a rejection is logged, then thrown. */ private suspend fun Task.awaitLoggingFailure() { try { 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 a20ae121..7c5951c5 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 @@ -784,13 +784,17 @@ class FirebaseChatRepositoryTest { } @Test - fun sendPhotoRejectedMarkIsLoggedAndThrown() = runTest { + fun sendPhotoRejectedMarkWithPhotoStillPendingIsLoggedAndThrown() = runTest { val failure = FirebaseFirestoreException( "Missing or insufficient permissions.", FirebaseFirestoreException.Code.PERMISSION_DENIED, ) whenever(photoMessageRef.update("photoPending", false)).thenReturn(Tasks.forException(failure)) + val notWritten = messageSnapshot(exists = false) + val stillPending = messageSnapshot(exists = true, pending = true) + whenever(photoMessageRef.get(Source.SERVER)) + .thenReturn(Tasks.forResult(notWritten), Tasks.forResult(stillPending)) var logged: Exception? = null val repository = FirebaseChatRepository(photoCompressor, firestore, auth, storage) { logged = it } From f9b174942a74877bf870aa6514b3f67b1df8d931 Mon Sep 17 00:00:00 2001 From: Mamel0uk Date: Wed, 18 Nov 2026 14:45:21 +0100 Subject: [PATCH 27/27] test(chat): cover a photo mark sent twice Co-Authored-By: Claude Opus 5.5 --- .../chat/model/FirebaseChatRepositoryTest.kt | 35 +++++++++++++++++++ 1 file changed, 35 insertions(+) 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 7c5951c5..593eb03f 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 @@ -60,6 +60,7 @@ import org.mockito.kotlin.eq import org.mockito.kotlin.inOrder import org.mockito.kotlin.mock import org.mockito.kotlin.never +import org.mockito.kotlin.times import org.mockito.kotlin.verify import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever @@ -805,6 +806,40 @@ class FirebaseChatRepositoryTest { assertSame(failure, error) } + @Test + fun sendPhotoRefusedMarkCountsAsDoneWhenTheServerShowsThePhotoUploaded() = runTest { + // A mark that timed out still reached the server, so this second one is refused. + val refused = + FirebaseFirestoreException( + "Missing or insufficient permissions.", + FirebaseFirestoreException.Code.PERMISSION_DENIED, + ) + whenever(photoMessageRef.update("photoPending", false)).thenReturn(Tasks.forException(refused)) + val notWritten = messageSnapshot(exists = false) + val uploaded = messageSnapshot(exists = true, pending = false) + whenever(photoMessageRef.get(Source.SERVER)) + .thenReturn(Tasks.forResult(notWritten), Tasks.forResult(uploaded)) + var logged: Exception? = null + val repository = + FirebaseChatRepository(photoCompressor, firestore, auth, storage) { logged = it } + + repository.sendPhoto(replied, PHOTO_ID, photo) + + assertNull(logged) + } + + @Test + fun sendPhotoOtherMarkFailureIsThrownWithoutReadingTheMessageAgain() = runTest { + val failure = + FirebaseFirestoreException("Internal error.", FirebaseFirestoreException.Code.INTERNAL) + whenever(photoMessageRef.update("photoPending", false)).thenReturn(Tasks.forException(failure)) + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertSame(failure, error) + verify(photoMessageRef, times(1)).get(Source.SERVER) + } + @Test fun sendPhotoMarkWithNoServerAnswerFailsWithNetworkAfterTimeout() = runTest { whenever(photoMessageRef.update("photoPending", false))