1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
//! Idiomatic building of MS Teams messages. //! //! Most documentation in this module are from //! [microsoft docs](https://docs.microsoft.com/en-us/outlook/actionable-messages/message-card-reference). //! //! # Goal //! //! Provide easy building of a [MS Teams](https://teams.microsoft.com/) messages, //! through the [`Message`] object. The [`Message`] object is serializable, //! using [Serde](https://serde.rs), allowing it to be converted to JSON //! and sent to a Teams webhook. //! //! # Example //! //! ```no_run //! # fn main() -> Result<(), Box<dyn Error>> { //! extern crate mhteams; //! extern crate reqwest; //! //! use mhteams::{Message, Section, Image}; //! use reqwest::blocking::Client; //! //! let msg = Message::new() //! .title("My title 😉") //! .text("TL;DR: it's awesome 👍") //! .sections(vec![ //! Section::new() //! .title("The **Section**") //! .activity_title("_Check this out_") //! .activity_subtitle("It's awesome") //! .activity_image("https://sweet.image/cute.png") //! .activity_text("Lorum ipsum!") //! .hero_image(Image::new("MyImage", "https://sweet.image/bigasscar.png")), //! Section::new() //! .title("Layin down some facts ✅") //! .facts(vec![ //! Fact::new("Name", "John Smith"), //! Fact::new("Language", "Rust. What else?"), //! ]), //! ]); //! //! let client = Client::new(); //! let resp = client //! .post(URL) //! .json(&msg) //! .send()?; //! //! # Ok(()) //! # } //! ``` //! //! [`Message`]: struct.Message.html extern crate serde; use serde::{Serialize, Serializer}; /// Main object representing a teams message. #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)] pub struct Message<'a> { // Required to always be set to "MessageCard" #[serde(rename = "@type")] typ: &'a str, // Required to always be set to "https://schema.org/extensions" #[serde(rename = "@context")] context: &'a str, #[serde(skip_serializing_if = "String::is_empty")] summary: String, #[serde(rename = "themeColor", skip_serializing_if = "String::is_empty")] theme_color: String, #[serde(rename = "correlationId", skip_serializing_if = "usize_is_zero")] correlation_id: usize, #[serde(rename = "expectedActors", skip_serializing_if = "Vec::is_empty")] expected_actors: Vec<String>, #[serde(skip_serializing_if = "String::is_empty")] originator: String, #[serde(rename = "hideOriginalBody", skip_serializing_if = "Option::is_none", serialize_with = "optional_bool")] hide_original_body: Option<bool>, #[serde(skip_serializing_if = "String::is_empty")] title: String, #[serde(skip_serializing_if = "String::is_empty")] text: String, #[serde(skip_serializing_if = "Vec::is_empty")] sections: Vec<Section>, // #[serde(rename = "potentialAction", skip_serializing_if = "Vec::is_empty")] // potential_action: Vec<Action>, } impl<'a> Message<'a> { /// Create a new, empty message. /// /// The message @type and @context are automatically set upon /// creation, since these always have the same values. pub fn new() -> Message<'a> { Message { typ: "MessageCard", context: "https://schema.org/extensions", ..Default::default() } } /// Required if the card does not contain a `text` property, otherwise optional. /// The `summary` property is typically displayed in the list view in Outlook, /// as a way to quickly determine what the card is all about. /// /// **Do** always include a summary. /// /// **Don't** include details in the summary. For example, for a Twitter post, /// a summary might simply read "New tweet from @someuser" without mentioning /// the content of the tweet itself. pub fn summary(mut self, s: impl ToString) -> Self { self.summary = s.to_string(); self } /// Specifies a custom brand color for the card. The color will be displayed /// in a non-obtrusive manner. pub fn theme_color(mut self, c: impl ToString) -> Self { self.theme_color = c.to_string(); self } /// The `correlationId` property simplifies the process of locating logs for /// troubleshooting issues. We recommend that when sending an actionable card, /// your service should set and log a unique UUID in this property. /// /// When the user invokes an action on the card, Office 365 sends the `Card-Correlation-Id` /// and `Action-Request-Id` headers in the POST request to your service. /// `Card-Correlation-Id` contains the same value as the `correlationId` /// property in the card. `Action-Request-Id` is a unique UUID generated by /// Office 365 to help locate specific action performed by a user. Your /// service should log both of these values when receiving action POST requests. pub fn correlation_id(mut self, id: usize) -> Self { self.correlation_id = id; self } /// Optional. This contains a list of expected email addresses of the /// recipient for the action endpoint. /// /// A user can have multiple email addresses and the action endpoint might /// not be expecting the particular email address presented in the `sub` claim /// of the bearer token. For example, a user could have both the `john.doe@contoso.com` /// or `john@contoso.com` email address, but the action endpoint expects to receive /// `john@contoso.com` in the `sub` claim of the bearer token. By setting /// this field to `["john@contoso.com"]`, the `sub` claim will have the /// expected email address. pub fn expected_actors<I>(mut self, v: I) -> Self where I: IntoIterator, I::Item: ToString, { self.expected_actors = v.into_iter() .map(|s| s.to_string()) .collect(); self } /// Required when sent via email, not applicable when sent via connector. /// For actionable email, MUST be set to the provider ID generated by the /// Actionable Email Developer Dashboard. pub fn originator(mut self, s: impl ToString) -> Self { self.originator = s.to_string(); self } /// _Only applies to cards in email messages_ /// /// When set to true, causes the HTML body of the message to be hidden. This /// is very useful in scenarios where the card is a better or more useful /// representation of the content than the HTML body itself, which is especially /// true when the card contains actions (see below.) /// /// Consider hiding the original HTML body: /// * If the card itself contains all the information a user would need /// * If the content of the card is redundant with the content of the body /// /// **Do** always include a nice HTML body, even if it is going to be hidden. /// The HTML body is the only thing an email client that doesn't support cards /// will be able to display. Furthermore, cards are not included when replying /// to or forwarding emails, only the HTML body. /// /// **Don't** hide the body when it is complementary to the information presented /// in the card. For example, the body of an expense report approval might /// describe the report in great details while the card just presents a quick /// summary along with approve/decline actions. pub fn hide_original_body(mut self, b: bool) -> Self { self.hide_original_body = Some(b); self } /// The `title` property is meant to be rendered in a prominent way, at the /// very top of the card. Use it to introduce the content of the card in such /// a way users will immediately know what to expect. /// /// Examples: /// * Daily news /// * New bug opened /// * Task <name of task> assigned /// /// **Do** keep title short, don't make it a long sentence. /// /// **Do** mention the name of the entity being referenced in the title. /// /// **Don't** use hyperlinks (via Markdown) in the title. pub fn title(mut self, s: impl ToString) -> Self { self.title = s.to_string(); self } /// Required if the card does not contain a `summary` property, otherwise optional. /// The `text` property is meant to be displayed in a normal font below the card's /// title. Use it to display content, such as the description of the entity /// being referenced, or an abstract of a news article. /// /// **Do** use simple Markdown, such as bold or italics to emphasize words, /// and links to external resources. /// /// **Don't** include any call to action in the text property. Users should be /// able to not read it and still understand what the card is all about. pub fn text(mut self, s: impl ToString) -> Self { self.text = s.to_string(); self } /// A collection of [`sections`] to include in the card. /// /// [`sections`]: struct.Section.html pub fn sections(mut self, v: Vec<Section>) -> Self { self.sections = v; self } // A collection of [`actions`] that can be invoked on this card. // // [`actions`]: struct.Action.html // pub fn potential_action(mut self, v: Vec<Action>) -> Self { // self.potential_action = v; // self // } } /// A section in a message. #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)] pub struct Section { #[serde(skip_serializing_if = "String::is_empty")] title: String, #[serde(rename = "startGroup", skip_serializing_if = "Option::is_none", serialize_with = "optional_bool")] start_group: Option<bool>, #[serde(rename = "activityImage", skip_serializing_if = "String::is_empty")] activity_image: String, #[serde(rename = "activityTitle", skip_serializing_if = "String::is_empty")] activity_title: String, #[serde(rename = "activitySubtitle", skip_serializing_if = "String::is_empty")] activity_subtitle: String, #[serde(rename = "activityText", skip_serializing_if = "String::is_empty")] activity_text: String, #[serde(rename = "heroImage", skip_serializing_if = "Option::is_none", serialize_with = "optional_image")] hero_image: Option<Image>, #[serde(skip_serializing_if = "String::is_empty")] text: String, #[serde(skip_serializing_if = "Vec::is_empty")] facts: Vec<Fact>, #[serde(skip_serializing_if = "Vec::is_empty")] images: Vec<Image>, // #[serde(rename = "potentialAction", skip_serializing_if = "Vec::is_empty")] // potential_action: Vec<Action>, } impl Section { /// Create a new, empty section. pub fn new() -> Self { Section { ..Default::default() } } /// The `title` property of a section is displayed in a font that stands out /// while not as prominent as the card's title. It is meant to introduce the /// section and summarize its content, similarly to how the card's title /// property is meant to summarize the whole card. /// /// **Do** keep title short, don't make it a long sentence. /// /// **Do** mention the name of the entity being referenced in the title. /// /// **Don't** use hyperlinks (via Markdown) in the title. pub fn title(mut self, s: impl ToString) -> Self { self.title = s.to_string(); self } /// When set to `true`, the `startGroup` property marks the start of a logical /// group of information. Typically, sections with `startGroup` set to `true` /// will be visually separated from previous card elements. For example, /// Outlook uses a subtle horizontal separation line. /// /// **Do** use `startGroup` to separate sections that represent different objects; /// for example, multiple tweets in a digest. pub fn start_group(mut self, b: bool) -> Self { self.start_group = Some(b); self } /// These four properties form a logical group. `activityTitle`, `activitySubtitle` /// and `activityText` will be displayed alongside `activityImage`, using a /// layout appropriate for the form factor of the device the card is being /// viewed on. For instance, in Outlook on the Web, `activityTitle`, /// `activitySubtitle` and `activityText` are displayed on the right of `activityImage`, using a two-column layout. pub fn activity_image(mut self, url: impl ToString) -> Self { self.activity_image = url.to_string(); self } /// These four properties form a logical group. `activityTitle`, `activitySubtitle` /// and `activityText` will be displayed alongside `activityImage`, using a /// layout appropriate for the form factor of the device the card is being /// viewed on. For instance, in Outlook on the Web, `activityTitle`, /// `activitySubtitle` and `activityText` are displayed on the right of `activityImage`, using a two-column layout. pub fn activity_title(mut self, s: impl ToString) -> Self { self.activity_title = s.to_string(); self } /// These four properties form a logical group. `activityTitle`, `activitySubtitle` /// and `activityText` will be displayed alongside `activityImage`, using a /// layout appropriate for the form factor of the device the card is being /// viewed on. For instance, in Outlook on the Web, `activityTitle`, /// `activitySubtitle` and `activityText` are displayed on the right of `activityImage`, using a two-column layout. pub fn activity_subtitle(mut self, s: impl ToString) -> Self { self.activity_subtitle = s.to_string(); self } /// These four properties form a logical group. `activityTitle`, `activitySubtitle` /// and `activityText` will be displayed alongside `activityImage`, using a /// layout appropriate for the form factor of the device the card is being /// viewed on. For instance, in Outlook on the Web, `activityTitle`, /// `activitySubtitle` and `activityText` are displayed on the right of `activityImage`, using a two-column layout. pub fn activity_text(mut self, s: impl ToString) -> Self { self.activity_text = s.to_string(); self } /// Use `heroImage` to make an image the centerpiece of your card. For example, /// a tweet that contains an image will want to put that image front and center. pub fn hero_image(mut self, i: Image) -> Self { self.hero_image = Some(i); self } /// The section's `text` property is very similar to the `text` property of /// the card. It can be used for the same purpose. pub fn text(mut self, s: impl ToString) -> Self { self.text = s.to_string(); self } /// Facts are a very important component of a section. They often contain /// the information that really matters to the user. /// /// Facts are displayed in such a way that they can be read quickly and /// efficiently. For example, in Outlook on the Web, facts are presented in /// a two-column layout, with fact names rendered in a slightly more prominent font. /// /// **Do** use facts instead of embedding important information inside the text /// property of either the card or the section. /// /// **Do** keep fact names short. /// /// **Avoid** making fact values too long. /// /// **Avoid** using Markdown formatting for both fact names and values. Let /// facts be rendered as intended as that is how they will have the most impact. /// /// **Do** however use Markdown for links in fact values only. For instance, /// if a fact references an external document, make the value of that fact /// a link to the document. /// /// **Don't** add a fact without a real purpose. For instance, a fact that /// would always have the same value across all cards is not interesting /// and a waste of space. pub fn facts(mut self, f: Vec<Fact>) -> Self { self.facts = f; self } /// The `images` property allows for the inclusion of a photo gallery inside /// a section. That photo gallery will always be displayed in a way that is /// easy to consume regardless of the form factor of the device it is being /// viewed on. For instance, in Outlook on the Web, images might be displayed /// as a horizontal strip of thumbnails with controls allowing to scroll /// through the collection if it doesn't all fit on the screen. On mobile, /// images might be displayed as a single thumbnail, with the user able to /// swipe through the collection with their finger. pub fn images(mut self, i: Vec<Image>) -> Self { self.images = i; self } // A collection of [`actions`] that can be invoked on this section. // // [`actions`]: struct.Action.html // pub fn potential_action(mut self, a: Vec<Action>) -> Self { // self.potential_action = a; // self // } } /// A fact (title-value pair) used in sections. #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)] pub struct Fact { name: String, value: String, } impl Fact { pub fn new(name: impl ToString, value: impl ToString) -> Self { Fact { name: name.to_string(), value: value.to_string() } } } /// An image, referenced by a url. #[derive(Debug, Default, Clone, PartialEq, Eq, Serialize)] pub struct Image { image: String, title: String, } impl Image { /// Title: A short description of the image. Typically, `title` is displayed in a tooltip as the user hovers their mouse over the image. pub fn new(title: impl ToString, url: impl ToString) -> Self { Image { image: url.to_string(), title: title.to_string() } } } // #[derive(Debug, Clone, PartialEq, Eq, Serialize)] // pub enum Action { // OpenUri, // HttpPOST, // ActionCard, // InvokeAddInCommand, // None, // } // impl Action { // pub fn is_none(&self) -> bool { // matches!(self, Action::None) // } // } // impl Default for Action { // fn default() -> Self { // Action::None // } // } fn usize_is_zero(x: &usize) -> bool { *x == 0 } fn optional_bool<S>(val: &Option<bool>, s: S) -> Result<S::Ok, S::Error> where S: Serializer { let v = match *val { Some(b) => b, None => false, }; s.serialize_bool(v) } fn optional_image<S>(val: &Option<Image>, s: S) -> Result<S::Ok, S::Error> where S: Serializer { match val { Some(v) => v.serialize(s), None => s.serialize_none(), } }