BlueGit

ict rusty-teams

fix(posts): report a banner that fails after the post, clean up banner images

- the banner card gets three tries; when all fail the post stays and the channel shows "Posted, but Teams did not take the banner." instead of a retry that would post twice
- a missing or broken banner file is a permanent failure with its own message
- prepared banner PNGs are removed after the post, unsent ones after 30 days

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-11-08 · 3 weeks ago

Hash
d1a40661f9f49a74010714603367e512fb0e609d
Parent
c4a9deb8
7 files changed +147 −24
crates/app-state/src/banner_image.rs +51 −4
@@ -1,4 +1,5 @@
1 1 use std::path::{Path, PathBuf};
2 use std::time::{Duration, SystemTime};
2 3
3 4 use image::imageops::FilterType;
4 5 use uuid::Uuid;
@@ -7,6 +8,7 @@ use uuid::Uuid;
7 8 pub const BANNER_IMAGE_WIDTH: u32 = 1317;
8 9 pub const BANNER_IMAGE_HEIGHT: u32 = 366;
9 10 const BANNER_DIRECTORY: &str = "banners";
11 const ABANDONED_AFTER: Duration = Duration::from_secs(30 * 24 * 60 * 60);
10 12
11 13 /// The centered box with the banner's aspect ratio: `(x, y, width, height)`.
12 14 pub fn crop_box(width: u32, height: u32) -> (u32, u32, u32, u32) {
@@ -28,10 +30,9 @@ pub fn prepare_banner_image(source: &Path) -> Result<PathBuf, String> {
28 30 BANNER_IMAGE_HEIGHT,
29 31 FilterType::Triangle,
30 32 );
31 let directory = directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
32 .map(|directories| directories.data_local_dir().join(BANNER_DIRECTORY))
33 .ok_or("no data folder")?;
33 let directory = banner_directory().ok_or("no data folder")?;
34 34 std::fs::create_dir_all(&directory).map_err(|error| error.to_string())?;
35 remove_abandoned(&directory, SystemTime::now());
35 36 let target = directory.join(format!("{}.png", Uuid::new_v4().simple()));
36 37 banner
37 38 .to_rgb8()
@@ -40,9 +41,55 @@ pub fn prepare_banner_image(source: &Path) -> Result<PathBuf, String> {
40 41 Ok(target)
41 42 }
42 43
44 fn banner_directory() -> Option<PathBuf> {
45 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
46 .map(|directories| directories.data_local_dir().join(BANNER_DIRECTORY))
47 }
48
49 /// Removes a prepared banner once it is uploaded; files outside the banner folder stay.
50 pub fn discard_banner_image(path: &Path) {
51 if banner_directory().is_some_and(|directory| path.starts_with(directory)) {
52 let _ = std::fs::remove_file(path);
53 }
54 }
55
56 /// Banners of drafts that were never sent.
57 fn remove_abandoned(directory: &Path, now: SystemTime) {
58 let Ok(entries) = std::fs::read_dir(directory) else {
59 return;
60 };
61 for entry in entries.flatten() {
62 let old = entry
63 .metadata()
64 .and_then(|metadata| metadata.modified())
65 .ok()
66 .and_then(|modified| now.duration_since(modified).ok())
67 .is_some_and(|age| age > ABANDONED_AFTER);
68 if old {
69 let _ = std::fs::remove_file(entry.path());
70 }
71 }
72 }
73
43 74 #[cfg(test)]
44 75 mod tests {
45 use super::crop_box;
76 use std::time::{Duration, SystemTime};
77
78 use super::{ABANDONED_AFTER, crop_box, remove_abandoned};
79
80 #[test]
81 fn only_banners_older_than_a_month_are_removed() {
82 let directory = tempfile::tempdir().unwrap();
83 let banner = directory.path().join("a.png");
84 std::fs::write(&banner, b"x").unwrap();
85 remove_abandoned(directory.path(), SystemTime::now());
86 assert!(banner.exists());
87 remove_abandoned(
88 directory.path(),
89 SystemTime::now() + ABANDONED_AFTER + Duration::from_secs(60),
90 );
91 assert!(!banner.exists());
92 }
46 93
47 94 #[test]
48 95 fn crop_keeps_the_middle_band_of_a_tall_or_wide_picture() {
@@ -1,4 +1,5 @@
1use std::path::{Path, PathBuf};
1use std::path::{Path, PathBuf};
2use std::time::{Duration, SystemTime};
2
3
3use image::imageops::FilterType;
4use image::imageops::FilterType;
4use uuid::Uuid;
5use uuid::Uuid;
@@ -7,6 +8,7 @@ use uuid::Uuid;
7pub const BANNER_IMAGE_WIDTH: u32 = 1317;
8pub const BANNER_IMAGE_WIDTH: u32 = 1317;
8pub const BANNER_IMAGE_HEIGHT: u32 = 366;
9pub const BANNER_IMAGE_HEIGHT: u32 = 366;
9const BANNER_DIRECTORY: &str = "banners";
10const BANNER_DIRECTORY: &str = "banners";
11const ABANDONED_AFTER: Duration = Duration::from_secs(30 * 24 * 60 * 60);
10
12
11/// The centered box with the banner's aspect ratio: `(x, y, width, height)`.
13/// The centered box with the banner's aspect ratio: `(x, y, width, height)`.
12pub fn crop_box(width: u32, height: u32) -> (u32, u32, u32, u32) {
14pub fn crop_box(width: u32, height: u32) -> (u32, u32, u32, u32) {
@@ -28,10 +30,9 @@ pub fn prepare_banner_image(source: &Path) -> Result<PathBuf, String> {
28 BANNER_IMAGE_HEIGHT,
30 BANNER_IMAGE_HEIGHT,
29 FilterType::Triangle,
31 FilterType::Triangle,
30 );
32 );
31 let directory = directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
33 let directory = banner_directory().ok_or("no data folder")?;
32 .map(|directories| directories.data_local_dir().join(BANNER_DIRECTORY))
33 .ok_or("no data folder")?;
34 std::fs::create_dir_all(&directory).map_err(|error| error.to_string())?;
34 std::fs::create_dir_all(&directory).map_err(|error| error.to_string())?;
35 remove_abandoned(&directory, SystemTime::now());
35 let target = directory.join(format!("{}.png", Uuid::new_v4().simple()));
36 let target = directory.join(format!("{}.png", Uuid::new_v4().simple()));
36 banner
37 banner
37 .to_rgb8()
38 .to_rgb8()
@@ -40,9 +41,55 @@ pub fn prepare_banner_image(source: &Path) -> Result<PathBuf, String> {
40 Ok(target)
41 Ok(target)
41}
42}
42
43
44fn banner_directory() -> Option<PathBuf> {
45 directories::ProjectDirs::from("", "", store::DATA_DIR_NAME)
46 .map(|directories| directories.data_local_dir().join(BANNER_DIRECTORY))
47}
48
49/// Removes a prepared banner once it is uploaded; files outside the banner folder stay.
50pub fn discard_banner_image(path: &Path) {
51 if banner_directory().is_some_and(|directory| path.starts_with(directory)) {
52 let _ = std::fs::remove_file(path);
53 }
54}
55
56/// Banners of drafts that were never sent.
57fn remove_abandoned(directory: &Path, now: SystemTime) {
58 let Ok(entries) = std::fs::read_dir(directory) else {
59 return;
60 };
61 for entry in entries.flatten() {
62 let old = entry
63 .metadata()
64 .and_then(|metadata| metadata.modified())
65 .ok()
66 .and_then(|modified| now.duration_since(modified).ok())
67 .is_some_and(|age| age > ABANDONED_AFTER);
68 if old {
69 let _ = std::fs::remove_file(entry.path());
70 }
71 }
72}
73
43#[cfg(test)]
74#[cfg(test)]
44mod tests {
75mod tests {
45 use super::crop_box;
76 use std::time::{Duration, SystemTime};
77
78 use super::{ABANDONED_AFTER, crop_box, remove_abandoned};
79
80 #[test]
81 fn only_banners_older_than_a_month_are_removed() {
82 let directory = tempfile::tempdir().unwrap();
83 let banner = directory.path().join("a.png");
84 std::fs::write(&banner, b"x").unwrap();
85 remove_abandoned(directory.path(), SystemTime::now());
86 assert!(banner.exists());
87 remove_abandoned(
88 directory.path(),
89 SystemTime::now() + ABANDONED_AFTER + Duration::from_secs(60),
90 );
91 assert!(!banner.exists());
92 }
46
93
47 #[test]
94 #[test]
48 fn crop_keeps_the_middle_band_of_a_tall_or_wide_picture() {
95 fn crop_keeps_the_middle_band_of_a_tall_or_wide_picture() {
crates/app-state/src/outbox.rs +28 −7
@@ -51,13 +51,20 @@ pub fn outgoing_of(record: &OutboxRecord) -> Option<Outgoing> {
51 51 decode(&record.payload, &record.images)
52 52 }
53 53
54 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
55 pub enum Delivered {
56 Complete,
57 /// The post went out but its announcement banner could not be set.
58 WithoutBanner,
59 }
60
54 61 pub async fn deliver(
55 62 engine: &Engine,
56 63 conversation_id: &str,
57 64 target: OutboxTarget,
58 65 thread_root_id: Option<&str>,
59 66 outgoing: &Outgoing,
60 ) -> teams_core::Result<()> {
67 ) -> teams_core::Result<Delivered> {
61 68 let extras = outgoing.extras();
62 69 let html = outgoing.html();
63 70 let mentions = &outgoing.mentions;
@@ -74,7 +81,7 @@ pub async fn deliver(
74 81 }
75 82 (OutboxTarget::Post, None) => match &outgoing.banner {
76 83 Some(banner) => {
77 engine
84 let posted = engine
78 85 .post_announcement(
79 86 conversation_id,
80 87 &html,
@@ -83,7 +90,14 @@ pub async fn deliver(
83 90 &extras,
84 91 banner,
85 92 )
86 .await
93 .await;
94 if matches!(posted, Ok(_) | Err(teams_core::Error::PostedWithoutBanner)) {
95 discard_banner_image(banner);
96 }
97 match posted {
98 Err(teams_core::Error::PostedWithoutBanner) => return Ok(Delivered::WithoutBanner),
99 other => other,
100 }
87 101 }
88 102 None => {
89 103 engine
@@ -108,7 +122,13 @@ pub async fn deliver(
108 122 .attach_link_preview(conversation_id, &record.message_id, preview)
109 123 .await;
110 124 }
111 Ok(())
125 Ok(Delivered::Complete)
126 }
127
128 fn discard_banner_image(banner: &teams_core::AnnouncementBanner) {
129 if let teams_core::BannerBackground::LocalImage(path) = &banner.background {
130 crate::banner_image::discard_banner_image(std::path::Path::new(path));
131 }
112 132 }
113 133
114 134 fn is_permanent(error: &teams_core::Error) -> bool {
@@ -118,6 +138,7 @@ fn is_permanent(error: &teams_core::Error) -> bool {
118 138 }
119 139 teams_core::Error::Graph(graph::Error::NotAMember)
120 140 | teams_core::Error::Unsupported(_)
141 | teams_core::Error::BannerImage(_)
121 142 | teams_core::Error::UnknownConversation(_) => true,
122 143 _ => false,
123 144 }
@@ -170,10 +191,10 @@ async fn attempt(
170 191 engine: &Engine,
171 192 record: &OutboxRecord,
172 193 outgoing: &Outgoing,
173 ) -> teams_core::Result<()> {
194 ) -> teams_core::Result<Delivered> {
174 195 // Graph has no idempotency key: a send cut off by the quit may have gone through.
175 196 if already_sent(engine, record, outgoing).await? {
176 return Ok(());
197 return Ok(Delivered::Complete);
177 198 }
178 199 deliver(
179 200 engine,
@@ -195,7 +216,7 @@ async fn resend(engine: &Engine, record: &OutboxRecord, outgoing: &Outgoing) ->
195 216 tokio::time::sleep(delay).await;
196 217 }
197 218 match attempt(engine, record, outgoing).await {
198 Ok(()) => return Ok(()),
219 Ok(_) => return Ok(()),
199 220 Err(error) if is_permanent(&error) => return Err(short_error(&error)),
200 221 Err(error) => failure = short_error(&error),
201 222 }
@@ -51,13 +51,20 @@ pub fn outgoing_of(record: &OutboxRecord) -> Option<Outgoing> {
51 decode(&record.payload, &record.images)
51 decode(&record.payload, &record.images)
52}
52}
53
53
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub enum Delivered {
56 Complete,
57 /// The post went out but its announcement banner could not be set.
58 WithoutBanner,
59}
60
54pub async fn deliver(
61pub async fn deliver(
55 engine: &Engine,
62 engine: &Engine,
56 conversation_id: &str,
63 conversation_id: &str,
57 target: OutboxTarget,
64 target: OutboxTarget,
58 thread_root_id: Option<&str>,
65 thread_root_id: Option<&str>,
59 outgoing: &Outgoing,
66 outgoing: &Outgoing,
60) -> teams_core::Result<()> {
67) -> teams_core::Result<Delivered> {
61 let extras = outgoing.extras();
68 let extras = outgoing.extras();
62 let html = outgoing.html();
69 let html = outgoing.html();
63 let mentions = &outgoing.mentions;
70 let mentions = &outgoing.mentions;
@@ -74,7 +81,7 @@ pub async fn deliver(
74 }
81 }
75 (OutboxTarget::Post, None) => match &outgoing.banner {
82 (OutboxTarget::Post, None) => match &outgoing.banner {
76 Some(banner) => {
83 Some(banner) => {
77 engine
84 let posted = engine
78 .post_announcement(
85 .post_announcement(
79 conversation_id,
86 conversation_id,
80 &html,
87 &html,
@@ -83,7 +90,14 @@ pub async fn deliver(
83 &extras,
90 &extras,
84 banner,
91 banner,
85 )
92 )
86 .await
93 .await;
94 if matches!(posted, Ok(_) | Err(teams_core::Error::PostedWithoutBanner)) {
95 discard_banner_image(banner);
96 }
97 match posted {
98 Err(teams_core::Error::PostedWithoutBanner) => return Ok(Delivered::WithoutBanner),
99 other => other,
100 }
87 }
101 }
88 None => {
102 None => {
89 engine
103 engine
@@ -108,7 +122,13 @@ pub async fn deliver(
108 .attach_link_preview(conversation_id, &record.message_id, preview)
122 .attach_link_preview(conversation_id, &record.message_id, preview)
109 .await;
123 .await;
110 }
124 }
111 Ok(())
125 Ok(Delivered::Complete)
126}
127
128fn discard_banner_image(banner: &teams_core::AnnouncementBanner) {
129 if let teams_core::BannerBackground::LocalImage(path) = &banner.background {
130 crate::banner_image::discard_banner_image(std::path::Path::new(path));
131 }
112}
132}
113
133
114fn is_permanent(error: &teams_core::Error) -> bool {
134fn is_permanent(error: &teams_core::Error) -> bool {
@@ -118,6 +138,7 @@ fn is_permanent(error: &teams_core::Error) -> bool {
118 }
138 }
119 teams_core::Error::Graph(graph::Error::NotAMember)
139 teams_core::Error::Graph(graph::Error::NotAMember)
120 | teams_core::Error::Unsupported(_)
140 | teams_core::Error::Unsupported(_)
141 | teams_core::Error::BannerImage(_)
121 | teams_core::Error::UnknownConversation(_) => true,
142 | teams_core::Error::UnknownConversation(_) => true,
122 _ => false,
143 _ => false,
123 }
144 }
@@ -170,10 +191,10 @@ async fn attempt(
170 engine: &Engine,
191 engine: &Engine,
171 record: &OutboxRecord,
192 record: &OutboxRecord,
172 outgoing: &Outgoing,
193 outgoing: &Outgoing,
173) -> teams_core::Result<()> {
194) -> teams_core::Result<Delivered> {
174 // Graph has no idempotency key: a send cut off by the quit may have gone through.
195 // Graph has no idempotency key: a send cut off by the quit may have gone through.
175 if already_sent(engine, record, outgoing).await? {
196 if already_sent(engine, record, outgoing).await? {
176 return Ok(());
197 return Ok(Delivered::Complete);
177 }
198 }
178 deliver(
199 deliver(
179 engine,
200 engine,
@@ -195,7 +216,7 @@ async fn resend(engine: &Engine, record: &OutboxRecord, outgoing: &Outgoing) ->
195 tokio::time::sleep(delay).await;
216 tokio::time::sleep(delay).await;
196 }
217 }
197 match attempt(engine, record, outgoing).await {
218 match attempt(engine, record, outgoing).await {
198 Ok(()) => return Ok(()),
219 Ok(_) => return Ok(()),
199 Err(error) if is_permanent(&error) => return Err(short_error(&error)),
220 Err(error) if is_permanent(&error) => return Err(short_error(&error)),
200 Err(error) => failure = short_error(&error),
221 Err(error) => failure = short_error(&error),
201 }
222 }
crates/app/src/views/conversation.rs +7 −3
@@ -84,7 +84,7 @@ use crate::emoji;
84 84 use crate::emoticons;
85 85 use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
86 86 use crate::notice::short_error;
87 use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
87 use crate::outbox::{Delivered, deliver, new_outbox_id, outbox_record, outgoing_of};
88 88 use crate::pending_rows::pending_row;
89 89 use crate::people::{local_names, resolve_names};
90 90 use crate::reaction_model::UNKNOWN_REACTOR;
@@ -113,6 +113,7 @@ pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
113 113 pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
114 114 pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
115 115 pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
116 const POSTED_WITHOUT_BANNER: &str = "Posted, but Teams did not take the banner.";
116 117 const QUIET_RETRY_DELAYS: [Duration; 3] = [
117 118 Duration::from_secs(2),
118 119 Duration::from_secs(5),
@@ -3406,11 +3407,14 @@ impl ConversationView {
3406 3407 fn finish_send(
3407 3408 &mut self,
3408 3409 key: &str,
3409 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
3410 result: Result<teams_core::Result<Delivered>, tokio::sync::oneshot::error::RecvError>,
3410 3411 cx: &mut Context<Self>,
3411 3412 ) {
3413 if matches!(result, Ok(Ok(Delivered::WithoutBanner))) {
3414 self.notice = Some(POSTED_WITHOUT_BANNER.to_owned());
3415 }
3412 3416 let failure = match result {
3413 Ok(Ok(())) => None,
3417 Ok(Ok(_)) => None,
3414 3418 Ok(Err(error)) => Some(short_error(&error)),
3415 3419 Err(error) => Some(short_error(&error)),
3416 3420 };
@@ -84,7 +84,7 @@ use crate::emoji;
84use crate::emoticons;
84use crate::emoticons;
85use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
85use crate::image_view_gallery::{ViewerRequest, collect_gallery, position_of};
86use crate::notice::short_error;
86use crate::notice::short_error;
87use crate::outbox::{deliver, new_outbox_id, outbox_record, outgoing_of};
87use crate::outbox::{Delivered, deliver, new_outbox_id, outbox_record, outgoing_of};
88use crate::pending_rows::pending_row;
88use crate::pending_rows::pending_row;
89use crate::people::{local_names, resolve_names};
89use crate::people::{local_names, resolve_names};
90use crate::reaction_model::UNKNOWN_REACTOR;
90use crate::reaction_model::UNKNOWN_REACTOR;
@@ -113,6 +113,7 @@ pub const MEMBERS_BUTTON: &str = "shell/islands/main/members-button";
113pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
113pub const HEADER_DIVIDER: &str = "shell/islands/main/divider-header";
114pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
114pub const TIMELINE_TAG: &str = "shell/islands/main/timeline";
115pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
115pub const FEED_EDGE_TAG: &str = "shell/islands/main/timeline/divider-feed";
116const POSTED_WITHOUT_BANNER: &str = "Posted, but Teams did not take the banner.";
116const QUIET_RETRY_DELAYS: [Duration; 3] = [
117const QUIET_RETRY_DELAYS: [Duration; 3] = [
117 Duration::from_secs(2),
118 Duration::from_secs(2),
118 Duration::from_secs(5),
119 Duration::from_secs(5),
@@ -3406,11 +3407,14 @@ impl ConversationView {
3406 fn finish_send(
3407 fn finish_send(
3407 &mut self,
3408 &mut self,
3408 key: &str,
3409 key: &str,
3409 result: Result<teams_core::Result<()>, tokio::sync::oneshot::error::RecvError>,
3410 result: Result<teams_core::Result<Delivered>, tokio::sync::oneshot::error::RecvError>,
3410 cx: &mut Context<Self>,
3411 cx: &mut Context<Self>,
3411 ) {
3412 ) {
3413 if matches!(result, Ok(Ok(Delivered::WithoutBanner))) {
3414 self.notice = Some(POSTED_WITHOUT_BANNER.to_owned());
3415 }
3412 let failure = match result {
3416 let failure = match result {
3413 Ok(Ok(())) => None,
3417 Ok(Ok(_)) => None,
3414 Ok(Err(error)) => Some(short_error(&error)),
3418 Ok(Err(error)) => Some(short_error(&error)),
3415 Err(error) => Some(short_error(&error)),
3419 Err(error) => Some(short_error(&error)),
3416 };
3420 };
crates/app/src/views/conversation/scheduled.rs +1 −1
@@ -402,7 +402,7 @@ impl ConversationView {
402 402 });
403 403 cx.spawn(async move |_, cx| {
404 404 let failure = match receiver.await {
405 Ok(Ok(())) => None,
405 Ok(Ok(_)) => None,
406 406 Ok(Err(error)) => Some(short_error(&error)),
407 407 Err(error) => Some(short_error(&error)),
408 408 };
@@ -402,7 +402,7 @@ impl ConversationView {
402 });
402 });
403 cx.spawn(async move |_, cx| {
403 cx.spawn(async move |_, cx| {
404 let failure = match receiver.await {
404 let failure = match receiver.await {
405 Ok(Ok(())) => None,
405 Ok(Ok(_)) => None,
406 Ok(Err(error)) => Some(short_error(&error)),
406 Ok(Err(error)) => Some(short_error(&error)),
407 Err(error) => Some(short_error(&error)),
407 Err(error) => Some(short_error(&error)),
408 };
408 };
crates/core/src/announcement_post.rs +32 −9
@@ -1,3 +1,5 @@
1 use std::time::Duration;
2
1 3 use chatsvc::ConversationRef;
2 4 use graph::MessageExtras;
3 5 use store::MessageRecord;
@@ -11,6 +13,11 @@ use crate::remote::Remote;
11 13
12 14 const BANNER_FILE_NAME: &str = "MicrosoftTeams-image.png";
13 15 const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
16 const CARD_RETRY_DELAYS: [Duration; 3] = [
17 Duration::ZERO,
18 Duration::from_secs(1),
19 Duration::from_secs(3),
20 ];
14 21
15 22 fn png_size(bytes: &[u8]) -> Option<(u32, u32)> {
16 23 if !bytes.starts_with(PNG_SIGNATURE) || bytes.get(12..16)? != b"IHDR" {
@@ -51,12 +58,8 @@ impl<R: Remote> SyncEngine<R> {
51 58 let target = ConversationRef::ChannelRoot {
52 59 channel_id: channel_id.to_owned(),
53 60 };
54 if self
55 .remote
56 .set_message_cards(&target, &sent.id, &cards)
57 .await
58 .is_ok()
59 {
61 let attached = self.set_cards_with_retry(&target, &sent.id, &cards).await;
62 if attached {
60 63 let shown = match &image {
61 64 Some(image) => AnnouncementBanner {
62 65 title: banner.title.clone(),
@@ -67,14 +70,34 @@ impl<R: Remote> SyncEngine<R> {
67 70 sent.attachments
68 71 .insert(0, shown.attachment(format!("announcement-card-{}", sent.id)));
69 72 }
70 self.cache_sent(channel_id, &sent, &html, extras)
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
71 94 }
72 95
73 96 async fn upload_banner_image(&self, channel_id: &str, path: &str) -> Result<TeamsBannerImage> {
74 97 let bytes = std::fs::read(path)
75 .map_err(|_| Error::Unsupported("a banner image that is no longer on disk"))?;
98 .map_err(|_| Error::BannerImage("the picked file is gone"))?;
76 99 let (width, height) =
77 png_size(&bytes).ok_or(Error::Unsupported("a banner image that is not a PNG"))?;
100 png_size(&bytes).ok_or(Error::BannerImage("not a PNG"))?;
78 101 let uploaded = self
79 102 .remote
80 103 .upload_ams_image(channel_id, &bytes, BANNER_FILE_NAME)
@@ -1,3 +1,5 @@
1use std::time::Duration;
2
1use chatsvc::ConversationRef;
3use chatsvc::ConversationRef;
2use graph::MessageExtras;
4use graph::MessageExtras;
3use store::MessageRecord;
5use store::MessageRecord;
@@ -11,6 +13,11 @@ use crate::remote::Remote;
11
13
12const BANNER_FILE_NAME: &str = "MicrosoftTeams-image.png";
14const BANNER_FILE_NAME: &str = "MicrosoftTeams-image.png";
13const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
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];
14
21
15fn png_size(bytes: &[u8]) -> Option<(u32, u32)> {
22fn png_size(bytes: &[u8]) -> Option<(u32, u32)> {
16 if !bytes.starts_with(PNG_SIGNATURE) || bytes.get(12..16)? != b"IHDR" {
23 if !bytes.starts_with(PNG_SIGNATURE) || bytes.get(12..16)? != b"IHDR" {
@@ -51,12 +58,8 @@ impl<R: Remote> SyncEngine<R> {
51 let target = ConversationRef::ChannelRoot {
58 let target = ConversationRef::ChannelRoot {
52 channel_id: channel_id.to_owned(),
59 channel_id: channel_id.to_owned(),
53 };
60 };
54 if self
61 let attached = self.set_cards_with_retry(&target, &sent.id, &cards).await;
55 .remote
62 if attached {
56 .set_message_cards(&target, &sent.id, &cards)
57 .await
58 .is_ok()
59 {
60 let shown = match &image {
63 let shown = match &image {
61 Some(image) => AnnouncementBanner {
64 Some(image) => AnnouncementBanner {
62 title: banner.title.clone(),
65 title: banner.title.clone(),
@@ -67,14 +70,34 @@ impl<R: Remote> SyncEngine<R> {
67 sent.attachments
70 sent.attachments
68 .insert(0, shown.attachment(format!("announcement-card-{}", sent.id)));
71 .insert(0, shown.attachment(format!("announcement-card-{}", sent.id)));
69 }
72 }
70 self.cache_sent(channel_id, &sent, &html, extras)
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
71 }
94 }
72
95
73 async fn upload_banner_image(&self, channel_id: &str, path: &str) -> Result<TeamsBannerImage> {
96 async fn upload_banner_image(&self, channel_id: &str, path: &str) -> Result<TeamsBannerImage> {
74 let bytes = std::fs::read(path)
97 let bytes = std::fs::read(path)
75 .map_err(|_| Error::Unsupported("a banner image that is no longer on disk"))?;
98 .map_err(|_| Error::BannerImage("the picked file is gone"))?;
76 let (width, height) =
99 let (width, height) =
77 png_size(&bytes).ok_or(Error::Unsupported("a banner image that is not a PNG"))?;
100 png_size(&bytes).ok_or(Error::BannerImage("not a PNG"))?;
78 let uploaded = self
101 let uploaded = self
79 .remote
102 .remote
80 .upload_ams_image(channel_id, &bytes, BANNER_FILE_NAME)
103 .upload_ams_image(channel_id, &bytes, BANNER_FILE_NAME)
crates/core/src/error.rs +5 −0
@@ -16,6 +16,11 @@ pub enum Error {
16 16 GifsDisabled,
17 17 #[error("{0} is not supported yet")]
18 18 Unsupported(&'static str),
19 #[error("banner image: {0}")]
20 BannerImage(&'static str),
21 /// The post is out; only its banner card could not be set.
22 #[error("posted without the banner")]
23 PostedWithoutBanner,
19 24 }
20 25
21 26 impl From<chatsvc::Error> for Error {
@@ -16,6 +16,11 @@ pub enum Error {
16 GifsDisabled,
16 GifsDisabled,
17 #[error("{0} is not supported yet")]
17 #[error("{0} is not supported yet")]
18 Unsupported(&'static str),
18 Unsupported(&'static str),
19 #[error("banner image: {0}")]
20 BannerImage(&'static str),
21 /// The post is out; only its banner card could not be set.
22 #[error("posted without the banner")]
23 PostedWithoutBanner,
19}
24}
20
25
21impl From<chatsvc::Error> for Error {
26impl From<chatsvc::Error> for Error {
crates/core/tests/engine.rs +23 −0
@@ -92,6 +92,7 @@ struct Fake {
92 92 channel_pages: Mutex<Vec<Vec<Message>>>,
93 93 teams: Mutex<Vec<Team>>,
94 94 failing_team: Mutex<Option<String>>,
95 failing_cards: Mutex<bool>,
95 96 sent: Mutex<Vec<String>>,
96 97 chat_calls: Mutex<usize>,
97 98 chat_page_calls: Mutex<usize>,
@@ -567,6 +568,9 @@ impl Remote for Handle {
567 568 "cards {} {message_id} {cards}",
568 569 conversation.conversation_id()
569 570 ));
571 if *self.failing_cards.lock().unwrap() {
572 return Err(teams_core::Error::Folders("cards refused".to_owned()));
573 }
570 574 Ok(())
571 575 }
572 576
@@ -2185,6 +2189,25 @@ async fn an_announcement_posts_through_graph_then_adds_the_banner_card() {
2185 2189 );
2186 2190 }
2187 2191
2192 #[tokio::test]
2193 async fn a_refused_banner_card_still_keeps_the_post() {
2194 let fake = Arc::new(Fake::default());
2195 *fake.failing_cards.lock().unwrap() = true;
2196 let engine = channel_engine(&fake).await;
2197 let banner = teams_core::AnnouncementBanner {
2198 title: "Ship it".to_owned(),
2199 background: teams_core::BannerBackground::Color("rose".to_owned()),
2200 };
2201 let posted = engine
2202 .post_announcement(CHANNEL, "<p>hi</p>", None, &[], &MessageExtras::default(), &banner)
2203 .await;
2204 assert!(matches!(posted, Err(teams_core::Error::PostedWithoutBanner)));
2205 let tries = fake.calls().iter().filter(|call| call.starts_with("cards ")).count();
2206 assert_eq!(tries, 3);
2207 let cached = engine.store().messages(CHANNEL, None, 10).unwrap();
2208 assert!(cached.iter().any(|record| record.message_id == "m9001"));
2209 }
2210
2188 2211 #[tokio::test]
2189 2212 async fn channel_sends_post_and_reply_through_graph() {
2190 2213 let fake = Arc::new(Fake::default());
@@ -92,6 +92,7 @@ struct Fake {
92 channel_pages: Mutex<Vec<Vec<Message>>>,
92 channel_pages: Mutex<Vec<Vec<Message>>>,
93 teams: Mutex<Vec<Team>>,
93 teams: Mutex<Vec<Team>>,
94 failing_team: Mutex<Option<String>>,
94 failing_team: Mutex<Option<String>>,
95 failing_cards: Mutex<bool>,
95 sent: Mutex<Vec<String>>,
96 sent: Mutex<Vec<String>>,
96 chat_calls: Mutex<usize>,
97 chat_calls: Mutex<usize>,
97 chat_page_calls: Mutex<usize>,
98 chat_page_calls: Mutex<usize>,
@@ -567,6 +568,9 @@ impl Remote for Handle {
567 "cards {} {message_id} {cards}",
568 "cards {} {message_id} {cards}",
568 conversation.conversation_id()
569 conversation.conversation_id()
569 ));
570 ));
571 if *self.failing_cards.lock().unwrap() {
572 return Err(teams_core::Error::Folders("cards refused".to_owned()));
573 }
570 Ok(())
574 Ok(())
571 }
575 }
572
576
@@ -2185,6 +2189,25 @@ async fn an_announcement_posts_through_graph_then_adds_the_banner_card() {
2185 );
2189 );
2186}
2190}
2187
2191
2192#[tokio::test]
2193async fn a_refused_banner_card_still_keeps_the_post() {
2194 let fake = Arc::new(Fake::default());
2195 *fake.failing_cards.lock().unwrap() = true;
2196 let engine = channel_engine(&fake).await;
2197 let banner = teams_core::AnnouncementBanner {
2198 title: "Ship it".to_owned(),
2199 background: teams_core::BannerBackground::Color("rose".to_owned()),
2200 };
2201 let posted = engine
2202 .post_announcement(CHANNEL, "<p>hi</p>", None, &[], &MessageExtras::default(), &banner)
2203 .await;
2204 assert!(matches!(posted, Err(teams_core::Error::PostedWithoutBanner)));
2205 let tries = fake.calls().iter().filter(|call| call.starts_with("cards ")).count();
2206 assert_eq!(tries, 3);
2207 let cached = engine.store().messages(CHANNEL, None, 10).unwrap();
2208 assert!(cached.iter().any(|record| record.message_id == "m9001"));
2209}
2210
2188#[tokio::test]
2211#[tokio::test]
2189async fn channel_sends_post_and_reply_through_graph() {
2212async fn channel_sends_post_and_reply_through_graph() {
2190 let fake = Arc::new(Fake::default());
2213 let fake = Arc::new(Fake::default());