use alloc::{format, string::String, vec::Vec};
use io_http::rfc6750::bearer::HttpAuthBearer;
use log::{debug, trace};
use serde::{Deserialize, Serialize, de::DeserializeOwned};
use url::Url;
use crate::{
coroutine::*,
msgraph_try,
v1::send::{MSGRAPH_API_BASE, MsgraphSend, MsgraphSendError, MsgraphSendOutput},
};
#[derive(Debug, Clone, Deserialize, Serialize, Eq, PartialEq)]
pub struct MsgraphPage<T> {
#[serde(default = "Vec::new")]
pub value: Vec<T>,
#[serde(default, rename = "@odata.nextLink")]
pub next_link: Option<String>,
#[serde(
default,
rename = "@odata.deltaLink",
skip_serializing_if = "Option::is_none"
)]
pub delta_link: Option<String>,
#[serde(
default,
rename = "@odata.count",
skip_serializing_if = "Option::is_none"
)]
pub count: Option<u64>,
}
impl<T> Default for MsgraphPage<T> {
fn default() -> Self {
Self {
value: Vec::new(),
next_link: None,
delta_link: None,
count: None,
}
}
}
pub struct MsgraphPageGet<T> {
send: MsgraphSend<MsgraphPage<T>>,
}
impl<T: DeserializeOwned> MsgraphPageGet<T> {
pub fn new(auth: &HttpAuthBearer, link: &str) -> Result<Self, MsgraphSendError> {
debug!("prepare microsoft graph page retrieval");
trace!("link: {link:?}");
let send = MsgraphSend::get(auth, link_url(link)?);
Ok(Self { send })
}
pub fn max_page_size(mut self, size: u32) -> Self {
self.send = self.send.max_page_size(size);
self
}
}
impl<T: DeserializeOwned> MsgraphCoroutine for MsgraphPageGet<T> {
type Yield = MsgraphYield;
type Return = Result<MsgraphSendOutput<MsgraphPage<T>>, MsgraphSendError>;
fn resume(&mut self, arg: Option<&[u8]>) -> MsgraphCoroutineState<Self::Yield, Self::Return> {
let out = msgraph_try!(&mut self.send, arg);
debug!("page received");
trace!("items: {}", out.response.value.len());
MsgraphCoroutineState::Complete(Ok(out))
}
}
pub(crate) fn link_url(link: &str) -> Result<Url, MsgraphSendError> {
let url = Url::parse(link)?;
let origin = url.origin();
if origin != Url::parse(MSGRAPH_API_BASE)?.origin() {
let origin = origin.ascii_serialization();
let reason = format!("a link to `{origin}` leaves the Microsoft Graph origin");
return Err(MsgraphSendError::InvalidRequest(reason));
}
Ok(url)
}
#[cfg(test)]
mod tests {
use alloc::string::String;
use crate::v1::page::MsgraphPage;
#[test]
fn a_page_leaves_out_the_links_and_the_count_it_does_not_hold() {
let page = MsgraphPage::<String> {
value: [String::from("a")].into(),
..Default::default()
};
assert_eq!(
serde_json::to_string(&page).unwrap(),
r#"{"value":["a"],"@odata.nextLink":null}"#
);
let read: MsgraphPage<String> =
serde_json::from_str(r#"{ "@odata.deltaLink": "d", "@odata.count": 3 }"#).unwrap();
assert!(read.value.is_empty());
assert_eq!(read.delta_link.as_deref(), Some("d"));
assert_eq!(read.count, Some(3));
}
}