Skip to main content

io_jmap/rfc8621/mailbox/
get.rs

1//! JMAP `Mailbox/get` coroutine (RFC 8621 ยง2.5): wraps the generic [`JmapGet`]
2//! with the JMAP-Mail capability set.
3//!
4//! # Example
5//!
6//! ```rust,no_run
7//! use std::{
8//!     io::{Read, Write},
9//!     net::TcpStream,
10//! };
11//!
12//! use io_jmap::{
13//!     coroutine::{JmapCoroutine, JmapCoroutineState, JmapYield},
14//!     rfc8620::session::JmapSession,
15//!     rfc8621::mailbox::get::{JmapMailboxGet, JmapMailboxGetOptions},
16//! };
17//! use secrecy::SecretString;
18//!
19//! // Ready stream needed (TCP-connected, TLS-negociated)
20//! let mut stream = TcpStream::connect("api.example.com:443").unwrap();
21//! let mut buf = [0u8; 4096];
22//!
23//! let session: JmapSession = serde_json::from_str(r#"{
24//!     "username": "",
25//!     "accounts": {},
26//!     "primaryAccounts": {"urn:ietf:params:jmap:mail": "a1"},
27//!     "capabilities": {},
28//!     "apiUrl": "https://api.example.com/jmap/",
29//!     "downloadUrl": "",
30//!     "uploadUrl": "",
31//!     "eventSourceUrl": "",
32//!     "state": ""
33//! }"#).unwrap();
34//! let auth = SecretString::from("Bearer xyz");
35//! let mut coroutine =
36//!     JmapMailboxGet::new(&session, &auth, JmapMailboxGetOptions::default()).unwrap();
37//! let mut arg = None;
38//!
39//! let out = loop {
40//!     match coroutine.resume(arg.take()) {
41//!         JmapCoroutineState::Yielded(JmapYield::WantsWrite(bytes)) => {
42//!             stream.write_all(&bytes).unwrap();
43//!         }
44//!         JmapCoroutineState::Yielded(JmapYield::WantsRead) => {
45//!             let n = stream.read(&mut buf).unwrap();
46//!             arg = Some(&buf[..n]);
47//!         }
48//!         JmapCoroutineState::Complete(Ok(out)) => break out,
49//!         JmapCoroutineState::Complete(Err(err)) => panic!("{err}"),
50//!     }
51//! };
52//!
53//! println!("{} mailboxes", out.mailboxes.len());
54//! ```
55
56use alloc::{borrow::ToOwned, format, string::String, vec, vec::Vec};
57
58use secrecy::SecretString;
59use thiserror::Error;
60
61use crate::{
62    coroutine::*,
63    jmap_try,
64    rfc8620::{JMAP_CORE_CAPABILITY, get::*, session::JmapSession},
65    rfc8621::{
66        JMAP_MAIL_CAPABILITY,
67        mailbox::{JmapMailbox, JmapMailboxProperty},
68    },
69};
70
71/// Failure causes during a JMAP `Mailbox/get` flow.
72#[derive(Debug, Error)]
73pub enum JmapMailboxGetError {
74    /// The inner generic get coroutine failed.
75    #[error("JMAP Mailbox/get failed: {0}")]
76    Get(#[from] JmapGetError),
77}
78
79/// Options for [`JmapMailboxGet::new`].
80#[derive(Clone, Debug, Default)]
81pub struct JmapMailboxGetOptions {
82    /// Restrict the fetch to these mailbox IDs; `None` fetches all.
83    pub ids: Option<Vec<String>>,
84    /// Restrict the returned properties; `None` returns all.
85    pub properties: Option<Vec<JmapMailboxProperty>>,
86}
87
88/// Successful terminal output of [`JmapMailboxGet`].
89#[derive(Clone, Debug)]
90pub struct JmapMailboxGetOutput {
91    /// The fetched mailboxes.
92    pub mailboxes: Vec<JmapMailbox>,
93    /// The requested ids the server did not find.
94    pub not_found: Vec<String>,
95    /// The new server state after the call.
96    pub new_state: String,
97    /// Whether the server indicated the connection can be reused.
98    pub keep_alive: bool,
99}
100
101/// I/O-free coroutine for the JMAP `Mailbox/get` method.
102pub struct JmapMailboxGet {
103    state: State,
104}
105
106impl JmapMailboxGet {
107    /// Prepares the method call request and builds the coroutine.
108    pub fn new(
109        session: &JmapSession,
110        http_auth: &SecretString,
111        opts: JmapMailboxGetOptions,
112    ) -> Result<Self, JmapMailboxGetError> {
113        let account_id = session
114            .primary_accounts
115            .get(JMAP_MAIL_CAPABILITY)
116            .cloned()
117            .unwrap_or_default();
118        let api_url = &session.api_url;
119
120        let props = opts.properties.map(|ps| {
121            ps.iter()
122                .map(|p| {
123                    serde_json::to_value(p)
124                        .ok()
125                        .and_then(|v| v.as_str().map(str::to_owned))
126                        .unwrap_or_else(|| format!("{p:?}"))
127                })
128                .collect()
129        });
130
131        Ok(Self {
132            state: State::Get(JmapGet::new(
133                account_id,
134                http_auth,
135                api_url,
136                "Mailbox/get",
137                vec![JMAP_CORE_CAPABILITY.into(), JMAP_MAIL_CAPABILITY.into()],
138                JmapGetOptions {
139                    ids: opts.ids,
140                    properties: props,
141                },
142            )?),
143        })
144    }
145}
146
147impl JmapCoroutine for JmapMailboxGet {
148    type Yield = JmapYield;
149    type Return = Result<JmapMailboxGetOutput, JmapMailboxGetError>;
150
151    fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
152        match &mut self.state {
153            State::Get(get) => {
154                let JmapGetOutput {
155                    list,
156                    not_found,
157                    state,
158                    keep_alive,
159                } = jmap_try!(get, arg);
160                JmapCoroutineState::Complete(Ok(JmapMailboxGetOutput {
161                    mailboxes: list,
162                    not_found,
163                    new_state: state,
164                    keep_alive,
165                }))
166            }
167        }
168    }
169}
170
171enum State {
172    Get(JmapGet<JmapMailbox>),
173}