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}
155
156/// One round of mailbox sync.
157#[derive(Debug, Clone, Default)]
158pub struct MailSync {
159    /// New or changed messages (folder moves included).
160    pub upserts: Vec<MailItem>,
161    /// Ids that left the synced window (deleted for good, or moved out of
162    /// every tracked folder).
163    pub removed: Vec<String>,
164    /// Opaque cursor for the next call.
165    pub cursor: String,
166    /// More changes are waiting: call again with `cursor` at once.
167    pub more: bool,
168}
169
170/// Search beyond the index (and the only search for old mail).
171#[derive(Debug, Clone, Default, Serialize, Deserialize)]
172pub struct SearchQuery {
173    pub text: Option<String>,
174    pub from: Option<String>,
175    pub subject: Option<String>,
176    pub after: Option<NaiveDate>,
177    pub before: Option<NaiveDate>,
178    pub has_attachments: Option<bool>,
179    pub folder: Option<Folder>,
180    pub unread: Option<bool>,
181    pub limit: usize,
182}
183
184/// A change to one or more messages.
185#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
186#[serde(tag = "op", rename_all = "snake_case")]
187pub enum MailChange {
188    MarkRead,
189    MarkUnread,
190    Flag {
191        due: Option<NaiveDate>,
192    },
193    Unflag,
194    Move {
195        to: Folder,
196    },
197    /// Replace the message's categories (labels) with exactly these names.
198    SetCategories {
199        categories: Vec<String>,
200    },
201    /// To Deleted Items / Trash. Never permanent.
202    Delete,
203}
204
205/// What kind of draft to make.
206#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
207#[serde(tag = "kind", rename_all = "snake_case")]
208pub enum DraftKind {
209    New,
210    Reply { to_id: String },
211    ReplyAll { to_id: String },
212    Forward { to_id: String },
213}
214
215/// Draft content. Recipients are resolved addresses; on a reply they are
216/// *added* to what the provider fills in.
217#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
218pub struct DraftSpec {
219    pub kind: DraftKind,
220    #[serde(default)]
221    pub to: Vec<MessageFrom>,
222    #[serde(default)]
223    pub cc: Vec<MessageFrom>,
224    #[serde(default)]
225    pub bcc: Vec<MessageFrom>,
226    /// New mail only; replies and forwards keep the original's.
227    pub subject: Option<String>,
228    /// Plain text; blank lines separate paragraphs.
229    pub body: String,
230}
231
232/// A draft as the provider stored it.
233#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
234pub struct Draft {
235    pub account: String,
236    pub id: String,
237    pub thread_id: Option<String>,
238    pub to: Vec<MessageFrom>,
239    pub cc: Vec<MessageFrom>,
240    pub bcc: Vec<MessageFrom>,
241    pub subject: String,
242    /// The body as it will go out, quoted history included, as text.
243    pub body_text: String,
244    pub has_attachments: bool,
245}
246
247/// A folder or label, for listing and moving.
248#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249pub struct FolderInfo {
250    pub folder: Folder,
251    /// Display path, `/`-separated for nested folders.
252    pub path: String,
253    pub unread: u32,
254    pub total: u32,
255}
256
257/// `List-Unsubscribe` and `List-Unsubscribe-Post`, raw.
258#[derive(Debug, Clone, Default, PartialEq, Eq)]
259pub struct UnsubscribeHeaders {
260    pub list_unsubscribe: Option<String>,
261    pub list_unsubscribe_post: Option<String>,
262}
263
264/// A new event.
265#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
266pub struct EventSpec {
267    pub title: String,
268    pub when: EventWhen,
269    pub location: Option<String>,
270    pub body: Option<String>,
271    #[serde(default)]
272    pub attendees: Vec<MessageFrom>,
273    #[serde(default)]
274    pub online_meeting: bool,
275}
276
277/// An event's time: timed in a zone, or whole days (end inclusive).
278#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
279#[serde(tag = "type", rename_all = "snake_case")]
280pub enum EventWhen {
281    Timed { start: EventTime, end: EventTime },
282    AllDay { first: NaiveDate, last: NaiveDate },
283}
284
285/// Fields to change on an event; `None` leaves a field alone. `attendees`
286/// is the full new list (the engine computes it from add/remove).
287#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
288pub struct EventPatch {
289    pub title: Option<String>,
290    pub when: Option<EventWhen>,
291    pub location: Option<String>,
292    pub body: Option<String>,
293    pub attendees: Option<Vec<MessageFrom>>,
294    pub online_meeting: Option<bool>,
295}
296
297/// An answer to an invitation.
298#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
299#[serde(rename_all = "lowercase")]
300pub enum Rsvp {
301    Accept,
302    Tentative,
303    Decline,
304}
305
306/// A busy block for free/busy.
307#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
308pub struct BusyBlock {
309    pub start: DateTime<Utc>,
310    pub end: DateTime<Utc>,
311}
312
313/// Someone the user corresponds with, from the provider's people API.
314#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315pub struct PersonHint {
316    pub name: String,
317    pub address: String,
318}
319
320/// Provider failures, mapped onto the categories the engine acts on.
321#[derive(Debug, Clone, Error, PartialEq, Eq)]
322pub enum ProviderError {
323    /// The account must sign in again.
324    #[error("{account} needs to sign in again: {message}")]
325    Auth { account: String, message: String },
326    #[error("not found: {0}")]
327    NotFound(String),
328    #[error("throttled by the provider")]
329    Throttled { retry_after: Option<u64> },
330    /// The provider cannot do this (e.g. free/busy on a personal account).
331    #[error("not supported: {0}")]
332    Unsupported(String),
333    /// The provider refused the input.
334    #[error("{0}")]
335    Invalid(String),
336    /// A sync cursor the provider no longer accepts: re-bootstrap.
337    #[error("sync state expired")]
338    CursorExpired,
339    #[error("{0}")]
340    Other(String),
341}
342
343pub type ProviderResult<T> = Result<T, ProviderError>;
344
345/// One mailbox (and its calendar) at one provider.
346///
347/// Implementations hold their own credentials; every call acts as
348/// [`Provider::address`]. They must never follow a URL taken from message
349/// content, and must keep ids confined to their own id alphabet before
350/// putting them in a request path.
351#[async_trait]
352pub trait Provider: Send + Sync {
353    fn kind(&self) -> ProviderKind;
354    /// The mailbox address.
355    fn address(&self) -> &str;
356
357    // ---- mail -------------------------------------------------------------
358
359    /// Sync the inbox, archive and sent mail received on or after `since`.
360    /// `cursor` is `None` to bootstrap, which returns everything in the
361    /// window as upserts (paged with `more`).
362    async fn sync_mail(
363        &self,
364        since: DateTime<Utc>,
365        cursor: Option<&str>,
366    ) -> ProviderResult<MailSync>;
367
368    /// Search the whole mailbox, newest first.
369    async fn search(&self, query: &SearchQuery) -> ProviderResult<Vec<MailItem>>;
370
371    /// Metadata of a few messages (a refresh after a change).
372    async fn get_items(&self, ids: &[String]) -> ProviderResult<Vec<MailItem>>;
373
374    async fn get_message(&self, id: &str) -> ProviderResult<FullMessage>;
375
376    /// The messages of a conversation, oldest first.
377    async fn get_thread(&self, thread_id: &str) -> ProviderResult<Vec<FullMessage>>;
378
379    async fn unsubscribe_headers(&self, id: &str) -> ProviderResult<UnsubscribeHeaders>;
380
381    /// Every internet header of a message, in the order the service gives
382    /// them.
383    async fn message_headers(&self, id: &str) -> ProviderResult<Vec<(String, String)>>;
384
385    /// Apply one change to many messages; one result per id, in order.
386    async fn apply(&self, ids: &[String], change: &MailChange) -> Vec<ProviderResult<()>>;
387
388    async fn list_folders(&self) -> ProviderResult<Vec<FolderInfo>>;
389
390    /// Find or create a folder by `/`-separated path; returns it.
391    async fn ensure_folder(&self, path: &str) -> ProviderResult<Folder>;
392
393    /// The mailbox's category (label) names.
394    async fn list_categories(&self) -> ProviderResult<Vec<String>>;
395
396    /// Make sure a category exists (idempotent).
397    async fn ensure_category(&self, name: &str) -> ProviderResult<()>;
398
399    async fn list_attachments(&self, id: &str) -> ProviderResult<Vec<Attachment>>;
400
401    async fn attachment_bytes(&self, id: &str, attachment_id: &str) -> ProviderResult<Vec<u8>>;
402
403    async fn create_draft(&self, spec: &DraftSpec) -> ProviderResult<Draft>;
404
405    async fn update_draft(&self, id: &str, spec: &DraftSpec) -> ProviderResult<Draft>;
406
407    async fn get_draft(&self, id: &str) -> ProviderResult<Draft>;
408
409    async fn delete_draft(&self, id: &str) -> ProviderResult<()>;
410
411    async fn send_draft(&self, id: &str) -> ProviderResult<()>;
412
413    /// People the user corresponds with, best first. Empty when the
414    /// provider has no such API (the engine also learns from the index).
415    async fn people(&self) -> ProviderResult<Vec<PersonHint>> {
416        Ok(Vec::new())
417    }
418
419    // ---- calendar ---------------------------------------------------------
420
421    /// Events overlapping `[from, to)`, recurring events expanded.
422    async fn list_events(
423        &self,
424        from: DateTime<Utc>,
425        to: DateTime<Utc>,
426    ) -> ProviderResult<Vec<Event>>;
427
428    async fn get_event(&self, id: &str) -> ProviderResult<Event>;
429
430    /// Create; invitations go out to attendees at once.
431    async fn create_event(&self, spec: &EventSpec) -> ProviderResult<Event>;
432
433    async fn update_event(&self, id: &str, patch: &EventPatch) -> ProviderResult<Event>;
434
435    /// Cancel an event the user organizes; attendees are notified.
436    async fn cancel_event(&self, id: &str, message: Option<&str>) -> ProviderResult<()>;
437
438    /// Delete an event from the user's calendar without notifying anyone.
439    async fn delete_event(&self, id: &str) -> ProviderResult<()>;
440
441    async fn respond(
442        &self,
443        id: &str,
444        response: Rsvp,
445        message: Option<&str>,
446        notify: bool,
447    ) -> ProviderResult<()>;
448
449    /// Busy blocks for other people. `Unsupported` where the account type
450    /// cannot see others' calendars.
451    async fn free_busy(
452        &self,
453        people: &[String],
454        from: DateTime<Utc>,
455        to: DateTime<Utc>,
456    ) -> ProviderResult<Vec<(String, Vec<BusyBlock>)>>;
457}
458
459#[cfg(test)]
460mod tests {
461    use super::*;
462
463    #[test]
464    fn folder_keys_round_trip() {
465        for f in [
466            Folder::Inbox,
467            Folder::Archive,
468            Folder::Sent,
469            Folder::Drafts,
470            Folder::Deleted,
471            Folder::Junk,
472            Folder::Other("AAMk=".into()),
473        ] {
474            assert_eq!(Folder::from_key(&f.key()), f);
475        }
476        assert_eq!(Folder::from_key("Trash"), Folder::Deleted);
477    }
478
479    #[test]
480    fn bulk_hints_round_trip() {
481        for h in [
482            BulkHint::Focused,
483            BulkHint::Other,
484            BulkHint::Primary,
485            BulkHint::Promotions,
486            BulkHint::Social,
487            BulkHint::Updates,
488            BulkHint::Forums,
489        ] {
490            assert_eq!(BulkHint::parse(h.as_str()), Some(h));
491        }
492    }
493
494    #[test]
495    fn mail_change_serializes_tagged() {
496        let j = serde_json::to_string(&MailChange::Move {
497            to: Folder::Archive,
498        })
499        .unwrap();
500        assert_eq!(j, r#"{"op":"move","to":"archive"}"#);
501    }
502}