BlueGit

ict rusty-teams

Files

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

announcement_post.rs

announcement_post.rs 4.3 KiB Download Raw
1use std::time::Duration;
2
3use chatsvc::ConversationRef;
4use graph::MessageExtras;
5use store::MessageRecord;
6
7use crate::actions::outgoing;
8use crate::announcement::{AnnouncementBanner, BannerBackground, TeamsBannerImage};
9use crate::engine::{Conversation, SyncEngine};
10use crate::error::{Error, Result};
11use crate::mentions::MentionInput;
12use crate::remote::Remote;
13
14const BANNER_FILE_NAME: &str = "MicrosoftTeams-image.png";
15const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
16const CARD_RETRY_DELAYS: [Duration; 3] = [
17 Duration::ZERO,
18 Duration::from_secs(1),
19 Duration::from_secs(3),
20];
21
22fn png_size(bytes: &[u8]) -> Option<(u32, u32)> {
23 if !bytes.starts_with(PNG_SIGNATURE) || bytes.get(12..16)? != b"IHDR" {
24 return None;
25 }
26 let read = |range: std::ops::Range<usize>| -> Option<u32> {
27 Some(u32::from_be_bytes(bytes.get(range)?.try_into().ok()?))
28 };
29 Some((read(16..20)?, read(20..24)?))
30}
31
32impl<R: Remote> SyncEngine<R> {
33 /// Graph rejects the banner card from a user token, so the post goes out plain and the
34 /// chat service adds the card. The image is uploaded first so a failed upload sends nothing.
35 pub async fn post_announcement(
36 &self,
37 channel_id: &str,
38 html: &str,
39 subject: Option<&str>,
40 mentions: &[MentionInput],
41 extras: &MessageExtras,
42 banner: &AnnouncementBanner,
43 ) -> Result<MessageRecord> {
44 let conversation = self.resolve(channel_id).await?;
45 let Conversation::Channel { team_id } = &conversation else {
46 return Err(Error::Unsupported("an announcement in a chat"));
47 };
48 let image = match &banner.background {
49 BannerBackground::LocalImage(path) => Some(self.upload_banner_image(channel_id, path).await?),
50 _ => None,
51 };
52 let (html, mentions) = outgoing(&conversation, html, mentions)?;
53 let mut sent = self
54 .remote
55 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
56 .await?;
57 let cards = banner.teams_cards(image.as_ref());
58 let target = ConversationRef::ChannelRoot {
59 channel_id: channel_id.to_owned(),
60 };
61 let attached = self.set_cards_with_retry(&target, &sent.id, &cards).await;
62 if attached {
63 let shown = match &image {
64 Some(image) => AnnouncementBanner {
65 title: banner.title.clone(),
66 background: BannerBackground::Image(image.url.clone()),
67 },
68 None => banner.clone(),
69 };
70 sent.attachments
71 .insert(0, shown.attachment(format!("announcement-card-{}", sent.id)));
72 }
73 let record = self.cache_sent(channel_id, &sent, &html, extras)?;
74 if attached {
75 Ok(record)
76 } else {
77 Err(Error::PostedWithoutBanner)
78 }
79 }
80
81 async fn set_cards_with_retry(&self, target: &ConversationRef, message_id: &str, cards: &str) -> bool {
82 for delay in CARD_RETRY_DELAYS {
83 tokio::time::sleep(delay).await;
84 if self
85 .remote
86 .set_message_cards(target, message_id, cards)
87 .await
88 .is_ok()
89 {
90 return true;
91 }
92 }
93 false
94 }
95
96 async fn upload_banner_image(&self, channel_id: &str, path: &str) -> Result<TeamsBannerImage> {
97 let bytes = std::fs::read(path)
98 .map_err(|_| Error::BannerImage("the picked file is gone"))?;
99 let (width, height) =
100 png_size(&bytes).ok_or(Error::BannerImage("not a PNG"))?;
101 let uploaded = self
102 .remote
103 .upload_ams_image(channel_id, &bytes, BANNER_FILE_NAME)
104 .await?;
105 Ok(TeamsBannerImage {
106 object_id: uploaded.object_id,
107 url: uploaded.url,
108 width,
109 height,
110 })
111 }
112}
113
114#[cfg(test)]
115mod tests {
116 use super::png_size;
117
118 #[test]
119 fn png_size_reads_the_header() {
120 let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
121 header.extend_from_slice(&1317u32.to_be_bytes());
122 header.extend_from_slice(&366u32.to_be_bytes());
123 assert_eq!(png_size(&header), Some((1317, 366)));
124 assert_eq!(png_size(b"GIF89a"), None);
125 }
126}