| 1 | use std::time::Duration; |
| 2 | |
| 3 | use chrono::{DateTime, Duration as ChronoDuration, Utc}; |
| 4 | use serde_json::{Value, json}; |
| 5 | use session::{ApiResponse, Method, Request, Session}; |
| 6 | |
| 7 | use crate::error::Result; |
| 8 | use crate::messages::{ |
| 9 | DEFAULT_RETRY_DELAY, MessageTransport, SessionMessageTransport, encode, ensure_success, |
| 10 | new_client_message_id, |
| 11 | }; |
| 12 | use crate::pins::DEFAULT_REGION; |
| 13 | |
| 14 | const SCHEDULED_DRAFT: &str = "ScheduledDraft"; |
| 15 | const NOT_FOUND_RETRIES: u32 = 3; |
| 16 | const BACKOFF_FACTOR: u32 = 3; |
| 17 | const LIST_PAGE_SIZE: u32 = 200; |
| 18 | const LIST_WINDOW_DAYS: i64 = 8; |
| 19 | |
| 20 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 21 | pub struct ScheduledDraft { |
| 22 | pub id: String, |
| 23 | pub client_message_id: String, |
| 24 | pub inner_thread_id: String, |
| 25 | pub send_at: DateTime<Utc>, |
| 26 | pub html: String, |
| 27 | pub delivery_state: Option<String>, |
| 28 | } |
| 29 | |
| 30 | pub struct ScheduledDrafts<T: MessageTransport = SessionMessageTransport> { |
| 31 | transport: T, |
| 32 | base_url: String, |
| 33 | retry_delay: Duration, |
| 34 | } |
| 35 | |
| 36 | impl ScheduledDrafts<SessionMessageTransport> { |
| 37 | pub fn new(session: &Session) -> Self { |
| 38 | Self::with_region(session, DEFAULT_REGION) |
| 39 | } |
| 40 | |
| 41 | pub fn with_region(session: &Session, region: &str) -> Self { |
| 42 | ScheduledDrafts::with_transport(SessionMessageTransport::new(session), region) |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | impl<T: MessageTransport> ScheduledDrafts<T> { |
| 47 | pub fn with_transport(transport: T, region: &str) -> Self { |
| 48 | ScheduledDrafts { |
| 49 | transport, |
| 50 | base_url: format!( |
| 51 | "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/drafts" |
| 52 | ), |
| 53 | retry_delay: DEFAULT_RETRY_DELAY, |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | pub fn with_retry_delay(mut self, retry_delay: Duration) -> Self { |
| 58 | self.retry_delay = retry_delay; |
| 59 | self |
| 60 | } |
| 61 | |
| 62 | pub fn draft_url(&self, draft_id: &str) -> String { |
| 63 | format!("{}/{}", self.base_url, encode(draft_id)) |
| 64 | } |
| 65 | |
| 66 | pub async fn create( |
| 67 | &self, |
| 68 | inner_thread_id: &str, |
| 69 | html: &str, |
| 70 | send_at: DateTime<Utc>, |
| 71 | display_name: &str, |
| 72 | ) -> Result<ScheduledDraft> { |
| 73 | let client_message_id = new_client_message_id(); |
| 74 | let body = draft_body( |
| 75 | inner_thread_id, |
| 76 | html, |
| 77 | send_at, |
| 78 | display_name, |
| 79 | &client_message_id, |
| 80 | None, |
| 81 | ); |
| 82 | let answer = self |
| 83 | .send_retrying_not_found(Method::Post, &self.base_url, &body) |
| 84 | .await?; |
| 85 | ensure_success(&answer)?; |
| 86 | // The POST answers without the draft id, so it is looked up by clientmessageid. |
| 87 | let mut delay = self.retry_delay; |
| 88 | for attempt in 0..=NOT_FOUND_RETRIES { |
| 89 | if attempt > 0 { |
| 90 | tokio::time::sleep(delay).await; |
| 91 | delay *= BACKOFF_FACTOR; |
| 92 | } |
| 93 | if let Some(draft) = self.find(&client_message_id).await? { |
| 94 | return Ok(draft); |
| 95 | } |
| 96 | } |
| 97 | Ok(ScheduledDraft { |
| 98 | id: String::new(), |
| 99 | client_message_id, |
| 100 | inner_thread_id: inner_thread_id.to_owned(), |
| 101 | send_at, |
| 102 | html: html.to_owned(), |
| 103 | delivery_state: None, |
| 104 | }) |
| 105 | } |
| 106 | |
| 107 | pub async fn list(&self) -> Result<Vec<ScheduledDraft>> { |
| 108 | self.list_at(Utc::now()).await |
| 109 | } |
| 110 | |
| 111 | pub async fn list_at(&self, now: DateTime<Utc>) -> Result<Vec<ScheduledDraft>> { |
| 112 | let start_time = (now - ChronoDuration::days(LIST_WINDOW_DAYS)).timestamp_millis(); |
| 113 | let url = format!( |
| 114 | "{}?view=msnp24Equivalent&pageSize={LIST_PAGE_SIZE}&startTime={start_time}", |
| 115 | self.base_url |
| 116 | ); |
| 117 | let answer = self.transport.send(Request::get(&url)).await?; |
| 118 | if answer.status == 404 { |
| 119 | return Ok(Vec::new()); |
| 120 | } |
| 121 | ensure_success(&answer)?; |
| 122 | Ok(parse_drafts(&answer.body)) |
| 123 | } |
| 124 | |
| 125 | pub async fn update( |
| 126 | &self, |
| 127 | draft: &ScheduledDraft, |
| 128 | html: &str, |
| 129 | display_name: &str, |
| 130 | ) -> Result<ScheduledDraft> { |
| 131 | let body = draft_body( |
| 132 | &draft.inner_thread_id, |
| 133 | html, |
| 134 | draft.send_at, |
| 135 | display_name, |
| 136 | &draft.client_message_id, |
| 137 | Some(&draft.id), |
| 138 | ); |
| 139 | let answer = self |
| 140 | .send_retrying_not_found(Method::Put, &self.draft_url(&draft.id), &body) |
| 141 | .await?; |
| 142 | ensure_success(&answer)?; |
| 143 | Ok(ScheduledDraft { |
| 144 | html: html.to_owned(), |
| 145 | ..draft.clone() |
| 146 | }) |
| 147 | } |
| 148 | |
| 149 | pub async fn cancel(&self, draft_id: &str) -> Result<()> { |
| 150 | let answer = self |
| 151 | .transport |
| 152 | .send(Request::delete(self.draft_url(draft_id))) |
| 153 | .await?; |
| 154 | ensure_success(&answer) |
| 155 | } |
| 156 | |
| 157 | async fn find(&self, client_message_id: &str) -> Result<Option<ScheduledDraft>> { |
| 158 | Ok(self |
| 159 | .list() |
| 160 | .await? |
| 161 | .into_iter() |
| 162 | .find(|draft| draft.client_message_id == client_message_id)) |
| 163 | } |
| 164 | |
| 165 | async fn send_retrying_not_found( |
| 166 | &self, |
| 167 | method: Method, |
| 168 | url: &str, |
| 169 | body: &Value, |
| 170 | ) -> Result<ApiResponse> { |
| 171 | let mut delay = self.retry_delay; |
| 172 | let mut answer = self |
| 173 | .transport |
| 174 | .send(Request::with_body(method, url, body.clone())) |
| 175 | .await?; |
| 176 | for _ in 0..NOT_FOUND_RETRIES { |
| 177 | if answer.status != 404 { |
| 178 | break; |
| 179 | } |
| 180 | tokio::time::sleep(delay).await; |
| 181 | delay *= BACKOFF_FACTOR; |
| 182 | answer = self |
| 183 | .transport |
| 184 | .send(Request::with_body(method, url, body.clone())) |
| 185 | .await?; |
| 186 | } |
| 187 | Ok(answer) |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | fn draft_body( |
| 192 | inner_thread_id: &str, |
| 193 | html: &str, |
| 194 | send_at: DateTime<Utc>, |
| 195 | display_name: &str, |
| 196 | client_message_id: &str, |
| 197 | draft_id: Option<&str>, |
| 198 | ) -> Value { |
| 199 | let mut message = json!({ |
| 200 | "content": html, |
| 201 | "messagetype": "RichText/Html", |
| 202 | "contenttype": "text", |
| 203 | "clientmessageid": client_message_id, |
| 204 | "imdisplayname": display_name, |
| 205 | "properties": {}, |
| 206 | }); |
| 207 | if let Some(draft_id) = draft_id { |
| 208 | message["id"] = json!(draft_id); |
| 209 | } |
| 210 | json!({ |
| 211 | "draftDetails": {"sendAt": send_at.timestamp_millis().to_string()}, |
| 212 | "draftType": SCHEDULED_DRAFT, |
| 213 | "innerThreadId": inner_thread_id, |
| 214 | "message": message, |
| 215 | }) |
| 216 | } |
| 217 | |
| 218 | fn parse_drafts(body: &Value) -> Vec<ScheduledDraft> { |
| 219 | body.get("drafts") |
| 220 | .and_then(Value::as_array) |
| 221 | .into_iter() |
| 222 | .flatten() |
| 223 | .filter_map(parse_draft) |
| 224 | .collect() |
| 225 | } |
| 226 | |
| 227 | fn parse_draft(draft: &Value) -> Option<ScheduledDraft> { |
| 228 | if draft["draftType"].as_str()? != SCHEDULED_DRAFT { |
| 229 | return None; |
| 230 | } |
| 231 | let properties = &draft["properties"]; |
| 232 | let html = draft["content"].as_str().filter(|html| !html.is_empty())?; |
| 233 | if !properties["deletetime"].is_null() { |
| 234 | return None; |
| 235 | } |
| 236 | let send_at_millis: i64 = draft["draftDetails"]["sendAt"] |
| 237 | .as_str() |
| 238 | .and_then(|text| text.parse().ok()) |
| 239 | .or_else(|| draft["draftDetails"]["sendAt"].as_i64())?; |
| 240 | Some(ScheduledDraft { |
| 241 | id: draft["id"].as_str()?.to_owned(), |
| 242 | client_message_id: draft["clientmessageid"].as_str()?.to_owned(), |
| 243 | inner_thread_id: draft["innerThreadId"].as_str()?.to_owned(), |
| 244 | send_at: DateTime::from_timestamp_millis(send_at_millis)?, |
| 245 | html: html.to_owned(), |
| 246 | delivery_state: properties["deliveryState"].as_str().map(str::to_owned), |
| 247 | }) |
| 248 | } |