use alloc::{borrow::ToOwned, format, string::String, vec, vec::Vec};
use secrecy::SecretString;
use thiserror::Error;
use crate::{
coroutine::*,
jmap_try,
rfc8620::{JMAP_CORE_CAPABILITY, get::*, session::JmapSession},
rfc8621::{
JMAP_MAIL_CAPABILITY,
mailbox::{JmapMailbox, JmapMailboxProperty},
},
};
#[derive(Debug, Error)]
pub enum JmapMailboxGetError {
#[error("JMAP Mailbox/get failed: {0}")]
Get(#[from] JmapGetError),
}
#[derive(Clone, Debug, Default)]
pub struct JmapMailboxGetOptions {
pub ids: Option<Vec<String>>,
pub properties: Option<Vec<JmapMailboxProperty>>,
}
#[derive(Clone, Debug)]
pub struct JmapMailboxGetOutput {
pub mailboxes: Vec<JmapMailbox>,
pub not_found: Vec<String>,
pub new_state: String,
pub keep_alive: bool,
}
pub struct JmapMailboxGet {
state: State,
}
impl JmapMailboxGet {
pub fn new(
session: &JmapSession,
http_auth: &SecretString,
opts: JmapMailboxGetOptions,
) -> Result<Self, JmapMailboxGetError> {
let account_id = session
.primary_accounts
.get(JMAP_MAIL_CAPABILITY)
.cloned()
.unwrap_or_default();
let api_url = &session.api_url;
let props = opts.properties.map(|ps| {
ps.iter()
.map(|p| {
serde_json::to_value(p)
.ok()
.and_then(|v| v.as_str().map(str::to_owned))
.unwrap_or_else(|| format!("{p:?}"))
})
.collect()
});
Ok(Self {
state: State::Get(JmapGet::new(
account_id,
http_auth,
api_url,
"Mailbox/get",
vec![JMAP_CORE_CAPABILITY.into(), JMAP_MAIL_CAPABILITY.into()],
JmapGetOptions {
ids: opts.ids,
properties: props,
},
)?),
})
}
}
impl JmapCoroutine for JmapMailboxGet {
type Yield = JmapYield;
type Return = Result<JmapMailboxGetOutput, JmapMailboxGetError>;
fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
match &mut self.state {
State::Get(get) => {
let JmapGetOutput {
list,
not_found,
state,
keep_alive,
} = jmap_try!(get, arg);
JmapCoroutineState::Complete(Ok(JmapMailboxGetOutput {
mailboxes: list,
not_found,
new_state: state,
keep_alive,
}))
}
}
}
}
enum State {
Get(JmapGet<JmapMailbox>),
}