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