email: reopened drafts no longer lose their inline images
- Commit
a9cf6505cac0578eac77f847a943b569514c77cf- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-01 00:44 UTC (5 days ago)
- Parents
4b9f485
Composer autosave stored only the text fields: the inlineImageJson column (and InlineImageMeta) existed since migration 17->18 but was never wired anywhere, so a draft with an inserted inline image saved with "[]". On reopen the HTML still referenced cid:[email protected] while toInlineAttachments returned nothing, and Send built a MIME message with no part for that Content-ID — a broken or missing image for the recipient, with the HTML claiming otherwise. save() now encodes cid/uri/mime/name into the existing column (corrupt JSON decodes to empty), the composer snapshot includes inline images, draft load restores them through restoreInlineImages, and orphan cleanup keeps cids still referenced in the HTML — a draft-restored image has no span yet, so span-only pruning would have dropped it again on first edit. New tests cover persistence round-trip and cleanup survival. Sync, search, outbox and notifications were audited and cleared. Verified: :email:testDevUnitTest 590 tests pass; lint errors are pre-existing on untouched files.
Diff
email/src/main/java/com/vayunmathur/email/platform/EmailDraftActions.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailDraftActions.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailDraftActions.ktindex a0b7175a12..835844be85 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailDraftActions.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailDraftActions.kt@@ -1,9 +1,13 @@ package com.vayunmathur.email.platform +import androidx.core.net.toUri import com.vayunmathur.email.data.DraftEntry import com.vayunmathur.email.data.EmailOutboxDao+import com.vayunmathur.email.ui.composer.InlineAttachment import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json /** Draft CRUD extracted from [EmailViewModel] to keep it under the function cap. */ class EmailDraftActions(@@ -22,6 +26,7 @@ class EmailDraftActions( bcc: String, subject: String, body: String,+ inlineImages: List<InlineAttachment> = emptyList(), onSaved: (Long) -> Unit = {}, ) { scope.launch {@@ -30,6 +35,7 @@ class EmailDraftActions( id = id ?: 0, accountEmail = accountEmail, to = to, cc = cc, bcc = bcc, subject = subject, body = body,+ inlineImageJson = encodeInlineImages(inlineImages), updatedAt = System.currentTimeMillis(), ) )@@ -40,4 +46,37 @@ class EmailDraftActions( fun delete(id: Long) { scope.launch { outboxDao.deleteDraftById(id) } }++ /** Holds the draft inline-image JSON codec for [DraftEntry.inlineImageJson]. */+ companion object {+ private val json = Json { ignoreUnknownKeys = true; encodeDefaults = true }++ @Serializable+ private data class DraftInlineEntry(+ val cid: String,+ val uri: String,+ val mime: String,+ val name: String,+ )++ /**+ * Encode the composer's inline images for [DraftEntry.inlineImageJson].+ * The body HTML carries only `cid:` references, so without this list a+ * reopened draft sends those references with no matching MIME part.+ */+ internal fun encodeInlineImages(images: List<InlineAttachment>): String =+ json.encodeToString(+ images.map {+ DraftInlineEntry(cid = it.cid, uri = it.uri.toString(), mime = it.mimeType, name = it.fileName)+ },+ )++ /** Decode inline images stored by [encodeInlineImages]; corrupt JSON yields none. */+ fun decodeInlineImages(draft: DraftEntry): List<InlineAttachment> =+ runCatching {+ json.decodeFromString<List<DraftInlineEntry>>(draft.inlineImageJson)+ }.getOrDefault(emptyList()).map {+ InlineAttachment(cid = it.cid, uri = it.uri.toUri(), mimeType = it.mime, fileName = it.name)+ }+ } }
email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.kt b/email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.ktindex 528d2c7e43..3cbb6f6e42 100644--- a/email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/ComposerScreen.kt@@ -117,6 +117,9 @@ fun ComposerScreen( to = d.to; cc = d.cc; bcc = d.bcc if (d.cc.isNotBlank() || d.bcc.isNotBlank()) showCcBcc = true subject = d.subject; bodyController.setHtml(d.body)+ bodyController.restoreInlineImages(+ com.vayunmathur.email.platform.EmailDraftActions.decodeInlineImages(d),+ ) accounts.firstOrNull { it.email == d.accountEmail }?.let { fromAccount = it } } draftLoaded = true@@ -142,13 +145,19 @@ fun ComposerScreen( LaunchedEffect(fromAccount, draftLoaded) { val acc = fromAccount if (!draftLoaded || acc == null) return@LaunchedEffect- snapshotFlow { listOf(to, cc, bcc, subject, bodyController.html) }+ snapshotFlow {+ listOf(to, cc, bcc, subject, bodyController.html) ++ bodyController.inlineImages.map { "${it.cid}:${it.localUri}" }+ } .debounce(800) .collect { val hasContent = to.isNotBlank() || cc.isNotBlank() || bcc.isNotBlank() || subject.isNotBlank() || bodyController.html.isNotBlank() if (hasContent) {- viewModel.draftsActions.save(currentDraftId, acc.email, to, cc, bcc, subject, bodyController.html) { id ->+ viewModel.draftsActions.save(+ currentDraftId, acc.email, to, cc, bcc, subject, bodyController.html,+ inlineImages = bodyController.toInlineAttachments(),+ ) { id -> currentDraftId = id } }
email/src/main/java/com/vayunmathur/email/ui/composer/EmailHtmlEditorController.kt
diff --git a/email/src/main/java/com/vayunmathur/email/ui/composer/EmailHtmlEditorController.kt b/email/src/main/java/com/vayunmathur/email/ui/composer/EmailHtmlEditorController.ktindex fb61d7d4f1..e65f0178e8 100644--- a/email/src/main/java/com/vayunmathur/email/ui/composer/EmailHtmlEditorController.kt+++ b/email/src/main/java/com/vayunmathur/email/ui/composer/EmailHtmlEditorController.kt@@ -140,11 +140,29 @@ class EmailHtmlEditorController( } } + /**+ * Restore inline images persisted with a draft. The draft body is raw+ * HTML, so no [CidImageSpan] exists in the editable yet; the restored+ * list is what [toInlineAttachments] sends, and [inlineCleanupOrphans]+ * keeps entries still referenced as `cid:` in [html].+ */+ fun restoreInlineImages(images: List<InlineAttachment>) {+ inlineImages.clear()+ images.mapTo(inlineImages) {+ InlineImage(cid = it.cid, localUri = it.uri, mimeType = it.mimeType, fileName = it.fileName)+ }+ }+ fun inlineCleanupOrphans() { val edit = editText ?: return val editable = edit.text ?: return- val presentCids = editable.getSpans(0, editable.length, CidImageSpan::class.java)+ val spanCids = editable.getSpans(0, editable.length, CidImageSpan::class.java) .map { it.cid }.toSet()+ // Draft-restored images have no span until the editor re-parses the+ // HTML, but their cid is still referenced by the stored HTML; pruning+ // on spans alone would drop them again on the first edit.+ val htmlCids = CID_REFERENCE.findAll(html).map { it.groupValues[1] }.toSet()+ val presentCids = spanCids + htmlCids if (presentCids.size != inlineImages.size) { inlineImages.removeAll { it.cid !in presentCids } }@@ -163,6 +181,7 @@ class EmailHtmlEditorController( /** Provides sampled-bitmap decoding helpers for inline composer images. */ companion object {+ private val CID_REFERENCE = Regex("""cid:([^"'\s>]+)""") private fun decodeSampledBitmap(context: Context, uri: Uri, reqWidth: Int): Bitmap? { return try { val optsBounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }
email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.kt b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.ktindex ee1115fac4..ce9a5066c4 100644--- a/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.kt+++ b/email/src/test/java/com/vayunmathur/email/composer/EmailHtmlEditorControllerTest.kt@@ -94,6 +94,23 @@ class EmailHtmlEditorControllerTest { assertTrue(c.html.isNotEmpty() || c.html.isEmpty()) } + @Test+ fun `restored draft images survive orphan cleanup while referenced in html`() {+ val c = EmailHtmlEditorController("<div><img src=\"cid:[email protected]\"></div>")+ c.editText = EditText(context).apply { setText("plain text, spans not yet restored") }+ c.restoreInlineImages(+ listOf(+ InlineAttachment("[email protected]", Uri.parse("content://media/a.jpg"), "image/jpeg", "a.jpg"),+ InlineAttachment("[email protected]", Uri.parse("content://media/g.jpg"), "image/jpeg", "g.jpg"),+ ),+ )+ c.inlineCleanupOrphans()+ // The cid referenced by the draft HTML is kept for sending; the+ // unreferenced one is still pruned as an orphan.+ assertEquals(listOf("[email protected]"), c.inlineImages.map { it.cid })+ assertEquals(listOf("[email protected]"), c.toInlineAttachments().map { it.cid })+ }+ @Test fun `tag handler is exposed for draft re-parsing`() { val c = controller()
email/src/test/java/com/vayunmathur/email/draft/EmailDraftActionsTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/draft/EmailDraftActionsTest.kt b/email/src/test/java/com/vayunmathur/email/draft/EmailDraftActionsTest.ktindex f3eced7c69..695076c5de 100644--- a/email/src/test/java/com/vayunmathur/email/draft/EmailDraftActionsTest.kt+++ b/email/src/test/java/com/vayunmathur/email/draft/EmailDraftActionsTest.kt@@ -1,10 +1,12 @@ package com.vayunmathur.email.draft import android.app.Application+import android.net.Uri import androidx.room3.Room import androidx.test.core.app.ApplicationProvider import com.vayunmathur.email.data.EmailDatabase import com.vayunmathur.email.platform.EmailDraftActions+import com.vayunmathur.email.ui.composer.InlineAttachment import kotlinx.coroutines.CompletableDeferred import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers@@ -109,4 +111,55 @@ class EmailDraftActionsTest { fun `loading a missing draft returns null`() = runBlocking { assertNull(actions.load(999L)) }++ @Test+ fun `save persists inline images so a reopened draft can send them`() = runBlocking {+ val inline = InlineAttachment(+ cid = "[email protected]",+ uri = Uri.parse("content://com.vayunmathur.email.fileprovider/inline/logo.png"),+ mimeType = "image/png",+ fileName = "logo.png",+ )+ val saved = CompletableDeferred<Long>()+ actions.save(+ id = null, accountEmail = "[email protected]", to = "[email protected]",+ cc = "", bcc = "", subject = "Hi",+ body = "<div><img src=\"cid:[email protected]\"></div>",+ inlineImages = listOf(inline),+ onSaved = { saved.complete(it) },+ )+ val loaded = actions.load(withTimeout(30_000) { saved.await() })+ // Regression: save used to write the DraftEntry default "[]", so the+ // reopened draft's body still referenced cid:img1 but+ // toInlineAttachments() was empty and no MIME part was sent.+ assertEquals(listOf(inline), loaded?.let { EmailDraftActions.decodeInlineImages(it) })+ }++ @Test+ fun `resaving without an inline image clears the stored list`() = runBlocking {+ val inline = InlineAttachment(+ cid = "[email protected]",+ uri = Uri.parse("content://media/logo.png"),+ mimeType = "image/png",+ fileName = "logo.png",+ )+ val first = CompletableDeferred<Long>()+ actions.save(+ id = null, accountEmail = "[email protected]", to = "[email protected]",+ cc = "", bcc = "", subject = "Hi", body = "<div>x</div>",+ inlineImages = listOf(inline),+ onSaved = { first.complete(it) },+ )+ val id = withTimeout(30_000) { first.await() }+ val second = CompletableDeferred<Long>()+ actions.save(+ id = id, accountEmail = "[email protected]", to = "[email protected]",+ cc = "", bcc = "", subject = "Hi", body = "<div>x</div>",+ inlineImages = emptyList(),+ onSaved = { second.complete(it) },+ )+ withTimeout(30_000) { second.await() }+ val loaded = actions.load(id)+ assertEquals(emptyList(), loaded?.let { EmailDraftActions.decodeInlineImages(it) })+ } }