BlueGit

ict rusty-teams

Files

rusty-teams / crates / graph / src / writes.rs

writes.rs

writes.rs 9.6 KiB Download Raw
1use chrono::{DateTime, SecondsFormat, Utc};
2use serde_json::{Value, json};
3use session::{GRAPH, Method, Scope};
4
5use crate::client::Graph;
6use crate::error::{Error, Result};
7use crate::models::{Chat, Member, Message};
8use crate::outgoing::{MessageExtras, OutgoingMention, message_body};
9use crate::target::MessageTarget;
10use crate::urls;
11
12fn 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
20fn user_body(user_id: &str, tenant_id: &str) -> Value {
21 json!({"user": {"id": user_id, "tenantId": tenant_id}})
22}
23
24fn 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
31fn 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
38impl 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 /// `user_id` is only used for chats.
229 pub async fn undo_soft_delete_message(
230 &self,
231 user_id: &str,
232 target: &MessageTarget,
233 ) -> Result<()> {
234 self.write(
235 Method::Post,
236 &target.undo_soft_delete_url(user_id),
237 target.write_scope(),
238 None,
239 )
240 .await
241 }
242
243 pub async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> {
244 let body = json!({
245 "chatType": "oneOnOne",
246 "members": [conversation_member(my_user_id), conversation_member(user_id)],
247 });
248 self.write_for_chat(body).await
249 }
250
251 pub async fn create_group(
252 &self,
253 my_user_id: &str,
254 user_ids: &[String],
255 topic: Option<&str>,
256 ) -> Result<Chat> {
257 let members: Vec<Value> = std::iter::once(my_user_id)
258 .chain(user_ids.iter().map(String::as_str))
259 .map(conversation_member)
260 .collect();
261 let mut body = json!({"chatType": "group", "members": members});
262 if let Some(topic) = topic.filter(|topic| !topic.is_empty()) {
263 body["topic"] = json!(topic);
264 }
265 self.write_for_chat(body).await
266 }
267
268 async fn write_for_chat(&self, body: Value) -> Result<Chat> {
269 let answer = self
270 .session()
271 .request(
272 Method::Post,
273 &urls::create_chat(),
274 &Scope::graph("Chat.ReadWrite"),
275 Some(body),
276 )
277 .await?;
278 Ok(serde_json::from_value(answer.body)?)
279 }
280
281 async fn write_for_message(
282 &self,
283 method: Method,
284 url: &str,
285 scope: &'static str,
286 body: Option<Value>,
287 ) -> Result<Message> {
288 let answer = self
289 .session()
290 .request(method, url, &Scope::graph(scope), body)
291 .await?;
292 Ok(serde_json::from_value(answer.body)?)
293 }
294
295 async fn write(
296 &self,
297 method: Method,
298 url: &str,
299 scope: &'static str,
300 body: Option<Value>,
301 ) -> Result<()> {
302 self.session()
303 .request(method, url, &Scope::graph(scope), body)
304 .await?;
305 Ok(())
306 }
307}
308
309#[cfg(test)]
310mod tests {
311 use chrono::TimeZone;
312
313 use super::*;
314
315 fn member(id: &str, user_id: &str) -> Member {
316 Member {
317 id: Some(id.to_owned()),
318 user_id: Some(user_id.to_owned()),
319 tenant_id: None,
320 display_name: None,
321 email: None,
322 }
323 }
324
325 #[test]
326 fn membership_is_found_by_user_id() {
327 let members = [member("m1", "u1"), member("m2", "u2")];
328 assert_eq!(membership_id(&members, "u2"), Some("m2"));
329 assert_eq!(membership_id(&members, "u3"), None);
330 }
331
332 #[test]
333 fn mark_unread_body_carries_the_read_horizon() {
334 let at = Utc.with_ymd_and_hms(2026, 10, 6, 9, 0, 0).unwrap();
335 let body = mark_unread_body("u1", "t1", at);
336 assert_eq!(body["user"]["id"], "u1");
337 assert_eq!(body["user"]["tenantId"], "t1");
338 assert_eq!(body["lastMessageReadDateTime"], "2026-10-06T09:00:00.000Z");
339 }
340}