Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_net/src/imap/types.rs

11.9 KiB, 21 runs

created by r1870400018:75217, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! The plain data the IMAP client returns and a sync engine holds: a mailbox's LIST entry and
2//! special-use role, the state a SELECT leaves, a fetched message, and the UIDPLUS response codes.
3//!
4//! Tokio-free, so the folder sync engine in `fe2o3_mail::sync` can hold them in a browser; the
5//! client re-exports every one, so `imap::client::FetchWhat` and the rest still resolve (F3).
6
7use crate::imap::uid_set::UidSet;
8
9
10/// One mailbox as reported by `LIST`.
11#[derive(Clone, Debug)]
12pub struct MailboxInfo {
13 pub name: String, // as the server spells it
14 pub delimiter: Option<char>, // `None` for a flat namespace
15 pub attrs: Vec<String>, // e.g. `\HasChildren`, `\Noselect`, `\Sent`
16}
17
18impl MailboxInfo {
19 /// A mailbox that exists only to hold children cannot itself be selected.
20 pub fn selectable(&self) -> bool {
21 !self.attrs.iter().any(|a| a.eq_ignore_ascii_case("\\Noselect"))
22 }
23
24 /// The RFC 6154 special-use role, where the server declared one. This is how a client
25 /// recognises the Sent folder on a mailbox whose
26 /// names are localised -- Gmail spells it "[Gmail]/Gesendet" for a German
27 /// account, but the attribute is `\Sent` everywhere.
28 pub fn special_use(&self) -> Option<SpecialUse> {
29 for a in &self.attrs {
30 let role = match a.to_uppercase().as_str() {
31 "\\SENT" => Some(SpecialUse::Sent),
32 "\\DRAFTS" => Some(SpecialUse::Drafts),
33 "\\TRASH" => Some(SpecialUse::Trash),
34 "\\JUNK" => Some(SpecialUse::Junk),
35 "\\ARCHIVE" => Some(SpecialUse::Archive),
36 "\\ALL" => Some(SpecialUse::All),
37 "\\FLAGGED" => Some(SpecialUse::Flagged),
38 _ => None,
39 };
40 if role.is_some() {
41 return role;
42 }
43 }
44 None
45 }
46}
47
48/// The special-use roles of RFC 6154, one per mailbox at most.
49#[derive(Clone, Copy, Debug, PartialEq, Eq)]
50pub enum SpecialUse {
51 Sent,
52 Drafts,
53 Trash, // deleted messages await expunge
54 Junk, // spam
55 Archive, // filed out of the inbox
56 All, // every message however filed, Gmail's "All Mail"
57 Flagged, // starred or flagged
58}
59
60/// The state of a mailbox after `SELECT` or `EXAMINE`.
61///
62/// `uid_validity` is the one field a synchronising caller must persist:
63/// if it changes, every UID it has cached is meaningless and the mailbox
64/// must be re-read from scratch.
65#[derive(Clone, Debug, Default)]
66pub struct MailboxStatus {
67 pub name: String,
68 pub exists: u32, // messages present
69 pub recent: u32, // messages flagged `\Recent`
70 pub uid_validity: u32, // UID namespace generation
71 pub uid_next: u32, // the UID the next arrival will be given
72 pub flags: Vec<String>, // defined in this mailbox
73 pub read_only: bool, // `EXAMINE`, or a server that downgraded the `SELECT`
74 // RFC 7162. `None` from a server without CONDSTORE in use, and for a mailbox it answers
75 // `NOMODSEQ`, which keeps no mod-sequences.
76 pub highest_modseq: Option<u64>,
77 pub vanished: UidSet, // QRESYNC: known UIDs expunged since the modseq
78 pub changed: Vec<FetchedMessage>, // QRESYNC: flags changed since the modseq
79}
80
81/// What a `SELECT` or `EXAMINE` asks for beyond the mailbox itself (RFC 7162).
82#[derive(Clone, Debug, Default, Eq, PartialEq)]
83pub enum SelectWith {
84 #[default]
85 Plain,
86 CondStore, // `(CONDSTORE)`: the mailbox's HIGHESTMODSEQ, and a MODSEQ on every fetch
87 // `(QRESYNC (uid_validity modseq known))`: the reply carries the flags changed since `modseq`
88 // and those of `known` (every UID, where `None`) that have vanished. A server whose
89 // UIDVALIDITY is no longer `uid_validity` ignores the rest, and the caller starts again.
90 QResync {
91 uid_validity: u32,
92 modseq: u64,
93 known: Option<UidSet>,
94 },
95}
96
97/// A mailbox's counts by `STATUS`, without selecting it.
98#[derive(Clone, Debug, Default, Eq, PartialEq)]
99pub struct FolderStatus {
100 pub messages: u32,
101 pub uid_next: u32,
102 pub uid_validity: u32,
103 pub unseen: u32,
104 pub highest_modseq: Option<u64>, // asked for only where CONDSTORE is offered
105}
106
107/// What a `UID FETCH ... (CHANGEDSINCE n)` returned.
108#[derive(Clone, Debug, Default)]
109pub struct FetchChanged {
110 pub messages: Vec<FetchedMessage>, // changed since the modseq
111 pub vanished: UidSet, // QRESYNC only: expunged since the modseq
112}
113
114/// How much of each message to pull down. Where the mailbox keeps mod-sequences each fetch also
115/// asks for `MODSEQ`, and where the server offers `X-GM-EXT-1`, for Gmail's message ID and labels;
116/// `MessageId` alone asks for nothing it does not name, being a check that must stay a few bytes.
117#[derive(Clone, Copy, Debug, Eq, PartialEq)]
118pub enum FetchWhat {
119 Flags, // UID and flags, the cheapest poll of what changed
120 Meta, // and internal date and size; no body at all
121 Headers, // and the RFC 5322 header block
122 Full, // and the whole message
123 MessageId, // UID, size and the `Message-ID` field alone, to confirm a search's match
124 Summary, // UID, flags, date, size and the fields a listing shows, decoded by the caller
125 Structure, // UID, flags, date, size, `BODYSTRUCTURE` and the header block, to read by part
126 BodyStructure, // UID and `BODYSTRUCTURE` alone, to read a message's attachment names
127}
128
129impl FetchWhat {
130 /// `BODY.PEEK` rather than `BODY`, so reading a message does not silently mark it `\Seen` --
131 /// a sync should be invisible to whoever is reading the mailbox elsewhere.
132 pub fn items(&self) -> &'static str {
133 match self {
134 Self::Flags => "UID FLAGS",
135 Self::Meta => "UID FLAGS INTERNALDATE RFC822.SIZE",
136 Self::Headers => "UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[HEADER]",
137 Self::Full => "UID FLAGS INTERNALDATE RFC822.SIZE BODY.PEEK[]",
138 Self::MessageId => "UID RFC822.SIZE BODY.PEEK[HEADER.FIELDS (MESSAGE-ID)]",
139 Self::Summary => "UID FLAGS INTERNALDATE RFC822.SIZE \
140 BODY.PEEK[HEADER.FIELDS (DATE FROM TO CC SUBJECT MESSAGE-ID)]",
141 Self::Structure => "UID FLAGS INTERNALDATE RFC822.SIZE BODYSTRUCTURE BODY.PEEK[HEADER]",
142 Self::BodyStructure => "UID BODYSTRUCTURE",
143 }
144 }
145}
146
147/// The instant an `INTERNALDATE` names, in seconds since the Unix epoch, its zone applied:
148/// `17-Nov-2026 09:00:00 +0800` and `17-Nov-2026 01:00:00 +0000` are one instant. A missing zone
149/// is read as UTC, since some clients send none. The year is the grammar's four digits.
150pub fn parse_internal_date(s: &str) -> Option<i64> {
151 const MONTHS: [&str; 12] = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
152 "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; // fixed: RFC 3501 date-month
153 let w: Vec<&str> = s.split_whitespace().collect();
154 let zone = if w.len() == 2 { "+0000" } else { w.get(2).copied().unwrap_or("") };
155 let d: Vec<&str> = w.first().map_or(Vec::new(), |x| x.split('-').collect());
156 let t: Vec<&str> = w.get(1).map_or(Vec::new(), |x| x.split(':').collect());
157 if w.len() > 3 || d.len() != 3 || d[2].len() != 4 || t.len() != 3 || zone.len() != 5
158 || !zone.is_ascii()
159 {
160 return None;
161 }
162 let n = |x: &str| x.bytes().all(|b| b.is_ascii_digit()).then(|| x.parse::<i64>().ok()).flatten();
163 match ([n(d[0]), n(d[2]), n(t[0]), n(t[1]), n(t[2]), n(&zone[1..])],
164 MONTHS.iter().position(|m| m.eq_ignore_ascii_case(d[1])), &zone[..1])
165 {
166 ([Some(dd), Some(y), Some(h), Some(mi), Some(se), Some(z)], Some(mo), sign @ ("+" | "-"))
167 if (1..=31).contains(&dd) && h < 24 && mi < 60 && se <= 60 && z % 100 < 60 =>
168 {
169 let off = (z / 100 * 60 + z % 100) * 60;
170 let off = if sign == "-" { -off } else { off };
171 Some(days_from_civil(y, mo as i64 + 1, dd) * 86_400 + h * 3_600 + mi * 60 + se - off)
172 }
173 _ => None,
174 }
175}
176
177/// Days since the Unix epoch of a proleptic-Gregorian date (Howard Hinnant's `days_from_civil`).
178fn days_from_civil(y: i64, m: i64, d: i64) -> i64 {
179 let y = if m <= 2 { y - 1 } else { y };
180 let era = if y >= 0 { y } else { y - 399 } / 400;
181 let yoe = y - era * 400;
182 let doy = (153 * ((m + 9) % 12) + 2) / 5 + d - 1;
183 era * 146_097 + yoe * 365 + yoe / 4 - yoe / 100 + doy - 719_468
184}
185
186/// One message returned by `UID FETCH`.
187#[derive(Clone, Debug, Default)]
188pub struct FetchedMessage {
189 pub seq: u32, // sequence number in the current mailbox view
190 pub uid: u32, // stable within the mailbox's current `uid_validity`
191 pub flags: Vec<String>, // e.g. `\Seen`, `\Answered`
192 // `INTERNALDATE` exactly as the server gave it, e.g. `01-Jan-2026 09:15:00 +0000`. Left as
193 // the server's string, because only the caller knows what calendar it wants it in.
194 pub internal_date: String,
195 pub size: u32, // `RFC822.SIZE`, which may exceed `body.len()`
196 pub body: Vec<u8>, // whole message, header block, or empty, per FetchWhat
197 pub modseq: Option<u64>, // RFC 7162 `MODSEQ`, where the mailbox keeps them
198 pub gm_msgid: Option<u64>, // Gmail's `X-GM-MSGID`, stable across its labels
199 pub gm_labels: Vec<String>, // Gmail's `X-GM-LABELS`, e.g. `\Inbox`, `Important`
200 pub structure: Option<BodyPart>, // `BODYSTRUCTURE`, where asked for
201}
202
203/// One entity of a message's MIME structure as `BODYSTRUCTURE` gives it (RFC 3501 §7.4.2), so a
204/// reader can fetch its text parts by section and list its attachments without their bytes.
205#[derive(Clone, Debug, Default, Eq, PartialEq)]
206pub struct BodyPart {
207 pub section: String, // `1`, `1.2`; empty for the whole message
208 pub media: String, // lower case, `text/plain`, `multipart/mixed`
209 pub params: Vec<(String, String)>, // lower-case names, e.g. `charset`, `name`
210 pub encoding: String, // Content-Transfer-Encoding, lower case
211 pub size: u32, // octets of the body in its transfer encoding
212 pub disposition: Option<String>, // lower case, `attachment` or `inline`
213 pub filename: Option<String>, // the type's `name`, else the disposition's, RFC 2231 read
214 pub parts: Vec<BodyPart>, // a multipart's children, in order
215}
216
217impl BodyPart {
218 pub fn param(&self, name: &str) -> Option<&str> {
219 self.params.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
220 }
221
222 /// Is this a text body to read, rather than an attachment to list?
223 pub fn is_text_body(&self) -> bool {
224 self.parts.is_empty()
225 && (self.media == "text/plain" || self.media == "text/html")
226 && self.disposition.as_deref() != Some("attachment")
227 }
228
229 /// Every leaf, in the order the message holds them.
230 pub fn leaves(&self) -> Vec<&BodyPart> {
231 let mut out = Vec::new();
232 self.walk(&mut out);
233 out
234 }
235
236 fn walk<'a>(&'a self, out: &mut Vec<&'a BodyPart>) {
237 if self.parts.is_empty() {
238 out.push(self);
239 } else {
240 for p in &self.parts {
241 p.walk(out);
242 }
243 }
244 }
245}
246
247/// Where `UID COPY` or `UID MOVE` put each message, from the `UIDPLUS` `COPYUID` response code.
248#[derive(Clone, Debug, Default, Eq, PartialEq)]
249pub struct CopyUid {
250 pub uid_validity: u32, // of the destination
251 pub pairs: Vec<(u32, u32)>, // source UID, destination UID
252}
253
254/// The new message's place, from the `UIDPLUS` `APPENDUID` response code.
255#[derive(Clone, Copy, Debug, Eq, PartialEq)]
256pub struct AppendUid {
257 pub uid_validity: u32,
258 pub uid: u32,
259}