Skip to main content

io_jmap/rfc8621/email/
import.rs

1//! JMAP `Email/import` coroutine (RFC 8621 §4.9): imports RFC 5322 messages
2//! (previously uploaded as blobs) into mailboxes. JMAP equivalent of IMAP
3//! `APPEND`.
4//!
5//! # Example
6//!
7//! ```rust,no_run
8//! use std::{
9//!     collections::BTreeMap,
10//!     io::{Read, Write},
11//!     net::TcpStream,
12//! };
13//!
14//! use io_jmap::{
15//!     coroutine::{JmapCoroutine, JmapCoroutineState, JmapYield},
16//!     rfc8620::session::JmapSession,
17//!     rfc8621::email::import::{JmapEmailImport, JmapEmailImportArgs},
18//! };
19//! use secrecy::SecretString;
20//!
21//! // Ready stream needed (TCP-connected, TLS-negociated)
22//! let mut stream = TcpStream::connect("api.example.com:443").unwrap();
23//! let mut buf = [0u8; 4096];
24//!
25//! let session: JmapSession = serde_json::from_str(r#"{
26//!     "username": "",
27//!     "accounts": {},
28//!     "primaryAccounts": {"urn:ietf:params:jmap:mail": "a1"},
29//!     "capabilities": {},
30//!     "apiUrl": "https://api.example.com/jmap/",
31//!     "downloadUrl": "",
32//!     "uploadUrl": "",
33//!     "eventSourceUrl": "",
34//!     "state": ""
35//! }"#).unwrap();
36//! let auth = SecretString::from("Bearer xyz");
37//! let mut emails = BTreeMap::new();
38//! emails.insert(
39//!     "c1".to_string(),
40//!     JmapEmailImportArgs {
41//!         blob_id: "b1".into(),
42//!         mailbox_ids: Default::default(),
43//!         keywords: None,
44//!         received_at: None,
45//!     },
46//! );
47//! let mut coroutine = JmapEmailImport::new(&session, &auth, emails).unwrap();
48//! let mut arg = None;
49//!
50//! let out = loop {
51//!     match coroutine.resume(arg.take()) {
52//!         JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
53//!             stream.write_all(&bytes).unwrap();
54//!         }
55//!         JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
56//!             let n = stream.read(&mut buf).unwrap();
57//!             arg = Some(&buf[..n]);
58//!         }
59//!         JmapCoroutineState::Complete(Ok(out)) => break out,
60//!         JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
61//!     }
62//! };
63//!
64//! println!("{} created", out.created.len());
65//! ```
66
67use alloc::{collections::BTreeMap, string::String, vec, vec::Vec};
68
69use secrecy::SecretString;
70use serde::{Deserialize, Serialize};
71use thiserror::Error;
72
73use crate::{
74    coroutine::*,
75    jmap_try,
76    rfc8620::{
77        JMAP_CORE_CAPABILITY, error::JmapMethodError, request::JmapBatch, send::*,
78        session::JmapSession,
79    },
80    rfc8621::{JMAP_MAIL_CAPABILITY, email::JmapEmail},
81};
82
83/// Arguments for importing a single RFC 5322 message via `Email/import`.
84#[derive(Clone, Debug, Serialize)]
85#[serde(rename_all = "camelCase")]
86pub struct JmapEmailImportArgs {
87    /// Blob ID of the RFC 5322 message.
88    pub blob_id: String,
89    /// `{ mailbox-id -> true }` for destination mailboxes.
90    pub mailbox_ids: BTreeMap<String, bool>,
91    /// `{ keyword -> true }` to set on the imported email.
92    #[serde(skip_serializing_if = "Option::is_none")]
93    pub keywords: Option<BTreeMap<String, bool>>,
94    /// RFC 3339 override for `receivedAt`.
95    #[serde(skip_serializing_if = "Option::is_none")]
96    pub received_at: Option<String>,
97}
98
99/// Per-object error returned in `Email/import` responses (RFC 8621 §4.9).
100#[derive(Clone, Debug, Deserialize)]
101#[serde(tag = "type", rename_all = "camelCase")]
102pub enum JmapEmailImportItemError {
103    /// The message body was not a valid RFC 5322 message (RFC 8621 §4.9).
104    InvalidEmail {
105        /// Optional human-readable detail.
106        description: Option<String>,
107    },
108    /// Standard set error (RFC 8620 §5.3): target id not found.
109    NotFound {
110        /// Optional human-readable detail.
111        description: Option<String>,
112    },
113    /// Standard set error (RFC 8620 §5.3): one or more properties were invalid.
114    InvalidProperties {
115        /// Optional human-readable detail.
116        description: Option<String>,
117        /// The invalid property names.
118        #[serde(default)]
119        properties: Vec<String>,
120    },
121    /// Catch-all for set errors not modelled above.
122    #[serde(other)]
123    Unknown,
124}
125
126/// Failure causes during a JMAP `Email/import` flow.
127#[derive(Debug, Error)]
128pub enum JmapEmailImportError {
129    /// The response carried no method response.
130    #[error("JMAP Email/import failed: missing response in method_responses")]
131    MissingResponse,
132    /// The inner send coroutine failed.
133    #[error("JMAP Email/import failed: {0}")]
134    Send(#[from] JmapSendError),
135    /// The method arguments could not be serialized.
136    #[error("JMAP Email/import failed: serialize args: {0}")]
137    SerializeArgs(#[source] serde_json::Error),
138    /// The method response could not be parsed.
139    #[error("JMAP Email/import failed: parse response: {0}")]
140    ParseResponse(#[source] serde_json::Error),
141    /// The server returned a method-level error.
142    #[error("JMAP Email/import failed: {0}")]
143    Method(#[from] JmapMethodError),
144}
145
146/// Successful terminal output of [`JmapEmailImport`].
147#[derive(Clone, Debug)]
148pub struct JmapEmailImportOutput {
149    /// The new server state after the call.
150    pub new_state: String,
151    /// The created emails, keyed by client id.
152    pub created: BTreeMap<String, JmapEmail>,
153    /// The failed imports, keyed by client id.
154    pub not_created: BTreeMap<String, JmapEmailImportItemError>,
155    /// Whether the server indicated the connection can be reused.
156    pub keep_alive: bool,
157}
158
159/// I/O-free coroutine for the JMAP `Email/import` method.
160pub struct JmapEmailImport {
161    state: State,
162}
163
164impl JmapEmailImport {
165    /// `emails` maps client-assigned IDs to [`JmapEmailImportArgs`] descriptors.
166    pub fn new(
167        session: &JmapSession,
168        http_auth: &SecretString,
169        emails: BTreeMap<String, JmapEmailImportArgs>,
170    ) -> Result<Self, JmapEmailImportError> {
171        let account_id = session
172            .primary_accounts
173            .get(JMAP_MAIL_CAPABILITY)
174            .cloned()
175            .unwrap_or_default();
176        let api_url = &session.api_url;
177
178        let args = serde_json::to_value(EmailImportArgs { account_id, emails })
179            .map_err(JmapEmailImportError::SerializeArgs)?;
180
181        let mut batch = JmapBatch::new();
182        batch.add("Email/import", args);
183        let request = batch.into_request(vec![
184            JMAP_CORE_CAPABILITY.into(),
185            JMAP_MAIL_CAPABILITY.into(),
186        ]);
187
188        Ok(Self {
189            state: State::Send(JmapSend::new(http_auth, api_url, request)?),
190        })
191    }
192}
193
194impl JmapCoroutine for JmapEmailImport {
195    type Yield = JmapYield;
196    type Return = Result<JmapEmailImportOutput, JmapEmailImportError>;
197
198    fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
199        match &mut self.state {
200            State::Send(send) => {
201                let JmapSendOutput {
202                    response,
203                    keep_alive,
204                } = jmap_try!(send, arg);
205
206                let Some((name, args, _)) = response.method_responses.into_iter().next() else {
207                    return JmapCoroutineState::Complete(Err(
208                        JmapEmailImportError::MissingResponse,
209                    ));
210                };
211
212                if name == "error" {
213                    let err = serde_json::from_value::<JmapMethodError>(args)
214                        .unwrap_or(JmapMethodError::Unknown);
215                    return JmapCoroutineState::Complete(Err(err.into()));
216                }
217
218                match serde_json::from_value::<EmailImportResponse>(args) {
219                    Ok(r) => JmapCoroutineState::Complete(Ok(JmapEmailImportOutput {
220                        new_state: r.new_state,
221                        created: r.created,
222                        not_created: r.not_created,
223                        keep_alive,
224                    })),
225                    Err(err) => {
226                        JmapCoroutineState::Complete(Err(JmapEmailImportError::ParseResponse(err)))
227                    }
228                }
229            }
230        }
231    }
232}
233
234enum State {
235    Send(JmapSend),
236}
237
238#[derive(Serialize)]
239#[serde(rename_all = "camelCase")]
240struct EmailImportArgs {
241    account_id: String,
242    emails: BTreeMap<String, JmapEmailImportArgs>,
243}
244
245#[derive(Deserialize)]
246#[serde(rename_all = "camelCase")]
247struct EmailImportResponse {
248    new_state: String,
249    #[serde(default)]
250    created: BTreeMap<String, JmapEmail>,
251    #[serde(default)]
252    not_created: BTreeMap<String, JmapEmailImportItemError>,
253}