io_jmap/rfc9610/contact_card/get.rs
1//! JMAP `ContactCard/get` coroutine (RFC 9610 ยง3.1): wraps the generic
2//! [`JmapGet`] with the JMAP-Contacts 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//! rfc9610::contact_card::get::{JmapContactCardGet, JmapContactCardGetOptions},
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:contacts": "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//! JmapContactCardGet::new(&session, &auth, JmapContactCardGetOptions::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!("{} cards", out.cards.len());
54//! ```
55
56use alloc::{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 rfc9610::{JMAP_CONTACTS_CAPABILITY, contact_card::JmapContactCard},
66};
67
68/// Failure causes during a JMAP `ContactCard/get` flow.
69#[derive(Debug, Error)]
70pub enum JmapContactCardGetError {
71 /// The inner generic get coroutine failed.
72 #[error("JMAP ContactCard/get failed: {0}")]
73 Get(#[from] JmapGetError),
74}
75
76/// Options for [`JmapContactCardGet::new`].
77#[derive(Clone, Debug, Default)]
78pub struct JmapContactCardGetOptions {
79 /// Restrict the fetch to these ContactCard IDs; `None` fetches all.
80 pub ids: Option<Vec<String>>,
81 /// Restrict the returned properties (JSContact property names plus `id`
82 /// and `addressBookIds`); `None` returns all.
83 pub properties: Option<Vec<String>>,
84}
85
86/// Successful terminal output of [`JmapContactCardGet`].
87#[derive(Clone, Debug)]
88pub struct JmapContactCardGetOutput {
89 /// The fetched contact cards.
90 pub cards: Vec<JmapContactCard>,
91 /// The requested ids the server did not find.
92 pub not_found: Vec<String>,
93 /// The new server state after the call.
94 pub new_state: String,
95 /// Whether the server indicated the connection can be reused.
96 pub keep_alive: bool,
97}
98
99/// I/O-free coroutine for the JMAP `ContactCard/get` method.
100pub struct JmapContactCardGet {
101 state: State,
102}
103
104impl JmapContactCardGet {
105 /// Prepares the method call request and builds the coroutine.
106 pub fn new(
107 session: &JmapSession,
108 http_auth: &SecretString,
109 opts: JmapContactCardGetOptions,
110 ) -> Result<Self, JmapContactCardGetError> {
111 let account_id = session
112 .primary_accounts
113 .get(JMAP_CONTACTS_CAPABILITY)
114 .cloned()
115 .unwrap_or_default();
116 let api_url = &session.api_url;
117
118 Ok(Self {
119 state: State::Get(JmapGet::new(
120 account_id,
121 http_auth,
122 api_url,
123 "ContactCard/get",
124 vec![JMAP_CORE_CAPABILITY.into(), JMAP_CONTACTS_CAPABILITY.into()],
125 JmapGetOptions {
126 ids: opts.ids,
127 properties: opts.properties,
128 },
129 )?),
130 })
131 }
132}
133
134impl JmapCoroutine for JmapContactCardGet {
135 type Yield = JmapYield;
136 type Return = Result<JmapContactCardGetOutput, JmapContactCardGetError>;
137
138 fn resume(&mut self, arg: Option<&[u8]>) -> JmapCoroutineState<Self::Yield, Self::Return> {
139 match &mut self.state {
140 State::Get(get) => {
141 let JmapGetOutput {
142 list,
143 not_found,
144 state,
145 keep_alive,
146 } = jmap_try!(get, arg);
147 JmapCoroutineState::Complete(Ok(JmapContactCardGetOutput {
148 cards: list,
149 not_found,
150 new_state: state,
151 keep_alive,
152 }))
153 }
154 }
155 }
156}
157
158enum State {
159 Get(JmapGet<JmapContactCard>),
160}