BlueGit

ict rusty-teams

Files

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

client.rs

client.rs 10.5 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, Chat, Member, Message, 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}
19
20impl Graph {
21 pub fn new(session: Session) -> Self {
22 Graph { session }
23 }
24
25 pub fn session(&self) -> &Session {
26 &self.session
27 }
28
29 pub async fn me(&self) -> Result<User> {
30 let body = self.get(&urls::me(), &Scope::graph("User.Read")).await?;
31 Ok(serde_json::from_value(body)?)
32 }
33
34 pub async fn chats_page(&self, top: usize) -> Result<Page<Chat>> {
35 self.get_page(&urls::chats(top), Scope::graph("Chat.Read"))
36 .await
37 }
38
39 pub async fn chats_at(&self, next_link: &str) -> Result<Page<Chat>> {
40 self.get_page(next_link, Scope::graph("Chat.Read")).await
41 }
42
43 pub async fn chat(&self, chat_id: &str) -> Result<Chat> {
44 let body = self
45 .get(&urls::chat(chat_id), &Scope::graph("Chat.Read"))
46 .await?;
47 Ok(serde_json::from_value(body)?)
48 }
49
50 pub async fn chat_members(&self, chat_id: &str) -> Result<Vec<Member>> {
51 self.get_all(&urls::chat_members(chat_id), Scope::graph("Chat.Read"))
52 .await
53 }
54
55 pub async fn chat_message(&self, chat_id: &str, message_id: &str) -> Result<Message> {
56 let body = self
57 .get(
58 &urls::chat_message(chat_id, message_id),
59 &Scope::graph("Chat.Read"),
60 )
61 .await?;
62 Ok(serde_json::from_value(body)?)
63 }
64
65 pub async fn chat_messages_by_id(
66 &self,
67 chat_id: &str,
68 message_ids: &[String],
69 ) -> Result<Vec<Result<Message>>> {
70 let scope = Scope::graph("Chat.Read");
71 let mut messages = Vec::with_capacity(message_ids.len());
72 for chunk in message_ids.chunks(BATCH_SIZE) {
73 let requests: Vec<Request> = chunk
74 .iter()
75 .map(|message_id| Request::get(urls::chat_message(chat_id, message_id)))
76 .collect();
77 let answers = self.session.batch(&requests, &scope).await?;
78 for (request, answer) in requests.iter().zip(answers) {
79 messages.push(if answer.is_success() {
80 serde_json::from_value(answer.body).map_err(Into::into)
81 } else {
82 Err(session::Error::api(answer.status, &request.url, answer.body).into())
83 });
84 }
85 }
86 Ok(messages)
87 }
88
89 pub async fn list_chats(&self, limit: usize) -> Result<Vec<Chat>> {
90 let mut page = self.chats_page(limit.clamp(1, CHAT_PAGE_SIZE)).await?;
91 let mut chats = std::mem::take(&mut page.items);
92 while chats.len() < limit {
93 let Some(mut next) = self.next_page(&page).await? else {
94 break;
95 };
96 chats.append(&mut std::mem::take(&mut next.items));
97 page = next;
98 }
99 chats.truncate(limit);
100 Ok(chats)
101 }
102
103 pub async fn chat_messages(
104 &self,
105 chat_id: &str,
106 before: Option<DateTime<Utc>>,
107 top: usize,
108 ) -> Result<Page<Message>> {
109 let url = urls::chat_messages(chat_id, before, top.clamp(1, MESSAGE_PAGE_SIZE));
110 self.get_page(&url, Scope::graph("Chat.Read")).await
111 }
112
113 pub async fn joined_teams(&self) -> Result<Vec<Team>> {
114 self.get_all(&urls::joined_teams(), Scope::graph("Team.ReadBasic.All"))
115 .await
116 }
117
118 pub async fn channels(&self, team_id: &str) -> Result<Vec<Channel>> {
119 self.get_all(
120 &urls::channels(team_id),
121 Scope::graph("Channel.ReadBasic.All"),
122 )
123 .await
124 }
125
126 pub async fn channels_for_teams(
127 &self,
128 team_ids: &[String],
129 ) -> Result<Vec<Result<Vec<Channel>>>> {
130 let scope = Scope::graph("Channel.ReadBasic.All");
131 let mut listings = Vec::with_capacity(team_ids.len());
132 for chunk in team_ids.chunks(BATCH_SIZE) {
133 let requests: Vec<Request> = chunk
134 .iter()
135 .map(|team_id| Request::get(urls::channels(team_id)))
136 .collect();
137 let answers = self.session.batch(&requests, &scope).await?;
138 for (request, answer) in requests.iter().zip(answers) {
139 listings.push(self.collect_pages(&request.url, answer, &scope).await);
140 }
141 }
142 Ok(listings)
143 }
144
145 pub async fn channel_message(
146 &self,
147 team_id: &str,
148 channel_id: &str,
149 message_id: &str,
150 ) -> Result<Message> {
151 let url = urls::channel_message(team_id, channel_id, message_id);
152 let body = self
153 .get(&url, &Scope::graph("ChannelMessage.Read.All"))
154 .await?;
155 Ok(serde_json::from_value(body)?)
156 }
157
158 pub async fn channel_reply(
159 &self,
160 team_id: &str,
161 channel_id: &str,
162 message_id: &str,
163 reply_id: &str,
164 ) -> Result<Message> {
165 let url = urls::channel_reply(team_id, channel_id, message_id, reply_id);
166 let body = self
167 .get(&url, &Scope::graph("ChannelMessage.Read.All"))
168 .await?;
169 Ok(serde_json::from_value(body)?)
170 }
171
172 pub async fn channel_replies(
173 &self,
174 team_id: &str,
175 channel_id: &str,
176 root_ids: &[String],
177 ) -> Result<Vec<Result<Vec<Message>>>> {
178 let scope = Scope::graph("ChannelMessage.Read.All");
179 let mut listings = Vec::with_capacity(root_ids.len());
180 for chunk in root_ids.chunks(BATCH_SIZE) {
181 let requests: Vec<Request> = chunk
182 .iter()
183 .map(|root_id| {
184 Request::get(urls::channel_replies(
185 team_id,
186 channel_id,
187 root_id,
188 MESSAGE_PAGE_SIZE,
189 ))
190 })
191 .collect();
192 let answers = self.session.batch(&requests, &scope).await?;
193 for (request, answer) in requests.iter().zip(answers) {
194 listings.push(self.collect_pages(&request.url, answer, &scope).await);
195 }
196 }
197 Ok(listings)
198 }
199
200 pub async fn channel_delta(
201 &self,
202 team_id: &str,
203 channel_id: &str,
204 modified_after: Option<DateTime<Utc>>,
205 ) -> Result<Page<Message>> {
206 let url = urls::channel_delta(team_id, channel_id, modified_after);
207 self.get_page(&url, Scope::graph("ChannelMessage.Read.All"))
208 .await
209 }
210
211 pub async fn search_people(&self, query: &str) -> Result<Vec<User>> {
212 let scope = Scope::graph("User.ReadBasic.All");
213 let query = query.trim();
214 if query.contains('@') {
215 return Ok(self
216 .get_page::<User>(&urls::user_by_address(query), scope)
217 .await?
218 .items);
219 }
220 let mut request = Request::get(urls::people_search(query, PEOPLE_PAGE_SIZE));
221 request
222 .headers
223 .push(("ConsistencyLevel".to_owned(), "eventual".to_owned()));
224 let answer = self
225 .session
226 .batch(std::slice::from_ref(&request), &scope)
227 .await?
228 .remove(0);
229 self.collect_pages::<User>(&request.url, answer, &scope)
230 .await
231 }
232
233 pub async fn channel_messages(
234 &self,
235 team_id: &str,
236 channel_id: &str,
237 top: usize,
238 ) -> Result<Page<Message>> {
239 let url = urls::channel_messages(team_id, channel_id, top.clamp(1, MESSAGE_PAGE_SIZE));
240 self.get_page(&url, Scope::graph("ChannelMessage.Read.All"))
241 .await
242 }
243
244 pub async fn channel_messages_at(&self, next_link: &str) -> Result<Page<Message>> {
245 self.get_page(next_link, Scope::graph("ChannelMessage.Read.All"))
246 .await
247 }
248
249 pub async fn channel_delta_at(&self, link: &str) -> Result<Page<Message>> {
250 self.get_page(link, Scope::graph("ChannelMessage.Read.All"))
251 .await
252 }
253
254 pub async fn next_page<T: DeserializeOwned>(&self, page: &Page<T>) -> Result<Option<Page<T>>> {
255 let Some(link) = page.next_link.as_deref() else {
256 return Ok(None);
257 };
258 Ok(Some(self.get_page(link, page.scope.clone()).await?))
259 }
260
261 pub(crate) async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
262 ensure_graph_url(url)?;
263 Ok(self
264 .session
265 .request(Method::Get, url, scope, None)
266 .await?
267 .body)
268 }
269
270 async fn get_page<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Page<T>> {
271 let body = self.get(url, &scope).await?;
272 Page::parse(body, scope)
273 }
274
275 async fn collect_pages<T: DeserializeOwned>(
276 &self,
277 url: &str,
278 answer: ApiResponse,
279 scope: &Scope,
280 ) -> Result<Vec<T>> {
281 if !answer.is_success() {
282 return Err(session::Error::api(answer.status, url, answer.body).into());
283 }
284 let mut page: Page<T> = Page::parse(answer.body, scope.clone())?;
285 let mut items = std::mem::take(&mut page.items);
286 while let Some(mut next) = self.next_page(&page).await? {
287 items.append(&mut std::mem::take(&mut next.items));
288 page = next;
289 }
290 Ok(items)
291 }
292
293 pub(crate) async fn get_all<T: DeserializeOwned>(
294 &self,
295 url: &str,
296 scope: Scope,
297 ) -> Result<Vec<T>> {
298 let mut page: Page<T> = self.get_page(url, scope).await?;
299 let mut items = std::mem::take(&mut page.items);
300 while let Some(mut next) = self.next_page(&page).await? {
301 items.append(&mut std::mem::take(&mut next.items));
302 page = next;
303 }
304 Ok(items)
305 }
306}
307
308pub(crate) fn ensure_graph_url(url: &str) -> Result<()> {
309 match url.strip_prefix(GRAPH) {
310 Some(rest) if rest.starts_with('/') => Ok(()),
311 _ => Err(Error::ForeignNextLink),
312 }
313}
314
315#[cfg(test)]
316mod tests {
317 use super::*;
318
319 #[test]
320 fn accepts_graph_urls_only() {
321 assert!(ensure_graph_url("https://graph.microsoft.com/v1.0/me/chats?$skiptoken=x").is_ok());
322 assert!(ensure_graph_url("https://graph.microsoft.com.evil.example/v1.0/me").is_err());
323 assert!(ensure_graph_url("https://example.com/v1.0/me").is_err());
324 }
325}