| 1 | use chrono::{DateTime, Utc}; |
| 2 | use serde_json::Value; |
| 3 | use session::{Method, Request}; |
| 4 | |
| 5 | use super::Pins; |
| 6 | use super::chats::{api_error, ensure_success}; |
| 7 | use super::pinbar::PinnedMessage; |
| 8 | use super::transport::CsaTransport; |
| 9 | use crate::error::{Error, Result}; |
| 10 | use crate::messages::encode; |
| 11 | |
| 12 | pub const PINNED_POSTS_PAGE_SIZE: usize = 20; |
| 13 | const MAX_PINNED_POST_PAGES: usize = 10; |
| 14 | const CONTINUATION_HEADER: &str = "x-ms-continuation"; |
| 15 | |
| 16 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 17 | pub struct PinnedPostsPage { |
| 18 | pub pins: Vec<PinnedMessage>, |
| 19 | pub continuation_token: Option<String>, |
| 20 | } |
| 21 | |
| 22 | fn pinned_time(message: &Value) -> Option<DateTime<Utc>> { |
| 23 | let pinned = message.pointer("/properties/pinned")?; |
| 24 | let parsed; |
| 25 | let pinned = match pinned { |
| 26 | Value::String(text) => { |
| 27 | parsed = serde_json::from_str::<Value>(text).ok()?; |
| 28 | &parsed |
| 29 | } |
| 30 | other => other, |
| 31 | }; |
| 32 | let millis = match pinned.get("pinnedTime")? { |
| 33 | Value::String(text) => text.parse::<i64>().ok()?, |
| 34 | other => other.as_i64()?, |
| 35 | }; |
| 36 | DateTime::from_timestamp_millis(millis) |
| 37 | } |
| 38 | |
| 39 | fn pinned_post(message: &Value) -> Option<PinnedMessage> { |
| 40 | let message_id = match message.get("id")? { |
| 41 | Value::String(text) => text.clone(), |
| 42 | Value::Number(number) => number.to_string(), |
| 43 | _ => return None, |
| 44 | }; |
| 45 | Some(PinnedMessage { |
| 46 | message_id, |
| 47 | pinned_at: pinned_time(message), |
| 48 | parent_id: None, |
| 49 | }) |
| 50 | } |
| 51 | |
| 52 | pub fn parse_pinned_posts(body: &Value) -> Result<PinnedPostsPage> { |
| 53 | let messages = body |
| 54 | .get("messages") |
| 55 | .and_then(Value::as_array) |
| 56 | .ok_or_else(|| Error::UnexpectedAnswer("pinned posts messages missing".into()))?; |
| 57 | Ok(PinnedPostsPage { |
| 58 | pins: messages.iter().filter_map(pinned_post).collect(), |
| 59 | continuation_token: body |
| 60 | .get("continuationToken") |
| 61 | .and_then(Value::as_str) |
| 62 | .filter(|token| !token.is_empty()) |
| 63 | .map(str::to_owned), |
| 64 | }) |
| 65 | } |
| 66 | |
| 67 | impl<T: CsaTransport> Pins<T> { |
| 68 | pub fn channel_url(&self, team_thread_id: &str, channel_id: &str) -> String { |
| 69 | format!( |
| 70 | "{}/teams/{}/channels/{}", |
| 71 | self.api_url, |
| 72 | encode(team_thread_id), |
| 73 | encode(channel_id) |
| 74 | ) |
| 75 | } |
| 76 | |
| 77 | pub fn pinned_posts_request( |
| 78 | &self, |
| 79 | team_thread_id: &str, |
| 80 | channel_id: &str, |
| 81 | continuation_token: Option<&str>, |
| 82 | ) -> Request { |
| 83 | let mut request = Request::get(format!( |
| 84 | "{}/pins?pageSize={PINNED_POSTS_PAGE_SIZE}", |
| 85 | self.channel_url(team_thread_id, channel_id) |
| 86 | )); |
| 87 | if let Some(token) = continuation_token { |
| 88 | request |
| 89 | .headers |
| 90 | .push((CONTINUATION_HEADER.to_owned(), token.to_owned())); |
| 91 | } |
| 92 | request |
| 93 | } |
| 94 | |
| 95 | pub fn post_pin_request( |
| 96 | &self, |
| 97 | team_thread_id: &str, |
| 98 | channel_id: &str, |
| 99 | post_id: &str, |
| 100 | pinned: bool, |
| 101 | ) -> Request { |
| 102 | let url = format!( |
| 103 | "{}/posts/{post_id}/pin", |
| 104 | self.channel_url(team_thread_id, channel_id) |
| 105 | ); |
| 106 | if pinned { |
| 107 | Request { |
| 108 | method: Method::Post, |
| 109 | ..Request::get(url) |
| 110 | } |
| 111 | } else { |
| 112 | Request::delete(url) |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | /// Pinned root posts in service order; only roots can be pinned while `enablePinMessageV2` is off. |
| 117 | pub async fn channel_pinned_posts( |
| 118 | &self, |
| 119 | team_thread_id: &str, |
| 120 | channel_id: &str, |
| 121 | ) -> Result<Vec<PinnedMessage>> { |
| 122 | let mut pins = Vec::new(); |
| 123 | let mut continuation_token: Option<String> = None; |
| 124 | for _ in 0..MAX_PINNED_POST_PAGES { |
| 125 | let request = self.pinned_posts_request( |
| 126 | team_thread_id, |
| 127 | channel_id, |
| 128 | continuation_token.as_deref(), |
| 129 | ); |
| 130 | let answer = self.transport.send(request).await?; |
| 131 | ensure_success(&answer)?; |
| 132 | let page = parse_pinned_posts(&answer.body)?; |
| 133 | pins.extend(page.pins); |
| 134 | match page.continuation_token { |
| 135 | Some(token) if Some(&token) != continuation_token.as_ref() => { |
| 136 | continuation_token = Some(token) |
| 137 | } |
| 138 | _ => break, |
| 139 | } |
| 140 | } |
| 141 | Ok(pins) |
| 142 | } |
| 143 | |
| 144 | pub async fn set_post_pinned( |
| 145 | &self, |
| 146 | team_thread_id: &str, |
| 147 | channel_id: &str, |
| 148 | post_id: &str, |
| 149 | pinned: bool, |
| 150 | ) -> Result<()> { |
| 151 | let request = self.post_pin_request(team_thread_id, channel_id, post_id, pinned); |
| 152 | let answer = self.transport.send(request).await?; |
| 153 | if answer.is_success() { |
| 154 | Ok(()) |
| 155 | } else { |
| 156 | Err(api_error(&answer)) |
| 157 | } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | #[cfg(test)] |
| 162 | mod tests { |
| 163 | use std::collections::VecDeque; |
| 164 | use std::sync::Mutex; |
| 165 | |
| 166 | use serde_json::json; |
| 167 | use session::ApiResponse; |
| 168 | |
| 169 | use super::*; |
| 170 | |
| 171 | const TEAM: &str = "19:team@thread.tacv2"; |
| 172 | const CHANNEL: &str = "19:channel@thread.tacv2"; |
| 173 | const CHANNEL_URL: &str = "https://teams.cloud.microsoft/api/csa/emea/api/v1/teams/19%3Ateam%40thread.tacv2/channels/19%3Achannel%40thread.tacv2"; |
| 174 | |
| 175 | struct Canned { |
| 176 | answers: Mutex<VecDeque<(u16, Value)>>, |
| 177 | requests: Mutex<Vec<Request>>, |
| 178 | } |
| 179 | |
| 180 | impl CsaTransport for Canned { |
| 181 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 182 | self.requests.lock().unwrap().push(request); |
| 183 | let (status, body) = self.answers.lock().unwrap().pop_front().expect("exhausted"); |
| 184 | Ok(ApiResponse { |
| 185 | status, |
| 186 | body, |
| 187 | retry_after: None, |
| 188 | }) |
| 189 | } |
| 190 | } |
| 191 | |
| 192 | fn canned(answers: Vec<(u16, Value)>) -> Pins<Canned> { |
| 193 | Pins::with_transport( |
| 194 | Canned { |
| 195 | answers: Mutex::new(answers.into()), |
| 196 | requests: Mutex::new(Vec::new()), |
| 197 | }, |
| 198 | "emea", |
| 199 | ) |
| 200 | } |
| 201 | |
| 202 | #[test] |
| 203 | fn parses_ids_pinned_time_and_the_continuation() { |
| 204 | let body = json!({ |
| 205 | "messages": [ |
| 206 | {"id": "1791368000000", "parentMessageId": "1791368000000", |
| 207 | "properties": {"pinned": "{\"pinnedTime\":1791368500000}"}}, |
| 208 | {"id": 1791367000000_i64, "properties": {"pinned": {"pinnedTime": "1791367500000"}}}, |
| 209 | {"id": "1791366000000"}, |
| 210 | {"content": "no id"} |
| 211 | ], |
| 212 | "continuationToken": "next-page" |
| 213 | }); |
| 214 | let page = parse_pinned_posts(&body).unwrap(); |
| 215 | let ids: Vec<&str> = page |
| 216 | .pins |
| 217 | .iter() |
| 218 | .map(|pin| pin.message_id.as_str()) |
| 219 | .collect(); |
| 220 | assert_eq!(ids, ["1791368000000", "1791367000000", "1791366000000"]); |
| 221 | assert_eq!( |
| 222 | page.pins[0].pinned_at.map(|time| time.timestamp_millis()), |
| 223 | Some(1791368500000) |
| 224 | ); |
| 225 | assert_eq!( |
| 226 | page.pins[1].pinned_at.map(|time| time.timestamp_millis()), |
| 227 | Some(1791367500000) |
| 228 | ); |
| 229 | assert_eq!(page.pins[2].pinned_at, None); |
| 230 | assert_eq!(page.continuation_token.as_deref(), Some("next-page")); |
| 231 | } |
| 232 | |
| 233 | #[test] |
| 234 | fn an_answer_without_messages_is_unexpected() { |
| 235 | assert!(matches!( |
| 236 | parse_pinned_posts(&json!({"continuationToken": "x"})), |
| 237 | Err(Error::UnexpectedAnswer(_)) |
| 238 | )); |
| 239 | } |
| 240 | |
| 241 | #[test] |
| 242 | fn pin_and_unpin_hit_the_post_pin_url_without_a_body() { |
| 243 | let pins = canned(Vec::new()); |
| 244 | let pin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", true); |
| 245 | assert_eq!(pin.method, Method::Post); |
| 246 | assert_eq!(pin.url, format!("{CHANNEL_URL}/posts/1791368000000/pin")); |
| 247 | assert_eq!(pin.body, None); |
| 248 | let unpin = pins.post_pin_request(TEAM, CHANNEL, "1791368000000", false); |
| 249 | assert_eq!(unpin.method, Method::Delete); |
| 250 | assert_eq!(unpin.url, pin.url); |
| 251 | assert_eq!(unpin.body, None); |
| 252 | } |
| 253 | |
| 254 | #[tokio::test] |
| 255 | async fn pinned_posts_follow_the_continuation_header() { |
| 256 | let pins = canned(vec![ |
| 257 | ( |
| 258 | 200, |
| 259 | json!({"messages": [{"id": "3"}, {"id": "2"}], "continuationToken": "page-2"}), |
| 260 | ), |
| 261 | (200, json!({"messages": [{"id": "1"}]})), |
| 262 | ]); |
| 263 | let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap(); |
| 264 | let ids: Vec<&str> = found.iter().map(|pin| pin.message_id.as_str()).collect(); |
| 265 | assert_eq!(ids, ["3", "2", "1"]); |
| 266 | let requests = pins.transport.requests.lock().unwrap(); |
| 267 | assert_eq!(requests[0].url, format!("{CHANNEL_URL}/pins?pageSize=20")); |
| 268 | assert!(requests[0].headers.is_empty()); |
| 269 | assert_eq!( |
| 270 | requests[1].headers, |
| 271 | [("x-ms-continuation".to_owned(), "page-2".to_owned())] |
| 272 | ); |
| 273 | } |
| 274 | |
| 275 | #[tokio::test] |
| 276 | async fn a_repeated_continuation_stops_paging() { |
| 277 | let pins = canned(vec![ |
| 278 | ( |
| 279 | 200, |
| 280 | json!({"messages": [{"id": "2"}], "continuationToken": "same"}), |
| 281 | ), |
| 282 | ( |
| 283 | 200, |
| 284 | json!({"messages": [{"id": "1"}], "continuationToken": "same"}), |
| 285 | ), |
| 286 | ]); |
| 287 | let found = pins.channel_pinned_posts(TEAM, CHANNEL).await.unwrap(); |
| 288 | assert_eq!(found.len(), 2); |
| 289 | assert_eq!(pins.transport.requests.lock().unwrap().len(), 2); |
| 290 | } |
| 291 | |
| 292 | #[tokio::test] |
| 293 | async fn failures_are_errors() { |
| 294 | let pins = canned(vec![(403, json!({})), (412, json!({}))]); |
| 295 | assert!(pins.channel_pinned_posts(TEAM, CHANNEL).await.is_err()); |
| 296 | assert!( |
| 297 | pins.set_post_pinned(TEAM, CHANNEL, "1", true) |
| 298 | .await |
| 299 | .is_err() |
| 300 | ); |
| 301 | } |
| 302 | |
| 303 | #[tokio::test] |
| 304 | async fn unpin_accepts_no_content() { |
| 305 | let pins = canned(vec![(204, Value::Null)]); |
| 306 | pins.set_post_pinned(TEAM, CHANNEL, "1", false) |
| 307 | .await |
| 308 | .unwrap(); |
| 309 | } |
| 310 | } |