Skip to main content

ibridge_core/
mail.rs

1// SPDX-License-Identifier: Apache-2.0
2
3//! Mail identifiers.
4
5use std::fmt;
6use std::num::NonZeroU32;
7
8use crate::error::{CoreError, ParseError};
9
10/// An IMAP mailbox path, stored as Unicode (not modified UTF-7).
11#[derive(Clone, PartialEq, Eq, Hash, Debug)]
12pub struct MailboxPath(String);
13
14impl MailboxPath {
15    /// Returns the mailbox path.
16    #[must_use]
17    pub fn as_str(&self) -> &str {
18        &self.0
19    }
20}
21
22impl TryFrom<&str> for MailboxPath {
23    type Error = ParseError;
24
25    fn try_from(value: &str) -> Result<Self, Self::Error> {
26        if value.is_empty()
27            || value.len() > 1024
28            || value.contains("://")
29            || value.starts_with("//")
30            || value.chars().any(char::is_control)
31        {
32            return Err(ParseError::MailboxPath);
33        }
34        Ok(Self(value.to_owned()))
35    }
36}
37
38impl fmt::Display for MailboxPath {
39    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
40        f.write_str(self.as_str())
41    }
42}
43
44/// An IMAP UID. Zero is never a valid UID.
45#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
46pub struct Uid(NonZeroU32);
47
48impl Uid {
49    /// Returns the UID as a `u32`.
50    #[must_use]
51    pub const fn get(self) -> u32 {
52        self.0.get()
53    }
54}
55
56impl TryFrom<u32> for Uid {
57    type Error = ParseError;
58
59    fn try_from(value: u32) -> Result<Self, Self::Error> {
60        NonZeroU32::new(value).map(Self).ok_or(ParseError::Uid)
61    }
62}
63
64impl fmt::Display for Uid {
65    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
66        write!(f, "{}", self.get())
67    }
68}
69
70/// An IMAP UIDVALIDITY. Zero is never valid.
71#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
72pub struct UidValidity(NonZeroU32);
73
74impl UidValidity {
75    /// Returns the UIDVALIDITY as a `u32`.
76    #[must_use]
77    pub const fn get(self) -> u32 {
78        self.0.get()
79    }
80}
81
82impl TryFrom<u32> for UidValidity {
83    type Error = ParseError;
84
85    fn try_from(value: u32) -> Result<Self, Self::Error> {
86        NonZeroU32::new(value).map(Self).ok_or(ParseError::Uid)
87    }
88}
89
90impl fmt::Display for UidValidity {
91    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
92        write!(f, "{}", self.get())
93    }
94}
95
96/// A mail id: mailbox path, `UIDVALIDITY` and `UID`.
97///
98/// The wire form is an opaque base64url token from [`crate::encode`]. It carries no host.
99#[derive(Clone, PartialEq, Eq, Hash, Debug)]
100pub struct MessageId {
101    /// Mailbox the message lives in.
102    pub mailbox: MailboxPath,
103    /// `UIDVALIDITY` of that mailbox at the time the id was issued.
104    pub validity: UidValidity,
105    /// IMAP `UID`.
106    pub uid: Uid,
107}
108
109/// Which well-known mailbox a path plays, when the server says.
110#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
111#[non_exhaustive]
112pub enum MailboxRole {
113    /// Inbox.
114    Inbox,
115    /// Sent messages.
116    Sent,
117    /// Drafts.
118    Drafts,
119    /// Trash.
120    Trash,
121    /// Junk.
122    Junk,
123    /// Archive.
124    Archive,
125    /// Notes stored as mail.
126    Notes,
127    /// A mailbox with no special role.
128    Other,
129}
130
131/// One mailbox and its counts.
132#[derive(Clone, Debug, PartialEq, Eq)]
133pub struct Mailbox {
134    /// Mailbox path.
135    pub path: MailboxPath,
136    /// Special-use role, or [`MailboxRole::Other`].
137    pub role: MailboxRole,
138    /// Messages in the mailbox.
139    pub total: u32,
140    /// Messages that are not seen.
141    pub unread: u32,
142}
143
144/// A search over one mailbox or role.
145#[derive(Clone, Debug, PartialEq, Eq)]
146pub struct MailSearch {
147    /// Restrict to this mailbox path.
148    pub mailbox: Option<MailboxPath>,
149    /// Restrict to this role.
150    pub role: Option<MailboxRole>,
151    /// From header contains this text.
152    pub from: Option<String>,
153    /// To header contains this text.
154    pub to: Option<String>,
155    /// Subject contains this text.
156    pub subject: Option<String>,
157    /// Body or subject contains this text.
158    pub text: Option<String>,
159    /// Messages on or after this ISO-8601 date.
160    pub since: Option<String>,
161    /// Messages before this ISO-8601 date.
162    pub before: Option<String>,
163    /// When true, only unseen messages.
164    pub unread_only: bool,
165    /// When true, only flagged messages.
166    pub flagged_only: bool,
167    /// Page size. Callers cap this at 100.
168    pub limit: u32,
169    /// Opaque cursor from the previous page.
170    pub cursor: Option<String>,
171}
172
173/// One hit from [`MailProvider::search`].
174#[derive(Clone, Debug, PartialEq, Eq)]
175pub struct MessageSummary {
176    /// Opaque message id.
177    pub id: MessageId,
178    /// From header.
179    pub from: String,
180    /// Subject.
181    pub subject: String,
182    /// Date header, as text.
183    pub date: String,
184    /// The message is unseen.
185    pub unread: bool,
186    /// The message is flagged.
187    pub flagged: bool,
188}
189
190/// A page of search hits.
191#[derive(Clone, Debug, PartialEq, Eq)]
192pub struct MailPage {
193    /// Hits, newest first.
194    pub messages: Vec<MessageSummary>,
195    /// Present when another page exists.
196    pub next_cursor: Option<String>,
197}
198
199/// An attachment listed on a message.
200#[derive(Clone, Debug, PartialEq, Eq)]
201pub struct AttachmentInfo {
202    /// Part identifier the provider understands.
203    pub part: String,
204    /// MIME type.
205    pub content_type: String,
206    /// Size in bytes.
207    pub size: u64,
208    /// File name, when the message has one.
209    pub name: String,
210}
211
212/// A fetched message.
213#[derive(Clone, Debug, PartialEq, Eq)]
214pub struct Message {
215    /// Opaque message id.
216    pub id: MessageId,
217    /// From header.
218    pub from: String,
219    /// To headers.
220    pub to: Vec<String>,
221    /// Subject.
222    pub subject: String,
223    /// Date header, as text.
224    pub date: String,
225    /// Body as text.
226    pub body: String,
227    /// Attachments, without their bytes.
228    pub attachments: Vec<AttachmentInfo>,
229    /// How the sender lets a reader unsubscribe, from `List-Unsubscribe`.
230    pub unsubscribe: Option<Unsubscribe>,
231}
232
233/// A mailto unsubscribe target from `List-Unsubscribe`, already checked.
234///
235/// Only `to`, `subject` and `body` survive. Every value is free of CR and LF and under
236/// its cap, so it is safe to put in a message.
237#[derive(Clone, Debug, PartialEq, Eq)]
238pub struct UnsubscribeMail {
239    /// The one recipient.
240    pub to: String,
241    /// Subject the sender asked for.
242    pub subject: Option<String>,
243    /// Body the sender asked for.
244    pub body: Option<String>,
245}
246
247/// How a sender lets a reader unsubscribe (RFC 2369, RFC 8058).
248///
249/// The header is written by the sender, so nothing here is trusted: tools take a message
250/// id and read this themselves, never a URL or an address from a caller.
251#[derive(Clone, Debug, Default, PartialEq, Eq)]
252pub struct Unsubscribe {
253    /// The mailto route, when the header has one that passed every check.
254    pub mailto: Option<UnsubscribeMail>,
255    /// `http` and `https` links, in header order.
256    pub links: Vec<String>,
257    /// `List-Unsubscribe-Post` asks for `List-Unsubscribe=One-Click` and an `https` link exists.
258    pub one_click: bool,
259}
260
261/// Why a one-click unsubscribe POST failed. Never carries server text.
262#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
263#[non_exhaustive]
264pub enum OneClickFailure {
265    /// The link is not a plain `https` link on port 443 without credentials.
266    #[error("the link is not a plain https link on port 443")]
267    InvalidLink,
268    /// The link's host is a private, local or otherwise non-public address, so it was not contacted.
269    #[error("the link points to a private or local network address, so it was not contacted")]
270    Blocked,
271    /// The sender's server could not be found or connected to.
272    #[error("the sender's server could not be reached")]
273    Unreachable,
274    /// The sender's server did not present a valid certificate for its name.
275    #[error("the sender's server did not present a valid certificate")]
276    Tls,
277    /// The sender's server did not answer in time.
278    #[error("the sender's server did not answer in time")]
279    Timeout,
280    /// The sender's server answered with a redirect, which is never followed.
281    #[error("the sender's server redirected the request, and redirects are not followed")]
282    Redirected,
283    /// The sender's server answered with an error status.
284    #[error("the sender's server refused the request")]
285    Rejected,
286    /// The sender's server sent a reply that is not valid HTTP.
287    #[error("the sender's server sent a reply that is not valid HTTP")]
288    BadResponse,
289}
290
291/// One way to unsubscribe.
292#[derive(Clone, Copy, Debug, PartialEq, Eq)]
293#[non_exhaustive]
294pub enum UnsubscribeMethod {
295    /// Send an email to the sender's address.
296    Mailto,
297    /// Post to the sender's `https` link without opening it.
298    OneClick,
299    /// Open a link in a browser.
300    Link,
301}
302
303impl Unsubscribe {
304    /// The `https` link a one-click POST goes to: the first one, when `List-Unsubscribe-Post`
305    /// asked for one-click. `None` otherwise, so a plain link is never posted to.
306    #[must_use]
307    pub fn one_click_link(&self) -> Option<&str> {
308        self.one_click
309            .then(|| {
310                self.links.iter().map(String::as_str).find(|link| {
311                    link.get(..8)
312                        .is_some_and(|head| head.eq_ignore_ascii_case("https://"))
313                })
314            })
315            .flatten()
316    }
317
318    /// The methods on offer, best first: one-click, then mailto, then a link.
319    #[must_use]
320    pub fn methods(&self) -> Vec<UnsubscribeMethod> {
321        let mut methods = Vec::new();
322        if self.one_click {
323            methods.push(UnsubscribeMethod::OneClick);
324        }
325        if self.mailto.is_some() {
326            methods.push(UnsubscribeMethod::Mailto);
327        }
328        if !self.links.is_empty() {
329            methods.push(UnsubscribeMethod::Link);
330        }
331        methods
332    }
333}
334
335/// A fetched attachment.
336#[derive(Clone, Debug, PartialEq, Eq)]
337pub struct Attachment {
338    /// The part that was fetched.
339    pub info: AttachmentInfo,
340    /// Extracted text, for a text-like part.
341    pub text: Option<String>,
342    /// Raw bytes, only when the part is small enough to return inline.
343    pub bytes: Option<Vec<u8>>,
344}
345
346/// A draft or a message to send.
347#[derive(Clone, Debug, PartialEq, Eq)]
348pub struct Draft {
349    /// Recipients.
350    pub to: Vec<String>,
351    /// Subject.
352    pub subject: String,
353    /// Body as text.
354    pub body: String,
355    /// `From` when it is not the account's Apple ID. A custom domain is allowed.
356    pub from: Option<String>,
357    /// Message this draft replies to.
358    pub reply_to: Option<MessageId>,
359}
360
361/// Flags to set or clear. `None` leaves a flag unchanged.
362#[derive(Clone, Copy, Debug, PartialEq, Eq)]
363pub struct FlagChange {
364    /// Seen flag.
365    pub seen: Option<bool>,
366    /// Flagged flag.
367    pub flagged: Option<bool>,
368}
369
370/// Mail read and write operations.
371#[trait_variant::make(Send)]
372pub trait MailProvider {
373    /// Lists mailboxes.
374    ///
375    /// # Errors
376    ///
377    /// Returns [`CoreError`] when the mailbox list cannot be read.
378    async fn list_mailboxes(&self) -> Result<Vec<Mailbox>, CoreError>;
379
380    /// Searches messages.
381    ///
382    /// # Errors
383    ///
384    /// Returns [`CoreError`] when the search cannot be run.
385    async fn search(&self, query: &MailSearch) -> Result<MailPage, CoreError>;
386
387    /// Fetches one message.
388    ///
389    /// # Errors
390    ///
391    /// Returns [`CoreError`] when the message cannot be read.
392    async fn get_message(&self, id: &MessageId) -> Result<Message, CoreError>;
393
394    /// Fetches one attachment.
395    ///
396    /// # Errors
397    ///
398    /// Returns [`CoreError`] when the part cannot be read.
399    async fn get_attachment(&self, id: &MessageId, part: &str) -> Result<Attachment, CoreError>;
400
401    /// Appends a draft.
402    ///
403    /// # Errors
404    ///
405    /// Returns [`CoreError`] when the draft cannot be saved.
406    async fn create_draft(&self, draft: &Draft) -> Result<MessageId, CoreError>;
407
408    /// Sends a message.
409    ///
410    /// # Errors
411    ///
412    /// Returns [`CoreError`] when the message cannot be sent.
413    async fn send(&self, draft: &Draft) -> Result<MessageId, CoreError>;
414
415    /// Moves a message to another mailbox.
416    ///
417    /// # Errors
418    ///
419    /// Returns [`CoreError`] when the move cannot be done.
420    async fn move_to(&self, id: &MessageId, destination: &MailboxPath) -> Result<(), CoreError>;
421
422    /// Sets or clears flags.
423    ///
424    /// # Errors
425    ///
426    /// Returns [`CoreError`] when the flags cannot be stored.
427    async fn set_flags(&self, id: &MessageId, flags: &FlagChange) -> Result<(), CoreError>;
428}