| 1 | use std::time::Duration; |
| 2 | |
| 3 | use chrono::Utc; |
| 4 | use percent_encoding::{AsciiSet, NON_ALPHANUMERIC, utf8_percent_encode}; |
| 5 | use serde_json::{Value, json}; |
| 6 | use session::{ApiResponse, IC3, Method, Request, Scope, Session}; |
| 7 | |
| 8 | use crate::error::{Error, Result}; |
| 9 | use crate::pins::DEFAULT_REGION; |
| 10 | |
| 11 | const MESSAGES_SCOPE: &str = "Teams.AccessAsUser.All"; |
| 12 | pub fn messages_scope() -> Scope { |
| 13 | Scope::new(IC3, MESSAGES_SCOPE) |
| 14 | } |
| 15 | |
| 16 | pub const DEFAULT_RETRY_DELAY: Duration = Duration::from_millis(500); |
| 17 | |
| 18 | const ENCODE_COMPONENT: &AsciiSet = &NON_ALPHANUMERIC |
| 19 | .remove(b'-') |
| 20 | .remove(b'_') |
| 21 | .remove(b'.') |
| 22 | .remove(b'!') |
| 23 | .remove(b'~') |
| 24 | .remove(b'*') |
| 25 | .remove(b'\'') |
| 26 | .remove(b'(') |
| 27 | .remove(b')'); |
| 28 | |
| 29 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 30 | pub enum ConversationRef { |
| 31 | Chat { chat_id: String }, |
| 32 | ChannelRoot { channel_id: String }, |
| 33 | ChannelReply { channel_id: String, root_id: String }, |
| 34 | } |
| 35 | |
| 36 | impl ConversationRef { |
| 37 | pub fn chat(chat_id: &str) -> Self { |
| 38 | ConversationRef::Chat { |
| 39 | chat_id: chat_id.to_owned(), |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | pub fn channel_root(channel_id: &str) -> Self { |
| 44 | ConversationRef::ChannelRoot { |
| 45 | channel_id: channel_id.to_owned(), |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | pub fn channel_reply(channel_id: &str, root_id: &str) -> Self { |
| 50 | ConversationRef::ChannelReply { |
| 51 | channel_id: channel_id.to_owned(), |
| 52 | root_id: root_id.to_owned(), |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | pub fn conversation_id(&self) -> String { |
| 57 | match self { |
| 58 | ConversationRef::Chat { chat_id } => chat_id.clone(), |
| 59 | ConversationRef::ChannelRoot { channel_id } => channel_id.clone(), |
| 60 | ConversationRef::ChannelReply { |
| 61 | channel_id, |
| 62 | root_id, |
| 63 | } => format!("{channel_id};messageid={root_id}"), |
| 64 | } |
| 65 | } |
| 66 | } |
| 67 | |
| 68 | pub(crate) fn encode(value: &str) -> String { |
| 69 | utf8_percent_encode(value, ENCODE_COMPONENT).to_string() |
| 70 | } |
| 71 | |
| 72 | pub trait MessageTransport { |
| 73 | fn send(&self, request: Request) -> impl std::future::Future<Output = Result<ApiResponse>>; |
| 74 | } |
| 75 | |
| 76 | pub struct SessionMessageTransport { |
| 77 | session: Session, |
| 78 | scope: Scope, |
| 79 | } |
| 80 | |
| 81 | impl SessionMessageTransport { |
| 82 | pub fn new(session: &Session) -> Self { |
| 83 | SessionMessageTransport { |
| 84 | session: session.clone(), |
| 85 | scope: messages_scope(), |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | impl MessageTransport for SessionMessageTransport { |
| 91 | async fn send(&self, request: Request) -> Result<ApiResponse> { |
| 92 | let mut answers = self.session.batch(&[request], &self.scope).await?; |
| 93 | Ok(answers.remove(0)) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | pub struct Messages<T: MessageTransport = SessionMessageTransport> { |
| 98 | transport: T, |
| 99 | base_url: String, |
| 100 | retry_delay: Duration, |
| 101 | } |
| 102 | |
| 103 | impl Messages<SessionMessageTransport> { |
| 104 | pub fn new(session: &Session) -> Self { |
| 105 | Self::with_region(session, DEFAULT_REGION) |
| 106 | } |
| 107 | |
| 108 | pub fn with_region(session: &Session, region: &str) -> Self { |
| 109 | Messages::with_transport(SessionMessageTransport::new(session), region) |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | impl<T: MessageTransport> Messages<T> { |
| 114 | pub fn with_transport(transport: T, region: &str) -> Self { |
| 115 | Messages { |
| 116 | transport, |
| 117 | base_url: format!( |
| 118 | "https://teams.cloud.microsoft/api/chatsvc/{region}/v1/users/ME/conversations" |
| 119 | ), |
| 120 | retry_delay: DEFAULT_RETRY_DELAY, |
| 121 | } |
| 122 | } |
| 123 | |
| 124 | pub fn with_retry_delay(mut self, retry_delay: Duration) -> Self { |
| 125 | self.retry_delay = retry_delay; |
| 126 | self |
| 127 | } |
| 128 | |
| 129 | pub fn message_url(&self, conversation: &ConversationRef, message_id: &str) -> String { |
| 130 | format!( |
| 131 | "{}/{}/messages/{}", |
| 132 | self.base_url, |
| 133 | encode(&conversation.conversation_id()), |
| 134 | encode(message_id) |
| 135 | ) |
| 136 | } |
| 137 | |
| 138 | pub async fn edit_message( |
| 139 | &self, |
| 140 | conversation: &ConversationRef, |
| 141 | message_id: &str, |
| 142 | html: &str, |
| 143 | ) -> Result<()> { |
| 144 | let url = self.message_url(conversation, message_id); |
| 145 | let body = edit_body(message_id, html); |
| 146 | let mut answer = self.put(&url, &body).await?; |
| 147 | if answer.status == 404 { |
| 148 | tokio::time::sleep(self.retry_delay).await; |
| 149 | answer = self.put(&url, &body).await?; |
| 150 | } |
| 151 | ensure_success(&answer) |
| 152 | } |
| 153 | |
| 154 | pub async fn soft_delete_message( |
| 155 | &self, |
| 156 | conversation: &ConversationRef, |
| 157 | message_id: &str, |
| 158 | ) -> Result<()> { |
| 159 | let url = format!( |
| 160 | "{}?behavior=softDelete", |
| 161 | self.message_url(conversation, message_id) |
| 162 | ); |
| 163 | let answer = self.transport.send(Request::delete(&url)).await?; |
| 164 | ensure_success(&answer) |
| 165 | } |
| 166 | |
| 167 | async fn put(&self, url: &str, body: &Value) -> Result<ApiResponse> { |
| 168 | self.transport |
| 169 | .send(Request::with_body(Method::Put, url, body.clone())) |
| 170 | .await |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | fn edit_body(message_id: &str, html: &str) -> Value { |
| 175 | json!({ |
| 176 | "id": message_id, |
| 177 | "content": html, |
| 178 | "messagetype": "RichText/Html", |
| 179 | "contenttype": "text", |
| 180 | "properties": {"edittime": Utc::now().timestamp_millis().to_string()}, |
| 181 | }) |
| 182 | } |
| 183 | |
| 184 | fn ensure_success(answer: &ApiResponse) -> Result<()> { |
| 185 | if answer.is_success() { |
| 186 | Ok(()) |
| 187 | } else { |
| 188 | Err(Error::Session(session::Error::api( |
| 189 | answer.status, |
| 190 | "chatsvc", |
| 191 | answer.body.clone(), |
| 192 | ))) |
| 193 | } |
| 194 | } |