Skip to main content

io_msgraph/v1/rest/users/contacts/
delta.rs

1//! Track changes to Microsoft Graph contacts (`GET /me/contacts/delta`
2//! or `GET /me/contactFolders/{id}/contacts/delta`).
3//!
4//! An initial request (no delta link) enumerates every contact and
5//! ends with an `@odata.deltaLink`; feeding that link back through
6//! [`MsgraphSend`] returns only what changed since, removals arriving
7//! as `@removed`-marked rows. An expired link answers HTTP 410; the
8//! consumer falls back to an initial request.
9//!
10//! <https://learn.microsoft.com/en-us/graph/api/contact-delta>
11
12use alloc::{format, string::String, vec::Vec};
13
14use io_http::rfc6750::bearer::HttpAuthBearer;
15use log::{debug, trace};
16use serde::{Deserialize, Serialize};
17use url::Url;
18
19use crate::{
20    coroutine::*,
21    msgraph_try,
22    v1::{
23        rest::users::contacts::MsgraphContact,
24        send::{MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput, user_path},
25    },
26};
27
28/// One page of a contacts delta round.
29///
30/// More pages follow through `next_link`; the round ends when
31/// `delta_link` arrives (the token of the next round).
32#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
33pub struct MsgraphContactsDeltaResponse {
34    /// The changed contacts of the page.
35    #[serde(default)]
36    pub value: Vec<MsgraphContactDelta>,
37    /// The URL of the next page of the round, when one exists.
38    #[serde(default, rename = "@odata.nextLink")]
39    pub next_link: Option<String>,
40    /// The URL closing the round, carrying the next round's token.
41    #[serde(default, rename = "@odata.deltaLink")]
42    pub delta_link: Option<String>,
43}
44
45/// One contact row of a delta page: the contact (only its id when the
46/// row is a removal), plus the `@removed` marker.
47#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
48pub struct MsgraphContactDelta {
49    /// The changed contact.
50    #[serde(flatten)]
51    pub contact: MsgraphContact,
52    /// The removal marker, present when the row is a removal.
53    #[serde(default, rename = "@removed", skip_serializing_if = "Option::is_none")]
54    pub removed: Option<MsgraphRemoved>,
55}
56
57/// The `@removed` marker of a delta row.
58///
59/// <https://learn.microsoft.com/en-us/graph/delta-query-overview>
60#[derive(Debug, Clone, Default, Deserialize, Serialize, Eq, PartialEq)]
61pub struct MsgraphRemoved {
62    /// `deleted` for a hard delete, `changed` for an item that left
63    /// the queried scope.
64    #[serde(default)]
65    pub reason: String,
66}
67
68/// I/O-free coroutine for a contacts delta request, opening a round
69/// with [`new`](Self::new) or continuing one with
70/// [`from_link`](Self::from_link).
71pub struct MsgraphContactsDelta {
72    send: MsgraphSend<MsgraphContactsDeltaResponse>,
73}
74
75impl MsgraphContactsDelta {
76    /// Starts a delta round over the default Contacts folder, or over
77    /// `folder` when given (a contact folder id).
78    ///
79    /// `select` trims each row to the named properties (the id always
80    /// rides along).
81    pub fn new(
82        auth: &HttpAuthBearer,
83        user_id: &str,
84        folder: Option<&str>,
85        select: Option<&str>,
86    ) -> Result<Self, MsgraphSendError> {
87        debug!("prepare microsoft graph contacts delta");
88        trace!("folder: {folder:?}");
89
90        let user = user_path(user_id);
91        let path = match folder {
92            Some(folder) => format!("{user}/contactFolders/{folder}/contacts/delta"),
93            None => format!("{user}/contacts/delta"),
94        };
95        let mut url = Url::parse(MSGRAPH_API_BASE)?.join(&path)?;
96        if let Some(select) = select {
97            url.query_pairs_mut().append_pair("$select", select);
98        }
99
100        let send = MsgraphSend::get(auth, url);
101
102        Ok(Self { send })
103    }
104
105    /// Continues a round from an `@odata.nextLink`, or starts the next
106    /// round from a saved `@odata.deltaLink`.
107    ///
108    /// The link already carries the folder, the `$select` and the
109    /// server-issued token, so it is sent as-is through a plain GET.
110    pub fn from_link(auth: &HttpAuthBearer, link: &str) -> Result<Self, MsgraphSendError> {
111        debug!("prepare microsoft graph contacts delta from link");
112        trace!("link: {link:?}");
113
114        let url = Url::parse(link)?;
115        let send = MsgraphSend::get(auth, url);
116
117        Ok(Self { send })
118    }
119}
120
121impl MsgraphCoroutine for MsgraphContactsDelta {
122    type Yield = MsgraphYield;
123    type Return = Result<MsgraphSendOutput<MsgraphContactsDeltaResponse>, MsgraphSendError>;
124
125    fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
126        let out = msgraph_try!(&mut self.send, arg);
127        debug!("contacts delta page received");
128        trace!("out: {out:?}");
129        MsgraphCoroutineState::Complete(Ok(out))
130    }
131}