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