io_jmap/rfc8621/identity/get.rs
1//! JMAP `Identity/get` coroutine (RFC 8621 ยง6.3): wraps the generic [`JmapGet`]
2//! with the Submission capability.
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::JmapSession,
15//! rfc8621::identity::get::{JmapIdentityGet, JmapIdentityGetOptions},
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//! JmapIdentityGet::new(&session, &auth, JmapIdentityGetOptions::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!("{} identities", out.identities.len());
54//! ```
55
56use core::fmt;
57
58use alloc::{string::String, vec, vec::Vec};
59
60use log::trace;
61use secrecy::SecretString;
62use thiserror::Error;
63
64use crate::{
65 coroutine::*,
66 jmap_try,
67 rfc8620::{CORE_CAPABILITY, JmapSession, get::*},
68 rfc8621::{MAIL_CAPABILITY, email_submission::SUBMISSION_CAPABILITY, identity::JmapIdentity},
69};
70
71/// Failure causes during a JMAP `Identity/get` flow.
72#[derive(Debug, Error)]
73pub enum JmapIdentityGetError {
74 #[error("JMAP Identity/get failed: {0}")]
75 Get(#[from] JmapGetError),
76}
77
78/// Options for [`JmapIdentityGet::new`].
79#[derive(Clone, Debug, Default)]
80pub struct JmapIdentityGetOptions {
81 /// Restrict the fetch to these identity IDs; `None` fetches all.
82 pub ids: Option<Vec<String>>,
83}
84
85/// Successful terminal output of [`JmapIdentityGet`].
86#[derive(Clone, Debug)]
87pub struct JmapIdentityGetOutput {
88 pub identities: Vec<JmapIdentity>,
89 pub not_found: Vec<String>,
90 pub new_state: String,
91 pub keep_alive: bool,
92}
93
94/// I/O-free coroutine for the JMAP `Identity/get` method.
95pub struct JmapIdentityGet {
96 state: State,
97}
98
99impl JmapIdentityGet {
100 pub fn new(
101 session: &JmapSession,
102 http_auth: &SecretString,
103 opts: JmapIdentityGetOptions,
104 ) -> Result<Self, JmapIdentityGetError> {
105 let account_id = session
106 .primary_accounts
107 .get(MAIL_CAPABILITY)
108 .cloned()
109 .unwrap_or_default();
110 let api_url = &session.api_url;
111
112 Ok(Self {
113 state: State::Get(JmapGet::new(
114 account_id,
115 http_auth,
116 api_url,
117 "Identity/get",
118 vec![
119 CORE_CAPABILITY.into(),
120 MAIL_CAPABILITY.into(),
121 SUBMISSION_CAPABILITY.into(),
122 ],
123 JmapGetOptions {
124 ids: opts.ids,
125 properties: None,
126 },
127 )?),
128 })
129 }
130}
131
132impl JmapCoroutine for JmapIdentityGet {
133 type Yield = JmapYield;
134 type Return = Result<JmapIdentityGetOutput, JmapIdentityGetError>;
135
136 fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
137 trace!("Identity/get: {}", self.state);
138 match &mut self.state {
139 State::Get(get) => {
140 let JmapGetOutput {
141 list,
142 not_found,
143 state,
144 keep_alive,
145 } = jmap_try!(get, arg);
146 JmapCoroutineState::Complete(Ok(JmapIdentityGetOutput {
147 identities: list,
148 not_found,
149 new_state: state,
150 keep_alive,
151 }))
152 }
153 }
154 }
155}
156
157enum State {
158 Get(JmapGet<JmapIdentity>),
159}
160
161impl fmt::Display for State {
162 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
163 match self {
164 Self::Get(_) => f.write_str("get"),
165 }
166 }
167}