use async_trait::async_trait;
use chrono::{DateTime, NaiveDate, Utc};
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::event::{Event, EventTime};
use crate::message::{Attachment, FullMessage, MessageFrom};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum ProviderKind {
#[default]
Microsoft,
Google,
}
impl ProviderKind {
pub fn is_microsoft(&self) -> bool {
*self == Self::Microsoft
}
pub fn as_str(self) -> &'static str {
match self {
Self::Microsoft => "microsoft",
Self::Google => "google",
}
}
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Folder {
Inbox,
Archive,
Sent,
Drafts,
Deleted,
Junk,
Other(String),
}
impl Folder {
pub fn key(&self) -> String {
match self {
Self::Inbox => "inbox".into(),
Self::Archive => "archive".into(),
Self::Sent => "sent".into(),
Self::Drafts => "drafts".into(),
Self::Deleted => "deleted".into(),
Self::Junk => "junk".into(),
Self::Other(id) => format!("folder:{id}"),
}
}
pub fn from_key(s: &str) -> Self {
match s.to_ascii_lowercase().as_str() {
"inbox" => Self::Inbox,
"archive" => Self::Archive,
"sent" => Self::Sent,
"drafts" => Self::Drafts,
"deleted" | "trash" => Self::Deleted,
"junk" | "spam" => Self::Junk,
_ => Self::Other(s.strip_prefix("folder:").unwrap_or(s).to_string()),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum BulkHint {
Focused,
Other,
Primary,
Promotions,
Social,
Updates,
Forums,
}
impl BulkHint {
pub fn as_str(self) -> &'static str {
match self {
Self::Focused => "focused",
Self::Other => "other",
Self::Primary => "primary",
Self::Promotions => "promotions",
Self::Social => "social",
Self::Updates => "updates",
Self::Forums => "forums",
}
}
pub fn parse(s: &str) -> Option<Self> {
Some(match s {
"focused" => Self::Focused,
"other" => Self::Other,
"primary" => Self::Primary,
"promotions" => Self::Promotions,
"social" => Self::Social,
"updates" => Self::Updates,
"forums" => Self::Forums,
_ => return None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MailItem {
pub account: String,
pub id: String,
pub thread_id: String,
pub folder: Folder,
pub from: MessageFrom,
#[serde(default)]
pub to: Vec<MessageFrom>,
#[serde(default)]
pub cc: Vec<MessageFrom>,
pub subject: String,
pub received_at: DateTime<Utc>,
pub preview: String,
pub unread: bool,
pub flagged: bool,
pub has_attachments: bool,
#[serde(default)]
pub categories: Vec<String>,
#[serde(default)]
pub bulk_hint: Option<BulkHint>,
#[serde(default)]
pub list_unsubscribe: bool,
#[serde(default)]
pub is_invite: bool,
#[serde(default)]
pub message_id: String,
}
#[derive(Debug, Clone, Default)]
pub struct MailSync {
pub upserts: Vec<MailItem>,
pub removed: Vec<String>,
pub cursor: String,
pub more: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SearchQuery {
pub text: Option<String>,
pub from: Option<String>,
pub subject: Option<String>,
pub after: Option<NaiveDate>,
pub before: Option<NaiveDate>,
pub has_attachments: Option<bool>,
pub folder: Option<Folder>,
pub unread: Option<bool>,
pub limit: usize,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "op", rename_all = "snake_case")]
pub enum MailChange {
MarkRead,
MarkUnread,
Flag {
due: Option<NaiveDate>,
},
Unflag,
Move {
to: Folder,
},
SetCategories {
categories: Vec<String>,
},
Delete,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum DraftKind {
New,
Reply { to_id: String },
ReplyAll { to_id: String },
Forward { to_id: String },
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct DraftSpec {
pub kind: DraftKind,
#[serde(default)]
pub to: Vec<MessageFrom>,
#[serde(default)]
pub cc: Vec<MessageFrom>,
#[serde(default)]
pub bcc: Vec<MessageFrom>,
pub subject: Option<String>,
pub body: String,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Draft {
pub account: String,
pub id: String,
pub thread_id: Option<String>,
pub to: Vec<MessageFrom>,
pub cc: Vec<MessageFrom>,
pub bcc: Vec<MessageFrom>,
pub subject: String,
pub body_text: String,
pub has_attachments: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct FolderInfo {
pub folder: Folder,
pub path: String,
pub unread: u32,
pub total: u32,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct UnsubscribeHeaders {
pub list_unsubscribe: Option<String>,
pub list_unsubscribe_post: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct EventSpec {
pub title: String,
pub when: EventWhen,
pub location: Option<String>,
pub body: Option<String>,
#[serde(default)]
pub attendees: Vec<MessageFrom>,
#[serde(default)]
pub online_meeting: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum EventWhen {
Timed { start: EventTime, end: EventTime },
AllDay { first: NaiveDate, last: NaiveDate },
}
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
pub struct EventPatch {
pub title: Option<String>,
pub when: Option<EventWhen>,
pub location: Option<String>,
pub body: Option<String>,
pub attendees: Option<Vec<MessageFrom>>,
pub online_meeting: Option<bool>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Rsvp {
Accept,
Tentative,
Decline,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct BusyBlock {
pub start: DateTime<Utc>,
pub end: DateTime<Utc>,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct PersonHint {
pub name: String,
pub address: String,
}
#[derive(Debug, Clone, Error, PartialEq, Eq)]
pub enum ProviderError {
#[error("{account} needs to sign in again: {message}")]
Auth { account: String, message: String },
#[error("not found: {0}")]
NotFound(String),
#[error("throttled by the provider")]
Throttled { retry_after: Option<u64> },
#[error("not supported: {0}")]
Unsupported(String),
#[error("{0}")]
Invalid(String),
#[error("sync state expired")]
CursorExpired,
#[error("{0}")]
Other(String),
}
pub type ProviderResult<T> = Result<T, ProviderError>;
#[async_trait]
pub trait Provider: Send + Sync {
fn kind(&self) -> ProviderKind;
fn address(&self) -> &str;
async fn sync_mail(
&self,
since: DateTime<Utc>,
cursor: Option<&str>,
) -> ProviderResult<MailSync>;
async fn search(&self, query: &SearchQuery) -> ProviderResult<Vec<MailItem>>;
async fn get_items(&self, ids: &[String]) -> ProviderResult<Vec<MailItem>>;
async fn find_by_message_id(&self, _message_id: &str) -> ProviderResult<Vec<MailItem>> {
Ok(Vec::new())
}
async fn get_message(&self, id: &str) -> ProviderResult<FullMessage>;
async fn get_thread(&self, thread_id: &str) -> ProviderResult<Vec<FullMessage>>;
async fn unsubscribe_headers(&self, id: &str) -> ProviderResult<UnsubscribeHeaders>;
async fn message_headers(&self, id: &str) -> ProviderResult<Vec<(String, String)>>;
async fn apply(&self, ids: &[String], change: &MailChange) -> Vec<ProviderResult<()>>;
async fn list_folders(&self) -> ProviderResult<Vec<FolderInfo>>;
async fn ensure_folder(&self, path: &str) -> ProviderResult<Folder>;
async fn list_categories(&self) -> ProviderResult<Vec<String>>;
async fn ensure_category(&self, name: &str) -> ProviderResult<()>;
async fn list_attachments(&self, id: &str) -> ProviderResult<Vec<Attachment>>;
async fn attachment_bytes(&self, id: &str, attachment_id: &str) -> ProviderResult<Vec<u8>>;
async fn create_draft(&self, spec: &DraftSpec) -> ProviderResult<Draft>;
async fn update_draft(&self, id: &str, spec: &DraftSpec) -> ProviderResult<Draft>;
async fn get_draft(&self, id: &str) -> ProviderResult<Draft>;
async fn delete_draft(&self, id: &str) -> ProviderResult<()>;
async fn send_draft(&self, id: &str) -> ProviderResult<()>;
async fn people(&self) -> ProviderResult<Vec<PersonHint>> {
Ok(Vec::new())
}
async fn list_events(
&self,
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> ProviderResult<Vec<Event>>;
async fn get_event(&self, id: &str) -> ProviderResult<Event>;
async fn create_event(&self, spec: &EventSpec) -> ProviderResult<Event>;
async fn update_event(&self, id: &str, patch: &EventPatch) -> ProviderResult<Event>;
async fn cancel_event(&self, id: &str, message: Option<&str>) -> ProviderResult<()>;
async fn delete_event(&self, id: &str) -> ProviderResult<()>;
async fn respond(
&self,
id: &str,
response: Rsvp,
message: Option<&str>,
notify: bool,
) -> ProviderResult<()>;
async fn free_busy(
&self,
people: &[String],
from: DateTime<Utc>,
to: DateTime<Utc>,
) -> ProviderResult<Vec<(String, Vec<BusyBlock>)>>;
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn folder_keys_round_trip() {
for f in [
Folder::Inbox,
Folder::Archive,
Folder::Sent,
Folder::Drafts,
Folder::Deleted,
Folder::Junk,
Folder::Other("AAMk=".into()),
] {
assert_eq!(Folder::from_key(&f.key()), f);
}
assert_eq!(Folder::from_key("Trash"), Folder::Deleted);
}
#[test]
fn bulk_hints_round_trip() {
for h in [
BulkHint::Focused,
BulkHint::Other,
BulkHint::Primary,
BulkHint::Promotions,
BulkHint::Social,
BulkHint::Updates,
BulkHint::Forums,
] {
assert_eq!(BulkHint::parse(h.as_str()), Some(h));
}
}
#[test]
fn mail_change_serializes_tagged() {
let j = serde_json::to_string(&MailChange::Move {
to: Folder::Archive,
})
.unwrap();
assert_eq!(j, r#"{"op":"move","to":"archive"}"#);
}
}