io_jmap/rfc8621/email/copy.rs
1//! JMAP `Email/copy` coroutine (RFC 8621 §4.10): copies emails from one account
2//! into the current session account.
3//!
4//! # Example
5//!
6//! ```rust,no_run
7//! use std::{
8//! collections::BTreeMap,
9//! io::{Read, Write},
10//! net::TcpStream,
11//! };
12//!
13//! use io_jmap::{
14//! coroutine::{JmapCoroutine, JmapCoroutineState, JmapYield},
15//! rfc8620::session::JmapSession,
16//! rfc8621::email::copy::{JmapEmailCopy, JmapEmailCopyArgs},
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 create = BTreeMap::new();
37//! create.insert(
38//! "c1".to_string(),
39//! JmapEmailCopyArgs {
40//! id: "e1".into(),
41//! mailbox_ids: Default::default(),
42//! keywords: None,
43//! received_at: None,
44//! },
45//! );
46//! let mut coroutine = JmapEmailCopy::new(&session, &auth, "from", create).unwrap();
47//! let mut arg = None;
48//!
49//! let out = loop {
50//! match coroutine.resume(arg.take()) {
51//! JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
52//! stream.write_all(&bytes).unwrap();
53//! }
54//! JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
55//! let n = stream.read(&mut buf).unwrap();
56//! arg = Some(&buf[..n]);
57//! }
58//! JmapCoroutineState::Complete(Ok(out)) => break out,
59//! JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
60//! }
61//! };
62//!
63//! println!("{} created", out.created.len());
64//! ```
65
66use alloc::{collections::BTreeMap, string::String, vec, vec::Vec};
67
68use secrecy::SecretString;
69use serde::{Deserialize, Serialize};
70use thiserror::Error;
71
72use crate::{
73 coroutine::*,
74 jmap_try,
75 rfc8620::{
76 JMAP_CORE_CAPABILITY, error::JmapMethodError, request::JmapBatch, send::*,
77 session::JmapSession,
78 },
79 rfc8621::{JMAP_MAIL_CAPABILITY, email::JmapEmail},
80};
81
82/// Arguments for copying a single email between accounts via `Email/copy`.
83#[derive(Clone, Debug, Serialize)]
84#[serde(rename_all = "camelCase")]
85pub struct JmapEmailCopyArgs {
86 /// Source email ID.
87 pub id: String,
88 /// `{ mailbox-id -> true }` for destination mailboxes.
89 pub mailbox_ids: BTreeMap<String, bool>,
90 /// Keywords on the copy (replaces source keywords).
91 #[serde(skip_serializing_if = "Option::is_none")]
92 pub keywords: Option<BTreeMap<String, bool>>,
93 /// RFC 3339 override for the copy's `receivedAt`.
94 #[serde(skip_serializing_if = "Option::is_none")]
95 pub received_at: Option<String>,
96}
97
98/// Per-object error returned in `Email/copy` responses (RFC 8621 §4.10).
99#[derive(Clone, Debug, Deserialize)]
100#[serde(tag = "type", rename_all = "camelCase")]
101pub enum JmapEmailCopyItemError {
102 /// The email already exists in the destination account (RFC 8621 §4.10).
103 AlreadyExists {
104 /// Optional human-readable detail.
105 description: Option<String>,
106 },
107 /// Standard set error (RFC 8620 §5.3): target id not found.
108 NotFound {
109 /// Optional human-readable detail.
110 description: Option<String>,
111 },
112 /// Standard set error (RFC 8620 §5.3): one or more properties were invalid.
113 InvalidProperties {
114 /// Optional human-readable detail.
115 description: Option<String>,
116 /// The invalid property names.
117 #[serde(default)]
118 properties: Vec<String>,
119 },
120 /// Catch-all for set errors not modelled above.
121 #[serde(other)]
122 Unknown,
123}
124
125/// Failure causes during a JMAP `Email/copy` flow.
126#[derive(Debug, Error)]
127pub enum JmapEmailCopyError {
128 /// The response carried no method response.
129 #[error("JMAP Email/copy failed: missing response in method_responses")]
130 MissingResponse,
131 /// The inner send coroutine failed.
132 #[error("JMAP Email/copy failed: {0}")]
133 Send(#[from] JmapSendError),
134 /// The method arguments could not be serialized.
135 #[error("JMAP Email/copy failed: serialize args: {0}")]
136 SerializeArgs(#[source] serde_json::Error),
137 /// The method response could not be parsed.
138 #[error("JMAP Email/copy failed: parse response: {0}")]
139 ParseResponse(#[source] serde_json::Error),
140 /// The server returned a method-level error.
141 #[error("JMAP Email/copy failed: {0}")]
142 Method(#[from] JmapMethodError),
143}
144
145/// Successful terminal output of [`JmapEmailCopy`].
146#[derive(Clone, Debug)]
147pub struct JmapEmailCopyOutput {
148 /// The new server state after the call.
149 pub new_state: String,
150 /// The created emails, keyed by client id.
151 pub created: BTreeMap<String, JmapEmail>,
152 /// The failed copies, keyed by client id.
153 pub not_created: BTreeMap<String, JmapEmailCopyItemError>,
154 /// Whether the server indicated the connection can be reused.
155 pub keep_alive: bool,
156}
157
158/// I/O-free coroutine for the JMAP `Email/copy` method.
159pub struct JmapEmailCopy {
160 state: State,
161}
162
163impl JmapEmailCopy {
164 /// Prepares the method call request and builds the coroutine.
165 pub fn new(
166 session: &JmapSession,
167 http_auth: &SecretString,
168 from_account_id: impl Into<String>,
169 emails: BTreeMap<String, JmapEmailCopyArgs>,
170 ) -> Result<Self, JmapEmailCopyError> {
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(EmailCopyArgs {
179 from_account_id: from_account_id.into(),
180 account_id,
181 create: emails,
182 })
183 .map_err(JmapEmailCopyError::SerializeArgs)?;
184
185 let mut batch = JmapBatch::new();
186 batch.add("Email/copy", args);
187 let request = batch.into_request(vec![
188 JMAP_CORE_CAPABILITY.into(),
189 JMAP_MAIL_CAPABILITY.into(),
190 ]);
191
192 Ok(Self {
193 state: State::Send(JmapSend::new(http_auth, api_url, request)?),
194 })
195 }
196}
197
198impl JmapCoroutine for JmapEmailCopy {
199 type Yield = JmapYield;
200 type Return = Result<JmapEmailCopyOutput, JmapEmailCopyError>;
201
202 fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
203 match &mut self.state {
204 State::Send(send) => {
205 let JmapSendOutput {
206 response,
207 keep_alive,
208 } = jmap_try!(send, arg);
209
210 let Some((name, args, _)) = response.method_responses.into_iter().next() else {
211 return JmapCoroutineState::Complete(Err(JmapEmailCopyError::MissingResponse));
212 };
213
214 if name == "error" {
215 let err = serde_json::from_value::<JmapMethodError>(args)
216 .unwrap_or(JmapMethodError::Unknown);
217 return JmapCoroutineState::Complete(Err(err.into()));
218 }
219
220 match serde_json::from_value::<EmailCopyResponse>(args) {
221 Ok(r) => JmapCoroutineState::Complete(Ok(JmapEmailCopyOutput {
222 new_state: r.new_state,
223 created: r.created,
224 not_created: r.not_created,
225 keep_alive,
226 })),
227 Err(err) => {
228 JmapCoroutineState::Complete(Err(JmapEmailCopyError::ParseResponse(err)))
229 }
230 }
231 }
232 }
233 }
234}
235
236enum State {
237 Send(JmapSend),
238}
239
240#[derive(Serialize)]
241#[serde(rename_all = "camelCase")]
242struct EmailCopyArgs {
243 from_account_id: String,
244 account_id: String,
245 create: BTreeMap<String, JmapEmailCopyArgs>,
246}
247
248#[derive(Deserialize)]
249#[serde(rename_all = "camelCase")]
250struct EmailCopyResponse {
251 new_state: String,
252 #[serde(default)]
253 created: BTreeMap<String, JmapEmail>,
254 #[serde(default)]
255 not_created: BTreeMap<String, JmapEmailCopyItemError>,
256}