use alloc::{collections::BTreeMap, format, string::String, vec, vec::Vec};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
coroutine::*,
jmap_try,
rfc8620::{JMAP_CORE_CAPABILITY, request::JmapBatch, send::*, session::JmapSession, set::*},
rfc8621::{JMAP_MAIL_CAPABILITY, email::JmapEmail},
};
#[derive(Clone, Debug)]
pub enum JmapEmailPatchOp {
SetKeyword(String),
UnsetKeyword(String),
ReplaceKeywords(BTreeMap<String, bool>),
AddToMailbox(String),
RemoveFromMailbox(String),
ReplaceMailboxIds(BTreeMap<String, bool>),
}
#[derive(Clone, Debug, Default)]
pub struct JmapEmailPatch(pub Vec<JmapEmailPatchOp>);
impl JmapEmailPatch {
pub fn set_keyword(mut self, keyword: impl Into<String>) -> Self {
self.0.push(JmapEmailPatchOp::SetKeyword(keyword.into()));
self
}
pub fn unset_keyword(mut self, keyword: impl Into<String>) -> Self {
self.0.push(JmapEmailPatchOp::UnsetKeyword(keyword.into()));
self
}
pub fn replace_keywords(mut self, keywords: BTreeMap<String, bool>) -> Self {
self.0.push(JmapEmailPatchOp::ReplaceKeywords(keywords));
self
}
pub fn add_to_mailbox(mut self, id: impl Into<String>) -> Self {
self.0.push(JmapEmailPatchOp::AddToMailbox(id.into()));
self
}
pub fn remove_from_mailbox(mut self, id: impl Into<String>) -> Self {
self.0.push(JmapEmailPatchOp::RemoveFromMailbox(id.into()));
self
}
pub fn replace_mailbox_ids(mut self, ids: BTreeMap<String, bool>) -> Self {
self.0.push(JmapEmailPatchOp::ReplaceMailboxIds(ids));
self
}
}
impl Serialize for JmapEmailPatch {
fn serialize<S: serde::Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
use serde::ser::SerializeMap;
let mut map = s.serialize_map(Some(self.0.len()))?;
for op in &self.0 {
match op {
JmapEmailPatchOp::SetKeyword(kw) => {
map.serialize_entry(&format!("keywords/{kw}"), &true)?
}
JmapEmailPatchOp::UnsetKeyword(kw) => {
map.serialize_entry(&format!("keywords/{kw}"), &Option::<bool>::None)?
}
JmapEmailPatchOp::ReplaceKeywords(kws) => map.serialize_entry("keywords", kws)?,
JmapEmailPatchOp::AddToMailbox(id) => {
map.serialize_entry(&format!("mailboxIds/{id}"), &true)?
}
JmapEmailPatchOp::RemoveFromMailbox(id) => {
map.serialize_entry(&format!("mailboxIds/{id}"), &Option::<bool>::None)?
}
JmapEmailPatchOp::ReplaceMailboxIds(ids) => {
map.serialize_entry("mailboxIds", ids)?
}
}
}
map.end()
}
}
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum JmapEmailSetItemError {
TooManyKeywords {
description: Option<String>,
},
TooManyMailboxes {
description: Option<String>,
},
BlobNotFound {
description: Option<String>,
},
NotFound {
description: Option<String>,
},
InvalidPatch {
description: Option<String>,
},
WillDestroy {
description: Option<String>,
},
InvalidProperties {
description: Option<String>,
#[serde(default)]
properties: Vec<String>,
},
Singleton {
description: Option<String>,
},
#[serde(other)]
Unknown,
}
#[derive(Debug, Error)]
pub enum JmapEmailSetError {
#[error("JMAP Email/set failed: {0}")]
Send(#[from] JmapSendError),
#[error("JMAP Email/set failed: serialize args: {0}")]
SerializeArgs(#[source] serde_json::Error),
#[error("JMAP Email/set failed: {0}")]
Set(#[from] JmapSetError),
}
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JmapEmailSetArgs {
#[serde(skip_serializing_if = "Option::is_none")]
pub create: Option<BTreeMap<String, JmapEmail>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub update: Option<BTreeMap<String, JmapEmailPatch>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub destroy: Option<Vec<String>>,
}
impl JmapEmailSetArgs {
pub fn create(&mut self, client_id: impl Into<String>, email: JmapEmail) -> &mut Self {
self.create
.get_or_insert_with(Default::default)
.insert(client_id.into(), email);
self
}
pub fn destroy(&mut self, id: impl Into<String>) -> &mut Self {
self.destroy
.get_or_insert_with(Default::default)
.push(id.into());
self
}
pub fn set_keyword(&mut self, id: impl Into<String>, keyword: impl Into<String>) -> &mut Self {
self.patch(id)
.0
.push(JmapEmailPatchOp::SetKeyword(keyword.into()));
self
}
pub fn unset_keyword(
&mut self,
id: impl Into<String>,
keyword: impl Into<String>,
) -> &mut Self {
self.patch(id)
.0
.push(JmapEmailPatchOp::UnsetKeyword(keyword.into()));
self
}
pub fn replace_keywords(
&mut self,
id: impl Into<String>,
keywords: BTreeMap<String, bool>,
) -> &mut Self {
self.patch(id)
.0
.push(JmapEmailPatchOp::ReplaceKeywords(keywords));
self
}
pub fn add_to_mailbox(
&mut self,
id: impl Into<String>,
mailbox_id: impl Into<String>,
) -> &mut Self {
self.patch(id)
.0
.push(JmapEmailPatchOp::AddToMailbox(mailbox_id.into()));
self
}
pub fn remove_from_mailbox(
&mut self,
id: impl Into<String>,
mailbox_id: impl Into<String>,
) -> &mut Self {
self.patch(id)
.0
.push(JmapEmailPatchOp::RemoveFromMailbox(mailbox_id.into()));
self
}
pub fn replace_mailbox_ids(
&mut self,
id: impl Into<String>,
ids: BTreeMap<String, bool>,
) -> &mut Self {
self.patch(id)
.0
.push(JmapEmailPatchOp::ReplaceMailboxIds(ids));
self
}
fn patch(&mut self, id: impl Into<String>) -> &mut JmapEmailPatch {
self.update
.get_or_insert_with(Default::default)
.entry(id.into())
.or_default()
}
}
#[derive(Clone, Debug)]
pub struct JmapEmailSetOutput {
pub new_state: String,
pub created: BTreeMap<String, JmapEmail>,
pub updated: BTreeMap<String, Option<JmapEmail>>,
pub destroyed: Vec<String>,
pub not_created: BTreeMap<String, JmapEmailSetItemError>,
pub not_updated: BTreeMap<String, JmapEmailSetItemError>,
pub not_destroyed: BTreeMap<String, JmapEmailSetItemError>,
pub keep_alive: bool,
}
pub struct JmapEmailSet {
state: State,
}
impl JmapEmailSet {
pub fn new(
session: &JmapSession,
http_auth: &SecretString,
args: JmapEmailSetArgs,
) -> Result<Self, JmapEmailSetError> {
let account_id = session
.primary_accounts
.get(JMAP_MAIL_CAPABILITY)
.cloned()
.unwrap_or_default();
let api_url = &session.api_url;
let json_args = serde_json::to_value(EmailSetRequest { account_id, args })
.map_err(JmapEmailSetError::SerializeArgs)?;
let mut batch = JmapBatch::new();
batch.add("Email/set", json_args);
let request = batch.into_request(vec![
JMAP_CORE_CAPABILITY.into(),
JMAP_MAIL_CAPABILITY.into(),
]);
let send = JmapSend::new(http_auth, api_url, request)?;
Ok(Self {
state: State::Set(JmapSet::from_send(send)),
})
}
}
impl JmapCoroutine for JmapEmailSet {
type Yield = JmapYield;
type Return = Result<JmapEmailSetOutput, JmapEmailSetError>;
fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
match &mut self.state {
State::Set(set) => {
let JmapSetOutput {
new_state,
created,
updated,
destroyed,
not_created,
not_updated,
not_destroyed,
keep_alive,
} = jmap_try!(set, arg);
let parse = |map: BTreeMap<String, serde_json::Value>| {
map.into_iter()
.map(|(k, v)| {
let e =
serde_json::from_value(v).unwrap_or(JmapEmailSetItemError::Unknown);
(k, e)
})
.collect()
};
JmapCoroutineState::Complete(Ok(JmapEmailSetOutput {
new_state,
created,
updated,
destroyed,
not_created: parse(not_created),
not_updated: parse(not_updated),
not_destroyed: parse(not_destroyed),
keep_alive,
}))
}
}
}
}
enum State {
Set(JmapSet<JmapEmail>),
}
#[derive(Serialize)]
struct EmailSetRequest {
#[serde(rename = "accountId")]
account_id: String,
#[serde(flatten)]
args: JmapEmailSetArgs,
}