BlueGit

ict rusty-teams

feat(channels): write channel quote replies like Teams via chatsvc

- quote as Teams' blockquote (itemscope, itemtype Reply, itemid, mri with sender itemid, time, preview)
- qtdMsgs property with messageId, sender, time
- POST through chatsvc reply thread, person mentions as Teams spans
- drop the Graph messageReference attachment
- engine test asserts the Teams shape

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-18 · 6 weeks ago

Hash
647843e337719862fb5ecc84ac271ac786806778
Parent
4fa800b3
7 files changed +364 −47
crates/chatsvc/src/messages.rs +39 −0
@@ -225,6 +225,34 @@ impl<T: MessageTransport> Messages<T> {
225 225 }
226 226 }
227 227
228 /// Answers with the new message id, which chatsvc returns as `OriginalArrivalTime`.
229 pub async fn post_message(
230 &self,
231 conversation: &ConversationRef,
232 html: &str,
233 display_name: &str,
234 properties: &Value,
235 ) -> Result<String> {
236 let url = format!(
237 "{}/{}/messages",
238 self.base_url,
239 encode(&conversation.conversation_id())
240 );
241 let body = rich_text_body(html, display_name, properties);
242 let answer = self
243 .transport
244 .send(Request::with_body(Method::Post, &url, body))
245 .await?;
246 ensure_success(&answer)?;
247 match &answer.body["OriginalArrivalTime"] {
248 Value::Number(number) => Ok(number.to_string()),
249 Value::String(text) => Ok(text.clone()),
250 _ => Err(Error::UnexpectedAnswer(
251 "message post has no OriginalArrivalTime".into(),
252 )),
253 }
254 }
255
228 256 pub async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
229 257 let url = format!(
230 258 "{}/{}/messages",
@@ -277,6 +305,17 @@ fn edit_body(message_id: &str, html: &str) -> Value {
277 305 })
278 306 }
279 307
308 fn rich_text_body(html: &str, display_name: &str, properties: &Value) -> Value {
309 json!({
310 "clientmessageid": Utc::now().timestamp_millis().to_string(),
311 "content": html,
312 "messagetype": "RichText/Html",
313 "contenttype": "text",
314 "imdisplayname": display_name,
315 "properties": properties,
316 })
317 }
318
280 319 fn typing_body(active: bool) -> Value {
281 320 json!({
282 321 "content": "",
@@ -225,6 +225,34 @@ impl<T: MessageTransport> Messages<T> {
225 }
225 }
226 }
226 }
227
227
228 /// Answers with the new message id, which chatsvc returns as `OriginalArrivalTime`.
229 pub async fn post_message(
230 &self,
231 conversation: &ConversationRef,
232 html: &str,
233 display_name: &str,
234 properties: &Value,
235 ) -> Result<String> {
236 let url = format!(
237 "{}/{}/messages",
238 self.base_url,
239 encode(&conversation.conversation_id())
240 );
241 let body = rich_text_body(html, display_name, properties);
242 let answer = self
243 .transport
244 .send(Request::with_body(Method::Post, &url, body))
245 .await?;
246 ensure_success(&answer)?;
247 match &answer.body["OriginalArrivalTime"] {
248 Value::Number(number) => Ok(number.to_string()),
249 Value::String(text) => Ok(text.clone()),
250 _ => Err(Error::UnexpectedAnswer(
251 "message post has no OriginalArrivalTime".into(),
252 )),
253 }
254 }
255
228 pub async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
256 pub async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> {
229 let url = format!(
257 let url = format!(
230 "{}/{}/messages",
258 "{}/{}/messages",
@@ -277,6 +305,17 @@ fn edit_body(message_id: &str, html: &str) -> Value {
277 })
305 })
278}
306}
279
307
308fn rich_text_body(html: &str, display_name: &str, properties: &Value) -> Value {
309 json!({
310 "clientmessageid": Utc::now().timestamp_millis().to_string(),
311 "content": html,
312 "messagetype": "RichText/Html",
313 "contenttype": "text",
314 "imdisplayname": display_name,
315 "properties": properties,
316 })
317}
318
280fn typing_body(active: bool) -> Value {
319fn typing_body(active: bool) -> Value {
281 json!({
320 json!({
282 "content": "",
321 "content": "",
crates/chatsvc/tests/messages.rs +46 −0
@@ -386,3 +386,49 @@ async fn list_message_links_asks_for_the_msnp24_view() {
386 386 format!("{BASE}/19%3Ac%40thread.tacv2/messages?view=msnp24Equivalent&pageSize=50")
387 387 );
388 388 }
389
390 struct ArrivalMock {
391 requests: Mutex<Vec<Request>>,
392 }
393
394 impl chatsvc::messages::MessageTransport for &ArrivalMock {
395 async fn send(&self, request: Request) -> Result<ApiResponse> {
396 self.requests.lock().unwrap().push(request);
397 Ok(ApiResponse {
398 status: 201,
399 body: serde_json::json!({"OriginalArrivalTime": 1727203440000_i64}),
400 retry_after: None,
401 })
402 }
403 }
404
405 #[tokio::test]
406 async fn post_message_sends_rich_text_to_the_reply_thread_and_returns_the_arrival_id() {
407 let mock = ArrivalMock {
408 requests: Mutex::new(Vec::new()),
409 };
410 let properties = serde_json::json!({"importance": "", "subject": "", "qtdMsgs": "[]"});
411 let message_id = Messages::with_transport(&mock, "emea")
412 .post_message(
413 &ConversationRef::channel_reply("19:c@thread.tacv2", "99"),
414 "<p>hi</p>",
415 "Daniel",
416 &properties,
417 )
418 .await
419 .unwrap();
420 assert_eq!(message_id, "1727203440000");
421 let requests = mock.requests.lock().unwrap().clone();
422 assert_eq!(requests[0].method, Method::Post);
423 assert_eq!(
424 requests[0].url,
425 format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")
426 );
427 let body = requests[0].body.as_ref().unwrap();
428 assert_eq!(body["messagetype"], "RichText/Html");
429 assert_eq!(body["contenttype"], "text");
430 assert_eq!(body["content"], "<p>hi</p>");
431 assert_eq!(body["imdisplayname"], "Daniel");
432 assert_eq!(body["properties"], properties);
433 assert!(body["clientmessageid"].is_string());
434 }
@@ -386,3 +386,49 @@ async fn list_message_links_asks_for_the_msnp24_view() {
386 format!("{BASE}/19%3Ac%40thread.tacv2/messages?view=msnp24Equivalent&pageSize=50")
386 format!("{BASE}/19%3Ac%40thread.tacv2/messages?view=msnp24Equivalent&pageSize=50")
387 );
387 );
388}
388}
389
390struct ArrivalMock {
391 requests: Mutex<Vec<Request>>,
392}
393
394impl chatsvc::messages::MessageTransport for &ArrivalMock {
395 async fn send(&self, request: Request) -> Result<ApiResponse> {
396 self.requests.lock().unwrap().push(request);
397 Ok(ApiResponse {
398 status: 201,
399 body: serde_json::json!({"OriginalArrivalTime": 1727203440000_i64}),
400 retry_after: None,
401 })
402 }
403}
404
405#[tokio::test]
406async fn post_message_sends_rich_text_to_the_reply_thread_and_returns_the_arrival_id() {
407 let mock = ArrivalMock {
408 requests: Mutex::new(Vec::new()),
409 };
410 let properties = serde_json::json!({"importance": "", "subject": "", "qtdMsgs": "[]"});
411 let message_id = Messages::with_transport(&mock, "emea")
412 .post_message(
413 &ConversationRef::channel_reply("19:c@thread.tacv2", "99"),
414 "<p>hi</p>",
415 "Daniel",
416 &properties,
417 )
418 .await
419 .unwrap();
420 assert_eq!(message_id, "1727203440000");
421 let requests = mock.requests.lock().unwrap().clone();
422 assert_eq!(requests[0].method, Method::Post);
423 assert_eq!(
424 requests[0].url,
425 format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")
426 );
427 let body = requests[0].body.as_ref().unwrap();
428 assert_eq!(body["messagetype"], "RichText/Html");
429 assert_eq!(body["contenttype"], "text");
430 assert_eq!(body["content"], "<p>hi</p>");
431 assert_eq!(body["imdisplayname"], "Daniel");
432 assert_eq!(body["properties"], properties);
433 assert!(body["clientmessageid"].is_string());
434}
crates/core/src/actions.rs +69 −36
@@ -1,7 +1,7 @@
1 1 use chatsvc::ConversationRef;
2 2 use chrono::{DateTime, Duration, Utc};
3 3 use graph::{
4 FileReference, KeptAttachment, MessageExtras, MessageTarget, OutgoingMention,
4 FileReference, MessageExtras, MessageTarget, OutgoingMention,
5 5 UploadDestination, UploadedFile, hosted_image_order,
6 6 };
7 7 use store::MessageRecord;
@@ -13,12 +13,10 @@ use crate::hidden_chats::cleared_until_ms;
13 13 use crate::links::LinkPreview;
14 14 use crate::mapping::message_record;
15 15 use crate::markdown::markdown_to_html;
16 use crate::preview::preview_text;
17 16 use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
18 17 use crate::remote::Remote;
19 18 use crate::scheduled::NOTES_CHAT_ID;
20
21 const MESSAGE_REFERENCE: &str = "messageReference";
19 use crate::teams_quote::{chatsvc_mention_html, quote_reply_properties, teams_quote};
22 20
23 21 impl<R: Remote> SyncEngine<R> {
24 22 pub async fn send_message(
@@ -144,9 +142,19 @@ impl<R: Remote> SyncEngine<R> {
144 142 .as_ref()
145 143 .and_then(|record| record.reply_to_id.clone())
146 144 .unwrap_or_else(|| message_id.to_owned());
147 let mut extras = extras.clone();
148 if let Some(quoted) = &quoted {
149 extras.kept.insert(0, quote_reference(quoted));
145 if let Some(quoted) = &quoted
146 && let Some((sent, html)) = self
147 .quote_reply_via_chatsvc(
148 conversation_id,
149 &root_id,
150 quoted,
151 &html,
152 &mentions,
153 extras,
154 )
155 .await?
156 {
157 return self.cache_sent(conversation_id, &sent, &html, extras);
150 158 }
151 159 let sent = self
152 160 .remote
@@ -156,10 +164,10 @@ impl<R: Remote> SyncEngine<R> {
156 164 &root_id,
157 165 &html,
158 166 &mentions,
159 &extras,
167 extras,
160 168 )
161 169 .await?;
162 (sent, extras)
170 (sent, extras.clone())
163 171 }
164 172 };
165 173 self.cache_sent(conversation_id, &sent, &html, &extras)
@@ -742,6 +750,58 @@ impl<R: Remote> SyncEngine<R> {
742 750 self.seed_images(&seeds)
743 751 }
744 752
753 async fn quote_reply_via_chatsvc(
754 &self,
755 channel_id: &str,
756 root_id: &str,
757 quoted: &MessageRecord,
758 html: &str,
759 mentions: &[OutgoingMention],
760 extras: &MessageExtras,
761 ) -> Result<Option<(graph::Message, String)>> {
762 if !extras.images.is_empty() || !extras.files.is_empty() {
763 return Ok(None);
764 }
765 let Some(quote) = teams_quote(quoted) else {
766 return Ok(None);
767 };
768 let Some(properties) = quote_reply_properties(&quote, mentions, extras.importance) else {
769 return Ok(None);
770 };
771 self.ensure_display_name().await?;
772 let me = self
773 .me()
774 .ok_or(Error::Unsupported("a quote reply before sign-in"))?;
775 let content = format!("{}{}", quote.html, chatsvc_mention_html(html, mentions));
776 let message_id = self
777 .remote
778 .post_chatsvc_message(
779 &ConversationRef::channel_reply(channel_id, root_id),
780 &content,
781 &me.display_name,
782 &properties,
783 )
784 .await?;
785 let created_at = message_id
786 .parse::<i64>()
787 .ok()
788 .and_then(DateTime::from_timestamp_millis)
789 .unwrap_or_else(Utc::now);
790 let cached_html = format!("{}{html}", quote.html);
791 let sent = serde_json::from_value(serde_json::json!({
792 "id": message_id,
793 "messageType": "message",
794 "createdDateTime": created_at.to_rfc3339(),
795 "replyToId": root_id,
796 "importance": extras.importance,
797 "from": {"user": {"id": me.user_id, "displayName": me.display_name}},
798 "body": {"contentType": "html", "content": cached_html},
799 "mentions": mentions.iter().map(OutgoingMention::to_json).collect::<Vec<_>>(),
800 }))
801 .map_err(|_| Error::Unsupported("a chatsvc reply without a message shape"))?;
802 Ok(Some((sent, cached_html)))
803 }
804
745 805 fn cache_sent(
746 806 &self,
747 807 conversation_id: &str,
@@ -804,33 +864,6 @@ fn outgoing(
804 864 Ok(apply_mentions(html, mentions))
805 865 }
806 866
807 /// The `messageReference` attachment Graph's chat `replyWithQuote` produces; channels have no such action.
808 fn quote_reference(record: &MessageRecord) -> KeptAttachment {
809 let sender = record.sender_id.as_ref().map(|user_id| {
810 serde_json::json!({
811 "application": null,
812 "device": null,
813 "user": {
814 "userIdentityType": "aadUser",
815 "id": user_id,
816 "displayName": record.sender_name,
817 },
818 })
819 });
820 let content = serde_json::json!({
821 "messageId": record.message_id,
822 "messagePreview": preview_text(&record.body_html).unwrap_or_default(),
823 "messageSender": sender,
824 });
825 KeptAttachment {
826 id: record.message_id.clone(),
827 content_type: Some(MESSAGE_REFERENCE.to_owned()),
828 content: Some(content.to_string()),
829 content_url: None,
830 name: None,
831 }
832 }
833
834 867 fn missing_attachment_id() -> Error {
835 868 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
836 869 }
@@ -1,7 +1,7 @@
1use chatsvc::ConversationRef;
1use chatsvc::ConversationRef;
2use chrono::{DateTime, Duration, Utc};
2use chrono::{DateTime, Duration, Utc};
3use graph::{
3use graph::{
4 FileReference, KeptAttachment, MessageExtras, MessageTarget, OutgoingMention,
4 FileReference, MessageExtras, MessageTarget, OutgoingMention,
5 UploadDestination, UploadedFile, hosted_image_order,
5 UploadDestination, UploadedFile, hosted_image_order,
6};
6};
7use store::MessageRecord;
7use store::MessageRecord;
@@ -13,12 +13,10 @@ use crate::hidden_chats::cleared_until_ms;
13use crate::links::LinkPreview;
13use crate::links::LinkPreview;
14use crate::mapping::message_record;
14use crate::mapping::message_record;
15use crate::markdown::markdown_to_html;
15use crate::markdown::markdown_to_html;
16use crate::preview::preview_text;
17use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
16use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
18use crate::remote::Remote;
17use crate::remote::Remote;
19use crate::scheduled::NOTES_CHAT_ID;
18use crate::scheduled::NOTES_CHAT_ID;
20
19use crate::teams_quote::{chatsvc_mention_html, quote_reply_properties, teams_quote};
21const MESSAGE_REFERENCE: &str = "messageReference";
22
20
23impl<R: Remote> SyncEngine<R> {
21impl<R: Remote> SyncEngine<R> {
24 pub async fn send_message(
22 pub async fn send_message(
@@ -144,9 +142,19 @@ impl<R: Remote> SyncEngine<R> {
144 .as_ref()
142 .as_ref()
145 .and_then(|record| record.reply_to_id.clone())
143 .and_then(|record| record.reply_to_id.clone())
146 .unwrap_or_else(|| message_id.to_owned());
144 .unwrap_or_else(|| message_id.to_owned());
147 let mut extras = extras.clone();
145 if let Some(quoted) = &quoted
148 if let Some(quoted) = &quoted {
146 && let Some((sent, html)) = self
149 extras.kept.insert(0, quote_reference(quoted));
147 .quote_reply_via_chatsvc(
148 conversation_id,
149 &root_id,
150 quoted,
151 &html,
152 &mentions,
153 extras,
154 )
155 .await?
156 {
157 return self.cache_sent(conversation_id, &sent, &html, extras);
150 }
158 }
151 let sent = self
159 let sent = self
152 .remote
160 .remote
@@ -156,10 +164,10 @@ impl<R: Remote> SyncEngine<R> {
156 &root_id,
164 &root_id,
157 &html,
165 &html,
158 &mentions,
166 &mentions,
159 &extras,
167 extras,
160 )
168 )
161 .await?;
169 .await?;
162 (sent, extras)
170 (sent, extras.clone())
163 }
171 }
164 };
172 };
165 self.cache_sent(conversation_id, &sent, &html, &extras)
173 self.cache_sent(conversation_id, &sent, &html, &extras)
@@ -742,6 +750,58 @@ impl<R: Remote> SyncEngine<R> {
742 self.seed_images(&seeds)
750 self.seed_images(&seeds)
743 }
751 }
744
752
753 async fn quote_reply_via_chatsvc(
754 &self,
755 channel_id: &str,
756 root_id: &str,
757 quoted: &MessageRecord,
758 html: &str,
759 mentions: &[OutgoingMention],
760 extras: &MessageExtras,
761 ) -> Result<Option<(graph::Message, String)>> {
762 if !extras.images.is_empty() || !extras.files.is_empty() {
763 return Ok(None);
764 }
765 let Some(quote) = teams_quote(quoted) else {
766 return Ok(None);
767 };
768 let Some(properties) = quote_reply_properties(&quote, mentions, extras.importance) else {
769 return Ok(None);
770 };
771 self.ensure_display_name().await?;
772 let me = self
773 .me()
774 .ok_or(Error::Unsupported("a quote reply before sign-in"))?;
775 let content = format!("{}{}", quote.html, chatsvc_mention_html(html, mentions));
776 let message_id = self
777 .remote
778 .post_chatsvc_message(
779 &ConversationRef::channel_reply(channel_id, root_id),
780 &content,
781 &me.display_name,
782 &properties,
783 )
784 .await?;
785 let created_at = message_id
786 .parse::<i64>()
787 .ok()
788 .and_then(DateTime::from_timestamp_millis)
789 .unwrap_or_else(Utc::now);
790 let cached_html = format!("{}{html}", quote.html);
791 let sent = serde_json::from_value(serde_json::json!({
792 "id": message_id,
793 "messageType": "message",
794 "createdDateTime": created_at.to_rfc3339(),
795 "replyToId": root_id,
796 "importance": extras.importance,
797 "from": {"user": {"id": me.user_id, "displayName": me.display_name}},
798 "body": {"contentType": "html", "content": cached_html},
799 "mentions": mentions.iter().map(OutgoingMention::to_json).collect::<Vec<_>>(),
800 }))
801 .map_err(|_| Error::Unsupported("a chatsvc reply without a message shape"))?;
802 Ok(Some((sent, cached_html)))
803 }
804
745 fn cache_sent(
805 fn cache_sent(
746 &self,
806 &self,
747 conversation_id: &str,
807 conversation_id: &str,
@@ -804,33 +864,6 @@ fn outgoing(
804 Ok(apply_mentions(html, mentions))
864 Ok(apply_mentions(html, mentions))
805}
865}
806
866
807/// The `messageReference` attachment Graph's chat `replyWithQuote` produces; channels have no such action.
808fn quote_reference(record: &MessageRecord) -> KeptAttachment {
809 let sender = record.sender_id.as_ref().map(|user_id| {
810 serde_json::json!({
811 "application": null,
812 "device": null,
813 "user": {
814 "userIdentityType": "aadUser",
815 "id": user_id,
816 "displayName": record.sender_name,
817 },
818 })
819 });
820 let content = serde_json::json!({
821 "messageId": record.message_id,
822 "messagePreview": preview_text(&record.body_html).unwrap_or_default(),
823 "messageSender": sender,
824 });
825 KeptAttachment {
826 id: record.message_id.clone(),
827 content_type: Some(MESSAGE_REFERENCE.to_owned()),
828 content: Some(content.to_string()),
829 content_url: None,
830 name: None,
831 }
832}
833
834fn missing_attachment_id() -> Error {
867fn missing_attachment_id() -> Error {
835 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
868 graph::Error::Upload("the uploaded file has no attachment id".into()).into()
836}
869}
crates/core/src/lib.rs +1 −0
@@ -61,6 +61,7 @@ mod skin_tone;
61 61 mod spans;
62 62 mod stored;
63 63 mod table;
64 mod teams_quote;
64 65 mod time_zone;
65 66 mod translate_sync;
66 67 mod translation;
@@ -61,6 +61,7 @@ mod skin_tone;
61mod spans;
61mod spans;
62mod stored;
62mod stored;
63mod table;
63mod table;
64mod teams_quote;
64mod time_zone;
65mod time_zone;
65mod translate_sync;
66mod translate_sync;
66mod translation;
67mod translation;
crates/core/src/remote.rs +19 −0
@@ -122,6 +122,13 @@ pub trait Remote {
122 122 mentions: &[OutgoingMention],
123 123 extras: &MessageExtras,
124 124 ) -> Result<Message>;
125 async fn post_chatsvc_message(
126 &self,
127 conversation: &ConversationRef,
128 html: &str,
129 display_name: &str,
130 properties: &serde_json::Value,
131 ) -> Result<String>;
125 132 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
126 133 async fn mark_chat_unread(
127 134 &self,
@@ -723,6 +730,18 @@ impl Remote for Graph {
723 730 .await?)
724 731 }
725 732
733 async fn post_chatsvc_message(
734 &self,
735 conversation: &ConversationRef,
736 html: &str,
737 display_name: &str,
738 properties: &serde_json::Value,
739 ) -> Result<String> {
740 Ok(Messages::new(self.session())
741 .post_message(conversation, html, display_name, properties)
742 .await?)
743 }
744
726 745 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
727 746 Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)
728 747 }
@@ -122,6 +122,13 @@ pub trait Remote {
122 mentions: &[OutgoingMention],
122 mentions: &[OutgoingMention],
123 extras: &MessageExtras,
123 extras: &MessageExtras,
124 ) -> Result<Message>;
124 ) -> Result<Message>;
125 async fn post_chatsvc_message(
126 &self,
127 conversation: &ConversationRef,
128 html: &str,
129 display_name: &str,
130 properties: &serde_json::Value,
131 ) -> Result<String>;
125 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
132 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
126 async fn mark_chat_unread(
133 async fn mark_chat_unread(
127 &self,
134 &self,
@@ -723,6 +730,18 @@ impl Remote for Graph {
723 .await?)
730 .await?)
724 }
731 }
725
732
733 async fn post_chatsvc_message(
734 &self,
735 conversation: &ConversationRef,
736 html: &str,
737 display_name: &str,
738 properties: &serde_json::Value,
739 ) -> Result<String> {
740 Ok(Messages::new(self.session())
741 .post_message(conversation, html, display_name, properties)
742 .await?)
743 }
744
726 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
745 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
727 Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)
746 Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)
728 }
747 }
crates/core/src/teams_quote.rs added +145 −0
@@ -0,0 +1,145 @@
1 use graph::{MentionTarget, OutgoingMention};
2 use serde_json::{Value, json};
3 use store::MessageRecord;
4
5 use crate::markdown::escape_html;
6 use crate::preview::preview_text;
7
8 const REPLY_ITEMTYPE: &str = "http://schema.skype.com/Reply";
9 const MENTION_ITEMTYPE: &str = "http://schema.skype.com/Mention";
10 const ORGID_PREFIX: &str = "8:orgid:";
11
12 #[derive(Debug, Clone, PartialEq)]
13 pub(crate) struct TeamsQuote {
14 pub html: String,
15 pub quoted_message: Value,
16 }
17
18 /// Teams' `createBlockquoteTag`: no quote without sender, name or preview.
19 pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {
20 let sender_mri = user_mri(record.sender_id.as_deref()?);
21 let sender_name = record.sender_name.as_deref().filter(|name| !name.is_empty())?;
22 let preview = preview_text(&record.body_html).filter(|preview| !preview.is_empty())?;
23 let time = record.created_at.timestamp_millis();
24 let html = format!(
25 "<blockquote itemscope=\"\" itemtype=\"{REPLY_ITEMTYPE}\" itemid=\"{}\"><strong itemprop=\"mri\" itemid=\"{}\">{}</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">{}</p></blockquote>",
26 escape_html(&record.message_id),
27 escape_html(&sender_mri),
28 escape_html(sender_name),
29 escape_html(&preview),
30 );
31 let quoted_message = json!({
32 "messageId": record.message_id,
33 "sender": sender_mri,
34 "time": time,
35 });
36 Some(TeamsQuote {
37 html,
38 quoted_message,
39 })
40 }
41
42 pub(crate) fn quote_reply_properties(
43 quote: &TeamsQuote,
44 mentions: &[OutgoingMention],
45 importance: Option<&str>,
46 ) -> Option<Value> {
47 let mut properties = json!({
48 "importance": importance.unwrap_or_default(),
49 "subject": "",
50 "qtdMsgs": Value::Array(vec![quote.quoted_message.clone()]).to_string(),
51 });
52 if !mentions.is_empty() {
53 let entries = mentions
54 .iter()
55 .map(|mention| match &mention.target {
56 MentionTarget::User { user_id } => Some(json!({
57 "@type": MENTION_ITEMTYPE,
58 "itemid": mention.id,
59 "mri": user_mri(user_id),
60 "mentionType": "person",
61 "displayName": mention.text,
62 })),
63 MentionTarget::Channel { .. } | MentionTarget::Team { .. } => None,
64 })
65 .collect::<Option<Vec<_>>>()?;
66 properties["mentions"] = json!(Value::Array(entries).to_string());
67 }
68 Some(properties)
69 }
70
71 pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {
72 let mut converted = html.to_owned();
73 for mention in mentions {
74 converted = converted.replace(
75 &format!("<at id=\"{}\">", mention.id),
76 &format!(
77 "<span itemscope=\"\" itemtype=\"{MENTION_ITEMTYPE}\" itemid=\"{}\">",
78 mention.id
79 ),
80 );
81 }
82 converted.replace("</at>", "</span>")
83 }
84
85 fn user_mri(user_id: &str) -> String {
86 if user_id.starts_with("8:") {
87 user_id.to_owned()
88 } else {
89 format!("{ORGID_PREFIX}{user_id}")
90 }
91 }
92
93 #[cfg(test)]
94 mod tests {
95 use super::*;
96
97 fn mention(id: u32, target: MentionTarget) -> OutgoingMention {
98 OutgoingMention {
99 id,
100 text: "Ada".into(),
101 target,
102 }
103 }
104
105 #[test]
106 fn person_mentions_become_teams_spans_and_a_mentions_property() {
107 let quote = TeamsQuote {
108 html: String::new(),
109 quoted_message: json!({"messageId": "1"}),
110 };
111 let mentions = [mention(
112 0,
113 MentionTarget::User {
114 user_id: "user-ada".into(),
115 },
116 )];
117 let html = chatsvc_mention_html("hi <at id=\"0\">Ada</at>", &mentions);
118 assert_eq!(
119 html,
120 "hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
121 );
122 let properties = quote_reply_properties(&quote, &mentions, Some("high")).unwrap();
123 assert_eq!(properties["importance"], "high");
124 assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
125 let entries: Value =
126 serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();
127 assert_eq!(entries[0]["mri"], "8:orgid:user-ada");
128 assert_eq!(entries[0]["mentionType"], "person");
129 }
130
131 #[test]
132 fn a_channel_mention_has_no_chatsvc_shape() {
133 let quote = TeamsQuote {
134 html: String::new(),
135 quoted_message: Value::Null,
136 };
137 let mentions = [mention(
138 0,
139 MentionTarget::Channel {
140 channel_id: "19:c".into(),
141 },
142 )];
143 assert!(quote_reply_properties(&quote, &mentions, None).is_none());
144 }
145 }
@@ -0,0 +1,145 @@
1use graph::{MentionTarget, OutgoingMention};
2use serde_json::{Value, json};
3use store::MessageRecord;
4
5use crate::markdown::escape_html;
6use crate::preview::preview_text;
7
8const REPLY_ITEMTYPE: &str = "http://schema.skype.com/Reply";
9const MENTION_ITEMTYPE: &str = "http://schema.skype.com/Mention";
10const ORGID_PREFIX: &str = "8:orgid:";
11
12#[derive(Debug, Clone, PartialEq)]
13pub(crate) struct TeamsQuote {
14 pub html: String,
15 pub quoted_message: Value,
16}
17
18/// Teams' `createBlockquoteTag`: no quote without sender, name or preview.
19pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {
20 let sender_mri = user_mri(record.sender_id.as_deref()?);
21 let sender_name = record.sender_name.as_deref().filter(|name| !name.is_empty())?;
22 let preview = preview_text(&record.body_html).filter(|preview| !preview.is_empty())?;
23 let time = record.created_at.timestamp_millis();
24 let html = format!(
25 "<blockquote itemscope=\"\" itemtype=\"{REPLY_ITEMTYPE}\" itemid=\"{}\"><strong itemprop=\"mri\" itemid=\"{}\">{}</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">{}</p></blockquote>",
26 escape_html(&record.message_id),
27 escape_html(&sender_mri),
28 escape_html(sender_name),
29 escape_html(&preview),
30 );
31 let quoted_message = json!({
32 "messageId": record.message_id,
33 "sender": sender_mri,
34 "time": time,
35 });
36 Some(TeamsQuote {
37 html,
38 quoted_message,
39 })
40}
41
42pub(crate) fn quote_reply_properties(
43 quote: &TeamsQuote,
44 mentions: &[OutgoingMention],
45 importance: Option<&str>,
46) -> Option<Value> {
47 let mut properties = json!({
48 "importance": importance.unwrap_or_default(),
49 "subject": "",
50 "qtdMsgs": Value::Array(vec![quote.quoted_message.clone()]).to_string(),
51 });
52 if !mentions.is_empty() {
53 let entries = mentions
54 .iter()
55 .map(|mention| match &mention.target {
56 MentionTarget::User { user_id } => Some(json!({
57 "@type": MENTION_ITEMTYPE,
58 "itemid": mention.id,
59 "mri": user_mri(user_id),
60 "mentionType": "person",
61 "displayName": mention.text,
62 })),
63 MentionTarget::Channel { .. } | MentionTarget::Team { .. } => None,
64 })
65 .collect::<Option<Vec<_>>>()?;
66 properties["mentions"] = json!(Value::Array(entries).to_string());
67 }
68 Some(properties)
69}
70
71pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {
72 let mut converted = html.to_owned();
73 for mention in mentions {
74 converted = converted.replace(
75 &format!("<at id=\"{}\">", mention.id),
76 &format!(
77 "<span itemscope=\"\" itemtype=\"{MENTION_ITEMTYPE}\" itemid=\"{}\">",
78 mention.id
79 ),
80 );
81 }
82 converted.replace("</at>", "</span>")
83}
84
85fn user_mri(user_id: &str) -> String {
86 if user_id.starts_with("8:") {
87 user_id.to_owned()
88 } else {
89 format!("{ORGID_PREFIX}{user_id}")
90 }
91}
92
93#[cfg(test)]
94mod tests {
95 use super::*;
96
97 fn mention(id: u32, target: MentionTarget) -> OutgoingMention {
98 OutgoingMention {
99 id,
100 text: "Ada".into(),
101 target,
102 }
103 }
104
105 #[test]
106 fn person_mentions_become_teams_spans_and_a_mentions_property() {
107 let quote = TeamsQuote {
108 html: String::new(),
109 quoted_message: json!({"messageId": "1"}),
110 };
111 let mentions = [mention(
112 0,
113 MentionTarget::User {
114 user_id: "user-ada".into(),
115 },
116 )];
117 let html = chatsvc_mention_html("hi <at id=\"0\">Ada</at>", &mentions);
118 assert_eq!(
119 html,
120 "hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
121 );
122 let properties = quote_reply_properties(&quote, &mentions, Some("high")).unwrap();
123 assert_eq!(properties["importance"], "high");
124 assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
125 let entries: Value =
126 serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();
127 assert_eq!(entries[0]["mri"], "8:orgid:user-ada");
128 assert_eq!(entries[0]["mentionType"], "person");
129 }
130
131 #[test]
132 fn a_channel_mention_has_no_chatsvc_shape() {
133 let quote = TeamsQuote {
134 html: String::new(),
135 quoted_message: Value::Null,
136 };
137 let mentions = [mention(
138 0,
139 MentionTarget::Channel {
140 channel_id: "19:c".into(),
141 },
142 )];
143 assert!(quote_reply_properties(&quote, &mentions, None).is_none());
144 }
145}
crates/core/tests/engine.rs +45 −11
@@ -108,6 +108,7 @@ struct Fake {
108 108 external_requests: Mutex<Vec<String>>,
109 109 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
110 110 extras_sent: Mutex<Vec<MessageExtras>>,
111 chatsvc_posts: Mutex<Vec<(String, String, String, serde_json::Value)>>,
111 112 send_answer_body: Mutex<Option<String>>,
112 113 folder_requests: Mutex<usize>,
113 114 directory_users: Mutex<Vec<User>>,
@@ -524,6 +525,24 @@ impl Remote for Handle {
524 525 Ok(message(9002, 502, html))
525 526 }
526 527
528 async fn post_chatsvc_message(
529 &self,
530 conversation: &chatsvc::ConversationRef,
531 html: &str,
532 display_name: &str,
533 properties: &serde_json::Value,
534 ) -> Result<String> {
535 let conversation_id = conversation.conversation_id();
536 self.record(format!("chatsvc post {conversation_id}"));
537 self.chatsvc_posts.lock().unwrap().push((
538 conversation_id,
539 html.to_owned(),
540 display_name.to_owned(),
541 properties.clone(),
542 ));
543 Ok("1727203440000".to_owned())
544 }
545
527 546 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
528 547 self.record(format!("mark_read {chat_id} {user_id} {tenant_id}"));
529 548 Ok(())
@@ -3834,7 +3853,11 @@ async fn chat_reply_quotes_and_channel_reply_uses_the_thread_root() {
3834 3853 let channel = channel_engine(&channel_fake).await;
3835 3854 channel.fetch_newer(CHANNEL).await.unwrap();
3836 3855 channel.reply_to(CHANNEL, "m0030", "hi").await.unwrap();
3837 assert!(channel_fake.calls().contains(&"reply to m0030".to_owned()));
3856 assert!(
3857 channel_fake
3858 .calls()
3859 .contains(&format!("chatsvc post {CHANNEL};messageid=m0030"))
3860 );
3838 3861 assert!(engine.reply_to("unknown", "m1", "x").await.is_err());
3839 3862 }
3840 3863
@@ -5416,20 +5439,31 @@ async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {
5416 5439 }
5417 5440
5418 5441 #[tokio::test]
5419 async fn a_quoted_channel_reply_carries_the_quote_as_a_message_reference() {
5442 async fn a_quoted_channel_reply_is_written_through_chatsvc_in_the_teams_quote_shape() {
5420 5443 let fake = Arc::new(Fake::default());
5421 5444 let engine = channel_engine(&fake).await;
5422 5445 engine.fetch_newer(CHANNEL).await.unwrap();
5423 engine
5446 let sent = engine
5424 5447 .reply_to_with_mentions(CHANNEL, "m0030", "answer", &[])
5425 5448 .await
5426 5449 .unwrap();
5427 let extras = fake.extras_sent.lock().unwrap().last().cloned().unwrap();
5428 let quote = &extras.kept[0];
5429 assert_eq!(quote.id, "m0030");
5430 assert_eq!(quote.content_type.as_deref(), Some("messageReference"));
5431 let content: serde_json::Value =
5432 serde_json::from_str(quote.content.as_deref().unwrap()).unwrap();
5433 assert_eq!(content["messageId"], "m0030");
5434 assert_eq!(content["messageSender"]["user"]["userIdentityType"], "aadUser");
5450 assert!(!fake.calls().contains(&"reply to m0030".to_owned()));
5451 let (conversation_id, html, display_name, properties) =
5452 fake.chatsvc_posts.lock().unwrap().last().cloned().unwrap();
5453 assert_eq!(conversation_id, format!("{CHANNEL};messageid=m0030"));
5454 assert_eq!(display_name, "Me Myself");
5455 let time = (base() + Duration::minutes(30)).timestamp_millis();
5456 let quote = format!(
5457 "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m0030\"><strong itemprop=\"mri\" itemid=\"8:orgid:user-ada\">Ada Example</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">root</p></blockquote>"
5458 );
5459 assert_eq!(html, format!("{quote}answer"));
5460 let quoted: serde_json::Value =
5461 serde_json::from_str(properties["qtdMsgs"].as_str().unwrap()).unwrap();
5462 assert_eq!(
5463 quoted,
5464 json!([{"messageId": "m0030", "sender": "8:orgid:user-ada", "time": time}])
5465 );
5466 assert_eq!(sent.message_id, "1727203440000");
5467 assert_eq!(sent.reply_to_id.as_deref(), Some("m0030"));
5468 assert!(sent.body_html.starts_with(&quote));
5435 5469 }
@@ -108,6 +108,7 @@ struct Fake {
108 external_requests: Mutex<Vec<String>>,
108 external_requests: Mutex<Vec<String>>,
109 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
109 mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>,
110 extras_sent: Mutex<Vec<MessageExtras>>,
110 extras_sent: Mutex<Vec<MessageExtras>>,
111 chatsvc_posts: Mutex<Vec<(String, String, String, serde_json::Value)>>,
111 send_answer_body: Mutex<Option<String>>,
112 send_answer_body: Mutex<Option<String>>,
112 folder_requests: Mutex<usize>,
113 folder_requests: Mutex<usize>,
113 directory_users: Mutex<Vec<User>>,
114 directory_users: Mutex<Vec<User>>,
@@ -524,6 +525,24 @@ impl Remote for Handle {
524 Ok(message(9002, 502, html))
525 Ok(message(9002, 502, html))
525 }
526 }
526
527
528 async fn post_chatsvc_message(
529 &self,
530 conversation: &chatsvc::ConversationRef,
531 html: &str,
532 display_name: &str,
533 properties: &serde_json::Value,
534 ) -> Result<String> {
535 let conversation_id = conversation.conversation_id();
536 self.record(format!("chatsvc post {conversation_id}"));
537 self.chatsvc_posts.lock().unwrap().push((
538 conversation_id,
539 html.to_owned(),
540 display_name.to_owned(),
541 properties.clone(),
542 ));
543 Ok("1727203440000".to_owned())
544 }
545
527 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
546 async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
528 self.record(format!("mark_read {chat_id} {user_id} {tenant_id}"));
547 self.record(format!("mark_read {chat_id} {user_id} {tenant_id}"));
529 Ok(())
548 Ok(())
@@ -3834,7 +3853,11 @@ async fn chat_reply_quotes_and_channel_reply_uses_the_thread_root() {
3834 let channel = channel_engine(&channel_fake).await;
3853 let channel = channel_engine(&channel_fake).await;
3835 channel.fetch_newer(CHANNEL).await.unwrap();
3854 channel.fetch_newer(CHANNEL).await.unwrap();
3836 channel.reply_to(CHANNEL, "m0030", "hi").await.unwrap();
3855 channel.reply_to(CHANNEL, "m0030", "hi").await.unwrap();
3837 assert!(channel_fake.calls().contains(&"reply to m0030".to_owned()));
3856 assert!(
3857 channel_fake
3858 .calls()
3859 .contains(&format!("chatsvc post {CHANNEL};messageid=m0030"))
3860 );
3838 assert!(engine.reply_to("unknown", "m1", "x").await.is_err());
3861 assert!(engine.reply_to("unknown", "m1", "x").await.is_err());
3839}
3862}
3840
3863
@@ -5416,20 +5439,31 @@ async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() {
5416}
5439}
5417
5440
5418#[tokio::test]
5441#[tokio::test]
5419async fn a_quoted_channel_reply_carries_the_quote_as_a_message_reference() {
5442async fn a_quoted_channel_reply_is_written_through_chatsvc_in_the_teams_quote_shape() {
5420 let fake = Arc::new(Fake::default());
5443 let fake = Arc::new(Fake::default());
5421 let engine = channel_engine(&fake).await;
5444 let engine = channel_engine(&fake).await;
5422 engine.fetch_newer(CHANNEL).await.unwrap();
5445 engine.fetch_newer(CHANNEL).await.unwrap();
5423 engine
5446 let sent = engine
5424 .reply_to_with_mentions(CHANNEL, "m0030", "answer", &[])
5447 .reply_to_with_mentions(CHANNEL, "m0030", "answer", &[])
5425 .await
5448 .await
5426 .unwrap();
5449 .unwrap();
5427 let extras = fake.extras_sent.lock().unwrap().last().cloned().unwrap();
5450 assert!(!fake.calls().contains(&"reply to m0030".to_owned()));
5428 let quote = &extras.kept[0];
5451 let (conversation_id, html, display_name, properties) =
5429 assert_eq!(quote.id, "m0030");
5452 fake.chatsvc_posts.lock().unwrap().last().cloned().unwrap();
5430 assert_eq!(quote.content_type.as_deref(), Some("messageReference"));
5453 assert_eq!(conversation_id, format!("{CHANNEL};messageid=m0030"));
5431 let content: serde_json::Value =
5454 assert_eq!(display_name, "Me Myself");
5432 serde_json::from_str(quote.content.as_deref().unwrap()).unwrap();
5455 let time = (base() + Duration::minutes(30)).timestamp_millis();
5433 assert_eq!(content["messageId"], "m0030");
5456 let quote = format!(
5434 assert_eq!(content["messageSender"]["user"]["userIdentityType"], "aadUser");
5457 "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m0030\"><strong itemprop=\"mri\" itemid=\"8:orgid:user-ada\">Ada Example</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">root</p></blockquote>"
5458 );
5459 assert_eq!(html, format!("{quote}answer"));
5460 let quoted: serde_json::Value =
5461 serde_json::from_str(properties["qtdMsgs"].as_str().unwrap()).unwrap();
5462 assert_eq!(
5463 quoted,
5464 json!([{"messageId": "m0030", "sender": "8:orgid:user-ada", "time": time}])
5465 );
5466 assert_eq!(sent.message_id, "1727203440000");
5467 assert_eq!(sent.reply_to_id.as_deref(), Some("m0030"));
5468 assert!(sent.body_html.starts_with(&quote));
5435}
5469}