securemail: render HTML mail (links, formatting) with scripts and trackers off
- Commit
0f8569617a7402f72b380b2f7ddbf7b05a945a3a- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-02 04:46 UTC (1 month ago)
- Parents
f5cf271
Mail from Proton showed its plain-text alternative, where links appear as "Text [https://...]" and all formatting is lost. Rendering the HTML part fixes that; the plain-text view gains clickable links too. securemail - MimeCodec.parseMime returns MimeContent(subject, body, from, html): body stays plain text (previews, quoting, fallback), html is the first text/html part found in the MIME tree. The first three fields match the old Triple so existing destructuring is unchanged. - StoredMessage gains nullable decryptedHtml (Room v3 -> v4, ALTER TABLE ADD COLUMN). InboundStore and decryptStored persist it; storeDecrypted takes the html. - New MessageBodyView: HTML renders through library HtmlText with JavaScript off and every remote fetch blocked; a "Remote content blocked - Load" row appears only when the HTML actually references remote resources (src/background/srcset/url(), not plain links). Quoted history (incl. Proton's protonmail_quote) collapses behind "Show quoted text". Plain-text mail gets tappable http(s) links and mailto: for addresses via LinkAnnotation.Url. - ReaderScreen delegates the body to MessageBodyView. library/ui HtmlText (opt-in, defaults unchanged for the email app) - javaScriptEnabled (default true): untrusted mail can turn scripts off. - blockRemoteContent (default false): blockRemoteImages only stopped <img>; CSS backgrounds, web fonts, iframes and scripted fetches still hit the sender's server, which defeats tracking protection. When set, every non-cid request is answered locally with an empty response and the document carries a default-src 'none' CSP as a second layer. - .protonmail_quote joins the hide-quotes selector list. Messages received before this change have no stored HTML and keep the plain-text view. Verified: :securemail:compileDevKotlin and :email:compileDevKotlin, securemail unit tests (MimeCodecTest now 10 incl. HTML-part extraction), :securemail:lint and :library:ui:lint clean, :library:ui:detekt clean, securemail detekt unchanged at 40. Not yet viewed on a device.
Diff
library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt
diff --git a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.ktindex 404cd903e9..e46412ec1a 100644--- a/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt+++ b/library/ui/src/main/java/com/vayunmathur/library/ui/HtmlText.kt@@ -24,6 +24,12 @@ import java.io.File * embedded in a scrolling column, so in-place navigation would strand the user * on a full web page inside a message. Only turn this off for content that is * genuinely meant to be browsed in place.+ * @param javaScriptEnabled runs scripts in the content. Untrusted mail should+ * pass false: a sender's script otherwise executes on open.+ * @param blockRemoteContent refuses every network fetch (images, CSS, fonts,+ * iframes, script requests) - not just `<img>` like [blockRemoteImages] - so+ * opening a message cannot ping the sender's server. Inline `cid:` images+ * and `data:` URIs still load. */ @Composable fun HtmlText(@@ -33,6 +39,8 @@ fun HtmlText( hideQuotes: Boolean = false, cidMap: Map<String, File> = emptyMap(), openLinksExternally: Boolean = true,+ javaScriptEnabled: Boolean = true,+ blockRemoteContent: Boolean = false, ) { val backgroundColor = MaterialTheme.colorScheme.surface val onSurfaceColor = MaterialTheme.colorScheme.onSurface@@ -41,7 +49,7 @@ fun HtmlText( val backgroundHex = String.format("#%06X", 0xFFFFFF and backgroundColor.toArgb()) val textHex = String.format("#%06X", 0xFFFFFF and onSurfaceColor.toArgb()) val quoteCss = if (hideQuotes) {- "blockquote, .gmail_quote, .yahoo_quoted, .moz-cite-prefix, .gmail_extra { display: none !important; }"+ "blockquote, .gmail_quote, .yahoo_quoted, .moz-cite-prefix, .gmail_extra, .protonmail_quote { display: none !important; }" } else "" // Rewrite cid: -> https://cid.local/ to allow intercept without network permission@@ -60,6 +68,13 @@ fun HtmlText( val webClient = remember { HtmlTextWebViewClient() } webClient.cidMap = cidMap webClient.openLinksExternally = openLinksExternally+ webClient.blockRemoteContent = blockRemoteContent+ // Defence in depth alongside the request interceptor: the document itself+ // forbids any non-local fetch when remote content is blocked.+ val csp = if (blockRemoteContent) {+ "<meta http-equiv=\"Content-Security-Policy\" content=\"default-src 'none'; " ++ "img-src data: https://cid.local; style-src 'unsafe-inline'; font-src data:\">"+ } else "" AndroidView( modifier = modifier,@@ -70,7 +85,7 @@ fun HtmlText( ViewGroup.LayoutParams.WRAP_CONTENT, ) isVerticalScrollBarEnabled = false- settings.javaScriptEnabled = true+ settings.javaScriptEnabled = javaScriptEnabled settings.useWideViewPort = true settings.loadWithOverviewMode = false settings.builtInZoomControls = false@@ -82,7 +97,8 @@ fun HtmlText( } }, update = { webView ->- webView.settings.blockNetworkImage = blockRemoteImages+ webView.settings.blockNetworkImage = blockRemoteImages || blockRemoteContent+ webView.settings.javaScriptEnabled = javaScriptEnabled val htmlToLoad = if (cidMap.isEmpty()) html else rewrittenHtml val richCss = """ h1,h2,h3 { margin:0.5em 0; font-weight:600; line-height:1.25; }@@ -102,6 +118,7 @@ fun HtmlText( <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1">+ $csp <style> * { box-sizing: border-box; } html, body { max-width: 100%; }@@ -138,6 +155,7 @@ fun HtmlText( <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1">+ $csp <style> * { box-sizing: border-box; } html, body { max-width: 100%; }@@ -179,13 +197,14 @@ private class HtmlTextWebViewClient : WebViewClient() { var cidMap: Map<String, File> = emptyMap() var openLinksExternally: Boolean = true+ var blockRemoteContent: Boolean = false override fun shouldInterceptRequest( view: WebView?, request: WebResourceRequest?, ): WebResourceResponse? { val uri = request?.url ?: return null- if (uri.host != CID_HOST) return null+ if (uri.host != CID_HOST) return if (blockRemoteContent) emptyResponse() else null val cid = uri.lastPathSegment ?: uri.path?.removePrefix("/")?.substringAfterLast("/")@@ -225,6 +244,9 @@ private class HtmlTextWebViewClient : WebViewClient() { private companion object { const val CID_HOST = "cid.local" val IN_PLACE_SCHEMES = setOf("data", "about", "javascript", "blob")++ /** Answers a blocked fetch locally so nothing reaches the network. */+ fun emptyResponse() = WebResourceResponse("text/plain", "utf-8", java.io.ByteArrayInputStream(ByteArray(0))) } }
securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.ktindex be0970832f..dba9840ce5 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/InboundStore.kt@@ -37,7 +37,7 @@ object InboundStore { val keyManager = KeyManager(app) val folder = if (flags.spam) MailFolder.SPAM else MailFolder.INBOX if (flags.unencrypted) {- val (subject, body, from) = MimeCodec.parseMime(raw.toString(Charsets.UTF_8))+ val (subject, body, from, html) = MimeCodec.parseMime(raw.toString(Charsets.UTF_8)) repo.messageDao().upsert( StoredMessage( id = id,@@ -50,6 +50,7 @@ object InboundStore { decryptedSubject = subject, unencrypted = true, folder = folder,+ decryptedHtml = html, ), ) return@@ -90,7 +91,7 @@ object InboundStore { } else { provisional to null }- val (subject, body, from) = MimeCodec.parseMime(mime)+ val (subject, body, from, html) = MimeCodec.parseMime(mime) StoredMessage( id = id, from = from,@@ -103,6 +104,7 @@ object InboundStore { verifiedSigner = verified, unencrypted = false, folder = folder,+ decryptedHtml = html, ) }.getOrNull() } else {
securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.ktindex 11c26c8811..71d3236135 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/data/MailDatabase.kt@@ -48,6 +48,8 @@ data class StoredMessage( val isRead: Boolean = false, /** Folder assignment; defaults to INBOX (v2→v3 backfills existing rows). */ val folder: MailFolder = MailFolder.INBOX,+ /** Sender's HTML part, when the message had one (rendered by the reader). */+ val decryptedHtml: String? = null, ) /** Cached public key for a recipient (own directory, WKD, or VKS result). */@@ -92,9 +94,9 @@ interface MessageDao { @Query( "UPDATE StoredMessage SET decryptedBody = :body, decryptedSubject = :subject, " +- "verifiedSigner = :verified WHERE id = :id",+ "verifiedSigner = :verified, decryptedHtml = :html WHERE id = :id", )- suspend fun storeDecrypted(id: String, body: String, subject: String, verified: String?)+ suspend fun storeDecrypted(id: String, body: String, subject: String, verified: String?, html: String?) /** Permanently deletes everything in Trash (local only). */ @Query("DELETE FROM StoredMessage WHERE folder = 'TRASH'")@@ -145,7 +147,7 @@ interface OutboxDao { @Database( entities = [StoredMessage::class, CachedKey::class, OutboxMessage::class],- version = 3,+ version = 4, exportSchema = false, ) abstract class MailDatabase : RoomDatabase() {@@ -194,6 +196,11 @@ abstract class MailDatabase : RoomDatabase() { it.execSQL("ALTER TABLE StoredMessage ADD COLUMN folder TEXT NOT NULL DEFAULT 'INBOX'") } - override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3)+ /** v3 → v4: adds the nullable `decryptedHtml` column (HTML part of a message). */+ private val MIGRATION_3_4 = Migration(3, 4) {+ it.execSQL("ALTER TABLE StoredMessage ADD COLUMN decryptedHtml TEXT")+ }++ override val migrations: List<Migration> = listOf(MIGRATION_1_2, MIGRATION_2_3, MIGRATION_3_4) } }
securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.ktindex d36c8e3cb7..9279dfef31 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/domain/mail/MimeCodec.kt@@ -59,18 +59,29 @@ object MimeCodec { private const val ARMOR_BEGIN = "-----BEGIN PGP MESSAGE-----" /**- * Parses a MIME message into (subject, body, from): our own composer's- * text/plain, and whatever other providers send (Proton, Gmail): folded- * headers, RFC 2047 encoded-words, quoted-printable/base64 bodies in any- * charset, and multipart trees. Plain text is preferred; HTML-only mail is- * reduced to readable text.+ * A parsed message. [body] is always plain text (previews, quoting, and the+ * fallback view); [html] is the sender's HTML part when there is one, which+ * the reader renders so links and formatting survive. */- fun parseMime(mime: String): Triple<String, String, String> {+ data class MimeContent(val subject: String, val body: String, val from: String, val html: String?)++ /**+ * Parses a MIME message: our own composer's text/plain, and whatever other+ * providers send (Proton, Gmail): folded headers, RFC 2047 encoded-words,+ * quoted-printable/base64 bodies in any charset, and multipart trees.+ */+ fun parseMime(mime: String): MimeContent { val (headers, body) = splitEntity(mime)- return Triple(- decodeWords(headers["subject"].orEmpty()),- readableBody(headers, body).trimEnd(),- decodeWords(headers["from"].orEmpty()),+ val html = findPart(headers, body, "text/html")+ val charset = param(headers["content-type"].orEmpty(), "charset")+ val text = findPart(headers, body, "text/plain")+ ?: html?.let(::htmlToText)+ ?: decodeTransfer(body, headers["content-transfer-encoding"], charset)+ return MimeContent(+ subject = decodeWords(headers["subject"].orEmpty()),+ body = text.trimEnd(),+ from = decodeWords(headers["from"].orEmpty()),+ html = html, ) } @@ -101,22 +112,19 @@ object MimeCodec { return headers to body } - private fun readableBody(headers: Map<String, String>, body: String): String {+ /** Decoded text of the first part of [wanted] type, searching multipart trees depth-first. */+ private fun findPart(headers: Map<String, String>, body: String, wanted: String): String? { val type = headers["content-type"].orEmpty() val mediaType = type.substringBefore(';').trim().lowercase().ifEmpty { "text/plain" } if (mediaType.startsWith("multipart/")) {- val boundary = param(type, "boundary") ?: return body- val parts = multipartParts(body, boundary).map { splitEntity(it) }- fun typeOf(h: Map<String, String>) =- h["content-type"].orEmpty().substringBefore(';').trim().lowercase().ifEmpty { "text/plain" }- val chosen = parts.firstOrNull { typeOf(it.first) == "text/plain" }- ?: parts.firstOrNull { typeOf(it.first).startsWith("multipart/") }- ?: parts.firstOrNull { typeOf(it.first) == "text/html" }- ?: return ""- return readableBody(chosen.first, chosen.second)+ val boundary = param(type, "boundary") ?: return null+ return multipartParts(body, boundary).firstNotNullOfOrNull { part ->+ val (h, b) = splitEntity(part)+ findPart(h, b, wanted)+ } }- val decoded = decodeTransfer(body, headers["content-transfer-encoding"], param(type, "charset"))- return if (mediaType == "text/html") htmlToText(decoded) else decoded+ if (mediaType != wanted) return null+ return decodeTransfer(body, headers["content-transfer-encoding"], param(type, "charset")) } private fun multipartParts(body: String, boundary: String): List<String> {@@ -187,7 +195,8 @@ object MimeCodec { }.getOrDefault(m.value) } - private fun htmlToText(html: String): String = html+ /** Readable plain text from an HTML body (for previews and the no-HTML fallback). */+ fun htmlToText(html: String): String = html .replace(Regex("(?is)<(style|script|head)[^>]*>.*?</\\1>"), "") .replace(Regex("(?i)<br\\s*/?>"), "\n") .replace(Regex("(?i)</(p|div|tr|li|h[1-6]|blockquote)>"), "\n")
securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.ktindex ae473aafbf..594e16acdb 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/platform/MailViewModel.kt@@ -384,10 +384,11 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { } else { provisional to null }- val (subject, body, resolvedFrom) = parseMime(mime)+ val (subject, body, resolvedFrom, html) = parseMime(mime) repo.messageDao().storeDecrypted( id, body, subject, verified = verified,+ html = html, ) if (resolvedFrom.isNotBlank()) { repo.messageDao().upsert(stored.copy(from = resolvedFrom))@@ -740,7 +741,7 @@ class MailViewModel(app: Application) : AndroidViewModel(app) { * trailing `--boundary--`). Returns (subject, body, from). The payload is * already authenticated PGP plaintext at this point; this only splits it. */- private fun parseMime(mime: String): Triple<String, String, String> =+ private fun parseMime(mime: String): com.vayunmathur.securemail.domain.mail.MimeCodec.MimeContent = com.vayunmathur.securemail.domain.mail.MimeCodec.parseMime(mime) private fun newMessageId(): String = "${UUID.randomUUID()}@maemail.org"
securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.ktnew file mode 100644index 0000000000..8c4b59d4da--- /dev/null+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/MessageBodyView.kt@@ -0,0 +1,123 @@+package com.vayunmathur.securemail.ui++import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.padding+import androidx.compose.runtime.Composable+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.text.AnnotatedString+import androidx.compose.ui.text.LinkAnnotation+import androidx.compose.ui.text.SpanStyle+import androidx.compose.ui.text.TextLinkStyles+import androidx.compose.ui.text.buildAnnotatedString+import androidx.compose.ui.text.style.TextDecoration+import androidx.compose.ui.unit.dp+import com.vayunmathur.library.ui.HtmlText+import com.vayunmathur.library.ui.MaterialTheme+import com.vayunmathur.library.ui.Text+import com.vayunmathur.library.ui.TextButton+import com.vayunmathur.securemail.data.StoredMessage++/**+ * Message body: the sender's HTML part when there is one (links, lists,+ * formatting), otherwise plain text with clickable URLs. HTML renders with+ * scripts off and every remote fetch blocked until the user opts in, so+ * opening a message can't run sender code or ping a tracker.+ */+@Composable+fun MessageBodyView(msg: StoredMessage) {+ val html = msg.decryptedHtml+ if (html != null) HtmlBody(msg.id, html) else PlainBody(msg)+}++@Composable+private fun HtmlBody(id: String, html: String) {+ var loadRemote by remember(id) { mutableStateOf(false) }+ var showQuotes by remember(id) { mutableStateOf(false) }+ val hasRemote = remember(html) { REMOTE_REF.containsMatchIn(html) }+ val hasQuotes = remember(html) { QUOTE_MARKERS.any { html.contains(it, ignoreCase = true) } }+ Column {+ if (hasRemote && !loadRemote) {+ Row(+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp),+ horizontalArrangement = Arrangement.SpaceBetween,+ verticalAlignment = Alignment.CenterVertically,+ ) {+ Text(+ "Remote content blocked",+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant,+ )+ TextButton(onClick = { loadRemote = true }) { Text("Load") }+ }+ }+ HtmlText(+ html = html,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+ blockRemoteImages = !loadRemote,+ blockRemoteContent = !loadRemote,+ javaScriptEnabled = false,+ hideQuotes = hasQuotes && !showQuotes,+ )+ if (hasQuotes) {+ TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) {+ Text(if (showQuotes) "Hide quoted text" else "Show quoted text")+ }+ }+ }+}++@Composable+private fun PlainBody(msg: StoredMessage) {+ val body = msg.decryptedBody ?: "(decrypting\u2026)"+ var showQuotes by remember(msg.id) { mutableStateOf(false) }+ val (main, quoted) = remember(body) { splitQuotedText(body) }+ val linkColor = MaterialTheme.colorScheme.primary+ val shown = if (showQuotes || quoted.isEmpty()) body else main+ val annotated = remember(shown, linkColor) { linkify(shown, linkColor) }+ Text(+ annotated,+ style = MaterialTheme.typography.bodyMedium,+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),+ )+ if (quoted.isNotEmpty()) {+ TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) {+ Text(if (showQuotes) "Hide quoted text" else "Show quoted text")+ }+ }+}++/** Plain text with http(s) URLs and email addresses turned into tappable links. */+private fun linkify(text: String, color: androidx.compose.ui.graphics.Color): AnnotatedString = buildAnnotatedString {+ append(text)+ val style = TextLinkStyles(SpanStyle(color = color, textDecoration = TextDecoration.Underline))+ URL.findAll(text).forEach { m ->+ val raw = m.value.trimEnd('.', ',', ')', ']', ';', ':', '!', '?')+ val target = if (raw.contains('@') && !raw.startsWith("http", ignoreCase = true)) "mailto:$raw" else raw+ addLink(LinkAnnotation.Url(target, style), m.range.first, m.range.first + raw.length)+ }+}++private fun splitQuotedText(body: String): Pair<String, String> {+ val lines = body.split("\n")+ val onWrote = Regex("^On .+ wrote:\\s*$")+ val origMsg = Regex("^-{2,}\\s*Original Message\\s*-{2,}\\s*$", RegexOption.IGNORE_CASE)+ for (i in lines.indices) {+ val line = lines[i].trim()+ if (i > 0 && (onWrote.matches(line) || origMsg.matches(line) || line.startsWith(">"))) {+ return lines.subList(0, i).joinToString("\n").trimEnd() to lines.subList(i, lines.size).joinToString("\n")+ }+ }+ return body to ""+}++private val URL = Regex("""https?://[^\s<>"]+|[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}""")+private val REMOTE_REF = Regex("""(?i)(src|background|srcset)\s*=\s*["']?\s*https?://|url\(\s*["']?https?://""")+private val QUOTE_MARKERS = listOf("protonmail_quote", "gmail_quote", "yahoo_quoted", "moz-cite-prefix", "<blockquote")
securemail/src/main/java/com/vayunmathur/securemail/ui/ReaderScreen.kt
diff --git a/securemail/src/main/java/com/vayunmathur/securemail/ui/ReaderScreen.kt b/securemail/src/main/java/com/vayunmathur/securemail/ui/ReaderScreen.ktindex 7bcd598fcd..213b4c289a 100644--- a/securemail/src/main/java/com/vayunmathur/securemail/ui/ReaderScreen.kt+++ b/securemail/src/main/java/com/vayunmathur/securemail/ui/ReaderScreen.kt@@ -37,7 +37,6 @@ import com.vayunmathur.library.ui.ModalBottomSheet import com.vayunmathur.library.ui.OutlinedButton import com.vayunmathur.library.ui.Surface import com.vayunmathur.library.ui.Text-import com.vayunmathur.library.ui.TextButton import com.vayunmathur.library.ui.appBarScrollBehavior import com.vayunmathur.library.ui.rememberModalBottomSheetState import com.vayunmathur.securemail.data.MailFolder@@ -127,7 +126,7 @@ private fun MessageBody(msg: StoredMessage, ownAddress: String, onReply: () -> U } } - BodyText(msg)+ MessageBodyView(msg) Row(modifier = Modifier.padding(16.dp)) { OutlinedButton(onClick = onReply, modifier = Modifier.weight(1f)) {@@ -186,23 +185,6 @@ private fun TrustLine(msg: StoredMessage) { } } -@Composable-private fun BodyText(msg: StoredMessage) {- val body = msg.decryptedBody ?: "(decrypting\u2026)"- var showQuotes by remember(msg.id) { mutableStateOf(false) }- val (main, quoted) = remember(body) { splitQuotedText(body) }- Text(- if (showQuotes || quoted.isEmpty()) body else main,- style = MaterialTheme.typography.bodyMedium,- modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp),- )- if (quoted.isNotEmpty()) {- TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) {- Text(if (showQuotes) "Hide quoted text" else "Show quoted text")- }- }-}- @Composable private fun DetailRow(label: String, address: String, avatarColor: Color) { Column(modifier = Modifier.padding(vertical = 8.dp)) {@@ -222,16 +204,3 @@ private fun Avatar(address: String, color: Color, contentColor: Color, sizeDp: I } } }--private fun splitQuotedText(body: String): Pair<String, String> {- val lines = body.split("\n")- val onWrote = Regex("^On .+ wrote:\\s*$")- val origMsg = Regex("^-{2,}\\s*Original Message\\s*-{2,}\\s*$", RegexOption.IGNORE_CASE)- for (i in lines.indices) {- val line = lines[i].trim()- if (i > 0 && (onWrote.matches(line) || origMsg.matches(line) || line.startsWith(">"))) {- return lines.subList(0, i).joinToString("\n").trimEnd() to lines.subList(i, lines.size).joinToString("\n")- }- }- return body to ""-}
securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt
diff --git a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.ktindex 46f3c95e2a..f61b1c22ae 100644--- a/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt+++ b/securemail/src/test/java/com/vayunmathur/securemail/domain/mail/MimeCodecTest.kt@@ -87,15 +87,21 @@ class MimeCodecTest { @Test fun multipartAlternativePrefersPlainText() {- val (_, body, _) = MimeCodec.parseMime(+ val parsed = MimeCodec.parseMime( "Subject: x\r\n" + "Content-Type: multipart/alternative;\r\n boundary=\"b1\"\r\n" + "\r\n" +- "--b1\r\nContent-Type: text/html\r\n\r\n<p>html version</p>\r\n" ++ "--b1\r\nContent-Type: text/html\r\n\r\n<p>html <a href=\"https://proton.me\">version</a></p>\r\n" + "--b1\r\nContent-Type: text/plain; charset=utf-8\r\n\r\nplain version\r\n" + "--b1--\r\n", )- assertEquals("plain version", body)+ assertEquals("plain version", parsed.body)+ assertEquals("<p>html <a href=\"https://proton.me\">version</a></p>\n", parsed.html)+ }++ @Test+ fun plainOnlyMailHasNoHtml() {+ assertNull(MimeCodec.parseMime("Subject: x\r\nContent-Type: text/plain\r\n\r\nhi\r\n").html) } @Test