BlueGit

ict rusty-teams

Files

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

legacy_card.rs

legacy_card.rs 9.5 KiB Download Raw
1//! Cards without an Adaptive Card `body`: Office 365 connector `MessageCard`s (incoming
2//! webhooks, legacy workflows) and hero or thumbnail cards. Teams draws them with title,
3//! sections, facts and buttons; they are rewritten into an Adaptive Card here.
4
5use std::sync::LazyLock;
6
7use regex::Regex;
8use serde_json::{Value, json};
9
10/// Set on a converted `TextBlock` or fact whose text is HTML, which connector cards allow
11/// besides markdown. The card parser then reads it as HTML instead of escaping the tags.
12pub(crate) const HTML_TEXT: &str = "x-legacyHtml";
13
14static HTML_TAG: LazyLock<Regex> =
15 LazyLock::new(|| Regex::new(r"</?[a-zA-Z][a-zA-Z0-9]*(\s[^<>]*)?/?>").unwrap());
16
17const OPEN_URI: &str = "OpenUri";
18const VIEW_ACTION: &str = "ViewAction";
19const OPEN_URL_BUTTON: &str = "openUrl";
20const DEFAULT_OS: &str = "default";
21
22/// The Adaptive Card that shows `root`, or `None` when it is no legacy card.
23pub(crate) fn as_adaptive_card(root: &Value) -> Option<Value> {
24 let object = root.as_object()?;
25 if object.contains_key("body") || text(root, "type") == Some("AdaptiveCard") {
26 return None;
27 }
28 let connector = text(root, "@type") == Some("MessageCard")
29 || ["sections", "potentialAction"]
30 .iter()
31 .any(|key| root.get(key).is_some_and(Value::is_array));
32 let hero = ["buttons", "images"]
33 .iter()
34 .any(|key| root.get(key).is_some_and(Value::is_array));
35 if !connector && !hero {
36 return None;
37 }
38 let mut body = Vec::new();
39 if let Some(title) = text(root, "title") {
40 body.push(json!({"type": "TextBlock", "text": title, "weight": "Bolder", "size": "Medium", "wrap": true}));
41 }
42 if let Some(subtitle) = text(root, "subtitle") {
43 body.push(json!({"type": "TextBlock", "text": subtitle, "isSubtle": true, "wrap": true}));
44 }
45 if let Some(text) = text(root, "text") {
46 body.push(json!({"type": "TextBlock", "text": text, "wrap": true}));
47 }
48 for image in root
49 .get("images")
50 .and_then(Value::as_array)
51 .into_iter()
52 .flatten()
53 {
54 if let Some(url) = text(image, "url").or_else(|| text(image, "image")) {
55 body.push(json!({"type": "Image", "url": url}));
56 }
57 }
58 for section in root
59 .get("sections")
60 .and_then(Value::as_array)
61 .into_iter()
62 .flatten()
63 {
64 body.extend(section_items(section));
65 }
66 if body.is_empty() {
67 if let Some(summary) = text(root, "summary") {
68 body.push(json!({"type": "TextBlock", "text": summary, "wrap": true}));
69 }
70 }
71 let actions: Vec<Value> = root
72 .get("potentialAction")
73 .or_else(|| root.get("buttons"))
74 .and_then(Value::as_array)
75 .into_iter()
76 .flatten()
77 .filter_map(open_url_action)
78 .collect();
79 if body.is_empty() && actions.is_empty() {
80 return None;
81 }
82 let mut card =
83 json!({"type": "AdaptiveCard", "version": "1.4", "body": body, "actions": actions});
84 mark_html_text(&mut card);
85 Some(card)
86}
87
88fn mark_html_text(value: &mut Value) {
89 match value {
90 Value::Array(items) => items.iter_mut().for_each(mark_html_text),
91 Value::Object(object) => {
92 let html_in = |key: &str| {
93 object
94 .get(key)
95 .and_then(Value::as_str)
96 .is_some_and(|text| HTML_TAG.is_match(text))
97 };
98 if html_in("text") || html_in("value") {
99 object.insert(HTML_TEXT.to_owned(), Value::Bool(true));
100 }
101 object.values_mut().for_each(mark_html_text);
102 }
103 _ => {}
104 }
105}
106
107fn section_items(section: &Value) -> Vec<Value> {
108 let mut items = Vec::new();
109 let separator = section
110 .get("startGroup")
111 .and_then(Value::as_bool)
112 .unwrap_or(false);
113 if let Some(title) = text(section, "title") {
114 items.push(json!({"type": "TextBlock", "text": title, "weight": "Bolder", "wrap": true}));
115 }
116 let mut activity = Vec::new();
117 if let Some(title) = text(section, "activityTitle") {
118 activity
119 .push(json!({"type": "TextBlock", "text": title, "weight": "Bolder", "wrap": true}));
120 }
121 if let Some(subtitle) = text(section, "activitySubtitle") {
122 activity.push(json!({"type": "TextBlock", "text": subtitle, "isSubtle": true, "spacing": "None", "wrap": true}));
123 }
124 if let Some(body) = text(section, "activityText") {
125 activity.push(json!({"type": "TextBlock", "text": body, "wrap": true}));
126 }
127 match (text(section, "activityImage"), activity.is_empty()) {
128 (Some(image), false) => items.push(json!({
129 "type": "ColumnSet",
130 "columns": [
131 {"type": "Column", "width": "auto", "items": [{"type": "Image", "url": image, "size": "Small", "style": "Person"}]},
132 {"type": "Column", "width": "stretch", "items": activity},
133 ],
134 })),
135 _ => items.extend(activity),
136 }
137 if let Some(body) = text(section, "text") {
138 items.push(json!({"type": "TextBlock", "text": body, "wrap": true}));
139 }
140 let facts: Vec<Value> = section
141 .get("facts")
142 .and_then(Value::as_array)
143 .into_iter()
144 .flatten()
145 .filter_map(|fact| {
146 Some(json!({"title": text(fact, "name").unwrap_or_default(), "value": text(fact, "value")?}))
147 })
148 .collect();
149 if !facts.is_empty() {
150 items.push(json!({"type": "FactSet", "facts": facts}));
151 }
152 for image in section
153 .get("images")
154 .and_then(Value::as_array)
155 .into_iter()
156 .flatten()
157 {
158 if let Some(url) = text(image, "image").or_else(|| text(image, "url")) {
159 items.push(json!({"type": "Image", "url": url}));
160 }
161 }
162 if separator && let Some(first) = items.first_mut() {
163 first["separator"] = json!(true);
164 }
165 items
166}
167
168fn open_url_action(action: &Value) -> Option<Value> {
169 let title = text(action, "name").or_else(|| text(action, "title"))?;
170 let kind = text(action, "@type").or_else(|| text(action, "type"))?;
171 let url = match kind {
172 OPEN_URI => {
173 let targets = action.get("targets")?.as_array()?;
174 targets
175 .iter()
176 .find(|target| text(target, "os") == Some(DEFAULT_OS))
177 .or_else(|| targets.first())
178 .and_then(|target| text(target, "uri"))?
179 }
180 VIEW_ACTION => action.get("target")?.as_array()?.first()?.as_str()?,
181 OPEN_URL_BUTTON => text(action, "value")?,
182 _ => return None,
183 };
184 Some(json!({"type": "Action.OpenUrl", "title": title, "url": url}))
185}
186
187fn text<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
188 value
189 .get(key)?
190 .as_str()
191 .map(str::trim)
192 .filter(|text| !text.is_empty())
193}
194
195#[cfg(test)]
196mod tests {
197 use crate::adaptive_card::AdaptiveCard;
198
199 const WEBHOOK: &str = r#"{
200 "@type": "MessageCard",
201 "summary": "Build failed",
202 "title": "Pipeline main",
203 "sections": [{
204 "activityTitle": "Build 128 failed",
205 "activitySubtitle": "on agent 3",
206 "facts": [{"name": "Branch", "value": "main"}, {"name": "Duration", "value": "4 min"}],
207 "text": "See the log for details."
208 }],
209 "potentialAction": [
210 {"@type": "OpenUri", "name": "Open log", "targets": [{"os": "default", "uri": "https://ci.example/128"}]},
211 {"@type": "HttpPOST", "name": "Retry", "target": "https://ci.example/retry"}
212 ]
213 }"#;
214
215 #[test]
216 fn a_connector_message_card_shows_title_sections_facts_and_links() {
217 let card = AdaptiveCard::parse(WEBHOOK).expect("connector card is shown");
218 let text = card.plain_text().unwrap_or_default();
219 for expected in [
220 "Pipeline main",
221 "Build 128 failed",
222 "on agent 3",
223 "See the log",
224 "Branch",
225 "main",
226 ] {
227 assert!(text.contains(expected), "{expected} missing in {text:?}");
228 }
229 let titles: Vec<_> = card
230 .actions
231 .iter()
232 .map(|action| action.title.as_str())
233 .collect();
234 assert_eq!(titles, ["Open log"]);
235 }
236
237 #[test]
238 fn a_hero_card_shows_its_text_and_buttons() {
239 let hero = r#"{"title": "Release 1.2", "text": "Ready", "buttons": [{"type": "openUrl", "title": "Notes", "value": "https://example.com/notes"}]}"#;
240 let card = AdaptiveCard::parse(hero).expect("hero card is shown");
241 assert!(
242 card.plain_text()
243 .unwrap_or_default()
244 .contains("Release 1.2")
245 );
246 assert_eq!(card.actions.len(), 1);
247 }
248
249 #[test]
250 fn html_in_connector_text_and_facts_is_read_as_html() {
251 let html_card = r#"{"@type": "MessageCard", "text": "Deploy <b>done</b><br>see <a href=\"https://example.com/run\">run</a>", "sections": [{"facts": [{"name": "Status", "value": "<i>green</i>"}]}]}"#;
252 let text = AdaptiveCard::parse(html_card)
253 .expect("connector card is shown")
254 .plain_text()
255 .unwrap_or_default();
256 assert!(text.contains("done") && text.contains("green"));
257 assert!(!text.contains('<'), "tags leaked: {text}");
258 }
259
260 #[test]
261 fn an_object_without_card_shape_stays_no_card() {
262 assert!(AdaptiveCard::parse("{}").is_none());
263 assert!(AdaptiveCard::parse(r#"{"title": "t", "value": "v"}"#).is_none());
264 }
265}