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/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/ChatRepository.kt b/app/src/main/java/com/android/polybazaar/chat/model/ChatRepository.kt index d84b79fe..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 @@ -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,54 @@ 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, 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 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 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. + * @param caption optional text sent with the photo; null or blank sends the photo alone, which + * previews as an empty lastMessageText. + */ + suspend fun sendPhoto( + conversation: Conversation, + messageId: String, + photo: Uri, + caption: String? = null, + ) + + /** + * Downloads the photo of a message, from its [ChatMessage.imagePath], as the signed-in user. + * Fails with PERMISSION_DENIED for a user who is not a participant of the conversation, with an + * 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 + /** * 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 989d44e2..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 @@ -1,8 +1,15 @@ // 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.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 import com.google.firebase.firestore.FieldPath import com.google.firebase.firestore.FieldValue @@ -10,16 +17,35 @@ 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 +import java.io.IOException 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 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, private val firestore: FirebaseFirestore = FirebaseFirestore.getInstance(), private val auth: FirebaseAuth = FirebaseAuth.getInstance(), + private val storage: FirebaseStorage = FirebaseStorage.getInstance(), + private val photoTimeout: Duration = 30.seconds, private val logWriteFailure: (Exception) -> Unit = { Log.e("ChatRepository", "Chat write failed", it) }, @@ -30,52 +56,19 @@ 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) - } - 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( + // Not awaited: the write is queued, so a text can be sent offline. + messageBatch( + conversation, messageRef, - mapOf( - "senderUid" to senderUid, - "text" to trimmed, - "sentAt" to FieldValue.serverTimestamp(), - ), + senderUid, + preview = trimmed, + messageFields = mapOf("text" to trimmed), ) .commit() .addOnFailureListener(Executor { it.run() }) { @@ -84,6 +77,90 @@ class FirebaseChatRepository( } } + override fun newMessageId(conversationId: String): String = + conversationDocument(conversationId).collection(MESSAGES).document().id + + override suspend fun sendPhoto( + conversation: Conversation, + messageId: String, + photo: Uri, + caption: String?, + ) { + val senderUid = participantUid(conversation) + // 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" + } + val trimmedCaption = + caption + ?.takeIf { it.isNotBlank() } + ?.also { + require(ChatRules.isSendable(it)) { + "A caption must have 1 to ${ChatRules.MAX_MESSAGE_LENGTH} characters" + } + } + ?.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 = + 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) + // 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. + 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. + var onServer = messageRef.get(Source.SERVER).await() + // 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() + } + // 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, + messageRef, + senderUid, + // A photo alone previews as an empty text. + preview = trimmedCaption ?: "", + messageFields = + buildMap { + put("imagePath", path) + put(PHOTO_PENDING, true) + trimmedCaption?.let { put("text", it) } + }, + ) + 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) markPhotoUploaded(messageRef) + } + } + + 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 // Not awaited, like sendMessage: the write is queued offline and the listener sees it at once. @@ -167,6 +244,92 @@ 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 + } + + /** + * 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 messageBatch( + conversation: Conversation, + messageRef: DocumentReference, + senderUid: String, + preview: String, + messageFields: Map, + ): WriteBatch { + 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) + } + 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. + .set(conversationDocument(conversation.id), conversationFields, SetOptions.merge()) + .set( + messageRef, + mapOf("senderUid" to senderUid, "sentAt" to FieldValue.serverTimestamp()) + + messageFields, + ) + } + + /** + * 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 { + 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") @@ -178,6 +341,51 @@ class FirebaseChatRepository( private fun conversationDocument(id: String) = firestore.collection(CONVERSATIONS).document(id) + /** + * 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. + */ + 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 + } + + /** + * 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) + 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: 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" + // 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? = @@ -218,6 +426,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(PHOTO_PENDING) ?: false, ) } @@ -225,5 +435,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/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt b/app/src/sharedTest/java/com/android/polybazaar/chat/model/FakeChatRepository.kt index 82ce8d71..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 @@ -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,13 @@ 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] 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]. + * * [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 +55,23 @@ 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 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() @@ -55,6 +80,8 @@ class FakeChatRepository( var conversationGate: CompletableDeferred? = null var messagesGate: CompletableDeferred? = null + private var messageIds = 0 + var observeConversationCalls = 0 private set @@ -72,6 +99,24 @@ 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?, + ) { + sentPhotos += SentPhoto(conversation, messageId, photo, caption) + gate?.await() + 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 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..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 @@ -1,6 +1,12 @@ // Co-authored-by: Claude Code (Claude Opus 5.5) 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.Task import com.google.android.gms.tasks.TaskCompletionSource import com.google.android.gms.tasks.Tasks import com.google.firebase.Timestamp @@ -18,10 +24,23 @@ 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 +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 +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 import kotlinx.coroutines.test.runCurrent import kotlinx.coroutines.test.runTest @@ -36,11 +55,14 @@ 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.times import org.mockito.kotlin.verify +import org.mockito.kotlin.verifyNoInteractions import org.mockito.kotlin.whenever @OptIn(kotlinx.coroutines.ExperimentalCoroutinesApi::class) @@ -59,7 +81,20 @@ 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 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( listingId = "listing", @@ -67,6 +102,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() { @@ -89,6 +126,20 @@ 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) + // By default the photo's message is not on the server yet, as for a first try. + val notWritten = messageSnapshot(exists = 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) + 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 @@ -267,7 +318,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 +346,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 } @@ -354,6 +407,648 @@ 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 sendPhotoChecksTheServerThenCommitsTheMessageBeforeUploading() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + // 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 + fun sendPhotoWithoutCaptionWritesImagePathWithoutTextAndEmptyPreview() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + verifyPhotoBatch( + preview = "", + message = + mapOf( + "senderUid" to "renter", + "sentAt" to FieldValue.serverTimestamp(), + "imagePath" to PHOTO_PATH, + "photoPending" to true, + ), + ) + } + + @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, + "photoPending" to true, + "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, + "photoPending" to true, + ), + ) + } + + @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 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) { logged = it } + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + 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 + 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 sendPhotoUploadFailureOfflineIsNetworkAfterTheMessageIsWritten() = 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()) + // Kept: a retry with the same ID only uploads. + verify(batch).commit() + } + + @Test + fun sendPhotoRefusedUploadIsPermissionDenied() = 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()) + } + + @Test + fun sendPhotoCompressionFailureWritesAndUploadsNothing() = 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(photoMessageRef, never()).get(any()) + 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 = + FirebaseChatRepository( + { + delay(10.seconds) + compressedPhoto + }, + firestore, + auth, + storage, + photoTimeout = 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") + + verify(photoRef, never()).putBytes(any(), any()) + 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 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 } + + val error = runCatching { repository.sendPhoto(replied, PHOTO_ID, photo) }.exceptionOrNull() + + assertSame(failure, logged) + 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)) + .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 sendPhotoFirstTryDoesNotWaitForOtherWrites() = runTest { + repository.sendPhoto(replied, PHOTO_ID, photo) + + 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() + // 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()) + 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), then = messageSnapshot(exists = false)) + + repository.sendPhoto(replied, PHOTO_ID, photo) + + verify(batch).commit() + 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) + + 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) + + val order = inOrder(photoRef) + order.verify(photoRef).metadata + order.verify(photoRef).putBytes(any(), any()) + } + + @Test + fun sendPhotoRethrowsOtherStoredPhotoCheckFailuresWithoutUploading() = 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()) + } + + @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() + } + + @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()) + } + + @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() + } + + @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 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())) @@ -383,7 +1078,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 +1093,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") @@ -619,6 +1316,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)) @@ -715,6 +1441,100 @@ 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 compressorFailing(failure: Exception) = + FirebaseChatRepository({ throw failure }, firestore, auth, storage) + + private fun shortTimeoutRepository() = + FirebaseChatRepository( + photoCompressor, + firestore, + auth, + storage, + 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 = 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: 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, + 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) + } + + /** 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 + } + private fun signInAs(uid: String) { val user = mock() whenever(user.uid).thenReturn(uid) @@ -737,12 +1557,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)) } @@ -786,4 +1608,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" + } } 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))); + }); });