| 1 | use chrono::{DateTime, SecondsFormat, Utc}; |
| 2 | use serde_json::{Value, json}; |
| 3 | use session::{GRAPH, Method, Scope}; |
| 4 | |
| 5 | use crate::client::Graph; |
| 6 | use crate::error::{Error, Result}; |
| 7 | use crate::models::{Chat, Member, Message}; |
| 8 | use crate::outgoing::{MessageExtras, OutgoingMention, message_body}; |
| 9 | use crate::target::MessageTarget; |
| 10 | use crate::urls; |
| 11 | |
| 12 | fn conversation_member(user_id: &str) -> Value { |
| 13 | json!({ |
| 14 | "@odata.type": "#microsoft.graph.aadUserConversationMember", |
| 15 | "roles": ["owner"], |
| 16 | "user@odata.bind": format!("{GRAPH}/v1.0/users('{user_id}')"), |
| 17 | }) |
| 18 | } |
| 19 | |
| 20 | fn user_body(user_id: &str, tenant_id: &str) -> Value { |
| 21 | json!({"user": {"id": user_id, "tenantId": tenant_id}}) |
| 22 | } |
| 23 | |
| 24 | fn mark_unread_body(user_id: &str, tenant_id: &str, last_read_at: DateTime<Utc>) -> Value { |
| 25 | json!({ |
| 26 | "user": {"id": user_id, "tenantId": tenant_id}, |
| 27 | "lastMessageReadDateTime": last_read_at.to_rfc3339_opts(SecondsFormat::Millis, true), |
| 28 | }) |
| 29 | } |
| 30 | |
| 31 | fn membership_id<'a>(members: &'a [Member], user_id: &str) -> Option<&'a str> { |
| 32 | members |
| 33 | .iter() |
| 34 | .find(|member| member.user_id.as_deref() == Some(user_id)) |
| 35 | .and_then(|member| member.id.as_deref()) |
| 36 | } |
| 37 | |
| 38 | impl Graph { |
| 39 | pub async fn send_chat_message( |
| 40 | &self, |
| 41 | chat_id: &str, |
| 42 | html: &str, |
| 43 | mentions: &[OutgoingMention], |
| 44 | extras: &MessageExtras, |
| 45 | ) -> Result<Message> { |
| 46 | self.write_for_message( |
| 47 | Method::Post, |
| 48 | &urls::chat_message_collection(chat_id), |
| 49 | "Chat.ReadWrite", |
| 50 | Some(message_body(html, mentions, extras)), |
| 51 | ) |
| 52 | .await |
| 53 | } |
| 54 | |
| 55 | pub async fn send_channel_message( |
| 56 | &self, |
| 57 | team_id: &str, |
| 58 | channel_id: &str, |
| 59 | html: &str, |
| 60 | subject: Option<&str>, |
| 61 | mentions: &[OutgoingMention], |
| 62 | extras: &MessageExtras, |
| 63 | ) -> Result<Message> { |
| 64 | let mut body = message_body(html, mentions, extras); |
| 65 | if let Some(subject) = subject.filter(|subject| !subject.is_empty()) { |
| 66 | body["subject"] = json!(subject); |
| 67 | } |
| 68 | self.write_for_message( |
| 69 | Method::Post, |
| 70 | &urls::channel_post(team_id, channel_id), |
| 71 | "ChannelMessage.Send", |
| 72 | Some(body), |
| 73 | ) |
| 74 | .await |
| 75 | } |
| 76 | |
| 77 | pub async fn reply_to_channel_message( |
| 78 | &self, |
| 79 | team_id: &str, |
| 80 | channel_id: &str, |
| 81 | message_id: &str, |
| 82 | html: &str, |
| 83 | mentions: &[OutgoingMention], |
| 84 | extras: &MessageExtras, |
| 85 | ) -> Result<Message> { |
| 86 | self.write_for_message( |
| 87 | Method::Post, |
| 88 | &urls::channel_reply_post(team_id, channel_id, message_id), |
| 89 | "ChannelMessage.Send", |
| 90 | Some(message_body(html, mentions, extras)), |
| 91 | ) |
| 92 | .await |
| 93 | } |
| 94 | |
| 95 | /// Beta API `chats/{id}/messages/replyWithQuote`; Teams renders the quote from the `messageReference` attachment. |
| 96 | pub async fn reply_with_quote( |
| 97 | &self, |
| 98 | chat_id: &str, |
| 99 | quoted_message_id: &str, |
| 100 | html: &str, |
| 101 | mentions: &[OutgoingMention], |
| 102 | extras: &MessageExtras, |
| 103 | ) -> Result<Message> { |
| 104 | let body = json!({ |
| 105 | "messageIds": [quoted_message_id], |
| 106 | "replyMessage": message_body(html, mentions, extras), |
| 107 | }); |
| 108 | self.write_for_message( |
| 109 | Method::Post, |
| 110 | &urls::reply_with_quote(chat_id), |
| 111 | "Chat.ReadWrite", |
| 112 | Some(body), |
| 113 | ) |
| 114 | .await |
| 115 | } |
| 116 | |
| 117 | pub async fn mark_chat_read( |
| 118 | &self, |
| 119 | chat_id: &str, |
| 120 | user_id: &str, |
| 121 | tenant_id: &str, |
| 122 | ) -> Result<()> { |
| 123 | self.write( |
| 124 | Method::Post, |
| 125 | &urls::mark_chat_read(chat_id), |
| 126 | "Chat.ReadWrite", |
| 127 | Some(user_body(user_id, tenant_id)), |
| 128 | ) |
| 129 | .await |
| 130 | } |
| 131 | |
| 132 | pub async fn mark_chat_unread( |
| 133 | &self, |
| 134 | chat_id: &str, |
| 135 | user_id: &str, |
| 136 | tenant_id: &str, |
| 137 | last_read_at: DateTime<Utc>, |
| 138 | ) -> Result<()> { |
| 139 | let body = mark_unread_body(user_id, tenant_id, last_read_at); |
| 140 | self.write( |
| 141 | Method::Post, |
| 142 | &urls::mark_chat_unread(chat_id), |
| 143 | "Chat.ReadWrite", |
| 144 | Some(body), |
| 145 | ) |
| 146 | .await |
| 147 | } |
| 148 | |
| 149 | pub async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> { |
| 150 | self.write( |
| 151 | Method::Post, |
| 152 | &urls::hide_chat(chat_id), |
| 153 | "Chat.ReadWrite", |
| 154 | Some(user_body(user_id, tenant_id)), |
| 155 | ) |
| 156 | .await |
| 157 | } |
| 158 | |
| 159 | pub async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> { |
| 160 | self.write( |
| 161 | Method::Post, |
| 162 | &urls::unhide_chat(chat_id), |
| 163 | "Chat.ReadWrite", |
| 164 | Some(user_body(user_id, tenant_id)), |
| 165 | ) |
| 166 | .await |
| 167 | } |
| 168 | |
| 169 | pub async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> { |
| 170 | let members = self.chat_members(chat_id).await?; |
| 171 | let membership_id = membership_id(&members, user_id).ok_or(Error::NotAMember)?; |
| 172 | self.write( |
| 173 | Method::Delete, |
| 174 | &urls::chat_member(chat_id, membership_id), |
| 175 | "Chat.ReadWrite", |
| 176 | None, |
| 177 | ) |
| 178 | .await |
| 179 | } |
| 180 | |
| 181 | pub async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> { |
| 182 | self.write( |
| 183 | Method::Post, |
| 184 | &target.reaction_url("setReaction"), |
| 185 | target.react_scope(), |
| 186 | Some(json!({"reactionType": reaction_type})), |
| 187 | ) |
| 188 | .await |
| 189 | } |
| 190 | |
| 191 | pub async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> { |
| 192 | self.write( |
| 193 | Method::Post, |
| 194 | &target.reaction_url("unsetReaction"), |
| 195 | target.react_scope(), |
| 196 | Some(json!({"reactionType": reaction_type})), |
| 197 | ) |
| 198 | .await |
| 199 | } |
| 200 | |
| 201 | pub async fn edit_message( |
| 202 | &self, |
| 203 | target: &MessageTarget, |
| 204 | html: &str, |
| 205 | mentions: &[OutgoingMention], |
| 206 | extras: &MessageExtras, |
| 207 | ) -> Result<()> { |
| 208 | self.write( |
| 209 | Method::Patch, |
| 210 | &target.url(), |
| 211 | target.write_scope(), |
| 212 | Some(message_body(html, mentions, extras)), |
| 213 | ) |
| 214 | .await |
| 215 | } |
| 216 | |
| 217 | /// `user_id` is only used for chats. |
| 218 | pub async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> { |
| 219 | self.write( |
| 220 | Method::Post, |
| 221 | &target.soft_delete_url(user_id), |
| 222 | target.write_scope(), |
| 223 | None, |
| 224 | ) |
| 225 | .await |
| 226 | } |
| 227 | |
| 228 | pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> { |
| 229 | let body = json!({ |
| 230 | "chatType": "oneOnOne", |
| 231 | "members": [conversation_member(my_user_id), conversation_member(user_id)], |
| 232 | }); |
| 233 | self.write_for_chat(body).await |
| 234 | } |
| 235 | |
| 236 | pub async fn create_group( |
| 237 | &self, |
| 238 | my_user_id: &str, |
| 239 | user_ids: &[String], |
| 240 | topic: Option<&str>, |
| 241 | ) -> Result<Chat> { |
| 242 | let members: Vec<Value> = std::iter::once(my_user_id) |
| 243 | .chain(user_ids.iter().map(String::as_str)) |
| 244 | .map(conversation_member) |
| 245 | .collect(); |
| 246 | let mut body = json!({"chatType": "group", "members": members}); |
| 247 | if let Some(topic) = topic.filter(|topic| !topic.is_empty()) { |
| 248 | body["topic"] = json!(topic); |
| 249 | } |
| 250 | self.write_for_chat(body).await |
| 251 | } |
| 252 | |
| 253 | async fn write_for_chat(&self, body: Value) -> Result<Chat> { |
| 254 | let answer = self |
| 255 | .session() |
| 256 | .request( |
| 257 | Method::Post, |
| 258 | &urls::create_chat(), |
| 259 | &Scope::graph("Chat.ReadWrite"), |
| 260 | Some(body), |
| 261 | ) |
| 262 | .await?; |
| 263 | Ok(serde_json::from_value(answer.body)?) |
| 264 | } |
| 265 | |
| 266 | async fn write_for_message( |
| 267 | &self, |
| 268 | method: Method, |
| 269 | url: &str, |
| 270 | scope: &'static str, |
| 271 | body: Option<Value>, |
| 272 | ) -> Result<Message> { |
| 273 | let answer = self |
| 274 | .session() |
| 275 | .request(method, url, &Scope::graph(scope), body) |
| 276 | .await?; |
| 277 | Ok(serde_json::from_value(answer.body)?) |
| 278 | } |
| 279 | |
| 280 | async fn write( |
| 281 | &self, |
| 282 | method: Method, |
| 283 | url: &str, |
| 284 | scope: &'static str, |
| 285 | body: Option<Value>, |
| 286 | ) -> Result<()> { |
| 287 | self.session() |
| 288 | .request(method, url, &Scope::graph(scope), body) |
| 289 | .await?; |
| 290 | Ok(()) |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | #[cfg(test)] |
| 295 | mod tests { |
| 296 | use chrono::TimeZone; |
| 297 | |
| 298 | use super::*; |
| 299 | |
| 300 | fn member(id: &str, user_id: &str) -> Member { |
| 301 | Member { |
| 302 | id: Some(id.to_owned()), |
| 303 | user_id: Some(user_id.to_owned()), |
| 304 | tenant_id: None, |
| 305 | display_name: None, |
| 306 | email: None, |
| 307 | } |
| 308 | } |
| 309 | |
| 310 | #[test] |
| 311 | fn membership_is_found_by_user_id() { |
| 312 | let members = [member("m1", "u1"), member("m2", "u2")]; |
| 313 | assert_eq!(membership_id(&members, "u2"), Some("m2")); |
| 314 | assert_eq!(membership_id(&members, "u3"), None); |
| 315 | } |
| 316 | |
| 317 | #[test] |
| 318 | fn mark_unread_body_carries_the_read_horizon() { |
| 319 | let at = Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, 0).unwrap(); |
| 320 | let body = mark_unread_body("u1", "t1", at); |
| 321 | assert_eq!(body["user"]["id"], "u1"); |
| 322 | assert_eq!(body["user"]["tenantId"], "t1"); |
| 323 | assert_eq!(body["lastMessageReadDateTime"], "2026-10-06T09:00:00.000Z"); |
| 324 | } |
| 325 | } |