Skip to main content

io_jmap/rfc8621/email/
get.rs

1//! JMAP `Email/get` coroutine (RFC 8621 ยง4.5): wraps the generic [`JmapGet`]
2//! with the `Email/get`-specific args shape (property selection, body-value
3//! fetch toggles) and a typed [`JmapEmail`] decoder.
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::session::JmapSession,
16//!     rfc8621::email::get::{JmapEmailGet, JmapEmailGetOptions},
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 coroutine = JmapEmailGet::new(
37//!     &session,
38//!     &auth,
39//!     vec!["e1".into()],
40//!     JmapEmailGetOptions {
41//!         fetch_text_body_values: true,
42//!         ..Default::default()
43//!     },
44//! )
45//! .unwrap();
46//! let mut arg = None;
47//!
48//! let out = loop {
49//!     match coroutine.resume(arg.take()) {
50//!         JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
51//!             stream.write_all(&bytes).unwrap();
52//!         }
53//!         JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
54//!             let n = stream.read(&mut buf).unwrap();
55//!             arg = Some(&buf[..n]);
56//!         }
57//!         JmapCoroutineState::Complete(Ok(out)) => break out,
58//!         JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
59//!     }
60//! };
61//!
62//! println!("{} emails", out.emails.len());
63//! ```
64
65use alloc::{string::String, vec, vec::Vec};
66
67use secrecy::SecretString;
68use serde::Serialize;
69use thiserror::Error;
70
71use crate::{
72    coroutine::*,
73    jmap_try,
74    rfc8620::{JMAP_CORE_CAPABILITY, get::*, request::JmapBatch, send::*, session::JmapSession},
75    rfc8621::{
76        JMAP_MAIL_CAPABILITY,
77        email::{JmapEmail, JmapEmailProperty},
78    },
79};
80
81/// Failure causes during a JMAP `Email/get` flow.
82#[derive(Debug, Error)]
83pub enum JmapEmailGetError {
84    /// The inner send coroutine failed.
85    #[error("JMAP Email/get failed: {0}")]
86    Send(#[from] JmapSendError),
87    /// The method arguments could not be serialized.
88    #[error("JMAP Email/get failed: serialize args: {0}")]
89    SerializeArgs(#[source] serde_json::Error),
90    /// The inner generic get coroutine failed.
91    #[error("JMAP Email/get failed: {0}")]
92    Get(#[from] JmapGetError),
93}
94
95/// Options for [`JmapEmailGet::new`].
96#[derive(Clone, Debug, Default)]
97pub struct JmapEmailGetOptions {
98    /// Restrict the returned properties; `None` returns all.
99    pub properties: Option<Vec<JmapEmailProperty>>,
100    /// Include `bodyValues` for text parts.
101    pub fetch_text_body_values: bool,
102    /// Include `bodyValues` for HTML parts.
103    pub fetch_html_body_values: bool,
104    /// Max bytes per body value (`0` is unlimited).
105    pub max_body_value_bytes: u64,
106}
107
108/// Successful terminal output of [`JmapEmailGet`].
109#[derive(Clone, Debug)]
110pub struct JmapEmailGetOutput {
111    /// The fetched emails.
112    pub emails: Vec<JmapEmail>,
113    /// The requested ids the server did not find.
114    pub not_found: Vec<String>,
115    /// The new server state after the call.
116    pub new_state: String,
117    /// Whether the server indicated the connection can be reused.
118    pub keep_alive: bool,
119}
120
121/// I/O-free coroutine for the JMAP `Email/get` method.
122pub struct JmapEmailGet {
123    state: State,
124}
125
126impl JmapEmailGet {
127    /// Prepares the method call request and builds the coroutine.
128    pub fn new(
129        session: &JmapSession,
130        http_auth: &SecretString,
131        ids: Vec<String>,
132        opts: JmapEmailGetOptions,
133    ) -> Result<Self, JmapEmailGetError> {
134        let account_id = session
135            .primary_accounts
136            .get(JMAP_MAIL_CAPABILITY)
137            .cloned()
138            .unwrap_or_default();
139        let api_url = &session.api_url;
140
141        let args = serde_json::to_value(EmailGetArgs {
142            account_id,
143            ids,
144            properties: opts.properties,
145            fetch_text_body_values: opts.fetch_text_body_values,
146            fetch_html_body_values: opts.fetch_html_body_values,
147            max_body_value_bytes: opts.max_body_value_bytes,
148        })
149        .map_err(JmapEmailGetError::SerializeArgs)?;
150
151        let mut batch = JmapBatch::new();
152        batch.add("Email/get", args);
153        let request = batch.into_request(vec![
154            JMAP_CORE_CAPABILITY.into(),
155            JMAP_MAIL_CAPABILITY.into(),
156        ]);
157
158        let send = JmapSend::new(http_auth, api_url, request)?;
159        Ok(Self {
160            state: State::Get(JmapGet::from_send(send)),
161        })
162    }
163}
164
165impl JmapCoroutine for JmapEmailGet {
166    type Yield = JmapYield;
167    type Return = Result<JmapEmailGetOutput, JmapEmailGetError>;
168
169    fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
170        match &mut self.state {
171            State::Get(get) => {
172                let JmapGetOutput {
173                    list,
174                    not_found,
175                    state,
176                    keep_alive,
177                } = jmap_try!(get, arg);
178                JmapCoroutineState::Complete(Ok(JmapEmailGetOutput {
179                    emails: list,
180                    not_found,
181                    new_state: state,
182                    keep_alive,
183                }))
184            }
185        }
186    }
187}
188
189enum State {
190    Get(JmapGet<JmapEmail>),
191}
192
193#[derive(Serialize)]
194#[serde(rename_all = "camelCase")]
195struct EmailGetArgs {
196    account_id: String,
197    ids: Vec<String>,
198    #[serde(skip_serializing_if = "Option::is_none")]
199    properties: Option<Vec<JmapEmailProperty>>,
200    #[serde(skip_serializing_if = "is_false")]
201    fetch_text_body_values: bool,
202    #[serde(rename = "fetchHTMLBodyValues", skip_serializing_if = "is_false")]
203    fetch_html_body_values: bool,
204    #[serde(skip_serializing_if = "is_zero")]
205    max_body_value_bytes: u64,
206}
207
208fn is_false(b: &bool) -> bool {
209    !b
210}
211
212fn is_zero(v: &u64) -> bool {
213    *v == 0
214}