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