BlueGit

ict rusty-teams

Files

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

content.rs

content.rs 2.6 KiB Download Raw
1use session::{GRAPH, Request, Scope};
2
3use crate::client::{Graph, ensure_graph_url};
4use crate::error::{Error, Result};
5use crate::models::Photo;
6use crate::people::decode_binary;
7
8const CHAT_PATH: &str = "/v1.0/chats/";
9const CHANNEL_PATH: &str = "/v1.0/teams/";
10const SHARES_PATH: &str = "/v1.0/shares/";
11const SHARES_SCOPE: &str = "Files.ReadWrite.All";
12const EXTERNAL_IMAGE_SCOPE: &str = "Chat.Read";
13
14impl Graph {
15 /// Binary GET of a Graph hosted content URL (`.../hostedContents/{id}/$value`).
16 pub async fn download_hosted_content(&self, url: &str) -> Result<Photo> {
17 ensure_graph_url(url)?;
18 let scope = hosted_content_scope(url).ok_or(Error::ForeignNextLink)?;
19 let request = Request::binary_get(url);
20 let answer = self
21 .session()
22 .batch(std::slice::from_ref(&request), &scope)
23 .await?
24 .remove(0);
25 decode_binary(url, answer)
26 }
27
28 /// Anonymous binary GET of a public image URL (GIF or sticker CDN), run inside the page.
29 pub async fn download_external_image(&self, url: &str) -> Result<Photo> {
30 let request = Request::anonymous_binary_get(url, Vec::new());
31 let answer = self
32 .session()
33 .send(request, &Scope::graph(EXTERNAL_IMAGE_SCOPE))
34 .await?;
35 decode_binary(url, answer)
36 }
37}
38
39pub fn hosted_content_scope(url: &str) -> Option<Scope> {
40 let path = url.strip_prefix(GRAPH)?;
41 if path.starts_with(CHAT_PATH) {
42 Some(Scope::graph("Chat.Read"))
43 } else if path.starts_with(CHANNEL_PATH) {
44 Some(Scope::graph("ChannelMessage.Read.All"))
45 } else if path.starts_with(SHARES_PATH) {
46 Some(Scope::graph(SHARES_SCOPE))
47 } else {
48 None
49 }
50}
51
52#[cfg(test)]
53mod tests {
54 use super::*;
55
56 #[test]
57 fn scope_follows_the_conversation_kind() {
58 let chat =
59 "https://graph.microsoft.com/v1.0/chats/19%3Aa/messages/1/hostedContents/2/$value";
60 let channel = "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/2/$value";
61 assert_eq!(hosted_content_scope(chat).unwrap().name, "Chat.Read");
62 assert_eq!(
63 hosted_content_scope(channel).unwrap().name,
64 "ChannelMessage.Read.All"
65 );
66 let thumbnail =
67 "https://graph.microsoft.com/v1.0/shares/u!aHR0cA/driveItem/thumbnails/0/large/content";
68 assert_eq!(
69 hosted_content_scope(thumbnail).unwrap().name,
70 "Files.ReadWrite.All"
71 );
72 assert!(hosted_content_scope("https://graph.microsoft.com/v1.0/me").is_none());
73 }
74}