BlueGit

ict rusty-teams

Files

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

teams_quote.rs

0ff9db96 History
teams_quote.rs 7.5 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 (mri, mention_type) = match &mention.target {
77 MentionTarget::User { user_id } => (user_mri(user_id), "person"),
78 MentionTarget::Everyone { chat_id } => (chat_id.clone(), "everyone"),
79 _ => return None,
80 };
81 Some(json!({
82 "@type": MENTION_ITEMTYPE,
83 "itemid": mention.id.to_string(),
84 "mri": mri,
85 "mentionType": mention_type,
86 "displayName": mention.text,
87 }))
88}
89
90pub(crate) fn chatsvc_mention_html(html: &str, mentions: &[OutgoingMention]) -> String {
91 let mut converted = html.to_owned();
92 for mention in mentions {
93 converted = converted.replace(
94 &format!("<at id=\"{}\">", mention.id),
95 &format!(
96 "<span itemscope=\"\" itemtype=\"{MENTION_ITEMTYPE}\" itemid=\"{}\">",
97 mention.id
98 ),
99 );
100 }
101 converted.replace("</at>", "</span>")
102}
103
104fn sender_mri(record: &MessageRecord) -> Option<String> {
105 match (&record.sender_id, &record.sender_application_id) {
106 (Some(user_id), _) => Some(user_mri(user_id)),
107 (None, Some(application_id)) if application_id.contains(':') => {
108 Some(application_id.clone())
109 }
110 (None, Some(application_id)) => Some(format!("{BOT_PREFIX}{application_id}")),
111 (None, None) => None,
112 }
113}
114
115fn user_mri(user_id: &str) -> String {
116 if user_id.contains(':') {
117 user_id.to_owned()
118 } else {
119 format!("{ORGID_PREFIX}{user_id}")
120 }
121}
122
123#[cfg(test)]
124mod tests {
125 use super::*;
126
127 fn mention(id: u32, target: MentionTarget) -> OutgoingMention {
128 OutgoingMention {
129 id,
130 text: "Ada".into(),
131 target,
132 }
133 }
134
135 fn quote() -> TeamsQuote {
136 TeamsQuote {
137 html: String::new(),
138 quoted_message: json!({"messageId": "1"}),
139 }
140 }
141
142 #[test]
143 fn a_quote_reply_gets_the_teams_property_set() {
144 let properties = message_properties(Some(&quote()), &[], None, &json!([])).unwrap();
145 assert_eq!(
146 properties,
147 json!({
148 "importance": "",
149 "links": "[]",
150 "mentions": "[]",
151 "onbehalfof": null,
152 "files": "[]",
153 "qtdMsgs": "[{\"messageId\":\"1\"}]",
154 "formatVariant": "TEAMS",
155 })
156 );
157 }
158
159 #[test]
160 fn person_mentions_become_teams_spans_and_a_mentions_property() {
161 let mentions = [mention(
162 0,
163 MentionTarget::User {
164 user_id: "user-ada".into(),
165 },
166 )];
167 let html = chatsvc_mention_html("hi <at id=\"0\">Ada</at>", &mentions);
168 assert_eq!(
169 html,
170 "hi <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada</span>"
171 );
172 let properties =
173 message_properties(Some(&quote()), &mentions, Some("high"), &json!([])).unwrap();
174 assert_eq!(properties["importance"], "high");
175 assert_eq!(properties["qtdMsgs"], "[{\"messageId\":\"1\"}]");
176 let entries: Value =
177 serde_json::from_str(properties["mentions"].as_str().unwrap()).unwrap();
178 assert_eq!(
179 entries,
180 json!([{
181 "@type": "http://schema.skype.com/Mention",
182 "itemid": "0",
183 "mri": "8:orgid:user-ada",
184 "mentionType": "person",
185 "displayName": "Ada",
186 }])
187 );
188 }
189
190 #[test]
191 fn an_everyone_mention_names_the_chat_itself() {
192 let everyone = mention(
193 0,
194 MentionTarget::Everyone {
195 chat_id: "19:g@thread.v2".into(),
196 },
197 );
198 let entries = mention_entries(&[everyone]).unwrap();
199 assert_eq!(entries[0]["mri"], "19:g@thread.v2");
200 assert_eq!(entries[0]["mentionType"], "everyone");
201 }
202
203 #[test]
204 fn group_mentions_have_no_chatsvc_shape() {
205 for target in [
206 MentionTarget::Channel {
207 channel_id: "19:c@thread.tacv2".into(),
208 },
209 MentionTarget::Team {
210 team_id: "team-1".into(),
211 },
212 MentionTarget::Tag {
213 tag_id: "tag-1".into(),
214 },
215 ] {
216 let mentions = [mention(0, target)];
217 assert!(message_properties(Some(&quote()), &mentions, None, &json!([])).is_none());
218 }
219 }
220
221 #[test]
222 fn a_bot_sender_is_quoted_with_its_28_mri() {
223 let record = MessageRecord {
224 message_id: "5".into(),
225 sender_name: Some("Echo".into()),
226 sender_application_id: Some("app-1".into()),
227 body_html: "<p>pong</p>".into(),
228 ..MessageRecord::default()
229 };
230 let quote = teams_quote(&record).unwrap();
231 assert_eq!(quote.quoted_message["sender"], "28:app-1");
232 assert!(quote.html.contains("itemid=\"28:app-1\">Echo</strong>"));
233 }
234}