BlueGit

ict rusty-teams

Files

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

legacy_card.rs

legacy_card.rs 7.4 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 serde_json::{Value, json};
6
7const OPEN_URI: &str = "OpenUri";
8const VIEW_ACTION: &str = "ViewAction";
9const OPEN_URL_BUTTON: &str = "openUrl";
10const DEFAULT_OS: &str = "default";
11
12/// The Adaptive Card that shows `root`, or `None` when it is no legacy card.
13pub(crate) fn as_adaptive_card(root: &Value) -> Option<Value> {
14 let object = root.as_object()?;
15 if object.contains_key("body") || text(root, "type") == Some("AdaptiveCard") {
16 return None;
17 }
18 let mut body = Vec::new();
19 if let Some(title) = text(root, "title") {
20 body.push(json!({"type": "TextBlock", "text": title, "weight": "Bolder", "size": "Medium", "wrap": true}));
21 }
22 if let Some(subtitle) = text(root, "subtitle") {
23 body.push(json!({"type": "TextBlock", "text": subtitle, "isSubtle": true, "wrap": true}));
24 }
25 if let Some(text) = text(root, "text") {
26 body.push(json!({"type": "TextBlock", "text": text, "wrap": true}));
27 }
28 for image in root
29 .get("images")
30 .and_then(Value::as_array)
31 .into_iter()
32 .flatten()
33 {
34 if let Some(url) = text(image, "url").or_else(|| text(image, "image")) {
35 body.push(json!({"type": "Image", "url": url}));
36 }
37 }
38 for section in root
39 .get("sections")
40 .and_then(Value::as_array)
41 .into_iter()
42 .flatten()
43 {
44 body.extend(section_items(section));
45 }
46 if body.is_empty() {
47 if let Some(summary) = text(root, "summary") {
48 body.push(json!({"type": "TextBlock", "text": summary, "wrap": true}));
49 }
50 }
51 let actions: Vec<Value> = root
52 .get("potentialAction")
53 .or_else(|| root.get("buttons"))
54 .and_then(Value::as_array)
55 .into_iter()
56 .flatten()
57 .filter_map(open_url_action)
58 .collect();
59 if body.is_empty() && actions.is_empty() {
60 return None;
61 }
62 Some(json!({"type": "AdaptiveCard", "version": "1.4", "body": body, "actions": actions}))
63}
64
65fn section_items(section: &Value) -> Vec<Value> {
66 let mut items = Vec::new();
67 let separator = section
68 .get("startGroup")
69 .and_then(Value::as_bool)
70 .unwrap_or(false);
71 if let Some(title) = text(section, "title") {
72 items.push(json!({"type": "TextBlock", "text": title, "weight": "Bolder", "wrap": true}));
73 }
74 let mut activity = Vec::new();
75 if let Some(title) = text(section, "activityTitle") {
76 activity
77 .push(json!({"type": "TextBlock", "text": title, "weight": "Bolder", "wrap": true}));
78 }
79 if let Some(subtitle) = text(section, "activitySubtitle") {
80 activity.push(json!({"type": "TextBlock", "text": subtitle, "isSubtle": true, "spacing": "None", "wrap": true}));
81 }
82 if let Some(body) = text(section, "activityText") {
83 activity.push(json!({"type": "TextBlock", "text": body, "wrap": true}));
84 }
85 match (text(section, "activityImage"), activity.is_empty()) {
86 (Some(image), false) => items.push(json!({
87 "type": "ColumnSet",
88 "columns": [
89 {"type": "Column", "width": "auto", "items": [{"type": "Image", "url": image, "size": "Small", "style": "Person"}]},
90 {"type": "Column", "width": "stretch", "items": activity},
91 ],
92 })),
93 _ => items.extend(activity),
94 }
95 if let Some(body) = text(section, "text") {
96 items.push(json!({"type": "TextBlock", "text": body, "wrap": true}));
97 }
98 let facts: Vec<Value> = section
99 .get("facts")
100 .and_then(Value::as_array)
101 .into_iter()
102 .flatten()
103 .filter_map(|fact| {
104 Some(json!({"title": text(fact, "name").unwrap_or_default(), "value": text(fact, "value")?}))
105 })
106 .collect();
107 if !facts.is_empty() {
108 items.push(json!({"type": "FactSet", "facts": facts}));
109 }
110 for image in section
111 .get("images")
112 .and_then(Value::as_array)
113 .into_iter()
114 .flatten()
115 {
116 if let Some(url) = text(image, "image").or_else(|| text(image, "url")) {
117 items.push(json!({"type": "Image", "url": url}));
118 }
119 }
120 if separator && let Some(first) = items.first_mut() {
121 first["separator"] = json!(true);
122 }
123 items
124}
125
126fn open_url_action(action: &Value) -> Option<Value> {
127 let title = text(action, "name").or_else(|| text(action, "title"))?;
128 let kind = text(action, "@type").or_else(|| text(action, "type"))?;
129 let url = match kind {
130 OPEN_URI => {
131 let targets = action.get("targets")?.as_array()?;
132 targets
133 .iter()
134 .find(|target| text(target, "os") == Some(DEFAULT_OS))
135 .or_else(|| targets.first())
136 .and_then(|target| text(target, "uri"))?
137 }
138 VIEW_ACTION => action.get("target")?.as_array()?.first()?.as_str()?,
139 OPEN_URL_BUTTON => text(action, "value")?,
140 _ => return None,
141 };
142 Some(json!({"type": "Action.OpenUrl", "title": title, "url": url}))
143}
144
145fn text<'value>(value: &'value Value, key: &str) -> Option<&'value str> {
146 value
147 .get(key)?
148 .as_str()
149 .map(str::trim)
150 .filter(|text| !text.is_empty())
151}
152
153#[cfg(test)]
154mod tests {
155 use crate::adaptive_card::AdaptiveCard;
156
157 const WEBHOOK: &str = r#"{
158 "@type": "MessageCard",
159 "summary": "Build failed",
160 "title": "Pipeline main",
161 "sections": [{
162 "activityTitle": "Build 128 failed",
163 "activitySubtitle": "on agent 3",
164 "facts": [{"name": "Branch", "value": "main"}, {"name": "Duration", "value": "4 min"}],
165 "text": "See the log for details."
166 }],
167 "potentialAction": [
168 {"@type": "OpenUri", "name": "Open log", "targets": [{"os": "default", "uri": "https://ci.example/128"}]},
169 {"@type": "HttpPOST", "name": "Retry", "target": "https://ci.example/retry"}
170 ]
171 }"#;
172
173 #[test]
174 fn a_connector_message_card_shows_title_sections_facts_and_links() {
175 let card = AdaptiveCard::parse(WEBHOOK).expect("connector card is shown");
176 let text = card.plain_text().unwrap_or_default();
177 for expected in [
178 "Pipeline main",
179 "Build 128 failed",
180 "on agent 3",
181 "See the log",
182 "Branch",
183 "main",
184 ] {
185 assert!(text.contains(expected), "{expected} missing in {text:?}");
186 }
187 let titles: Vec<_> = card
188 .actions
189 .iter()
190 .map(|action| action.title.as_str())
191 .collect();
192 assert_eq!(titles, ["Open log"]);
193 }
194
195 #[test]
196 fn a_hero_card_shows_its_text_and_buttons() {
197 let hero = r#"{"title": "Release 1.2", "text": "Ready", "buttons": [{"type": "openUrl", "title": "Notes", "value": "https://example.com/notes"}]}"#;
198 let card = AdaptiveCard::parse(hero).expect("hero card is shown");
199 assert!(
200 card.plain_text()
201 .unwrap_or_default()
202 .contains("Release 1.2")
203 );
204 assert_eq!(card.actions.len(), 1);
205 }
206
207 #[test]
208 fn an_empty_object_stays_no_card() {
209 assert!(AdaptiveCard::parse("{}").is_none());
210 }
211}