| 1 | use chrono::{DateTime, Utc}; |
| 2 | use serde::de::DeserializeOwned; |
| 3 | use serde_json::Value; |
| 4 | use session::{ApiResponse, GRAPH, Method, Request, Scope, Session}; |
| 5 | |
| 6 | use crate::error::{Error, Result}; |
| 7 | use crate::models::{Channel, Chat, Member, Message, Tag, Team, User}; |
| 8 | use crate::page::Page; |
| 9 | use crate::urls; |
| 10 | |
| 11 | pub const CHAT_PAGE_SIZE: usize = 50; |
| 12 | pub const MESSAGE_PAGE_SIZE: usize = 50; |
| 13 | pub const BATCH_SIZE: usize = 20; |
| 14 | const PEOPLE_PAGE_SIZE: usize = 10; |
| 15 | |
| 16 | pub struct Graph { |
| 17 | session: Session, |
| 18 | } |
| 19 | |
| 20 | impl 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 team_tags(&self, team_id: &str) -> Result<Vec<Tag>> { |
| 119 | self.get_all(&urls::team_tags(team_id), Scope::graph("TeamworkTag.Read")) |
| 120 | .await |
| 121 | } |
| 122 | |
| 123 | pub async fn channels(&self, team_id: &str) -> Result<Vec<Channel>> { |
| 124 | self.get_all( |
| 125 | &urls::channels(team_id), |
| 126 | Scope::graph("Channel.ReadBasic.All"), |
| 127 | ) |
| 128 | .await |
| 129 | } |
| 130 | |
| 131 | pub async fn channels_for_teams( |
| 132 | &self, |
| 133 | team_ids: &[String], |
| 134 | ) -> Result<Vec<Result<Vec<Channel>>>> { |
| 135 | let scope = Scope::graph("Channel.ReadBasic.All"); |
| 136 | let mut listings = Vec::with_capacity(team_ids.len()); |
| 137 | for chunk in team_ids.chunks(BATCH_SIZE) { |
| 138 | let requests: Vec<Request> = chunk |
| 139 | .iter() |
| 140 | .map(|team_id| Request::get(urls::channels(team_id))) |
| 141 | .collect(); |
| 142 | let answers = self.session.batch(&requests, &scope).await?; |
| 143 | for (request, answer) in requests.iter().zip(answers) { |
| 144 | listings.push(self.collect_pages(&request.url, answer, &scope).await); |
| 145 | } |
| 146 | } |
| 147 | Ok(listings) |
| 148 | } |
| 149 | |
| 150 | pub async fn channel_message( |
| 151 | &self, |
| 152 | team_id: &str, |
| 153 | channel_id: &str, |
| 154 | message_id: &str, |
| 155 | ) -> Result<Message> { |
| 156 | let url = urls::channel_message(team_id, channel_id, message_id); |
| 157 | let body = self |
| 158 | .get(&url, &Scope::graph("ChannelMessage.Read.All")) |
| 159 | .await?; |
| 160 | Ok(serde_json::from_value(body)?) |
| 161 | } |
| 162 | |
| 163 | pub async fn channel_reply( |
| 164 | &self, |
| 165 | team_id: &str, |
| 166 | channel_id: &str, |
| 167 | message_id: &str, |
| 168 | reply_id: &str, |
| 169 | ) -> Result<Message> { |
| 170 | let url = urls::channel_reply(team_id, channel_id, message_id, reply_id); |
| 171 | let body = self |
| 172 | .get(&url, &Scope::graph("ChannelMessage.Read.All")) |
| 173 | .await?; |
| 174 | Ok(serde_json::from_value(body)?) |
| 175 | } |
| 176 | |
| 177 | pub async fn channel_replies( |
| 178 | &self, |
| 179 | team_id: &str, |
| 180 | channel_id: &str, |
| 181 | root_ids: &[String], |
| 182 | ) -> Result<Vec<Result<Vec<Message>>>> { |
| 183 | let scope = Scope::graph("ChannelMessage.Read.All"); |
| 184 | let mut listings = Vec::with_capacity(root_ids.len()); |
| 185 | for chunk in root_ids.chunks(BATCH_SIZE) { |
| 186 | let requests: Vec<Request> = chunk |
| 187 | .iter() |
| 188 | .map(|root_id| { |
| 189 | Request::get(urls::channel_replies( |
| 190 | team_id, |
| 191 | channel_id, |
| 192 | root_id, |
| 193 | MESSAGE_PAGE_SIZE, |
| 194 | )) |
| 195 | }) |
| 196 | .collect(); |
| 197 | let answers = self.session.batch(&requests, &scope).await?; |
| 198 | for (request, answer) in requests.iter().zip(answers) { |
| 199 | listings.push(self.collect_pages(&request.url, answer, &scope).await); |
| 200 | } |
| 201 | } |
| 202 | Ok(listings) |
| 203 | } |
| 204 | |
| 205 | pub async fn channel_delta( |
| 206 | &self, |
| 207 | team_id: &str, |
| 208 | channel_id: &str, |
| 209 | modified_after: Option<DateTime<Utc>>, |
| 210 | ) -> Result<Page<Message>> { |
| 211 | let url = urls::channel_delta(team_id, channel_id, modified_after); |
| 212 | self.get_page(&url, Scope::graph("ChannelMessage.Read.All")) |
| 213 | .await |
| 214 | } |
| 215 | |
| 216 | pub async fn search_people(&self, query: &str) -> Result<Vec<User>> { |
| 217 | let scope = Scope::graph("User.ReadBasic.All"); |
| 218 | let query = query.trim(); |
| 219 | if query.contains('@') { |
| 220 | return Ok(self |
| 221 | .get_page::<User>(&urls::user_by_address(query), scope) |
| 222 | .await? |
| 223 | .items); |
| 224 | } |
| 225 | let mut request = Request::get(urls::people_search(query, PEOPLE_PAGE_SIZE)); |
| 226 | request |
| 227 | .headers |
| 228 | .push(("ConsistencyLevel".to_owned(), "eventual".to_owned())); |
| 229 | let answer = self |
| 230 | .session |
| 231 | .batch(std::slice::from_ref(&request), &scope) |
| 232 | .await? |
| 233 | .remove(0); |
| 234 | self.collect_pages::<User>(&request.url, answer, &scope) |
| 235 | .await |
| 236 | } |
| 237 | |
| 238 | pub async fn channel_messages( |
| 239 | &self, |
| 240 | team_id: &str, |
| 241 | channel_id: &str, |
| 242 | top: usize, |
| 243 | ) -> Result<Page<Message>> { |
| 244 | let url = urls::channel_messages(team_id, channel_id, top.clamp(1, MESSAGE_PAGE_SIZE)); |
| 245 | self.get_page(&url, Scope::graph("ChannelMessage.Read.All")) |
| 246 | .await |
| 247 | } |
| 248 | |
| 249 | pub async fn channel_messages_at(&self, next_link: &str) -> Result<Page<Message>> { |
| 250 | self.get_page(next_link, Scope::graph("ChannelMessage.Read.All")) |
| 251 | .await |
| 252 | } |
| 253 | |
| 254 | pub async fn channel_delta_at(&self, link: &str) -> Result<Page<Message>> { |
| 255 | self.get_page(link, Scope::graph("ChannelMessage.Read.All")) |
| 256 | .await |
| 257 | } |
| 258 | |
| 259 | pub async fn next_page<T: DeserializeOwned>(&self, page: &Page<T>) -> Result<Option<Page<T>>> { |
| 260 | let Some(link) = page.next_link.as_deref() else { |
| 261 | return Ok(None); |
| 262 | }; |
| 263 | Ok(Some(self.get_page(link, page.scope.clone()).await?)) |
| 264 | } |
| 265 | |
| 266 | pub(crate) async fn get(&self, url: &str, scope: &Scope) -> Result<Value> { |
| 267 | ensure_graph_url(url)?; |
| 268 | Ok(self |
| 269 | .session |
| 270 | .request(Method::Get, url, scope, None) |
| 271 | .await? |
| 272 | .body) |
| 273 | } |
| 274 | |
| 275 | async fn get_page<T: DeserializeOwned>(&self, url: &str, scope: Scope) -> Result<Page<T>> { |
| 276 | let body = self.get(url, &scope).await?; |
| 277 | Page::parse(body, scope) |
| 278 | } |
| 279 | |
| 280 | async fn collect_pages<T: DeserializeOwned>( |
| 281 | &self, |
| 282 | url: &str, |
| 283 | answer: ApiResponse, |
| 284 | scope: &Scope, |
| 285 | ) -> Result<Vec<T>> { |
| 286 | if !answer.is_success() { |
| 287 | return Err(session::Error::api(answer.status, url, answer.body).into()); |
| 288 | } |
| 289 | let mut page: Page<T> = Page::parse(answer.body, scope.clone())?; |
| 290 | let mut items = std::mem::take(&mut page.items); |
| 291 | while let Some(mut next) = self.next_page(&page).await? { |
| 292 | items.append(&mut std::mem::take(&mut next.items)); |
| 293 | page = next; |
| 294 | } |
| 295 | Ok(items) |
| 296 | } |
| 297 | |
| 298 | pub(crate) async fn get_all<T: DeserializeOwned>( |
| 299 | &self, |
| 300 | url: &str, |
| 301 | scope: Scope, |
| 302 | ) -> Result<Vec<T>> { |
| 303 | let mut page: Page<T> = self.get_page(url, scope).await?; |
| 304 | let mut items = std::mem::take(&mut page.items); |
| 305 | while let Some(mut next) = self.next_page(&page).await? { |
| 306 | items.append(&mut std::mem::take(&mut next.items)); |
| 307 | page = next; |
| 308 | } |
| 309 | Ok(items) |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | pub(crate) fn ensure_graph_url(url: &str) -> Result<()> { |
| 314 | match url.strip_prefix(GRAPH) { |
| 315 | Some(rest) if rest.starts_with('/') => Ok(()), |
| 316 | _ => Err(Error::ForeignNextLink), |
| 317 | } |
| 318 | } |
| 319 | |
| 320 | #[cfg(test)] |
| 321 | mod tests { |
| 322 | use super::*; |
| 323 | |
| 324 | #[test] |
| 325 | fn accepts_graph_urls_only() { |
| 326 | assert!(ensure_graph_url("https://graph.microsoft.com/v1.0/me/chats?$skiptoken=x").is_ok()); |
| 327 | assert!(ensure_graph_url("https://graph.microsoft.com.evil.example/v1.0/me").is_err()); |
| 328 | assert!(ensure_graph_url("https://example.com/v1.0/me").is_err()); |
| 329 | } |
| 330 | } |