flows: no duplicate mail, atomic document saves, drafts survive failed sends
- Commit
25b2f6eefd0c56cc0e3a7a9e7c0f429a125afe06- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 09:06 UTC (15 days ago)
- Parents
94e912a
Email: a timeout after SMTP DATA enqueued the message and resent it with a fresh Message-ID - a guaranteed duplicate. The ID is now minted once before the first attempt, stored on the outbox entry (DB v24), and reused by every retry. Office offline saves wrote document bytes directly over the user's only copy - a kill mid-write corrupts it. File targets now write a sibling temp, fsync, and rename (original intact on any failure); SAF targets write fully-materialised bytes. Communicate cleared the composer before sending; on failure the text and attachments are now retained per-thread, cleared only on success (and only if not already replaced). Verified: office 1074, communicate 1970 tests pass; email's touched classes green (2 unrelated flakes pass isolated).
Diff
communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt
diff --git a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.ktindex 73c7b027fb..cd86603b02 100644--- a/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt+++ b/communicate/src/main/java/com/vayunmathur/communicate/ui/ConversationScreen.kt@@ -227,10 +227,12 @@ fun ConversationScreen( }, onSend = { val text = draft.trim()+ val sentDraft = draft val attachments = selectedAttachments if (text.isEmpty() && attachments.isEmpty()) return@ComposeSmsRow- draft = ""- selectedAttachments = emptyList()+ // Keep the draft and attachments in place until the send+ // succeeds: clearing them up front lost the composed+ // message entirely when the send failed. scope.launch { val ok = CommunicateRepository.sendMessage( context,@@ -241,7 +243,17 @@ fun ConversationScreen( attachments, participants = if (isGroup) participants else emptyList(), )- if (ok) refresh++ else AppMessages.show(gvSendFailedMessage)+ if (ok) {+ // Clear only what was sent; anything the user+ // typed or attached while sending survives.+ if (draft == sentDraft) draft = ""+ if (selectedAttachments == attachments) {+ selectedAttachments = emptyList()+ }+ refresh+++ } else {+ AppMessages.show(gvSendFailedMessage)+ } } }, )
email/schemas/com.vayunmathur.email.data.EmailDatabase/24.json
diff --git a/email/schemas/com.vayunmathur.email.data.EmailDatabase/24.json b/email/schemas/com.vayunmathur.email.data.EmailDatabase/24.jsonnew file mode 100644index 0000000000..1c6d63dfdf--- /dev/null+++ b/email/schemas/com.vayunmathur.email.data.EmailDatabase/24.json@@ -0,0 +1,683 @@+{+ "formatVersion": 1,+ "database": {+ "version": 24,+ "identityHash": "010b9f1bcf4b8e28fc4bea506339826a",+ "entities": [+ {+ "tableName": "EmailFolder",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountEmail` TEXT NOT NULL, `fullName` TEXT NOT NULL, `name` TEXT NOT NULL, `parentFullName` TEXT, `holdsMessages` INTEGER NOT NULL, `delimiter` TEXT NOT NULL, PRIMARY KEY(`accountEmail`, `fullName`))",+ "fields": [+ {+ "fieldPath": "accountEmail",+ "columnName": "accountEmail",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "fullName",+ "columnName": "fullName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "name",+ "columnName": "name",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "parentFullName",+ "columnName": "parentFullName",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "holdsMessages",+ "columnName": "holdsMessages",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "delimiter",+ "columnName": "delimiter",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "accountEmail",+ "fullName"+ ]+ }+ },+ {+ "tableName": "EmailMessage",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountEmail` TEXT NOT NULL, `folderName` TEXT NOT NULL, `id` INTEGER NOT NULL, `serverId` TEXT, `threadId` TEXT, `subject` TEXT NOT NULL, `from` TEXT NOT NULL, `to` TEXT, `cc` TEXT, `date` TEXT NOT NULL, `dateMillis` INTEGER NOT NULL, `body` TEXT, `isHtml` INTEGER NOT NULL, `isRead` INTEGER NOT NULL, `references` TEXT, `hasAttachments` INTEGER NOT NULL, `snoozedUntil` INTEGER NOT NULL, `listUnsubscribe` TEXT, `listUnsubscribePost` TEXT, `peekContent` TEXT NOT NULL DEFAULT '', PRIMARY KEY(`accountEmail`, `folderName`, `id`))",+ "fields": [+ {+ "fieldPath": "accountEmail",+ "columnName": "accountEmail",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "folderName",+ "columnName": "folderName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "serverId",+ "columnName": "serverId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "threadId",+ "columnName": "threadId",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "subject",+ "columnName": "subject",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "from",+ "columnName": "from",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "to",+ "columnName": "to",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "cc",+ "columnName": "cc",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "date",+ "columnName": "date",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "dateMillis",+ "columnName": "dateMillis",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "body",+ "columnName": "body",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "isHtml",+ "columnName": "isHtml",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isRead",+ "columnName": "isRead",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "references",+ "columnName": "references",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "hasAttachments",+ "columnName": "hasAttachments",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "snoozedUntil",+ "columnName": "snoozedUntil",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "listUnsubscribe",+ "columnName": "listUnsubscribe",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "listUnsubscribePost",+ "columnName": "listUnsubscribePost",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "peekContent",+ "columnName": "peekContent",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "''"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "accountEmail",+ "folderName",+ "id"+ ]+ },+ "indices": [+ {+ "name": "index_EmailMessage_folderName_dateMillis",+ "unique": false,+ "columnNames": [+ "folderName",+ "dateMillis"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_EmailMessage_folderName_dateMillis` ON `${TABLE_NAME}` (`folderName`, `dateMillis`)"+ },+ {+ "name": "index_EmailMessage_accountEmail_folderName_dateMillis",+ "unique": false,+ "columnNames": [+ "accountEmail",+ "folderName",+ "dateMillis"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_EmailMessage_accountEmail_folderName_dateMillis` ON `${TABLE_NAME}` (`accountEmail`, `folderName`, `dateMillis`)"+ },+ {+ "name": "index_EmailMessage_threadId",+ "unique": false,+ "columnNames": [+ "threadId"+ ],+ "orders": [],+ "createSql": "CREATE INDEX IF NOT EXISTS `index_EmailMessage_threadId` ON `${TABLE_NAME}` (`threadId`)"+ }+ ]+ },+ {+ "tableName": "EmailAccount",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`email` TEXT NOT NULL, `accessToken` TEXT NOT NULL, `refreshToken` TEXT, `expiresAt` INTEGER NOT NULL, `provider` TEXT NOT NULL DEFAULT 'gmail', `imapHost` TEXT NOT NULL DEFAULT 'imap.gmail.com', `imapPort` INTEGER NOT NULL DEFAULT 993, `imapUseSsl` INTEGER NOT NULL DEFAULT 1, `smtpHost` TEXT NOT NULL DEFAULT 'smtp.gmail.com', `smtpPort` INTEGER NOT NULL DEFAULT 465, `smtpUseSsl` INTEGER NOT NULL DEFAULT 1, `username` TEXT NOT NULL DEFAULT '', `authType` TEXT NOT NULL DEFAULT 'oauth2', `passwordEncrypted` BLOB, `passwordIv` BLOB, `signature` TEXT NOT NULL DEFAULT '', `allowInsecureCertificates` INTEGER NOT NULL DEFAULT 0, PRIMARY KEY(`email`))",+ "fields": [+ {+ "fieldPath": "email",+ "columnName": "email",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "accessToken",+ "columnName": "accessToken",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "refreshToken",+ "columnName": "refreshToken",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "expiresAt",+ "columnName": "expiresAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "provider",+ "columnName": "provider",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "'gmail'"+ },+ {+ "fieldPath": "imapHost",+ "columnName": "imapHost",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "'imap.gmail.com'"+ },+ {+ "fieldPath": "imapPort",+ "columnName": "imapPort",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "993"+ },+ {+ "fieldPath": "imapUseSsl",+ "columnName": "imapUseSsl",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "1"+ },+ {+ "fieldPath": "smtpHost",+ "columnName": "smtpHost",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "'smtp.gmail.com'"+ },+ {+ "fieldPath": "smtpPort",+ "columnName": "smtpPort",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "465"+ },+ {+ "fieldPath": "smtpUseSsl",+ "columnName": "smtpUseSsl",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "1"+ },+ {+ "fieldPath": "username",+ "columnName": "username",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "''"+ },+ {+ "fieldPath": "authType",+ "columnName": "authType",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "'oauth2'"+ },+ {+ "fieldPath": "passwordEncrypted",+ "columnName": "passwordEncrypted",+ "affinity": "BLOB"+ },+ {+ "fieldPath": "passwordIv",+ "columnName": "passwordIv",+ "affinity": "BLOB"+ },+ {+ "fieldPath": "signature",+ "columnName": "signature",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "''"+ },+ {+ "fieldPath": "allowInsecureCertificates",+ "columnName": "allowInsecureCertificates",+ "affinity": "INTEGER",+ "notNull": true,+ "defaultValue": "0"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "email"+ ]+ }+ },+ {+ "tableName": "Attachment",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountEmail` TEXT NOT NULL, `folderName` TEXT NOT NULL, `messageId` INTEGER NOT NULL, `partId` TEXT NOT NULL, `fileName` TEXT NOT NULL, `mimeType` TEXT NOT NULL, `size` INTEGER NOT NULL, `localUri` TEXT, PRIMARY KEY(`accountEmail`, `messageId`, `partId`))",+ "fields": [+ {+ "fieldPath": "accountEmail",+ "columnName": "accountEmail",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "folderName",+ "columnName": "folderName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "messageId",+ "columnName": "messageId",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "partId",+ "columnName": "partId",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "fileName",+ "columnName": "fileName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "mimeType",+ "columnName": "mimeType",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "size",+ "columnName": "size",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "localUri",+ "columnName": "localUri",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "accountEmail",+ "messageId",+ "partId"+ ]+ }+ },+ {+ "tableName": "OutboxEntry",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `accountEmail` TEXT NOT NULL, `to` TEXT NOT NULL, `cc` TEXT, `bcc` TEXT, `subject` TEXT NOT NULL, `body` TEXT NOT NULL, `attachmentLocalPaths` TEXT NOT NULL, `inlineImageJson` TEXT NOT NULL DEFAULT '[]', `inReplyTo` TEXT, `references` TEXT, `createdAt` INTEGER NOT NULL, `lastError` TEXT, `attemptCount` INTEGER NOT NULL, `lastAttemptAt` INTEGER NOT NULL, `scheduledAt` INTEGER NOT NULL, `isHtml` INTEGER NOT NULL, `messageId` TEXT)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "accountEmail",+ "columnName": "accountEmail",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "to",+ "columnName": "to",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "cc",+ "columnName": "cc",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "bcc",+ "columnName": "bcc",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "subject",+ "columnName": "subject",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "body",+ "columnName": "body",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "attachmentLocalPaths",+ "columnName": "attachmentLocalPaths",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "inlineImageJson",+ "columnName": "inlineImageJson",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "'[]'"+ },+ {+ "fieldPath": "inReplyTo",+ "columnName": "inReplyTo",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "references",+ "columnName": "references",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "createdAt",+ "columnName": "createdAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastError",+ "columnName": "lastError",+ "affinity": "TEXT"+ },+ {+ "fieldPath": "attemptCount",+ "columnName": "attemptCount",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "lastAttemptAt",+ "columnName": "lastAttemptAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "scheduledAt",+ "columnName": "scheduledAt",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "isHtml",+ "columnName": "isHtml",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "messageId",+ "columnName": "messageId",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "DraftEntry",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`id` INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, `accountEmail` TEXT NOT NULL, `to` TEXT NOT NULL, `cc` TEXT NOT NULL, `bcc` TEXT NOT NULL, `subject` TEXT NOT NULL, `body` TEXT NOT NULL, `inlineImageJson` TEXT NOT NULL DEFAULT '[]', `updatedAt` INTEGER NOT NULL)",+ "fields": [+ {+ "fieldPath": "id",+ "columnName": "id",+ "affinity": "INTEGER",+ "notNull": true+ },+ {+ "fieldPath": "accountEmail",+ "columnName": "accountEmail",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "to",+ "columnName": "to",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "cc",+ "columnName": "cc",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "bcc",+ "columnName": "bcc",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "subject",+ "columnName": "subject",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "body",+ "columnName": "body",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "inlineImageJson",+ "columnName": "inlineImageJson",+ "affinity": "TEXT",+ "notNull": true,+ "defaultValue": "'[]'"+ },+ {+ "fieldPath": "updatedAt",+ "columnName": "updatedAt",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "id"+ ]+ }+ },+ {+ "tableName": "BlockedSender",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`address` TEXT NOT NULL, PRIMARY KEY(`address`))",+ "fields": [+ {+ "fieldPath": "address",+ "columnName": "address",+ "affinity": "TEXT",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "address"+ ]+ }+ },+ {+ "tableName": "DeletedUid",+ "createSql": "CREATE TABLE IF NOT EXISTS `${TABLE_NAME}` (`accountEmail` TEXT NOT NULL, `folderName` TEXT NOT NULL, `uid` INTEGER NOT NULL, PRIMARY KEY(`accountEmail`, `folderName`, `uid`))",+ "fields": [+ {+ "fieldPath": "accountEmail",+ "columnName": "accountEmail",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "folderName",+ "columnName": "folderName",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "uid",+ "columnName": "uid",+ "affinity": "INTEGER",+ "notNull": true+ }+ ],+ "primaryKey": {+ "autoGenerate": false,+ "columnNames": [+ "accountEmail",+ "folderName",+ "uid"+ ]+ }+ },+ {+ "tableName": "EmailMessageFts",+ "createSql": "CREATE VIRTUAL TABLE IF NOT EXISTS `${TABLE_NAME}` USING FTS4(`subject` TEXT NOT NULL, `from` TEXT NOT NULL, `body` TEXT, tokenize=unicode61 `remove_diacritics=1`, content=`EmailMessage`)",+ "fields": [+ {+ "fieldPath": "subject",+ "columnName": "subject",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "from",+ "columnName": "from",+ "affinity": "TEXT",+ "notNull": true+ },+ {+ "fieldPath": "body",+ "columnName": "body",+ "affinity": "TEXT"+ }+ ],+ "primaryKey": {+ "autoGenerate": true,+ "columnNames": [+ "rowid"+ ]+ },+ "ftsVersion": "FTS4",+ "ftsOptions": {+ "tokenizer": "unicode61",+ "tokenizerArgs": [+ "remove_diacritics=1"+ ],+ "contentTable": "EmailMessage",+ "languageIdColumnName": "",+ "matchInfo": "FTS4",+ "notIndexedColumns": [],+ "prefixSizes": [],+ "preferredOrder": "ASC"+ },+ "contentSyncTriggers": [+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_EmailMessageFts_BEFORE_UPDATE BEFORE UPDATE ON `EmailMessage` BEGIN DELETE FROM `EmailMessageFts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_EmailMessageFts_BEFORE_DELETE BEFORE DELETE ON `EmailMessage` BEGIN DELETE FROM `EmailMessageFts` WHERE `docid`=OLD.`rowid`; END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_EmailMessageFts_AFTER_UPDATE AFTER UPDATE ON `EmailMessage` BEGIN INSERT INTO `EmailMessageFts`(`docid`, `subject`, `from`, `body`) VALUES (NEW.`rowid`, NEW.`subject`, NEW.`from`, NEW.`body`); END",+ "CREATE TRIGGER IF NOT EXISTS room_fts_content_sync_EmailMessageFts_AFTER_INSERT AFTER INSERT ON `EmailMessage` BEGIN INSERT INTO `EmailMessageFts`(`docid`, `subject`, `from`, `body`) VALUES (NEW.`rowid`, NEW.`subject`, NEW.`from`, NEW.`body`); END"+ ]+ }+ ],+ "setupQueries": [+ "CREATE TABLE IF NOT EXISTS room_master_table (id INTEGER PRIMARY KEY,identity_hash TEXT)",+ "INSERT OR REPLACE INTO room_master_table (id,identity_hash) VALUES(42, '010b9f1bcf4b8e28fc4bea506339826a')"+ ]+ }+}\ No newline at end of file
email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.ktindex efe7ff3b2b..70e9bd72c5 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailDatabase.kt@@ -27,7 +27,7 @@ import com.vayunmathur.email.data.Attachment DeletedUid::class, EmailMessageFts::class, ],- version = 23,+ version = 24, exportSchema = true, ) /** Room database holding email folders, messages, accounts and outbox state. */@@ -352,6 +352,16 @@ abstract class EmailDatabase : RoomDatabase() { ) } + /**+ * v23 → v24: stable Message-ID for outbox entries. Minted once at+ * enqueue time and reused on every retry, so an SMTP timeout after+ * DATA cannot deliver a duplicate under a regenerated ID. Existing+ * rows stay null; the worker mints and persists one on first retry.+ */+ private val MIGRATION_23_24 = Migration(23, 24) {+ it.execSQL("ALTER TABLE OutboxEntry ADD COLUMN messageId TEXT")+ }+ /** * Every migration for this database, registered with the Room builder via the * [DatabaseMigrations] reflection hook in `openRoomDatabase`. Order is@@ -380,6 +390,7 @@ abstract class EmailDatabase : RoomDatabase() { MIGRATION_20_21, MIGRATION_21_22, MIGRATION_22_23,+ MIGRATION_23_24, ) fun getInstance(context: Context): EmailDatabase =
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 b58530a354..52fa2aa8dc 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailModels.kt@@ -423,7 +423,14 @@ data class OutboxEntry( val attemptCount: Int = 0, val lastAttemptAt: Long = 0, val scheduledAt: Long = 0,- val isHtml: Boolean = false+ val isHtml: Boolean = false,+ /**+ * Stable Message-ID (bare value, no angle brackets) minted once when+ * this entry is created and reused on every retry build, so a send+ * that timed out after DATA does not deliver a second copy under a+ * fresh ID. Null only on rows queued before v24.+ */+ val messageId: String? = null ) @Entity
email/src/main/java/com/vayunmathur/email/data/EmailOutboxDao.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailOutboxDao.kt b/email/src/main/java/com/vayunmathur/email/data/EmailOutboxDao.ktindex d14be92581..49d97d0e04 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailOutboxDao.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailOutboxDao.kt@@ -33,6 +33,9 @@ interface EmailOutboxDao { ) suspend fun updateOutboxAttempt(id: Long, error: String?, attempts: Int, at: Long) + @Query("UPDATE OutboxEntry SET messageId = :messageId WHERE id = :id")+ suspend fun updateOutboxMessageId(id: Long, messageId: String?)+ // ---- Drafts ---- @Query("SELECT * FROM DraftEntry ORDER BY updatedAt DESC")
email/src/main/java/com/vayunmathur/email/data/EmailOutboxStore.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailOutboxStore.kt b/email/src/main/java/com/vayunmathur/email/data/EmailOutboxStore.ktindex 0ecd395737..0c5c03fa06 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailOutboxStore.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailOutboxStore.kt@@ -13,6 +13,8 @@ class EmailOutboxStore internal constructor(private val db: EmailDatabase) { suspend fun deleteOutboxEntry(entry: OutboxEntry) = dao.deleteOutboxEntry(entry) suspend fun updateOutboxAttempt(id: Long, error: String?, attempts: Int, at: Long) = dao.updateOutboxAttempt(id, error, attempts, at)+ suspend fun updateOutboxMessageId(id: Long, messageId: String?) =+ dao.updateOutboxMessageId(id, messageId) fun getDraftsFlow(): Flow<List<DraftEntry>> = dao.getDraftsFlow() suspend fun getDraft(id: Long): DraftEntry? = dao.getDraft(id)
email/src/main/java/com/vayunmathur/email/data/EmailRepository.kt
diff --git a/email/src/main/java/com/vayunmathur/email/data/EmailRepository.kt b/email/src/main/java/com/vayunmathur/email/data/EmailRepository.ktindex e0ea1b3331..7997d1b7be 100644--- a/email/src/main/java/com/vayunmathur/email/data/EmailRepository.kt+++ b/email/src/main/java/com/vayunmathur/email/data/EmailRepository.kt@@ -34,6 +34,8 @@ class EmailRepository private constructor(context: Context) : suspend fun deleteOutboxEntry(entry: OutboxEntry) = outbox.deleteOutboxEntry(entry) suspend fun updateOutboxAttempt(id: Long, error: String?, attempts: Int, at: Long) = outbox.updateOutboxAttempt(id, error, attempts, at)+ suspend fun updateOutboxMessageId(id: Long, messageId: String?) =+ outbox.updateOutboxMessageId(id, messageId) /** Provides the singleton EmailRepository instance. */ companion object {
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 aaaf84c0ae..8a344c9f06 100644--- a/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt+++ b/email/src/main/java/com/vayunmathur/email/data/OutboxSendWorker.kt@@ -12,6 +12,7 @@ import androidx.work.OneTimeWorkRequestBuilder import androidx.work.WorkManager import androidx.work.WorkerParameters import com.vayunmathur.email.data.OutboxEntry+import com.vayunmathur.email.network.smtp.MimeBuilder import com.vayunmathur.email.platform.EmailManager import com.vayunmathur.email.platform.SendRequest import com.vayunmathur.email.platform.imapServer@@ -78,11 +79,20 @@ class OutboxSendWorker( ) return EntryOutcome(true, Long.MAX_VALUE) }- val uris = decodePaths(entry.attachmentLocalPaths).map { Uri.fromFile(File(it)) }- val inline = decodeInline(entry.inlineImageJson).map {+ // Legacy (pre-v24) rows carry no ID: mint one now and persist it+ // before sending, so this and every later retry share it.+ val effectiveEntry = if (entry.messageId.isNullOrBlank()) {+ val minted = entry.copy(messageId = MimeBuilder.generateMessageId(entry.accountEmail))+ repository.updateOutboxMessageId(minted.id, minted.messageId)+ minted+ } else {+ entry+ }+ val uris = decodePaths(effectiveEntry.attachmentLocalPaths).map { Uri.fromFile(File(it)) }+ val inline = decodeInline(effectiveEntry.inlineImageJson).map { InlineAttachment(cid = it.cid, uri = Uri.fromFile(File(it.path)), mimeType = it.mime, fileName = it.name) }- return when (val sendResult = trySend(manager, account, entry, uris, inline)) {+ return when (val sendResult = trySend(manager, account, effectiveEntry, uris, inline)) { is SendResult.Success -> { Log.dev(TAG, "Sent outbox entry #${entry.id} to ${entry.to}") attachmentDirFor(applicationContext, entry.id).deleteRecursively()@@ -146,6 +156,7 @@ class OutboxSendWorker( references = entry.references, asHtml = entry.isHtml, from = account.email,+ messageId = entry.messageId, ), ) }.fold(@@ -231,6 +242,7 @@ object OutboxManager { initialError: String? = null, scheduledAt: Long = 0, isHtml: Boolean = false,+ messageId: String? = null, ): OutboxEntry { val dao = EmailRepository.get(context).getDatabase().outboxDao() val base = OutboxEntry(@@ -247,6 +259,9 @@ object OutboxManager { lastError = initialError, scheduledAt = scheduledAt, isHtml = isHtml,+ // Mint once at creation; every worker retry reuses this ID.+ messageId = messageId?.takeIf { it.isNotBlank() }+ ?: MimeBuilder.generateMessageId(accountEmail), ) val pendingId = dao.insertOutboxEntry(base) val localPaths = copyAttachmentsToOutbox(context, pendingId, attachments)
email/src/main/java/com/vayunmathur/email/network/smtp/MimeBuilder.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/smtp/MimeBuilder.kt b/email/src/main/java/com/vayunmathur/email/network/smtp/MimeBuilder.ktindex 3195d79a10..dc4aba2d54 100644--- a/email/src/main/java/com/vayunmathur/email/network/smtp/MimeBuilder.kt+++ b/email/src/main/java/com/vayunmathur/email/network/smtp/MimeBuilder.kt@@ -46,6 +46,20 @@ object MimeBuilder { return "${System.currentTimeMillis()}.$random@$domain" } + /**+ * Mint a new Message-ID for [from] (bare value, no angle brackets).+ * Callers that may retry a send (direct attempt → outbox → worker)+ * generate this once and pass the same value to every [buildMessage]+ * call, so a server that accepted the first copy but whose reply was+ * lost (e.g. timeout after DATA) sees the retry as the same message.+ */+ fun generateMessageId(from: String): String = buildMessageId(from)++ /** Strip brackets/whitespace and reject header-breaking characters. */+ private fun sanitizeMessageId(messageId: String?): String? =+ messageId?.trim()?.removeSurrounding("<", ">")?.trim()+ ?.takeIf { it.isNotBlank() && it.none { c -> c == '\r' || c == '\n' || c == '<' || c == '>' } }+ /** The built raw RFC 822 message text ready for SMTP submission. */ data class BuildResult(val rawMessage: String) @@ -61,9 +75,10 @@ object MimeBuilder { inlineImages: List<InlineAttachment> = emptyList(), inReplyTo: String? = null, references: String? = null,+ messageId: String? = null, ): String { val sb = StringBuilder()- appendHeaders(sb, from, to, subject, cc, inReplyTo, references)+ appendHeaders(sb, from, to, subject, cc, inReplyTo, references, messageId) if (inlineImages.isEmpty() && attachments.isEmpty()) { appendSingleTextPart(sb, body, asHtml)@@ -92,6 +107,7 @@ object MimeBuilder { cc: String?, inReplyTo: String?, references: String?,+ messageId: String? = null, ) { // Standard headers sb.append("From: $from\r\n")@@ -110,9 +126,10 @@ object MimeBuilder { sb.append("MIME-Version: 1.0\r\n") if (!inReplyTo.isNullOrBlank()) sb.append("In-Reply-To: $inReplyTo\r\n") if (!references.isNullOrBlank()) sb.append("References: $references\r\n")- // Message-ID- val messageId = buildMessageId(from)- sb.append("Message-ID: <$messageId>\r\n")+ // Message-ID: reuse the caller-supplied stable ID when present so+ // retries of the same logical message are de-duplicated downstream.+ val effectiveMessageId = sanitizeMessageId(messageId) ?: buildMessageId(from)+ sb.append("Message-ID: <$effectiveMessageId>\r\n") } private fun appendSingleTextPart(sb: StringBuilder, body: String, asHtml: Boolean) {
email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.kt
diff --git a/email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.kt b/email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.ktindex c8c5b209e8..ea27ca4f6e 100644--- a/email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.kt+++ b/email/src/main/java/com/vayunmathur/email/network/smtp/SmtpClient.kt@@ -36,6 +36,7 @@ object SmtpClient { inlineImages = request.inlineImages, inReplyTo = request.inReplyTo, references = request.references,+ messageId = request.messageId, ) val conn = RawSmtpConnection(server, trustAll = server.trustAllCertificates) try {
email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailManager.ktindex bfffa4f443..20256b3f06 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailManager.kt@@ -70,6 +70,8 @@ data class SendRequest( val references: String? = null, val from: String? = null, val asHtml: Boolean = false,+ /** Stable Message-ID (bare, no brackets) reused across every retry. */+ val messageId: String? = null, ) /** Coordinates mail operations across IMAP and SMTP for configured accounts. */
email/src/main/java/com/vayunmathur/email/platform/EmailSendActions.kt
diff --git a/email/src/main/java/com/vayunmathur/email/platform/EmailSendActions.kt b/email/src/main/java/com/vayunmathur/email/platform/EmailSendActions.ktindex ad8679dc89..fea1690b66 100644--- a/email/src/main/java/com/vayunmathur/email/platform/EmailSendActions.kt+++ b/email/src/main/java/com/vayunmathur/email/platform/EmailSendActions.kt@@ -6,6 +6,7 @@ import com.vayunmathur.email.data.EmailAccount import com.vayunmathur.email.data.OutboxEntry import com.vayunmathur.email.data.OutboxManager import com.vayunmathur.email.data.OutboxSendWorker+import com.vayunmathur.email.network.smtp.MimeBuilder import com.vayunmathur.email.ui.composer.InlineAttachment import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.launch@@ -32,6 +33,10 @@ class EmailSendActions( onError: (String) -> Unit, ) { scope.launch {+ // Mint the Message-ID once, before the first attempt: if the+ // direct send times out after DATA and we fall back to the+ // outbox, the worker retry must carry this same ID.+ val messageId = MimeBuilder.generateMessageId(account.email) try { emailManager.sendMessage( context = appContext,@@ -50,6 +55,7 @@ class EmailSendActions( references = references, from = account.email, asHtml = asHtml,+ messageId = messageId, ), ) onSuccess()@@ -70,6 +76,7 @@ class EmailSendActions( references = references, initialError = msg, isHtml = asHtml,+ messageId = messageId, ) } catch (_: Exception) { onError("$msg (and outbox save failed)")
email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt b/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.ktindex dfb2979289..816749d8dd 100644--- a/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt+++ b/email/src/test/java/com/vayunmathur/email/data/EmailMigrationsW5Test.kt@@ -78,7 +78,7 @@ class EmailMigrationsW5Test { @Test fun migrationChainIsCompleteAndOrdered() { assertEquals(- (1..22).map { it to it + 1 },+ (1..23).map { it to it + 1 }, EmailDatabase.migrations.map { it.startVersion to it.endVersion }.sortedBy { it.first }, ) }@@ -109,7 +109,7 @@ class EmailMigrationsW5Test { } @Test- fun v1DatabaseUpgradesAllTheWayToV23Shape() {+ fun v1DatabaseUpgradesAllTheWayToV24Shape() { val conn = openV1() migrate(conn, 1) assertTrue(tableExists(conn, "OutboxEntry"))@@ -159,7 +159,7 @@ class EmailMigrationsW5Test { } @Test- fun v4DatabaseUpgradesToV23Shape() {+ fun v4DatabaseUpgradesToV24Shape() { val conn = openV4() migrate(conn, 4) assertTrue(tableExists(conn, "OutboxEntry"))@@ -169,7 +169,7 @@ class EmailMigrationsW5Test { assertTrue(tableExists(conn, "EmailMessageFts")) assertTrue(columns(conn, "EmailMessage").containsAll(setOf("dateMillis", "snoozedUntil", "listUnsubscribe", "listUnsubscribePost", "peekContent")), columns(conn, "EmailMessage").toString()) assertTrue(columns(conn, "EmailAccount").containsAll(setOf("provider", "imapHost", "smtpHost", "authType", "username", "signature", "allowInsecureCertificates")), columns(conn, "EmailAccount").toString())- assertTrue(columns(conn, "OutboxEntry").containsAll(setOf("scheduledAt", "isHtml", "bcc", "inlineImageJson")), columns(conn, "OutboxEntry").toString())+ assertTrue(columns(conn, "OutboxEntry").containsAll(setOf("scheduledAt", "isHtml", "bcc", "inlineImageJson", "messageId")), columns(conn, "OutboxEntry").toString()) assertTrue(columns(conn, "DraftEntry").contains("inlineImageJson")) // The 6→7 backfill copies email into the new username column. assertEquals(listOf("[email protected]"), strings(conn, "SELECT username FROM EmailAccount"))
email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.kt b/email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.ktindex 15354d99e2..534d9ad23e 100644--- a/email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.kt+++ b/email/src/test/java/com/vayunmathur/email/data/OutboxSendWorkerTest.kt@@ -92,6 +92,11 @@ class OutboxSendWorkerTest { assertEquals(0, db.outboxDao().getOutboxCount()) assertTrue(smtp.dataBodies.single().contains("Flush me")) assertTrue(smtp.dataBodies.single().contains("flushbody"))+ assertTrue(!entry.messageId.isNullOrBlank(), "enqueue must mint a stable Message-ID")+ assertTrue(+ smtp.dataBodies.single().contains("Message-ID: <${entry.messageId}>"),+ smtp.dataBodies.single(),+ ) assertFalse(OutboxSendWorker.attachmentDirFor(context, entry.id).exists()) }
email/src/test/java/com/vayunmathur/email/draft/DraftMergeTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/draft/DraftMergeTest.kt b/email/src/test/java/com/vayunmathur/email/draft/DraftMergeTest.ktindex 8ef31d55b0..8bb6575947 100644--- a/email/src/test/java/com/vayunmathur/email/draft/DraftMergeTest.kt+++ b/email/src/test/java/com/vayunmathur/email/draft/DraftMergeTest.kt@@ -32,6 +32,7 @@ class DraftMergeTest { override suspend fun insertOutboxEntry(entry: OutboxEntry): Long = 0 override suspend fun deleteOutboxEntry(entry: OutboxEntry) {} override suspend fun updateOutboxAttempt(id: Long, error: String?, attempts: Int, at: Long) {}+ override suspend fun updateOutboxMessageId(id: Long, messageId: String?) {} override fun getDraftsFlow(): Flow<List<DraftEntry>> = flowOf(drafts.values.toList()) override suspend fun getDraft(id: Long): DraftEntry? = drafts[id]
email/src/test/java/com/vayunmathur/email/mime/MimeBuilderTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/mime/MimeBuilderTest.kt b/email/src/test/java/com/vayunmathur/email/mime/MimeBuilderTest.ktindex ea86e4711d..2b9adda8cf 100644--- a/email/src/test/java/com/vayunmathur/email/mime/MimeBuilderTest.kt+++ b/email/src/test/java/com/vayunmathur/email/mime/MimeBuilderTest.kt@@ -56,6 +56,26 @@ class MimeBuilderTest { assertTrue(raw.contains("World"), raw) } + @Test+ fun `supplied message id is reused verbatim on every build`() {+ val first = MimeBuilder.buildMessage(+ context, "[email protected]", "[email protected]", "s", "b", false,+ messageId = "[email protected]",+ )+ val second = MimeBuilder.buildMessage(+ context, "[email protected]", "[email protected]", "s", "b", false,+ messageId = "[email protected]",+ )+ assertTrue(first.contains("Message-ID: <[email protected]>\r\n"), first)+ assertTrue(second.contains("Message-ID: <[email protected]>\r\n"), second)+ // Bracketed input from a stored row is normalised, not double-wrapped.+ val bracketed = MimeBuilder.buildMessage(+ context, "[email protected]", "[email protected]", "s", "b", false,+ messageId = "<[email protected]>",+ )+ assertTrue(bracketed.contains("Message-ID: <[email protected]>\r\n"), bracketed)+ }+ @Test fun `multiple recipients split on comma and semicolon`() { val raw = MimeBuilder.buildMessage(
email/src/test/java/com/vayunmathur/email/platform/EmailSendActionsTest.kt
diff --git a/email/src/test/java/com/vayunmathur/email/platform/EmailSendActionsTest.kt b/email/src/test/java/com/vayunmathur/email/platform/EmailSendActionsTest.ktindex 4020f0a7dc..6760b4471b 100644--- a/email/src/test/java/com/vayunmathur/email/platform/EmailSendActionsTest.kt+++ b/email/src/test/java/com/vayunmathur/email/platform/EmailSendActionsTest.kt@@ -135,6 +135,7 @@ class EmailSendActionsTest { assertEquals("Will fail", row.subject) assertEquals("queued body", row.body) assertEquals("[email protected]", row.cc)+ assertTrue(!row.messageId.isNullOrBlank(), "outbox row must carry the stable Message-ID minted for the direct attempt") assertTrue(!row.lastError.isNullOrBlank(), "outbox row must record the failure") }
office/src/main/java/com/vayunmathur/office/data/odf/OdfWriter.kt
diff --git a/office/src/main/java/com/vayunmathur/office/data/odf/OdfWriter.kt b/office/src/main/java/com/vayunmathur/office/data/odf/OdfWriter.ktindex 5ecbe80ea6..1a6eba6940 100644--- a/office/src/main/java/com/vayunmathur/office/data/odf/OdfWriter.kt+++ b/office/src/main/java/com/vayunmathur/office/data/odf/OdfWriter.kt@@ -6,11 +6,58 @@ import com.vayunmathur.library.ui.odf.OdfDocument import com.vayunmathur.library.ui.odf.OdfPageSetup import com.vayunmathur.library.ui.odf.OdfSerializer import java.io.ByteArrayOutputStream+import java.io.File+import java.io.FileOutputStream+import java.io.IOException import java.util.zip.ZipEntry import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream import com.vayunmathur.office.platform.save++/**+ * Replace [targetUri] with [bytes] without truncating the existing file.+ *+ * File-backed targets: write `<name>.tmp` in the same directory, fsync it,+ * then rename it over the original. A failure at any step before the rename+ * (including a failed rename) leaves the original bytes untouched and+ * surfaces as an [IOException]; the temp file is removed on failure.+ *+ * Content-resolver targets have no sibling path that can be renamed over+ * the original through the resolver API, so they keep the direct write —+ * but [bytes] are already fully materialised by the caller, so a+ * serialisation failure can never reach (and truncate) the target.+ */+internal fun writeDocumentBytesAtomically(context: Context, targetUri: Uri, bytes: ByteArray) {+ val targetPath = targetUri.path?.takeIf { targetUri.scheme == "file" }+ if (targetPath == null) {+ context.contentResolver.openOutputStream(targetUri)?.use { it.write(bytes) }+ ?: throw IOException("Cannot open $targetUri for writing")+ return+ }+ val targetFile = File(targetPath)+ val dir = targetFile.parentFile+ ?: throw IOException("No parent directory for $targetUri")+ val tmpFile = File(dir, targetFile.name + ".tmp")+ try {+ FileOutputStream(tmpFile).use { out ->+ out.write(bytes)+ out.flush()+ out.fd.sync()+ }+ if (!tmpFile.renameTo(targetFile)) {+ throw IOException("Could not rename ${tmpFile.name} over ${targetFile.name}")+ }+ // Best-effort directory fsync so the rename itself is durable.+ runCatching {+ java.io.RandomAccessFile(dir, "r").use { it.channel.force(true) }+ }+ } catch (expected: Exception) {+ tmpFile.delete()+ throw expected+ }+}+ /** Singleton holding odf writer state and operations. */ object OdfWriter { @@ -39,7 +86,7 @@ object OdfWriter { } // AFTER the ZipOutputStream is closed (close writes the END header). val bytes = buffer.toByteArray()- context.contentResolver.openOutputStream(targetUri)?.use { it.write(bytes) }+ writeDocumentBytesAtomically(context, targetUri, bytes) } /** Save accumulation state. */
office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelDocuments.kt
diff --git a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelDocuments.kt b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelDocuments.ktindex 9d1b885214..fee1908285 100644--- a/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelDocuments.kt+++ b/office/src/main/java/com/vayunmathur/office/platform/OfficeViewModelDocuments.kt@@ -23,6 +23,7 @@ import com.vayunmathur.library.util.AppMessages import com.vayunmathur.office.R import com.vayunmathur.office.data.odf.DocumentImporter import com.vayunmathur.office.data.odf.OdfWriter+import com.vayunmathur.office.data.odf.writeDocumentBytesAtomically import com.vayunmathur.office.platform.MAX_RECENT import com.vayunmathur.office.platform.OfficeViewModel.ViewState import kotlinx.coroutines.Dispatchers@@ -214,9 +215,7 @@ fun OfficeViewModel.save(targetUri: Uri? = null) { try { if (targetIsOoxml) { val bytes = com.vayunmathur.library.ui.odf.OoxmlExporter.export(doc)- getApplication<Application>().contentResolver.openOutputStream(target)- ?.use { it.write(bytes) }- ?: throw java.io.IOException("Cannot open $target for writing")+ writeDocumentBytesAtomically(getApplication(), target, bytes) } else { OdfWriter.save(getApplication(), source, doc, target) }
office/src/test/java/com/vayunmathur/office/data/odf/AtomicDocumentWriteTest.kt
diff --git a/office/src/test/java/com/vayunmathur/office/data/odf/AtomicDocumentWriteTest.kt b/office/src/test/java/com/vayunmathur/office/data/odf/AtomicDocumentWriteTest.ktnew file mode 100644index 0000000000..1cfcabde21--- /dev/null+++ b/office/src/test/java/com/vayunmathur/office/data/odf/AtomicDocumentWriteTest.kt@@ -0,0 +1,99 @@+package com.vayunmathur.office.data.odf++import android.net.Uri+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.ui.odf.OdfContentBlock+import com.vayunmathur.library.ui.odf.OdfDocument+import com.vayunmathur.library.ui.odf.OdfParagraph+import com.vayunmathur.library.ui.odf.OdfSpan+import java.io.File+import java.io.IOException+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFailsWith+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config++/**+ * Atomic document replace: a save must never truncate the only copy.+ * Bytes go to `<name>.tmp` in the same directory, are fsynced, and are+ * renamed over the original; any failure leaves the original intact.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class AtomicDocumentWriteTest {++ private val context get() = ApplicationProvider.getApplicationContext<android.content.Context>()++ @Test+ fun `write replaces an existing file and leaves no tmp behind`() {+ val target = File(context.cacheDir, "atomic-replace.odt")+ target.writeText("original-bytes")+ try {+ writeDocumentBytesAtomically(context, Uri.fromFile(target), "replacement".toByteArray())+ assertEquals("replacement", target.readText())+ assertFalse(File(context.cacheDir, "atomic-replace.odt.tmp").exists())+ } finally {+ target.delete()+ }+ }++ @Test+ fun `write creates a new file when none existed`() {+ val target = File(context.cacheDir, "atomic-new.odt")+ target.delete()+ try {+ writeDocumentBytesAtomically(context, Uri.fromFile(target), "fresh".toByteArray())+ assertEquals("fresh", target.readText())+ assertFalse(File(context.cacheDir, "atomic-new.odt.tmp").exists())+ } finally {+ target.delete()+ }+ }++ @Test+ fun `failed rename surfaces an error and keeps the original intact`() {+ // A non-empty directory at the target path cannot be replaced by+ // renaming a file over it, which exercises the rename-failure path.+ val target = File(context.cacheDir, "atomic-dir.odt")+ target.mkdirs()+ File(target, "keep.txt").writeText("keep me")+ try {+ assertFailsWith<IOException> {+ writeDocumentBytesAtomically(context, Uri.fromFile(target), "replacement".toByteArray())+ }+ assertTrue(target.isDirectory)+ assertEquals("keep me", File(target, "keep.txt").readText())+ assertFalse(File(context.cacheDir, "atomic-dir.odt.tmp").exists())+ } finally {+ target.deleteRecursively()+ }+ }++ @Test+ fun `odf writer save to a file target replaces the previous package`() {+ val target = File(context.cacheDir, "atomic-writer.odt")+ target.writeText("not a zip - the only copy before save")+ val doc = OdfDocument.TextDocument(+ "Saved",+ listOf(+ OdfContentBlock.Paragraph(+ OdfParagraph(listOf(OdfSpan("round trip"))),+ ),+ ),+ )+ try {+ OdfWriter.save(context, null, doc, Uri.fromFile(target))+ assertTrue(target.length() > 100, "save wrote ${target.length()} bytes")+ java.util.zip.ZipFile(target).use { z ->+ assertTrue(z.getEntry("content.xml") != null)+ }+ assertFalse(File(context.cacheDir, "atomic-writer.odt.tmp").exists())+ } finally {+ target.delete()+ }+ }+}