| 1 | use serde_json::{Value, json}; |
| 2 | use session::{Method, Request, Session}; |
| 3 | |
| 4 | use crate::channel_notifications::{ChannelNotifications, PROPERTY_NAME}; |
| 5 | use crate::error::{Error, Result}; |
| 6 | use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success}; |
| 7 | use crate::pins::DEFAULT_REGION; |
| 8 | use crate::read_horizon::{self, ReadHorizon}; |
| 9 | |
| 10 | const PAGE_SIZE: usize = 200; |
| 11 | const MAX_PAGES: usize = 100; |
| 12 | const ALERTS_OFF: &str = "false"; |
| 13 | |
| 14 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 15 | pub struct ConversationState { |
| 16 | pub id: String, |
| 17 | pub muted: bool, |
| 18 | pub hidden: Option<bool>, |
| 19 | pub read: ReadHorizon, |
| 20 | } |
| 21 | |
| 22 | pub struct Conversations<T: MessageTransport = SessionMessageTransport> { |
| 23 | transport: T, |
| 24 | base_url: String, |
| 25 | } |
| 26 | |
| 27 | impl Conversations<SessionMessageTransport> { |
| 28 | pub fn new(session: &Session) -> Self { |
| 29 | Self::with_region(session, DEFAULT_REGION) |
| 30 | } |
| 31 | |
| 32 | pub fn with_region(session: &Session, region: &str) -> Self { |
| 33 | Conversations::with_transport(SessionMessageTransport::new(session), region) |
| 34 | } |
| 35 | } |
| 36 | |
| 37 | impl<T: MessageTransport> Conversations<T> { |
| 38 | pub fn with_transport(transport: T, region: &str) -> Self { |
| 39 | Conversations { |
| 40 | transport, |
| 41 | base_url: format!( |
| 42 | "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations" |
| 43 | ), |
| 44 | } |
| 45 | } |
| 46 | |
| 47 | pub fn alerts_url(&self, conversation_id: &str) -> String { |
| 48 | format!( |
| 49 | "{}/{}/properties?name=alerts", |
| 50 | self.base_url, |
| 51 | encode(conversation_id) |
| 52 | ) |
| 53 | } |
| 54 | |
| 55 | pub async fn conversation_states(&self) -> Result<Vec<ConversationState>> { |
| 56 | let url = format!( |
| 57 | "{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}", |
| 58 | self.base_url |
| 59 | ); |
| 60 | let mut states = Vec::new(); |
| 61 | let mut next_url = Some(url); |
| 62 | for _ in 0..MAX_PAGES { |
| 63 | let Some(url) = next_url.take() else { |
| 64 | break; |
| 65 | }; |
| 66 | let answer = self.transport.send(Request::get(&url)).await?; |
| 67 | ensure_success(&answer)?; |
| 68 | states.extend(states_in_page(&answer.body)?); |
| 69 | next_url = backward_link(&answer.body).filter(|link| *link != url); |
| 70 | } |
| 71 | Ok(states) |
| 72 | } |
| 73 | |
| 74 | pub async fn set_alerts(&self, conversation_id: &str, enabled: bool) -> Result<()> { |
| 75 | let body = json!({"alerts": if enabled { "true" } else { ALERTS_OFF }}); |
| 76 | let answer = self |
| 77 | .transport |
| 78 | .send(Request::with_body( |
| 79 | Method::Put, |
| 80 | self.alerts_url(conversation_id), |
| 81 | body, |
| 82 | )) |
| 83 | .await?; |
| 84 | ensure_success(&answer) |
| 85 | } |
| 86 | |
| 87 | pub async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> { |
| 88 | let url = format!( |
| 89 | "{}/{}/properties?name={}", |
| 90 | self.base_url, |
| 91 | encode(conversation_id), |
| 92 | read_horizon::PROPERTY_NAME |
| 93 | ); |
| 94 | let body = json!({ read_horizon::PROPERTY_NAME: horizon }); |
| 95 | let answer = self |
| 96 | .transport |
| 97 | .send(Request::with_body(Method::Put, url, body)) |
| 98 | .await?; |
| 99 | ensure_success(&answer) |
| 100 | } |
| 101 | |
| 102 | pub async fn set_channel_notifications( |
| 103 | &self, |
| 104 | channel_id: &str, |
| 105 | notifications: ChannelNotifications, |
| 106 | ) -> Result<()> { |
| 107 | let url = format!( |
| 108 | "{}/{}/properties?name={PROPERTY_NAME}", |
| 109 | self.base_url, |
| 110 | encode(channel_id) |
| 111 | ); |
| 112 | let body = json!({ PROPERTY_NAME: notifications.property_value() }); |
| 113 | let answer = self |
| 114 | .transport |
| 115 | .send(Request::with_body(Method::Put, url, body)) |
| 116 | .await?; |
| 117 | ensure_success(&answer) |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | /// One conversation with its thread properties, as Teams reads a meeting or 1:1 thread. |
| 122 | pub fn thread_url(region: &str, thread_id: &str) -> String { |
| 123 | format!( |
| 124 | "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations/{}?view=msnp24Equivalent", |
| 125 | thread_id.replace(':', "%3A").replace('@', "%40") |
| 126 | ) |
| 127 | } |
| 128 | |
| 129 | fn backward_link(body: &Value) -> Option<String> { |
| 130 | body.pointer("/_metadata/backwardLink") |
| 131 | .and_then(Value::as_str) |
| 132 | .filter(|link| !link.is_empty()) |
| 133 | .map(str::to_owned) |
| 134 | } |
| 135 | |
| 136 | fn hidden_flag(conversation: &Value) -> Option<bool> { |
| 137 | let flags: Vec<bool> = [ |
| 138 | &conversation["properties"]["hidden"], |
| 139 | &conversation["threadProperties"]["hidden"], |
| 140 | ] |
| 141 | .into_iter() |
| 142 | .filter_map(|value| match value { |
| 143 | Value::Bool(flag) => Some(*flag), |
| 144 | Value::String(text) => text.parse().ok(), |
| 145 | _ => None, |
| 146 | }) |
| 147 | .collect(); |
| 148 | if flags.contains(&true) { |
| 149 | Some(true) |
| 150 | } else { |
| 151 | flags.first().copied() |
| 152 | } |
| 153 | } |
| 154 | |
| 155 | fn states_in_page(body: &Value) -> Result<Vec<ConversationState>> { |
| 156 | let conversations = body |
| 157 | .get("conversations") |
| 158 | .and_then(Value::as_array) |
| 159 | .ok_or_else(|| Error::UnexpectedAnswer("no conversations list".into()))?; |
| 160 | Ok(conversations |
| 161 | .iter() |
| 162 | .filter_map(|conversation| { |
| 163 | let id = conversation["id"].as_str()?; |
| 164 | let muted = conversation["properties"]["alerts"].as_str() == Some(ALERTS_OFF); |
| 165 | Some(ConversationState { |
| 166 | id: id.to_owned(), |
| 167 | muted, |
| 168 | hidden: hidden_flag(conversation), |
| 169 | read: ReadHorizon::from_conversation(conversation), |
| 170 | }) |
| 171 | }) |
| 172 | .collect()) |
| 173 | } |
| 174 | |
| 175 | #[cfg(test)] |
| 176 | mod tests { |
| 177 | use std::collections::VecDeque; |
| 178 | use std::sync::Mutex; |
| 179 | |
| 180 | use session::ApiResponse; |
| 181 | |
| 182 | use super::*; |
| 183 | |
| 184 | struct Canned { |
| 185 | answers: Mutex<VecDeque<(u16, Value)>>, |
| 186 | requests: Mutex<Vec<Request>>, |
| 187 | } |
| 188 | |
| 189 | impl MessageTransport for &Canned { |
| 190 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 191 | self.requests.lock().unwrap().push(request); |
| 192 | let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted"); |
| 193 | Ok(ApiResponse { |
| 194 | status, |
| 195 | body, |
| 196 | retry_after: None, |
| 197 | }) |
| 198 | } |
| 199 | } |
| 200 | |
| 201 | fn canned(answers: Vec<(u16, Value)>) -> Canned { |
| 202 | Canned { |
| 203 | answers: Mutex::new(answers.into()), |
| 204 | requests: Mutex::new(Vec::new()), |
| 205 | } |
| 206 | } |
| 207 | |
| 208 | fn state(id: &str, muted: bool) -> ConversationState { |
| 209 | ConversationState { |
| 210 | id: id.to_owned(), |
| 211 | muted, |
| 212 | hidden: None, |
| 213 | read: ReadHorizon::default(), |
| 214 | } |
| 215 | } |
| 216 | |
| 217 | const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations"; |
| 218 | |
| 219 | #[test] |
| 220 | fn thread_url_escapes_the_thread_id() { |
| 221 | assert_eq!( |
| 222 | thread_url("emea", "19:meeting_a@thread.v2"), |
| 223 | "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations/19%3Ameeting_a%40thread.v2?view=msnp24Equivalent" |
| 224 | ); |
| 225 | } |
| 226 | |
| 227 | #[tokio::test] |
| 228 | async fn mute_states_pair_every_conversation_with_its_flag() { |
| 229 | let transport = canned(vec![( |
| 230 | 200, |
| 231 | json!({ |
| 232 | "conversations": [ |
| 233 | {"id": "19:a", "properties": {"alerts": "false"}}, |
| 234 | {"id": "19:b", "properties": {"alerts": "true"}}, |
| 235 | {"id": "19:c", "properties": {}}, |
| 236 | {"id": "19:d"}, |
| 237 | ], |
| 238 | }), |
| 239 | )]); |
| 240 | let states = Conversations::with_transport(&transport, "emea") |
| 241 | .conversation_states() |
| 242 | .await |
| 243 | .unwrap(); |
| 244 | assert_eq!( |
| 245 | states, |
| 246 | vec![ |
| 247 | state("19:a", true), |
| 248 | state("19:b", false), |
| 249 | state("19:c", false), |
| 250 | state("19:d", false), |
| 251 | ] |
| 252 | ); |
| 253 | let requests = transport.requests.lock().unwrap(); |
| 254 | assert_eq!(requests.len(), 1); |
| 255 | assert_eq!( |
| 256 | requests[0].url, |
| 257 | format!("{BASE}?view=msnp24Equivalent&pageSize=200") |
| 258 | ); |
| 259 | } |
| 260 | |
| 261 | #[tokio::test] |
| 262 | async fn mute_states_follow_the_backward_link_through_every_page() { |
| 263 | let transport = canned(vec![ |
| 264 | ( |
| 265 | 200, |
| 266 | json!({ |
| 267 | "conversations": [{"id": "19:a", "properties": {"alerts": "true"}}], |
| 268 | "_metadata": {"backwardLink": "https://example.test/page2"}, |
| 269 | }), |
| 270 | ), |
| 271 | ( |
| 272 | 200, |
| 273 | json!({ |
| 274 | "conversations": [{"id": "19:old", "properties": {"alerts": "false"}}], |
| 275 | "_metadata": {"backwardLink": "https://example.test/page3"}, |
| 276 | }), |
| 277 | ), |
| 278 | (200, json!({"conversations": [{"id": "19:oldest"}]})), |
| 279 | ]); |
| 280 | let states = Conversations::with_transport(&transport, "emea") |
| 281 | .conversation_states() |
| 282 | .await |
| 283 | .unwrap(); |
| 284 | assert_eq!( |
| 285 | states, |
| 286 | vec![ |
| 287 | state("19:a", false), |
| 288 | state("19:old", true), |
| 289 | state("19:oldest", false), |
| 290 | ] |
| 291 | ); |
| 292 | let requests = transport.requests.lock().unwrap(); |
| 293 | let urls: Vec<&str> = requests |
| 294 | .iter() |
| 295 | .map(|request| request.url.as_str()) |
| 296 | .collect(); |
| 297 | assert_eq!(urls[1], "https://example.test/page2"); |
| 298 | assert_eq!(urls[2], "https://example.test/page3"); |
| 299 | } |
| 300 | |
| 301 | #[tokio::test] |
| 302 | async fn hidden_flag_is_read_from_the_thread_properties_as_text_or_bool() { |
| 303 | let transport = canned(vec![( |
| 304 | 200, |
| 305 | json!({ |
| 306 | "conversations": [ |
| 307 | {"id": "19:a", "threadProperties": {"hidden": "true"}}, |
| 308 | {"id": "19:b", "threadProperties": {"hidden": "false"}}, |
| 309 | {"id": "19:c", "properties": {"hidden": true}}, |
| 310 | {"id": "19:d", "properties": {}}, |
| 311 | {"id": "19:e", "properties": {"hidden": "false"}, "threadProperties": {"hidden": "true"}}, |
| 312 | {"id": "19:f", "properties": {"hidden": "true"}, "threadProperties": {"hidden": "false"}}, |
| 313 | ], |
| 314 | }), |
| 315 | )]); |
| 316 | let states = Conversations::with_transport(&transport, "emea") |
| 317 | .conversation_states() |
| 318 | .await |
| 319 | .unwrap(); |
| 320 | let hidden: Vec<Option<bool>> = states.iter().map(|state| state.hidden).collect(); |
| 321 | assert_eq!( |
| 322 | hidden, |
| 323 | [ |
| 324 | Some(true), |
| 325 | Some(false), |
| 326 | Some(true), |
| 327 | None, |
| 328 | Some(true), |
| 329 | Some(true) |
| 330 | ] |
| 331 | ); |
| 332 | } |
| 333 | |
| 334 | #[tokio::test] |
| 335 | async fn mute_states_fail_on_an_error_status() { |
| 336 | let transport = canned(vec![(500, Value::Null)]); |
| 337 | let outcome = Conversations::with_transport(&transport, "emea") |
| 338 | .conversation_states() |
| 339 | .await; |
| 340 | assert!(outcome.is_err()); |
| 341 | } |
| 342 | |
| 343 | #[tokio::test] |
| 344 | async fn set_alerts_puts_the_flag_as_text() { |
| 345 | let transport = canned(vec![(200, Value::Null), (200, Value::Null)]); |
| 346 | let conversations = Conversations::with_transport(&transport, "emea"); |
| 347 | conversations |
| 348 | .set_alerts("19:a@thread.v2", false) |
| 349 | .await |
| 350 | .unwrap(); |
| 351 | conversations |
| 352 | .set_alerts("19:a@thread.v2", true) |
| 353 | .await |
| 354 | .unwrap(); |
| 355 | let requests = transport.requests.lock().unwrap(); |
| 356 | assert_eq!(requests[0].method, Method::Put); |
| 357 | assert_eq!( |
| 358 | requests[0].url, |
| 359 | format!("{BASE}/19%3Aa%40thread.v2/properties?name=alerts") |
| 360 | ); |
| 361 | assert_eq!(requests[0].body, Some(json!({"alerts": "false"}))); |
| 362 | assert_eq!(requests[1].body, Some(json!({"alerts": "true"}))); |
| 363 | } |
| 364 | |
| 365 | #[tokio::test] |
| 366 | async fn states_carry_the_read_horizon() { |
| 367 | let transport = canned(vec![( |
| 368 | 200, |
| 369 | json!({ |
| 370 | "conversations": [{ |
| 371 | "id": "19:a", |
| 372 | "properties": {"consumptionhorizon": "5;6;7"}, |
| 373 | "lastMessage": {"originalarrivaltime": "1970-01-01T00:00:00.009Z", "from": "x/contacts/8:orgid:b"}, |
| 374 | }], |
| 375 | }), |
| 376 | )]); |
| 377 | let states = Conversations::with_transport(&transport, "emea") |
| 378 | .conversation_states() |
| 379 | .await |
| 380 | .unwrap(); |
| 381 | assert_eq!(states[0].read.consumed_until_ms, 5); |
| 382 | assert_eq!(states[0].read.last_message_ms, 9); |
| 383 | assert!(states[0].read.is_unread("8:orgid:me")); |
| 384 | } |
| 385 | |
| 386 | #[tokio::test] |
| 387 | async fn set_read_horizon_puts_the_consumption_horizon_property() { |
| 388 | let transport = canned(vec![(200, Value::Null)]); |
| 389 | Conversations::with_transport(&transport, "emea") |
| 390 | .set_read_horizon("19:a@thread.skype", "9;10;0") |
| 391 | .await |
| 392 | .unwrap(); |
| 393 | let requests = transport.requests.lock().unwrap(); |
| 394 | assert_eq!(requests[0].method, Method::Put); |
| 395 | assert_eq!( |
| 396 | requests[0].url, |
| 397 | format!("{BASE}/19%3Aa%40thread.skype/properties?name=consumptionhorizon") |
| 398 | ); |
| 399 | assert_eq!( |
| 400 | requests[0].body, |
| 401 | Some(json!({"consumptionhorizon": "9;10;0"})) |
| 402 | ); |
| 403 | } |
| 404 | } |