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}
155
156#[derive(Debug, Clone, Default)]
158pub struct MailSync {
159 pub upserts: Vec<MailItem>,
161 pub removed: Vec<String>,
164 pub cursor: String,
166 pub more: bool,
168}
169
170#[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#[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 SetCategories {
199 categories: Vec<String>,
200 },
201 Delete,
203}
204
205#[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#[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 pub subject: Option<String>,
228 pub body: String,
230}
231
232#[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 pub body_text: String,
244 pub has_attachments: bool,
245}
246
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
249pub struct FolderInfo {
250 pub folder: Folder,
251 pub path: String,
253 pub unread: u32,
254 pub total: u32,
255}
256
257#[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#[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#[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#[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#[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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
308pub struct BusyBlock {
309 pub start: DateTime<Utc>,
310 pub end: DateTime<Utc>,
311}
312
313#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
315pub struct PersonHint {
316 pub name: String,
317 pub address: String,
318}
319
320#[derive(Debug, Clone, Error, PartialEq, Eq)]
322pub enum ProviderError {
323 #[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 #[error("not supported: {0}")]
332 Unsupported(String),
333 #[error("{0}")]
335 Invalid(String),
336 #[error("sync state expired")]
338 CursorExpired,
339 #[error("{0}")]
340 Other(String),
341}
342
343pub type ProviderResult<T> = Result<T, ProviderError>;
344
345#[async_trait]
352pub trait Provider: Send + Sync {
353 fn kind(&self) -> ProviderKind;
354 fn address(&self) -> &str;
356
357 async fn sync_mail(
363 &self,
364 since: DateTime<Utc>,
365 cursor: Option<&str>,
366 ) -> ProviderResult<MailSync>;
367
368 async fn search(&self, query: &SearchQuery) -> ProviderResult<Vec<MailItem>>;
370
371 async fn get_items(&self, ids: &[String]) -> ProviderResult<Vec<MailItem>>;
373
374 async fn get_message(&self, id: &str) -> ProviderResult<FullMessage>;
375
376 async fn get_thread(&self, thread_id: &str) -> ProviderResult<Vec<FullMessage>>;
378
379 async fn unsubscribe_headers(&self, id: &str) -> ProviderResult<UnsubscribeHeaders>;
380
381 async fn message_headers(&self, id: &str) -> ProviderResult<Vec<(String, String)>>;
384
385 async fn apply(&self, ids: &[String], change: &MailChange) -> Vec<ProviderResult<()>>;
387
388 async fn list_folders(&self) -> ProviderResult<Vec<FolderInfo>>;
389
390 async fn ensure_folder(&self, path: &str) -> ProviderResult<Folder>;
392
393 async fn list_categories(&self) -> ProviderResult<Vec<String>>;
395
396 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 async fn people(&self) -> ProviderResult<Vec<PersonHint>> {
416 Ok(Vec::new())
417 }
418
419 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 async fn create_event(&self, spec: &EventSpec) -> ProviderResult<Event>;
432
433 async fn update_event(&self, id: &str, patch: &EventPatch) -> ProviderResult<Event>;
434
435 async fn cancel_event(&self, id: &str, message: Option<&str>) -> ProviderResult<()>;
437
438 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 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}