Skip to main content

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

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