BlueGit

ict rusty-teams

Files

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

announcement_post.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
announcement_post.rs 4.4 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) => {
50 Some(self.upload_banner_image(channel_id, path).await?)
51 }
52 _ => None,
53 };
54 let (html, mentions) = outgoing(&conversation, html, mentions)?;
55 let mut sent = self
56 .remote
57 .send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
58 .await?;
59 let cards = banner.teams_cards(image.as_ref());
60 let target = ConversationRef::ChannelRoot {
61 channel_id: channel_id.to_owned(),
62 };
63 let attached = self.set_cards_with_retry(&target, &sent.id, &cards).await;
64 if attached {
65 let shown = match &image {
66 Some(image) => AnnouncementBanner {
67 title: banner.title.clone(),
68 background: BannerBackground::Image(image.url.clone()),
69 },
70 None => banner.clone(),
71 };
72 sent.attachments.insert(
73 0,
74 shown.attachment(format!("announcement-card-{}", sent.id)),
75 );
76 }
77 let record = self.cache_sent(channel_id, &sent, &html, extras)?;
78 if attached {
79 Ok(record)
80 } else {
81 Err(Error::PostedWithoutBanner)
82 }
83 }
84
85 async fn set_cards_with_retry(
86 &self,
87 target: &ConversationRef,
88 message_id: &str,
89 cards: &str,
90 ) -> bool {
91 for delay in CARD_RETRY_DELAYS {
92 tokio::time::sleep(delay).await;
93 if self
94 .remote
95 .set_message_cards(target, message_id, cards)
96 .await
97 .is_ok()
98 {
99 return true;
100 }
101 }
102 false
103 }
104
105 async fn upload_banner_image(&self, channel_id: &str, path: &str) -> Result<TeamsBannerImage> {
106 let bytes =
107 std::fs::read(path).map_err(|_| Error::BannerImage("the picked file is gone"))?;
108 let (width, height) = png_size(&bytes).ok_or(Error::BannerImage("not a PNG"))?;
109 let uploaded = self
110 .remote
111 .upload_ams_image(channel_id, &bytes, BANNER_FILE_NAME)
112 .await?;
113 Ok(TeamsBannerImage {
114 object_id: uploaded.object_id,
115 url: uploaded.url,
116 width,
117 height,
118 })
119 }
120}
121
122#[cfg(test)]
123mod tests {
124 use super::png_size;
125
126 #[test]
127 fn png_size_reads_the_header() {
128 let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
129 header.extend_from_slice(&1317u32.to_be_bytes());
130 header.extend_from_slice(&366u32.to_be_bytes());
131 assert_eq!(png_size(&header), Some((1317, 366)));
132 assert_eq!(png_size(b"GIF89a"), None);
133 }
134}