1use core::fmt;
59
60use alloc::{collections::BTreeMap, string::String, vec, vec::Vec};
61
62use log::trace;
63use secrecy::SecretString;
64use serde::Serialize;
65use thiserror::Error;
66
67use crate::{
68 coroutine::*,
69 jmap_try,
70 rfc8620::{CORE_CAPABILITY, JmapBatch, JmapSession, send::*, set::*},
71 rfc8621::{
72 MAIL_CAPABILITY,
73 email::{JmapEmail, JmapEmailPatch, JmapEmailPatchOp, JmapEmailSetItemError},
74 },
75};
76
77#[derive(Debug, Error)]
79pub enum JmapEmailSetError {
80 #[error("JMAP Email/set failed: {0}")]
81 Send(#[from] JmapSendError),
82 #[error("JMAP Email/set failed: serialize args: {0}")]
83 SerializeArgs(#[source] serde_json::Error),
84 #[error("JMAP Email/set failed: {0}")]
85 Set(#[from] JmapSetError),
86}
87
88#[derive(Clone, Debug, Default, Serialize)]
90#[serde(rename_all = "camelCase")]
91pub struct JmapEmailSetArgs {
92 #[serde(skip_serializing_if = "Option::is_none")]
94 pub create: Option<BTreeMap<String, JmapEmail>>,
95
96 #[serde(skip_serializing_if = "Option::is_none")]
98 pub update: Option<BTreeMap<String, JmapEmailPatch>>,
99
100 #[serde(skip_serializing_if = "Option::is_none")]
102 pub destroy: Option<Vec<String>>,
103}
104
105impl JmapEmailSetArgs {
106 pub fn create(&mut self, client_id: impl Into<String>, email: JmapEmail) -> &mut Self {
108 self.create
109 .get_or_insert_with(Default::default)
110 .insert(client_id.into(), email);
111 self
112 }
113
114 pub fn destroy(&mut self, id: impl Into<String>) -> &mut Self {
116 self.destroy
117 .get_or_insert_with(Default::default)
118 .push(id.into());
119 self
120 }
121
122 pub fn set_keyword(&mut self, id: impl Into<String>, keyword: impl Into<String>) -> &mut Self {
123 self.patch(id)
124 .0
125 .push(JmapEmailPatchOp::SetKeyword(keyword.into()));
126 self
127 }
128
129 pub fn unset_keyword(
130 &mut self,
131 id: impl Into<String>,
132 keyword: impl Into<String>,
133 ) -> &mut Self {
134 self.patch(id)
135 .0
136 .push(JmapEmailPatchOp::UnsetKeyword(keyword.into()));
137 self
138 }
139
140 pub fn replace_keywords(
141 &mut self,
142 id: impl Into<String>,
143 keywords: BTreeMap<String, bool>,
144 ) -> &mut Self {
145 self.patch(id)
146 .0
147 .push(JmapEmailPatchOp::ReplaceKeywords(keywords));
148 self
149 }
150
151 pub fn add_to_mailbox(
152 &mut self,
153 id: impl Into<String>,
154 mailbox_id: impl Into<String>,
155 ) -> &mut Self {
156 self.patch(id)
157 .0
158 .push(JmapEmailPatchOp::AddToMailbox(mailbox_id.into()));
159 self
160 }
161
162 pub fn remove_from_mailbox(
163 &mut self,
164 id: impl Into<String>,
165 mailbox_id: impl Into<String>,
166 ) -> &mut Self {
167 self.patch(id)
168 .0
169 .push(JmapEmailPatchOp::RemoveFromMailbox(mailbox_id.into()));
170 self
171 }
172
173 pub fn replace_mailbox_ids(
174 &mut self,
175 id: impl Into<String>,
176 ids: BTreeMap<String, bool>,
177 ) -> &mut Self {
178 self.patch(id)
179 .0
180 .push(JmapEmailPatchOp::ReplaceMailboxIds(ids));
181 self
182 }
183
184 fn patch(&mut self, id: impl Into<String>) -> &mut JmapEmailPatch {
185 self.update
186 .get_or_insert_with(Default::default)
187 .entry(id.into())
188 .or_default()
189 }
190}
191
192#[derive(Clone, Debug)]
194pub struct JmapEmailSetOutput {
195 pub new_state: String,
196 pub created: BTreeMap<String, JmapEmail>,
197 pub updated: BTreeMap<String, Option<JmapEmail>>,
198 pub destroyed: Vec<String>,
199 pub not_created: BTreeMap<String, JmapEmailSetItemError>,
200 pub not_updated: BTreeMap<String, JmapEmailSetItemError>,
201 pub not_destroyed: BTreeMap<String, JmapEmailSetItemError>,
202 pub keep_alive: bool,
203}
204
205pub struct JmapEmailSet {
207 state: State,
208}
209
210impl JmapEmailSet {
211 pub fn new(
212 session: &JmapSession,
213 http_auth: &SecretString,
214 args: JmapEmailSetArgs,
215 ) -> Result<Self, JmapEmailSetError> {
216 let account_id = session
217 .primary_accounts
218 .get(MAIL_CAPABILITY)
219 .cloned()
220 .unwrap_or_default();
221 let api_url = &session.api_url;
222
223 let json_args = serde_json::to_value(EmailSetRequest { account_id, args })
224 .map_err(JmapEmailSetError::SerializeArgs)?;
225
226 let mut batch = JmapBatch::new();
227 batch.add("Email/set", json_args);
228 let request = batch.into_request(vec![CORE_CAPABILITY.into(), MAIL_CAPABILITY.into()]);
229
230 let send = JmapSend::new(http_auth, api_url, request)?;
231 Ok(Self {
232 state: State::Set(JmapSet::from_send(send)),
233 })
234 }
235}
236
237impl JmapCoroutine for JmapEmailSet {
238 type Yield = JmapYield;
239 type Return = Result<JmapEmailSetOutput, JmapEmailSetError>;
240
241 fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
242 trace!("Email/set: {}", self.state);
243 match &mut self.state {
244 State::Set(set) => {
245 let JmapSetOutput {
246 new_state,
247 created,
248 updated,
249 destroyed,
250 not_created,
251 not_updated,
252 not_destroyed,
253 keep_alive,
254 } = jmap_try!(set, arg);
255 let parse = |map: BTreeMap<String, serde_json::Value>| {
256 map.into_iter()
257 .map(|(k, v)| {
258 let e =
259 serde_json::from_value(v).unwrap_or(JmapEmailSetItemError::Unknown);
260 (k, e)
261 })
262 .collect()
263 };
264 JmapCoroutineState::Complete(Ok(JmapEmailSetOutput {
265 new_state,
266 created,
267 updated,
268 destroyed,
269 not_created: parse(not_created),
270 not_updated: parse(not_updated),
271 not_destroyed: parse(not_destroyed),
272 keep_alive,
273 }))
274 }
275 }
276 }
277}
278
279enum State {
280 Set(JmapSet<JmapEmail>),
281}
282
283impl fmt::Display for State {
284 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
285 match self {
286 Self::Set(_) => f.write_str("set"),
287 }
288 }
289}
290
291#[derive(Serialize)]
292struct EmailSetRequest {
293 #[serde(rename = "accountId")]
294 account_id: String,
295 #[serde(flatten)]
296 args: JmapEmailSetArgs,
297}