BlueGit

ict rusty-teams

Files

rusty-teams / crates / core / src / teams_quote.rs

teams_quote.rs

teams_quote.rs 7.0 KiB Download Raw
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:";
11const BOT_PREFIX: &str = "28:";
12const FORMAT_VARIANT: &str = "TEAMS";
13
14#[derive(Debug, Clone, PartialEq)]
15pub(crate) struct TeamsQuote {
16 pub html: String,
17 pub quoted_message: Value,
18}
19
20/// Teams' `createBlockquoteTag`: no quote without sender, name or preview.
21pub(crate) fn teams_quote(record: &MessageRecord) -> Option<TeamsQuote> {
22 let sender_mri = sender_mri(record)?;
23 let sender_name = record
24 .sender_name
25 .as_deref()
26 .filter(|name| !name.is_empty())?;
27 let preview = preview_text(&record.body_html).filter(|preview| !preview.is_empty())?;
28 let time = record.created_at.timestamp_millis();
29 let html = format!(
30 "<blockquote itemscope=\"\" itemtype=\"{REPLY_ITEMTYPE}\" itemid=\"{}\"><strong itemprop=\"mri\" itemid=\"{}\">{}</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">{}</p></blockquote>",
31 escape_html(&record.message_id),
32 escape_html(&sender_mri),
33 escape_html(sender_name),
34 escape_html(&preview),
35 );
36 let quoted_message = json!({
37 "messageId": record.message_id,
38 "sender": sender_mri,
39 "time": time,
40 });
41 Some(TeamsQuote {
42 html,
43 quoted_message,
44 })
45}
46
47/// The `properties` Teams' `sendMessageInConv` writes; `None` when a mention has no chatsvc shape here.
48pub(crate) fn message_properties(
49 quote: Option<&TeamsQuote>,
50 mentions: &[OutgoingMention],
51 importance: Option<&str>,
52 files: &Value,
53) -> Option<Value> {
54 let mention_entries = mention_entries(mentions)?;
55 let quoted: Vec<Value> = quote
56 .map(|quote| quote.quoted_message.clone())
57 .into_iter()
58 .collect();
59 Some(json!({
60 "importance": importance.unwrap_or_default(),
61 "links": "[]",
62 "mentions": Value::Array(mention_entries).to_string(),
63 "onbehalfof": null,
64 "files": files.to_string(),
65 "qtdMsgs": Value::Array(quoted).to_string(),
66 "formatVariant": FORMAT_VARIANT,
67 }))
68}
69
70/// The chatsvc `mentions` entries; `None` when a mention is not a person.
71pub(crate) fn mention_entries(mentions: &[OutgoingMention]) -> Option<Vec<Value>> {
72 mentions.iter().map(mention_entry).collect()
73}
74
75fn mention_entry(mention: &OutgoingMention) -> Option<Value> {
76 let MentionTarget::User { user_id } = &mention.target else {
77 return None;
78 };
79 Some(json!({
80 "@type": MENTION_ITEMTYPE,
81 "itemid": mention.id.to_string(),
82 "mri": user_mri(user_id),
83 "mentionType": "person",
84 "displayName": mention.text,
85 }))
86}
87
88pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {
89 let mut converted = html.to_owned();
90 for mention in mentions {
91 converted = converted.replace(
92 &format!("<at id=\"{}\">", mention.id),
93 &format!(
94 "<span itemscope=\"\" itemtype=\"{MENTION_ITEMTYPE}\" itemid=\"{}\">",
95 mention.id
96 ),
97 );
98 }
99 converted.replace("</at>", "</span>")
100}
101
102fn sender_mri(record: &MessageRecord) -> Option<String> {
103 match (&record.sender_id, &record.sender_application_id) {
104 (Some(user_id), _) => Some(user_mri(user_id)),
105 (None, Some(application_id)) if application_id.contains(':') => {
106 Some(application_id.clone())
107 }
108 (None, Some(application_id)) => Some(format!("{BOT_PREFIX}{application_id}")),
109 (None, None) => None,
110 }
111}
112
113fn user_mri(user_id: &str) -> String {
114 if user_id.contains(':') {
115 user_id.to_owned()
116 } else {
117 format!("{ORGID_PREFIX}{user_id}")
118 }
119}
120
121#[cfg(test)]
122mod tests {
123 use super::*;
124
125 fn mention(id: u32, target: MentionTarget) -> OutgoingMention {
126 OutgoingMention {
127 id,
128 text: "Ada".into(),
129 target,
130 }
131 }
132
133 fn quote() -> TeamsQuote {
134 TeamsQuote {
135 html: String::new(),
136 quoted_message: json!({"messageId": "1"}),
137 }
138 }
139
140 #[test]
141 fn a_quote_reply_gets_the_teams_property_set() {
142 let properties = message_properties(Some(&quote()), &[], None, &json!([])).unwrap();
143 assert_eq!(
144 properties,
145 json!({
146 "importance": "",
147 "links": "[]",
148 "mentions": "[]",
149 "onbehalfof": null,
150 "files": "[]",
151 "qtdMsgs": "[{\"messageId\":\"1\"}]",
152 "formatVariant": "TEAMS",
153 })
154 );
155 }
156
157 #[test]
158 fn person_mentions_become_teams_spans_and_a_mentions_property() {
159 let mentions = [mention(
160 0,
161 MentionTarget::User {
162 user_id: "user-ada".into(),
163 },
164 )];
165 let html = chatsvc_mention_html("hi <at id=\"0\">Ada</at>", &mentions);
166 assert_eq!(
167 html,
168 "hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
169 );
170 let properties =
171 message_properties(Some(&quote()), &mentions, Some("high"), &json!([])).unwrap();
172 assert_eq!(properties["importance"], "high");
173 assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
174 let entries: Value =
175 serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();
176 assert_eq!(
177 entries,
178 json!([{
179 "@type": "http://schema.skype.com/Mention",
180 "itemid": "0",
181 "mri": "8:orgid:user-ada",
182 "mentionType": "person",
183 "displayName": "Ada",
184 }])
185 );
186 }
187
188 #[test]
189 fn group_mentions_have_no_chatsvc_shape() {
190 for target in [
191 MentionTarget::Channel {
192 channel_id: "19:c@thread.tacv2".into(),
193 },
194 MentionTarget::Team {
195 team_id: "team-1".into(),
196 },
197 MentionTarget::Everyone {
198 chat_id: "19:g@thread.v2".into(),
199 },
200 MentionTarget::Tag {
201 tag_id: "tag-1".into(),
202 },
203 ] {
204 let mentions = [mention(0, target)];
205 assert!(message_properties(Some(&quote()), &mentions, None, &json!([])).is_none());
206 }
207 }
208
209 #[test]
210 fn a_bot_sender_is_quoted_with_its_28_mri() {
211 let record = MessageRecord {
212 message_id: "5".into(),
213 sender_name: Some("Echo".into()),
214 sender_application_id: Some("app-1".into()),
215 body_html: "<p>pong</p>".into(),
216 ..MessageRecord::default()
217 };
218 let quote = teams_quote(&record).unwrap();
219 assert_eq!(quote.quoted_message["sender"], "28:app-1");
220 assert!(quote.html.contains("itemid=\"28:app-1\">Echo</strong>"));
221 }
222}