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