use alloc::{collections::BTreeMap, string::String, vec, vec::Vec};
use secrecy::SecretString;
use serde::{Deserialize, Serialize};
use thiserror::Error;
use crate::{
coroutine::*,
jmap_try,
rfc8620::{
JMAP_CORE_CAPABILITY, error::JmapMethodError, request::JmapBatch, send::*,
session::JmapSession,
},
rfc8621::{
JMAP_MAIL_CAPABILITY, email::JmapEmailAddress,
email_submission::JMAP_SUBMISSION_CAPABILITY, identity::JmapIdentity,
},
};
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JmapIdentityCreate {
pub name: String,
pub email: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub reply_to: Option<Vec<JmapEmailAddress>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bcc: Option<Vec<JmapEmailAddress>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text_signature: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub html_signature: Option<String>,
}
#[derive(Clone, Debug, Default, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JmapIdentityUpdate {
#[serde(skip_serializing_if = "Option::is_none")]
pub name: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub reply_to: Option<Vec<JmapEmailAddress>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub bcc: Option<Vec<JmapEmailAddress>>,
#[serde(skip_serializing_if = "Option::is_none")]
pub text_signature: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub html_signature: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum JmapIdentitySetItemError {
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 JmapIdentitySetError {
#[error("JMAP Identity/set failed: missing response in method_responses")]
MissingResponse,
#[error("JMAP Identity/set failed: {0}")]
Send(#[from] JmapSendError),
#[error("JMAP Identity/set failed: serialize args: {0}")]
SerializeArgs(#[source] serde_json::Error),
#[error("JMAP Identity/set failed: parse response: {0}")]
ParseResponse(#[source] serde_json::Error),
#[error("JMAP Identity/set failed: {0}")]
Method(#[from] JmapMethodError),
}
#[derive(Clone, Debug, Default)]
pub struct JmapIdentitySetArgs {
pub create: BTreeMap<String, JmapIdentityCreate>,
pub update: BTreeMap<String, JmapIdentityUpdate>,
pub destroy: Vec<String>,
}
impl JmapIdentitySetArgs {
pub fn create(
&mut self,
client_id: impl Into<String>,
identity: JmapIdentityCreate,
) -> &mut Self {
self.create.insert(client_id.into(), identity);
self
}
pub fn update(&mut self, id: impl Into<String>, patch: JmapIdentityUpdate) -> &mut Self {
self.update.insert(id.into(), patch);
self
}
pub fn destroy(&mut self, id: impl Into<String>) -> &mut Self {
self.destroy.push(id.into());
self
}
}
#[derive(Clone, Debug)]
pub struct JmapIdentitySetOutput {
pub new_state: String,
pub created: BTreeMap<String, JmapIdentity>,
pub updated: BTreeMap<String, Option<JmapIdentity>>,
pub destroyed: Vec<String>,
pub not_created: BTreeMap<String, JmapIdentitySetItemError>,
pub not_updated: BTreeMap<String, JmapIdentitySetItemError>,
pub not_destroyed: BTreeMap<String, JmapIdentitySetItemError>,
pub keep_alive: bool,
}
pub struct JmapIdentitySet {
state: State,
}
impl JmapIdentitySet {
pub fn new(
session: &JmapSession,
http_auth: &SecretString,
args: JmapIdentitySetArgs,
) -> Result<Self, JmapIdentitySetError> {
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(IdentitySetRequest {
account_id,
create: args.create,
update: args.update,
destroy: args.destroy,
})
.map_err(JmapIdentitySetError::SerializeArgs)?;
let mut batch = JmapBatch::new();
batch.add("Identity/set", json_args);
let request = batch.into_request(vec![
JMAP_CORE_CAPABILITY.into(),
JMAP_MAIL_CAPABILITY.into(),
JMAP_SUBMISSION_CAPABILITY.into(),
]);
Ok(Self {
state: State::Send(JmapSend::new(http_auth, api_url, request)?),
})
}
}
impl JmapCoroutine for JmapIdentitySet {
type Yield = JmapYield;
type Return = Result<JmapIdentitySetOutput, JmapIdentitySetError>;
fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
match &mut self.state {
State::Send(send) => {
let JmapSendOutput {
response,
keep_alive,
} = jmap_try!(send, arg);
let Some((name, args, _)) = response.method_responses.into_iter().next() else {
return JmapCoroutineState::Complete(Err(
JmapIdentitySetError::MissingResponse,
));
};
if name == "error" {
let err = serde_json::from_value::<JmapMethodError>(args)
.unwrap_or(JmapMethodError::Unknown);
return JmapCoroutineState::Complete(Err(err.into()));
}
match serde_json::from_value::<IdentitySetResponse>(args) {
Ok(r) => JmapCoroutineState::Complete(Ok(JmapIdentitySetOutput {
new_state: r.new_state.unwrap_or_default(),
created: BTreeMap::new(),
updated: BTreeMap::new(),
destroyed: r.destroyed.unwrap_or_default(),
not_created: r.not_created.unwrap_or_default(),
not_updated: r.not_updated.unwrap_or_default(),
not_destroyed: r.not_destroyed.unwrap_or_default(),
keep_alive,
})),
Err(err) => {
JmapCoroutineState::Complete(Err(JmapIdentitySetError::ParseResponse(err)))
}
}
}
}
}
}
enum State {
Send(JmapSend),
}
#[derive(Serialize)]
#[serde(rename_all = "camelCase")]
struct IdentitySetRequest {
account_id: String,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
create: BTreeMap<String, JmapIdentityCreate>,
#[serde(skip_serializing_if = "BTreeMap::is_empty")]
update: BTreeMap<String, JmapIdentityUpdate>,
#[serde(skip_serializing_if = "Vec::is_empty")]
destroy: Vec<String>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct IdentitySetResponse {
#[serde(default)]
new_state: Option<String>,
#[serde(default)]
#[allow(dead_code)]
created: Option<serde_json::Value>,
#[serde(default)]
#[allow(dead_code)]
updated: Option<serde_json::Value>,
#[serde(default)]
destroyed: Option<Vec<String>>,
#[serde(default)]
not_created: Option<BTreeMap<String, JmapIdentitySetItemError>>,
#[serde(default)]
not_updated: Option<BTreeMap<String, JmapIdentitySetItemError>>,
#[serde(default)]
not_destroyed: Option<BTreeMap<String, JmapIdentitySetItemError>>,
}