Skip to main content

pidge_core/
provider.rs

1//! The provider seam: what pidge needs from a mail and calendar service.
2//!
3//! The engine (`pidge-engine`) talks only to [`Provider`]; `pidge-graph`
4//! (Microsoft 365 / Outlook.com) and `pidge-gmail` (Gmail + Google Calendar)
5//! implement it. Everything here is provider-neutral: a folder is a
6//! [`Folder`], a label or Outlook category is a category name, ids are the
7//! provider's own *stable* ids (Graph immutable ids, Gmail ids), opaque to the
8//! engine.
9
10use async_trait::async_trait;
11use chrono::{DateTime, NaiveDate, Utc};
12use serde::{Deserialize, Serialize};
13use thiserror::Error;
14
15use crate::event::{Event, EventTime};
16use crate::message::{Attachment, FullMessage, MessageFrom};
17
18/// Which service an account lives at.
19#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "lowercase")]
21pub enum ProviderKind {
22    /// Microsoft 365 work/school accounts and personal Microsoft accounts.
23    #[default]
24    Microsoft,
25    /// Gmail and Google Calendar.
26    Google,
27}
28
29impl ProviderKind {
30    pub fn is_microsoft(&self) -> bool {
31        *self == Self::Microsoft
32    }
33
34    pub fn as_str(self) -> &'static str {
35        match self {
36            Self::Microsoft => "microsoft",
37            Self::Google => "google",
38        }
39    }
40}
41
42/// A mail folder in provider-neutral terms. Gmail maps these onto labels
43/// (`Inbox` = has `INBOX`, `Archive` = none of the system folders).
44#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
45#[serde(rename_all = "lowercase")]
46pub enum Folder {
47    Inbox,
48    Archive,
49    Sent,
50    Drafts,
51    Deleted,
52    Junk,
53    /// A user folder (Graph folder id) or user label (Gmail label id).
54    Other(String),
55}
56
57impl Folder {
58    /// The name used in the index and in tool input.
59    pub fn key(&self) -> String {
60        match self {
61            Self::Inbox => "inbox".into(),
62            Self::Archive => "archive".into(),
63            Self::Sent => "sent".into(),
64            Self::Drafts => "drafts".into(),
65            Self::Deleted => "deleted".into(),
66            Self::Junk => "junk".into(),
67            Self::Other(id) => format!("folder:{id}"),
68        }
69    }
70
71    pub fn from_key(s: &str) -> Self {
72        match s.to_ascii_lowercase().as_str() {
73            "inbox" => Self::Inbox,
74            "archive" => Self::Archive,
75            "sent" => Self::Sent,
76            "drafts" => Self::Drafts,
77            "deleted" | "trash" => Self::Deleted,
78            "junk" | "spam" => Self::Junk,
79            _ => Self::Other(s.strip_prefix("folder:").unwrap_or(s).to_string()),
80        }
81    }
82}
83
84/// What the provider itself thinks of a message's bulkiness. Graph's
85/// Focused/Other and Gmail's inbox categories.
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
87#[serde(rename_all = "lowercase")]
88pub enum BulkHint {
89    Focused,
90    Other,
91    Primary,
92    Promotions,
93    Social,
94    Updates,
95    Forums,
96}
97
98impl BulkHint {
99    pub fn as_str(self) -> &'static str {
100        match self {
101            Self::Focused => "focused",
102            Self::Other => "other",
103            Self::Primary => "primary",
104            Self::Promotions => "promotions",
105            Self::Social => "social",
106            Self::Updates => "updates",
107            Self::Forums => "forums",
108        }
109    }
110
111    pub fn parse(s: &str) -> Option<Self> {
112        Some(match s {
113            "focused" => Self::Focused,
114            "other" => Self::Other,
115            "primary" => Self::Primary,
116            "promotions" => Self::Promotions,
117            "social" => Self::Social,
118            "updates" => Self::Updates,
119            "forums" => Self::Forums,
120            _ => return None,
121        })
122    }
123}
124
125/// A message's metadata: what the index stores and what lists show.
126#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127pub struct MailItem {
128    pub account: String,
129    /// The provider's stable id.
130    pub id: String,
131    pub thread_id: String,
132    pub folder: Folder,
133    pub from: MessageFrom,
134    #[serde(default)]
135    pub to: Vec<MessageFrom>,
136    #[serde(default)]
137    pub cc: Vec<MessageFrom>,
138    pub subject: String,
139    pub received_at: DateTime<Utc>,
140    pub preview: String,
141    pub unread: bool,
142    pub flagged: bool,
143    pub has_attachments: bool,
144    #[serde(default)]
145    pub categories: Vec<String>,
146    #[serde(default)]
147    pub bulk_hint: Option<BulkHint>,
148    /// The message carries a `List-Unsubscribe` header (when the provider
149    /// returns headers in lists; Gmail does, Graph does not).
150    #[serde(default)]
151    pub list_unsubscribe: bool,
152    #[serde(default)]
153    pub is_invite: bool,
154    /// The internet Message-ID, when the provider gives it: the same for a
155    /// message however the provider names it.
156    #[serde(default)]
157    pub message_id: String,
158}
159
160/// One round of mailbox sync.
161#[derive(Debug, Clone, Default)]
162pub struct MailSync {
163    /// New or changed messages (folder moves included).
164    pub upserts: Vec<MailItem>,
165    /// Ids that left the synced window (deleted for good, or moved out of
166    /// every tracked folder).
167    pub removed: Vec<String>,
168    /// Opaque cursor for the next call.
169    pub cursor: String,
170    /// More changes are waiting: call again with `cursor` at once.
171    pub more: bool,
172}
173
174/// Search beyond the index (and the only search for old mail).
175#[derive(Debug, Clone, Default, Serialize, Deserialize)]
176pub struct SearchQuery {
177    pub text: Option<String>,
178    pub from: Option<String>,
179    pub subject: Option<String>,
180    pub after: Option<NaiveDate>,
181    pub before: Option<NaiveDate>,
182    pub has_attachments: Option<bool>,
183    pub folder: Option<Folder>,
184    pub unread: Option<bool>,
185    pub limit: usize,
186}
187
188/// A change to one or more messages.
189#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
190#[serde(tag = "op", rename_all = "snake_case")]
191pub enum MailChange {
192    MarkRead,
193    MarkUnread,
194    Flag {
195        due: Option<NaiveDate>,
196    },
197    Unflag,
198    Move {
199        to: Folder,
200    },
201    /// Replace the message's categories (labels) with exactly these names.
202    SetCategories {
203        categories: Vec<String>,
204    },
205    /// To Deleted Items / Trash. Never permanent.
206    Delete,
207}
208
209/// What kind of draft to make.
210#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
211#[serde(tag = "kind", rename_all = "snake_case")]
212pub enum DraftKind {
213    New,
214    Reply { to_id: String },
215    ReplyAll { to_id: String },
216    Forward { to_id: String },
217}
218
219/// Draft content. Recipients are resolved addresses; on a reply they are
220/// *added* to what the provider fills in.
221#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
222pub struct DraftSpec {
223    pub kind: DraftKind,
224    #[serde(default)]
225    pub to: Vec<MessageFrom>,
226    #[serde(default)]
227    pub cc: Vec<MessageFrom>,
228    #[serde(default)]
229    pub bcc: Vec<MessageFrom>,
230    /// New mail only; replies and forwards keep the original's.
231    pub subject: Option<String>,
232    /// Plain text; blank lines separate paragraphs.
233    pub body: String,
234}
235
236/// A draft as the provider stored it.
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238pub struct Draft {
239    pub account: String,
240    pub id: String,
241    pub thread_id: Option<String>,
242    pub to: Vec<MessageFrom>,
243    pub cc: Vec<MessageFrom>,
244    pub bcc: Vec<MessageFrom>,
245    pub subject: String,
246    /// The body as it will go out, quoted history included, as text.
247    pub body_text: String,
248    pub has_attachments: bool,
249}
250
251/// A folder or label, for listing and moving.
252#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253pub struct FolderInfo {
254    pub folder: Folder,
255    /// Display path, `/`-separated for nested folders.
256    pub path: String,
257    pub unread: u32,
258    pub total: u32,
259}
260
261/// `List-Unsubscribe` and `List-Unsubscribe-Post`, raw.
262#[derive(Debug, Clone, Default, PartialEq, Eq)]
263pub struct UnsubscribeHeaders {
264    pub list_unsubscribe: Option<String>,
265    pub list_unsubscribe_post: Option<String>,
266}
267
268/// A new event.
269#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
270pub struct EventSpec {
271    pub title: String,
272    pub when: EventWhen,
273    pub location: Option<String>,
274    pub body: Option<String>,
275    #[serde(default)]
276    pub attendees: Vec<MessageFrom>,
277    #[serde(default)]
278    pub online_meeting: bool,
279}
280
281/// An event's time: timed in a zone, or whole days (end inclusive).
282#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
283#[serde(tag = "type", rename_all = "snake_case")]
284pub enum EventWhen {
285    Timed { start: EventTime, end: EventTime },
286    AllDay { first: NaiveDate, last: NaiveDate },
287}
288
289/// Fields to change on an event; `None` leaves a field alone. `attendees`
290/// is the full new list (the engine computes it from add/remove).
291#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
292pub struct EventPatch {
293    pub title: Option<String>,
294    pub when: Option<EventWhen>,
295    pub location: Option<String>,
296    pub body: Option<String>,
297    pub attendees: Option<Vec<MessageFrom>>,
298    pub online_meeting: Option<bool>,
299}
300
301/// An answer to an invitation.
302#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
303#[serde(rename_all = "lowercase")]
304pub enum Rsvp {
305    Accept,
306    Tentative,
307    Decline,
308}
309
310/// A busy block for free/busy.
311#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312pub struct BusyBlock {
313    pub start: DateTime<Utc>,
314    pub end: DateTime<Utc>,
315}
316
317/// Someone the user corresponds with, from the provider's people API.
318#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319pub struct PersonHint {
320    pub name: String,
321    pub address: String,
322}
323
324/// Provider failures, mapped onto the categories the engine acts on.
325#[derive(Debug, Clone, Error, PartialEq, Eq)]
326pub enum ProviderError {
327    /// The account must sign in again.
328    #[error("{account} needs to sign in again: {message}")]
329    Auth { account: String, message: String },
330    #[error("not found: {0}")]
331    NotFound(String),
332    #[error("throttled by the provider")]
333    Throttled { retry_after: Option<u64> },
334    /// The provider cannot do this (e.g. free/busy on a personal account).
335    #[error("not supported: {0}")]
336    Unsupported(String),
337    /// The provider refused the input.
338    #[error("{0}")]
339    Invalid(String),
340    /// A sync cursor the provider no longer accepts: re-bootstrap.
341    #[error("sync state expired")]
342    CursorExpired,
343    #[error("{0}")]
344    Other(String),
345}
346
347pub type ProviderResult<T> = Result<T, ProviderError>;
348
349/// One mailbox (and its calendar) at one provider.
350///
351/// Implementations hold their own credentials; every call acts as
352/// [`Provider::address`]. They must never follow a URL taken from message
353/// content, and must keep ids confined to their own id alphabet before
354/// putting them in a request path.
355#[async_trait]
356pub trait Provider: Send + Sync {
357    fn kind(&self) -> ProviderKind;
358    /// The mailbox address.
359    fn address(&self) -> &str;
360
361    // ---- mail -------------------------------------------------------------
362
363    /// Sync the inbox, archive and sent mail received on or after `since`.
364    /// `cursor` is `None` to bootstrap, which returns everything in the
365    /// window as upserts (paged with `more`).
366    async fn sync_mail(
367        &self,
368        since: DateTime<Utc>,
369        cursor: Option<&str>,
370    ) -> ProviderResult<MailSync>;
371
372    /// Search the whole mailbox, newest first.
373    async fn search(&self, query: &SearchQuery) -> ProviderResult<Vec<MailItem>>;
374
375    /// Metadata of a few messages (a refresh after a change).
376    async fn get_items(&self, ids: &[String]) -> ProviderResult<Vec<MailItem>>;
377
378    /// The messages with this internet Message-ID (the received copy and the
379    /// sent one can both have it), when the provider's ids can go stale and
380    /// it can look them up.
381    async fn find_by_message_id(&self, _message_id: &str) -> ProviderResult<Vec<MailItem>> {
382        Ok(Vec::new())
383    }
384
385    async fn get_message(&self, id: &str) -> ProviderResult<FullMessage>;
386
387    /// The messages of a conversation, oldest first.
388    async fn get_thread(&self, thread_id: &str) -> ProviderResult<Vec<FullMessage>>;
389
390    async fn unsubscribe_headers(&self, id: &str) -> ProviderResult<UnsubscribeHeaders>;
391
392    /// Every internet header of a message, in the order the service gives
393    /// them.
394    async fn message_headers(&self, id: &str) -> ProviderResult<Vec<(String, String)>>;
395
396    /// Apply one change to many messages; one result per id, in order.
397    async fn apply(&self, ids: &[String], change: &MailChange) -> Vec<ProviderResult<()>>;
398
399    async fn list_folders(&self) -> ProviderResult<Vec<FolderInfo>>;
400
401    /// Find or create a folder by `/`-separated path; returns it.
402    async fn ensure_folder(&self, path: &str) -> ProviderResult<Folder>;
403
404    /// The mailbox's category (label) names.
405    async fn list_categories(&self) -> ProviderResult<Vec<String>>;
406
407    /// Make sure a category exists (idempotent).
408    async fn ensure_category(&self, name: &str) -> ProviderResult<()>;
409
410    async fn list_attachments(&self, id: &str) -> ProviderResult<Vec<Attachment>>;
411
412    async fn attachment_bytes(&self, id: &str, attachment_id: &str) -> ProviderResult<Vec<u8>>;
413
414    async fn create_draft(&self, spec: &DraftSpec) -> ProviderResult<Draft>;
415
416    async fn update_draft(&self, id: &str, spec: &DraftSpec) -> ProviderResult<Draft>;
417
418    async fn get_draft(&self, id: &str) -> ProviderResult<Draft>;
419
420    async fn delete_draft(&self, id: &str) -> ProviderResult<()>;
421
422    async fn send_draft(&self, id: &str) -> ProviderResult<()>;
423
424    /// People the user corresponds with, best first. Empty when the
425    /// provider has no such API (the engine also learns from the index).
426    async fn people(&self) -> ProviderResult<Vec<PersonHint>> {
427        Ok(Vec::new())
428    }
429
430    // ---- calendar ---------------------------------------------------------
431
432    /// Events overlapping `[from, to)`, recurring events expanded.
433    async fn list_events(
434        &self,
435        from: DateTime<Utc>,
436        to: DateTime<Utc>,
437    ) -> ProviderResult<Vec<Event>>;
438
439    async fn get_event(&self, id: &str) -> ProviderResult<Event>;
440
441    /// Create; invitations go out to attendees at once.
442    async fn create_event(&self, spec: &EventSpec) -> ProviderResult<Event>;
443
444    async fn update_event(&self, id: &str, patch: &EventPatch) -> ProviderResult<Event>;
445
446    /// Cancel an event the user organizes; attendees are notified.
447    async fn cancel_event(&self, id: &str, message: Option<&str>) -> ProviderResult<()>;
448
449    /// Delete an event from the user's calendar without notifying anyone.
450    async fn delete_event(&self, id: &str) -> ProviderResult<()>;
451
452    async fn respond(
453        &self,
454        id: &str,
455        response: Rsvp,
456        message: Option<&str>,
457        notify: bool,
458    ) -> ProviderResult<()>;
459
460    /// Busy blocks for other people. `Unsupported` where the account type
461    /// cannot see others' calendars.
462    async fn free_busy(
463        &self,
464        people: &[String],
465        from: DateTime<Utc>,
466        to: DateTime<Utc>,
467    ) -> ProviderResult<Vec<(String, Vec<BusyBlock>)>>;
468}
469
470#[cfg(test)]
471mod tests {
472    use super::*;
473
474    #[test]
475    fn folder_keys_round_trip() {
476        for f in [
477            Folder::Inbox,
478            Folder::Archive,
479            Folder::Sent,
480            Folder::Drafts,
481            Folder::Deleted,
482            Folder::Junk,
483            Folder::Other("AAMk=".into()),
484        ] {
485            assert_eq!(Folder::from_key(&f.key()), f);
486        }
487        assert_eq!(Folder::from_key("Trash"), Folder::Deleted);
488    }
489
490    #[test]
491    fn bulk_hints_round_trip() {
492        for h in [
493            BulkHint::Focused,
494            BulkHint::Other,
495            BulkHint::Primary,
496            BulkHint::Promotions,
497            BulkHint::Social,
498            BulkHint::Updates,
499            BulkHint::Forums,
500        ] {
501            assert_eq!(BulkHint::parse(h.as_str()), Some(h));
502        }
503    }
504
505    #[test]
506    fn mail_change_serializes_tagged() {
507        let j = serde_json::to_string(&MailChange::Move {
508            to: Folder::Archive,
509        })
510        .unwrap();
511        assert_eq!(j, r#"{"op":"move","to":"archive"}"#);
512    }
513}