Skip to main content

io_jmap/rfc8621/email/
set.rs

1//! JMAP `Email/set` coroutine (RFC 8621 §4.7): wraps the generic [`JmapSet`]
2//! with [`JmapEmailSetArgs`] (create/update/destroy) and decodes per-object
3//! [`JmapEmailSetItemError`] payloads.
4//!
5//! # Example
6//!
7//! ```rust,no_run
8//! use std::{
9//!     io::{Read, Write},
10//!     net::TcpStream,
11//! };
12//!
13//! use io_jmap::{
14//!     coroutine::{JmapCoroutine, JmapCoroutineState, JmapYield},
15//!     rfc8620::JmapSession,
16//!     rfc8621::email::set::{JmapEmailSet, JmapEmailSetArgs},
17//! };
18//! use secrecy::SecretString;
19//!
20//! // Ready stream needed (TCP-connected, TLS-negociated)
21//! let mut stream = TcpStream::connect("api.example.com:443").unwrap();
22//! let mut buf = [0u8; 4096];
23//!
24//! let session: JmapSession = serde_json::from_str(r#"{
25//!     "username": "",
26//!     "accounts": {},
27//!     "primaryAccounts": {"urn:ietf:params:jmap:mail": "a1"},
28//!     "capabilities": {},
29//!     "apiUrl": "https://api.example.com/jmap/",
30//!     "downloadUrl": "",
31//!     "uploadUrl": "",
32//!     "eventSourceUrl": "",
33//!     "state": ""
34//! }"#).unwrap();
35//! let auth = SecretString::from("Bearer xyz");
36//! let mut args = JmapEmailSetArgs::default();
37//! args.destroy("e1");
38//! let mut coroutine = JmapEmailSet::new(&session, &auth, args).unwrap();
39//! let mut arg = None;
40//!
41//! let out = loop {
42//!     match coroutine.resume(arg.take()) {
43//!         JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
44//!             stream.write_all(&bytes).unwrap();
45//!         }
46//!         JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
47//!             let n = stream.read(&mut buf).unwrap();
48//!             arg = Some(&buf[..n]);
49//!         }
50//!         JmapCoroutineState::Complete(Ok(out)) => break out,
51//!         JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
52//!     }
53//! };
54//!
55//! println!("new state {}", out.new_state);
56//! ```
57
58use 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/// Failure causes during a JMAP `Email/set` flow.
78#[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/// Arguments for an `Email/set` request.
89#[derive(Clone, Debug, Default, Serialize)]
90#[serde(rename_all = "camelCase")]
91pub struct JmapEmailSetArgs {
92    /// Objects to create (client ID → partial email object).
93    #[serde(skip_serializing_if = "Option::is_none")]
94    pub create: Option<BTreeMap<String, JmapEmail>>,
95
96    /// Objects to update (email ID → patch).
97    #[serde(skip_serializing_if = "Option::is_none")]
98    pub update: Option<BTreeMap<String, JmapEmailPatch>>,
99
100    /// IDs to destroy (delete).
101    #[serde(skip_serializing_if = "Option::is_none")]
102    pub destroy: Option<Vec<String>>,
103}
104
105impl JmapEmailSetArgs {
106    /// Queue an email for creation under the given client-chosen ID.
107    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    /// Queue an email ID for destruction.
115    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/// Successful terminal output of [`JmapEmailSet`].
193#[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
205/// I/O-free coroutine for the JMAP `Email/set` method.
206pub 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}