BlueGit

ict rusty-teams

Files

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

announcement.rs

announcement.rs 9.2 KiB Download Raw
1use serde_json::{Value, json};
2
3use crate::stored::{AttachmentInfo, ImageRef};
4
5pub const ANNOUNCEMENT_BANNER_TYPE: &str =
6 "application/vnd.microsoft.teams.messaging-announcementBanner";
7pub const ANNOUNCEMENT_APP_ID: &str = "announcement-card";
8const DEFAULT_BANNER_COLOR: &str = "periwinkleBlue";
9const COLOR_THEME: &str = "colorTheme";
10const UPLOADED_IMAGE: &str = "uploadedImage";
11const LOCAL_IMAGE: &str = "localImage";
12const TEAMS_THEMES: [&str; 12] = [
13 "periwinkleBlue",
14 "lavender",
15 "rose",
16 "orangeSherbet",
17 "flaxYellow",
18 "teal",
19 "navyBlue",
20 "indigo",
21 "mulberryRed",
22 "fireOrange",
23 "rawUmber",
24 "oceanGreen",
25];
26
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub enum BannerBackground {
29 Color(String),
30 Image(String),
31 /// A picked file that is uploaded when the post is sent.
32 LocalImage(String),
33}
34
35/// Teams web stores the color theme as its index.
36pub fn teams_theme(color: &str) -> String {
37 TEAMS_THEMES
38 .iter()
39 .position(|known| *known == color)
40 .unwrap_or_default()
41 .to_string()
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
45pub struct AnnouncementBanner {
46 pub title: String,
47 pub background: BannerBackground,
48}
49
50impl AnnouncementBanner {
51 pub fn from_attachments(attachments: &[AttachmentInfo]) -> Option<AnnouncementBanner> {
52 attachments
53 .iter()
54 .filter(|attachment| {
55 attachment.content_type.as_deref() == Some(ANNOUNCEMENT_BANNER_TYPE)
56 })
57 .find_map(|attachment| AnnouncementBanner::parse(attachment.content.as_deref()?))
58 }
59
60 pub fn parse(content: &str) -> Option<AnnouncementBanner> {
61 let content: Value = serde_json::from_str(content).ok()?;
62 let title = content.get("title")?.as_str()?.trim().to_owned();
63 if let Some(path) = content.get(LOCAL_IMAGE).and_then(Value::as_str) {
64 return Some(AnnouncementBanner {
65 title,
66 background: BannerBackground::LocalImage(path.to_owned()),
67 });
68 }
69 let details = content.get("cardImageDetails");
70 let image = details
71 .filter(|_| content.get("cardImageType").and_then(Value::as_str) != Some(COLOR_THEME))
72 .and_then(|details| {
73 image_source(details, "croppedImage")
74 .or_else(|| image_source(details, "originalImage"))
75 });
76 let background = match image {
77 Some(url) => BannerBackground::Image(url),
78 None => BannerBackground::Color(
79 details
80 .and_then(|details| details.get(COLOR_THEME))
81 .and_then(Value::as_str)
82 .unwrap_or(DEFAULT_BANNER_COLOR)
83 .to_owned(),
84 ),
85 };
86 Some(AnnouncementBanner { title, background })
87 }
88
89 pub fn image(&self) -> Option<ImageRef> {
90 let BannerBackground::Image(url) = &self.background else {
91 return None;
92 };
93 Some(ImageRef {
94 id: url.clone(),
95 url: url.clone(),
96 width: None,
97 height: None,
98 alt: Some(self.title.clone()),
99 })
100 }
101
102 /// Graph shape, as Graph returns it for a post.
103 pub fn attachment(&self, id: String) -> graph::Attachment {
104 graph::Attachment {
105 id: Some(id),
106 content_type: Some(ANNOUNCEMENT_BANNER_TYPE.to_owned()),
107 content_url: None,
108 name: None,
109 content: Some(self.content()),
110 teams_app_id: Some(ANNOUNCEMENT_APP_ID.to_owned()),
111 }
112 }
113
114 /// Graph shape; a local image keeps its path so a queued post survives a restart.
115 pub fn content(&self) -> String {
116 let mut content = json!({ "title": self.title });
117 match &self.background {
118 BannerBackground::Color(color) => {
119 content["cardImageType"] = json!(COLOR_THEME);
120 content["cardImageDetails"] = json!({ COLOR_THEME: color });
121 }
122 BannerBackground::Image(url) => {
123 content["cardImageType"] = json!(UPLOADED_IMAGE);
124 content["cardImageDetails"] = json!({ "uploadedImageDetail": {
125 "originalImage": { "source": url },
126 "croppedImage": { "source": url },
127 }});
128 }
129 BannerBackground::LocalImage(path) => content[LOCAL_IMAGE] = json!(path),
130 }
131 content.to_string()
132 }
133
134 /// The chat service `cards` property Teams web renders; `image` is the uploaded background.
135 pub fn teams_cards(&self, image: Option<&TeamsBannerImage>) -> String {
136 let content = match (image, &self.background) {
137 (Some(image), _) => json!({ "imageData": {
138 "origImage": { "id": image.object_id, "src": image.url },
139 "croppedImage": {
140 "id": image.object_id,
141 "src": image.url,
142 "imageWidth": image.width,
143 "imageHeight": image.height,
144 "imageAltText": "",
145 },
146 }}),
147 (None, BannerBackground::Color(color)) => json!({ COLOR_THEME: teams_theme(color) }),
148 (None, _) => json!({ COLOR_THEME: teams_theme(DEFAULT_BANNER_COLOR) }),
149 };
150 json!([{
151 "appId": ANNOUNCEMENT_APP_ID,
152 "contentType": ANNOUNCEMENT_BANNER_TYPE,
153 "content": content,
154 }])
155 .to_string()
156 }
157}
158
159#[derive(Debug, Clone, PartialEq, Eq)]
160pub struct TeamsBannerImage {
161 pub object_id: String,
162 pub url: String,
163 pub width: u32,
164 pub height: u32,
165}
166
167fn image_source(details: &Value, key: &str) -> Option<String> {
168 let found = details
169 .get(key)
170 .or_else(|| details.get("uploadedImageDetail")?.get(key))?;
171 found
172 .get("source")
173 .or_else(|| found.get("url"))
174 .and_then(Value::as_str)
175 .filter(|url| url.starts_with("https://"))
176 .map(str::to_owned)
177}
178
179#[cfg(test)]
180mod tests {
181 use super::*;
182
183 fn banner_attachment(content: &str) -> AttachmentInfo {
184 serde_json::from_value(json!({
185 "content_type": ANNOUNCEMENT_BANNER_TYPE,
186 "name": null,
187 "url": null,
188 "text": null,
189 "content": content,
190 }))
191 .unwrap()
192 }
193
194 #[test]
195 fn color_banner_from_graph_content() {
196 let content = r#"{"title":"Release day","cardImageType":"colorTheme","cardImageDetails":{"colorTheme":"periwinkleBlue"}}"#;
197 let banner = AnnouncementBanner::from_attachments(&[banner_attachment(content)]).unwrap();
198 assert_eq!(banner.title, "Release day");
199 assert_eq!(
200 banner.background,
201 BannerBackground::Color("periwinkleBlue".into())
202 );
203 }
204
205 #[test]
206 fn uploaded_image_banner_uses_the_cropped_image() {
207 let content = r#"{"title":"Hi","cardImageType":"uploadedImage","cardImageDetails":{"uploadedImageDetail":{"originalImage":{"source":"https://example.test/o"},"croppedImage":{"source":"https://example.test/c"}}}}"#;
208 let banner = AnnouncementBanner::parse(content).unwrap();
209 assert_eq!(
210 banner.background,
211 BannerBackground::Image("https://example.test/c".into())
212 );
213 }
214
215 #[test]
216 fn content_round_trips() {
217 let banner = AnnouncementBanner {
218 title: "Ship it".into(),
219 background: BannerBackground::Color("teal".into()),
220 };
221 assert_eq!(AnnouncementBanner::parse(&banner.content()), Some(banner));
222 }
223
224 #[test]
225 fn teams_cards_carry_the_theme_index_or_the_uploaded_image() {
226 let banner = AnnouncementBanner {
227 title: "Ship it".into(),
228 background: BannerBackground::Color("indigo".into()),
229 };
230 let cards: Value = serde_json::from_str(&banner.teams_cards(None)).unwrap();
231 assert_eq!(cards[0]["appId"], ANNOUNCEMENT_APP_ID);
232 assert_eq!(cards[0]["contentType"], ANNOUNCEMENT_BANNER_TYPE);
233 assert_eq!(cards[0]["content"], json!({"colorTheme": "7"}));
234 let image = TeamsBannerImage {
235 object_id: "0-a".into(),
236 url: "https://ams.test/0-a".into(),
237 width: 1200,
238 height: 300,
239 };
240 let cards: Value = serde_json::from_str(&banner.teams_cards(Some(&image))).unwrap();
241 let cropped = &cards[0]["content"]["imageData"]["croppedImage"];
242 assert_eq!(cropped["src"], "https://ams.test/0-a");
243 assert_eq!(cropped["imageHeight"], 300);
244 assert_eq!(cards[0]["content"]["imageData"]["origImage"]["id"], "0-a");
245 assert_eq!(teams_theme("unknown"), "0");
246 }
247
248 #[test]
249 fn local_and_uploaded_images_round_trip() {
250 for background in [
251 BannerBackground::LocalImage("/home/a/b.png".into()),
252 BannerBackground::Image("https://ams.test/0-a".into()),
253 ] {
254 let banner = AnnouncementBanner {
255 title: "Hi".into(),
256 background,
257 };
258 assert_eq!(AnnouncementBanner::parse(&banner.content()), Some(banner));
259 }
260 }
261
262 #[test]
263 fn banner_without_content_is_none() {
264 let mut attachment = banner_attachment("");
265 attachment.content = None;
266 assert_eq!(AnnouncementBanner::from_attachments(&[attachment]), None);
267 }
268}