BlueGit

ict rusty-teams

Files

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

links.rs

links.rs 13.1 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=";
14const AMS_HOST_SUFFIX: &str = ".asm.skype.com";
15const VIEWS_SEGMENT: &str = "/views/";
16const FULL_SIZE_VIEW_PREFIX: &str = "imgpsh_fullsize";
17/// The view Teams opens in its image viewer; `_anim` keeps animated GIFs moving.
18const FULL_SIZE_VIEW: &str = "imgpsh_fullsize_anim";
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct MessageLinks {
22 pub message_id: String,
23 pub links_json: String,
24}
25
26#[derive(Debug, Clone, Default, PartialEq, Eq)]
27pub struct LinkInfo {
28 pub url: String,
29 pub title: Option<String>,
30 pub description: Option<String>,
31 pub site: Option<String>,
32 pub thumbnail: Option<String>,
33 pub thumbnail_width: Option<u32>,
34 pub thumbnail_height: Option<u32>,
35}
36
37#[derive(Debug, Clone, PartialEq, Eq)]
38pub struct LinkImage {
39 pub bytes: Vec<u8>,
40 pub content_type: String,
41}
42
43pub fn is_link_image_url(url: &str) -> bool {
44 url.strip_prefix("https://")
45 .and_then(|rest| rest.split(['/', '?', '#']).next())
46 .is_some_and(|host| host.ends_with(LINK_PROXY_HOST_SUFFIX))
47}
48
49/// The AMS image behind a Graph chat `hostedContents/{id}/$value` link: the id encodes `id=..,type=..,url=<AMS url>`.
50pub fn hosted_content_image_url(graph_url: &str) -> Option<String> {
51 let after = graph_url.split(HOSTED_CONTENTS_SEGMENT).nth(1)?;
52 let encoded = after.split('/').next()?;
53 let bytes = STANDARD
54 .decode(encoded)
55 .or_else(|_| URL_SAFE_NO_PAD.decode(encoded))
56 .ok()?;
57 let decoded = String::from_utf8(bytes).ok()?;
58 let (_, url) = decoded.split_once(HOSTED_URL_KEY)?;
59 (is_link_image_url(url) || is_ams_image_url(url)).then(|| url.to_owned())
60}
61
62/// An AMS object view (`https://*.asm.skype.com/v1/objects/...`), the inline images of chat service messages.
63pub fn is_ams_image_url(url: &str) -> bool {
64 url.strip_prefix("https://")
65 .and_then(|rest| rest.split_once('/'))
66 .is_some_and(|(host, path)| {
67 host.ends_with(AMS_HOST_SUFFIX) && path.starts_with("v1/objects/")
68 })
69}
70
71/// The full-resolution view of the AMS image at `url` (a plain AMS view or a Graph `hostedContents` link to one).
72/// Messages carry the compressed `imgo` view; Teams swaps to this view when the image is opened.
73/// `None` for other images, video clips and thumbnails, and views that already are full size.
74pub fn ams_full_size_url(url: &str) -> Option<String> {
75 let decoded = hosted_content_image_url(url);
76 let url = decoded.as_deref().unwrap_or(url);
77 let is_object = |host: &str, path: &str| {
78 path.starts_with("v1/objects/")
79 && (host.ends_with(AMS_HOST_SUFFIX) || host.ends_with(LINK_PROXY_HOST_SUFFIX))
80 };
81 let (host, path) = url.strip_prefix("https://")?.split_once('/')?;
82 if !is_object(host, path) {
83 return None;
84 }
85 let (object, view) = url.rsplit_once(VIEWS_SEGMENT)?;
86 let still_picture = view.starts_with("img") && !view.contains(['/', '?', '#']);
87 (still_picture && !view.starts_with(FULL_SIZE_VIEW_PREFIX))
88 .then(|| format!("{object}{VIEWS_SEGMENT}{FULL_SIZE_VIEW}"))
89}
90
91pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {
92 body.get("messages")
93 .and_then(Value::as_array)
94 .into_iter()
95 .flatten()
96 .filter_map(|message| {
97 let message_id = message.get("id")?.as_str()?.to_owned();
98 let links_json = match message.pointer("/properties/links")? {
99 Value::String(text) => text.clone(),
100 array @ Value::Array(_) => array.to_string(),
101 _ => return None,
102 };
103 Some(MessageLinks {
104 message_id,
105 links_json,
106 })
107 })
108 .collect()
109}
110
111pub fn parse_link_info(body: &Value) -> LinkInfo {
112 let text = |key: &str| {
113 body.get(key)
114 .and_then(Value::as_str)
115 .map(str::trim)
116 .filter(|value| !value.is_empty())
117 .map(str::to_owned)
118 };
119 let size = |key: &str| {
120 body.pointer(&format!("/thumbnail_meta/{key}"))
121 .and_then(Value::as_u64)
122 .and_then(|value| u32::try_from(value).ok())
123 .filter(|value| *value > 0)
124 };
125 LinkInfo {
126 url: text("target_url")
127 .or_else(|| text("url"))
128 .unwrap_or_default(),
129 title: text("title"),
130 description: text("description"),
131 site: text("site"),
132 thumbnail: text("thumbnail"),
133 thumbnail_width: size("width"),
134 thumbnail_height: size("height"),
135 }
136}
137
138impl<T: MessageTransport> Messages<T> {
139 pub async fn list_message_links(
140 &self,
141 conversation: &ConversationRef,
142 page_size: usize,
143 ) -> Result<Vec<MessageLinks>> {
144 let url = format!(
145 "{}/{}/messages?view={LIST_VIEW}&pageSize={page_size}",
146 self.base_url,
147 encode(&conversation.conversation_id())
148 );
149 let answer = self.transport.send(Request::get(&url)).await?;
150 ensure_success(&answer)?;
151 Ok(parse_message_links(&answer.body))
152 }
153
154 pub async fn set_links(
155 &self,
156 conversation: &ConversationRef,
157 message_id: &str,
158 links_json: &str,
159 ) -> Result<()> {
160 let url = format!(
161 "{}/properties?name=links",
162 self.message_url(conversation, message_id)
163 );
164 let body = json!({"links": links_json});
165 let answer = self
166 .transport
167 .send(Request::with_body(Method::Put, url, body))
168 .await?;
169 ensure_success(&answer)
170 }
171
172 pub async fn link_info(&self, url: &str) -> Result<LinkInfo> {
173 let request_url = format!("{URLP_BASE}/info?url={}", encode(url));
174 let answer = self.transport.send(Request::get(&request_url)).await?;
175 ensure_success(&answer)?;
176 Ok(parse_link_info(&answer.body))
177 }
178
179 pub async fn link_image(&self, url: &str) -> Result<LinkImage> {
180 if !is_link_image_url(url) {
181 return Err(Error::UnexpectedAnswer(format!(
182 "not a link preview image url: {url}"
183 )));
184 }
185 let answer = self.transport.send(Request::binary_get(url)).await?;
186 ensure_success(&answer)?;
187 decoded_image(&answer.body)
188 }
189}
190
191/// An image answer shaped `{base64, contentType}`.
192pub(crate) fn decoded_image(body: &Value) -> Result<LinkImage> {
193 let encoded = body
194 .get("base64")
195 .and_then(Value::as_str)
196 .unwrap_or_default();
197 let bytes = STANDARD
198 .decode(encoded.as_bytes())
199 .map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
200 let content_type = body
201 .get("contentType")
202 .and_then(Value::as_str)
203 .unwrap_or_default()
204 .to_owned();
205 Ok(LinkImage {
206 bytes,
207 content_type,
208 })
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn hosted_content_ids_carry_the_ams_url() {
217 let ams = "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d1-abc/views/imgo";
218 let id = STANDARD.encode(format!("id=x_0-weu-d1-abc,type=1,url={ams}"));
219 let graph = format!(
220 "https://graph.microsoft.com/v1.0/chats/19:a/messages/1/hostedContents/{id}/$value"
221 );
222 assert_eq!(hosted_content_image_url(&graph).as_deref(), Some(ams));
223 let foreign = STANDARD.encode("id=x,type=1,url=https://evil.example/a");
224 assert_eq!(
225 hosted_content_image_url(&format!(
226 "https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/{foreign}/$value"
227 )),
228 None
229 );
230 }
231
232 #[test]
233 fn ams_object_views_are_recognized_inside_hosted_content_ids() {
234 let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo";
235 assert!(is_ams_image_url(ams));
236 let id = STANDARD.encode(format!("id=x_0-frca-d14-abc,type=1,url={ams}"));
237 assert_eq!(
238 hosted_content_image_url(&format!(
239 "https://graph.microsoft.com/v1.0/teams/t/channels/c/messages/1/hostedContents/{id}/$value"
240 ))
241 .as_deref(),
242 Some(ams)
243 );
244 assert!(!is_ams_image_url(
245 "https://evil.example/v1/objects/a/views/imgo"
246 ));
247 assert!(!is_ams_image_url(
248 "https://eu-api.asm.skype.com/v1/users/me"
249 ));
250 }
251
252 #[test]
253 fn an_inline_ams_image_opens_in_its_full_size_view() {
254 assert_eq!(
255 ams_full_size_url("https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgo")
256 .as_deref(),
257 Some("https://eu-api.asm.skype.com/v1/objects/0-weu-d1-abc/views/imgpsh_fullsize_anim")
258 );
259 assert_eq!(
260 ams_full_size_url(
261 "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d4-abc/views/imgo"
262 )
263 .as_deref(),
264 Some(
265 "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d4-abc/views/imgpsh_fullsize_anim"
266 )
267 );
268 let ams = "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgo";
269 let id = STANDARD.encode(format!("id=x_0-frca-d14-abc,type=1,url={ams}"));
270 assert_eq!(
271 ams_full_size_url(&format!(
272 "https://graph.microsoft.com/v1.0/chats/19:a/messages/1/hostedContents/{id}/$value"
273 ))
274 .as_deref(),
275 Some(
276 "https://eu-api.asm.skype.com/v1/objects/0-frca-d14-abc/views/imgpsh_fullsize_anim"
277 )
278 );
279 }
280
281 #[test]
282 fn full_size_and_non_picture_views_have_no_separate_full_size() {
283 for url in [
284 "https://eu-api.asm.skype.com/v1/objects/a/views/imgpsh_fullsize",
285 "https://eu-api.asm.skype.com/v1/objects/a/views/imgpsh_fullsize_anim",
286 "https://eu-api.asm.skype.com/v1/objects/a/views/video",
287 "https://eu-api.asm.skype.com/v1/objects/a/views/thumbnail",
288 "https://eu-api.asm.skype.com/v1/objects/a",
289 "https://evil.example/v1/objects/a/views/imgo",
290 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=x/views/imgo",
291 "https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/aGk=/$value",
292 ] {
293 assert_eq!(ams_full_size_url(url), None, "{url}");
294 }
295 }
296
297 #[test]
298 fn parses_link_info_with_target_url_and_thumbnail_size() {
299 let info = parse_link_info(&json!({
300 "title": " Rust ",
301 "description": "",
302 "site": "GitHub",
303 "thumbnail": "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x",
304 "thumbnail_meta": {"height": 160, "width": 320},
305 "url": "https://github.com/a",
306 "target_url": "https://github.com/rust-lang/rust",
307 }));
308 assert_eq!(info.url, "https://github.com/rust-lang/rust");
309 assert_eq!(info.title.as_deref(), Some("Rust"));
310 assert_eq!(info.description, None);
311 assert_eq!(info.site.as_deref(), Some("GitHub"));
312 assert_eq!(
313 (info.thumbnail_width, info.thumbnail_height),
314 (Some(320), Some(160))
315 );
316 }
317
318 #[test]
319 fn link_info_tolerates_missing_fields() {
320 let info = parse_link_info(&json!({"url": "https://a.example", "thumbnail_meta": null}));
321 assert_eq!(info.url, "https://a.example");
322 assert_eq!(info.title, None);
323 assert_eq!(info.thumbnail, None);
324 assert_eq!(info.thumbnail_width, None);
325 }
326
327 #[test]
328 fn reads_links_as_string_or_array_and_skips_messages_without() {
329 let links = parse_message_links(&json!({"messages": [
330 {"id": "1", "properties": {"links": "[{\"url\":\"https://a\"}]"}},
331 {"id": "2", "properties": {"links": [{"url": "https://b"}]}},
332 {"id": "3", "properties": {}},
333 {"id": "4"},
334 {"properties": {"links": "[]"}},
335 ]}));
336 assert_eq!(
337 links,
338 vec![
339 MessageLinks {
340 message_id: "1".into(),
341 links_json: "[{\"url\":\"https://a\"}]".into()
342 },
343 MessageLinks {
344 message_id: "2".into(),
345 links_json: "[{\"url\":\"https://b\"}]".into()
346 },
347 ]
348 );
349 }
350
351 #[test]
352 fn only_asyncgw_hosts_receive_the_token() {
353 assert!(is_link_image_url(
354 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x"
355 ));
356 assert!(!is_link_image_url(
357 "https://evil.example/?a=.asyncgw.teams.microsoft.com"
358 ));
359 assert!(!is_link_image_url(
360 "http://de-prod.asyncgw.teams.microsoft.com/x"
361 ));
362 }
363}