email: fix package declarations and imports for canonical locations (data/network/platform/ui)
- Commit
017f47885df03ad26ccbe3a844ac78c603d8aa2a- Author
- vayun-mathur <[email protected]>
- When
- 2026-08-15 19:25 UTC (3 months ago)
- Parents
01ed937
Diff
email/src/main/java/com/vayunmathur/email/data/EmailModels.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt b/email/src/main/java/com/vayunmathur/email/data/EmailModels.ktindex 79cabe1056..7833f47ebe 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt@@ -1,376 +1,376 @@-package com.vayunmathur.email--import androidx.room.ColumnInfo-import androidx.room.Entity-import androidx.room.PrimaryKey-import androidx.core.text.HtmlCompat-import kotlinx.serialization.Serializable-import com.vayunmathur.email.imap.MimeParser--@Serializable-@Entity(primaryKeys = ["accountEmail", "fullName"])-data class EmailFolder(- val accountEmail: String,- val fullName: String,- val name: String,- val parentFullName: String? = null,- val holdsMessages: Boolean = true,- val delimiter: String = "/"-)--@Serializable-@Entity(primaryKeys = ["accountEmail", "folderName", "id"])-data class EmailMessage(- val accountEmail: String,- val folderName: String,- val id: Long, // IMAP UID- val serverId: String? = null, // Message-ID header- val threadId: String? = null, // Gmail Thread ID or custom grouping- val subject: String,- val from: String,- val to: String? = null,- val cc: String? = null,- val date: String,- /** Date in epoch-millis. Used for chronological ordering, especially in the- * cross-account unified inbox where IMAP UIDs aren't comparable. Defaults- * to 0 for rows persisted before this column existed; backfilled on app- * start via [EmailDao.getRowsWithZeroDateMillis]. */- val dateMillis: Long = 0,- val body: String? = null,- val isHtml: Boolean = false,- val isRead: Boolean = false,- val references: String? = null, // References/In-Reply-To for threading- val hasAttachments: Boolean = false,- val snoozedUntil: Long = 0, // 0 = not snoozed; else epoch millis to resurface- val listUnsubscribe: String? = null, // raw List-Unsubscribe header, if present- val listUnsubscribePost: String? = null, // raw List-Unsubscribe-Post header (RFC 8058), if present-)--@Entity-data class BlockedSender(- @PrimaryKey val address: String,-)--/**- * Tombstone for a locally-deleted message. Recorded when the user deletes a- * message so that the sync worker / IMAP IDLE fetch skips its UID and never- * re-inserts it (the server expunge can lag or fail, leaving the UID briefly- * fetchable). Keyed by the same (account, folder, uid) tuple as EmailMessage.- */-@Entity(primaryKeys = ["accountEmail", "folderName", "uid"])-data class DeletedUid(- val accountEmail: String,- val folderName: String,- val uid: Long,-)--@Serializable-@Entity(primaryKeys = ["accountEmail", "messageId", "partId"])-data class Attachment(- val accountEmail: String,- val folderName: String,- val messageId: Long, // IMAP UID- val partId: String,- val fileName: String,- val mimeType: String,- val size: Long,- val localUri: String? = null-)--@Serializable-@Entity-data class EmailAccount(- @PrimaryKey val email: String,- /**- * Legacy OAuth-token columns. Kept in the schema so old DB rows still- * load, but no longer written: every account now uses an app password.- */- val accessToken: String = "",- val refreshToken: String? = null,- val expiresAt: Long = 0,- /**- * Preset identifier — `gmail`, `outlook`, `yahoo`, `icloud`, `fastmail`, or- * `custom`. Used to (a) skip Gmail-only behaviour (virtual folder filtering)- * for non-Gmail accounts, and (b) display the provider name in- * account-picker UIs.- *- * `@ColumnInfo(defaultValue = ...)` is required so the schema generated- * from this entity matches `MIGRATION_6_7`, which `ALTER TABLE`s these- * columns in with a SQL default. Without it Room would throw- * `IllegalStateException: Migration didn't properly handle: EmailAccount`- * at startup for users upgrading from v6.- */- @ColumnInfo(defaultValue = "gmail")- val provider: String = "gmail",- /** IMAP hostname this account fetches from. Hard-coded to Gmail's pre-multi-provider migration. */- @ColumnInfo(defaultValue = "imap.gmail.com")- val imapHost: String = "imap.gmail.com",- @ColumnInfo(defaultValue = "993")- val imapPort: Int = 993,- /** true = implicit SSL/TLS on connect, false = plaintext + STARTTLS upgrade. */- @ColumnInfo(defaultValue = "1")- val imapUseSsl: Boolean = true,- @ColumnInfo(defaultValue = "smtp.gmail.com")- val smtpHost: String = "smtp.gmail.com",- @ColumnInfo(defaultValue = "465")- val smtpPort: Int = 465,- @ColumnInfo(defaultValue = "1")- val smtpUseSsl: Boolean = true,- /**- * Optional login username for IMAP/SMTP authentication when it differs- * from the email address (common with custom providers). When null or- * blank, [email] is used for authentication.- */- @ColumnInfo(defaultValue = "")- val username: String = "",- /**- * Auth scheme. Only `password` is supported now; the column is preserved- * with its original default for legacy DB compatibility, but every newly- * added account stores credentials as an encrypted app password.- */- @ColumnInfo(defaultValue = "oauth2")- val authType: String = "password",- /** AES-256-GCM ciphertext of the app password. */- val passwordEncrypted: ByteArray? = null,- /** GCM IV used to decrypt [passwordEncrypted]. */- val passwordIv: ByteArray? = null,- /** Plain-text signature appended to outgoing messages from this account. */- @ColumnInfo(defaultValue = "")- val signature: String = "",-) {- fun getColor(): Long = accountColor(email)-}--/** Material palette used to give each account a stable color, by email hash. */-val ACCOUNT_COLORS: List<Long> = listOf(- 0xFFF44336, // Red- 0xFFE91E63, // Pink- 0xFF9C27B0, // Purple- 0xFF673AB7, // Deep Purple- 0xFF3F51B5, // Indigo- 0xFF2196F3, // Blue- 0xFF03A9F4, // Light Blue- 0xFF00BCD4, // Cyan- 0xFF009688, // Teal- 0xFF4CAF50, // Green- 0xFF8BC34A, // Light Green- 0xFFCDDC39, // Lime- 0xFFFFEB3B, // Yellow- 0xFFFFC107, // Amber- 0xFFFF9800, // Orange- 0xFFFF5722, // Deep Orange- 0xFF795548, // Brown- 0xFF9E9E9E, // Grey- 0xFF607D8B // Blue Grey-)--/** Stable color for [email], derived from its hash. */-fun accountColor(email: String): Long {- val hash = email.hashCode()- return ACCOUNT_COLORS[(hash and Int.MAX_VALUE) % ACCOUNT_COLORS.size]-}--/**- * Content of `<script>`, `<style>`, `<head>` and `<title>` elements.- *- * [HtmlCompat.fromHtml] emits the *text* inside these rather than dropping- * them, so a message whose body is a full HTML document renders its stylesheet- * as the first hundred characters of the preview.- */-private val HTML_NON_CONTENT = Regex("""<(script|style|head|title)\b[^>]*>.*?</\1\s*>""", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))-private val HTML_COMMENT = Regex("""<!--.*?-->""", RegexOption.DOT_MATCHES_ALL)-private val HTML_DECLARATION = Regex("""<[!?][^>]*>""")-/** Tags common enough that their presence means the body is HTML whatever the flag says. */-private val LOOKS_LIKE_HTML = Regex("""<(html|body|head|div|table|p|br|span|a|img|font)\b[^>]*>""", RegexOption.IGNORE_CASE)-/**- * Includes the non-breaking space `fromHtml` produces from ` ` and the- * Unicode line/paragraph separators, none of which `\s` matches.- */-private val WHITESPACE_RUN = Regex("""[\s\u00A0\u2028\u2029]+""")--/**- * Characters that draw as an empty box, or as nothing at all.- *- * `fromHtml` returns a `Spanned` in which every `<img>` is a U+FFFC anchored to- * an `ImageSpan`; `toString()` discards the span and leaves the placeholder- * behind with nothing to stand for. U+FFFD is the decoder's marker for bytes it- * could not make sense of. The zero-width characters are the invisible padding- * marketing mail uses to pull its preheader around, and the C0/C1 controls come- * through from mail that was never really text.- *- * Deliberately excludes tab, newline and the vertical whitespace controls -- * those separate words, so deleting them would run the words together where- * collapsing them to a space does not.- */-private val UNRENDERABLE = Regex("[\\uFFFC\\uFFFD\\u200B-\\u200F\\uFEFF\\u0000-\\u0008\\u000E-\\u001F\\u007F]")--/**- * Plain-text rendering of this message's body.- *- * Falls back to sniffing the markup when [EmailMessage.isHtml] is false, because- * plenty of senders set `text/plain` on a body that is anything but.- */-fun EmailMessage.plainTextBody(): String? {- val raw = body ?: return null- if (!isHtml && !LOOKS_LIKE_HTML.containsMatchIn(raw)) return raw.replace(UNRENDERABLE, "")- val stripped = raw- .replace(HTML_COMMENT, " ")- .replace(HTML_NON_CONTENT, " ")- .replace(HTML_DECLARATION, " ")- return HtmlCompat.fromHtml(stripped, HtmlCompat.FROM_HTML_MODE_LEGACY)- .toString()- .replace(UNRENDERABLE, "")-}--/**- * A single-line snippet of the body for list rows, widgets and notifications.- *- * Collapses whitespace before truncating: the block structure of an HTML mail- * turns into leading blank lines, so [plainTextBody] truncated as-is is often- * entirely empty.- */-fun EmailMessage.previewText(maxChars: Int): String =- (plainTextBody() ?: "").replace(WHITESPACE_RUN, " ").trim().take(maxChars)--/** Display name for a "Name <addr>" sender header, falling back to the address.- * Implemented via own RFC2047 decode + simple parse to remove Jakarta dependency. */-fun senderDisplayName(from: String): String {- if (from.isBlank()) return ""- // Try to extract "Name <addr>" pattern- val trimmed = from.trim()- // Decode RFC2047 first- val decoded = MimeParser.decodeHeader(trimmed)- // Look for <...> format- val angleMatch = Regex("""^(.*)<([^>]+)>$""").find(decoded.trim())- if (angleMatch != null) {- val namePart = angleMatch.groupValues[1].trim().trim('"').trim()- val addr = angleMatch.groupValues[2].trim()- if (namePart.isNotBlank()) return namePart- return addr- }- // No angle brackets — could be bare address or just name- if (decoded.contains("@")) return decoded.substringBefore("<").trim()- return decoded-}--/**- * A detected way to unsubscribe from a message. Produced by [detectUnsubscribe]- * and acted on by the message-view UI.- */-sealed interface UnsubscribeMethod {- /** RFC 8058 one-click: HTTPS POST to [url] with body `List-Unsubscribe=One-Click`. */- data class OneClickPost(val url: String) : UnsubscribeMethod- /** Open an unsubscribe web page ([url]) in the browser. */- data class OpenWeb(val url: String) : UnsubscribeMethod- /** Compose an unsubscribe email to [address] using the in-app composer. */- data class SendMail(val address: String) : UnsubscribeMethod-}--/** Words that signal an unsubscribe affordance; kept small to avoid false positives. */-private val UNSUBSCRIBE_KEYWORDS = listOf("unsubscribe", "opt out", "opt-out", "optout")--/**- * Work out how (if at all) the user can unsubscribe from this message.- *- * Order of preference, per the email standards:- * 1. RFC 8058 one-click POST — when `List-Unsubscribe-Post: List-Unsubscribe=One-Click`- * is present together with an https URL in `List-Unsubscribe`.- * 2. An https/http URL from the `List-Unsubscribe` header (opened in the browser).- * 3. A `mailto:` target from the `List-Unsubscribe` header (composed in-app).- * 4. Fallback: a conservative scan of the body for an "unsubscribe" link.- */-fun EmailMessage.detectUnsubscribe(): UnsubscribeMethod? {- listUnsubscribe?.let { header ->- val targets = parseListUnsubscribe(header)- val webUrl = targets.firstOrNull { it.startsWith("http", ignoreCase = true) }- val httpsUrl = targets.firstOrNull { it.startsWith("https://", ignoreCase = true) }- val mailto = targets.firstOrNull { it.startsWith("mailto:", ignoreCase = true) }-- val isOneClick = listUnsubscribePost?.contains("one-click", ignoreCase = true) == true- if (isOneClick && httpsUrl != null) return UnsubscribeMethod.OneClickPost(httpsUrl)- if (webUrl != null) return UnsubscribeMethod.OpenWeb(webUrl)- if (mailto != null) {- val address = mailto.removePrefix("mailto:").removePrefix("MAILTO:").substringBefore("?").trim()- if (address.contains("@")) return UnsubscribeMethod.SendMail(address)- }- }- return findUnsubscribeLinkInBody()?.let { UnsubscribeMethod.OpenWeb(it) }-}--/** Extract the angle-bracketed targets from a List-Unsubscribe header (RFC 2369). */-private fun parseListUnsubscribe(header: String): List<String> =- Regex("<([^>]+)>").findAll(header).map { it.groupValues[1].trim() }.toList()- .ifEmpty { header.split(",").map { it.trim() }.filter { it.isNotEmpty() } }--/**- * Conservatively look for an unsubscribe link in the body. Only returns a link- * when the word "unsubscribe" (or an "opt out" variant) appears in the link's- * href or visible text, to avoid mistaking ordinary links for unsubscribe ones.- */-private fun EmailMessage.findUnsubscribeLinkInBody(): String? {- val content = body ?: return null- if (isHtml) {- val anchor = Regex(- "<a\\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>(.*?)</a>",- setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),- )- for (match in anchor.findAll(content)) {- val href = match.groupValues[1].trim()- if (!href.startsWith("http", ignoreCase = true)) continue- val haystack = (href + " " + match.groupValues[2]).lowercase()- if (UNSUBSCRIBE_KEYWORDS.any { haystack.contains(it) }) return href- }- return null- }- // Plain text: return an http(s) URL sitting on a line that mentions unsubscribe.- for (line in content.lineSequence()) {- val lower = line.lowercase()- if (UNSUBSCRIBE_KEYWORDS.none { lower.contains(it) }) continue- Regex("https?://\\S+", RegexOption.IGNORE_CASE).find(line)?.value- ?.trimEnd('.', ',', ')', '>', ']')- ?.let { return it }- }- return null-}--/// Pending outgoing message stored locally until it is successfully sent by the-/// 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. [inlineImageJson] stores JSON array of {cid,path,mime,name}.-@Serializable-@Entity-data class OutboxEntry(- @PrimaryKey(autoGenerate = true) val id: Long = 0,- val accountEmail: String,- val to: String,- val cc: String? = null,- val bcc: String? = null,- 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(),- val lastError: String? = null,- val attemptCount: Int = 0,- val lastAttemptAt: Long = 0,- val scheduledAt: Long = 0,- val isHtml: Boolean = false-)--@Entity-data class DraftEntry(- @PrimaryKey(autoGenerate = true) val id: Long = 0,- val accountEmail: String,- val to: String = "",- val cc: String = "",- val bcc: String = "",- val subject: String = "",- val body: String = "",- @ColumnInfo(defaultValue = "[]")- val inlineImageJson: String = "[]",- val updatedAt: Long = System.currentTimeMillis(),-)+package com.vayunmathur.email.data++import androidx.room.ColumnInfo+import androidx.room.Entity+import androidx.room.PrimaryKey+import androidx.core.text.HtmlCompat+import kotlinx.serialization.Serializable+import com.vayunmathur.email.network.imap.MimeParser++@Serializable+@Entity(primaryKeys = ["accountEmail", "fullName"])+data class EmailFolder(+ val accountEmail: String,+ val fullName: String,+ val name: String,+ val parentFullName: String? = null,+ val holdsMessages: Boolean = true,+ val delimiter: String = "/"+)++@Serializable+@Entity(primaryKeys = ["accountEmail", "folderName", "id"])+data class EmailMessage(+ val accountEmail: String,+ val folderName: String,+ val id: Long, // IMAP UID+ val serverId: String? = null, // Message-ID header+ val threadId: String? = null, // Gmail Thread ID or custom grouping+ val subject: String,+ val from: String,+ val to: String? = null,+ val cc: String? = null,+ val date: String,+ /** Date in epoch-millis. Used for chronological ordering, especially in the+ * cross-account unified inbox where IMAP UIDs aren't comparable. Defaults+ * to 0 for rows persisted before this column existed; backfilled on app+ * start via [EmailDao.getRowsWithZeroDateMillis]. */+ val dateMillis: Long = 0,+ val body: String? = null,+ val isHtml: Boolean = false,+ val isRead: Boolean = false,+ val references: String? = null, // References/In-Reply-To for threading+ val hasAttachments: Boolean = false,+ val snoozedUntil: Long = 0, // 0 = not snoozed; else epoch millis to resurface+ val listUnsubscribe: String? = null, // raw List-Unsubscribe header, if present+ val listUnsubscribePost: String? = null, // raw List-Unsubscribe-Post header (RFC 8058), if present+)++@Entity+data class BlockedSender(+ @PrimaryKey val address: String,+)++/**+ * Tombstone for a locally-deleted message. Recorded when the user deletes a+ * message so that the sync worker / IMAP IDLE fetch skips its UID and never+ * re-inserts it (the server expunge can lag or fail, leaving the UID briefly+ * fetchable). Keyed by the same (account, folder, uid) tuple as EmailMessage.+ */+@Entity(primaryKeys = ["accountEmail", "folderName", "uid"])+data class DeletedUid(+ val accountEmail: String,+ val folderName: String,+ val uid: Long,+)++@Serializable+@Entity(primaryKeys = ["accountEmail", "messageId", "partId"])+data class Attachment(+ val accountEmail: String,+ val folderName: String,+ val messageId: Long, // IMAP UID+ val partId: String,+ val fileName: String,+ val mimeType: String,+ val size: Long,+ val localUri: String? = null+)++@Serializable+@Entity+data class EmailAccount(+ @PrimaryKey val email: String,+ /**+ * Legacy OAuth-token columns. Kept in the schema so old DB rows still+ * load, but no longer written: every account now uses an app password.+ */+ val accessToken: String = "",+ val refreshToken: String? = null,+ val expiresAt: Long = 0,+ /**+ * Preset identifier — `gmail`, `outlook`, `yahoo`, `icloud`, `fastmail`, or+ * `custom`. Used to (a) skip Gmail-only behaviour (virtual folder filtering)+ * for non-Gmail accounts, and (b) display the provider name in+ * account-picker UIs.+ *+ * `@ColumnInfo(defaultValue = ...)` is required so the schema generated+ * from this entity matches `MIGRATION_6_7`, which `ALTER TABLE`s these+ * columns in with a SQL default. Without it Room would throw+ * `IllegalStateException: Migration didn't properly handle: EmailAccount`+ * at startup for users upgrading from v6.+ */+ @ColumnInfo(defaultValue = "gmail")+ val provider: String = "gmail",+ /** IMAP hostname this account fetches from. Hard-coded to Gmail's pre-multi-provider migration. */+ @ColumnInfo(defaultValue = "imap.gmail.com")+ val imapHost: String = "imap.gmail.com",+ @ColumnInfo(defaultValue = "993")+ val imapPort: Int = 993,+ /** true = implicit SSL/TLS on connect, false = plaintext + STARTTLS upgrade. */+ @ColumnInfo(defaultValue = "1")+ val imapUseSsl: Boolean = true,+ @ColumnInfo(defaultValue = "smtp.gmail.com")+ val smtpHost: String = "smtp.gmail.com",+ @ColumnInfo(defaultValue = "465")+ val smtpPort: Int = 465,+ @ColumnInfo(defaultValue = "1")+ val smtpUseSsl: Boolean = true,+ /**+ * Optional login username for IMAP/SMTP authentication when it differs+ * from the email address (common with custom providers). When null or+ * blank, [email] is used for authentication.+ */+ @ColumnInfo(defaultValue = "")+ val username: String = "",+ /**+ * Auth scheme. Only `password` is supported now; the column is preserved+ * with its original default for legacy DB compatibility, but every newly+ * added account stores credentials as an encrypted app password.+ */+ @ColumnInfo(defaultValue = "oauth2")+ val authType: String = "password",+ /** AES-256-GCM ciphertext of the app password. */+ val passwordEncrypted: ByteArray? = null,+ /** GCM IV used to decrypt [passwordEncrypted]. */+ val passwordIv: ByteArray? = null,+ /** Plain-text signature appended to outgoing messages from this account. */+ @ColumnInfo(defaultValue = "")+ val signature: String = "",+) {+ fun getColor(): Long = accountColor(email)+}++/** Material palette used to give each account a stable color, by email hash. */+val ACCOUNT_COLORS: List<Long> = listOf(+ 0xFFF44336, // Red+ 0xFFE91E63, // Pink+ 0xFF9C27B0, // Purple+ 0xFF673AB7, // Deep Purple+ 0xFF3F51B5, // Indigo+ 0xFF2196F3, // Blue+ 0xFF03A9F4, // Light Blue+ 0xFF00BCD4, // Cyan+ 0xFF009688, // Teal+ 0xFF4CAF50, // Green+ 0xFF8BC34A, // Light Green+ 0xFFCDDC39, // Lime+ 0xFFFFEB3B, // Yellow+ 0xFFFFC107, // Amber+ 0xFFFF9800, // Orange+ 0xFFFF5722, // Deep Orange+ 0xFF795548, // Brown+ 0xFF9E9E9E, // Grey+ 0xFF607D8B // Blue Grey+)++/** Stable color for [email], derived from its hash. */+fun accountColor(email: String): Long {+ val hash = email.hashCode()+ return ACCOUNT_COLORS[(hash and Int.MAX_VALUE) % ACCOUNT_COLORS.size]+}++/**+ * Content of `<script>`, `<style>`, `<head>` and `<title>` elements.+ *+ * [HtmlCompat.fromHtml] emits the *text* inside these rather than dropping+ * them, so a message whose body is a full HTML document renders its stylesheet+ * as the first hundred characters of the preview.+ */+private val HTML_NON_CONTENT = Regex("""<(script|style|head|title)\b[^>]*>.*?</\1\s*>""", setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL))+private val HTML_COMMENT = Regex("""<!--.*?-->""", RegexOption.DOT_MATCHES_ALL)+private val HTML_DECLARATION = Regex("""<[!?][^>]*>""")+/** Tags common enough that their presence means the body is HTML whatever the flag says. */+private val LOOKS_LIKE_HTML = Regex("""<(html|body|head|div|table|p|br|span|a|img|font)\b[^>]*>""", RegexOption.IGNORE_CASE)+/**+ * Includes the non-breaking space `fromHtml` produces from ` ` and the+ * Unicode line/paragraph separators, none of which `\s` matches.+ */+private val WHITESPACE_RUN = Regex("""[\s\u00A0\u2028\u2029]+""")++/**+ * Characters that draw as an empty box, or as nothing at all.+ *+ * `fromHtml` returns a `Spanned` in which every `<img>` is a U+FFFC anchored to+ * an `ImageSpan`; `toString()` discards the span and leaves the placeholder+ * behind with nothing to stand for. U+FFFD is the decoder's marker for bytes it+ * could not make sense of. The zero-width characters are the invisible padding+ * marketing mail uses to pull its preheader around, and the C0/C1 controls come+ * through from mail that was never really text.+ *+ * Deliberately excludes tab, newline and the vertical whitespace controls -+ * those separate words, so deleting them would run the words together where+ * collapsing them to a space does not.+ */+private val UNRENDERABLE = Regex("[\\uFFFC\\uFFFD\\u200B-\\u200F\\uFEFF\\u0000-\\u0008\\u000E-\\u001F\\u007F]")++/**+ * Plain-text rendering of this message's body.+ *+ * Falls back to sniffing the markup when [EmailMessage.isHtml] is false, because+ * plenty of senders set `text/plain` on a body that is anything but.+ */+fun EmailMessage.plainTextBody(): String? {+ val raw = body ?: return null+ if (!isHtml && !LOOKS_LIKE_HTML.containsMatchIn(raw)) return raw.replace(UNRENDERABLE, "")+ val stripped = raw+ .replace(HTML_COMMENT, " ")+ .replace(HTML_NON_CONTENT, " ")+ .replace(HTML_DECLARATION, " ")+ return HtmlCompat.fromHtml(stripped, HtmlCompat.FROM_HTML_MODE_LEGACY)+ .toString()+ .replace(UNRENDERABLE, "")+}++/**+ * A single-line snippet of the body for list rows, widgets and notifications.+ *+ * Collapses whitespace before truncating: the block structure of an HTML mail+ * turns into leading blank lines, so [plainTextBody] truncated as-is is often+ * entirely empty.+ */+fun EmailMessage.previewText(maxChars: Int): String =+ (plainTextBody() ?: "").replace(WHITESPACE_RUN, " ").trim().take(maxChars)++/** Display name for a "Name <addr>" sender header, falling back to the address.+ * Implemented via own RFC2047 decode + simple parse to remove Jakarta dependency. */+fun senderDisplayName(from: String): String {+ if (from.isBlank()) return ""+ // Try to extract "Name <addr>" pattern+ val trimmed = from.trim()+ // Decode RFC2047 first+ val decoded = MimeParser.decodeHeader(trimmed)+ // Look for <...> format+ val angleMatch = Regex("""^(.*)<([^>]+)>$""").find(decoded.trim())+ if (angleMatch != null) {+ val namePart = angleMatch.groupValues[1].trim().trim('"').trim()+ val addr = angleMatch.groupValues[2].trim()+ if (namePart.isNotBlank()) return namePart+ return addr+ }+ // No angle brackets — could be bare address or just name+ if (decoded.contains("@")) return decoded.substringBefore("<").trim()+ return decoded+}++/**+ * A detected way to unsubscribe from a message. Produced by [detectUnsubscribe]+ * and acted on by the message-view UI.+ */+sealed interface UnsubscribeMethod {+ /** RFC 8058 one-click: HTTPS POST to [url] with body `List-Unsubscribe=One-Click`. */+ data class OneClickPost(val url: String) : UnsubscribeMethod+ /** Open an unsubscribe web page ([url]) in the browser. */+ data class OpenWeb(val url: String) : UnsubscribeMethod+ /** Compose an unsubscribe email to [address] using the in-app composer. */+ data class SendMail(val address: String) : UnsubscribeMethod+}++/** Words that signal an unsubscribe affordance; kept small to avoid false positives. */+private val UNSUBSCRIBE_KEYWORDS = listOf("unsubscribe", "opt out", "opt-out", "optout")++/**+ * Work out how (if at all) the user can unsubscribe from this message.+ *+ * Order of preference, per the email standards:+ * 1. RFC 8058 one-click POST — when `List-Unsubscribe-Post: List-Unsubscribe=One-Click`+ * is present together with an https URL in `List-Unsubscribe`.+ * 2. An https/http URL from the `List-Unsubscribe` header (opened in the browser).+ * 3. A `mailto:` target from the `List-Unsubscribe` header (composed in-app).+ * 4. Fallback: a conservative scan of the body for an "unsubscribe" link.+ */+fun EmailMessage.detectUnsubscribe(): UnsubscribeMethod? {+ listUnsubscribe?.let { header ->+ val targets = parseListUnsubscribe(header)+ val webUrl = targets.firstOrNull { it.startsWith("http", ignoreCase = true) }+ val httpsUrl = targets.firstOrNull { it.startsWith("https://", ignoreCase = true) }+ val mailto = targets.firstOrNull { it.startsWith("mailto:", ignoreCase = true) }++ val isOneClick = listUnsubscribePost?.contains("one-click", ignoreCase = true) == true+ if (isOneClick && httpsUrl != null) return UnsubscribeMethod.OneClickPost(httpsUrl)+ if (webUrl != null) return UnsubscribeMethod.OpenWeb(webUrl)+ if (mailto != null) {+ val address = mailto.removePrefix("mailto:").removePrefix("MAILTO:").substringBefore("?").trim()+ if (address.contains("@")) return UnsubscribeMethod.SendMail(address)+ }+ }+ return findUnsubscribeLinkInBody()?.let { UnsubscribeMethod.OpenWeb(it) }+}++/** Extract the angle-bracketed targets from a List-Unsubscribe header (RFC 2369). */+private fun parseListUnsubscribe(header: String): List<String> =+ Regex("<([^>]+)>").findAll(header).map { it.groupValues[1].trim() }.toList()+ .ifEmpty { header.split(",").map { it.trim() }.filter { it.isNotEmpty() } }++/**+ * Conservatively look for an unsubscribe link in the body. Only returns a link+ * when the word "unsubscribe" (or an "opt out" variant) appears in the link's+ * href or visible text, to avoid mistaking ordinary links for unsubscribe ones.+ */+private fun EmailMessage.findUnsubscribeLinkInBody(): String? {+ val content = body ?: return null+ if (isHtml) {+ val anchor = Regex(+ "<a\\b[^>]*href=[\"']([^\"']+)[\"'][^>]*>(.*?)</a>",+ setOf(RegexOption.IGNORE_CASE, RegexOption.DOT_MATCHES_ALL),+ )+ for (match in anchor.findAll(content)) {+ val href = match.groupValues[1].trim()+ if (!href.startsWith("http", ignoreCase = true)) continue+ val haystack = (href + " " + match.groupValues[2]).lowercase()+ if (UNSUBSCRIBE_KEYWORDS.any { haystack.contains(it) }) return href+ }+ return null+ }+ // Plain text: return an http(s) URL sitting on a line that mentions unsubscribe.+ for (line in content.lineSequence()) {+ val lower = line.lowercase()+ if (UNSUBSCRIBE_KEYWORDS.none { lower.contains(it) }) continue+ Regex("https?://\\S+", RegexOption.IGNORE_CASE).find(line)?.value+ ?.trimEnd('.', ',', ')', '>', ']')+ ?.let { return it }+ }+ return null+}++/// Pending outgoing message stored locally until it is successfully sent by the+/// 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. [inlineImageJson] stores JSON array of {cid,path,mime,name}.+@Serializable+@Entity+data class OutboxEntry(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val accountEmail: String,+ val to: String,+ val cc: String? = null,+ val bcc: String? = null,+ 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(),+ val lastError: String? = null,+ val attemptCount: Int = 0,+ val lastAttemptAt: Long = 0,+ val scheduledAt: Long = 0,+ val isHtml: Boolean = false+)++@Entity+data class DraftEntry(+ @PrimaryKey(autoGenerate = true) val id: Long = 0,+ val accountEmail: String,+ val to: String = "",+ val cc: String = "",+ 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/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 36b32127c0..15ea5bb724 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailSyncWorker.kt@@ -1,238 +1,238 @@-package com.vayunmathur.email.data--import android.content.Context-import android.util.Log-import androidx.core.content.edit-import androidx.work.*-import com.vayunmathur.email.imap.ImapClient-import com.vayunmathur.email.imapServer-import com.vayunmathur.email.loginUser-import com.vayunmathur.email.resolveAuth-import com.vayunmathur.email.widget.EmailWidget-import androidx.glance.appwidget.updateAll-import java.util.concurrent.TimeUnit--/**- * Sync worker — now uses raw IMAP client only (no Jakarta dependency).- * - Non-INBOX hourly via WorkManager- * - Full one-off for folder discovery + INBOX + body backfill- * - Notification baseline per account/folder- */-class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :- CoroutineWorker(appContext, workerParams) {-- override suspend fun doWork(): Result {- val nonInboxOnly = inputData.getBoolean(KEY_NON_INBOX_ONLY, false)- val repository = EmailRepository.get(applicationContext)- val dao = repository.getDatabase().emailDao()- val accounts = dao.getAccounts()-- if (accounts.isEmpty()) {- Log.d("EmailSync", "No accounts to sync")- return Result.success()- }-- EmailSyncState.start()- var hasErrors = false- var accountsProcessed = 0-- for (account in accounts) {- try {- Log.d("EmailSync", ">>> RAW Starting sync for ${account.email} (nonInboxOnly=$nonInboxOnly)")- val auth = account.resolveAuth(applicationContext)-- val folders = ImapClient.fetchFolders(account.imapServer(), account.loginUser(), auth)- dao.insertFolders(folders)- Log.d("EmailSync", "Synced ${folders.size} folders.")-- val skipSet = if (account.provider == PROVIDER_GMAIL) ImapClient.GMAIL_VIRTUAL_FOLDERS else emptySet()- val messageFolders = if (nonInboxOnly) {- folders.filter { it.holdsMessages && it.fullName !in skipSet && it.fullName != ImapClient.INBOX }- } else {- folders.filter { it.holdsMessages && it.fullName !in skipSet }- }- val totalUnits = (accounts.size * messageFolders.size).coerceAtLeast(1)-- for ((index, folder) in messageFolders.withIndex()) {- try {- val knownUids = dao.getKnownUids(account.email, folder.fullName).toSet()- val deletedUids = dao.getDeletedUids(account.email, folder.fullName).toSet()- val (messages, attachments) = ImapClient.fetchMessages(- server = account.imapServer(),- user = account.loginUser(),- auth = auth,- folderName = folder.fullName,- limit = 50,- fetchBodies = false,- skipUids = knownUids + deletedUids,- context = applicationContext,- )- if (messages.isNotEmpty()) dao.insertMessages(messages)- if (attachments.isNotEmpty()) dao.insertAttachments(attachments)-- if (!nonInboxOnly) {- if (knownUids.isNotEmpty() && folder.fullName == ImapClient.INBOX) {- syncReadStatusRaw(applicationContext, account, folder.fullName, knownUids)- }-- if (folder.fullName == ImapClient.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)- }- }- }- }-- Log.d("EmailSync", "[${index + 1}/${messageFolders.size}] ${folder.fullName}: ${messages.size} new (skipped ${knownUids.size}).")- } catch (e: Exception) {- Log.e("EmailSync", " x Failed folder ${folder.fullName}", e)- }- val unitsDone = accountsProcessed * messageFolders.size + (index + 1)- EmailSyncState.setProgress(unitsDone.toFloat() / totalUnits)- }-- 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) = ImapClient.fetchMessageBody(- server = account.imapServer(),- user = account.loginUser(),- auth = auth,- folderName = msg.folderName,- uid = msg.id,- context = applicationContext,- )- 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}")- }- EmailSyncState.setProgress((idx + 1f) / missing.size)- }- Log.d("EmailSync", "Backfill done for ${account.email}")- }- }-- Log.d("EmailSync", "<<< Completed RAW sync for ${account.email}")- } catch (e: Exception) {- Log.e("EmailSync", "Failed to sync account ${account.email}", e)- hasErrors = true- }- accountsProcessed++- }-- if (!nonInboxOnly) EmailWidget().updateAll(applicationContext)- EmailSyncState.finish()- return if (hasErrors) Result.retry() else Result.success()- }-- 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 status via raw FETCH FLAGS */- private suspend fun syncReadStatusRaw(- context: Context,- account: com.vayunmathur.email.EmailAccount,- folderName: String,- knownUids: Set<Long>,- ) {- try {- val db = EmailRepository.get(context).getDatabase()- val dao = db.emailDao()- val uidsToCheck = knownUids.sortedDescending().take(50)- if (uidsToCheck.isEmpty()) return- val auth = account.resolveAuth(context)- val server = account.imapServer()- val user = account.loginUser()-- ImapClient.withConnection(server, user, auth) { conn ->- conn.select(folderName)- val uidSet = uidsToCheck.joinToString(",")- val results = conn.uidFetchHeaders(uidSet)- for (r in results) {- val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }- try { dao.updateReadStatus(account.email, folderName, r.uid, isRead) } catch (_: Exception) {}- }- }- } catch (_: Exception) {}- }-- private val GMAIL_VIRTUAL_FOLDERS = setOf(- "[Gmail]/All Mail",- "[Gmail]/Important",- "[Gmail]/Starred",- "[Gmail]/Chats",- )-- private const val BACKFILL_LIMIT = 200-- private fun lastSeenPrefs(context: Context) =- context.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)-- private fun lastSeenKey(accountEmail: String, folderName: String) =- "$accountEmail::$folderName"-- @Deprecated("IDLE-only push: periodic polling removed.")- fun schedulePeriodicSync(context: Context) {- WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)- WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME)- }-- fun scheduleHourlyNonInboxSync(context: Context) {- WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)- val constraints = Constraints.Builder()- .setRequiredNetworkType(NetworkType.CONNECTED)- .build()- 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(- HOURLY_NON_INBOX_WORK_NAME,- ExistingPeriodicWorkPolicy.KEEP,- req,- )- }-- 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)- }- }-}+package com.vayunmathur.email.data++import android.content.Context+import android.util.Log+import androidx.core.content.edit+import androidx.work.*+import com.vayunmathur.email.network.imap.ImapClient+import com.vayunmathur.email.imapServer+import com.vayunmathur.email.loginUser+import com.vayunmathur.email.resolveAuth+import com.vayunmathur.email.widget.EmailWidget+import androidx.glance.appwidget.updateAll+import java.util.concurrent.TimeUnit++/**+ * Sync worker — now uses raw IMAP client only (no Jakarta dependency).+ * - Non-INBOX hourly via WorkManager+ * - Full one-off for folder discovery + INBOX + body backfill+ * - Notification baseline per account/folder+ */+class EmailSyncWorker(appContext: Context, workerParams: WorkerParameters) :+ CoroutineWorker(appContext, workerParams) {++ override suspend fun doWork(): Result {+ val nonInboxOnly = inputData.getBoolean(KEY_NON_INBOX_ONLY, false)+ val repository = EmailRepository.get(applicationContext)+ val dao = repository.getDatabase().emailDao()+ val accounts = dao.getAccounts()++ if (accounts.isEmpty()) {+ Log.d("EmailSync", "No accounts to sync")+ return Result.success()+ }++ EmailSyncState.start()+ var hasErrors = false+ var accountsProcessed = 0++ for (account in accounts) {+ try {+ Log.d("EmailSync", ">>> RAW Starting sync for ${account.email} (nonInboxOnly=$nonInboxOnly)")+ val auth = account.resolveAuth(applicationContext)++ val folders = ImapClient.fetchFolders(account.imapServer(), account.loginUser(), auth)+ dao.insertFolders(folders)+ Log.d("EmailSync", "Synced ${folders.size} folders.")++ val skipSet = if (account.provider == PROVIDER_GMAIL) ImapClient.GMAIL_VIRTUAL_FOLDERS else emptySet()+ val messageFolders = if (nonInboxOnly) {+ folders.filter { it.holdsMessages && it.fullName !in skipSet && it.fullName != ImapClient.INBOX }+ } else {+ folders.filter { it.holdsMessages && it.fullName !in skipSet }+ }+ val totalUnits = (accounts.size * messageFolders.size).coerceAtLeast(1)++ for ((index, folder) in messageFolders.withIndex()) {+ try {+ val knownUids = dao.getKnownUids(account.email, folder.fullName).toSet()+ val deletedUids = dao.getDeletedUids(account.email, folder.fullName).toSet()+ val (messages, attachments) = ImapClient.fetchMessages(+ server = account.imapServer(),+ user = account.loginUser(),+ auth = auth,+ folderName = folder.fullName,+ limit = 50,+ fetchBodies = false,+ skipUids = knownUids + deletedUids,+ context = applicationContext,+ )+ if (messages.isNotEmpty()) dao.insertMessages(messages)+ if (attachments.isNotEmpty()) dao.insertAttachments(attachments)++ if (!nonInboxOnly) {+ if (knownUids.isNotEmpty() && folder.fullName == ImapClient.INBOX) {+ syncReadStatusRaw(applicationContext, account, folder.fullName, knownUids)+ }++ if (folder.fullName == ImapClient.INBOX && messages.isNotEmpty()) {+ val lastSeen = lastSeenPrefs(applicationContext)+ .getLong(lastSeenKey(account.email, folder.fullName), -1L)+ if (lastSeen >= 0L && !com.vayunmathur.email.platform.AppLifecycleTracker.isAppInForeground) {+ val notifiable = messages.filter { it.id > lastSeen }+ com.vayunmathur.email.platform.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)+ }+ }+ }+ }++ Log.d("EmailSync", "[${index + 1}/${messageFolders.size}] ${folder.fullName}: ${messages.size} new (skipped ${knownUids.size}).")+ } catch (e: Exception) {+ Log.e("EmailSync", " x Failed folder ${folder.fullName}", e)+ }+ val unitsDone = accountsProcessed * messageFolders.size + (index + 1)+ EmailSyncState.setProgress(unitsDone.toFloat() / totalUnits)+ }++ 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) = ImapClient.fetchMessageBody(+ server = account.imapServer(),+ user = account.loginUser(),+ auth = auth,+ folderName = msg.folderName,+ uid = msg.id,+ context = applicationContext,+ )+ 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}")+ }+ EmailSyncState.setProgress((idx + 1f) / missing.size)+ }+ Log.d("EmailSync", "Backfill done for ${account.email}")+ }+ }++ Log.d("EmailSync", "<<< Completed RAW sync for ${account.email}")+ } catch (e: Exception) {+ Log.e("EmailSync", "Failed to sync account ${account.email}", e)+ hasErrors = true+ }+ accountsProcessed+++ }++ if (!nonInboxOnly) EmailWidget().updateAll(applicationContext)+ EmailSyncState.finish()+ return if (hasErrors) Result.retry() else Result.success()+ }++ 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 status via raw FETCH FLAGS */+ private suspend fun syncReadStatusRaw(+ context: Context,+ account: com.vayunmathur.email.EmailAccount,+ folderName: String,+ knownUids: Set<Long>,+ ) {+ try {+ val db = EmailRepository.get(context).getDatabase()+ val dao = db.emailDao()+ val uidsToCheck = knownUids.sortedDescending().take(50)+ if (uidsToCheck.isEmpty()) return+ val auth = account.resolveAuth(context)+ val server = account.imapServer()+ val user = account.loginUser()++ ImapClient.withConnection(server, user, auth) { conn ->+ conn.select(folderName)+ val uidSet = uidsToCheck.joinToString(",")+ val results = conn.uidFetchHeaders(uidSet)+ for (r in results) {+ val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }+ try { dao.updateReadStatus(account.email, folderName, r.uid, isRead) } catch (_: Exception) {}+ }+ }+ } catch (_: Exception) {}+ }++ private val GMAIL_VIRTUAL_FOLDERS = setOf(+ "[Gmail]/All Mail",+ "[Gmail]/Important",+ "[Gmail]/Starred",+ "[Gmail]/Chats",+ )++ private const val BACKFILL_LIMIT = 200++ private fun lastSeenPrefs(context: Context) =+ context.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)++ private fun lastSeenKey(accountEmail: String, folderName: String) =+ "$accountEmail::$folderName"++ @Deprecated("IDLE-only push: periodic polling removed.")+ fun schedulePeriodicSync(context: Context) {+ WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)+ WorkManager.getInstance(context).cancelUniqueWork(HOURLY_NON_INBOX_WORK_NAME)+ }++ fun scheduleHourlyNonInboxSync(context: Context) {+ WorkManager.getInstance(context).cancelUniqueWork(SYNC_WORK_NAME)+ val constraints = Constraints.Builder()+ .setRequiredNetworkType(NetworkType.CONNECTED)+ .build()+ 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(+ HOURLY_NON_INBOX_WORK_NAME,+ ExistingPeriodicWorkPolicy.KEEP,+ req,+ )+ }++ 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/ImapIdleRetryWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/ImapIdleRetryWorker.kt b/email/src/main/java/com/vayunmathur/email/data/ImapIdleRetryWorker.ktindex a0c0f985ac..f95b75f07b 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleRetryWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleRetryWorker.kt@@ -1,62 +1,62 @@-package com.vayunmathur.email.data--import android.content.Context-import android.util.Log-import androidx.core.content.edit-import androidx.work.Constraints-import androidx.work.CoroutineWorker-import androidx.work.ExistingWorkPolicy-import androidx.work.NetworkType-import androidx.work.OneTimeWorkRequestBuilder-import androidx.work.OutOfQuotaPolicy-import androidx.work.WorkManager-import androidx.work.WorkerParameters-import com.vayunmathur.email.util.BootReceiver--/**- * Retry worker that attempts to start [ImapIdleService] when network is available.- * Uses expedited work with OUT_OF_QUOTA so it can try even if quota exhausted.- * Scheduled from [BootReceiver] on S+ boot as fallback, and from [com.vayunmathur.email.util.AppLifecycleTracker]- * foreground path if direct start fails.- */-class ImapIdleRetryWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {-- override suspend fun doWork(): Result {- return try {- val started = ImapIdleService.start(applicationContext)- if (started) {- Log.d(TAG, "ImapIdleRetryWorker: IDLE started")- // Clear pending flag on success- applicationContext.getSharedPreferences(BootReceiver.PREFS, Context.MODE_PRIVATE)- .edit { remove(BootReceiver.KEY_PENDING) }- Result.success()- } else {- Log.w(TAG, "ImapIdleRetryWorker: start returned false, retrying")- Result.retry()- }- } catch (t: Throwable) {- Log.w(TAG, "ImapIdleRetryWorker failed: ${t.message}", t)- Result.retry()- }- }-- companion object {- private const val TAG = "ImapIdleRetry"- private const val WORK_NAME = "ImapIdleRetryWorker"-- fun schedule(context: Context) {- val constraints = Constraints.Builder()- .setRequiredNetworkType(NetworkType.CONNECTED)- .build()- val req = OneTimeWorkRequestBuilder<ImapIdleRetryWorker>()- .setConstraints(constraints)- .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)- .build()- WorkManager.getInstance(context).enqueueUniqueWork(- WORK_NAME,- ExistingWorkPolicy.REPLACE,- req,- )- }- }-}+package com.vayunmathur.email.data++import android.content.Context+import android.util.Log+import androidx.core.content.edit+import androidx.work.Constraints+import androidx.work.CoroutineWorker+import androidx.work.ExistingWorkPolicy+import androidx.work.NetworkType+import androidx.work.OneTimeWorkRequestBuilder+import androidx.work.OutOfQuotaPolicy+import androidx.work.WorkManager+import androidx.work.WorkerParameters+import com.vayunmathur.email.platform.BootReceiver++/**+ * Retry worker that attempts to start [ImapIdleService] when network is available.+ * Uses expedited work with OUT_OF_QUOTA so it can try even if quota exhausted.+ * Scheduled from [BootReceiver] on S+ boot as fallback, and from [com.vayunmathur.email.platform.AppLifecycleTracker]+ * foreground path if direct start fails.+ */+class ImapIdleRetryWorker(appContext: Context, params: WorkerParameters) : CoroutineWorker(appContext, params) {++ override suspend fun doWork(): Result {+ return try {+ val started = ImapIdleService.start(applicationContext)+ if (started) {+ Log.d(TAG, "ImapIdleRetryWorker: IDLE started")+ // Clear pending flag on success+ applicationContext.getSharedPreferences(BootReceiver.PREFS, Context.MODE_PRIVATE)+ .edit { remove(BootReceiver.KEY_PENDING) }+ Result.success()+ } else {+ Log.w(TAG, "ImapIdleRetryWorker: start returned false, retrying")+ Result.retry()+ }+ } catch (t: Throwable) {+ Log.w(TAG, "ImapIdleRetryWorker failed: ${t.message}", t)+ Result.retry()+ }+ }++ companion object {+ private const val TAG = "ImapIdleRetry"+ private const val WORK_NAME = "ImapIdleRetryWorker"++ fun schedule(context: Context) {+ val constraints = Constraints.Builder()+ .setRequiredNetworkType(NetworkType.CONNECTED)+ .build()+ val req = OneTimeWorkRequestBuilder<ImapIdleRetryWorker>()+ .setConstraints(constraints)+ .setExpedited(OutOfQuotaPolicy.RUN_AS_NON_EXPEDITED_WORK_REQUEST)+ .build()+ WorkManager.getInstance(context).enqueueUniqueWork(+ WORK_NAME,+ ExistingWorkPolicy.REPLACE,+ req,+ )+ }+ }+}
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 fce2341684..a5e34de212 100644--- a/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt+++ b/email/src/main/java/com/vayunmathur/email/data/ImapIdleService.kt@@ -1,305 +1,305 @@-@file:OptIn(kotlin.concurrent.atomics.ExperimentalAtomicApi::class)--package com.vayunmathur.email.data--import kotlin.concurrent.atomics.*-import android.app.Notification-import android.app.NotificationChannel-import android.app.NotificationManager-import android.app.Service-import android.content.Context-import android.content.Intent-import android.content.pm.ServiceInfo-import android.os.Build-import android.os.IBinder-import android.util.Log-import androidx.core.app.NotificationCompat-import androidx.core.content.edit-import com.vayunmathur.email.EmailAccount-import com.vayunmathur.email.EmailFolder-import com.vayunmathur.email.EmailManager-import com.vayunmathur.email.R-import com.vayunmathur.email.imap.ImapAuthException-import com.vayunmathur.email.imap.ImapClient-import com.vayunmathur.email.imap.RawImapConnection-import com.vayunmathur.email.imap.TrustAll-import com.vayunmathur.email.resolveAuth-import com.vayunmathur.email.imapServer-import com.vayunmathur.email.loginUser-import com.vayunmathur.email.util.AppLifecycleTracker-import com.vayunmathur.email.util.EmailNotifications-import com.vayunmathur.email.widget.EmailWidget-import androidx.glance.appwidget.updateAll-import kotlinx.coroutines.CoroutineScope-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.Job-import kotlinx.coroutines.SupervisorJob-import kotlinx.coroutines.cancel-import kotlinx.coroutines.delay-import kotlinx.coroutines.isActive-import kotlinx.coroutines.launch-import kotlinx.coroutines.withContext--/**- * Foreground service — raw IMAP IDLE (no Jakarta), app-password + Outlook OAuth XOAUTH2.- * Fix for BOOT_COMPLETED crash: start() returns Boolean, onStartCommand catches FGS exception.- */-class ImapIdleService : Service() {-- private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)- private val accountJobs = mutableMapOf<String, Job>()-- override fun onBind(intent: Intent?): IBinder? = null-- override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {- try {- startForeground(NOTIFICATION_ID, buildOngoingNotification(), foregroundServiceType())- } catch (e: Exception) {- Log.w(TAG, "startForeground failed: ${e.message}", e)- stopSelf()- return START_NOT_STICKY- }- scope.launch { startIdleLoops() }- return START_STICKY- }-- override fun onDestroy() { scope.cancel(); super.onDestroy() }-- private suspend fun startIdleLoops() {- val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()- val accounts = dao.getAccounts()- if (accounts.isEmpty()) { stopSelf(); return }- try { EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext) } catch (_: Throwable) {}- val current = accounts.map { it.email }.toSet()- accountJobs.keys.filter { it !in current }.forEach { accountJobs[it]?.cancel(); accountJobs.remove(it) }- for (account in accounts) {- accountJobs[account.email]?.cancel()- accountJobs[account.email] = scope.launch { idleLoop(account) }- }- }-- private suspend fun idleLoop(account: EmailAccount) {- var backoffMs = 2_000L- val maxBackoffMs = 60_000L- while (scope.coroutineContext.isActive) {- try {- runIdleSessionRaw(account)- backoffMs = 2_000L- delay(1_000L)- } catch (e: ImapAuthException) {- Log.w(TAG, "IDLE auth failed for ${account.email}; stop")- return- } catch (e: Exception) {- val msg = e.message?.lowercase() ?: ""- if (msg.contains("auth") && msg.contains("fail")) { Log.w(TAG, "IDLE auth fail ${account.email}"); return }- Log.w(TAG, "IDLE err ${account.email}: ${e.javaClass.simpleName}: ${e.message}")- delay(backoffMs)- backoffMs = (backoffMs * 2).coerceAtMost(maxBackoffMs)- }- }- }-- private suspend fun runIdleSessionRaw(account: EmailAccount) = withContext(Dispatchers.IO) {- val server = account.imapServer()- val user = account.loginUser()- val auth = account.resolveAuth(applicationContext)- val useTrustAll = !TrustAll.isKnownHost(server.host)- val rawConn = RawImapConnection(server, trustAll = useTrustAll)- try {- rawConn.connect()- var caps = rawConn.capability()- if (!server.useSsl && caps.has("STARTTLS")) {- try { rawConn.startTls(); caps = rawConn.capability() } catch (e: Exception) { Log.w(TAG, "STARTTLS fail ${account.email}: ${e.message}") }- }-- when (auth) {- is EmailManager.AuthType.OAuth -> rawConn.authenticateXoauth2(user, auth.token)- is EmailManager.AuthType.Password -> {- try { rawConn.login(user, auth.value) } catch (e: Exception) {- if (caps.has("AUTH=PLAIN")) rawConn.authenticatePlain(user, auth.value) else throw e- }- }- }-- val supportsIdle = caps.has("IDLE")- Log.d(TAG, "Raw IDLE supports $supportsIdle for ${account.email}")-- if (!supportsIdle) {- while (scope.coroutineContext.isActive) {- delay(FALLBACK_NO_IDLE_POLL_MS)- try {- val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()- val known = dao.getKnownUids(account.email, "INBOX").toSet()- val deleted = dao.getDeletedUids(account.email, "INBOX").toSet()- val (msgs, atts) = ImapClient.fetchMessagesInConnection(rawConn, account.email, "INBOX", 50, 0, false, known + deleted, applicationContext)- if (msgs.isNotEmpty()) { dao.insertMessages(msgs); if (atts.isNotEmpty()) dao.insertAttachments(atts); postNewMailNotification(account.email, msgs) }- syncReadStatusPullRaw(applicationContext, account, known)- } catch (t: Throwable) { Log.w(TAG, "Raw poll fail: ${t.message}") }- }- return@withContext- }-- val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()- while (scope.coroutineContext.isActive) {- val sel = rawConn.select("INBOX")- Log.d(TAG, "SELECT INBOX ${account.email} exists=${sel.exists}")- try {- val folders = rawConn.list("", "*").map { entry ->- val fullName = entry.mailbox- val delim = entry.delimiter ?: "/"- val nm = if (fullName.contains(delim)) fullName.substringAfterLast(delim) else fullName.substringAfterLast('/')- val parent = fullName.lastIndexOf(delim).let { if (it > 0) fullName.substring(0, it) else null }- val holds = !entry.flags.any { f -> f.equals("\\Noselect", ignoreCase = true) }- EmailFolder(account.email, fullName, nm.ifBlank { fullName }, parent, holds, delim)- }- dao.insertFolders(folders)- } catch (t: Throwable) { Log.w(TAG, "folder discovery fail: ${t.message}") }-- var sawNewMail = false- var sawExpunge = false- var sawFlags = false- val expungedSeqs = mutableListOf<Int>()- var needReopen = false- var isProactiveRefresh = false-- while (scope.coroutineContext.isActive && !needReopen) {- val idleTag = rawConn.sendIdle()- Log.d(TAG, "IDLE start ${account.email} tag=$idleTag")-- val watchdog = scope.launch {- delay(IDLE_REFRESH_MS)- if (isActive) { Log.d(TAG, "proactive refresh ${account.email}"); isProactiveRefresh = true; try { rawConn.sendIdleDone() } catch (_: Throwable) {} }- }-- var idleEnded = false- var idleLoopActive = true- while (idleLoopActive && scope.coroutineContext.isActive) {- val line = withContext(Dispatchers.IO) { try { rawConn.readIdleLine() } catch (_: Exception) { null } } ?: break- Log.d(TAG, "IDLE line ${account.email}: $line")- if (line.startsWith(idleTag)) { idleEnded = true; idleLoopActive = false; break }- when {- Regex("""^\* (\d+) EXISTS""").containsMatchIn(line) -> sawNewMail = true- Regex("""^\* (\d+) EXPUNGE""").containsMatchIn(line) -> {- val seq = Regex("""^\* (\d+) EXPUNGE""").find(line)?.groupValues?.get(1)?.toIntOrNull() ?: -1- if (seq != -1) expungedSeqs.add(seq); sawExpunge = true- }- line.contains("FETCH") && line.contains("FLAGS") -> sawFlags = true- }- if (sawNewMail || sawExpunge || sawFlags) { try { rawConn.sendIdleDone() } catch (_: Throwable) {} }- }-- if (!idleEnded) { try { rawConn.sendIdleDone() } catch (_: Throwable) {}; try { rawConn.readIdleResponseForTag(idleTag) } catch (_: Throwable) {} }-- watchdog.cancel()-- if (isProactiveRefresh) { Log.d(TAG, "24-min refresh ${account.email}"); isProactiveRefresh = false; needReopen = true; delay(200L); break }-- if (sawNewMail && !needReopen) {- sawNewMail = false- try {- val known = dao.getKnownUids(account.email, "INBOX").toSet()- val deleted = dao.getDeletedUids(account.email, "INBOX").toSet()- val (msgs, atts) = ImapClient.fetchMessagesInConnection(rawConn, account.email, "INBOX", 50, 0, false, known + deleted, applicationContext)- if (msgs.isNotEmpty()) { dao.insertMessages(msgs); if (atts.isNotEmpty()) dao.insertAttachments(atts); postNewMailNotification(account.email, msgs) }- } catch (t: Throwable) { Log.w(TAG, "quick fetch fail: ${t.message}") }- }-- if (sawExpunge && expungedSeqs.isNotEmpty() && !needReopen) {- sawExpunge = false; expungedSeqs.clear(); try { EmailWidget().updateAll(applicationContext) } catch (_: Throwable) {}- }-- if (sawFlags && !needReopen) {- sawFlags = false- try { syncReadStatusPullRaw(applicationContext, account, dao.getKnownUids(account.email, "INBOX").toSet()) } catch (t: Throwable) { Log.w(TAG, "flag sync fail: ${t.message}") }- }-- if (needReopen) break- if (scope.coroutineContext.isActive) delay(500L)- }- if (!scope.coroutineContext.isActive) break- if (needReopen) continue- delay(500L)- }- } catch (e: Exception) { try { rawConn.close() } catch (_: Throwable) {}; throw e }- }-- private suspend fun postNewMailNotification(accountEmail: String, messages: List<com.vayunmathur.email.EmailMessage>) {- if (messages.isEmpty()) return- val ctx = applicationContext ?: return- val prefs = ctx.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)- val lastSeen = prefs.getLong("$accountEmail::INBOX", -1L)- val notifiable = if (lastSeen == -1L) messages else messages.filter { it.id > lastSeen }- if (notifiable.isNotEmpty() && !AppLifecycleTracker.isAppInForeground) {- EmailNotifications.postForNewMessages(ctx, accountEmail, notifiable)- }- val maxUid = messages.maxOfOrNull { it.id } ?: lastSeen- if (maxUid > lastSeen) prefs.edit { putLong("$accountEmail::INBOX", maxUid) }- try { EmailWidget().updateAll(ctx) } catch (t: Throwable) { Log.w(TAG, "widget fail ${t.message}") }- }-- private suspend fun syncReadStatusPullRaw(context: Context, account: EmailAccount, knownUids: Set<Long>) {- if (knownUids.isEmpty()) return- try {- val dao = EmailRepository.get(context).getDatabase().emailDao()- val uidsToCheck = knownUids.sortedDescending().take(50)- val auth = account.resolveAuth(context)- ImapClient.withConnection(account.imapServer(), account.loginUser(), auth) { conn ->- conn.select("INBOX")- val results = conn.uidFetchHeaders(uidsToCheck.joinToString(","))- for (r in results) {- val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }- try { dao.updateReadStatus(account.email, "INBOX", r.uid, isRead) } catch (_: Exception) {}- }- }- } catch (_: Exception) {}- }-- private fun buildOngoingNotification(): Notification {- ensureChannel(applicationContext)- return androidx.core.app.NotificationCompat.Builder(applicationContext, CHANNEL_ID)- .setSmallIcon(R.drawable.ic_notification_mail)- .setContentTitle(getString(R.string.app_name))- .setContentText(getString(R.string.listening_for_new_mail))- .setPriority(androidx.core.app.NotificationCompat.PRIORITY_LOW)- .setOngoing(true)- .setShowWhen(false)- .build()- }-- private fun foregroundServiceType(): Int {- return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {- ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC- } else 0- }-- companion object {- private const val TAG = "ImapIdle"- private const val CHANNEL_ID = "imap_idle"- private const val NOTIFICATION_ID = 9001- const val IDLE_REFRESH_MS = 24L * 60 * 1000- const val FALLBACK_NO_IDLE_POLL_MS = 5L * 60 * 1000-- private fun ensureChannel(context: Context) {- val nm = context.getSystemService(NotificationManager::class.java) ?: return- if (nm.getNotificationChannel(CHANNEL_ID) != null) return- nm.createNotificationChannel(- NotificationChannel(CHANNEL_ID, context.getString(R.string.email_sync_channel_name), NotificationManager.IMPORTANCE_LOW).apply {- description = context.getString(R.string.email_sync_channel_desc)- setShowBadge(false)- }- )- }-- fun start(context: Context): Boolean {- return try {- val intent = Intent(context, ImapIdleService::class.java)- context.startForegroundService(intent)- true- } catch (e: Exception) {- Log.w(TAG, "start failed: ${e.message}", e); false- }- }-- fun stop(context: Context) { context.stopService(Intent(context, ImapIdleService::class.java)) }- }-}+@file:OptIn(kotlin.concurrent.atomics.ExperimentalAtomicApi::class)++package com.vayunmathur.email.data++import kotlin.concurrent.atomics.*+import android.app.Notification+import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.Service+import android.content.Context+import android.content.Intent+import android.content.pm.ServiceInfo+import android.os.Build+import android.os.IBinder+import android.util.Log+import androidx.core.app.NotificationCompat+import androidx.core.content.edit+import com.vayunmathur.email.EmailAccount+import com.vayunmathur.email.EmailFolder+import com.vayunmathur.email.EmailManager+import com.vayunmathur.email.R+import com.vayunmathur.email.network.imap.ImapAuthException+import com.vayunmathur.email.network.imap.ImapClient+import com.vayunmathur.email.network.imap.RawImapConnection+import com.vayunmathur.email.network.imap.TrustAll+import com.vayunmathur.email.resolveAuth+import com.vayunmathur.email.imapServer+import com.vayunmathur.email.loginUser+import com.vayunmathur.email.platform.AppLifecycleTracker+import com.vayunmathur.email.platform.EmailNotifications+import com.vayunmathur.email.widget.EmailWidget+import androidx.glance.appwidget.updateAll+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.Job+import kotlinx.coroutines.SupervisorJob+import kotlinx.coroutines.cancel+import kotlinx.coroutines.delay+import kotlinx.coroutines.isActive+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext++/**+ * Foreground service — raw IMAP IDLE (no Jakarta), app-password + Outlook OAuth XOAUTH2.+ * Fix for BOOT_COMPLETED crash: start() returns Boolean, onStartCommand catches FGS exception.+ */+class ImapIdleService : Service() {++ private val scope = CoroutineScope(SupervisorJob() + Dispatchers.IO)+ private val accountJobs = mutableMapOf<String, Job>()++ override fun onBind(intent: Intent?): IBinder? = null++ override fun onStartCommand(intent: Intent?, flags: Int, startId: Int): Int {+ try {+ startForeground(NOTIFICATION_ID, buildOngoingNotification(), foregroundServiceType())+ } catch (e: Exception) {+ Log.w(TAG, "startForeground failed: ${e.message}", e)+ stopSelf()+ return START_NOT_STICKY+ }+ scope.launch { startIdleLoops() }+ return START_STICKY+ }++ override fun onDestroy() { scope.cancel(); super.onDestroy() }++ private suspend fun startIdleLoops() {+ val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()+ val accounts = dao.getAccounts()+ if (accounts.isEmpty()) { stopSelf(); return }+ try { EmailSyncWorker.scheduleHourlyNonInboxSync(applicationContext) } catch (_: Throwable) {}+ val current = accounts.map { it.email }.toSet()+ accountJobs.keys.filter { it !in current }.forEach { accountJobs[it]?.cancel(); accountJobs.remove(it) }+ for (account in accounts) {+ accountJobs[account.email]?.cancel()+ accountJobs[account.email] = scope.launch { idleLoop(account) }+ }+ }++ private suspend fun idleLoop(account: EmailAccount) {+ var backoffMs = 2_000L+ val maxBackoffMs = 60_000L+ while (scope.coroutineContext.isActive) {+ try {+ runIdleSessionRaw(account)+ backoffMs = 2_000L+ delay(1_000L)+ } catch (e: ImapAuthException) {+ Log.w(TAG, "IDLE auth failed for ${account.email}; stop")+ return+ } catch (e: Exception) {+ val msg = e.message?.lowercase() ?: ""+ if (msg.contains("auth") && msg.contains("fail")) { Log.w(TAG, "IDLE auth fail ${account.email}"); return }+ Log.w(TAG, "IDLE err ${account.email}: ${e.javaClass.simpleName}: ${e.message}")+ delay(backoffMs)+ backoffMs = (backoffMs * 2).coerceAtMost(maxBackoffMs)+ }+ }+ }++ private suspend fun runIdleSessionRaw(account: EmailAccount) = withContext(Dispatchers.IO) {+ val server = account.imapServer()+ val user = account.loginUser()+ val auth = account.resolveAuth(applicationContext)+ val useTrustAll = !TrustAll.isKnownHost(server.host)+ val rawConn = RawImapConnection(server, trustAll = useTrustAll)+ try {+ rawConn.connect()+ var caps = rawConn.capability()+ if (!server.useSsl && caps.has("STARTTLS")) {+ try { rawConn.startTls(); caps = rawConn.capability() } catch (e: Exception) { Log.w(TAG, "STARTTLS fail ${account.email}: ${e.message}") }+ }++ when (auth) {+ is EmailManager.AuthType.OAuth -> rawConn.authenticateXoauth2(user, auth.token)+ is EmailManager.AuthType.Password -> {+ try { rawConn.login(user, auth.value) } catch (e: Exception) {+ if (caps.has("AUTH=PLAIN")) rawConn.authenticatePlain(user, auth.value) else throw e+ }+ }+ }++ val supportsIdle = caps.has("IDLE")+ Log.d(TAG, "Raw IDLE supports $supportsIdle for ${account.email}")++ if (!supportsIdle) {+ while (scope.coroutineContext.isActive) {+ delay(FALLBACK_NO_IDLE_POLL_MS)+ try {+ val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()+ val known = dao.getKnownUids(account.email, "INBOX").toSet()+ val deleted = dao.getDeletedUids(account.email, "INBOX").toSet()+ val (msgs, atts) = ImapClient.fetchMessagesInConnection(rawConn, account.email, "INBOX", 50, 0, false, known + deleted, applicationContext)+ if (msgs.isNotEmpty()) { dao.insertMessages(msgs); if (atts.isNotEmpty()) dao.insertAttachments(atts); postNewMailNotification(account.email, msgs) }+ syncReadStatusPullRaw(applicationContext, account, known)+ } catch (t: Throwable) { Log.w(TAG, "Raw poll fail: ${t.message}") }+ }+ return@withContext+ }++ val dao = EmailRepository.get(applicationContext).getDatabase().emailDao()+ while (scope.coroutineContext.isActive) {+ val sel = rawConn.select("INBOX")+ Log.d(TAG, "SELECT INBOX ${account.email} exists=${sel.exists}")+ try {+ val folders = rawConn.list("", "*").map { entry ->+ val fullName = entry.mailbox+ val delim = entry.delimiter ?: "/"+ val nm = if (fullName.contains(delim)) fullName.substringAfterLast(delim) else fullName.substringAfterLast('/')+ val parent = fullName.lastIndexOf(delim).let { if (it > 0) fullName.substring(0, it) else null }+ val holds = !entry.flags.any { f -> f.equals("\\Noselect", ignoreCase = true) }+ EmailFolder(account.email, fullName, nm.ifBlank { fullName }, parent, holds, delim)+ }+ dao.insertFolders(folders)+ } catch (t: Throwable) { Log.w(TAG, "folder discovery fail: ${t.message}") }++ var sawNewMail = false+ var sawExpunge = false+ var sawFlags = false+ val expungedSeqs = mutableListOf<Int>()+ var needReopen = false+ var isProactiveRefresh = false++ while (scope.coroutineContext.isActive && !needReopen) {+ val idleTag = rawConn.sendIdle()+ Log.d(TAG, "IDLE start ${account.email} tag=$idleTag")++ val watchdog = scope.launch {+ delay(IDLE_REFRESH_MS)+ if (isActive) { Log.d(TAG, "proactive refresh ${account.email}"); isProactiveRefresh = true; try { rawConn.sendIdleDone() } catch (_: Throwable) {} }+ }++ var idleEnded = false+ var idleLoopActive = true+ while (idleLoopActive && scope.coroutineContext.isActive) {+ val line = withContext(Dispatchers.IO) { try { rawConn.readIdleLine() } catch (_: Exception) { null } } ?: break+ Log.d(TAG, "IDLE line ${account.email}: $line")+ if (line.startsWith(idleTag)) { idleEnded = true; idleLoopActive = false; break }+ when {+ Regex("""^\* (\d+) EXISTS""").containsMatchIn(line) -> sawNewMail = true+ Regex("""^\* (\d+) EXPUNGE""").containsMatchIn(line) -> {+ val seq = Regex("""^\* (\d+) EXPUNGE""").find(line)?.groupValues?.get(1)?.toIntOrNull() ?: -1+ if (seq != -1) expungedSeqs.add(seq); sawExpunge = true+ }+ line.contains("FETCH") && line.contains("FLAGS") -> sawFlags = true+ }+ if (sawNewMail || sawExpunge || sawFlags) { try { rawConn.sendIdleDone() } catch (_: Throwable) {} }+ }++ if (!idleEnded) { try { rawConn.sendIdleDone() } catch (_: Throwable) {}; try { rawConn.readIdleResponseForTag(idleTag) } catch (_: Throwable) {} }++ watchdog.cancel()++ if (isProactiveRefresh) { Log.d(TAG, "24-min refresh ${account.email}"); isProactiveRefresh = false; needReopen = true; delay(200L); break }++ if (sawNewMail && !needReopen) {+ sawNewMail = false+ try {+ val known = dao.getKnownUids(account.email, "INBOX").toSet()+ val deleted = dao.getDeletedUids(account.email, "INBOX").toSet()+ val (msgs, atts) = ImapClient.fetchMessagesInConnection(rawConn, account.email, "INBOX", 50, 0, false, known + deleted, applicationContext)+ if (msgs.isNotEmpty()) { dao.insertMessages(msgs); if (atts.isNotEmpty()) dao.insertAttachments(atts); postNewMailNotification(account.email, msgs) }+ } catch (t: Throwable) { Log.w(TAG, "quick fetch fail: ${t.message}") }+ }++ if (sawExpunge && expungedSeqs.isNotEmpty() && !needReopen) {+ sawExpunge = false; expungedSeqs.clear(); try { EmailWidget().updateAll(applicationContext) } catch (_: Throwable) {}+ }++ if (sawFlags && !needReopen) {+ sawFlags = false+ try { syncReadStatusPullRaw(applicationContext, account, dao.getKnownUids(account.email, "INBOX").toSet()) } catch (t: Throwable) { Log.w(TAG, "flag sync fail: ${t.message}") }+ }++ if (needReopen) break+ if (scope.coroutineContext.isActive) delay(500L)+ }+ if (!scope.coroutineContext.isActive) break+ if (needReopen) continue+ delay(500L)+ }+ } catch (e: Exception) { try { rawConn.close() } catch (_: Throwable) {}; throw e }+ }++ private suspend fun postNewMailNotification(accountEmail: String, messages: List<com.vayunmathur.email.EmailMessage>) {+ if (messages.isEmpty()) return+ val ctx = applicationContext ?: return+ val prefs = ctx.getSharedPreferences("email_notif_last_seen", Context.MODE_PRIVATE)+ val lastSeen = prefs.getLong("$accountEmail::INBOX", -1L)+ val notifiable = if (lastSeen == -1L) messages else messages.filter { it.id > lastSeen }+ if (notifiable.isNotEmpty() && !AppLifecycleTracker.isAppInForeground) {+ EmailNotifications.postForNewMessages(ctx, accountEmail, notifiable)+ }+ val maxUid = messages.maxOfOrNull { it.id } ?: lastSeen+ if (maxUid > lastSeen) prefs.edit { putLong("$accountEmail::INBOX", maxUid) }+ try { EmailWidget().updateAll(ctx) } catch (t: Throwable) { Log.w(TAG, "widget fail ${t.message}") }+ }++ private suspend fun syncReadStatusPullRaw(context: Context, account: EmailAccount, knownUids: Set<Long>) {+ if (knownUids.isEmpty()) return+ try {+ val dao = EmailRepository.get(context).getDatabase().emailDao()+ val uidsToCheck = knownUids.sortedDescending().take(50)+ val auth = account.resolveAuth(context)+ ImapClient.withConnection(account.imapServer(), account.loginUser(), auth) { conn ->+ conn.select("INBOX")+ val results = conn.uidFetchHeaders(uidsToCheck.joinToString(","))+ for (r in results) {+ val isRead = r.flags.any { it.equals("\\Seen", ignoreCase = true) }+ try { dao.updateReadStatus(account.email, "INBOX", r.uid, isRead) } catch (_: Exception) {}+ }+ }+ } catch (_: Exception) {}+ }++ private fun buildOngoingNotification(): Notification {+ ensureChannel(applicationContext)+ return androidx.core.app.NotificationCompat.Builder(applicationContext, CHANNEL_ID)+ .setSmallIcon(R.drawable.ic_notification_mail)+ .setContentTitle(getString(R.string.app_name))+ .setContentText(getString(R.string.listening_for_new_mail))+ .setPriority(androidx.core.app.NotificationCompat.PRIORITY_LOW)+ .setOngoing(true)+ .setShowWhen(false)+ .build()+ }++ private fun foregroundServiceType(): Int {+ return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.UPSIDE_DOWN_CAKE) {+ ServiceInfo.FOREGROUND_SERVICE_TYPE_DATA_SYNC+ } else 0+ }++ companion object {+ private const val TAG = "ImapIdle"+ private const val CHANNEL_ID = "imap_idle"+ private const val NOTIFICATION_ID = 9001+ const val IDLE_REFRESH_MS = 24L * 60 * 1000+ const val FALLBACK_NO_IDLE_POLL_MS = 5L * 60 * 1000++ private fun ensureChannel(context: Context) {+ val nm = context.getSystemService(NotificationManager::class.java) ?: return+ if (nm.getNotificationChannel(CHANNEL_ID) != null) return+ nm.createNotificationChannel(+ NotificationChannel(CHANNEL_ID, context.getString(R.string.email_sync_channel_name), NotificationManager.IMPORTANCE_LOW).apply {+ description = context.getString(R.string.email_sync_channel_desc)+ setShowBadge(false)+ }+ )+ }++ fun start(context: Context): Boolean {+ return try {+ val intent = Intent(context, ImapIdleService::class.java)+ context.startForegroundService(intent)+ true+ } catch (e: Exception) {+ Log.w(TAG, "start failed: ${e.message}", e); false+ }+ }++ fun stop(context: Context) { context.stopService(Intent(context, ImapIdleService::class.java)) }+ }+}
email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt b/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.ktindex bc8fc7b017..0d363f173a 100644--- a/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt@@ -11,12 +11,13 @@ import androidx.work.NetworkType import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters-import com.vayunmathur.email.EmailManager-import com.vayunmathur.email.OutboxEntry-import com.vayunmathur.email.composer.InlineAttachment-import com.vayunmathur.email.loginUser-import com.vayunmathur.email.resolveAuth-import com.vayunmathur.email.smtpServer+import com.vayunmathur.email.data.OutboxEntry+import com.vayunmathur.email.platform.EmailManager+import com.vayunmathur.email.platform.imapServer+import com.vayunmathur.email.platform.loginUser+import com.vayunmathur.email.platform.resolveAuth+import com.vayunmathur.email.platform.smtpServer+import com.vayunmathur.email.ui.composer.InlineAttachment import kotlinx.serialization.Serializable import kotlinx.serialization.json.Json import java.io.File@@ -101,8 +102,8 @@ class OutboxSendWorker( private suspend fun trySend( manager: EmailManager,- account: com.vayunmathur.email.EmailAccount,- entry: com.vayunmathur.email.OutboxEntry,+ account: EmailAccount,+ entry: OutboxEntry, uris: List<android.net.Uri>, inline: List<InlineAttachment>, ): SendResult = runCatching {
email/src/main/java/com/vayunmathur/email/network/imap/ImapAuthException.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/ImapAuthException.kt b/email/src/main/java/com/vayunmathur/email/network/imap/ImapAuthException.ktindex aebc15a9be..b708a487b9 100644--- a/email/src/main/java/com/vayunmathur/email/network/imap/ImapAuthException.kt+++ b/email/src/main/java/com/vayunmathur/email/network/imap/ImapAuthException.kt@@ -1,9 +1,9 @@-package com.vayunmathur.email.imap--import java.io.IOException--/**- * Thrown when IMAP or SMTP authentication fails (LOGIN, PLAIN, LOGIN, XOAUTH2).- * Replaces `jakarta.mail.AuthenticationFailedException` after Jakarta removal.- */-class ImapAuthException(message: String, cause: Throwable? = null) : IOException(message, cause)+package com.vayunmathur.email.network.imap++import java.io.IOException++/**+ * Thrown when IMAP or SMTP authentication fails (LOGIN, PLAIN, LOGIN, XOAUTH2).+ * Replaces `jakarta.mail.AuthenticationFailedException` after Jakarta removal.+ */+class ImapAuthException(message: String, cause: Throwable? = null) : IOException(message, cause)
email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt b/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.ktindex 45fa1eed2a..007c2eca4f 100644--- a/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt+++ b/email/src/main/java/com/vayunmathur/email/network/imap/ImapClient.kt@@ -1,329 +1,329 @@-package com.vayunmathur.email.imap--import android.content.ContentValues-import android.content.Context-import android.os.Environment-import android.provider.MediaStore-import android.util.Log-import com.vayunmathur.email.Attachment-import com.vayunmathur.email.EmailFolder-import com.vayunmathur.email.EmailManager-import com.vayunmathur.email.EmailMessage-import com.vayunmathur.email.ServerConfig-import java.io.File-import java.io.OutputStream-import kotlinx.coroutines.Dispatchers-import kotlinx.coroutines.withContext--/**- * High-level IMAP client using raw sockets — app-password primary, Outlook OAuth via XOAUTH2.- */-object ImapClient {-- private const val TAG = "ImapClient"-- /**- * Canonical inbox mailbox name. RFC 3501 §5.1 defines INBOX case-insensitively,- * so servers are free to report it however they like — Gmail/Yahoo/iCloud return- * `INBOX`, but Office 365 / Exchange returns `Inbox`. Every inbox query in the app- * (per-account *and* the unified inbox) matches on this exact literal, and SQLite- * TEXT comparison is case-sensitive, so all persisted folder names must be folded- * to this constant via [canonicalizeMailbox] before they hit the DB.- */- const val INBOX = "INBOX"-- /**- * Folds a server-reported mailbox path to its canonical form, so `Inbox` and- * `Inbox/Receipts` (Office 365) are stored the same way as `INBOX` and- * `INBOX/Receipts` (Gmail). Non-inbox mailboxes are returned untouched — only the- * inbox has spec-mandated case-insensitivity.- *- * @param delimiter the server's hierarchy delimiter; when unknown, the two common- * ones (`/` and `.`) are both accepted.- */- fun canonicalizeMailbox(mailbox: String, delimiter: String? = null): String {- if (mailbox.equals(INBOX, ignoreCase = true)) return INBOX- if (mailbox.length <= INBOX.length) return mailbox- if (!mailbox.regionMatches(0, INBOX, 0, INBOX.length, ignoreCase = true)) return mailbox- val delims = if (delimiter.isNullOrEmpty()) listOf("/", ".") else listOf(delimiter)- return if (delims.any { mailbox.startsWith(it, INBOX.length) }) {- INBOX + mailbox.substring(INBOX.length)- } else {- mailbox- }- }-- val GMAIL_VIRTUAL_FOLDERS = setOf(- "[Gmail]/All Mail",- "[Gmail]/Important",- "[Gmail]/Starred",- "[Gmail]/Chats",- )-- suspend fun <T> withConnection(- server: ServerConfig,- user: String,- auth: EmailManager.AuthType,- trustAll: Boolean = false,- block: suspend (RawImapConnection) -> T,- ): T = withContext(Dispatchers.IO) {- val useTrustAll = trustAll || !TrustAll.isKnownHost(server.host)- val conn = RawImapConnection(server, trustAll = useTrustAll)- try {- conn.connect()- var caps = conn.capability()-- if (!server.useSsl && caps.has("STARTTLS")) {- try {- conn.startTls()- caps = conn.capability()- } catch (e: Exception) {- Log.w(TAG, "STARTTLS failed ${server.host}: ${e.message}")- }- } else if (!server.useSsl && caps.has("LOGINDISABLED")) {- try {- conn.startTls()- caps = conn.capability()- } catch (e: Exception) {- Log.w(TAG, "STARTTLS required failed: ${e.message}")- }- }-- when (auth) {- is EmailManager.AuthType.OAuth -> {- conn.authenticateXoauth2(user, auth.token)- }- is EmailManager.AuthType.Password -> {- try {- conn.login(user, auth.value)- } catch (e: Exception) {- if (caps.has("AUTH=PLAIN")) {- try { conn.authenticatePlain(user, auth.value) } catch (e2: Exception) { Log.w(TAG, "PLAIN fallback failed: ${e2.message}"); throw e }- } else throw e- }- }- }-- block(conn)- } finally {- try { conn.close() } catch (_: Exception) {}- }- }-- suspend fun fetchFolders(server: ServerConfig, user: String, auth: EmailManager.AuthType): List<EmailFolder> =- withConnection(server, user, auth) { conn ->- val entries = conn.list("", "*")- entries.map { entry ->- val delim = entry.delimiter ?: "/"- // Identify the folder by its canonical path, but keep the server's own- // casing for the drawer label so Outlook still reads "Inbox", not "INBOX".- val fullName = canonicalizeMailbox(entry.mailbox, delim)- val displayPath = entry.mailbox- val name = if (displayPath.contains(delim)) displayPath.substringAfterLast(delim) else displayPath.substringAfterLast('/')- val parent = fullName.lastIndexOf(delim).let { if (it > 0) fullName.substring(0, it).takeIf { it.isNotEmpty() } else null }- val holds = !entry.flags.any { it.equals("\\Noselect", ignoreCase = true) }- EmailFolder(accountEmail = user, fullName = fullName, name = name.ifBlank { fullName }, parentFullName = parent, holdsMessages = holds, delimiter = delim)- }- }-- suspend fun fetchMessages(- server: ServerConfig,- user: String,- auth: EmailManager.AuthType,- folderName: String,- limit: Int,- offset: Int = 0,- fetchBodies: Boolean = false,- skipUids: Set<Long> = emptySet(),- context: Context? = null,- ): Pair<List<EmailMessage>, List<Attachment>> =- withConnection(server, user, auth) { conn ->- fetchMessagesInConnection(conn, user, folderName, limit, offset, fetchBodies, skipUids, context)- }-- suspend fun fetchMessagesInConnection(- conn: RawImapConnection,- user: String,- folderName: String,- limit: Int,- offset: Int,- fetchBodies: Boolean,- skipUids: Set<Long>,- context: Context?,- ): Pair<List<EmailMessage>, List<Attachment>> {- // SELECT with the exact name the server gave us, but persist under the- // canonical one so an Office 365 "Inbox" lands in the same bucket as a- // Gmail "INBOX" (see [canonicalizeMailbox]).- val sel = conn.select(folderName)- val storedFolderName = canonicalizeMailbox(folderName)- val total = sel.exists- if (total == 0) return Pair(emptyList(), emptyList())- val end = (total - offset).coerceAtLeast(1)- val start = (end - limit + 1).coerceAtLeast(1)- if (end < 1 || start > end) return Pair(emptyList(), emptyList())- val seqSet = "$start:$end"- val fetchResults = conn.fetchHeadersForSeq(seqSet)- val filtered = fetchResults.filter { it.uid !in skipUids }.reversed()- if (filtered.isEmpty()) return Pair(emptyList(), emptyList())-- val messages = mutableListOf<EmailMessage>()- val allAttachments = mutableListOf<Attachment>()- for (fr in filtered) {- val headerMap = fr.headerBytes?.let { MimeParser.parseHeaderBlockBytes(it) } ?: emptyMap()- val from = headerMap["from"]?.let { MimeParser.decodeHeader(it) } ?: ""- val to = headerMap["to"]?.let { MimeParser.decodeHeader(it) }- val cc = headerMap["cc"]?.let { MimeParser.decodeHeader(it) }- val subject = headerMap["subject"]?.let { MimeParser.decodeHeader(it) } ?: "(no subject)"- val dateHeader = headerMap["date"] ?: ""- val dateMillis = if (dateHeader.isNotBlank()) MimeParser.parseDateToMillis(dateHeader) else MimeParser.parseDateToMillis(fr.internalDate ?: "")- val isRead = fr.flags.any { it.equals("\\Seen", ignoreCase = true) }- val gmThrid = headerMap["x-gm-thrid"]-- var body: String? = null- var isHtmlFlag = false- var hasAtt = false- if (fetchBodies && fr.bodyBytes != null) {- val triple = try { MimeParser.parseMessage(fr.bodyBytes, fr.uid, user, storedFolderName, context) } catch (_: Exception) { Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) }- body = triple.first- isHtmlFlag = triple.second- allAttachments.addAll(triple.third)- hasAtt = triple.third.isNotEmpty()- }-- messages.add(- EmailMessage(- accountEmail = user,- folderName = storedFolderName,- id = fr.uid,- serverId = headerMap["message-id"],- threadId = gmThrid ?: fr.uid.toString(),- subject = subject,- from = from,- to = to,- cc = cc,- date = dateHeader.ifBlank { fr.internalDate ?: "" },- dateMillis = dateMillis,- body = body,- isHtml = isHtmlFlag,- isRead = isRead,- references = headerMap["references"] ?: headerMap["in-reply-to"],- hasAttachments = hasAtt,- listUnsubscribe = headerMap["list-unsubscribe"],- listUnsubscribePost = headerMap["list-unsubscribe-post"]- )- )- }- return Pair(messages, allAttachments)- }-- suspend fun fetchMessageBody(- server: ServerConfig,- user: String,- auth: EmailManager.AuthType,- folderName: String,- uid: Long,- context: Context? = null,- ): Triple<String?, Boolean, List<Attachment>> = withConnection(server, user, auth) { conn ->- conn.select(folderName)- val res = conn.uidFetchFullSet(uid.toString()).firstOrNull()- ?: return@withConnection Triple<String?, Boolean, List<Attachment>>(null, false, emptyList())- val bytes = res.bodyBytes ?: return@withConnection Triple(null, false, emptyList())- try { MimeParser.parseMessage(bytes, uid, user, canonicalizeMailbox(folderName), context) } catch (e: Exception) { Log.w(TAG, "parse failed ${e.message}"); Triple(null, false, emptyList()) }- }-- suspend fun fetchFullForBody(- context: Context,- server: ServerConfig,- user: String,- auth: EmailManager.AuthType,- folderName: String,- uid: Long,- ): EmailManager.FullFetchResult = withConnection(server, user, auth) { conn ->- conn.select(folderName)- val res = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: return@withConnection EmailManager.FullFetchResult(Triple(null, false, emptyList()))- val bytes = res.bodyBytes ?: return@withConnection EmailManager.FullFetchResult(Triple(null, false, emptyList()))- val triple = try { MimeParser.parseMessage(bytes, uid, user, canonicalizeMailbox(folderName), context.applicationContext) } catch (e: Exception) { Log.w(TAG, "full parse fail ${e.message}"); Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) }- EmailManager.FullFetchResult(triple)- }-- suspend fun fetchCidMap(- context: Context,- server: ServerConfig,- user: String,- auth: EmailManager.AuthType,- folderName: String,- uid: Long,- ): Map<String, File> = withConnection(server, user, auth) { conn ->- conn.select(folderName)- val res = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: return@withConnection emptyMap()- val bytes = res.bodyBytes ?: return@withConnection emptyMap()- try { MimeParser.extractCidMap(context, bytes, uid) } catch (_: Exception) { emptyMap() }- }-- suspend fun setSeenFlag(server: ServerConfig, user: String, auth: EmailManager.AuthType, folderName: String, uid: Long, seen: Boolean) =- withConnection(server, user, auth) { it.select(folderName); it.uidStoreFlags(uid, "\\Seen", add = seen) }-- suspend fun deleteMessage(server: ServerConfig, user: String, auth: EmailManager.AuthType, folderName: String, uid: Long) =- withConnection(server, user, auth) { it.select(folderName); it.uidExpunge(uid) }-- suspend fun downloadAttachment(- context: Context,- server: ServerConfig,- user: String,- auth: EmailManager.AuthType,- folderName: String,- uid: Long,- partId: String,- fileName: String,- mimeType: String,- ): String = withConnection(server, user, auth) { conn ->- conn.select(folderName)- val section = partIdToSection(partId)- val bytes = conn.uidFetchPartBytes(uid, section) ?: throw IllegalStateException("Part $partId ($section) not found UID $uid")- val resolver = context.contentResolver- val values = ContentValues().apply {- put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, fileName)- put(android.provider.MediaStore.MediaColumns.MIME_TYPE, mimeType.ifBlank { "application/octet-stream" })- put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)- put(android.provider.MediaStore.MediaColumns.IS_PENDING, 1)- }- val itemUri = resolver.insert(android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) ?: throw IllegalStateException("Downloads entry failed")- try {- resolver.openOutputStream(itemUri)?.use { it.write(bytes) } ?: throw IllegalStateException("openOutput")- values.clear()- values.put(android.provider.MediaStore.MediaColumns.IS_PENDING, 0)- resolver.update(itemUri, values, null, null)- } catch (e: Exception) { resolver.delete(itemUri, null, null); throw e }- itemUri.toString()- }-- suspend fun fetchRawMessageBytes(server: ServerConfig, user: String, auth: EmailManager.AuthType, folderName: String, uid: Long): ByteArray =- withConnection(server, user, auth) { conn ->- conn.select(folderName)- val r = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: throw IllegalStateException("UID $uid not found $folderName")- r.bodyBytes ?: throw IllegalStateException("Empty $uid")- }-- suspend fun fetchRawMessageTo(server: ServerConfig, user: String, auth: EmailManager.AuthType, folderName: String, uid: Long, output: OutputStream) =- withConnection(server, user, auth) { conn ->- conn.select(folderName)- val r = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: throw IllegalStateException("UID $uid not found $folderName")- output.write(r.bodyBytes ?: throw IllegalStateException("Empty $uid"))- }-- suspend fun quickInboxFetchRaw(- conn: RawImapConnection,- accountEmail: String,- known: Set<Long>,- deleted: Set<Long>,- ): Pair<List<EmailMessage>, List<Attachment>> =- fetchMessagesInConnection(conn, accountEmail, "INBOX", 50, 0, false, known + deleted, null)-- fun partIdToSection(partId: String): String {- if (partId == "0" || partId.isBlank()) return "1"- val parts = partId.split(".")- val mapped = parts.mapNotNull { it.toIntOrNull()?.let { idx -> (idx + 1).toString() } }- if (mapped.isEmpty()) return "1"- return mapped.joinToString(".")- }-}+package com.vayunmathur.email.network.imap++import android.content.ContentValues+import android.content.Context+import android.os.Environment+import android.provider.MediaStore+import android.util.Log+import com.vayunmathur.email.data.Attachment+import com.vayunmathur.email.data.EmailFolder+import com.vayunmathur.email.platform.EmailManager+import com.vayunmathur.email.data.EmailMessage+import com.vayunmathur.email.platform.ServerConfig+import java.io.File+import java.io.OutputStream+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.withContext++/**+ * High-level IMAP client using raw sockets — app-password primary, Outlook OAuth via XOAUTH2.+ */+object ImapClient {++ private const val TAG = "ImapClient"++ /**+ * Canonical inbox mailbox name. RFC 3501 §5.1 defines INBOX case-insensitively,+ * so servers are free to report it however they like — Gmail/Yahoo/iCloud return+ * `INBOX`, but Office 365 / Exchange returns `Inbox`. Every inbox query in the app+ * (per-account *and* the unified inbox) matches on this exact literal, and SQLite+ * TEXT comparison is case-sensitive, so all persisted folder names must be folded+ * to this constant via [canonicalizeMailbox] before they hit the DB.+ */+ const val INBOX = "INBOX"++ /**+ * Folds a server-reported mailbox path to its canonical form, so `Inbox` and+ * `Inbox/Receipts` (Office 365) are stored the same way as `INBOX` and+ * `INBOX/Receipts` (Gmail). Non-inbox mailboxes are returned untouched — only the+ * inbox has spec-mandated case-insensitivity.+ *+ * @param delimiter the server's hierarchy delimiter; when unknown, the two common+ * ones (`/` and `.`) are both accepted.+ */+ fun canonicalizeMailbox(mailbox: String, delimiter: String? = null): String {+ if (mailbox.equals(INBOX, ignoreCase = true)) return INBOX+ if (mailbox.length <= INBOX.length) return mailbox+ if (!mailbox.regionMatches(0, INBOX, 0, INBOX.length, ignoreCase = true)) return mailbox+ val delims = if (delimiter.isNullOrEmpty()) listOf("/", ".") else listOf(delimiter)+ return if (delims.any { mailbox.startsWith(it, INBOX.length) }) {+ INBOX + mailbox.substring(INBOX.length)+ } else {+ mailbox+ }+ }++ val GMAIL_VIRTUAL_FOLDERS = setOf(+ "[Gmail]/All Mail",+ "[Gmail]/Important",+ "[Gmail]/Starred",+ "[Gmail]/Chats",+ )++ suspend fun <T> withConnection(+ server: ServerConfig,+ user: String,+ auth: EmailManager.AuthType,+ trustAll: Boolean = false,+ block: suspend (RawImapConnection) -> T,+ ): T = withContext(Dispatchers.IO) {+ val useTrustAll = trustAll || !TrustAll.isKnownHost(server.host)+ val conn = RawImapConnection(server, trustAll = useTrustAll)+ try {+ conn.connect()+ var caps = conn.capability()++ if (!server.useSsl && caps.has("STARTTLS")) {+ try {+ conn.startTls()+ caps = conn.capability()+ } catch (e: Exception) {+ Log.w(TAG, "STARTTLS failed ${server.host}: ${e.message}")+ }+ } else if (!server.useSsl && caps.has("LOGINDISABLED")) {+ try {+ conn.startTls()+ caps = conn.capability()+ } catch (e: Exception) {+ Log.w(TAG, "STARTTLS required failed: ${e.message}")+ }+ }++ when (auth) {+ is EmailManager.AuthType.OAuth -> {+ conn.authenticateXoauth2(user, auth.token)+ }+ is EmailManager.AuthType.Password -> {+ try {+ conn.login(user, auth.value)+ } catch (e: Exception) {+ if (caps.has("AUTH=PLAIN")) {+ try { conn.authenticatePlain(user, auth.value) } catch (e2: Exception) { Log.w(TAG, "PLAIN fallback failed: ${e2.message}"); throw e }+ } else throw e+ }+ }+ }++ block(conn)+ } finally {+ try { conn.close() } catch (_: Exception) {}+ }+ }++ suspend fun fetchFolders(server: ServerConfig, user: String, auth: EmailManager.AuthType): List<EmailFolder> =+ withConnection(server, user, auth) { conn ->+ val entries = conn.list("", "*")+ entries.map { entry ->+ val delim = entry.delimiter ?: "/"+ // Identify the folder by its canonical path, but keep the server's own+ // casing for the drawer label so Outlook still reads "Inbox", not "INBOX".+ val fullName = canonicalizeMailbox(entry.mailbox, delim)+ val displayPath = entry.mailbox+ val name = if (displayPath.contains(delim)) displayPath.substringAfterLast(delim) else displayPath.substringAfterLast('/')+ val parent = fullName.lastIndexOf(delim).let { if (it > 0) fullName.substring(0, it).takeIf { it.isNotEmpty() } else null }+ val holds = !entry.flags.any { it.equals("\\Noselect", ignoreCase = true) }+ EmailFolder(accountEmail = user, fullName = fullName, name = name.ifBlank { fullName }, parentFullName = parent, holdsMessages = holds, delimiter = delim)+ }+ }++ suspend fun fetchMessages(+ server: ServerConfig,+ user: String,+ auth: EmailManager.AuthType,+ folderName: String,+ limit: Int,+ offset: Int = 0,+ fetchBodies: Boolean = false,+ skipUids: Set<Long> = emptySet(),+ context: Context? = null,+ ): Pair<List<EmailMessage>, List<Attachment>> =+ withConnection(server, user, auth) { conn ->+ fetchMessagesInConnection(conn, user, folderName, limit, offset, fetchBodies, skipUids, context)+ }++ suspend fun fetchMessagesInConnection(+ conn: RawImapConnection,+ user: String,+ folderName: String,+ limit: Int,+ offset: Int,+ fetchBodies: Boolean,+ skipUids: Set<Long>,+ context: Context?,+ ): Pair<List<EmailMessage>, List<Attachment>> {+ // SELECT with the exact name the server gave us, but persist under the+ // canonical one so an Office 365 "Inbox" lands in the same bucket as a+ // Gmail "INBOX" (see [canonicalizeMailbox]).+ val sel = conn.select(folderName)+ val storedFolderName = canonicalizeMailbox(folderName)+ val total = sel.exists+ if (total == 0) return Pair(emptyList(), emptyList())+ val end = (total - offset).coerceAtLeast(1)+ val start = (end - limit + 1).coerceAtLeast(1)+ if (end < 1 || start > end) return Pair(emptyList(), emptyList())+ val seqSet = "$start:$end"+ val fetchResults = conn.fetchHeadersForSeq(seqSet)+ val filtered = fetchResults.filter { it.uid !in skipUids }.reversed()+ if (filtered.isEmpty()) return Pair(emptyList(), emptyList())++ val messages = mutableListOf<EmailMessage>()+ val allAttachments = mutableListOf<Attachment>()+ for (fr in filtered) {+ val headerMap = fr.headerBytes?.let { MimeParser.parseHeaderBlockBytes(it) } ?: emptyMap()+ val from = headerMap["from"]?.let { MimeParser.decodeHeader(it) } ?: ""+ val to = headerMap["to"]?.let { MimeParser.decodeHeader(it) }+ val cc = headerMap["cc"]?.let { MimeParser.decodeHeader(it) }+ val subject = headerMap["subject"]?.let { MimeParser.decodeHeader(it) } ?: "(no subject)"+ val dateHeader = headerMap["date"] ?: ""+ val dateMillis = if (dateHeader.isNotBlank()) MimeParser.parseDateToMillis(dateHeader) else MimeParser.parseDateToMillis(fr.internalDate ?: "")+ val isRead = fr.flags.any { it.equals("\\Seen", ignoreCase = true) }+ val gmThrid = headerMap["x-gm-thrid"]++ var body: String? = null+ var isHtmlFlag = false+ var hasAtt = false+ if (fetchBodies && fr.bodyBytes != null) {+ val triple = try { MimeParser.parseMessage(fr.bodyBytes, fr.uid, user, storedFolderName, context) } catch (_: Exception) { Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) }+ body = triple.first+ isHtmlFlag = triple.second+ allAttachments.addAll(triple.third)+ hasAtt = triple.third.isNotEmpty()+ }++ messages.add(+ EmailMessage(+ accountEmail = user,+ folderName = storedFolderName,+ id = fr.uid,+ serverId = headerMap["message-id"],+ threadId = gmThrid ?: fr.uid.toString(),+ subject = subject,+ from = from,+ to = to,+ cc = cc,+ date = dateHeader.ifBlank { fr.internalDate ?: "" },+ dateMillis = dateMillis,+ body = body,+ isHtml = isHtmlFlag,+ isRead = isRead,+ references = headerMap["references"] ?: headerMap["in-reply-to"],+ hasAttachments = hasAtt,+ listUnsubscribe = headerMap["list-unsubscribe"],+ listUnsubscribePost = headerMap["list-unsubscribe-post"]+ )+ )+ }+ return Pair(messages, allAttachments)+ }++ suspend fun fetchMessageBody(+ server: ServerConfig,+ user: String,+ auth: EmailManager.AuthType,+ folderName: String,+ uid: Long,+ context: Context? = null,+ ): Triple<String?, Boolean, List<Attachment>> = withConnection(server, user, auth) { conn ->+ conn.select(folderName)+ val res = conn.uidFetchFullSet(uid.toString()).firstOrNull()+ ?: return@withConnection Triple<String?, Boolean, List<Attachment>>(null, false, emptyList())+ val bytes = res.bodyBytes ?: return@withConnection Triple(null, false, emptyList())+ try { MimeParser.parseMessage(bytes, uid, user, canonicalizeMailbox(folderName), context) } catch (e: Exception) { Log.w(TAG, "parse failed ${e.message}"); Triple(null, false, emptyList()) }+ }++ suspend fun fetchFullForBody(+ context: Context,+ server: ServerConfig,+ user: String,+ auth: EmailManager.AuthType,+ folderName: String,+ uid: Long,+ ): EmailManager.FullFetchResult = withConnection(server, user, auth) { conn ->+ conn.select(folderName)+ val res = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: return@withConnection EmailManager.FullFetchResult(Triple(null, false, emptyList()))+ val bytes = res.bodyBytes ?: return@withConnection EmailManager.FullFetchResult(Triple(null, false, emptyList()))+ val triple = try { MimeParser.parseMessage(bytes, uid, user, canonicalizeMailbox(folderName), context.applicationContext) } catch (e: Exception) { Log.w(TAG, "full parse fail ${e.message}"); Triple<String?, Boolean, List<Attachment>>(null, false, emptyList()) }+ EmailManager.FullFetchResult(triple)+ }++ suspend fun fetchCidMap(+ context: Context,+ server: ServerConfig,+ user: String,+ auth: EmailManager.AuthType,+ folderName: String,+ uid: Long,+ ): Map<String, File> = withConnection(server, user, auth) { conn ->+ conn.select(folderName)+ val res = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: return@withConnection emptyMap()+ val bytes = res.bodyBytes ?: return@withConnection emptyMap()+ try { MimeParser.extractCidMap(context, bytes, uid) } catch (_: Exception) { emptyMap() }+ }++ suspend fun setSeenFlag(server: ServerConfig, user: String, auth: EmailManager.AuthType, folderName: String, uid: Long, seen: Boolean) =+ withConnection(server, user, auth) { it.select(folderName); it.uidStoreFlags(uid, "\\Seen", add = seen) }++ suspend fun deleteMessage(server: ServerConfig, user: String, auth: EmailManager.AuthType, folderName: String, uid: Long) =+ withConnection(server, user, auth) { it.select(folderName); it.uidExpunge(uid) }++ suspend fun downloadAttachment(+ context: Context,+ server: ServerConfig,+ user: String,+ auth: EmailManager.AuthType,+ folderName: String,+ uid: Long,+ partId: String,+ fileName: String,+ mimeType: String,+ ): String = withConnection(server, user, auth) { conn ->+ conn.select(folderName)+ val section = partIdToSection(partId)+ val bytes = conn.uidFetchPartBytes(uid, section) ?: throw IllegalStateException("Part $partId ($section) not found UID $uid")+ val resolver = context.contentResolver+ val values = ContentValues().apply {+ put(android.provider.MediaStore.MediaColumns.DISPLAY_NAME, fileName)+ put(android.provider.MediaStore.MediaColumns.MIME_TYPE, mimeType.ifBlank { "application/octet-stream" })+ put(android.provider.MediaStore.MediaColumns.RELATIVE_PATH, Environment.DIRECTORY_DOWNLOADS)+ put(android.provider.MediaStore.MediaColumns.IS_PENDING, 1)+ }+ val itemUri = resolver.insert(android.provider.MediaStore.Downloads.EXTERNAL_CONTENT_URI, values) ?: throw IllegalStateException("Downloads entry failed")+ try {+ resolver.openOutputStream(itemUri)?.use { it.write(bytes) } ?: throw IllegalStateException("openOutput")+ values.clear()+ values.put(android.provider.MediaStore.MediaColumns.IS_PENDING, 0)+ resolver.update(itemUri, values, null, null)+ } catch (e: Exception) { resolver.delete(itemUri, null, null); throw e }+ itemUri.toString()+ }++ suspend fun fetchRawMessageBytes(server: ServerConfig, user: String, auth: EmailManager.AuthType, folderName: String, uid: Long): ByteArray =+ withConnection(server, user, auth) { conn ->+ conn.select(folderName)+ val r = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: throw IllegalStateException("UID $uid not found $folderName")+ r.bodyBytes ?: throw IllegalStateException("Empty $uid")+ }++ suspend fun fetchRawMessageTo(server: ServerConfig, user: String, auth: EmailManager.AuthType, folderName: String, uid: Long, output: OutputStream) =+ withConnection(server, user, auth) { conn ->+ conn.select(folderName)+ val r = conn.uidFetchFullSet(uid.toString()).firstOrNull() ?: throw IllegalStateException("UID $uid not found $folderName")+ output.write(r.bodyBytes ?: throw IllegalStateException("Empty $uid"))+ }++ suspend fun quickInboxFetchRaw(+ conn: RawImapConnection,+ accountEmail: String,+ known: Set<Long>,+ deleted: Set<Long>,+ ): Pair<List<EmailMessage>, List<Attachment>> =+ fetchMessagesInConnection(conn, accountEmail, "INBOX", 50, 0, false, known + deleted, null)++ fun partIdToSection(partId: String): String {+ if (partId == "0" || partId.isBlank()) return "1"+ val parts = partId.split(".")+ val mapped = parts.mapNotNull { it.toIntOrNull()?.let { idx -> (idx + 1).toString() } }+ if (mapped.isEmpty()) return "1"+ return mapped.joinToString(".")+ }+}
email/src/main/java/com/vayunmathur/email/network/imap/ImapParser.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/imap/ImapParser.kt b/email/src/main/java/com/vayunmathur/email/network/imap/ImapParser.ktindex 4c2bd0e9ec..3ec3d07a8a 100644--- a/email/src/main/java/com/vayunmathur/email/network/imap/ImapParser.kt+++ b/email/src/main/java/com/vayunmathur/email/network/imap/ImapParser.kt@@ -1,260 +1,260 @@-package com.vayunmathur.email.imap--import android.util.Log--/**- * Parser helpers for IMAP LIST and FETCH.- */-object ImapParser {-- private const val TAG = "ImapParser"-- // Modified UTF-7 for IMAP mailbox names (RFC 3501 §5.1.3)- // '&' starts a base64 section terminated by '-'. Base64 modified: ',' instead of '/'.- private val base64Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+,"- private val base64Inv = IntArray(128) { -1 }.apply {- for (i in base64Chars.indices) {- this[base64Chars[i].code] = i- }- }-- fun decodeModifiedUtf7(s: String): String {- return try {- val sb = StringBuilder()- var i = 0- while (i < s.length) {- val c = s[i]- if (c == '&') {- if (i + 1 < s.length && s[i + 1] == '-') {- sb.append('&')- i += 2- continue- }- val dash = s.indexOf('-', i + 1)- if (dash == -1) {- // Unterminated, treat literally- sb.append(s.substring(i))- break- }- val b64Section = s.substring(i + 1, dash)- if (b64Section.isEmpty()) {- i = dash + 1- continue- }- // Modified Base64 -> standard: replace ',' with '/'- val stdB64 = b64Section.replace(',', '/')- // Pad to multiple of 4- val padded = stdB64 + "===".substring(0, (4 - stdB64.length % 4) % 4)- try {- val bytes = android.util.Base64.decode(padded, android.util.Base64.DEFAULT)-
Diff truncated.