C12.9: three-pane mailbox view, filters, virtualized list; ids never reused

This commit is contained in:
雷电芽衣 committed 2026-10-20 00:25:57 -04:00
1 parent 7f70ab6df7
commit ba358c7de6
29 files changed
+1274 -75

No files matched your search

+2 -1
View File
@@ -21,7 +21,8 @@ pub use net::{Login, Secret, Security, Server, system_tls};
pub use pop::Pop;
pub use smtp::Smtp;
pub use store::{
AccountId, Cached, Fetched, Held, Key, LocalFolder, MailboxId, MessageId, Sizes, Store, Stored, Synced,
AccountId, Cached, Fetched, Filter, Held, Key, LocalFolder, MailboxId, MessageId, Scope, Sizes,
Store, Stored, Summary, Synced,
};
pub use tokio_rustls::TlsConnector;
pub use vault::{Backend, Kept, Keyring, Vault};
+9 -2
View File
@@ -14,6 +14,7 @@ mod accounts;
mod aside;
mod folders;
mod html;
mod listing;
mod messages;
mod schema;
mod search;
@@ -22,6 +23,7 @@ mod tests;
pub use accounts::Cached;
pub use folders::{Held, LocalFolder, Synced};
pub use listing::{Filter, Scope, Summary};
pub use messages::{Fetched, Key, Stored};
const DB: &str = "mail.db";
@@ -175,13 +177,18 @@ fn upgrade(
Ok(())
}
fn migrate(conn: &mut Connection, version: usize, steps: &[&str]) -> rusqlite::Result<()> {
fn migrate(conn: &mut Connection, version: usize, steps: &[&str]) -> Result<()> {
// A rebuilt parent would cascade into its children.
conn.pragma_update(None, "foreign_keys", false)?;
let tx = conn.transaction()?;
for step in &steps[version..] {
tx.execute_batch(step)?;
}
if tx.prepare("PRAGMA foreign_key_check")?.exists([])? {
return Err(Error::Store("rows point at missing rows".into()));
}
tx.pragma_update(None, "user_version", steps.len() as i64)?;
tx.commit()
Ok(tx.commit()?)
}
fn backup(conn: &Connection, dir: &Path, version: usize) -> Result<()> {
+111
View File
@@ -0,0 +1,111 @@
//! Message lists: one mailbox or every inbox, newest first.
use std::collections::HashMap;
use rusqlite::ToSql;
use super::{MailboxId, MessageId, Store};
use crate::{Mailbox, Result};
/// Which messages a list holds.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Scope {
Mailbox(MailboxId),
/// Every account's inbox together.
Inboxes,
}
/// Each set field narrows the list.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct Filter {
pub unread: bool,
pub flagged: bool,
pub attachments: bool,
}
/// A message as a list shows it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Summary {
pub id: MessageId,
pub from: Vec<Mailbox>,
pub subject: Option<String>,
pub date: Option<i64>,
pub seen: bool,
pub flagged: bool,
/// None until the body is here.
pub attachments: Option<u32>,
}
// RFC 3501 §2.3.2: system flags match in any case.
const SEEN: &str = "EXISTS (SELECT 1 FROM flags f WHERE f.message = m.id \
AND f.flag = '\\Seen' COLLATE NOCASE)";
const FLAGGED: &str = "EXISTS (SELECT 1 FROM flags f WHERE f.message = m.id \
AND f.flag = '\\Flagged' COLLATE NOCASE)";
impl Store {
/// Newest first; SQLite sorts undated last.
pub fn list(&self, scope: Scope, filter: Filter) -> Result<Vec<Summary>> {
let mut clauses = vec![match scope {
Scope::Mailbox(_) => "m.mailbox = ?1".to_owned(),
Scope::Inboxes => "b.role = 'inbox'".to_owned(),
}];
if filter.unread {
clauses.push(format!("NOT {SEEN}"));
}
if filter.flagged {
clauses.push(FLAGGED.to_owned());
}
if filter.attachments {
clauses.push("m.attachments > 0".to_owned());
}
let sql = format!(
"SELECT m.id, m.sender, m.subject, m.date, m.attachments, {SEEN}, {FLAGGED}
FROM messages m JOIN mailboxes b ON b.id = m.mailbox
WHERE {}
ORDER BY m.date DESC, m.id DESC",
clauses.join(" AND ")
);
let id;
let values: Vec<&dyn ToSql> = match scope {
Scope::Mailbox(mailbox) => {
id = mailbox.0;
vec![&id]
}
Scope::Inboxes => Vec::new(),
};
let mut query = self.conn.prepare(&sql)?;
let rows = query.query_map(values.as_slice(), |row| {
Ok((
row.get::<_, i64>(0)?,
row.get::<_, String>(1)?,
row.get(2)?,
row.get(3)?,
row.get(4)?,
row.get(5)?,
row.get(6)?,
))
})?;
rows.map(|row| {
let (id, from, subject, date, attachments, seen, flagged) = row?;
Ok(Summary {
id: MessageId(id),
from: serde_json::from_str(&from)?,
subject,
date,
seen,
flagged,
attachments,
})
})
.collect()
}
/// Unread messages per mailbox; mailboxes with none are left out.
pub fn unread(&self) -> Result<HashMap<MailboxId, u32>> {
let mut query = self.conn.prepare(&format!(
"SELECT m.mailbox, COUNT(*) FROM messages m WHERE NOT {SEEN} GROUP BY m.mailbox"
))?;
let rows = query.query_map([], |row| Ok((MailboxId(row.get(0)?), row.get(1)?)))?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
}
}
+62 -1
View File
@@ -1,5 +1,5 @@
/// Step `n` upgrades version `n`.
pub(super) const STEPS: &[&str] = &[V1, V2, V3];
pub(super) const STEPS: &[&str] = &[V1, V2, V3, V4];
const V1: &str = "
CREATE TABLE accounts (
@@ -63,3 +63,64 @@ ALTER TABLE messages ADD COLUMN missing TEXT NOT NULL DEFAULT '[]';
const V3: &str = "
ALTER TABLE mailboxes ADD COLUMN offline INTEGER NOT NULL DEFAULT 0;
";
/// Ids never reused (C12.9); foreign keys are off here.
const V4: &str = "
CREATE TABLE accounts_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
address TEXT NOT NULL UNIQUE COLLATE NOCASE,
settings TEXT NOT NULL,
synced INTEGER
);
CREATE TABLE mailboxes_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
account INTEGER NOT NULL REFERENCES accounts ON DELETE CASCADE,
name TEXT NOT NULL,
role TEXT,
uidvalidity INTEGER,
offline INTEGER NOT NULL DEFAULT 0,
UNIQUE (account, name)
);
CREATE TABLE messages_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
mailbox INTEGER NOT NULL REFERENCES mailboxes ON DELETE CASCADE,
uidvalidity INTEGER,
uid INTEGER,
uidl TEXT,
message_id TEXT,
in_reply_to TEXT NOT NULL,
refs TEXT NOT NULL,
subject TEXT,
sender TEXT NOT NULL,
recipients TEXT NOT NULL,
copies TEXT NOT NULL,
date INTEGER,
attachments INTEGER,
content TEXT,
missing TEXT NOT NULL DEFAULT '[]',
CHECK ((uid IS NULL) = (uidvalidity IS NULL) AND (uid IS NULL) <> (uidl IS NULL))
);
INSERT INTO accounts_new (id, address, settings, synced)
SELECT id, address, settings, synced FROM accounts;
INSERT INTO mailboxes_new (id, account, name, role, uidvalidity, offline)
SELECT id, account, name, role, uidvalidity, offline FROM mailboxes;
INSERT INTO messages_new (id, mailbox, uidvalidity, uid, uidl, message_id, in_reply_to,
refs, subject, sender, recipients, copies, date, attachments, content, missing)
SELECT id, mailbox, uidvalidity, uid, uidl, message_id, in_reply_to,
refs, subject, sender, recipients, copies, date, attachments, content, missing
FROM messages;
DROP TABLE messages;
DROP TABLE mailboxes;
DROP TABLE accounts;
ALTER TABLE accounts_new RENAME TO accounts;
ALTER TABLE mailboxes_new RENAME TO mailboxes;
ALTER TABLE messages_new RENAME TO messages;
CREATE UNIQUE INDEX messages_imap ON messages (mailbox, uidvalidity, uid)
WHERE uid IS NOT NULL;
CREATE UNIQUE INDEX messages_pop ON messages (mailbox, uidl) WHERE uidl IS NOT NULL;
CREATE INDEX messages_thread ON messages (message_id);
CREATE INDEX messages_content ON messages (content);
CREATE TRIGGER messages_gone AFTER DELETE ON messages BEGIN
DELETE FROM search WHERE rowid = old.id;
END;
";
+25 -1
View File
@@ -22,6 +22,9 @@ fn account(address: &str) -> Account {
}
}
mod ids;
mod listing;
const ADD: &str = "ALTER TABLE accounts ADD COLUMN nick TEXT";
const BROKEN: &str = "ALTER TABLE nowhere ADD COLUMN nick TEXT";
@@ -144,7 +147,10 @@ fn a_v1_store_gains_sync_and_keeps_its_mail() {
.set_folders(ann, &[("INBOX", Some(Role::Inbox))])
.unwrap();
let [inbox] = store.folders(ann).unwrap().try_into().unwrap();
assert_eq!((inbox.name.as_str(), inbox.role), ("INBOX", Some(Role::Inbox)));
assert_eq!(
(inbox.name.as_str(), inbox.role),
("INBOX", Some(Role::Inbox))
);
assert!(!inbox.offline);
let held = store.open_mailbox(inbox.id, 7).unwrap();
assert_eq!(held.keys().copied().collect::<Vec<_>>(), [1]);
@@ -153,3 +159,21 @@ fn a_v1_store_gains_sync_and_keeps_its_mail() {
assert_eq!(store.synced(ann).unwrap().at, Some(9));
assert_eq!(store.synced(ann).unwrap().messages, 1);
}
#[test]
fn an_upgrade_leaving_a_row_without_its_parent_fails() {
let dir = tempfile::tempdir().unwrap();
let old = open(dir.path(), &[STEPS[0]]).unwrap();
old.conn
.execute_batch(
"PRAGMA foreign_keys = OFF;
INSERT INTO mailboxes (account, name) VALUES (99, 'INBOX');",
)
.unwrap();
drop(old);
let store = open(dir.path(), STEPS).unwrap();
let reason = store.read_only().unwrap();
assert!(reason.contains("missing rows"), "{reason}");
drop(store);
assert_eq!(version(&dir.path().join(DB)), 1);
}
@@ -0,0 +1,74 @@
//! Ids are never reused, so a stale one names nothing.
use super::{STEPS, account, open};
use crate::{Fetched, Key, Role, Store};
const MAIL: &[u8] = b"From: a@example.com\r\nSubject: hi\r\n\r\nhi\r\n";
fn imap(uidvalidity: u32) -> Key {
Key::Imap {
uidvalidity,
uid: 1,
}
}
#[test]
fn a_removed_account_folder_or_message_leaves_its_id_unused() {
let dir = tempfile::tempdir().unwrap();
let mut store = Store::open(dir.path()).unwrap();
let ann = store.add_account(&account("ann@example.com")).unwrap();
let bob = store.add_account(&account("bob@example.com")).unwrap();
store.remove_account(bob).unwrap();
let cy = store.add_account(&account("cy@example.com")).unwrap();
assert!(cy.0 > bob.0, "account {} came back", bob.0);
let [_, old] = store
.set_folders(ann, &[("INBOX", Some(Role::Inbox)), ("Old", None)])
.unwrap()
.try_into()
.unwrap();
store
.set_folders(ann, &[("INBOX", Some(Role::Inbox))])
.unwrap();
let [inbox, new] = store
.set_folders(ann, &[("INBOX", Some(Role::Inbox)), ("New", None)])
.unwrap()
.try_into()
.unwrap();
assert!(new.0 > old.0, "folder {} came back", old.0);
store.open_mailbox(inbox, 1).unwrap();
let first = store
.put(inbox, &imap(1), &[], Fetched::Whole(MAIL))
.unwrap();
store.open_mailbox(inbox, 2).unwrap();
let second = store
.put(inbox, &imap(2), &[], Fetched::Whole(MAIL))
.unwrap();
assert!(second.0 > first.0, "message {} came back", first.0);
}
#[test]
fn a_v3_store_keeps_its_ids_and_stops_reusing_them() {
let dir = tempfile::tempdir().unwrap();
let mut old = open(dir.path(), &STEPS[..3]).unwrap();
let ann = old.add_account(&account("ann@example.com")).unwrap();
let [inbox] = old
.set_folders(ann, &[("INBOX", Some(Role::Inbox))])
.unwrap()
.try_into()
.unwrap();
old.open_mailbox(inbox, 1).unwrap();
let first = old
.put(inbox, &imap(1), &["\\Seen"], Fetched::Whole(MAIL))
.unwrap();
drop(old);
let mut store = open(dir.path(), STEPS).unwrap();
assert_eq!(store.read_only(), None);
assert_eq!(store.accounts().unwrap()[0].0, ann);
let held = store.open_mailbox(inbox, 1).unwrap();
assert_eq!(held[&1].id, first);
store.open_mailbox(inbox, 2).unwrap();
let second = store
.put(inbox, &imap(2), &[], Fetched::Whole(MAIL))
.unwrap();
assert!(second.0 > first.0, "message {} came back", first.0);
}
@@ -0,0 +1,181 @@
use super::account;
use crate::{Fetched, Filter, Key, MailboxId, Role, Scope, Store};
fn mail(subject: &str, date: Option<&str>, attachment: bool) -> Vec<u8> {
let mut head = format!("From: Ann <ann@example.com>\r\nSubject: {subject}\r\n");
if let Some(date) = date {
head.push_str(&format!("Date: {date}\r\n"));
}
if attachment {
format!(
"{head}Content-Type: multipart/mixed; boundary=b\r\n\r\n--b\r\n\
Content-Type: text/plain\r\n\r\nhi\r\n--b\r\n\
Content-Type: application/pdf\r\nContent-Disposition: attachment; filename=a.pdf\r\n\r\n\
%PDF\r\n--b--\r\n"
)
.into_bytes()
} else {
format!("{head}Content-Type: text/plain\r\n\r\nhi\r\n").into_bytes()
}
}
fn put(store: &mut Store, mailbox: MailboxId, uid: u32, flags: &[&str], bytes: &[u8]) {
let key = Key::Imap {
uidvalidity: 1,
uid,
};
store
.put(mailbox, &key, flags, Fetched::Whole(bytes))
.unwrap();
}
fn subjects(store: &Store, scope: Scope, filter: Filter) -> Vec<String> {
let listed = store.list(scope, filter).unwrap();
listed.into_iter().map(|s| s.subject.unwrap()).collect()
}
/// Two accounts: inbox and archive, inbox only.
fn two_accounts() -> (tempfile::TempDir, Store, [MailboxId; 3]) {
let dir = tempfile::tempdir().unwrap();
let mut store = Store::open(dir.path()).unwrap();
let ann = store.add_account(&account("ann@example.com")).unwrap();
let bob = store.add_account(&account("bob@example.com")).unwrap();
let [ann_inbox, archive] = store
.set_folders(
ann,
&[
("INBOX", Some(Role::Inbox)),
("Archive", Some(Role::Archive)),
],
)
.unwrap()
.try_into()
.unwrap();
let [bob_inbox] = store
.set_folders(bob, &[("INBOX", Some(Role::Inbox))])
.unwrap()
.try_into()
.unwrap();
(dir, store, [ann_inbox, archive, bob_inbox])
}
#[test]
fn every_inbox_lists_newest_first_and_undated_last() {
let (_dir, mut store, [ann, archive, bob]) = two_accounts();
put(
&mut store,
ann,
1,
&[],
&mail("old", Some("Mon, 1 Jan 2024 10:00:00 +0000"), false),
);
put(
&mut store,
bob,
1,
&[],
&mail("new", Some("Tue, 2 Jan 2024 10:00:00 +0000"), false),
);
put(&mut store, ann, 2, &[], &mail("undated", None, false));
put(
&mut store,
archive,
1,
&[],
&mail("filed", Some("Wed, 3 Jan 2024 10:00:00 +0000"), false),
);
assert_eq!(
subjects(&store, Scope::Inboxes, Filter::default()),
["new", "old", "undated"]
);
assert_eq!(
subjects(&store, Scope::Mailbox(archive), Filter::default()),
["filed"]
);
assert_eq!(
subjects(&store, Scope::Mailbox(ann), Filter::default()),
["old", "undated"]
);
let first = &store.list(Scope::Inboxes, Filter::default()).unwrap()[0];
assert_eq!(first.from[0].email, "ann@example.com");
assert_eq!(first.date, Some(1_704_189_600));
}
#[test]
fn filters_narrow_together() {
let (_dir, mut store, [ann, ..]) = two_accounts();
let date = Some("Mon, 1 Jan 2024 10:00:00 +0000");
put(&mut store, ann, 1, &["\\Seen"], &mail("read", date, false));
put(
&mut store,
ann,
2,
&["\\SEEN", "\\flagged"],
&mail("read flagged", date, true),
);
put(
&mut store,
ann,
3,
&["\\Flagged"],
&mail("unread flagged", date, true),
);
put(&mut store, ann, 4, &[], &mail("unread", date, false));
let scope = Scope::Mailbox(ann);
let unread = Filter {
unread: true,
..Filter::default()
};
let flagged = Filter {
flagged: true,
..Filter::default()
};
let attached = Filter {
attachments: true,
..Filter::default()
};
let all = Filter {
unread: true,
flagged: true,
attachments: true,
};
assert_eq!(
subjects(&store, scope, unread),
["unread", "unread flagged"]
);
assert_eq!(
subjects(&store, scope, flagged),
["unread flagged", "read flagged"]
);
assert_eq!(
subjects(&store, scope, attached),
["unread flagged", "read flagged"]
);
assert_eq!(subjects(&store, scope, all), ["unread flagged"]);
let listed = store.list(scope, Filter::default()).unwrap();
let read_flagged = listed
.iter()
.find(|s| s.subject.as_deref() == Some("read flagged"))
.unwrap();
assert!(read_flagged.seen && read_flagged.flagged);
assert_eq!(read_flagged.attachments, Some(1));
}
#[test]
fn unread_counts_by_mailbox() {
let (_dir, mut store, [ann, archive, bob]) = two_accounts();
put(&mut store, ann, 1, &[], &mail("a", None, false));
put(&mut store, ann, 2, &["\\seen"], &mail("b", None, false));
put(&mut store, ann, 3, &[], &mail("c", None, false));
put(&mut store, archive, 1, &["\\Seen"], &mail("d", None, false));
put(&mut store, bob, 1, &[], &mail("e", None, false));
let counts = store.unread().unwrap();
assert_eq!(counts.len(), 2);
assert_eq!((counts[&ann], counts[&bob]), (2, 1));
assert!(!counts.contains_key(&archive));
}