1use 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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
20#[serde(rename_all = "lowercase")]
21pub enum ProviderKind {
22 #[default]
24 Microsoft,
25 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#[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 Other(String),
55}
56
57impl Folder {
58 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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
127pub struct MailItem {
128 pub account: String,
129 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 #[serde(default)]
151 pub list_unsubscribe: bool,
152 #[serde(default)]
153 pub is_invite: bool,
154 #[serde(default)]
157 pub message_id: String,
158}
159
160#[derive(Debug, Clone, Default)]
162pub struct MailSync {
163 pub upserts: Vec<MailItem>,
165 pub removed: Vec<String>,
168 pub cursor: String,
170 pub more: bool,
172}
173
174#[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#[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 SetCategories {
203 categories: Vec<String>,
204 },
205 Delete,
207}
208
209#[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#[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 pub subject: Option<String>,
232 pub body: String,
234}
235
236#[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 pub body_text: String,
248 pub has_attachments: bool,
249}
250
251#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
253pub struct FolderInfo {
254 pub folder: Folder,
255 pub path: String,
257 pub unread: u32,
258 pub total: u32,
259}
260
261#[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#[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#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
312pub struct BusyBlock {
313 pub start: DateTime<Utc>,
314 pub end: DateTime<Utc>,
315}
316
317#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
319pub struct PersonHint {
320 pub name: String,
321 pub address: String,
322}
323
324#[derive(Debug, Clone, Error, PartialEq, Eq)]
326pub enum ProviderError {
327 #[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 #[error("not supported: {0}")]
336 Unsupported(String),
337 #[error("{0}")]
339 Invalid(String),
340 #[error("sync state expired")]
342 CursorExpired,
343 #[error("{0}")]
344 Other(String),
345}
346
347pub type ProviderResult<T> = Result<T, ProviderError>;
348
349#[async_trait]
356pub trait Provider: Send + Sync {
357 fn kind(&self) -> ProviderKind;
358 fn address(&self) -> &str;
360
361 async fn sync_mail(
367 &self,
368 since: DateTime<Utc>,
369 cursor: Option<&str>,
370 ) -> ProviderResult<MailSync>;
371
372 async fn search(&self, query: &SearchQuery) -> ProviderResult<Vec<MailItem>>;
374
375 async fn get_items(&self, ids: &[String]) -> ProviderResult<Vec<MailItem>>;
377
378 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 async fn get_thread(&self, thread_id: &str) -> ProviderResult<Vec<FullMessage>>;
389
390 async fn unsubscribe_headers(&self, id: &str) -> ProviderResult<UnsubscribeHeaders>;
391
392 async fn message_headers(&self, id: &str) -> ProviderResult<Vec<(String, String)>>;
395
396 async fn apply(&self, ids: &[String], change: &MailChange) -> Vec<ProviderResult<()>>;
398
399 async fn list_folders(&self) -> ProviderResult<Vec<FolderInfo>>;
400
401 async fn ensure_folder(&self, path: &str) -> ProviderResult<Folder>;
403
404 async fn list_categories(&self) -> ProviderResult<Vec<String>>;
406
407 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 async fn people(&self) -> ProviderResult<Vec<PersonHint>> {
427 Ok(Vec::new())
428 }
429
430 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 async fn create_event(&self, spec: &EventSpec) -> ProviderResult<Event>;
443
444 async fn update_event(&self, id: &str, patch: &EventPatch) -> ProviderResult<Event>;
445
446 async fn cancel_event(&self, id: &str, message: Option<&str>) -> ProviderResult<()>;
448
449 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 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}