BlueGit

ict rusty-teams

Files

rusty-teams / crates / chatsvc / src / links.rs

links.rs

links.rs 8.7 KiB Download Raw
1use base64::Engine as _;
2use base64::engine::general_purpose::{STANDARD, URL_SAFE_NO_PAD};
3use serde_json::{Value, json};
4use session::{Method, Request};
5
6use crate::error::{Error, Result};
7use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};
8
9const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";
10pub const LINK_PROXY_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
11const LIST_VIEW: &str = "msnp24Equivalent";
12const HOSTED_CONTENTS_SEGMENT: &str = "/hostedContents/";
13const HOSTED_URL_KEY: &str = ",url=";
14
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub struct MessageLinks {
17 pub message_id: String,
18 pub links_json: String,
19}
20
21#[derive(Debug, Clone, Default, PartialEq, Eq)]
22pub struct LinkInfo {
23 pub url: String,
24 pub title: Option<String>,
25 pub description: Option<String>,
26 pub site: Option<String>,
27 pub thumbnail: Option<String>,
28 pub thumbnail_width: Option<u32>,
29 pub thumbnail_height: Option<u32>,
30}
31
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct LinkImage {
34 pub bytes: Vec<u8>,
35 pub content_type: String,
36}
37
38pub fn is_link_image_url(url: &str) -> bool {
39 url.strip_prefix("https://")
40 .and_then(|rest| rest.split(['/', '?', '#']).next())
41 .is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))
42}
43
44/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.
45pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
46 let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?;
47 let encoded = after.split('/').next()?;
48 let bytes = STANDARD
49 .decode(encoded)
50 .or_else(|_| URL_SAFE_NO_PAD.decode(encoded))
51 .ok()?;
52 let decoded = String::from_utf8(bytes).ok()?;
53 let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;
54 is_link_image_url(url).then(|| url.to_owned())
55}
56
57pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {
58 body.get("messages")
59 .and_then(Value::as_array)
60 .into_iter()
61 .flatten()
62 .filter_map(|message| {
63 let message_id = message.get("id")?.as_str()?.to_owned();
64 let links_json = match message.pointer("/properties/links")? {
65 Value::String(text) => text.clone(),
66 array @ Value::Array(_) => array.to_string(),
67 _ => return None,
68 };
69 Some(MessageLinks {
70 message_id,
71 links_json,
72 })
73 })
74 .collect()
75}
76
77pub fn parse_link_info(body: &Value) -> LinkInfo {
78 let text = |key: &str| {
79 body.get(key)
80 .and_then(Value::as_str)
81 .map(str::trim)
82 .filter(|value| !value.is_empty())
83 .map(str::to_owned)
84 };
85 let size = |key: &str| {
86 body.pointer(&format!("/thumbnail_meta/{key}"))
87 .and_then(Value::as_u64)
88 .and_then(|value| u32::try_from(value).ok())
89 .filter(|value| *value > 0)
90 };
91 LinkInfo {
92 url: text("target_url")
93 .or_else(|| text("url"))
94 .unwrap_or_default(),
95 title: text("title"),
96 description: text("description"),
97 site: text("site"),
98 thumbnail: text("thumbnail"),
99 thumbnail_width: size("width"),
100 thumbnail_height: size("height"),
101 }
102}
103
104impl<T: MessageTransport> Messages<T> {
105 pub async fn list_message_links(
106 &self,
107 conversation: &ConversationRef,
108 page_size: usize,
109 ) -> Result<Vec<MessageLinks>> {
110 let url = format!(
111 "{}/{}/messages?view={LIST_VIEW}&pageSize={page_size}",
112 self.base_url,
113 encode(&conversation.conversation_id())
114 );
115 let answer = self.transport.send(Request::get(&url)).await?;
116 ensure_success(&answer)?;
117 Ok(parse_message_links(&answer.body))
118 }
119
120 pub async fn set_links(
121 &self,
122 conversation: &ConversationRef,
123 message_id: &str,
124 links_json: &str,
125 ) -> Result<()> {
126 let url = format!(
127 "{}/properties?name=links",
128 self.message_url(conversation, message_id)
129 );
130 let body = json!({"links": links_json});
131 let answer = self
132 .transport
133 .send(Request::with_body(Method::Put, url, body))
134 .await?;
135 ensure_success(&answer)
136 }
137
138 pub async fn link_info(&self, url: &str) -> Result<LinkInfo> {
139 let request_url = format!("{URLP_BASE}/info?url={}", encode(url));
140 let answer = self.transport.send(Request::get(&request_url)).await?;
141 ensure_success(&answer)?;
142 Ok(parse_link_info(&answer.body))
143 }
144
145 pub async fn link_image(&self, url: &str) -> Result<LinkImage> {
146 if !is_link_image_url(url) {
147 return Err(Error::UnexpectedAnswer(format!(
148 "not a link preview image url: {url}"
149 )));
150 }
151 let answer = self.transport.send(Request::binary_get(url)).await?;
152 ensure_success(&answer)?;
153 let encoded = answer
154 .body
155 .get("base64")
156 .and_then(Value::as_str)
157 .unwrap_or_default();
158 let bytes = STANDARD
159 .decode(encoded.as_bytes())
160 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
161 let content_type = answer
162 .body
163 .get("contentType")
164 .and_then(Value::as_str)
165 .unwrap_or_default()
166 .to_owned();
167 Ok(LinkImage {
168 bytes,
169 content_type,
170 })
171 }
172}
173
174#[cfg(test)]
175mod tests {
176 use super::*;
177
178 #[test]
179 fn hosted_content_ids_carry_the_ams_url() {
180 let ams = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d1-abc/views/imgo";
181 let id = STANDARD.encode(format!("id=x_0-weu-d1-abc,type=1,url={ams}"));
182 let graph = format!(
183 "https://graph.microsoft.com/v1.0/chats/19:a/messages/1/hostedContents/{id}/$value"
184 );
185 assert_eq!(hosted_content_image_url(&graph).as_deref(), Some(ams));
186 let foreign = STANDARD.encode("id=x,type=1,url=https://evil.example/a");
187 assert_eq!(
188 hosted_content_image_url(&format!(
189 "https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/{foreign}/$value"
190 )),
191 None
192 );
193 }
194
195 #[test]
196 fn parses_link_info_with_target_url_and_thumbnail_size() {
197 let info = parse_link_info(&json!({
198 "title": " Rust ",
199 "description": "",
200 "site": "GitHub",
201 "thumbnail": "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x",
202 "thumbnail_meta": {"height": 160, "width": 320},
203 "url": "https://github.com/a",
204 "target_url": "https://github.com/rust-lang/rust",
205 }));
206 assert_eq!(info.url, "https://github.com/rust-lang/rust");
207 assert_eq!(info.title.as_deref(), Some("Rust"));
208 assert_eq!(info.description, None);
209 assert_eq!(info.site.as_deref(), Some("GitHub"));
210 assert_eq!(
211 (info.thumbnail_width, info.thumbnail_height),
212 (Some(320), Some(160))
213 );
214 }
215
216 #[test]
217 fn link_info_tolerates_missing_fields() {
218 let info = parse_link_info(&json!({"url": "https://a.example", "thumbnail_meta": null}));
219 assert_eq!(info.url, "https://a.example");
220 assert_eq!(info.title, None);
221 assert_eq!(info.thumbnail, None);
222 assert_eq!(info.thumbnail_width, None);
223 }
224
225 #[test]
226 fn reads_links_as_string_or_array_and_skips_messages_without() {
227 let links = parse_message_links(&json!({"messages": [
228 {"id": "1", "properties": {"links": "[{\"url\":\"https://a\"}]"}},
229 {"id": "2", "properties": {"links": [{"url": "https://b"}]}},
230 {"id": "3", "properties": {}},
231 {"id": "4"},
232 {"properties": {"links": "[]"}},
233 ]}));
234 assert_eq!(
235 links,
236 vec![
237 MessageLinks {
238 message_id: "1".into(),
239 links_json: "[{\"url\":\"https://a\"}]".into()
240 },
241 MessageLinks {
242 message_id: "2".into(),
243 links_json: "[{\"url\":\"https://b\"}]".into()
244 },
245 ]
246 );
247 }
248
249 #[test]
250 fn only_asyncgw_hosts_receive_the_token() {
251 assert!(is_link_image_url(
252 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x"
253 ));
254 assert!(!is_link_image_url(
255 "https://evil.example/?a=.asyncgw.teams.microsoft.com"
256 ));
257 assert!(!is_link_image_url(
258 "http://de-prod.asyncgw.teams.microsoft.com/x"
259 ));
260 }
261}