BlueGit

ict rusty-teams

Files

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

client.rs

Initial commit
metis Daniel Däschle · pushed by metis · 7 weeks ago
06e0ae51 History
client.rs 9.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 list_chats(&self, limit: usize) -> Result<Vec<Chat>> {
66 let mut page = self.chats_page(limit.clamp(1, CHAT_PAGE_SIZE)).await?;
67 let mut chats = std::mem::take(&mut page.items);
68 while chats.len() < limit {
69 let Some(mut next) = self.next_page(&page).await? else {
70 break;
71 };
72 chats.append(&mut std::mem::take(&mut next.items));
73 page = next;
74 }
75 chats.truncate(limit);
76 Ok(chats)
77 }
78
79 pub async fn chat_messages(
80 &self,
81 chat_id: &str,
82 before: Option<DateTime<Utc>>,
83 top: usize,
84 ) -> Result<Page<Message>> {
85 let url = urls::chat_messages(chat_id, before, top.clamp(1, MESSAGE_PAGE_SIZE));
86 self.get_page(&url, Scope::graph("Chat.Read")).await
87 }
88
89 pub async fn joined_teams(&self) -> Result<Vec<Team>> {
90 self.get_all(&urls::joined_teams(), Scope::graph("Team.ReadBasic.All"))
91 .await
92 }
93
94 pub async fn channels(&self, team_id: &str) -> Result<Vec<Channel>> {
95 self.get_all(
96 &urls::channels(team_id),
97 Scope::graph("Channel.ReadBasic.All"),
98 )
99 .await
100 }
101
102 pub async fn channels_for_teams(
103 &self,
104 team_ids: &[String],
105 ) -> Result<Vec<Result<Vec<Channel>>>> {
106 let scope = Scope::graph("Channel.ReadBasic.All");
107 let mut listings = Vec::with_capacity(team_ids.len());
108 for chunk in team_ids.chunks(BATCH_SIZE) {
109 let requests: Vec<Request> = chunk
110 .iter()
111 .map(|team_id| Request::get(urls::channels(team_id)))
112 .collect();
113 let answers = self.session.batch(&requests, &scope).await?;
114 for (request, answer) in requests.iter().zip(answers) {
115 listings.push(self.collect_pages(&request.url, answer, &scope).await);
116 }
117 }
118 Ok(listings)
119 }
120
121 pub async fn channel_message(
122 &self,
123 team_id: &str,
124 channel_id: &str,
125 message_id: &str,
126 ) -> Result<Message> {
127 let url = urls::channel_message(team_id, channel_id, message_id);
128 let body = self
129 .get(&url, &Scope::graph("ChannelMessage.Read.All"))
130 .await?;
131 Ok(serde_json::from_value(body)?)
132 }
133
134 pub async fn channel_reply(
135 &self,
136 team_id: &str,
137 channel_id: &str,
138 message_id: &str,
139 reply_id: &str,
140 ) -> Result<Message> {
141 let url = urls::channel_reply(team_id, channel_id, message_id, reply_id);
142 let body = self
143 .get(&url, &Scope::graph("ChannelMessage.Read.All"))
144 .await?;
145 Ok(serde_json::from_value(body)?)
146 }
147
148 pub async fn channel_replies(
149 &self,
150 team_id: &str,
151 channel_id: &str,
152 root_ids: &[String],
153 ) -> Result<Vec<Result<Vec<Message>>>> {
154 let scope = Scope::graph("ChannelMessage.Read.All");
155 let mut listings = Vec::with_capacity(root_ids.len());
156 for chunk in root_ids.chunks(BATCH_SIZE) {
157 let requests: Vec<Request> = chunk
158 .iter()
159 .map(|root_id| {
160 Request::get(urls::channel_replies(
161 team_id,
162 channel_id,
163 root_id,
164 MESSAGE_PAGE_SIZE,
165 ))
166 })
167 .collect();
168 let answers = self.session.batch(&requests, &scope).await?;
169 for (request, answer) in requests.iter().zip(answers) {
170 listings.push(self.collect_pages(&request.url, answer, &scope).await);
171 }
172 }
173 Ok(listings)
174 }
175
176 pub async fn channel_delta(
177 &self,
178 team_id: &str,
179 channel_id: &str,
180 modified_after: Option<DateTime<Utc>>,
181 ) -> Result<Page<Message>> {
182 let url = urls::channel_delta(team_id, channel_id, modified_after);
183 self.get_page(&url, Scope::graph("ChannelMessage.Read.All"))
184 .await
185 }
186
187 pub async fn search_people(&self, query: &str) -> Result<Vec<User>> {
188 let scope = Scope::graph("User.ReadBasic.All");
189 let query = query.trim();
190 if query.contains('@') {
191 return Ok(self
192 .get_page::<User>(&urls::user_by_address(query), scope)
193 .await?
194 .items);
195 }
196 let mut request = Request::get(urls::people_search(query, PEOPLE_PAGE_SIZE));
197 request
198 .headers
199 .push(("ConsistencyLevel".to_owned(), "eventual".to_owned()));
200 let answer = self
201 .session
202 .batch(std::slice::from_ref(&request), &scope)
203 .await?
204 .remove(0);
205 self.collect_pages::<User>(&request.url, answer, &scope)
206 .await
207 }
208
209 pub async fn channel_messages(
210 &self,
211 team_id: &str,
212 channel_id: &str,
213 top: usize,
214 ) -> Result<Page<Message>> {
215 let url = urls::channel_messages(team_id, channel_id, top.clamp(1, MESSAGE_PAGE_SIZE));
216 self.get_page(&url, Scope::graph("ChannelMessage.Read.All"))
217 .await
218 }
219
220 pub async fn channel_messages_at(&self, next_link: &str) -> Result<Page<Message>> {
221 self.get_page(next_link, Scope::graph("ChannelMessage.Read.All"))
222 .await
223 }
224
225 pub async fn channel_delta_at(&self, link: &str) -> Result<Page<Message>> {
226 self.get_page(link, Scope::graph("ChannelMessage.Read.All"))
227 .await
228 }
229
230 pub async fn next_page<T: DeserializeOwned>(&self, page: &Page<T>) -> Result<Option<Page<T>>> {
231 let Some(link) = page.next_link.as_deref() else {
232 return Ok(None);
233 };
234 Ok(Some(self.get_page(link, page.scope.clone()).await?))
235 }
236
237 async fn get(&self, url: &str, scope: &Scope) -> Result<Value> {
238 ensure_graph_url(url)?;
239 Ok(self
240 .session
241 .request(Method::Get, url, scope, None)
242 .await?
243 .body)
244 }
245
246 async fn get_page<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Page<T>> {
247 let body = self.get(url, &scope).await?;
248 Page::parse(body, scope)
249 }
250
251 async fn collect_pages<T: DeserializeOwned>(
252 &self,
253 url: &str,
254 answer: ApiResponse,
255 scope: &Scope,
256 ) -> Result<Vec<T>> {
257 if !answer.is_success() {
258 return Err(session::Error::api(answer.status, url, answer.body).into());
259 }
260 let mut page: Page<T> = Page::parse(answer.body, scope.clone())?;
261 let mut items = std::mem::take(&mut page.items);
262 while let Some(mut next) = self.next_page(&page).await? {
263 items.append(&mut std::mem::take(&mut next.items));
264 page = next;
265 }
266 Ok(items)
267 }
268
269 async fn get_all<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Vec<T>> {
270 let mut page: Page<T> = self.get_page(url, scope).await?;
271 let mut items = std::mem::take(&mut page.items);
272 while let Some(mut next) = self.next_page(&page).await? {
273 items.append(&mut std::mem::take(&mut next.items));
274 page = next;
275 }
276 Ok(items)
277 }
278}
279
280pub(crate) fn ensure_graph_url(url: &str) -> Result<()> {
281 match url.strip_prefix(GRAPH) {
282 Some(rest) if rest.starts_with('/') => Ok(()),
283 _ => Err(Error::ForeignNextLink),
284 }
285}
286
287#[cfg(test)]
288mod tests {
289 use super::*;
290
291 #[test]
292 fn accepts_graph_urls_only() {
293 assert!(ensure_graph_url("https://graph.microsoft.com/v1.0/me/chats?$skiptoken=x").is_ok());
294 assert!(ensure_graph_url("https://graph.microsoft.com.evil.example/v1.0/me").is_err());
295 assert!(ensure_graph_url("https://example.com/v1.0/me").is_err());
296 }
297}