BlueGit

ict rusty-teams

Files

rusty-teams / crates / graph / src / client.rs

client.rs

client.rs 9.8 KiB Download Raw
1use chrono::{DateTime, Utc};
2use serde::de::DeserializeOwned;
3use serde_json::Value;
4use session::{ApiResponse, GRAPH, Method, Request, Scope, Session};
5
6use crate::error::{Error, Result};
7use crate::models::{Channel, Message, Tag, Team, User};
8use crate::page::Page;
9use crate::urls;
10
11pub const CHAT_PAGE_SIZE: usize = 50;
12pub const MESSAGE_PAGE_SIZE: usize = 50;
13pub const BATCH_SIZE: usize = 20;
14const PEOPLE_PAGE_SIZE: usize = 10;
15
16pub struct Graph {
17 session: Session,
18 home_drive: Option<Session>,
19}
20
21impl Graph {
22 pub fn new(session: Session) -> Self {
23 Graph {
24 session,
25 home_drive: None,
26 }
27 }
28
29 /// Chat files go to the OneDrive of `home`, the account's home tenant.
30 /// For a guest org, where the account has no OneDrive.
31 pub fn with_home_drive(mut self, home: Session) -> Self {
32 self.home_drive = Some(home);
33 self
34 }
35
36 pub fn session(&self) -> &Session {
37 &self.session
38 }
39
40 /// The session that owns the file. A home-drive file with no home session is an error:
41 /// falling back to the guest session would delete or share it in the wrong tenant.
42 pub(crate) fn drive_session(&self, home: bool) -> Result<&Session> {
43 if !home {
44 return Ok(&self.session);
45 }
46 self.home_drive.as_ref().ok_or_else(|| {
47 Error::Upload(
48 "the file is in the home drive, but this session has no home tenant".into(),
49 )
50 })
51 }
52
53 pub(crate) fn has_home_drive(&self) -> bool {
54 self.home_drive.is_some()
55 }
56
57 pub async fn me(&self) -> Result<User> {
58 let body = self
59 .get(&urls::me(), &Scope::graph("User.ReadBasic.All"))
60 .await?;
61 Ok(serde_json::from_value(body)?)
62 }
63
64 pub async fn joined_teams(&self) -> Result<Vec<Team>> {
65 self.get_all(&urls::joined_teams(), Scope::graph("Team.ReadBasic.All"))
66 .await
67 }
68
69 pub async fn team_tags(&self, team_id: &str) -> Result<Vec<Tag>> {
70 self.get_all(&urls::team_tags(team_id), Scope::graph("TeamworkTag.Read"))
71 .await
72 }
73
74 pub async fn channels(&self, team_id: &str) -> Result<Vec<Channel>> {
75 self.get_all(
76 &urls::channels(team_id),
77 Scope::graph("Channel.ReadBasic.All"),
78 )
79 .await
80 }
81
82 pub async fn channel_description(&self, team_id: &str, channel_id: &str) -> Result<String> {
83 let body = self
84 .get(
85 &urls::channel_description(team_id, channel_id),
86 &Scope::graph("Channel.ReadBasic.All"),
87 )
88 .await?;
89 Ok(body
90 .get("description")
91 .and_then(Value::as_str)
92 .unwrap_or_default()
93 .to_owned())
94 }
95
96 pub async fn channels_for_teams(
97 &self,
98 team_ids: &[String],
99 ) -> Result<Vec<Result<Vec<Channel>>>> {
100 let scope = Scope::graph("Channel.ReadBasic.All");
101 let mut listings = Vec::with_capacity(team_ids.len());
102 for chunk in team_ids.chunks(BATCH_SIZE) {
103 let requests: Vec<Request> = chunk
104 .iter()
105 .map(|team_id| Request::get(urls::channels(team_id)))
106 .collect();
107 let answers = self.session.batch(&requests, &scope).await?;
108 for (request, answer) in requests.iter().zip(answers) {
109 listings.push(self.collect_pages(&request.url, answer, &scope).await);
110 }
111 }
112 Ok(listings)
113 }
114
115 pub async fn channel_message(
116 &self,
117 team_id: &str,
118 channel_id: &str,
119 message_id: &str,
120 ) -> Result<Message> {
121 let url = urls::channel_message(team_id, channel_id, message_id);
122 let body = self
123 .get(&url, &Scope::graph("ChannelMessage.Read.All"))
124 .await?;
125 Ok(serde_json::from_value(body)?)
126 }
127
128 pub async fn channel_reply(
129 &self,
130 team_id: &str,
131 channel_id: &str,
132 message_id: &str,
133 reply_id: &str,
134 ) -> Result<Message> {
135 let url = urls::channel_reply(team_id, channel_id, message_id, reply_id);
136 let body = self
137 .get(&url, &Scope::graph("ChannelMessage.Read.All"))
138 .await?;
139 Ok(serde_json::from_value(body)?)
140 }
141
142 pub async fn channel_replies(
143 &self,
144 team_id: &str,
145 channel_id: &str,
146 root_ids: &[String],
147 ) -> Result<Vec<Result<Vec<Message>>>> {
148 let scope = Scope::graph("ChannelMessage.Read.All");
149 let mut listings = Vec::with_capacity(root_ids.len());
150 for chunk in root_ids.chunks(BATCH_SIZE) {
151 let requests: Vec<Request> = chunk
152 .iter()
153 .map(|root_id| {
154 Request::get(urls::channel_replies(
155 team_id,
156 channel_id,
157 root_id,
158 MESSAGE_PAGE_SIZE,
159 ))
160 })
161 .collect();
162 let answers = self.session.batch(&requests, &scope).await?;
163 for (request, answer) in requests.iter().zip(answers) {
164 listings.push(self.collect_pages(&request.url, answer, &scope).await);
165 }
166 }
167 Ok(listings)
168 }
169
170 pub async fn channel_delta(
171 &self,
172 team_id: &str,
173 channel_id: &str,
174 modified_after: Option<DateTime<Utc>>,
175 ) -> Result<Page<Message>> {
176 let url = urls::channel_delta(team_id, channel_id, modified_after);
177 self.get_page(&url, Scope::graph("ChannelMessage.Read.All"))
178 .await
179 }
180
181 pub async fn search_people(&self, query: &str) -> Result<Vec<User>> {
182 let scope = Scope::graph("User.ReadBasic.All");
183 let query = query.trim();
184 if query.contains('@') {
185 return Ok(self
186 .get_page::<User>(&urls::user_by_address(query), scope)
187 .await?
188 .items);
189 }
190 match self.search_users(query, true, &scope).await {
191 Ok(users) => Ok(users),
192 Err(_) => self.search_users(query, false, &scope).await,
193 }
194 }
195
196 async fn search_users(
197 &self,
198 query: &str,
199 with_alias: bool,
200 scope: &Scope,
201 ) -> Result<Vec<User>> {
202 let mut request = Request::get(urls::people_search(query, PEOPLE_PAGE_SIZE, with_alias));
203 request
204 .headers
205 .push(("ConsistencyLevel".to_owned(), "eventual".to_owned()));
206 let answer = self
207 .session
208 .batch(std::slice::from_ref(&request), scope)
209 .await?
210 .remove(0);
211 if !answer.is_success() {
212 return Err(session::Error::api(answer.status, &request.url, answer.body).into());
213 }
214 Ok(Page::<User>::parse(answer.body, scope.clone())?.items)
215 }
216
217 pub async fn channel_messages(
218 &self,
219 team_id: &str,
220 channel_id: &str,
221 top: usize,
222 ) -> Result<Page<Message>> {
223 let url = urls::channel_messages(team_id, channel_id, top.clamp(1, MESSAGE_PAGE_SIZE));
224 self.get_page(&url, Scope::graph("ChannelMessage.Read.All"))
225 .await
226 }
227
228 pub async fn channel_messages_at(&self, next_link: &str) -> Result<Page<Message>> {
229 self.get_page(next_link, Scope::graph("ChannelMessage.Read.All"))
230 .await
231 }
232
233 pub async fn channel_delta_at(&self, link: &str) -> Result<Page<Message>> {
234 self.get_page(link, Scope::graph("ChannelMessage.Read.All"))
235 .await
236 }
237
238 pub async fn next_page<T: DeserializeOwned>(&self, page: &Page<T>) -> Result<Option<Page<T>>> {
239 let Some(link) = page.next_link.as_deref() else {
240 return Ok(None);
241 };
242 Ok(Some(self.get_page(link, page.scope.clone()).await?))
243 }
244
245 pub(crate) async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
246 ensure_graph_url(url)?;
247 Ok(self
248 .session
249 .request(Method::Get, url, scope, None)
250 .await?
251 .body)
252 }
253
254 async fn get_page<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Page<T>> {
255 let body = self.get(url, &scope).await?;
256 Page::parse(body, scope)
257 }
258
259 async fn collect_pages<T: DeserializeOwned>(
260 &self,
261 url: &str,
262 answer: ApiResponse,
263 scope: &Scope,
264 ) -> Result<Vec<T>> {
265 if !answer.is_success() {
266 return Err(session::Error::api(answer.status, url, answer.body).into());
267 }
268 let mut page: Page<T> = Page::parse(answer.body, scope.clone())?;
269 let mut items = std::mem::take(&mut page.items);
270 while let Some(mut next) = self.next_page(&page).await? {
271 items.append(&mut std::mem::take(&mut next.items));
272 page = next;
273 }
274 Ok(items)
275 }
276
277 pub(crate) async fn get_all<T: DeserializeOwned>(
278 &self,
279 url: &str,
280 scope: Scope,
281 ) -> Result<Vec<T>> {
282 let mut page: Page<T> = self.get_page(url, scope).await?;
283 let mut items = std::mem::take(&mut page.items);
284 while let Some(mut next) = self.next_page(&page).await? {
285 items.append(&mut std::mem::take(&mut next.items));
286 page = next;
287 }
288 Ok(items)
289 }
290}
291
292pub(crate) fn ensure_graph_url(url: &str) -> Result<()> {
293 match url.strip_prefix(GRAPH) {
294 Some(rest) if rest.starts_with('/') => Ok(()),
295 _ => Err(Error::ForeignNextLink),
296 }
297}
298
299#[cfg(test)]
300mod tests {
301 use super::*;
302
303 #[test]
304 fn accepts_graph_urls_only() {
305 assert!(ensure_graph_url("https://graph.microsoft.com/v1.0/me/chats?$skiptoken=x").is_ok());
306 assert!(ensure_graph_url("https://graph.microsoft.com.evil.example/v1.0/me").is_err());
307 assert!(ensure_graph_url("https://example.com/v1.0/me").is_err());
308 }
309}