| 1 | use std::cmp::Reverse; |
| 2 | |
| 3 | use chrono::{DateTime, Utc}; |
| 4 | use serde_json::{Value, json}; |
| 5 | use session::{Method, Request}; |
| 6 | |
| 7 | use super::Pins; |
| 8 | use super::chats::{api_error, ensure_success}; |
| 9 | use super::transport::CsaTransport; |
| 10 | use crate::error::{Error, Result}; |
| 11 | use crate::messages::encode; |
| 12 | |
| 13 | const PIN_MESSAGE_TYPE: &str = "pinmsg"; |
| 14 | const FOLDER_TYPE: &str = "folder"; |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct PinnedMessage { |
| 18 | pub message_id: String, |
| 19 | pub pinned_at: Option<DateTime<Utc>>, |
| 20 | pub parent_id: Option<String>, |
| 21 | } |
| 22 | |
| 23 | fn pinned_message(item: &Value, parent_id: Option<&str>) -> Option<PinnedMessage> { |
| 24 | if item.get("type")?.as_str()? != PIN_MESSAGE_TYPE { |
| 25 | return None; |
| 26 | } |
| 27 | let message_id = item |
| 28 | .get("pinBarItemId") |
| 29 | .and_then(Value::as_str) |
| 30 | .or_else(|| item.pointer("/pinnedMessageProperties/messageId")?.as_str())? |
| 31 | .to_owned(); |
| 32 | let pinned_at = item |
| 33 | .pointer("/pinnedMessageProperties/pinnedDateTime") |
| 34 | .and_then(|value| match value { |
| 35 | Value::String(text) => text.parse::<i64>().ok(), |
| 36 | other => other.as_i64(), |
| 37 | }) |
| 38 | .and_then(DateTime::from_timestamp_millis); |
| 39 | Some(PinnedMessage { |
| 40 | message_id, |
| 41 | pinned_at, |
| 42 | parent_id: parent_id.map(str::to_owned), |
| 43 | }) |
| 44 | } |
| 45 | |
| 46 | pub fn parse_chat_pins(body: &Value) -> Result<Vec<PinnedMessage>> { |
| 47 | let children = body |
| 48 | .get("children") |
| 49 | .and_then(Value::as_array) |
| 50 | .ok_or_else(|| Error::UnexpectedAnswer("pinbar children missing".into()))?; |
| 51 | let mut pins = Vec::new(); |
| 52 | for child in children { |
| 53 | if child.get("type").and_then(Value::as_str) == Some(FOLDER_TYPE) { |
| 54 | let folder_id = child.get("pinBarItemId").and_then(Value::as_str); |
| 55 | let nested = child.get("children").and_then(Value::as_array); |
| 56 | pins.extend( |
| 57 | nested |
| 58 | .into_iter() |
| 59 | .flatten() |
| 60 | .filter_map(|item| pinned_message(item, folder_id)), |
| 61 | ); |
| 62 | } else { |
| 63 | pins.extend(pinned_message(child, None)); |
| 64 | } |
| 65 | } |
| 66 | pins.sort_by_key(|pin| Reverse(pin.pinned_at)); |
| 67 | Ok(pins) |
| 68 | } |
| 69 | |
| 70 | fn pin_body(chat_id: &str, message_id: &str, parent_id: &str, operation: &str) -> Value { |
| 71 | let mut body = json!({ |
| 72 | "pinbarId": chat_id, |
| 73 | "pinbarItemType": PIN_MESSAGE_TYPE, |
| 74 | "pinbarItemId": message_id, |
| 75 | "pinbarParentItemId": parent_id, |
| 76 | "pinbarOperation": operation, |
| 77 | "pinnedMessageProperties": {"messageId": message_id, "rootMessageId": message_id}, |
| 78 | }); |
| 79 | if operation == "add" { |
| 80 | body["pinbarItemPosition"] = json!(0); |
| 81 | } |
| 82 | body |
| 83 | } |
| 84 | |
| 85 | impl<T: CsaTransport> Pins<T> { |
| 86 | pub fn pinbar_url(&self, chat_id: &str) -> String { |
| 87 | format!("{}/chats/{}/pinbar", self.api_url, encode(chat_id)) |
| 88 | } |
| 89 | |
| 90 | /// Newest pin first, with the folder id of pins that live in a folder. |
| 91 | pub async fn chat_pins(&self, chat_id: &str) -> Result<Vec<PinnedMessage>> { |
| 92 | let answer = self |
| 93 | .transport |
| 94 | .send(Request::get(self.pinbar_url(chat_id))) |
| 95 | .await?; |
| 96 | ensure_success(&answer)?; |
| 97 | parse_chat_pins(&answer.body) |
| 98 | } |
| 99 | |
| 100 | pub async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> { |
| 101 | let body = pin_body(chat_id, message_id, "", "add"); |
| 102 | self.write_pinbar(Method::Post, chat_id, body).await |
| 103 | } |
| 104 | |
| 105 | /// `parent_id` is the folder id from `chat_pins`, `None` for a pin at the root. |
| 106 | pub async fn unpin_message( |
| 107 | &self, |
| 108 | chat_id: &str, |
| 109 | message_id: &str, |
| 110 | parent_id: Option<&str>, |
| 111 | ) -> Result<()> { |
| 112 | let body = pin_body(chat_id, message_id, parent_id.unwrap_or_default(), "remove"); |
| 113 | self.write_pinbar(Method::Delete, chat_id, body).await |
| 114 | } |
| 115 | |
| 116 | async fn write_pinbar(&self, method: Method, chat_id: &str, body: Value) -> Result<()> { |
| 117 | let answer = self |
| 118 | .transport |
| 119 | .send(Request::with_body(method, self.pinbar_url(chat_id), body)) |
| 120 | .await?; |
| 121 | if answer.is_success() { |
| 122 | Ok(()) |
| 123 | } else { |
| 124 | Err(api_error(&answer)) |
| 125 | } |
| 126 | } |
| 127 | } |
| 128 | |
| 129 | #[cfg(test)] |
| 130 | mod tests { |
| 131 | use std::sync::Mutex; |
| 132 | |
| 133 | use session::ApiResponse; |
| 134 | |
| 135 | use super::*; |
| 136 | |
| 137 | struct Canned { |
| 138 | status: u16, |
| 139 | body: Value, |
| 140 | requests: Mutex<Vec<Request>>, |
| 141 | } |
| 142 | |
| 143 | impl CsaTransport for Canned { |
| 144 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 145 | self.requests.lock().unwrap().push(request); |
| 146 | Ok(ApiResponse { |
| 147 | status: self.status, |
| 148 | body: self.body.clone(), |
| 149 | retry_after: None, |
| 150 | }) |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | fn canned(status: u16, body: Value) -> Pins<Canned> { |
| 155 | Pins::with_transport( |
| 156 | Canned { |
| 157 | status, |
| 158 | body, |
| 159 | requests: Mutex::new(Vec::new()), |
| 160 | }, |
| 161 | "emea", |
| 162 | ) |
| 163 | } |
| 164 | |
| 165 | fn pinmsg(message_id: &str, pinned_at: &str) -> Value { |
| 166 | json!({ |
| 167 | "type": "pinmsg", |
| 168 | "pinBarItemId": message_id, |
| 169 | "pinnedMessageProperties": { |
| 170 | "messageId": message_id, |
| 171 | "rootMessageId": message_id, |
| 172 | "pinnedDateTime": pinned_at, |
| 173 | }, |
| 174 | }) |
| 175 | } |
| 176 | |
| 177 | #[tokio::test] |
| 178 | async fn reads_root_and_folder_pins_newest_first() { |
| 179 | let body = json!({ |
| 180 | "pinBarId": "19:abc@thread.v2", |
| 181 | "children": [ |
| 182 | pinmsg("100", "1791368000000"), |
| 183 | {"type": "folder", "pinBarItemId": "default-pinmsg-folder::g1", "children": [ |
| 184 | pinmsg("300", "1791368300000"), |
| 185 | {"type": "tab", "pinBarItemId": "t"}, |
| 186 | pinmsg("200", "1791368200000"), |
| 187 | ]}, |
| 188 | {"type": "tab", "pinBarItemId": "t2"}, |
| 189 | ] |
| 190 | }); |
| 191 | let pins = canned(200, body); |
| 192 | let found = pins.chat_pins("19:abc@thread.v2").await.unwrap(); |
| 193 | let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect(); |
| 194 | assert_eq!(ids, ["300", "200", "100"]); |
| 195 | assert_eq!( |
| 196 | found[0].parent_id.as_deref(), |
| 197 | Some("default-pinmsg-folder::g1") |
| 198 | ); |
| 199 | assert_eq!(found[2].parent_id, None); |
| 200 | assert_eq!( |
| 201 | found[2].pinned_at.map(|time| time.timestamp_millis()), |
| 202 | Some(1791368000000) |
| 203 | ); |
| 204 | let requests = pins.transport.requests.lock().unwrap(); |
| 205 | assert_eq!(requests[0].method, Method::Get); |
| 206 | assert_eq!( |
| 207 | requests[0].url, |
| 208 | "https://teams.cloud.microsoft/api/csa/emea/api/v1/chats/19%3Aabc%40thread.v2/pinbar" |
| 209 | ); |
| 210 | } |
| 211 | |
| 212 | #[tokio::test] |
| 213 | async fn pin_posts_add_body_at_position_zero() { |
| 214 | let pins = canned(201, json!({"pinBarItemId": "100"})); |
| 215 | pins.pin_message("19:abc@thread.v2", "100").await.unwrap(); |
| 216 | let requests = pins.transport.requests.lock().unwrap(); |
| 217 | assert_eq!(requests[0].method, Method::Post); |
| 218 | assert_eq!( |
| 219 | requests[0].url, |
| 220 | "https://teams.cloud.microsoft/api/csa/emea/api/v1/chats/19%3Aabc%40thread.v2/pinbar" |
| 221 | ); |
| 222 | assert_eq!( |
| 223 | requests[0].body, |
| 224 | Some(json!({ |
| 225 | "pinbarId": "19:abc@thread.v2", |
| 226 | "pinbarItemType": "pinmsg", |
| 227 | "pinbarItemId": "100", |
| 228 | "pinbarParentItemId": "", |
| 229 | "pinbarItemPosition": 0, |
| 230 | "pinbarOperation": "add", |
| 231 | "pinnedMessageProperties": {"messageId": "100", "rootMessageId": "100"}, |
| 232 | })) |
| 233 | ); |
| 234 | } |
| 235 | |
| 236 | #[tokio::test] |
| 237 | async fn unpin_deletes_with_remove_and_folder_parent() { |
| 238 | let pins = canned(204, Value::Null); |
| 239 | pins.unpin_message("c", "100", Some("default-pinmsg-folder::g1")) |
| 240 | .await |
| 241 | .unwrap(); |
| 242 | pins.unpin_message("c", "100", None).await.unwrap(); |
| 243 | let requests = pins.transport.requests.lock().unwrap(); |
| 244 | assert_eq!(requests[0].method, Method::Delete); |
| 245 | let body = requests[0].body.as_ref().unwrap(); |
| 246 | assert_eq!(body["pinbarOperation"], "remove"); |
| 247 | assert_eq!(body["pinbarParentItemId"], "default-pinmsg-folder::g1"); |
| 248 | assert!(body.get("pinbarItemPosition").is_none()); |
| 249 | assert_eq!(requests[1].body.as_ref().unwrap()["pinbarParentItemId"], ""); |
| 250 | } |
| 251 | |
| 252 | #[tokio::test] |
| 253 | async fn failures_are_errors() { |
| 254 | let pins = canned(403, json!({})); |
| 255 | assert!(pins.chat_pins("c").await.is_err()); |
| 256 | assert!(pins.pin_message("c", "1").await.is_err()); |
| 257 | assert!(pins.unpin_message("c", "1", None).await.is_err()); |
| 258 | } |
| 259 | |
| 260 | #[tokio::test] |
| 261 | async fn pinbar_without_children_is_unexpected() { |
| 262 | let pins = canned(200, json!({"pinBarId": "c"})); |
| 263 | assert!(matches!( |
| 264 | pins.chat_pins("c").await, |
| 265 | Err(Error::UnexpectedAnswer(_)) |
| 266 | )); |
| 267 | } |
| 268 | } |