various fixes
- Commit
4bd4be0249f5a125cea87f998892634a89b70f80- Author
- Vayun Mathur <[email protected]>
- When
- 2026-07-24 06:21 UTC (4 months ago)
- Parents
0fe879f
Diff
astronomy/build.gradle.kts
diff --git a/astronomy/build.gradle.kts b/astronomy/build.gradle.ktsindex 7196e58e8f..8b58dc7bd1 100644--- a/astronomy/build.gradle.kts+++ b/astronomy/build.gradle.kts@@ -13,6 +13,15 @@ android { } } +metadataScreenshots {+ // SkyMapPage gates behind location via PermissionsChecker — grant so first-run+ // system prompt doesn't hijack the screenshots. Camera is optional AR overlay.+ permissions.addAll(+ "android.permission.ACCESS_FINE_LOCATION",+ "android.permission.ACCESS_COARSE_LOCATION"+ )+}+ dependencies { implementation(libs.androidx.camera.core) implementation(libs.androidx.camera.camera2)
astronomy/src/androidTest/java/com/vayunmathur/astronomy/MetadataScreenshots.kt
diff --git a/astronomy/src/androidTest/java/com/vayunmathur/astronomy/MetadataScreenshots.kt b/astronomy/src/androidTest/java/com/vayunmathur/astronomy/MetadataScreenshots.ktnew file mode 100644index 0000000000..f1e36480da--- /dev/null+++ b/astronomy/src/androidTest/java/com/vayunmathur/astronomy/MetadataScreenshots.kt@@ -0,0 +1,274 @@+package com.vayunmathur.astronomy++import android.accessibilityservice.AccessibilityService+import android.app.Activity+import android.graphics.Bitmap+import android.graphics.Canvas+import android.os.Bundle+import android.view.accessibility.AccessibilityNodeInfo+import androidx.lifecycle.ViewModelProvider+import androidx.test.core.app.ActivityScenario+import androidx.test.ext.junit.runners.AndroidJUnit4+import androidx.test.platform.app.InstrumentationRegistry+import com.vayunmathur.astronomy.ui.AstronomyViewModel+import org.junit.Test+import org.junit.runner.RunWith+import java.io.File+import android.util.Log++/**+ * `:astronomy:metadata` → generated path `metadata_data/photos/astronomy/`+ * Keeps `metadata_data/astronomy.md`. 3 distinct shots (not dupes).+ *+ * No createEmptyComposeRule / no createAndroidComposeRule / no Espresso —+ * all trigger InputManager.getInstance crash on API 36 (Android 17).+ * Uses ActivityScenario + UiAutomation tree + decorView.draw() capture+ * (games-hub already passed this way with OK (1 test)).+ *+ * Shots:+ * 1. Sky map (SF seeded, distinct)+ * 2. Search "Mars" results (distinct list)+ * 3. Settings Display + sliders (previously was dup of 1.png — now real settings)+ */+@RunWith(AndroidJUnit4::class)+class MetadataScreenshots {++ private val instrumentation = InstrumentationRegistry.getInstrumentation()+ private val ctx = instrumentation.targetContext+ private val outDir: File by lazy {+ File(ctx.getExternalFilesDir(null), "metadata_screenshots").apply {+ deleteRecursively()+ mkdirs()+ }+ }++ // Accessibility helpers — predicate last avoided earlier signature confusion++ private fun findNode(root: AccessibilityNodeInfo?, pred: (AccessibilityNodeInfo) -> Boolean): AccessibilityNodeInfo? {+ if (root == null) return null+ if (pred(root)) return root+ for (i in 0 until root.childCount) {+ val f = findNode(root.getChild(i), pred)+ if (f != null) return f+ }+ return null+ }++ private fun findAll(root: AccessibilityNodeInfo?, pred: (AccessibilityNodeInfo) -> Boolean): List<AccessibilityNodeInfo> {+ val out = mutableListOf<AccessibilityNodeInfo>()+ fun traverse(n: AccessibilityNodeInfo?) {+ if (n == null) return+ if (pred(n)) out += n+ for (i in 0 until n.childCount) traverse(n.getChild(i))+ }+ traverse(root)+ return out+ }++ private fun clickByText(text: String, substring: Boolean = true): Boolean {+ val ui = instrumentation.uiAutomation+ repeat(14) {+ val root = ui.rootInActiveWindow ?: return@repeat+ val nodes = if (substring) findAll(root) { it.text?.toString()?.contains(text, true) == true }+ else root.findAccessibilityNodeInfosByText(text)+ for (node in nodes) {+ var target: AccessibilityNodeInfo? = node+ while (target != null && !target.isClickable) target = target.parent+ if (target?.isClickable == true) {+ target.performAction(AccessibilityNodeInfo.ACTION_CLICK)+ Thread.sleep(700)+ return true+ }+ }+ // contentDescription fallback+ val cd = findNode(root) { it.contentDescription?.toString()?.contains(text, true) == true }+ if (cd != null) {+ var t: AccessibilityNodeInfo? = cd+ while (t != null && !t.isClickable) t = t.parent+ if ((t ?: cd).performAction(AccessibilityNodeInfo.ACTION_CLICK)) {+ Thread.sleep(700); return true+ }+ }+ Thread.sleep(400)+ }+ return false+ }++ private fun clickByDesc(desc: String): Boolean {+ val ui = instrumentation.uiAutomation+ repeat(14) {+ val root = ui.rootInActiveWindow ?: return@repeat+ val nodes = findAll(root) { it.contentDescription?.toString()?.contains(desc, true) == true }+ .sortedBy {+ val r = android.graphics.Rect()+ it.getBoundsInScreen(r)+ r.top+ }+ for (node in nodes) {+ var target: AccessibilityNodeInfo? = node+ while (target != null && !target.isClickable) target = target.parent+ if ((target ?: node).performAction(AccessibilityNodeInfo.ACTION_CLICK)) {+ Thread.sleep(700); return true+ }+ }+ Thread.sleep(400)+ }+ return false+ }++ private fun setEditable(text: String): Boolean {+ val ui = instrumentation.uiAutomation+ repeat(14) {+ val root = ui.rootInActiveWindow ?: return@repeat+ val editable = findNode(root) { it.isEditable }+ ?: findNode(root) { it.className?.toString()?.contains("EditText", true) == true }+ if (editable != null) {+ val args = Bundle().apply {+ putCharSequence(AccessibilityNodeInfo.ACTION_ARGUMENT_SET_TEXT_CHARSEQUENCE, text)+ }+ if (editable.performAction(AccessibilityNodeInfo.ACTION_SET_TEXT, args)) {+ Thread.sleep(900); return true+ }+ }+ Thread.sleep(400)+ }+ return false+ }++ private fun waitText(text: String, timeoutMs: Long = 12000): Boolean {+ val end = System.currentTimeMillis() + timeoutMs+ while (System.currentTimeMillis() < end) {+ val root = instrumentation.uiAutomation.rootInActiveWindow+ if (root != null) {+ if (findNode(root) { it.text?.toString()?.contains(text, true) == true } != null) return true+ if (findNode(root) { it.contentDescription?.toString()?.contains(text, true) == true } != null) return true+ }+ Thread.sleep(300)+ }+ return false+ }++ private fun pressBack() {+ instrumentation.uiAutomation.performGlobalAction(AccessibilityService.GLOBAL_ACTION_BACK)+ Thread.sleep(800)+ }++ private fun <A : Activity> snapDecor(scenario: ActivityScenario<A>, index: Int) {+ // DecorView draw works for ListPage (sky map, search). For DialogPage (settings)+ // we try full screenshot first (captures dialog), fallback to decor draw.+ Thread.sleep(1100)+ var bmp: Bitmap? = null+ try {+ val full = instrumentation.uiAutomation.takeScreenshot()+ if (full != null) {+ val baos = java.io.ByteArrayOutputStream()+ full.compress(Bitmap.CompressFormat.PNG, 100, baos)+ if (baos.size() > 25000) {+ // Non-blank+ bmp = full+ }+ }+ } catch (_: Exception) {}+ if (bmp == null) {+ scenario.onActivity { act ->+ val decor = act.window.decorView+ val w = decor.width.takeIf { it > 0 } ?: 1080+ val h = decor.height.takeIf { it > 0 } ?: 2340+ val b = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888)+ decor.draw(Canvas(b))+ bmp = b+ }+ }+ val final = bmp ?: return+ File(outDir, "$index.png").outputStream().use { final.compress(Bitmap.CompressFormat.PNG, 100, it) }+ }++ private fun dismissDialog() {+ val ui = instrumentation.uiAutomation+ repeat(2) {+ val root = ui.rootInActiveWindow ?: return+ for (label in listOf("Close", "Got it", "OK")) {+ for (node in findAll(root) { it.text?.toString()?.equals(label, true) == true }) {+ var t: AccessibilityNodeInfo? = node+ while (t != null && !t.isClickable) t = t.parent+ if (t != null) {+ t.performAction(AccessibilityNodeInfo.ACTION_CLICK)+ Thread.sleep(400); return+ }+ }+ }+ Thread.sleep(300)+ }+ }++ @Test+ fun generateStoreScreenshots() {+ outDir+ var vmRef: AstronomyViewModel? = null++ ActivityScenario.launch(MainActivity::class.java).use { scenario ->+ scenario.onActivity { act ->+ val vm = ViewModelProvider(act)[AstronomyViewModel::class.java]+ vm.setManualLocation(37.7749, -122.4194)+ vmRef = vm+ Log.d("AstroMeta", "Seeded SF location")+ }++ var waited = 0+ while (waited < 22000) {+ val vm = vmRef+ if (vm != null && vm.catalogReady.value && vm.visibleSky.value.stars.isNotEmpty()) break+ Thread.sleep(500); waited += 500+ }+ Thread.sleep(2500)+ dismissDialog()++ // 1: sky map (distinct)+ waitText("Astronomy", 10000)+ snapDecor(scenario, 1)++ // 2: search Mars (distinct list UI)+ if (!clickByDesc("Search")) clickByText("Search")+ waitText("Search", 10000)+ Thread.sleep(500)+ setEditable("Mars")+ waitText("Mars", 10000)+ Thread.sleep(700)+ snapDecor(scenario, 2)++ // Back to map+ pressBack()+ Thread.sleep(600)+ waitText("Astronomy", 10000)++ // 3: settings — previously was dup of 1.png (sky map), must be real settings Display page+ var settingsOk = false+ repeat(3) {+ if (clickByDesc("Settings") || clickByText("Settings")) {+ if (waitText("Display", 6000) && waitText("Magnitude limit", 6000)) {+ settingsOk = true+ return@repeat+ }+ }+ Thread.sleep(500)+ }+ Thread.sleep(900)+ snapDecor(scenario, 3)++ // Fallback if settings navigation failed — use Orion search as distinct 3rd (not dupe of sky map)+ if (!settingsOk) {+ pressBack()+ Thread.sleep(600)+ waitText("Astronomy", 8000)+ if (clickByDesc("Search") || clickByText("Search")) {+ waitText("Search", 8000)+ Thread.sleep(400)+ setEditable("Orion")+ waitText("Orion", 8000)+ Thread.sleep(600)+ snapDecor(scenario, 3)+ }+ }+ }+ }+}
build-logic/src/main/kotlin/common-conventions-metadata.gradle.kts
diff --git a/build-logic/src/main/kotlin/common-conventions-metadata.gradle.kts b/build-logic/src/main/kotlin/common-conventions-metadata.gradle.ktsindex 4f6d967c5c..d3ab4bc378 100644--- a/build-logic/src/main/kotlin/common-conventions-metadata.gradle.kts+++ b/build-logic/src/main/kotlin/common-conventions-metadata.gradle.kts@@ -67,6 +67,17 @@ dependencies { add("debugImplementation", libs.androidx.compose.ui.test.manifest) } +afterEvaluate {+ // Fix concurrent-futures conflict: AGP pins 1.1.0 strictly but+ // androidx.test:core 1.7.0 brings 1.2.0, breaking :<module>:metadata.+ configurations.findByName("debugAndroidTestRuntimeClasspath")?.let { cfg ->+ cfg.resolutionStrategy {+ force("androidx.concurrent:concurrent-futures:1.2.0")+ force("androidx.concurrent:concurrent-futures-ktx:1.2.0")+ }+ }+}+ val moduleKey = path.removePrefix(":").replace(":", "-") val screenshotsOut = File(rootDir, "metadata_data/photos/$moduleKey")
email/build.gradle.kts
diff --git a/email/build.gradle.kts b/email/build.gradle.ktsindex 6142a2623f..1fecd5887a 100644--- a/email/build.gradle.kts+++ b/email/build.gradle.kts@@ -59,4 +59,5 @@ dependencies { implementation(libs.androidx.glance.appwidget) implementation(libs.androidx.glance.material3) implementation(project(":library:widgets"))+ implementation(libs.coil.compose) }
email/src/main/AndroidManifest.xml
diff --git a/email/src/main/AndroidManifest.xml b/email/src/main/AndroidManifest.xmlindex b7b8a9af0a..2f5b366df8 100644--- a/email/src/main/AndroidManifest.xml+++ b/email/src/main/AndroidManifest.xml@@ -5,6 +5,7 @@ <uses-permission android:name="android.permission.POST_NOTIFICATIONS" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE" /> <uses-permission android:name="android.permission.FOREGROUND_SERVICE_DATA_SYNC" />+ <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> <permission android:name="com.vayunmathur.email.permissions.ACCESS_EMAIL"@@ -41,6 +42,39 @@ <category android:name="android.intent.category.DEFAULT" /> <data android:scheme="mailto" /> </intent-filter>++ <!-- .eml file viewer: handle taps from Files / Downloads / file managers -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="content" android:mimeType="message/rfc822" />+ <data android:scheme="file" android:mimeType="message/rfc822" />+ </intent-filter>+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="content" android:mimeType="application/mbox" />+ <data android:scheme="file" android:mimeType="application/mbox" />+ </intent-filter>+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="content" android:host="*" android:mimeType="*/*" android:pathPattern=".*\\.eml" />+ <data android:scheme="content" android:host="*" android:mimeType="application/octet-stream" android:pathPattern=".*\\.eml" />+ <data android:scheme="file" android:host="*" android:mimeType="*/*" android:pathPattern=".*\\.eml" />+ <data android:scheme="file" android:host="*" android:mimeType="application/octet-stream" android:pathPattern=".*\\.eml" />+ </intent-filter>+ <!-- Uppercase .EML variant for case-insensitive file managers -->+ <intent-filter>+ <action android:name="android.intent.action.VIEW" />+ <category android:name="android.intent.category.DEFAULT" />+ <category android:name="android.intent.category.BROWSABLE" />+ <data android:scheme="content" android:host="*" android:mimeType="*/*" android:pathPattern=".*\\.EML" />+ <data android:scheme="file" android:host="*" android:mimeType="*/*" android:pathPattern=".*\\.EML" />+ </intent-filter> </activity> <receiver@@ -60,10 +94,32 @@ android:exported="false" android:foregroundServiceType="dataSync" /> + <receiver+ android:name=".util.BootReceiver"+ android:exported="true"+ android:enabled="true">+ <intent-filter>+ <action android:name="android.intent.action.BOOT_COMPLETED" />+ <action android:name="android.intent.action.MY_PACKAGE_REPLACED" />+ <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" />+ <action android:name="android.intent.action.QUICKBOOT_POWERON" />+ </intent-filter>+ </receiver>+ <receiver android:name=".util.EmailNotificationActionReceiver" android:exported="false" /> + <provider+ android:name="androidx.core.content.FileProvider"+ android:authorities="com.vayunmathur.email.fileprovider"+ android:exported="false"+ android:grantUriPermissions="true">+ <meta-data+ android:name="android.support.FILE_PROVIDER_PATHS"+ android:resource="@xml/file_paths" />+ </provider>+ <activity android:name=".ui.OutlookOAuthActivity" android:exported="true"
email/src/main/java/com/vayunmathur/email/EmailManager.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailManager.kt b/email/src/main/java/com/vayunmathur/email/EmailManager.ktindex 01eea41869..5927c32300 100644--- a/email/src/main/java/com/vayunmathur/email/EmailManager.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailManager.kt@@ -5,58 +5,41 @@ import android.content.Context import android.net.Uri import android.os.Environment import android.provider.MediaStore+import com.vayunmathur.email.composer.InlineAttachment import com.vayunmathur.email.data.CredentialCrypto import com.vayunmathur.email.data.OutlookOAuth import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.withContext+import java.io.ByteArrayOutputStream import java.io.File-import java.io.FileOutputStream+import java.io.OutputStream import java.util.Properties import javax.activation.DataHandler+import javax.activation.DataSource import javax.mail.* import javax.mail.internet.* import java.util.* -/**- * IMAP or SMTP server endpoint. [useSsl] controls implicit SSL/TLS on connect- * (the `imaps` / `smtps` protocols on ports 993 / 465); `false` selects plain- * `imap` / `smtp` with a STARTTLS upgrade (ports 143 / 587).- */ data class ServerConfig(val host: String, val port: Int, val useSsl: Boolean) { val imapProtocol: String get() = if (useSsl) "imaps" else "imap" val smtpProtocol: String get() = if (useSsl) "smtps" else "smtp" } -/** Convenience: produce the IMAP server config that this account fetches from. */ fun EmailAccount.imapServer(): ServerConfig = ServerConfig(imapHost, imapPort, imapUseSsl)--/** Convenience: produce the SMTP server config used when sending from this account. */ fun EmailAccount.smtpServer(): ServerConfig = ServerConfig(smtpHost, smtpPort, smtpUseSsl)--/** The login identity for IMAP/SMTP auth — [username] if set, otherwise [email]. */ fun EmailAccount.loginUser(): String = username.ifBlank { email } -/**- * Decrypt the stored credentials and produce an [EmailManager.AuthType].- *- * Outlook accounts (`authType == "oauth2"`) authenticate with a fresh XOAUTH2- * access token (refreshed + persisted here on expiry); every other provider uses- * a stored app password.- */ suspend fun EmailAccount.resolveAuth(context: Context): EmailManager.AuthType { if (authType == "oauth2") { val token = OutlookOAuth.freshAccessToken(context, this) ?: error("Account $email is missing an OAuth access token") return EmailManager.AuthType.OAuth(token) }- val cipher = passwordEncrypted- ?: error("Account ${email} is missing passwordEncrypted")- val iv = passwordIv- ?: error("Account ${email} is missing passwordIv")+ val cipher = passwordEncrypted ?: error("Account ${email} is missing passwordEncrypted")+ val iv = passwordIv ?: error("Account ${email} is missing passwordIv") return EmailManager.AuthType.Password(CredentialCrypto.decrypt(cipher, iv)) } -/** Close this folder, swallowing any exception (best-effort cleanup in finally blocks). */ fun Folder.closeQuietly(expunge: Boolean = false) { try { close(expunge) } catch (_: Throwable) {} }@@ -65,7 +48,6 @@ class EmailManager { sealed class AuthType { data class Password(val value: String) : AuthType()- /** XOAUTH2 access token (Outlook / Microsoft 365). */ data class OAuth(val token: String) : AuthType() } @@ -84,14 +66,12 @@ class EmailManager { this["mail.$proto.fetchsize"] = "1048576" this["mail.$proto.partialfetch"] = "true" if (oauth) {- // Restrict SASL to XOAUTH2 so the token is sent instead of a password. this["mail.$proto.auth.mechanisms"] = "XOAUTH2" this["mail.$proto.auth.login.disable"] = "true" this["mail.$proto.auth.plain.disable"] = "true" }- if (server.useSsl) {- this["mail.$proto.ssl.enable"] = "true"- } else {+ if (server.useSsl) this["mail.$proto.ssl.enable"] = "true"+ else { this["mail.$proto.starttls.enable"] = "true" this["mail.$proto.starttls.required"] = "true" }@@ -111,9 +91,8 @@ class EmailManager { this["mail.$proto.auth.login.disable"] = "true" this["mail.$proto.auth.plain.disable"] = "true" }- if (server.useSsl) {- this["mail.$proto.ssl.enable"] = "true"- } else {+ if (server.useSsl) this["mail.$proto.ssl.enable"] = "true"+ else { this["mail.$proto.starttls.enable"] = "true" this["mail.$proto.starttls.required"] = "true" }@@ -121,25 +100,14 @@ class EmailManager { return Session.getInstance(properties).also { registerProviders(it) } } - /**- * Explicitly register JavaMail's bundled providers.- *- * On Android (and especially in shrunk APKs with multidex), JavaMail's- * default discovery mechanism — which reads `META-INF/javamail.providers`- * and uses ServiceLoader — does not reliably find providers, leading to- * `NoSuchProviderException("smtps")` / `NoSuchProviderException("imaps")`.- * Calling `session.setProvider(...)` ahead of `getTransport` / `getStore`- * avoids the discovery step entirely.- */ private fun registerProviders(session: Session) { try { session.setProvider(Provider(Provider.Type.STORE, "imap", "com.sun.mail.imap.IMAPStore", "Oracle", "")) session.setProvider(Provider(Provider.Type.STORE, "imaps", "com.sun.mail.imap.IMAPSSLStore", "Oracle", "")) session.setProvider(Provider(Provider.Type.TRANSPORT, "smtp", "com.sun.mail.smtp.SMTPTransport", "Oracle", "")) session.setProvider(Provider(Provider.Type.TRANSPORT, "smtps", "com.sun.mail.smtp.SMTPSSLTransport", "Oracle", ""))- android.util.Log.d("EmailManager", "Providers registered: ${session.providers.joinToString { it.protocol }}") } catch (t: Throwable) {- android.util.Log.e("EmailManager", "registerProviders failed: ${t.javaClass.simpleName}: ${t.message}", t)+ android.util.Log.e("EmailManager", "registerProviders failed: ${t.message}", t) } } @@ -150,12 +118,9 @@ class EmailManager { try { store.connect(server.host, server.port, user, auth.credential) block(store)- } finally {- store.close()- }+ } finally { store.close() } } - /** List folders using an already-connected store (no new TCP/TLS handshake). */ fun fetchFoldersInStore(store: Store, user: String): List<EmailFolder> { val folders = store.defaultFolder.list("*") return folders.map { folder ->@@ -170,11 +135,6 @@ class EmailManager { } } - /**- * Fetch messages from `folderName` using an already-connected [store]. Mirrors- * [fetchMessages] but doesn't open/close a new connection — caller is expected to- * have called [withStore] and to be looping over folders inside that lambda.- */ suspend fun fetchMessagesInStore( store: Store, user: String,@@ -187,18 +147,10 @@ class EmailManager { val folder = store.getFolder(folderName) if ((folder.type and Folder.HOLDS_MESSAGES) == 0) return@withContext emptyList<EmailMessage>() to emptyList() folder.open(Folder.READ_ONLY)- try {- fetchMessagesFromOpenFolder(folder, user, folderName, limit, offset, fetchBodies, skipUids)- } finally {- folder.closeQuietly()- }+ try { fetchMessagesFromOpenFolder(folder, user, folderName, limit, offset, fetchBodies, skipUids) }+ finally { folder.closeQuietly() } } - /**- * Fetches new messages from an already-open [folder] without re-opening it.- * Used by [ImapIdleService] so that we can respond to `EXISTS` push events- * inline on the same connection instead of going through WorkManager.- */ fun fetchMessagesFromOpenFolder( folder: Folder, user: String,@@ -213,15 +165,11 @@ class EmailManager { val end = (totalMessages - offset).coerceAtLeast(1) val start = (end - limit + 1).coerceAtLeast(1) if (end < 1) return emptyList<EmailMessage>() to emptyList()- val messages = folder.getMessages(start, end)- // Cheap UIDs-only fetch first, so we can filter out known UIDs before- // pulling envelopes (much more bytes). folder.fetch(messages, FetchProfile().apply { add(UIDFolder.FetchProfileItem.UID) }) val uidFolder = folder as? UIDFolder val novel = messages.filter { (uidFolder?.getUID(it) ?: -1L) !in skipUids }.toTypedArray() if (novel.isEmpty()) return emptyList<EmailMessage>() to emptyList()- val fp = FetchProfile().apply { add(FetchProfile.Item.ENVELOPE) add(UIDFolder.FetchProfileItem.UID)@@ -230,16 +178,12 @@ class EmailManager { if (fetchBodies) add(FetchProfile.Item.CONTENT_INFO) } folder.fetch(novel, fp)- val emailMessages = mutableListOf<EmailMessage>() val allAttachments = mutableListOf<Attachment>() novel.reversedArray().forEach { msg -> val uid = uidFolder?.getUID(msg) ?: -1L- val (body, isHtml, attachments) = if (fetchBodies) {- processMessageContent(user, folderName, uid, msg)- } else {- Triple<String?, Boolean, List<Attachment>>(null, false, emptyList())- }+ val (body, isHtml, attachments) = if (fetchBodies) processMessageContent(user, folderName, uid, msg)+ else Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) allAttachments.addAll(attachments) emailMessages.add(buildEmailMessage(msg, user, folderName, uid, body, isHtml, attachments.isNotEmpty(), fetchBodies)) }@@ -247,7 +191,7 @@ class EmailManager { } private fun buildEmailMessage(- msg: javax.mail.Message,+ msg: Message, user: String, folderName: String, uid: Long,@@ -256,12 +200,12 @@ class EmailManager { hasAttachments: Boolean, fetchBodies: Boolean, ): EmailMessage {- val gmailThreadId = (msg as? javax.mail.internet.MimeMessage)?.getHeader("X-GM-THRID")?.firstOrNull()+ val gmailThreadId = (msg as? MimeMessage)?.getHeader("X-GM-THRID")?.firstOrNull() val serverId = msg.getHeader("Message-ID")?.firstOrNull() val refs = msg.getHeader("References")?.firstOrNull() val listUnsub = msg.getHeader("List-Unsubscribe")?.firstOrNull() val listUnsubPost = msg.getHeader("List-Unsubscribe-Post")?.firstOrNull()- val isRead = msg.isSet(javax.mail.Flags.Flag.SEEN)+ val isRead = msg.isSet(Flags.Flag.SEEN) val whenMillis = msg.sentDate?.time ?: msg.receivedDate?.time ?: 0L return EmailMessage( accountEmail = user,@@ -271,8 +215,8 @@ class EmailManager { threadId = gmailThreadId ?: uid.toString(), subject = msg.subject ?: "(no subject)", from = msg.from?.firstOrNull()?.toString() ?: "",- to = msg.getRecipients(javax.mail.Message.RecipientType.TO)?.joinToString { it.toString() },- cc = msg.getRecipients(javax.mail.Message.RecipientType.CC)?.joinToString { it.toString() },+ to = msg.getRecipients(Message.RecipientType.TO)?.joinToString { it.toString() },+ cc = msg.getRecipients(Message.RecipientType.CC)?.joinToString { it.toString() }, date = msg.sentDate?.toString() ?: msg.receivedDate?.toString() ?: "", dateMillis = whenMillis, body = body,@@ -285,10 +229,6 @@ class EmailManager { ) } - /**- * On-demand body + attachments fetch for a single message. Used by the- * MessageThread screen the first time a message without a stored body is opened.- */ suspend fun fetchMessageBody( server: ServerConfig, user: String,@@ -299,11 +239,6 @@ class EmailManager { fetchMessageBodyInStore(store, user, folderName, uid) } - /**- * Body+attachments fetch using an already-open [store]. Used by the sync- * worker's background backfill so we don't open a new TCP/TLS connection- * for each missing message.- */ suspend fun fetchMessageBodyInStore( store: Store, user: String,@@ -315,9 +250,7 @@ class EmailManager { try { val message = (folder as UIDFolder).getMessageByUID(uid) ?: return@withContext Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) processMessageContent(user, folderName, uid, message)- } finally {- folder.closeQuietly()- }+ } finally { folder.closeQuietly() } } suspend fun fetchFolders(server: ServerConfig, user: String, auth: AuthType): List<EmailFolder> = withStore(server, user, auth) { store ->@@ -356,6 +289,7 @@ class EmailManager { cc: String? = null, bcc: String? = null, attachments: List<Uri> = emptyList(),+ inlineImages: List<InlineAttachment> = emptyList(), inReplyTo: String? = null, references: String? = null, from: String? = null,@@ -366,56 +300,71 @@ class EmailManager { val message = MimeMessage(session) message.setFrom(InternetAddress(from ?: user)) message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(to))- if (!cc.isNullOrBlank()) {- message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc))- }- if (!bcc.isNullOrBlank()) {- message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc))- }+ if (!cc.isNullOrBlank()) message.setRecipients(Message.RecipientType.CC, InternetAddress.parse(cc))+ if (!bcc.isNullOrBlank()) message.setRecipients(Message.RecipientType.BCC, InternetAddress.parse(bcc)) message.subject = subject- - if (inReplyTo != null) {- message.setHeader("In-Reply-To", inReplyTo)- }- if (references != null) {- message.setHeader("References", references)+ if (inReplyTo != null) message.setHeader("In-Reply-To", inReplyTo)+ if (references != null) message.setHeader("References", references)++ val textPart = MimeBodyPart().apply {+ if (asHtml) setContent(body, "text/html; charset=utf-8") else setText(body) } - val multipart = MimeMultipart()- // Text part- val textPart = MimeBodyPart()- if (asHtml) {- textPart.setContent(body, "text/html; charset=utf-8")+ val finalMultipart: MimeMultipart+ if (inlineImages.isEmpty()) {+ finalMultipart = MimeMultipart("mixed")+ finalMultipart.addBodyPart(textPart)+ for (uri in attachments) finalMultipart.addBodyPart(buildAttachmentPart(context, uri)) } else {- textPart.setText(body)- }- multipart.addBodyPart(textPart)-- // Attachments- for (uri in attachments) {- val attachmentPart = MimeBodyPart()- val filename = getFileName(context, uri) ?: "attachment"- val dataSource = object : javax.activation.DataSource {- override fun getInputStream() = context.contentResolver.openInputStream(uri) ?: throw Exception("Cannot open URI")- override fun getOutputStream() = throw Exception("Not supported")- override fun getContentType() = context.contentResolver.getType(uri) ?: "application/octet-stream"- override fun getName() = filename+ val related = MimeMultipart("related")+ related.addBodyPart(textPart)+ for (inline in inlineImages) {+ val inlinePart = MimeBodyPart().apply {+ val ds = object : DataSource {+ override fun getInputStream() = try {+ context.contentResolver.openInputStream(inline.uri) ?: File(inline.uri.path ?: "").inputStream()+ } catch (_: Exception) { File(inline.uri.path ?: "").inputStream() }+ override fun getOutputStream() = throw Exception("Not supported")+ override fun getContentType() = inline.mimeType.ifBlank { "image/jpeg" }+ override fun getName() = inline.fileName+ }+ dataHandler = DataHandler(ds)+ setHeader("Content-ID", "<${inline.cid}>")+ setHeader("Content-Disposition", "inline; filename=\"${inline.fileName}\"")+ fileName = inline.fileName+ }+ related.addBodyPart(inlinePart) }- attachmentPart.dataHandler = DataHandler(dataSource)- attachmentPart.fileName = filename- multipart.addBodyPart(attachmentPart)+ val relatedWrapper = MimeBodyPart().apply { setContent(related) }+ finalMultipart = MimeMultipart("mixed")+ finalMultipart.addBodyPart(relatedWrapper)+ for (uri in attachments) finalMultipart.addBodyPart(buildAttachmentPart(context, uri)) } - message.setContent(multipart)+ message.setContent(finalMultipart) val transport = session.getTransport(server.smtpProtocol) try {- val credential = (auth as AuthType.Password).value- transport.connect(server.host, server.port, user, credential)+ transport.connect(server.host, server.port, user, auth.credential) transport.sendMessage(message, message.allRecipients)- } finally {- transport.close()+ } finally { transport.close() }+ }++ private fun buildAttachmentPart(context: Context, uri: Uri): MimeBodyPart {+ val attachmentPart = MimeBodyPart()+ val filename = getFileName(context, uri) ?: "attachment"+ val dataSource = object : DataSource {+ override fun getInputStream() = try {+ context.contentResolver.openInputStream(uri) ?: File(uri.path ?: "").inputStream()+ } catch (_: Exception) { File(uri.path ?: "").inputStream() }+ override fun getOutputStream() = throw Exception("Not supported")+ override fun getContentType() = context.contentResolver.getType(uri) ?: "application/octet-stream"+ override fun getName() = filename }+ attachmentPart.dataHandler = DataHandler(dataSource)+ attachmentPart.fileName = filename+ attachmentPart.setHeader("Content-Disposition", "attachment; filename=\"$filename\"")+ return attachmentPart } private fun getFileName(context: Context, uri: Uri): String? {@@ -431,9 +380,6 @@ class EmailManager { return uri.path?.let { File(it).name } } - /**- * Update the SEEN (read/unread) flag on the IMAP server for a single message.- */ suspend fun setSeenFlag( server: ServerConfig, user: String,@@ -447,12 +393,9 @@ class EmailManager { try { val msg = (folder as UIDFolder).getMessageByUID(uid) ?: return@withStore msg.setFlag(Flags.Flag.SEEN, seen)- } finally {- folder.closeQuietly()- }+ } finally { folder.closeQuietly() } } - /** Permanently delete a message on the IMAP server (sets \Deleted and expunges). */ suspend fun deleteMessage( server: ServerConfig, user: String,@@ -466,16 +409,9 @@ class EmailManager { val msg = (folder as UIDFolder).getMessageByUID(uid) ?: return@withStore msg.setFlag(Flags.Flag.DELETED, true) folder.expunge()- } finally {- folder.closeQuietly(true)- }+ } finally { folder.closeQuietly(true) } } - /**- * Streams an IMAP attachment MIME part into the public Downloads folder via MediaStore, so it- * lands in the user-visible Downloads directory (attachments have no HTTP URL, so- * DownloadManager isn't applicable). Returns the saved `content://` URI as a string.- */ suspend fun downloadAttachment( context: Context, server: ServerConfig,@@ -492,7 +428,6 @@ class EmailManager { try { val msg = (folder as UIDFolder).getMessageByUID(uid) val part = findPartById(msg, partId) ?: throw Exception("Part not found")- val resolver = context.contentResolver val values = ContentValues().apply { put(MediaStore.MediaColumns.DISPLAY_NAME, fileName)@@ -500,24 +435,19 @@ class EmailManager { put(MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS) put(MediaStore.MediaColumns.IS_PENDING, 1) }- val itemUri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values)- ?: throw Exception("Could not create Downloads entry")+ val itemUri = resolver.insert(MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) ?: throw Exception("Could not create Downloads entry") try {- resolver.openOutputStream(itemUri)?.use { output ->- part.inputStream.use { input -> input.copyTo(output) }- } ?: throw Exception("Could not open output stream")+ resolver.openOutputStream(itemUri)?.use { output -> part.inputStream.use { input -> input.copyTo(output) } }+ ?: throw Exception("Could not open output stream") values.clear() values.put(MediaStore.MediaColumns.IS_PENDING, 0) resolver.update(itemUri, values, null, null) } catch (e: Exception) {- // Roll back the partially-written entry so we don't leave a 0-byte file behind. resolver.delete(itemUri, null, null) throw e } itemUri.toString()- } finally {- folder.closeQuietly()- }+ } finally { folder.closeQuietly() } } private fun findPartById(part: Part, partId: String): Part? {@@ -529,9 +459,7 @@ class EmailManager { val index = id.toIntOrNull() ?: return null if (currentPart.content is MimeMultipart) { val innerMp = currentPart.content as MimeMultipart- if (index < innerMp.count) {- currentPart = innerMp.getBodyPart(index)- } else return null+ if (index < innerMp.count) currentPart = innerMp.getBodyPart(index) else return null } else return null } return currentPart@@ -539,42 +467,148 @@ class EmailManager { return null } - private fun processMessageContent(user: String, folderName: String, uid: Long, part: Part, partId: String = ""): Triple<String?, Boolean, List<Attachment>> {+ suspend fun fetchRawMessageBytes(+ server: ServerConfig,+ user: String,+ auth: AuthType,+ folderName: String,+ uid: Long,+ ): ByteArray = withStore(server, user, auth) { store ->+ val folder = store.getFolder(folderName)+ folder.open(Folder.READ_ONLY)+ try {+ val msg = (folder as UIDFolder).getMessageByUID(uid) ?: throw IllegalStateException("Message UID $uid not found in $folderName")+ val baos = ByteArrayOutputStream()+ (msg as? MimeMessage)?.writeTo(baos) ?: msg.dataHandler.writeTo(baos)+ baos.toByteArray()+ } finally { folder.closeQuietly() }+ }++ suspend fun fetchRawMessageTo(+ server: ServerConfig,+ user: String,+ auth: AuthType,+ folderName: String,+ uid: Long,+ output: OutputStream,+ ) = withStore(server, user, auth) { store ->+ val folder = store.getFolder(folderName)+ folder.open(Folder.READ_ONLY)+ try {+ val msg = (folder as UIDFolder).getMessageByUID(uid) ?: throw IllegalStateException("Message UID $uid not found in $folderName")+ (msg as? MimeMessage)?.writeTo(output) ?: msg.dataHandler.writeTo(output)+ } finally { folder.closeQuietly() }+ }++ internal fun processMessageContent(user: String, folderName: String, uid: Long, part: Part, partId: String = ""): Triple<String?, Boolean, List<Attachment>> { when { part.isMimeType("text/plain") -> return Triple(part.content.toString(), false, emptyList()) part.isMimeType("text/html") -> return Triple(part.content.toString(), true, emptyList()) part.isMimeType("multipart/*") -> {- val mp = part.content as MimeMultipart- var finalBody: String? = null- var finalIsHtml = false- val attachments = mutableListOf<Attachment>()-- for (i in 0 until mp.count) {- val bodyPart = mp.getBodyPart(i)- val currentPartId = if (partId.isEmpty()) i.toString() else "$partId.$i"- - if (Part.ATTACHMENT.equals(bodyPart.disposition, ignoreCase = true) || !bodyPart.fileName.isNullOrBlank()) {- attachments.add(Attachment(- accountEmail = user,- folderName = folderName,- messageId = uid,- partId = currentPartId,- fileName = bodyPart.fileName ?: "unnamed",- mimeType = bodyPart.contentType.split(";").first(),- size = bodyPart.size.toLong()- ))- } else {- val (b, h, a) = processMessageContent(user, folderName, uid, bodyPart, currentPartId)- attachments.addAll(a)- if (finalBody == null || (h && !finalIsHtml)) {- finalBody = b- finalIsHtml = h+ val mp = part.content as MimeMultipart+ var finalBody: String? = null+ var finalIsHtml = false+ val attachments = mutableListOf<Attachment>()+ for (i in 0 until mp.count) {+ val bodyPart = mp.getBodyPart(i)+ val currentPartId = if (partId.isEmpty()) i.toString() else "$partId.$i"+ val contentId = try { bodyPart.getHeader("Content-ID")?.firstOrNull() } catch (_: Exception) { null }+ val isInlineImage = contentId != null && (bodyPart.isMimeType("image/*") || Part.INLINE.equals(bodyPart.disposition, ignoreCase = true))+ if (!isInlineImage && (Part.ATTACHMENT.equals(bodyPart.disposition, ignoreCase = true) || !bodyPart.fileName.isNullOrBlank())) {+ attachments.add(Attachment(user, folderName, uid, currentPartId, bodyPart.fileName ?: "unnamed", bodyPart.contentType.split(";").first(), bodyPart.size.toLong()))+ } else if (!isInlineImage) {+ val (b, h, a) = processMessageContent(user, folderName, uid, bodyPart, currentPartId)+ attachments.addAll(a)+ if (finalBody == null || (h && !finalIsHtml)) { finalBody = b; finalIsHtml = h } } }- }- return Triple(finalBody, finalIsHtml, attachments)+ return Triple(finalBody, finalIsHtml, attachments) } } return Triple(null, false, emptyList()) }++ data class FullFetchResult(val contentTriple: Triple<String?, Boolean, List<Attachment>>)++ suspend fun fetchFullForBody(+ context: Context,+ server: ServerConfig,+ user: String,+ auth: AuthType,+ folderName: String,+ uid: Long,+ ): FullFetchResult = withStore(server, user, auth) { store ->+ val folder = store.getFolder(folderName)+ folder.open(Folder.READ_ONLY)+ try {+ val message = (folder as UIDFolder).getMessageByUID(uid)+ if (message == null) return@withStore FullFetchResult(Triple(null, false, emptyList()))+ val ctx = context.applicationContext+ try { extractInlineCidMapSync(ctx, message, uid) } catch (_: Exception) { }+ val triple = processMessageContent(user, folderName, uid, message, "")+ FullFetchResult(triple)+ } finally { folder.closeQuietly() }+ }++ suspend fun fetchCidMap(+ context: Context,+ server: ServerConfig,+ user: String,+ auth: AuthType,+ folderName: String,+ uid: Long,+ ): Map<String, File> = withContext(Dispatchers.IO) {+ withStore(server, user, auth) { store ->+ val folder = store.getFolder(folderName)+ folder.open(Folder.READ_ONLY)+ try {+ val msg = (folder as UIDFolder).getMessageByUID(uid) ?: return@withStore emptyMap<String, File>()+ extractInlineCidMapSync(context, msg, uid)+ } finally { folder.closeQuietly() }+ }+ }++ private fun extractInlineCidMapSync(context: Context, part: Part, uid: Long): Map<String, File> {+ val map = mutableMapOf<String, File>()+ fun walk(p: Part) {+ try {+ if (p.isMimeType("multipart/*")) {+ val mp = p.content as? MimeMultipart ?: return+ for (i in 0 until mp.count) walk(mp.getBodyPart(i))+ } else {+ val cidHeader = try { p.getHeader("Content-ID")?.firstOrNull() } catch (_: Exception) { null }+ if (cidHeader != null) {+ val cid = cidHeader.trim().removePrefix("<").removeSuffix(">").trim()+ if (cid.isNotEmpty()) {+ val dir = File(context.cacheDir, "cid/$uid").also { it.mkdirs() }+ val safeName = (p.fileName?.takeIf { it.isNotBlank() } ?: "${cid.hashCode()}.bin").replace(Regex("[/\\\\]"), "_")+ val outFile = File(dir, safeName)+ if (!outFile.exists()) {+ try { p.inputStream.use { input -> outFile.outputStream().use { out -> input.copyTo(out) } } } catch (_: Exception) { }+ }+ if (outFile.exists()) {+ map[cid] = outFile+ try { File(dir, "$cid.meta").writeText(outFile.name) } catch (_: Exception) { }+ }+ }+ }+ }+ } catch (_: Exception) { }+ }+ walk(part)+ val dir = File(context.cacheDir, "cid/$uid")+ if (dir.exists()) {+ dir.listFiles { f -> f.name.endsWith(".meta") }?.forEach { meta ->+ val cid = meta.name.removeSuffix(".meta")+ if (cid !in map) {+ val targetName = try { meta.readText().trim() } catch (_: Exception) { null }+ if (targetName != null) {+ val file = File(dir, targetName)+ if (file.exists()) map[cid] = file+ }+ }+ }+ }+ return map+ } }
email/src/main/java/com/vayunmathur/email/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/EmailModels.ktindex f35adc08fa..a91459aeed 100644--- a/email/src/main/java/com/vayunmathur/email/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailModels.kt@@ -263,7 +263,7 @@ private fun EmailMessage.findUnsubscribeLinkInBody(): String? { /// background sender. Attachments are copied to app-private storage at queue time /// (the original `content://` URIs aren't reliably readable across process /// restarts) and `attachmentLocalPaths` is a JSON-encoded `List<String>` of those-/// absolute file paths.+/// absolute file paths. [inlineImageJson] stores JSON array of {cid,path,mime,name}. @Serializable @Entity data class OutboxEntry(@@ -275,6 +275,8 @@ data class OutboxEntry( val subject: String, val body: String, val attachmentLocalPaths: String = "[]",+ @ColumnInfo(defaultValue = "[]")+ val inlineImageJson: String = "[]", val inReplyTo: String? = null, val references: String? = null, val createdAt: Long = System.currentTimeMillis(),@@ -294,5 +296,7 @@ data class DraftEntry( val bcc: String = "", val subject: String = "", val body: String = "",+ @ColumnInfo(defaultValue = "[]")+ val inlineImageJson: String = "[]", val updatedAt: Long = System.currentTimeMillis(), )
email/src/main/java/com/vayunmathur/email/EmailViewModel.kt
diff --git a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt b/email/src/main/java/com/vayunmathur/email/EmailViewModel.ktindex d24f37dc3c..359b9531eb 100644--- a/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt+++ b/email/src/main/java/com/vayunmathur/email/EmailViewModel.kt@@ -91,6 +91,7 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) { cc: String? = null, bcc: String? = null, attachments: List<Uri> = emptyList(),+ inlineImages: List<com.vayunmathur.email.composer.InlineAttachment> = emptyList(), inReplyTo: String? = null, references: String? = null, scheduledAt: Long,@@ -103,6 +104,7 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) { accountEmail = account.email, to = to, subject = subject, body = body, cc = cc, bcc = bcc, attachments = attachments,+ inlineImages = inlineImages, inReplyTo = inReplyTo, references = references, scheduledAt = scheduledAt, isHtml = asHtml,@@ -353,6 +355,7 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) { cc: String? = null, bcc: String? = null, attachments: List<Uri> = emptyList(),+ inlineImages: List<com.vayunmathur.email.composer.InlineAttachment> = emptyList(), inReplyTo: String? = null, references: String? = null, asHtml: Boolean = false,@@ -372,6 +375,7 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) { cc = cc, bcc = bcc, attachments = attachments,+ inlineImages = inlineImages, inReplyTo = inReplyTo, references = references, from = account.email,@@ -390,6 +394,7 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) { cc = cc, bcc = bcc, attachments = attachments,+ inlineImages = inlineImages, inReplyTo = inReplyTo, references = references, initialError = msg,@@ -409,19 +414,24 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) { * MessageItem when a stored row has `body == null` (the sync only fetches * headers — bodies are downloaded on first open). Updates the row in the * DB; the Flow-based UI will recompose automatically.+ * Also extracts inline CID images to cache/cid/<uid>/ for viewer rendering. */ fun fetchBodyIfNeeded(message: EmailMessage) { if (message.body != null) return viewModelScope.launch { val account = dao.getAccountByEmail(message.accountEmail) ?: return@launch try {- val (body, isHtml, attachments) = emailManager.fetchMessageBody(+ // We need raw mime to extract CID files+ val ctx = getApplication<Application>()+ val full = emailManager.fetchFullForBody(+ context = ctx, server = account.imapServer(), user = account.loginUser(), auth = account.resolveAuth(appContext), folderName = message.folderName, uid = message.id, )+ val (body, isHtml, attachments) = full.contentTriple if (body != null || attachments.isNotEmpty()) { dao.insertMessages(listOf(message.copy(body = body, isHtml = isHtml, hasAttachments = attachments.isNotEmpty()))) if (attachments.isNotEmpty()) dao.insertAttachments(attachments)@@ -432,6 +442,25 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) { } } + /** CID map loader for already-fetched message – extracts inline files to cache and returns map */+ suspend fun loadCidMap(context: android.content.Context, message: EmailMessage): Map<String, java.io.File> {+ return try {+ val account = dao.getAccountByEmail(message.accountEmail) ?: return emptyMap()+ val auth = account.resolveAuth(appContext)+ emailManager.fetchCidMap(+ context = context,+ server = account.imapServer(),+ user = account.loginUser(),+ auth = auth,+ folderName = message.folderName,+ uid = message.id,+ )+ } catch (e: Exception) {+ android.util.Log.w("EmailViewModel", "loadCidMap failed: ${e.message}")+ emptyMap()+ }+ }+ /** * Perform an RFC 8058 one-click unsubscribe: an HTTPS POST to [url] with the * body `List-Unsubscribe=One-Click`. Runs off the main thread and reports@@ -500,6 +529,42 @@ class EmailViewModel(application: Application) : AndroidViewModel(application) { } } + /**+ * Export a single email as a .eml file to a SAF [targetUri] (from CreateDocument).+ * Streams the raw RFC822 bytes directly to avoid OOM on large messages.+ */+ fun exportEml(+ accountEmail: String,+ folderName: String,+ uid: Long,+ targetUri: Uri,+ onResult: (Boolean, String?) -> Unit,+ ) {+ viewModelScope.launch(Dispatchers.IO) {+ try {+ val account = dao.getAccountByEmail(accountEmail)+ ?: run {+ withContext(Dispatchers.Main) { onResult(false, "Account not found") }+ return@launch+ }+ val server = account.imapServer()+ val user = account.loginUser()+ val auth = account.resolveAuth(appContext)+ val ctx = getApplication<Application>()+ ctx.contentResolver.openOutputStream(targetUri)?.use { out ->+ emailManager.fetchRawMessageTo(server, user, auth, folderName, uid, out)+ } ?: run {+ withContext(Dispatchers.Main) { onResult(false, "Could not open destination") }+ return@launch+ }+ withContext(Dispatchers.Main) { onResult(true, null) }+ } catch (e: Exception) {+ android.util.Log.w("EmailViewModel", "exportEml failed: ${e.message}", e)+ withContext(Dispatchers.Main) { onResult(false, e.message ?: e.javaClass.simpleName) }+ }+ }+ }+ companion object { private const val OA_PACKAGE = "com.vayunmathur.openassistant" private const val OA_SERVICE = "$OA_PACKAGE.util.InferenceService"
email/src/main/java/com/vayunmathur/email/MainActivity.kt
diff --git a/email/src/main/java/com/vayunmathur/email/MainActivity.kt b/email/src/main/java/com/vayunmathur/email/MainActivity.ktindex f335538444..ece8f8af7e 100644--- a/email/src/main/java/com/vayunmathur/email/MainActivity.kt+++ b/email/src/main/java/com/vayunmathur/email/MainActivity.kt@@ -33,8 +33,8 @@ import androidx.lifecycle.viewmodel.compose.viewModel import androidx.lifecycle.lifecycleScope import androidx.core.net.toUri import com.vayunmathur.email.data.EmailSyncWorker+import com.vayunmathur.email.util.EmlUtils import com.vayunmathur.email.widget.EmailWidgetReceiver-import com.vayunmathur.library.ui.* import com.vayunmathur.library.util.* import com.vayunmathur.library.widgets.updateWidgetPreviews import kotlinx.coroutines.flow.debounce@@ -48,6 +48,9 @@ class MainActivity : ComponentActivity() { updateWidgetPreviews(EmailWidgetReceiver::class) handleIntent(intent)+ // IDLE push for INBOX + hourly non-INBOX poll + on-demand pull-to-refresh.+ // Purge any legacy 15-min full-poll work from older APKs and ensure hourly non-INBOX is scheduled.+ com.vayunmathur.email.data.EmailSyncWorker.scheduleHourlyNonInboxSync(this) // Wake the outbox sender on every cold start: if the process was killed // between scheduled retries, this is what gets it going again. com.vayunmathur.email.data.OutboxSendWorker.runNow(this)@@ -90,6 +93,34 @@ class MainActivity : ComponentActivity() { private fun handleIntent(intent: Intent?) { if (intent == null) return + // .eml VIEW from file manager / Downloads / Files app+ if (intent.action == Intent.ACTION_VIEW) {+ val dataUri = intent.data+ if (dataUri != null) {+ val mime = intent.type+ val lastSeg = dataUri.lastPathSegment ?: ""+ val lowerMime = mime?.lowercase() ?: ""+ val isEmlMime = lowerMime.contains("rfc822") || lowerMime.contains("mbox")+ var isEmlExtension = lastSeg.endsWith(".eml", ignoreCase = true)+ // Content URIs sometimes encode the filename in DISPLAY_NAME, not lastPathSegment+ if (!isEmlExtension && dataUri.scheme == "content") {+ try {+ contentResolver.query(dataUri, arrayOf(android.provider.OpenableColumns.DISPLAY_NAME), null, null, null)?.use { c ->+ if (c.moveToFirst()) {+ val name = c.getString(0) ?: ""+ if (name.endsWith(".eml", ignoreCase = true)) isEmlExtension = true+ }+ }+ } catch (_: Exception) { /* best-effort */ }+ }+ val looksLikeEml = isEmlMime || isEmlExtension+ if (looksLikeEml) {+ IntentState.navigationRoute = Route.EmlViewer(dataUri.toString())+ return+ }+ }+ }+ val accountEmail = intent.getStringExtra("accountEmail") val threadId = intent.getStringExtra("threadId") when {@@ -116,7 +147,10 @@ object IntentState { @Composable fun MainContent(viewModel: EmailViewModel) { val accounts by viewModel.accounts.collectAsStateWithLifecycle(emptyList())- if (accounts.isEmpty()) {+ val navigationRoute = IntentState.navigationRoute+ val isEmlViewer = navigationRoute is Route.EmlViewer++ if (accounts.isEmpty() && !isEmlViewer) { // First run: jump straight into the add-account picker. The conditional // above auto-swaps us into EmailApp once the first account lands. com.vayunmathur.email.ui.AddAccountScreen(@@ -151,6 +185,8 @@ sealed interface Route : NavKey { object AddAccount : Route @Serializable object Settings : Route+ @Serializable+ data class EmlViewer(val uriString: String) : Route } @Composable@@ -364,6 +400,15 @@ fun EmailApp(viewModel: EmailViewModel) { onOpenDraft = { id -> backStack.add(Route.Composer(draftId = id)) }, ) }+ entry<Route.EmlViewer>(metadata = ListDetailPage()) { route ->+ com.vayunmathur.email.ui.EmlViewerScreen(+ uriString = route.uriString,+ onBack = { backStack.pop() },+ onComposeForward = { sub, body ->+ backStack.add(Route.Composer(subject = sub, body = body))+ },+ )+ } } } }@@ -748,6 +793,27 @@ fun MessageThreadScreen( ) { val messages by viewModel.getThread(accountEmail, threadId).collectAsStateWithLifecycle(emptyList()) var hasMarkedAsRead by remember(threadId) { mutableStateOf(false) }+ val context = LocalContext.current+ var pendingExport by remember { mutableStateOf<EmailMessage?>(null) }++ // SAF CreateDocument launcher for .eml export — streams raw RFC822 from IMAP directly to user-chosen location.+ val exportLauncher = rememberLauncherForActivityResult(+ ActivityResultContracts.CreateDocument("message/rfc822")+ ) { targetUri ->+ val msg = pendingExport+ pendingExport = null+ if (targetUri != null && msg != null) {+ viewModel.exportEml(+ accountEmail = msg.accountEmail,+ folderName = msg.folderName,+ uid = msg.id,+ targetUri = targetUri,+ ) { ok, err ->+ val toastText = if (ok) "Saved as .eml" else "Save failed: ${err ?: "unknown"}"+ Toast.makeText(context, toastText, Toast.LENGTH_SHORT).show()+ }+ }+ } // Mark all unread messages in the thread as read when the screen loads. // Only run once per thread navigation to allow user to mark as unread.@@ -774,7 +840,21 @@ fun MessageThreadScreen( verticalArrangement = Arrangement.spacedBy(8.dp) ) { items(messages, key = { "${it.accountEmail}|${it.folderName}|${it.id}" }) { msg ->- MessageItem(msg, viewModel, onBack, onReply, onForward, onCompose)+ MessageItem(+ msg = msg,+ viewModel = viewModel,+ onBack = onBack,+ onReply = onReply,+ onForward = onForward,+ onCompose = onCompose,+ onExportEml = { toExport ->+ pendingExport = toExport+ val fileName = EmlUtils.sanitizeFileName(+ toExport.subject.ifBlank { "email_${toExport.id}" }+ )+ exportLauncher.launch(fileName)+ },+ ) } } }@@ -783,23 +863,22 @@ fun MessageThreadScreen( @OptIn(ExperimentalMaterial3Api::class) @Composable fun MessageItem(- msg: EmailMessage, + msg: EmailMessage, viewModel: EmailViewModel, onBack: () -> Unit, onReply: (String, String, String?) -> Unit, onForward: (String, String?) -> Unit,- onCompose: (String, String) -> Unit+ onCompose: (String, String) -> Unit,+ onExportEml: (EmailMessage) -> Unit = {}, ) { var attachments by remember { mutableStateOf<List<Attachment>>(emptyList()) } var showDetails by remember { mutableStateOf(false) } val sheetState = rememberModalBottomSheetState() val context = LocalContext.current- + var showOverflow by remember { mutableStateOf(false) }+ LaunchedEffect(msg.id) { attachments = viewModel.getAttachments(msg.accountEmail, msg.id)- // If we only have the header for this message (sync skips bodies), pull- // the body now. The DB row update will flow back through the Thread Flow- // and trigger a recomposition with the body visible. if (msg.body == null) { viewModel.fetchBodyIfNeeded(msg) }@@ -811,7 +890,6 @@ fun MessageItem( val avatarColor = Color(accountColor(msg.accountEmail)) Column {- // Header Row( modifier = Modifier .fillMaxWidth()@@ -828,7 +906,6 @@ fun MessageItem( Text(text = initial, color = Color.White, style = MaterialTheme.typography.titleMedium) } }- Column( modifier = Modifier .weight(1f)@@ -843,7 +920,7 @@ fun MessageItem( modifier = Modifier.weight(1f, fill = false) ) Text(- text = " • ${msg.date.substringBeforeLast(":")}", // Simplified time+ text = " • ${msg.date.substringBeforeLast(":")}", style = MaterialTheme.typography.labelSmall, color = MaterialTheme.colorScheme.onSurfaceVariant )@@ -854,8 +931,7 @@ fun MessageItem( color = MaterialTheme.colorScheme.onSurfaceVariant ) }-- Row {+ Row(verticalAlignment = Alignment.CenterVertically) { var showSnooze by remember { mutableStateOf(false) } Box { TextButton(onClick = { showSnooze = true }) { Text("Snooze") }@@ -876,50 +952,61 @@ fun MessageItem( } IconButton(onClick = { viewModel.markAsRead(msg.accountEmail, msg.folderName, msg.id, !msg.isRead)- if (msg.isRead) { // If it was read, we just marked it as unread+ if (msg.isRead) { onBack() } }) { if (msg.isRead) IconMarkUnread() else IconMarkRead() }+ Box {+ IconButton(onClick = { showOverflow = true }) { IconMoreVert() }+ DropdownMenu(expanded = showOverflow, onDismissRequest = { showOverflow = false }) {+ DropdownMenuItem(+ text = { Text("Save as .eml") },+ leadingIcon = { IconSave(modifier = Modifier.size(20.dp)) },+ onClick = { showOverflow = false; onExportEml(msg) },+ )+ }+ } } } if (msg.isHtml && msg.body != null) { var loadImages by remember(msg.id) { mutableStateOf(false) } var showQuotes by remember(msg.id) { mutableStateOf(false) }+ var cidMap by remember(msg.id) { mutableStateOf<Map<String, java.io.File>>(emptyMap()) }+ val bodyHasCid = remember(msg.body) { msg.body.contains("cid:", ignoreCase = true) }+ LaunchedEffect(msg.id, msg.body) {+ if (bodyHasCid) {+ val map = viewModel.loadCidMap(context, msg)+ if (map.isNotEmpty()) cidMap = map+ }+ } val hasQuotes = remember(msg.body) { listOf("gmail_quote", "yahoo_quoted", "moz-cite-prefix", "<blockquote").any { msg.body.contains(it, ignoreCase = true) } }- if (!loadImages) {+ val remoteBlocked = !loadImages && cidMap.isEmpty() && !bodyHasCid+ if (remoteBlocked) { Row(- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 16.dp, vertical = 4.dp),+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 4.dp), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically, ) {- Text(- "Remote images blocked",- style = MaterialTheme.typography.bodySmall,- color = MaterialTheme.colorScheme.onSurfaceVariant,- )+ Text("Remote images blocked", style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant) TextButton(onClick = { loadImages = true }) { Text("Load images") } } } HtmlText( html = msg.body,- blockRemoteImages = !loadImages,+ blockRemoteImages = remoteBlocked, hideQuotes = hasQuotes && !showQuotes,- modifier = Modifier- .padding(horizontal = 16.dp)- .fillMaxWidth()+ cidMap = cidMap,+ modifier = Modifier.padding(horizontal = 16.dp).fillMaxWidth() ) if (hasQuotes) {- TextButton(- onClick = { showQuotes = !showQuotes },- modifier = Modifier.padding(horizontal = 8.dp),- ) { Text(if (showQuotes) "Hide quoted text" else "Show quoted text") }+ TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) {+ Text(if (showQuotes) "Hide quoted text" else "Show quoted text")+ } } } else { var showQuotes by remember(msg.id) { mutableStateOf(false) }@@ -927,69 +1014,40 @@ fun MessageItem( Text( text = if (showQuotes || quotedText.isEmpty()) (msg.body ?: "(No Content)") else mainText, style = MaterialTheme.typography.bodyMedium,- modifier = Modifier- .fillMaxWidth()- .padding(horizontal = 16.dp, vertical = 8.dp)+ modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 8.dp) ) if (quotedText.isNotEmpty()) {- TextButton(- onClick = { showQuotes = !showQuotes },- modifier = Modifier.padding(horizontal = 8.dp),- ) { Text(if (showQuotes) "Hide quoted text" else "Show quoted text") }+ TextButton(onClick = { showQuotes = !showQuotes }, modifier = Modifier.padding(horizontal = 8.dp)) {+ Text(if (showQuotes) "Hide quoted text" else "Show quoted text")+ } } }- + if (attachments.isNotEmpty()) { Column(modifier = Modifier.padding(horizontal = 16.dp, vertical = 8.dp)) { Text("Attachments:", style = MaterialTheme.typography.labelLarge)- attachments.forEach { att ->- AttachmentItem(att, viewModel)- }+ attachments.forEach { att -> AttachmentItem(att, viewModel) } } }- - Row(- modifier = Modifier.padding(16.dp),- horizontalArrangement = Arrangement.spacedBy(8.dp)- ) {- OutlinedButton(- onClick = { onReply(msg.from, msg.subject, msg.serverId) },- modifier = Modifier.weight(1f)- ) {- IconUndo(modifier = Modifier.size(18.dp))- Spacer(Modifier.width(8.dp))- Text(stringResource(R.string.reply))++ Row(modifier = Modifier.padding(16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(onClick = { onReply(msg.from, msg.subject, msg.serverId) }, modifier = Modifier.weight(1f)) {+ IconUndo(modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.reply)) }- OutlinedButton(- onClick = { onForward(msg.subject, msg.body) },- modifier = Modifier.weight(1f)- ) {- IconForward(modifier = Modifier.size(18.dp))- Spacer(Modifier.width(8.dp))- Text(stringResource(R.string.forward))+ OutlinedButton(onClick = { onForward(msg.subject, msg.body) }, modifier = Modifier.weight(1f)) {+ IconForward(modifier = Modifier.size(18.dp)); Spacer(Modifier.width(8.dp)); Text(stringResource(R.string.forward)) } } - // Unsubscribe + block sender- Row(- modifier = Modifier.padding(horizontal = 16.dp),- horizontalArrangement = Arrangement.spacedBy(8.dp),- ) {- val unsubscribe = remember(msg.listUnsubscribe, msg.listUnsubscribePost, msg.body, msg.isHtml) {- msg.detectUnsubscribe()- }+ Row(modifier = Modifier.padding(horizontal = 16.dp), horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ val unsubscribe = remember(msg.listUnsubscribe, msg.listUnsubscribePost, msg.body, msg.isHtml) { msg.detectUnsubscribe() } if (unsubscribe != null) { var showConfirm by remember(msg.id) { mutableStateOf(false) } TextButton(onClick = { showConfirm = true }) { Text("Unsubscribe") } if (showConfirm) {- UnsubscribeDialog(- method = unsubscribe,- onDismiss = { showConfirm = false },- onConfirm = {- showConfirm = false- performUnsubscribe(unsubscribe, context, viewModel, onCompose)- },- )+ UnsubscribeDialog(method = unsubscribe, onDismiss = { showConfirm = false }, onConfirm = {+ showConfirm = false; performUnsubscribe(unsubscribe, context, viewModel, onCompose)+ }) } } TextButton(onClick = {@@ -998,30 +1056,15 @@ fun MessageItem( onBack() }) { Text("Block sender") } }- HorizontalDivider() } if (showDetails) {- ModalBottomSheet(- onDismissRequest = { showDetails = false },- sheetState = sheetState- ) {- Column(- modifier = Modifier- .padding(16.dp)- .fillMaxWidth()- ) {- Text(- text = msg.date, // Full date- style = MaterialTheme.typography.labelSmall,- modifier = Modifier.align(Alignment.End)- )- + ModalBottomSheet(onDismissRequest = { showDetails = false }, sheetState = sheetState) {+ Column(modifier = Modifier.padding(16.dp).fillMaxWidth()) {+ Text(text = msg.date, style = MaterialTheme.typography.labelSmall, modifier = Modifier.align(Alignment.End)) DetailItem(label = stringResource(R.string.from_label), name = senderName, email = senderEmail, avatarColor = avatarColor)- // DetailItem(label = "Reply to", ...) // If available DetailItem(label = stringResource(R.string.to_label), name = "me", email = msg.to ?: "", avatarColor = Color.Gray)- Spacer(Modifier.height(16.dp)) Row(verticalAlignment = Alignment.CenterVertically) { IconInbox(modifier = Modifier.size(20.dp), tint = MaterialTheme.colorScheme.onSurfaceVariant)@@ -1034,6 +1077,8 @@ fun MessageItem( } } ++ @Composable fun DetailItem(label: String, name: String, email: String, avatarColor: Color) { Column(modifier = Modifier.padding(vertical = 8.dp)) {@@ -1124,28 +1169,24 @@ fun ComposerScreen( val accounts by viewModel.accounts.collectAsStateWithLifecycle(emptyList()) val selectedAccount by viewModel.selectedAccount.collectAsStateWithLifecycle() val context = LocalContext.current- - var fromAccount by remember(selectedAccount, accounts) { - mutableStateOf(selectedAccount ?: accounts.firstOrNull()) ++ var fromAccount by remember(selectedAccount, accounts) {+ mutableStateOf(selectedAccount ?: accounts.firstOrNull()) }- + var to by remember { mutableStateOf(initialTo) } var cc by remember { mutableStateOf("") } var bcc by remember { mutableStateOf("") } var showCcBcc by remember { mutableStateOf(false) } var subject by remember { mutableStateOf(initialSubject) }- val bodyController = remember { com.vayunmathur.library.ui.HtmlEditorController(initialBody) }+ val bodyController = remember { com.vayunmathur.email.composer.EmailHtmlEditorController(initialBody) } var sending by remember { mutableStateOf(false) } var attachments by remember { mutableStateOf<List<Uri>>(emptyList()) }- + var showAccountPicker by remember { mutableStateOf(false) } var showSchedule by remember { mutableStateOf(false) } - // Pick recipients from the system contact picker (no READ_CONTACTS needed —- // the picker grants temporary read access to the chosen email row). After- // each pick we re-open the picker so several contacts can be added in a row;- // the user dismisses it (cancel) when done.- var pickTarget by remember { mutableStateOf(0) } // 0=to, 1=cc, 2=bcc+ var pickTarget by remember { mutableStateOf(0) } var pickTick by remember { mutableStateOf(0) } val contactPicker = rememberLauncherForActivityResult( ActivityResultContracts.StartActivityForResult()@@ -1158,7 +1199,7 @@ fun ComposerScreen( 1 -> cc = appendRecipient(cc, email) 2 -> bcc = appendRecipient(bcc, email) }- pickTick++ // re-open so more contacts can be added+ pickTick++ } } }@@ -1174,7 +1215,6 @@ fun ComposerScreen( pickTick++ } - // Draft auto-save / resume state. var currentDraftId by remember { mutableStateOf(draftId) } var draftLoaded by remember { mutableStateOf(draftId == null) } LaunchedEffect(draftId) {@@ -1189,8 +1229,6 @@ fun ComposerScreen( } } - // Append the from-account's signature, swapping it when the account changes.- // Skipped when editing an existing draft (its body is already saved). var appliedSignature by remember { mutableStateOf("") } LaunchedEffect(fromAccount) { if (draftId != null) return@LaunchedEffect@@ -1207,7 +1245,6 @@ fun ComposerScreen( } } - // Auto-save the draft as the user types (debounced). LaunchedEffect(fromAccount, draftLoaded) { val acc = fromAccount if (!draftLoaded || acc == null) return@LaunchedEffect@@ -1224,10 +1261,52 @@ fun ComposerScreen( } } + // Clean up orphan inline images on text change+ LaunchedEffect(bodyController.html) {+ bodyController.inlineCleanupOrphans()+ }++ // Attachment launchers val attachmentLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetMultipleContents()) { uris -> if (uris.isNotEmpty()) attachments = attachments + uris } + // Inline image pickers: use PickVisualMedia + fallback GetContent image/*+ val inlineFallbackLauncher = rememberLauncherForActivityResult(ActivityResultContracts.GetContent()) { uri ->+ if (uri != null) {+ val mime = context.contentResolver.getType(uri) ?: "image/jpeg"+ val name = uriName(context, uri)+ // Copy to cache/inline for stable uri+ val cached = copyInlineToCache(context, uri, name)+ val finalUri = cached ?: uri+ bodyController.insertInlineImage(context, finalUri, mime, name)+ }+ }++ // Try to use PickVisualMedia if available+ var visualMediaLauncher: Any? = null+ val pickVisualLauncher = rememberLauncherForActivityResult(ActivityResultContracts.PickVisualMedia()) { uri ->+ if (uri != null) {+ val mime = context.contentResolver.getType(uri) ?: "image/jpeg"+ val name = uriName(context, uri)+ val cached = copyInlineToCache(context, uri, name)+ val finalUri = cached ?: uri+ bodyController.insertInlineImage(context, finalUri, mime, name)+ }+ }++ val pickMultipleVisualLauncher = rememberLauncherForActivityResult(ActivityResultContracts.PickMultipleVisualMedia(5)) { uris ->+ if (uris.isNotEmpty()) {+ uris.forEach { uri ->+ val mime = context.contentResolver.getType(uri) ?: "image/jpeg"+ val name = uriName(context, uri)+ val cached = copyInlineToCache(context, uri, name)+ val finalUri = cached ?: uri+ bodyController.insertInlineImage(context, finalUri, mime, name)+ }+ }+ }+ Scaffold( topBar = { TopAppBar(@@ -1237,6 +1316,16 @@ fun ComposerScreen( IconButton(onClick = { attachmentLauncher.launch("*/*") }) { IconAttachment() }+ IconButton(onClick = {+ // Prefer new photo picker+ try {+ pickVisualLauncher.launch(androidx.activity.result.PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))+ } catch (_: Exception) {+ inlineFallbackLauncher.launch("image/*")+ }+ }) {+ com.vayunmathur.library.ui.IconImage()+ } Box { TextButton(onClick = { showSchedule = true }, enabled = fromAccount != null) { Text("Later")@@ -1250,7 +1339,9 @@ fun ComposerScreen( body = bodyController.html, asHtml = true, cc = cc.ifBlank { null }, bcc = bcc.ifBlank { null },- attachments = attachments, inReplyTo = inReplyTo,+ attachments = attachments,+ inlineImages = bodyController.toInlineAttachments(),+ inReplyTo = inReplyTo, references = references, scheduledAt = at, ) { currentDraftId?.let { viewModel.deleteDraft(it) } } android.widget.Toast.makeText(context, "Scheduled", android.widget.Toast.LENGTH_SHORT).show()@@ -1267,15 +1358,16 @@ fun ComposerScreen( sending = true viewModel.sendEmailFrom( account = acc,- to = to, - subject = subject, + to = to,+ subject = subject, body = bodyController.html, asHtml = true, cc = cc.ifBlank { null }, bcc = bcc.ifBlank { null }, attachments = attachments,- inReplyTo = inReplyTo, - references = references, + inlineImages = bodyController.toInlineAttachments(),+ inReplyTo = inReplyTo,+ references = references, onSuccess = { sending = false currentDraftId?.let { viewModel.deleteDraft(it) }@@ -1284,8 +1376,6 @@ fun ComposerScreen( }, onError = { err -> sending = false- // ViewModel has already queued the message to the outbox;- // surface the underlying error so the user knows it'll retry. android.widget.Toast.makeText(context, "Saved to Outbox: $err", android.widget.Toast.LENGTH_LONG).show() onBack() }@@ -1298,13 +1388,20 @@ fun ComposerScreen( ) }, bottomBar = {+ // Always show formatting toolbar? Per plan, only when focused, but now scrollable and more buttons if (bodyController.focused) {- com.vayunmathur.library.ui.HtmlFormatToolbar(controller = bodyController)+ EmailComposerFormatToolbar(controller = bodyController,+ onInsertImage = {+ try {+ pickVisualLauncher.launch(androidx.activity.result.PickVisualMediaRequest(ActivityResultContracts.PickVisualMedia.ImageOnly))+ } catch (_: Exception) {+ inlineFallbackLauncher.launch("image/*")+ }+ }) } } ) { padding -> Column(modifier = Modifier.padding(padding).padding(horizontal = 16.dp, vertical = 8.dp).fillMaxSize(), verticalArrangement = Arrangement.spacedBy(4.dp)) {- // Compact account ("From") picker. Surface( onClick = { showAccountPicker = true }, shape = androidx.compose.foundation.shape.RoundedCornerShape(8.dp),@@ -1341,9 +1438,9 @@ fun ComposerScreen( accounts.forEach { acc -> ListItem( content = { Text(acc.email) },- modifier = Modifier.clickable { + modifier = Modifier.clickable { fromAccount = acc- showAccountPicker = false + showAccountPicker = false } ) }@@ -1387,16 +1484,39 @@ fun ComposerScreen( modifier = Modifier.fillMaxWidth(), ) - // True HTML body editor (real spans → HTML); the formatting toolbar- // lives in the Scaffold bottomBar so it docks above the keyboard. com.vayunmathur.library.ui.HtmlEditor( controller = bodyController, placeholder = stringResource(R.string.body_label), modifier = Modifier.fillMaxWidth().weight(1f), )- - if (attachments.isNotEmpty()) {- val totalBytes = remember(attachments) { attachments.sumOf { uriSize(context, it) } }++ // Inline images thumbnail row (text-based to avoid heavy deps; WYSIWYG preview already in editor)+ if (bodyController.inlineImages.isNotEmpty()) {+ val inlineTotal = bodyController.inlineImages.sumOf { uriSize(context, it.localUri) }+ Text("Inline images (${bodyController.inlineImages.size} - ${android.text.format.Formatter.formatShortFileSize(context, inlineTotal)})", style = MaterialTheme.typography.labelSmall)+ androidx.compose.foundation.lazy.LazyRow(+ horizontalArrangement = Arrangement.spacedBy(8.dp),+ modifier = Modifier.fillMaxWidth()+ ) {+ items(bodyController.inlineImages.size) { idx ->+ val img = bodyController.inlineImages[idx]+ Card(modifier = Modifier.size(96.dp)) {+ Box(modifier = Modifier.fillMaxSize(), contentAlignment = Alignment.Center) {+ Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.Center) {+ com.vayunmathur.library.ui.IconImage(modifier = Modifier.size(24.dp))+ Text(img.fileName.take(16), style = MaterialTheme.typography.labelSmall, maxLines = 1, overflow = androidx.compose.ui.text.style.TextOverflow.Ellipsis)+ }+ IconButton(onClick = { bodyController.removeInlineImage(img.cid) }, modifier = Modifier.align(Alignment.TopEnd).size(20.dp)) {+ com.vayunmathur.library.ui.IconClose(modifier = Modifier.size(12.dp))+ }+ }+ }+ }+ }+ }++ if (attachments.isNotEmpty() || bodyController.inlineImages.isNotEmpty()) {+ val totalBytes = attachments.sumOf { uriSize(context, it) } + bodyController.inlineImages.sumOf { uriSize(context, it.localUri) } Text("Attachments (${android.text.format.Formatter.formatShortFileSize(context, totalBytes)})", style = MaterialTheme.typography.labelLarge) if (totalBytes > 25L * 1024 * 1024) { Text(@@ -1405,6 +1525,9 @@ fun ComposerScreen( color = MaterialTheme.colorScheme.error, ) }+ }++ if (attachments.isNotEmpty()) { attachments.forEach { uri -> val attachmentLabel = remember(uri) { "${uriName(context, uri)} · " + android.text.format.Formatter.formatShortFileSize(context, uriSize(context, uri))@@ -1432,6 +1555,35 @@ fun ComposerScreen( } } +@Composable+private fun EmailComposerFormatToolbar(+ controller: com.vayunmathur.email.composer.EmailHtmlEditorController,+ onInsertImage: () -> Unit,+) {+ com.vayunmathur.library.ui.EditorBottomBar(modifier = Modifier, scrollable = true) {+ com.vayunmathur.library.ui.EditorBaseButtons(formatter = controller)+ // Extra image button – use library's image icon+ com.vayunmathur.library.ui.FormatIconButton(+ contentDescription = "Insert image",+ onClick = onInsertImage,+ ) { com.vayunmathur.library.ui.IconImage() }+ }+}++private fun copyInlineToCache(context: android.content.Context, uri: Uri, name: String): Uri? {+ return try {+ val dir = java.io.File(context.cacheDir, "inline").also { it.mkdirs() }+ val safeName = name.replace(Regex("[/\\\\]"), "_").ifBlank { "image_${System.currentTimeMillis()}.jpg" }+ val outFile = java.io.File(dir, "${System.currentTimeMillis()}-$safeName")+ context.contentResolver.openInputStream(uri)?.use { input ->+ outFile.outputStream().use { out -> input.copyTo(out) }+ } ?: return null+ androidx.core.content.FileProvider.getUriForFile(context, "${context.packageName}.fileprovider", outFile)+ } catch (_: Exception) { null }+}+++ @OptIn(ExperimentalMaterial3Api::class) @Composable fun OutboxScreen(
email/src/main/java/com/vayunmathur/email/composer/CidImageSpan.kt
diff --git a/email/src/main/java/com/vayunmathur/email/composer/CidImageSpan.kt b/email/src/main/java/com/vayunmathur/email/composer/CidImageSpan.ktnew file mode 100644index 0000000000..d37456eb86--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/composer/CidImageSpan.kt@@ -0,0 +1,18 @@+package com.vayunmathur.email.composer++import android.graphics.drawable.Drawable+import android.net.Uri+import android.text.style.ImageSpan++/**+ * ImageSpan that holds a CID for inline email rendering.+ * [cid] is without angle brackets, e.g. "[email protected]"+ * [localUri] points to the cached file used for preview and sending.+ */+class CidImageSpan(+ val cid: String,+ val localUri: Uri,+ drawable: Drawable,+ val mimeType: String,+ val fileName: String,+) : ImageSpan(drawable)
email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.kt
diff --git a/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.kt b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.ktnew file mode 100644index 0000000000..a63f56bcc4--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlEditorController.kt@@ -0,0 +1,183 @@+package com.vayunmathur.email.composer++import android.content.Context+import android.graphics.Bitmap+import android.graphics.BitmapFactory+import android.graphics.drawable.BitmapDrawable+import android.net.Uri+import androidx.compose.runtime.mutableStateListOf+import androidx.compose.runtime.snapshots.SnapshotStateList+import com.vayunmathur.library.ui.HtmlEditorController+import java.util.UUID++/**+ * Email-specific controller extending the generic HtmlEditorController.+ * Adds inline image (CID) support for WYSIWYG composer.+ */+class EmailHtmlEditorController(+ initialHtml: String = "",+) : HtmlEditorController(+ initialHtml = initialHtml,+ htmlSerializer = { spanned -> serializeEmailHtml(spanned) },+) {+ // Observable list of inline images currently in the editor (for UI chips / size guard)+ val inlineImages: SnapshotStateList<InlineImage> = mutableStateListOf()++ /**+ * Insert an image from [sourceUri] into the editor at current cursor.+ * Returns the generated CID or null on failure.+ *+ * Generation:+ * - cid = "<uuid>@inline.local" without brackets stored, header will wrap <>.+ * - bitmap decoded scaled to max 1024w to keep .eml reasonable.+ */+ fun insertInlineImage(+ context: Context,+ sourceUri: Uri,+ mimeType: String = "image/jpeg",+ fileName: String = "image.jpg",+ ): String? {+ val edit = editText ?: return null+ val editable = edit.text ?: return null+ val cid = "${UUID.randomUUID()}@inline.local"++ val bitmap = decodeSampledBitmap(context, sourceUri, 1024) ?: return null+ val drawable = BitmapDrawable(context.resources, bitmap)++ // Scale bounds: if bitmap wider than edit width, shrink proportionally.+ // We cap at 1024 but also try to fit within ~80% of EditText width if available.+ val maxWidth = 1024+ var w = bitmap.width+ var h = bitmap.height+ if (w > maxWidth) {+ val ratio = maxWidth.toFloat() / w+ w = maxWidth+ h = (h * ratio).toInt()+ }+ // Optionally cap to EditText width if known+ val etWidth = edit.width+ if (etWidth > 0) {+ val available = (etWidth * 0.85f).toInt().coerceAtLeast(100)+ if (w > available) {+ val ratio = available.toFloat() / w+ w = available+ h = (h * ratio).toInt()+ }+ }+ drawable.setBounds(0, 0, w, h)++ val span = CidImageSpan(cid, sourceUri, drawable, mimeType, fileName)++ // Insert placeholder char at cursor+ val cursor = (edit.selectionStart.coerceAtLeast(0)).coerceAtMost(editable.length)+ // Ensure we guard watcher+ updating = true+ try {+ editable.insert(cursor, "\uFFFC")+ editable.setSpan(span, cursor, cursor + 1, android.text.Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)+ // Move cursor after inserted image+ edit.setSelection((cursor + 1).coerceAtMost(editable.length))+ } finally {+ updating = false+ }+ // Track+ inlineImages.add(+ InlineImage(+ cid = cid,+ localUri = sourceUri,+ mimeType = mimeType,+ fileName = fileName,+ )+ )+ // Refresh html+ inlineCleanupOrphans()+ commitHtml(htmlSerializer(editable))+ return cid+ }++ fun removeInlineImage(cid: String) {+ val edit = editText ?: return+ val editable = edit.text ?: return+ val spans = editable.getSpans(0, editable.length, CidImageSpan::class.java)+ var removed = false+ updating = true+ try {+ for (sp in spans) {+ if (sp.cid == cid) {+ val s = editable.getSpanStart(sp)+ val e = editable.getSpanEnd(sp)+ editable.removeSpan(sp)+ if (s in 0 until editable.length && e in 0..editable.length && s < e) {+ editable.delete(s, e)+ }+ removed = true+ }+ }+ } finally {+ updating = false+ }+ inlineImages.removeAll { it.cid == cid }+ if (removed) {+ commitHtml(htmlSerializer(editable))+ }+ }++ /**+ * Scan editable for orphan CidImageSpans that were deleted via backspace+ * and drop them from [inlineImages] list.+ */+ fun inlineCleanupOrphans() {+ val edit = editText ?: return+ val editable = edit.text ?: return+ val presentCids = editable.getSpans(0, editable.length, CidImageSpan::class.java)+ .map { it.cid }.toSet()+ if (presentCids.size != inlineImages.size) {+ inlineImages.removeAll { it.cid !in presentCids }+ }+ }++ /** Build list ready for sending: maps tracked InlineImage -> InlineAttachment */+ fun toInlineAttachments(): List<InlineAttachment> {+ // Deduplicate by cid, keep last uri+ return inlineImages.map {+ InlineAttachment(+ cid = it.cid,+ uri = it.localUri,+ mimeType = it.mimeType,+ fileName = it.fileName,+ )+ }+ }++ companion object {+ private fun decodeSampledBitmap(context: Context, uri: Uri, reqWidth: Int): Bitmap? {+ return try {+ // First decode with inJustDecodeBounds=true to get dimensions+ val optsBounds = BitmapFactory.Options().apply { inJustDecodeBounds = true }+ context.contentResolver.openInputStream(uri)?.use { input ->+ BitmapFactory.decodeStream(input, null, optsBounds)+ }+ val width = optsBounds.outWidth+ if (width <= 0) {+ // Fallback direct decode+ return context.contentResolver.openInputStream(uri)?.use { BitmapFactory.decodeStream(it) }+ }+ var sample = 1+ var w = width+ while (w / 2 >= reqWidth) {+ w /= 2+ sample *= 2+ }+ val opts = BitmapFactory.Options().apply {+ inSampleSize = sample+ inPreferredConfig = Bitmap.Config.ARGB_8888+ }+ context.contentResolver.openInputStream(uri)?.use { input ->+ BitmapFactory.decodeStream(input, null, opts)+ }+ } catch (_: Exception) {+ null+ }+ }+ }+}
email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.kt
diff --git a/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.kt b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.ktnew file mode 100644index 0000000000..5cbabd5893--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/composer/EmailHtmlSerializer.kt@@ -0,0 +1,216 @@+package com.vayunmathur.email.composer++import android.graphics.drawable.Drawable+import android.text.Spanned+import com.vayunmathur.library.ui.IndentSpan+import com.vayunmathur.library.ui.OrderedListSpan+import android.text.style.BulletSpan+import android.text.style.ImageSpan+import android.text.style.StrikethroughSpan+import android.text.style.StyleSpan+import android.text.style.URLSpan+import android.text.style.UnderlineSpan+import android.graphics.Typeface+import kotlin.math.min++/**+ * Serialize a Spanned (from HtmlEditor) to HTML, emitting <img src="cid:...">+ * for [CidImageSpan] and preserving bold/italic/underline/strike/links/lists/indent.+ */++fun serializeEmailHtml(spanned: Spanned): String {+ if (spanned.isEmpty()) return ""+ val len = spanned.length+ val out = StringBuilder()++ // Paragraph walk to emit <ul>/<ol> etc. Similar logic to library serializeRich+ // but with CID image support and inline style detection.+ // For simplicity we will first build paragraph boundaries then handle list grouping.++ data class Para(val start: Int, val end: Int)++ fun paras(): List<Para> {+ val list = mutableListOf<Para>()+ var pos = 0+ val text = spanned.toString()+ while (pos < len) {+ val nl = text.indexOf('\n', pos).let { if (it < 0) len else it }+ list.add(Para(pos, nl))+ pos = nl + 1+ }+ if (list.isEmpty() && len == 0) return emptyList()+ // keep trailing empty handled as <br> later+ return list+ }++ val allParas = paras()+ var currentList: String? = null+ var orderedCounter = 0++ fun closeList() {+ if (currentList != null) {+ out.append("</${currentList}>")+ currentList = null+ orderedCounter = 0+ }+ }++ fun hasBullet(p: Para): Boolean {+ return spanned.getSpans(p.start, p.end, BulletSpan::class.java).any {+ spanned.getSpanStart(it) < p.end && spanned.getSpanEnd(it) > p.start+ }+ }++ fun orderedSpan(p: Para): OrderedListSpan? {+ return spanned.getSpans(p.start, p.end, OrderedListSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) < p.end && spanned.getSpanEnd(it) > p.start+ }+ }++ fun indentLevel(p: Para): Int {+ return spanned.getSpans(p.start, p.end, IndentSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) < p.end && spanned.getSpanEnd(it) > p.start+ }?.level ?: 0+ }++ fun inlineHtmlFor(p: Para): String {+ if (p.start >= p.end) return ""+ return buildInlineHtml(spanned, p.start, p.end)+ }++ for (para in allParas) {+ if (para.start >= para.end) {+ closeList()+ val lvl = indentLevel(para)+ if (lvl > 0) out.append("<div style=\"margin-left: ${lvl * 24}px\"><br></div>")+ else out.append("<br>")+ continue+ }++ val bullet = hasBullet(para)+ val oSpan = orderedSpan(para)+ val indentLvl = indentLevel(para)+ val rawInline = inlineHtmlFor(para)+ val inner = if (rawInline.isBlank()) "<br>" else rawInline+ val contentWithIndent = if (indentLvl > 0 && !bullet && oSpan == null) {+ "<div style=\"margin-left: ${indentLvl * 24}px\">$inner</div>"+ } else if (indentLvl > 0) {+ "<div style=\"margin-left: ${indentLvl * 24}px\">$inner</div>"+ } else inner++ when {+ bullet -> {+ if (currentList != "ul") {+ closeList()+ out.append("<ul>")+ currentList = "ul"+ }+ out.append("<li>$contentWithIndent</li>")+ }+ oSpan != null -> {+ if (currentList != "ol") {+ closeList()+ out.append("<ol>")+ currentList = "ol"+ orderedCounter = 0+ }+ orderedCounter+++ out.append("<li>$contentWithIndent</li>")+ }+ else -> {+ closeList()+ if (indentLvl > 0) {+ out.append(contentWithIndent)+ } else {+ out.append("<div>$inner</div>")+ }+ }+ }+ }+ closeList()+ val result = out.toString()+ return result.ifBlank { "<div><br></div>" }+}++private fun buildInlineHtml(spanned: Spanned, start: Int, end: Int): String {+ // Walk character by character emitting tags when spans change.+ // We collect events: open/close of StyleSpan bold/italic, underline, strike, link, and CidImageSpan placeholder.+ val sb = StringBuilder()+ // For each char position, determine active spans+ // We'll build runs where the set of spans is constant+ var i = start+ while (i < end) {+ val char = spanned[i]+ // Check if this char is covered by CidImageSpan — emit <img> and skip obj replacement char+ val cidSpans = spanned.getSpans(i, i + 1, CidImageSpan::class.java).filter {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ if (cidSpans.isNotEmpty()) {+ val cs = cidSpans.first()+ sb.append("<img src=\"cid:${cs.cid}\">")+ // advance past this span's range+ val spanEnd = min(spanned.getSpanEnd(cs), end)+ i = spanEnd+ continue+ }+ // Regular object replacement char for image? Skip if it's the generic placeholder+ if (char == '\uFFFC') {+ // If no cid span found (fallback generic ImageSpan), emit generic placeholder maybe skip+ // Just skip+ i+++ continue+ }+ // Find run length where inline style set stays same+ val nextChange = findNextSpanBoundary(spanned, i, end)+ val slice = spanned.subSequence(i, nextChange).toString()+ // Encode and wrap with tags based on current spans at i+ var piece = android.text.TextUtils.htmlEncode(slice)+ // Link outermost, then bold/italic/underline/strike+ val urlSpan = spanned.getSpans(i, i + 1, URLSpan::class.java).firstOrNull {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ if (urlSpan != null) {+ piece = "<a href=\"${escapeAttr(urlSpan.url ?: "")}\">$piece</a>"+ }+ val bold = spanned.getSpans(i, i + 1, StyleSpan::class.java).any {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i && (it.style and Typeface.BOLD) != 0+ }+ if (bold) piece = "<b>$piece</b>"+ val italic = spanned.getSpans(i, i + 1, StyleSpan::class.java).any {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i && (it.style and Typeface.ITALIC) != 0+ }+ if (italic) piece = "<i>$piece</i>"+ val ul = spanned.getSpans(i, i + 1, UnderlineSpan::class.java).any {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ if (ul) piece = "<u>$piece</u>"+ val strike = spanned.getSpans(i, i + 1, StrikethroughSpan::class.java).any {+ spanned.getSpanStart(it) <= i && spanned.getSpanEnd(it) > i+ }+ if (strike) piece = "<s>$piece</s>"++ sb.append(piece)+ i = nextChange+ }+ // Replace newlines inside slice shouldn't exist (paras split), but handle \n -> <br>+ return sb.toString().replace("\n", "<br>")+}++private fun findNextSpanBoundary(spanned: Spanned, from: Int, end: Int): Int {+ var next = end+ val spans = spanned.getSpans(from, end, Any::class.java)+ for (sp in spans) {+ val s = spanned.getSpanStart(sp)+ val e = spanned.getSpanEnd(sp)+ if (s > from && s < next) next = s+ if (e > from && e < next) next = e+ }+ // Also consider ImageSpan boundaries+ // Ensure at least advance 1+ if (next == from) next = from + 1+ return min(next, end)+}++private fun escapeAttr(value: String): String {+ return value.replace("&", "&").replace("\"", """).replace("<", "<").replace(">", ">")+}
email/src/main/java/com/vayunmathur/email/composer/InlineImage.kt
diff --git a/email/src/main/java/com/vayunmathur/email/composer/InlineImage.kt b/email/src/main/java/com/vayunmathur/email/composer/InlineImage.ktnew file mode 100644index 0000000000..c3d41a8e83--- /dev/null+++ b/email/src/main/java/com/vayunmathur/email/composer/InlineImage.kt@@ -0,0 +1,27 @@+package com.vayunmathur.email.composer++import android.net.Uri+import kotlinx.serialization.Serializable++@Serializable+data class InlineImageMeta(+ val cid: String,+ val fileName: String,+ val mimeType: String,+ val sizeBytes: Long = 0L,+)++data class InlineImage(+ val cid: String,+ val localUri: Uri,+ val mimeType: String,+ val fileName: String,+ val sizeBytes: Long = 0L,+)++data class InlineAttachment(+ val cid: String,+ val uri: Uri,+ val mimeType: String,+ val fileName: String,+)
email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.ktindex 31b71e2782..f7b96aa34f 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt@@ -25,7 +25,7 @@ import com.vayunmathur.email.Attachment BlockedSender::class, DeletedUid::class, ],- version = 17,+ version = 18, exportSchema = false, ) abstract class EmailDatabase : RoomDatabase() {@@ -91,6 +91,11 @@ abstract class EmailDatabase : RoomDatabase() { it.execSQL("ALTER TABLE EmailMessage ADD COLUMN listUnsubscribePost TEXT") } + private val MIGRATION_17_18 = Migration(17, 18) {+ it.execSQL("ALTER TABLE OutboxEntry ADD COLUMN inlineImageJson TEXT NOT NULL DEFAULT '[]'")+ it.execSQL("ALTER TABLE DraftEntry ADD COLUMN inlineImageJson TEXT NOT NULL DEFAULT '[]'")+ }+ private val MIGRATION_5_6 = Migration(5, 6) { it.execSQL("ALTER TABLE EmailMessage ADD COLUMN dateMillis INTEGER NOT NULL DEFAULT 0") }@@ -141,7 +146,7 @@ abstract class EmailDatabase : RoomDatabase() { fun getInstance(context: Context): EmailDatabase { return instance ?: synchronized(this) { instance ?: context.applicationContext.buildDatabase<EmailDatabase>(- migrations = listOf(MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17),+ migrations = listOf(MIGRATION_4_5, MIGRATION_5_6, MIGRATION_6_7, MIGRATION_7_8, MIGRATION_8_9, MIGRATION_9_10, MIGRATION_10_11, MIGRATION_11_12, MIGRATION_12_13, MIGRATION_13_14, MIGRATION_14_15, MIGRATION_15_16, MIGRATION_16_17, MIGRATION_17_18), dbName = "email-db" ).also { instance = it } }
email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.ktindex 1006c25b46..adf85c1161 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt@@ -15,6 +15,7 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : CoroutineWorker(appContext, workerParams) { override suspend fun doWork(): Result {+ val nonInboxOnly = inputData.getBoolean(KEY_NON_INBOX_ONLY, false) val db = EmailDatabase.getInstance(applicationContext) val dao = db.emailDao() val accounts = dao.getAccounts()@@ -31,7 +32,7 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : for (account in accounts) { try {- Log.d("EmailSync", ">>> Starting sync for account: ${account.email}")+ Log.d("EmailSync", ">>> Starting sync for account: ${account.email} (nonInboxOnly=$nonInboxOnly)") val auth = account.resolveAuth(applicationContext) manager.withStore(account.imapServer(), account.loginUser(), auth) { store ->@@ -43,8 +44,14 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : val skipSet = if (account.provider == PROVIDER_GMAIL) { GMAIL_VIRTUAL_FOLDERS } else emptySet()- val messageFolders = folders.filter { folder ->- folder.holdsMessages && folder.fullName !in skipSet+ val messageFolders = if (nonInboxOnly) {+ folders.filter { folder ->+ folder.holdsMessages && folder.fullName !in skipSet && folder.fullName != "INBOX"+ }+ } else {+ folders.filter { folder ->+ folder.holdsMessages && folder.fullName !in skipSet+ } } val totalUnits = (accounts.size * messageFolders.size).coerceAtLeast(1) @@ -63,24 +70,27 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : if (messages.isNotEmpty()) dao.insertMessages(messages) if (attachments.isNotEmpty()) dao.insertAttachments(attachments) - if (knownUids.isNotEmpty() && folder.fullName == "INBOX") {- syncReadStatus(store, account.email, folder.fullName, knownUids)- }-- if (folder.fullName == "INBOX" && messages.isNotEmpty()) {- val lastSeen = lastSeenPrefs(applicationContext)- .getLong(lastSeenKey(account.email, folder.fullName), -1L)- if (lastSeen >= 0L && !com.vayunmathur.email.util.AppLifecycleTracker.isAppInForeground) {- val notifiable = messages.filter { it.id > lastSeen }- com.vayunmathur.email.util.EmailNotifications.postForNewMessages(- applicationContext, account.email, notifiable,- )+ // INBOX-only: read-status sync + foreground notification (skip when nonInboxOnly)+ if (!nonInboxOnly) {+ if (knownUids.isNotEmpty() && folder.fullName == "INBOX") {+ syncReadStatus(store, account.email, folder.fullName, knownUids) }- val maxUid = messages.maxOf { it.id }- if (maxUid > lastSeen) {- lastSeenPrefs(applicationContext).edit()- .putLong(lastSeenKey(account.email, folder.fullName), maxUid)- .apply()++ if (folder.fullName == "INBOX" && messages.isNotEmpty()) {+ val lastSeen = lastSeenPrefs(applicationContext)+ .getLong(lastSeenKey(account.email, folder.fullName), -1L)+ if (lastSeen >= 0L && !com.vayunmathur.email.util.AppLifecycleTracker.isAppInForeground) {+ val notifiable = messages.filter { it.id > lastSeen }+ com.vayunmathur.email.util.EmailNotifications.postForNewMessages(+ applicationContext, account.email, notifiable,+ )+ }+ val maxUid = messages.maxOf { it.id }+ if (maxUid > lastSeen) {+ lastSeenPrefs(applicationContext).edit()+ .putLong(lastSeenKey(account.email, folder.fullName), maxUid)+ .apply()+ } } } @@ -92,38 +102,41 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : EmailSyncState.setProgress(unitsDone.toFloat() / totalUnits) } - val missing = dao.getMessagesWithoutBody(account.email, BACKFILL_LIMIT)- if (missing.isNotEmpty()) {- Log.d("EmailSync", "Body backfill: ${missing.size} message(s)")- EmailSyncState.setProgress(0f)- for ((idx, msg) in missing.withIndex()) {- if (isStopped) {- Log.d("EmailSync", "Backfill stopped at ${idx}/${missing.size}")- break- }- try {- val current = dao.getMessage(msg.accountEmail, msg.folderName, msg.id) ?: continue- if (current.body != null) continue- val (body, isHtml, attachments) = manager.fetchMessageBodyInStore(- store = store,- user = account.loginUser(),- folderName = msg.folderName,- uid = msg.id,- )- if (body != null || attachments.isNotEmpty()) {- dao.insertMessages(listOf(current.copy(- body = body,- isHtml = isHtml,- hasAttachments = attachments.isNotEmpty(),- )))- if (attachments.isNotEmpty()) dao.insertAttachments(attachments)+ // Body backfill only for full sync (on-demand / initial) — skip for hourly non-INBOX to save battery.+ if (!nonInboxOnly) {+ val missing = dao.getMessagesWithoutBody(account.email, BACKFILL_LIMIT)+ if (missing.isNotEmpty()) {+ Log.d("EmailSync", "Body backfill: ${missing.size} message(s)")+ EmailSyncState.setProgress(0f)+ for ((idx, msg) in missing.withIndex()) {+ if (isStopped) {+ Log.d("EmailSync", "Backfill stopped at ${idx}/${missing.size}")+ break+ }+ try {+ val current = dao.getMessage(msg.accountEmail, msg.folderName, msg.id) ?: continue+ if (current.body != null) continue+ val (body, isHtml, attachments) = manager.fetchMessageBodyInStore(+ store = store,+ user = account.loginUser(),+ folderName = msg.folderName,+ uid = msg.id,+ )+ if (body != null || attachments.isNotEmpty()) {+ dao.insertMessages(listOf(current.copy(+ body = body,+ isHtml = isHtml,+ hasAttachments = attachments.isNotEmpty(),+ )))+ if (attachments.isNotEmpty()) dao.insertAttachments(attachments)+ }+ } catch (e: Exception) {+ Log.w("EmailSync", " x Backfill failed for UID ${msg.id}: ${e.message}") }- } catch (e: Exception) {- Log.w("EmailSync", " x Backfill failed for UID ${msg.id}: ${e.message}")+ EmailSyncState.setProgress((idx + 1f) / missing.size) }- EmailSyncState.setProgress((idx + 1f) / missing.size)+ Log.d("EmailSync", "Backfill done for ${account.email}") }- Log.d("EmailSync", "Backfill done for ${account.email}") } } @@ -135,7 +148,9 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : accountsProcessed++ } - EmailWidget().updateAll(applicationContext)+ if (!nonInboxOnly) {+ EmailWidget().updateAll(applicationContext)+ } EmailSyncState.finish() return if (hasErrors) Result.retry() else Result.success()@@ -143,6 +158,8 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : companion object { private const val SYNC_WORK_NAME = "EmailSyncWorker"+ private const val HOURLY_NON_INBOX_WORK_NAME = "EmailNonInboxHourlySync"+ private const val KEY_NON_INBOX_ONLY = "non_inbox_only" /** * Sync read/unread flags from the IMAP server for messages we already@@ -199,31 +216,55 @@ class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) : private fun lastSeenKey(accountEmail: String, folderName: String) = "$accountEmail::$folderName" + /**+ * Legacy 15-min periodic polling — removed in IDLE-only model.+ * Kept as a no-op that cancels any previously scheduled periodic work+ * so upgrades from older APKs stop polling.+ */+ @Deprecated("IDLE-only push: periodic polling removed. This now cancels legacy periodic work.", ReplaceWith("cancelSync(context)")) fun schedulePeriodicSync(context: Context) {+ WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)+ WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME)+ }++ /**+ * Hourly non-INBOX sync: polls only non-INBOX folders (e.g. Sent, custom labels)+ * once per hour via WorkManager. INBOX stays IDLE-only push — no polling.+ * Cheap: skips body backfill, skip SEEN sync, skips notifications.+ */+ fun scheduleHourlyNonInboxSync(context: Context) {+ // Purge legacy 15-min full polling work that may still be scheduled.+ WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME) val constraints = Constraints.Builder() .setRequiredNetworkType(NetworkType.CONNECTED) .build()-- val syncRequest = PeriodicWorkRequestBuilder<EmailSyncWorker>(15, TimeUnit.MINUTES)+ val data = Data.Builder().putBoolean(KEY_NON_INBOX_ONLY, true).build()+ val req = PeriodicWorkRequestBuilder<EmailSyncWorker>(1, TimeUnit.HOURS) .setConstraints(constraints)+ .setInputData(data) .build()- WorkManager.getInstance(context).enqueueUniquePeriodicWork(- SYNC_WORK_NAME,+ HOURLY_NON_INBOX_WORK_NAME, ExistingPeriodicWorkPolicy.KEEP,- syncRequest+ req, ) } + /**+ * One-off catch-up: folder discovery + all-folder header fetch + body backfill.+ * Used for initial sync after account add, manual pull-to-refresh, boot recovery, and+ * non-INBOX folder catch-up. Not periodic — INBOX live push is handled by [ImapIdleService].+ */ fun runOneOffSync(context: Context) { val syncRequest = OneTimeWorkRequestBuilder<EmailSyncWorker>()+ .setInputData(Data.Builder().putBoolean(KEY_NON_INBOX_ONLY, false).build()) .build()- WorkManager.getInstance(context).enqueue(syncRequest) }- + fun cancelSync(context: Context) { WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)+ WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME) } } }
email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.ktindex f75fcd7fa4..bf87842df1 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -13,12 +13,19 @@ import android.util.Log import androidx.core.app.NotificationCompat import androidx.glance.appwidget.updateAll import com.sun.mail.imap.IMAPFolder+import com.sun.mail.imap.IMAPStore import com.vayunmathur.email.EmailManager import com.vayunmathur.email.R import com.vayunmathur.email.resolveAuth import com.vayunmathur.email.imapServer import com.vayunmathur.email.loginUser+import java.util.Collections+import java.util.concurrent.atomic.AtomicBoolean+import javax.mail.Flags import javax.mail.Folder+import javax.mail.UIDFolder+import javax.mail.event.MessageChangedEvent+import javax.mail.event.MessageChangedListener import javax.mail.event.MessageCountAdapter import javax.mail.event.MessageCountEvent import kotlinx.coroutines.CoroutineScope@@ -33,14 +40,18 @@ import kotlinx.coroutines.withContext /** * Foreground service that keeps one IMAP IDLE connection open per account.- * When Gmail pushes an `EXISTS` (new message) we kick off a one-off- * [EmailSyncWorker] run; that worker pulls the headers, updates the DB, and- * (via the notification code) raises a system notification if the app isn't- * in the foreground. *- * IDLE connections naturally time out after ~29 minutes on most servers — we- * just catch the disconnect and reconnect with exponential backoff. On- * auth-failed we stop retrying since app passwords can't be auto-refreshed.+ * IDLE push model:+ * - INBOX is watched via `IMAPFolder.idle(true)` for instant push (1 RTT).+ * A watchdog triggers a graceful refresh at ~24 min to beat the server's+ * ~29 min IDLE timeout — avoids BYE + full TLS re-handshake by closing+ * INBOX and reopening it on the same STORE.+ * - Folder list refreshed on every store connect.+ * - Read/unread via [MessageChangedListener] (FLAGS_CHANGED).+ * - Deletions via `messagesRemoved` (EXPUNGE).+ *+ * Non-INBOX: INBOX is live push; other folders hourly via+ * [EmailSyncWorker.scheduleHourlyNonInboxSync] + on-demand pull-to-refresh. */ class ImapIdleService : Service() { @@ -67,6 +78,14 @@ class ImapIdleService : Service() { stopSelf() return }+ try {+ EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext)+ } catch (_: Throwable) {}+ val currentEmails = accounts.map { it.email }.toSet()+ accountJobs.keys.filter { it !in currentEmails }.forEach { email ->+ accountJobs[email]?.cancel()+ accountJobs.remove(email)+ } for (account in accounts) { accountJobs[account.email]?.cancel() accountJobs[account.email] = scope.launch { idleLoop(account) }@@ -79,7 +98,6 @@ class ImapIdleService : Service() { while (scope.coroutineContext.isActive) { try { runIdleSession(account)- // Clean return (server dropped IDLE) — short reconnect. backoffMs = 2_000L delay(1_000L) } catch (e: javax.mail.AuthenticationFailedException) {@@ -93,16 +111,6 @@ class ImapIdleService : Service() { } } - /**
Diff truncated.