jmap_chat_client/methods/contact.rs
1//! JMAP Chat — ChatContact/* method implementations on SessionClient.
2//!
3//! Spec: JMAP Chat draft §5 (ChatContact/get, /changes, /set, /query, /queryChanges).
4
5use jmap_types::{Id, PatchObject, State};
6
7use super::{
8 ChangesResponse, ChatContactPatch, ChatContactQueryInput, GetResponse, QueryChangesResponse,
9 QueryResponse, SetResponse,
10};
11
12impl super::SessionClient {
13 /// Fetch ChatContact objects by IDs (JMAP Chat §5 ChatContact/get).
14 ///
15 /// If `ids` is `None`, returns all ChatContacts for the account.
16 ///
17 /// # Errors
18 ///
19 /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
20 /// if the bound session has no primary account for
21 /// `urn:ietf:params:jmap:chat`.
22 /// - Any transport / protocol variant returned by
23 /// [`JmapClient::call`](jmap_base_client::JmapClient::call):
24 /// [`Http`](jmap_base_client::ClientError::Http),
25 /// [`Parse`](jmap_base_client::ClientError::Parse),
26 /// [`AuthFailed`](jmap_base_client::ClientError::AuthFailed),
27 /// [`MethodError`](jmap_base_client::ClientError::MethodError)
28 /// (wraps RFC 8620 §3.6.2 method-level errors such as
29 /// `accountNotFound`, `invalidArguments`, `serverFail`),
30 /// [`MethodNotFound`](jmap_base_client::ClientError::MethodNotFound),
31 /// [`ResponseTooLarge`](jmap_base_client::ClientError::ResponseTooLarge),
32 /// or
33 /// [`UnexpectedResponse`](jmap_base_client::ClientError::UnexpectedResponse).
34 pub async fn chat_contact_get(
35 &self,
36 ids: Option<&[Id]>,
37 properties: Option<&[&str]>,
38 ) -> Result<GetResponse<jmap_chat_types::ChatContact>, jmap_base_client::ClientError> {
39 let (api_url, account_id) = self.session_parts()?;
40 // Omit `ids` / `properties` when None — see the matching comment on
41 // `chat_get` for the rationale (consistent with set/changes/query).
42 let mut args = serde_json::json!({ "accountId": account_id });
43 if let Some(id_slice) = ids {
44 args["ids"] = serde_json::to_value(id_slice)
45 .map_err(jmap_base_client::ClientError::from_parse)?;
46 }
47 if let Some(props) = properties {
48 args["properties"] =
49 serde_json::to_value(props).map_err(jmap_base_client::ClientError::from_parse)?;
50 }
51 let req = super::build_request("ChatContact/get", args, super::USING_CHAT);
52 let resp = self.call_internal(api_url, &req).await?;
53 jmap_base_client::extract_response(&resp, super::CALL_ID)
54 }
55
56 /// Fetch changes to ChatContact objects since `since_state` (RFC 8620 §5.2).
57 ///
58 /// # Errors
59 ///
60 /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
61 /// if `since_state` is the empty string (defence-in-depth —
62 /// `State` constructed via [`State::from`](jmap_types::State::from)
63 /// accepts empty strings, but an empty `sinceState` is never
64 /// useful and would otherwise generate a wasted round-trip).
65 /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
66 /// if the bound session has no primary account for
67 /// `urn:ietf:params:jmap:chat`.
68 /// - Any transport / protocol variant returned by
69 /// [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
70 /// the matching error list on [`Self::chat_contact_get`].
71 pub async fn chat_contact_changes(
72 &self,
73 since_state: &State,
74 max_changes: Option<u64>,
75 ) -> Result<ChangesResponse, jmap_base_client::ClientError> {
76 // Defence-in-depth: see `chat_changes`.
77 if since_state.as_ref().is_empty() {
78 return Err(jmap_base_client::ClientError::InvalidArgument(
79 "chat_contact_changes: since_state may not be empty".into(),
80 ));
81 }
82 let (api_url, account_id) = self.session_parts()?;
83 let mut args = serde_json::json!({
84 "accountId": account_id,
85 "sinceState": since_state,
86 });
87 if let Some(mc) = max_changes {
88 args["maxChanges"] = mc.into();
89 }
90 let req = super::build_request("ChatContact/changes", args, super::USING_CHAT);
91 let resp = self.call_internal(api_url, &req).await?;
92 jmap_base_client::extract_response(&resp, super::CALL_ID)
93 }
94
95 /// Update ChatContact properties (JMAP Chat §ChatContact/set).
96 ///
97 /// Supports `blocked` (Boolean) and `displayName` (nullable String).
98 /// Create and destroy are not supported by spec; the server returns `forbidden`.
99 ///
100 /// # Errors
101 ///
102 /// - [`ClientError::Parse`](jmap_base_client::ClientError::Parse) if
103 /// serializing the typed `display_name` Clearable entry fails
104 /// (pathological conditions only).
105 /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
106 /// if the bound session has no primary account for
107 /// `urn:ietf:params:jmap:chat`.
108 /// - Any transport / protocol variant returned by
109 /// [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
110 /// the matching error list on [`Self::chat_contact_get`]. /set
111 /// update errors appear in
112 /// [`SetResponse::not_updated`] rather than as
113 /// [`Err`].
114 pub async fn chat_contact_update(
115 &self,
116 id: &Id,
117 patch: &ChatContactPatch<'_>,
118 ) -> Result<SetResponse, jmap_base_client::ClientError> {
119 let (api_url, account_id) = self.session_parts()?;
120 let mut patch_map = serde_json::Map::new();
121 if let Some(b) = patch.blocked {
122 patch_map.insert("blocked".into(), b.into());
123 }
124 if let Some(entry) = patch
125 .display_name
126 .map_entry()
127 .map_err(jmap_base_client::ClientError::from_parse)?
128 {
129 patch_map.insert("displayName".into(), entry);
130 }
131 // Wrap the constructed map in a PatchObject (RFC 8620 §5.3) before
132 // serializing. Wire bytes are unchanged because PatchObject is
133 // #[serde(transparent)]; the typed boundary documents the contract.
134 let patch_value = serde_json::Value::Object(PatchObject::from_map(patch_map).into_inner());
135 let args = serde_json::json!({
136 "accountId": account_id,
137 "update": { id.as_ref(): patch_value },
138 });
139 let req = super::build_request("ChatContact/set", args, super::USING_CHAT);
140 let resp = self.call_internal(api_url, &req).await?;
141 jmap_base_client::extract_response(&resp, super::CALL_ID)
142 }
143
144 /// Query ChatContact IDs with optional filter (JMAP Chat §ChatContact/query).
145 ///
146 /// Supported filter keys: `blocked`, `presence`. Supported sort properties:
147 /// `"lastSeenAt"`, `"login"`, `"lastActiveAt"`.
148 ///
149 /// # Errors
150 ///
151 /// - [`ClientError::Parse`](jmap_base_client::ClientError::Parse) if
152 /// serializing the typed `filter_presence` enum or
153 /// `sort_property` enum fails (pathological conditions only).
154 /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
155 /// if the bound session has no primary account for
156 /// `urn:ietf:params:jmap:chat`.
157 /// - Any transport / protocol variant returned by
158 /// [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
159 /// the matching error list on [`Self::chat_contact_get`]. RFC
160 /// 8620 §5.5 defines additional /query method-level errors
161 /// (`anchorNotFound`, `unsupportedFilter`, `unsupportedSort`,
162 /// `tooManyChanges`) that surface as
163 /// [`MethodError`](jmap_base_client::ClientError::MethodError).
164 pub async fn chat_contact_query(
165 &self,
166 input: &ChatContactQueryInput,
167 ) -> Result<QueryResponse, jmap_base_client::ClientError> {
168 let (api_url, account_id) = self.session_parts()?;
169 let mut filter = serde_json::Map::new();
170 if let Some(b) = input.filter_blocked {
171 filter.insert("blocked".into(), b.into());
172 }
173 if let Some(p) = &input.filter_presence {
174 filter.insert(
175 "presence".into(),
176 serde_json::to_value(p).map_err(jmap_base_client::ClientError::from_parse)?,
177 );
178 }
179 let filter_val = if filter.is_empty() {
180 serde_json::Value::Null
181 } else {
182 serde_json::Value::Object(filter)
183 };
184 let mut args = serde_json::json!({
185 "accountId": account_id,
186 "filter": filter_val,
187 });
188 if let Some(sp) = &input.sort_property {
189 let property =
190 serde_json::to_value(sp).map_err(jmap_base_client::ClientError::from_parse)?;
191 args["sort"] = serde_json::json!([{
192 "property": property,
193 "isAscending": input.sort_ascending.unwrap_or(false),
194 }]);
195 }
196 if let Some(p) = input.position {
197 args["position"] = p.into();
198 }
199 if let Some(l) = input.limit {
200 args["limit"] = l.into();
201 }
202 let req = super::build_request("ChatContact/query", args, super::USING_CHAT);
203 let resp = self.call_internal(api_url, &req).await?;
204 jmap_base_client::extract_response(&resp, super::CALL_ID)
205 }
206
207 /// Fetch query-result changes for ChatContact since `since_query_state`
208 /// (RFC 8620 §5.6 / ChatContact/queryChanges).
209 ///
210 /// `filter` and `sort` MUST match the `filter` / `sort` passed to the
211 /// original `ChatContact/query` call that returned `since_query_state`
212 /// — RFC 8620 §5.6 is explicit that the server uses them to compute
213 /// which entries entered or left the result set.
214 ///
215 /// `up_to_id` is the highest-index id the client has cached;
216 /// `calculate_total` requests the new total result count.
217 ///
218 /// # Errors
219 ///
220 /// - [`ClientError::InvalidArgument`](jmap_base_client::ClientError::InvalidArgument)
221 /// if `since_query_state` is the empty string (defence-in-depth
222 /// empty-state guard; see [`Self::chat_contact_changes`]).
223 /// - [`ClientError::InvalidSession`](jmap_base_client::ClientError::InvalidSession)
224 /// if the bound session has no primary account for
225 /// `urn:ietf:params:jmap:chat`.
226 /// - Any transport / protocol variant returned by
227 /// [`JmapClient::call`](jmap_base_client::JmapClient::call) — see
228 /// the matching error list on [`Self::chat_contact_get`]. RFC
229 /// 8620 §5.6 also defines `cannotCalculateChanges` (returned when
230 /// the server cannot honour the request given the supplied
231 /// filter / sort); it surfaces as
232 /// [`MethodError`](jmap_base_client::ClientError::MethodError).
233 pub async fn chat_contact_query_changes(
234 &self,
235 since_query_state: &State,
236 max_changes: Option<u64>,
237 filter: Option<serde_json::Value>,
238 sort: Option<serde_json::Value>,
239 up_to_id: Option<&Id>,
240 calculate_total: Option<bool>,
241 ) -> Result<QueryChangesResponse, jmap_base_client::ClientError> {
242 // Defence-in-depth: see `chat_changes`.
243 if since_query_state.as_ref().is_empty() {
244 return Err(jmap_base_client::ClientError::InvalidArgument(
245 "chat_contact_query_changes: since_query_state may not be empty".into(),
246 ));
247 }
248 let (api_url, account_id) = self.session_parts()?;
249 let mut args = serde_json::json!({
250 "accountId": account_id,
251 "sinceQueryState": since_query_state,
252 });
253 if let Some(f) = filter {
254 args["filter"] = f;
255 }
256 if let Some(s) = sort {
257 args["sort"] = s;
258 }
259 if let Some(mc) = max_changes {
260 args["maxChanges"] = mc.into();
261 }
262 if let Some(uti) = up_to_id {
263 args["upToId"] =
264 serde_json::to_value(uti).map_err(jmap_base_client::ClientError::from_parse)?;
265 }
266 if let Some(ct) = calculate_total {
267 args["calculateTotal"] = ct.into();
268 }
269 let req = super::build_request("ChatContact/queryChanges", args, super::USING_CHAT);
270 let resp = self.call_internal(api_url, &req).await?;
271 jmap_base_client::extract_response(&resp, super::CALL_ID)
272 }
273}