| 1 | use serde_json::{Value, json}; |
| 2 | use session::{Method, Request, Session}; |
| 3 | |
| 4 | use crate::error::{Error, Result}; |
| 5 | use crate::messages::{MessageTransport, SessionMessageTransport, encode, ensure_success}; |
| 6 | use crate::pins::DEFAULT_REGION; |
| 7 | |
| 8 | const PAGE_SIZE: usize = 200; |
| 9 | const ALERTS_OFF: &str = "false"; |
| 10 | |
| 11 | pub struct Conversations<T: MessageTransport = SessionMessageTransport> { |
| 12 | transport: T, |
| 13 | base_url: String, |
| 14 | } |
| 15 | |
| 16 | impl Conversations<SessionMessageTransport> { |
| 17 | pub fn new(session: &Session) -> Self { |
| 18 | Self::with_region(session, DEFAULT_REGION) |
| 19 | } |
| 20 | |
| 21 | pub fn with_region(session: &Session, region: &str) -> Self { |
| 22 | Conversations::with_transport(SessionMessageTransport::new(session), region) |
| 23 | } |
| 24 | } |
| 25 | |
| 26 | impl<T: MessageTransport> Conversations<T> { |
| 27 | pub fn with_transport(transport: T, region: &str) -> Self { |
| 28 | Conversations { |
| 29 | transport, |
| 30 | base_url: format!( |
| 31 | "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations" |
| 32 | ), |
| 33 | } |
| 34 | } |
| 35 | |
| 36 | pub fn alerts_url(&self, conversation_id: &str) -> String { |
| 37 | format!( |
| 38 | "{}/{}/properties?name=alerts", |
| 39 | self.base_url, |
| 40 | encode(conversation_id) |
| 41 | ) |
| 42 | } |
| 43 | |
| 44 | pub async fn conversation_mute_states(&self) -> Result<Vec<(String, bool)>> { |
| 45 | let url = format!( |
| 46 | "{}?view=msnp24Equivalent&pageSize={PAGE_SIZE}", |
| 47 | self.base_url |
| 48 | ); |
| 49 | let answer = self.transport.send(Request::get(&url)).await?; |
| 50 | ensure_success(&answer)?; |
| 51 | mute_states_in_page(&answer.body) |
| 52 | } |
| 53 | |
| 54 | pub async fn set_alerts(&self, conversation_id: &str, enabled: bool) -> Result<()> { |
| 55 | let body = json!({"alerts": if enabled { "true" } else { ALERTS_OFF }}); |
| 56 | let answer = self |
| 57 | .transport |
| 58 | .send(Request::with_body( |
| 59 | Method::Put, |
| 60 | self.alerts_url(conversation_id), |
| 61 | body, |
| 62 | )) |
| 63 | .await?; |
| 64 | ensure_success(&answer) |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | fn mute_states_in_page(body: &Value) -> Result<Vec<(String, bool)>> { |
| 69 | let conversations = body |
| 70 | .get("conversations") |
| 71 | .and_then(Value::as_array) |
| 72 | .ok_or_else(|| Error::UnexpectedAnswer("no conversations list".into()))?; |
| 73 | Ok(conversations |
| 74 | .iter() |
| 75 | .filter_map(|conversation| { |
| 76 | let id = conversation["id"].as_str()?; |
| 77 | let muted = conversation["properties"]["alerts"].as_str() == Some(ALERTS_OFF); |
| 78 | Some((id.to_owned(), muted)) |
| 79 | }) |
| 80 | .collect()) |
| 81 | } |
| 82 | |
| 83 | #[cfg(test)] |
| 84 | mod tests { |
| 85 | use std::collections::VecDeque; |
| 86 | use std::sync::Mutex; |
| 87 | |
| 88 | use session::ApiResponse; |
| 89 | |
| 90 | use super::*; |
| 91 | |
| 92 | struct Canned { |
| 93 | answers: Mutex<VecDeque<(u16, Value)>>, |
| 94 | requests: Mutex<Vec<Request>>, |
| 95 | } |
| 96 | |
| 97 | impl MessageTransport for &Canned { |
| 98 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 99 | self.requests.lock().unwrap().push(request); |
| 100 | let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted"); |
| 101 | Ok(ApiResponse { |
| 102 | status, |
| 103 | body, |
| 104 | retry_after: None, |
| 105 | }) |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | fn canned(answers: Vec<(u16, Value)>) -> Canned { |
| 110 | Canned { |
| 111 | answers: Mutex::new(answers.into()), |
| 112 | requests: Mutex::new(Vec::new()), |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | const BASE: &str = "https://teams.cloud.microsoft/api/chatsvc/emea/v1/users/ME/conversations"; |
| 117 | |
| 118 | #[tokio::test] |
| 119 | async fn mute_states_pair_every_conversation_with_its_flag() { |
| 120 | let transport = canned(vec![( |
| 121 | 200, |
| 122 | json!({ |
| 123 | "conversations": [ |
| 124 | {"id": "19:a", "properties": {"alerts": "false"}}, |
| 125 | {"id": "19:b", "properties": {"alerts": "true"}}, |
| 126 | {"id": "19:c", "properties": {}}, |
| 127 | {"id": "19:d"}, |
| 128 | ], |
| 129 | "_metadata": {"backwardLink": "https://example.test/next"}, |
| 130 | }), |
| 131 | )]); |
| 132 | let states = Conversations::with_transport(&transport, "emea") |
| 133 | .conversation_mute_states() |
| 134 | .await |
| 135 | .unwrap(); |
| 136 | assert_eq!( |
| 137 | states, |
| 138 | vec![ |
| 139 | ("19:a".to_owned(), true), |
| 140 | ("19:b".to_owned(), false), |
| 141 | ("19:c".to_owned(), false), |
| 142 | ("19:d".to_owned(), false), |
| 143 | ] |
| 144 | ); |
| 145 | let requests = transport.requests.lock().unwrap(); |
| 146 | assert_eq!(requests.len(), 1); |
| 147 | assert_eq!( |
| 148 | requests[0].url, |
| 149 | format!("{BASE}?view=msnp24Equivalent&pageSize=200") |
| 150 | ); |
| 151 | } |
| 152 | |
| 153 | #[tokio::test] |
| 154 | async fn mute_states_fail_on_an_error_status() { |
| 155 | let transport = canned(vec![(500, Value::Null)]); |
| 156 | let outcome = Conversations::with_transport(&transport, "emea") |
| 157 | .conversation_mute_states() |
| 158 | .await; |
| 159 | assert!(outcome.is_err()); |
| 160 | } |
| 161 | |
| 162 | #[tokio::test] |
| 163 | async fn set_alerts_puts_the_flag_as_text() { |
| 164 | let transport = canned(vec![(200, Value::Null), (200, Value::Null)]); |
| 165 | let conversations = Conversations::with_transport(&transport, "emea"); |
| 166 | conversations |
| 167 | .set_alerts("19:a@thread.v2", false) |
| 168 | .await |
| 169 | .unwrap(); |
| 170 | conversations |
| 171 | .set_alerts("19:a@thread.v2", true) |
| 172 | .await |
| 173 | .unwrap(); |
| 174 | let requests = transport.requests.lock().unwrap(); |
| 175 | assert_eq!(requests[0].method, Method::Put); |
| 176 | assert_eq!( |
| 177 | requests[0].url, |
| 178 | format!("{BASE}/19%3Aa%40thread.v2/properties?name=alerts") |
| 179 | ); |
| 180 | assert_eq!(requests[0].body, Some(json!({"alerts": "false"}))); |
| 181 | assert_eq!(requests[1].body, Some(json!({"alerts": "true"}))); |
| 182 | } |
| 183 | } |