feat(posts): announcement banner with own image, sent the way Teams web does
- Graph refuses the banner card from a user token (teamsAppId 403), so the post goes out plain and the chat service sets the cards property - color themes as Teams web indexes, uploaded image via AMS (skype_token, x-ms-client-version) - composer: image swatch picks a picture, cropped and scaled to 1317x366 PNG - skype token page script no longer redeclares cache (fixed channel pins over CSA) - endpoint guard allows the account link and the demo join link Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -0,0 +1,53 @@
1
use std::path::{Path, PathBuf};
2
3
use image::imageops::FilterType;
4
use uuid::Uuid;
5
6
/// Teams web crops announcement backgrounds to this size.
7
pub const BANNER_IMAGE_WIDTH: u32 = 1317;
8
pub const BANNER_IMAGE_HEIGHT: u32 = 366;
9
const BANNER_DIRECTORY: &str = "banners";
10
11
/// The centered box with the banner's aspect ratio: `(x, y, width, height)`.
12
pub fn crop_box(width: u32, height: u32) -> (u32, u32, u32, u32) {
13
let wanted_height = (u64::from(width) * u64::from(BANNER_IMAGE_HEIGHT) / u64::from(BANNER_IMAGE_WIDTH)) as u32;
14
if wanted_height <= height {
15
(0, (height - wanted_height) / 2, width, wanted_height.max(1))
16
} else {
17
let wanted_width = (u64::from(height) * u64::from(BANNER_IMAGE_WIDTH) / u64::from(BANNER_IMAGE_HEIGHT)) as u32;
18
((width - wanted_width) / 2, 0, wanted_width.max(1), height)
19
}
20
}
21
22
/// Crops and scales `source` to the banner size and saves it as a PNG under the app data folder.
23
pub fn prepare_banner_image(source: &Path) -> Result<PathBuf, String> {
24
let picked = image::open(source).map_err(|error| error.to_string())?;
25
let (x, y, width, height) = crop_box(picked.width(), picked.height());
26
let banner = picked.crop_imm(x, y, width, height).resize_exact(
27
BANNER_IMAGE_WIDTH,
28
BANNER_IMAGE_HEIGHT,
29
FilterType::Triangle,
30
);
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")?;
34
std::fs::create_dir_all(&directory).map_err(|error| error.to_string())?;
35
let target = directory.join(format!("{}.png", Uuid::new_v4().simple()));
36
banner
37
.to_rgb8()
38
.save_with_format(&target, image::ImageFormat::Png)
39
.map_err(|error| error.to_string())?;
40
Ok(target)
41
}
42
43
#[cfg(test)]
44
mod tests {
45
use super::crop_box;
46
47
#[test]
48
fn crop_keeps_the_middle_band_of_a_tall_or_wide_picture() {
49
assert_eq!(crop_box(1317, 1000), (0, 317, 1317, 366));
50
assert_eq!(crop_box(4000, 366), (1341, 0, 1317, 366));
51
assert_eq!(crop_box(1317, 366), (0, 0, 1317, 366));
52
}
53
}
@@ -0,0 +1,53 @@1
use std::path::{Path, PathBuf};2
3
use image::imageops::FilterType;4
use uuid::Uuid;5
6
/// Teams web crops announcement backgrounds to this size.7
pub const BANNER_IMAGE_WIDTH: u32 = 1317;8
pub const BANNER_IMAGE_HEIGHT: u32 = 366;9
const BANNER_DIRECTORY: &str = "banners";10
11
/// The centered box with the banner's aspect ratio: `(x, y, width, height)`.12
pub fn crop_box(width: u32, height: u32) -> (u32, u32, u32, u32) {13
let wanted_height = (u64::from(width) * u64::from(BANNER_IMAGE_HEIGHT) / u64::from(BANNER_IMAGE_WIDTH)) as u32;14
if wanted_height <= height {15
(0, (height - wanted_height) / 2, width, wanted_height.max(1))16
} else {17
let wanted_width = (u64::from(height) * u64::from(BANNER_IMAGE_WIDTH) / u64::from(BANNER_IMAGE_HEIGHT)) as u32;18
((width - wanted_width) / 2, 0, wanted_width.max(1), height)19
}20
}21
22
/// Crops and scales `source` to the banner size and saves it as a PNG under the app data folder.23
pub fn prepare_banner_image(source: &Path) -> Result<PathBuf, String> {24
let picked = image::open(source).map_err(|error| error.to_string())?;25
let (x, y, width, height) = crop_box(picked.width(), picked.height());26
let banner = picked.crop_imm(x, y, width, height).resize_exact(27
BANNER_IMAGE_WIDTH,28
BANNER_IMAGE_HEIGHT,29
FilterType::Triangle,30
);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")?;34
std::fs::create_dir_all(&directory).map_err(|error| error.to_string())?;35
let target = directory.join(format!("{}.png", Uuid::new_v4().simple()));36
banner37
.to_rgb8()38
.save_with_format(&target, image::ImageFormat::Png)39
.map_err(|error| error.to_string())?;40
Ok(target)41
}42
43
#[cfg(test)]44
mod tests {45
use super::crop_box;46
47
#[test]48
fn crop_keeps_the_middle_band_of_a_tall_or_wide_picture() {49
assert_eq!(crop_box(1317, 1000), (0, 317, 1317, 366));50
assert_eq!(crop_box(4000, 366), (1341, 0, 1317, 366));51
assert_eq!(crop_box(1317, 366), (0, 0, 1317, 366));52
}53
}@@ -1,4 +1,5 @@
1
1
pub mod activity;
2
pub mod banner_image;
2
3
pub mod agent_api;
3
4
pub mod agents;
4
5
pub mod app_state;
@@ -1,4 +1,5 @@1
pub mod activity;1
pub mod activity;2
pub mod banner_image;2
pub mod agent_api;3
pub mod agent_api;3
pub mod agents;4
pub mod agents;4
pub mod app_state;5
pub mod app_state;@@ -72,17 +72,31 @@ pub async fn deliver(
72
72
.send_message_with_extras(conversation_id, &html, None, mentions, &extras)
73
73
.await
74
74
}
75
(OutboxTarget::Post, None) => {
76
engine
77
.post_to_channel_with_extras(
78
conversation_id,
79
&html,
80
outgoing.subject.as_deref(),
81
mentions,
82
&extras,
83
)
84
.await
85
}
75
(OutboxTarget::Post, None) => match &outgoing.banner {
76
Some(banner) => {
77
engine
78
.post_announcement(
79
conversation_id,
80
&html,
81
outgoing.subject.as_deref(),
82
mentions,
83
&extras,
84
banner,
85
)
86
.await
87
}
88
None => {
89
engine
90
.post_to_channel_with_extras(
91
conversation_id,
92
&html,
93
outgoing.subject.as_deref(),
94
mentions,
95
&extras,
96
)
97
.await
98
}
99
},
86
100
(OutboxTarget::Thread, None) => {
87
101
engine
88
102
.send_message_with_extras(conversation_id, &html, thread_root_id, mentions, &extras)
@@ -72,17 +72,31 @@ pub async fn deliver(72
.send_message_with_extras(conversation_id, &html, None, mentions, &extras)72
.send_message_with_extras(conversation_id, &html, None, mentions, &extras)73
.await73
.await74
}74
}75
(OutboxTarget::Post, None) => {75
(OutboxTarget::Post, None) => match &outgoing.banner {76
engine76
Some(banner) => {77
.post_to_channel_with_extras(77
engine78
conversation_id,78
.post_announcement(79
&html,79
conversation_id,80
outgoing.subject.as_deref(),80
&html,81
mentions,81
outgoing.subject.as_deref(),82
&extras,82
mentions,83
)83
&extras,84
.await84
banner,85
}85
)86
.await87
}88
None => {89
engine90
.post_to_channel_with_extras(91
conversation_id,92
&html,93
outgoing.subject.as_deref(),94
mentions,95
&extras,96
)97
.await98
}99
},86
(OutboxTarget::Thread, None) => {100
(OutboxTarget::Thread, None) => {87
engine101
engine88
.send_message_with_extras(conversation_id, &html, thread_root_id, mentions, &extras)102
.send_message_with_extras(conversation_id, &html, thread_root_id, mentions, &extras)@@ -10,7 +10,6 @@ use teams_core::{
10
10
};
11
11
12
12
use store::MessageImportance;
13
use uuid::Uuid;
14
13
15
14
use crate::remote_image::RemoteImage;
16
15
@@ -102,11 +101,7 @@ impl Outgoing {
102
101
pub fn extras(&self) -> MessageExtras {
103
102
MessageExtras {
104
103
importance: self.importance.stored(),
105
kept: self
106
.banner
107
.iter()
108
.map(|banner| banner.attachment(format!("announcement-card-{}", Uuid::new_v4().simple())))
109
.collect(),
104
kept: Vec::new(),
110
105
images: self
111
106
.images
112
107
.iter()
@@ -10,7 +10,6 @@ use teams_core::{10
};10
};11
11
12
use store::MessageImportance;12
use store::MessageImportance;13
use uuid::Uuid;14
13
15
use crate::remote_image::RemoteImage;14
use crate::remote_image::RemoteImage;16
15
@@ -102,11 +101,7 @@ impl Outgoing {102
pub fn extras(&self) -> MessageExtras {101
pub fn extras(&self) -> MessageExtras {103
MessageExtras {102
MessageExtras {104
importance: self.importance.stored(),103
importance: self.importance.stored(),105
kept: self104
kept: Vec::new(),106
.banner107
.iter()108
.map(|banner| banner.attachment(format!("announcement-card-{}", Uuid::new_v4().simple())))109
.collect(),110
images: self105
images: self111
.images106
.images112
.iter()107
.iter()@@ -242,13 +242,10 @@ mod tests {
242
242
}
243
243
244
244
#[test]
245
fn an_announcement_is_sent_as_a_banner_attachment_first() {
245
fn an_announcement_stays_out_of_the_graph_body() {
246
246
let extras = outgoing().extras();
247
let banner = &extras.kept[0];
248
assert!(banner.id.starts_with("announcement-card-"));
249
assert_eq!(banner.content_type.as_deref(), Some(teams_core::ANNOUNCEMENT_BANNER_TYPE));
250
assert_eq!(banner.teams_app_id.as_deref(), Some(teams_core::ANNOUNCEMENT_APP_ID));
251
assert!(extras.kept_html().starts_with("<attachment id=\"announcement-card-"));
247
assert!(extras.kept.is_empty());
248
assert_eq!(extras.kept_html(), "");
252
249
}
253
250
254
251
#[test]
@@ -242,13 +242,10 @@ mod tests {242
}242
}243
243
244
#[test]244
#[test]245
fn an_announcement_is_sent_as_a_banner_attachment_first() {245
fn an_announcement_stays_out_of_the_graph_body() {246
let extras = outgoing().extras();246
let extras = outgoing().extras();247
let banner = &extras.kept[0];247
assert!(extras.kept.is_empty());248
assert!(banner.id.starts_with("announcement-card-"));248
assert_eq!(extras.kept_html(), "");249
assert_eq!(banner.content_type.as_deref(), Some(teams_core::ANNOUNCEMENT_BANNER_TYPE));250
assert_eq!(banner.teams_app_id.as_deref(), Some(teams_core::ANNOUNCEMENT_APP_ID));251
assert!(extras.kept_html().starts_with("<attachment id=\"announcement-card-"));252
}249
}253
250
254
#[test]251
#[test]@@ -49,6 +49,16 @@ pub fn banner_frame(background: &BannerBackground, directory: &Directory) -> Div
49
49
.overflow_hidden();
50
50
match background {
51
51
BannerBackground::Color(color) => frame.bg(banner_fill(color)),
52
BannerBackground::LocalImage(path) => frame
53
.bg(banner_fill(""))
54
.child(
55
img(std::path::PathBuf::from(path))
56
.absolute()
57
.inset_0()
58
.size_full()
59
.object_fit(ObjectFit::Cover),
60
)
61
.child(div().absolute().inset_0().bg(black().opacity(IMAGE_SHADE))),
52
62
BannerBackground::Image(url) => {
53
63
let frame = frame.bg(banner_fill(""));
54
64
match directory.image(url) {
@@ -49,6 +49,16 @@ pub fn banner_frame(background: &BannerBackground, directory: &Directory) -> Div49
.overflow_hidden();49
.overflow_hidden();50
match background {50
match background {51
BannerBackground::Color(color) => frame.bg(banner_fill(color)),51
BannerBackground::Color(color) => frame.bg(banner_fill(color)),52
BannerBackground::LocalImage(path) => frame53
.bg(banner_fill(""))54
.child(55
img(std::path::PathBuf::from(path))56
.absolute()57
.inset_0()58
.size_full()59
.object_fit(ObjectFit::Cover),60
)61
.child(div().absolute().inset_0().bg(black().opacity(IMAGE_SHADE))),52
BannerBackground::Image(url) => {62
BannerBackground::Image(url) => {53
let frame = frame.bg(banner_fill(""));63
let frame = frame.bg(banner_fill(""));54
match directory.image(url) {64
match directory.image(url) {@@ -4,6 +4,7 @@ use gpui_kit::component::{Sizable as _, Size, h_flex, v_flex};
4
4
use gpui_kit::prelude::FluentBuilder as _;
5
5
use gpui_kit::*;
6
6
7
use crate::banner_image::prepare_banner_image;
7
8
use teams_core::{AnnouncementBanner, BannerBackground};
8
9
9
10
use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer, ComposerEvent};
@@ -26,6 +27,7 @@ pub const POST_AUDIENCE_TAG: &str = "composer/post/audience";
26
27
const DEMO_AUDIENCE: usize = 24;
27
28
const AUDIENCE_HEIGHT: f32 = 32.;
28
29
const ANNOUNCEMENT_TOOLTIP: &str = "Announcement";
30
const BANNER_IMAGE_TOOLTIP: &str = "Upload an image";
29
31
const HEADLINE_PLACEHOLDER: &str = "Type a headline";
30
32
pub const SUBJECT_PLACEHOLDER: &str = "Add a subject";
31
33
const SUBHEADING_PLACEHOLDER: &str = "Add a subheading";
@@ -48,9 +50,19 @@ const TEXT_INSET: f32 = 16.;
48
50
pub(super) struct AnnouncementDraft {
49
51
pub(super) headline: Entity<InputState>,
50
52
color: &'static str,
53
image: Option<String>,
51
54
_changes: Subscription,
52
55
}
53
56
57
impl AnnouncementDraft {
58
fn background(&self) -> BannerBackground {
59
match &self.image {
60
Some(path) => BannerBackground::LocalImage(path.clone()),
61
None => BannerBackground::Color(self.color.to_owned()),
62
}
63
}
64
}
65
54
66
pub fn audience_hint(count: usize) -> String {
55
67
match count {
56
68
1 => "1 person will see your message.".to_owned(),
@@ -96,7 +108,7 @@ impl Composer {
96
108
let title = draft.headline.read(cx).value().trim().to_owned();
97
109
(!title.is_empty()).then(|| AnnouncementBanner {
98
110
title,
99
background: BannerBackground::Color(draft.color.to_owned()),
111
background: draft.background(),
100
112
})
101
113
}
102
114
@@ -113,10 +125,15 @@ impl Composer {
113
125
.into_iter()
114
126
.find(|known| known == color)
115
127
.unwrap_or(BANNER_COLORS[0]),
116
BannerBackground::Image(_) => BANNER_COLORS[0],
128
BannerBackground::Image(_) | BannerBackground::LocalImage(_) => {
129
BANNER_COLORS[0]
130
}
117
131
};
118
132
self.open_announcement(color, window, cx);
119
if let Some(draft) = &self.announcement {
133
if let Some(draft) = self.announcement.as_mut() {
134
if let BannerBackground::LocalImage(path) = &banner.background {
135
draft.image = Some(path.clone());
136
}
120
137
let title = banner.title.clone();
121
138
draft
122
139
.headline
@@ -156,6 +173,7 @@ impl Composer {
156
173
self.announcement = Some(AnnouncementDraft {
157
174
headline,
158
175
color,
176
image: None,
159
177
_changes: changes,
160
178
});
161
179
self.set_subject_placeholder(SUBHEADING_PLACEHOLDER, window, cx);
@@ -164,6 +182,39 @@ impl Composer {
164
182
cx.notify();
165
183
}
166
184
185
fn pick_banner_image(&mut self, window: &mut Window, cx: &mut Context<Self>) {
186
let receiver = cx.prompt_for_paths(PathPromptOptions {
187
files: true,
188
directories: false,
189
multiple: false,
190
prompt: None,
191
});
192
cx.spawn_in(window, async move |this, cx| {
193
let Ok(Ok(Some(paths))) = receiver.await else {
194
return;
195
};
196
let Some(source) = paths.into_iter().next() else {
197
return;
198
};
199
let prepared = cx
200
.background_executor()
201
.spawn(async move { prepare_banner_image(&source) })
202
.await;
203
this.update(cx, |this, cx| match prepared {
204
Ok(path) => {
205
if let Some(draft) = this.announcement.as_mut() {
206
draft.image = Some(path.to_string_lossy().into_owned());
207
this.schedule_draft_save(cx);
208
cx.notify();
209
}
210
}
211
Err(error) => log::warn!("banner image: {error}"),
212
})
213
.ok();
214
})
215
.detach();
216
}
217
167
218
pub(super) fn close_announcement(&mut self, window: &mut Window, cx: &mut Context<Self>) {
168
219
if self.announcement.take().is_some() {
169
220
self.set_subject_placeholder(SUBJECT_PLACEHOLDER, window, cx);
@@ -297,7 +348,7 @@ impl Composer {
297
348
.bottom(px(SWATCH_INSET))
298
349
.gap(px(SWATCH_GAP))
299
350
.children(BANNER_COLORS.into_iter().map(|color| {
300
let selected = color == draft.color;
351
let selected = color == draft.color && draft.image.is_none();
301
352
div()
302
353
.id(ElementId::Name(format!("composer-banner-{color}").into()))
303
354
.size(px(SWATCH_SIZE))
@@ -314,11 +365,33 @@ impl Composer {
314
365
.on_click(cx.listener(move |this, _, _, cx| {
315
366
if let Some(draft) = this.announcement.as_mut() {
316
367
draft.color = color;
368
draft.image = None;
317
369
this.schedule_draft_save(cx);
318
370
cx.notify();
319
371
}
320
372
}))
321
}));
373
}))
374
.child({
375
let selected = draft.image.is_some();
376
div()
377
.id("composer-banner-image")
378
.size(px(SWATCH_SIZE))
379
.flex()
380
.items_center()
381
.justify_center()
382
.rounded_full()
383
.border(px(SWATCH_RING))
384
.border_color(if selected {
385
white()
386
} else {
387
white().opacity(0.4)
388
})
389
.bg(black().opacity(0.35))
390
.cursor_pointer()
391
.tooltip(|window, cx| Tooltip::new(BANNER_IMAGE_TOOLTIP).build(window, cx))
392
.child(symbol("image", SWATCH_SIZE - 6., white()))
393
.on_click(cx.listener(|this, _, window, cx| this.pick_banner_image(window, cx)))
394
});
322
395
Some(
323
396
div()
324
397
.debug_selector(|| POST_ANNOUNCEMENT_TAG.into())
@@ -326,7 +399,7 @@ impl Composer {
326
399
.px(px(CARD_INSET))
327
400
.pt(px(CARD_INSET))
328
401
.child(
329
banner_frame(&BannerBackground::Color(draft.color.to_owned()), directory)
402
banner_frame(&draft.background(), directory)
330
403
.h(px(COMPOSER_BANNER_HEIGHT))
331
404
.child(
332
405
headline_style(div().w_full()).child(
@@ -4,6 +4,7 @@ use gpui_kit::component::{Sizable as _, Size, h_flex, v_flex};4
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::prelude::FluentBuilder as _;5
use gpui_kit::*;5
use gpui_kit::*;6
6
7
use crate::banner_image::prepare_banner_image;7
use teams_core::{AnnouncementBanner, BannerBackground};8
use teams_core::{AnnouncementBanner, BannerBackground};8
9
9
use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer, ComposerEvent};10
use super::{COMPOSER_BUTTON_SIZE, COMPOSER_ICON_SIZE, Composer, ComposerEvent};@@ -26,6 +27,7 @@ pub const POST_AUDIENCE_TAG: &str = "composer/post/audience";26
const DEMO_AUDIENCE: usize = 24;27
const DEMO_AUDIENCE: usize = 24;27
const AUDIENCE_HEIGHT: f32 = 32.;28
const AUDIENCE_HEIGHT: f32 = 32.;28
const ANNOUNCEMENT_TOOLTIP: &str = "Announcement";29
const ANNOUNCEMENT_TOOLTIP: &str = "Announcement";30
const BANNER_IMAGE_TOOLTIP: &str = "Upload an image";29
const HEADLINE_PLACEHOLDER: &str = "Type a headline";31
const HEADLINE_PLACEHOLDER: &str = "Type a headline";30
pub const SUBJECT_PLACEHOLDER: &str = "Add a subject";32
pub const SUBJECT_PLACEHOLDER: &str = "Add a subject";31
const SUBHEADING_PLACEHOLDER: &str = "Add a subheading";33
const SUBHEADING_PLACEHOLDER: &str = "Add a subheading";@@ -48,9 +50,19 @@ const TEXT_INSET: f32 = 16.;48
pub(super) struct AnnouncementDraft {50
pub(super) struct AnnouncementDraft {49
pub(super) headline: Entity<InputState>,51
pub(super) headline: Entity<InputState>,50
color: &'static str,52
color: &'static str,53
image: Option<String>,51
_changes: Subscription,54
_changes: Subscription,52
}55
}53
56
57
impl AnnouncementDraft {58
fn background(&self) -> BannerBackground {59
match &self.image {60
Some(path) => BannerBackground::LocalImage(path.clone()),61
None => BannerBackground::Color(self.color.to_owned()),62
}63
}64
}65
54
pub fn audience_hint(count: usize) -> String {66
pub fn audience_hint(count: usize) -> String {55
match count {67
match count {56
1 => "1 person will see your message.".to_owned(),68
1 => "1 person will see your message.".to_owned(),@@ -96,7 +108,7 @@ impl Composer {96
let title = draft.headline.read(cx).value().trim().to_owned();108
let title = draft.headline.read(cx).value().trim().to_owned();97
(!title.is_empty()).then(|| AnnouncementBanner {109
(!title.is_empty()).then(|| AnnouncementBanner {98
title,110
title,99
background: BannerBackground::Color(draft.color.to_owned()),111
background: draft.background(),100
})112
})101
}113
}102
114
@@ -113,10 +125,15 @@ impl Composer {113
.into_iter()125
.into_iter()114
.find(|known| known == color)126
.find(|known| known == color)115
.unwrap_or(BANNER_COLORS[0]),127
.unwrap_or(BANNER_COLORS[0]),116
BannerBackground::Image(_) => BANNER_COLORS[0],128
BannerBackground::Image(_) | BannerBackground::LocalImage(_) => {129
BANNER_COLORS[0]130
}117
};131
};118
self.open_announcement(color, window, cx);132
self.open_announcement(color, window, cx);119
if let Some(draft) = &self.announcement {133
if let Some(draft) = self.announcement.as_mut() {134
if let BannerBackground::LocalImage(path) = &banner.background {135
draft.image = Some(path.clone());136
}120
let title = banner.title.clone();137
let title = banner.title.clone();121
draft138
draft122
.headline139
.headline@@ -156,6 +173,7 @@ impl Composer {156
self.announcement = Some(AnnouncementDraft {173
self.announcement = Some(AnnouncementDraft {157
headline,174
headline,158
color,175
color,176
image: None,159
_changes: changes,177
_changes: changes,160
});178
});161
self.set_subject_placeholder(SUBHEADING_PLACEHOLDER, window, cx);179
self.set_subject_placeholder(SUBHEADING_PLACEHOLDER, window, cx);@@ -164,6 +182,39 @@ impl Composer {164
cx.notify();182
cx.notify();165
}183
}166
184
185
fn pick_banner_image(&mut self, window: &mut Window, cx: &mut Context<Self>) {186
let receiver = cx.prompt_for_paths(PathPromptOptions {187
files: true,188
directories: false,189
multiple: false,190
prompt: None,191
});192
cx.spawn_in(window, async move |this, cx| {193
let Ok(Ok(Some(paths))) = receiver.await else {194
return;195
};196
let Some(source) = paths.into_iter().next() else {197
return;198
};199
let prepared = cx200
.background_executor()201
.spawn(async move { prepare_banner_image(&source) })202
.await;203
this.update(cx, |this, cx| match prepared {204
Ok(path) => {205
if let Some(draft) = this.announcement.as_mut() {206
draft.image = Some(path.to_string_lossy().into_owned());207
this.schedule_draft_save(cx);208
cx.notify();209
}210
}211
Err(error) => log::warn!("banner image: {error}"),212
})213
.ok();214
})215
.detach();216
}217
167
pub(super) fn close_announcement(&mut self, window: &mut Window, cx: &mut Context<Self>) {218
pub(super) fn close_announcement(&mut self, window: &mut Window, cx: &mut Context<Self>) {168
if self.announcement.take().is_some() {219
if self.announcement.take().is_some() {169
self.set_subject_placeholder(SUBJECT_PLACEHOLDER, window, cx);220
self.set_subject_placeholder(SUBJECT_PLACEHOLDER, window, cx);@@ -297,7 +348,7 @@ impl Composer {297
.bottom(px(SWATCH_INSET))348
.bottom(px(SWATCH_INSET))298
.gap(px(SWATCH_GAP))349
.gap(px(SWATCH_GAP))299
.children(BANNER_COLORS.into_iter().map(|color| {350
.children(BANNER_COLORS.into_iter().map(|color| {300
let selected = color == draft.color;351
let selected = color == draft.color && draft.image.is_none();301
div()352
div()302
.id(ElementId::Name(format!("composer-banner-{color}").into()))353
.id(ElementId::Name(format!("composer-banner-{color}").into()))303
.size(px(SWATCH_SIZE))354
.size(px(SWATCH_SIZE))@@ -314,11 +365,33 @@ impl Composer {314
.on_click(cx.listener(move |this, _, _, cx| {365
.on_click(cx.listener(move |this, _, _, cx| {315
if let Some(draft) = this.announcement.as_mut() {366
if let Some(draft) = this.announcement.as_mut() {316
draft.color = color;367
draft.color = color;368
draft.image = None;317
this.schedule_draft_save(cx);369
this.schedule_draft_save(cx);318
cx.notify();370
cx.notify();319
}371
}320
}))372
}))321
}));373
}))374
.child({375
let selected = draft.image.is_some();376
div()377
.id("composer-banner-image")378
.size(px(SWATCH_SIZE))379
.flex()380
.items_center()381
.justify_center()382
.rounded_full()383
.border(px(SWATCH_RING))384
.border_color(if selected {385
white()386
} else {387
white().opacity(0.4)388
})389
.bg(black().opacity(0.35))390
.cursor_pointer()391
.tooltip(|window, cx| Tooltip::new(BANNER_IMAGE_TOOLTIP).build(window, cx))392
.child(symbol("image", SWATCH_SIZE - 6., white()))393
.on_click(cx.listener(|this, _, window, cx| this.pick_banner_image(window, cx)))394
});322
Some(395
Some(323
div()396
div()324
.debug_selector(|| POST_ANNOUNCEMENT_TAG.into())397
.debug_selector(|| POST_ANNOUNCEMENT_TAG.into())@@ -326,7 +399,7 @@ impl Composer {326
.px(px(CARD_INSET))399
.px(px(CARD_INSET))327
.pt(px(CARD_INSET))400
.pt(px(CARD_INSET))328
.child(401
.child(329
banner_frame(&BannerBackground::Color(draft.color.to_owned()), directory)402
banner_frame(&draft.background(), directory)330
.h(px(COMPOSER_BANNER_HEIGHT))403
.h(px(COMPOSER_BANNER_HEIGHT))331
.child(404
.child(332
headline_style(div().w_full()).child(405
headline_style(div().w_full()).child(@@ -0,0 +1,26 @@
1
const objects = args.base + 'v1/objects/';
2
const auth = {Authorization: 'skype_token ' + skypeCache.token, 'x-ms-client-version': '1415/1.0.0.2018090100'};
3
try {
4
const created = await fetch(objects, {
5
method: 'POST',
6
headers: {...auth, 'Content-Type': 'application/json', Accept: 'application/json'},
7
body: JSON.stringify({
8
type: 'pish/image',
9
permissions: {[args.conversationId]: ['read']},
10
sharingMode: 'Inline',
11
filename: args.filename,
12
}),
13
});
14
if (!created.ok) return {status: created.status, body: 'create_' + (await created.text()).slice(0, 300)};
15
const id = (await created.json()).id;
16
const bytes = Uint8Array.from(atob(args.base64), (character) => character.charCodeAt(0));
17
const stored = await fetch(objects + encodeURIComponent(id) + '/content/imgpsh', {
18
method: 'PUT',
19
headers: {...auth, 'Content-Type': 'application/octet-stream', 'Content-Range': `bytes 0-${bytes.length - 1}/${bytes.length}`},
20
body: bytes,
21
});
22
if (!stored.ok) return {status: stored.status, body: 'put_' + (await stored.text()).slice(0, 300)};
23
return {status: stored.status, body: {id}};
24
} catch (error) {
25
return {status: 0, body: String(error)};
26
}
@@ -0,0 +1,26 @@1
const objects = args.base + 'v1/objects/';2
const auth = {Authorization: 'skype_token ' + skypeCache.token, 'x-ms-client-version': '1415/1.0.0.2018090100'};3
try {4
const created = await fetch(objects, {5
method: 'POST',6
headers: {...auth, 'Content-Type': 'application/json', Accept: 'application/json'},7
body: JSON.stringify({8
type: 'pish/image',9
permissions: {[args.conversationId]: ['read']},10
sharingMode: 'Inline',11
filename: args.filename,12
}),13
});14
if (!created.ok) return {status: created.status, body: 'create_' + (await created.text()).slice(0, 300)};15
const id = (await created.json()).id;16
const bytes = Uint8Array.from(atob(args.base64), (character) => character.charCodeAt(0));17
const stored = await fetch(objects + encodeURIComponent(id) + '/content/imgpsh', {18
method: 'PUT',19
headers: {...auth, 'Content-Type': 'application/octet-stream', 'Content-Range': `bytes 0-${bytes.length - 1}/${bytes.length}`},20
body: bytes,21
});22
if (!stored.ok) return {status: stored.status, body: 'put_' + (await stored.text()).slice(0, 300)};23
return {status: stored.status, body: {id}};24
} catch (error) {25
return {status: 0, body: String(error)};26
}@@ -1,28 +1,5 @@
1
const cache = (window.__rustyTeamsSkype = window.__rustyTeamsSkype || {});
2
if (!cache.token || cache.expires <= Date.now() + 60000) {
3
const spaces = await acquire('https://api.spaces.skype.com', 'authorization.readwrite');
4
if (!spaces.token) return {status: 0, body: 'no token for authsvc'};
5
let response;
6
try {
7
response = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {
8
method: 'POST',
9
headers: {Authorization: 'Bearer ' + spaces.token},
10
});
11
} catch (error) {
12
return {status: 0, body: 'authz_unreachable'};
13
}
14
if (!response.ok) return {status: 0, body: 'authz_http_' + response.status};
15
try {
16
const answer = await response.json();
17
cache.token = answer.tokens.skypeToken;
18
cache.expires = Date.now() + Number(answer.tokens.expiresIn || 0) * 1000;
19
cache.chatService = answer.regionGtms.chatService;
20
} catch (error) {
21
return {status: 0, body: 'authz_shape'};
22
}
23
}
24
const headers = {...args.headers, Authorization: 'Bearer ' + token, 'x-skypetoken': cache.token};
25
if (cache.chatService) headers['x-csendpoint'] = cache.chatService;
1
const headers = {...args.headers, Authorization: 'Bearer ' + token, 'x-skypetoken': skypeCache.token};
2
if (skypeCache.chatService) headers['x-csendpoint'] = skypeCache.chatService;
26
3
try {
27
4
const response = await fetch(args.url, {
28
5
method: args.method,
@@ -1,28 +1,5 @@1
const cache = (window.__rustyTeamsSkype = window.__rustyTeamsSkype || {});1
const headers = {...args.headers, Authorization: 'Bearer ' + token, 'x-skypetoken': skypeCache.token};2
if (!cache.token || cache.expires <= Date.now() + 60000) {2
if (skypeCache.chatService) headers['x-csendpoint'] = skypeCache.chatService;3
const spaces = await acquire('https://api.spaces.skype.com', 'authorization.readwrite');4
if (!spaces.token) return {status: 0, body: 'no token for authsvc'};5
let response;6
try {7
response = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {8
method: 'POST',9
headers: {Authorization: 'Bearer ' + spaces.token},10
});11
} catch (error) {12
return {status: 0, body: 'authz_unreachable'};13
}14
if (!response.ok) return {status: 0, body: 'authz_http_' + response.status};15
try {16
const answer = await response.json();17
cache.token = answer.tokens.skypeToken;18
cache.expires = Date.now() + Number(answer.tokens.expiresIn || 0) * 1000;19
cache.chatService = answer.regionGtms.chatService;20
} catch (error) {21
return {status: 0, body: 'authz_shape'};22
}23
}24
const headers = {...args.headers, Authorization: 'Bearer ' + token, 'x-skypetoken': cache.token};25
if (cache.chatService) headers['x-csendpoint'] = cache.chatService;26
try {3
try {27
const response = await fetch(args.url, {4
const response = await fetch(args.url, {28
method: args.method,5
method: args.method,@@ -0,0 +1,23 @@
1
const skypeCache = (window.__rustyTeamsSkype = window.__rustyTeamsSkype || {});
2
if (!skypeCache.token || skypeCache.expires <= Date.now() + 60000) {
3
const spaces = await acquire('https://api.spaces.skype.com', 'authorization.readwrite');
4
if (!spaces.token) return {status: 0, body: 'no token for authsvc'};
5
let response;
6
try {
7
response = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {
8
method: 'POST',
9
headers: {Authorization: 'Bearer ' + spaces.token},
10
});
11
} catch (error) {
12
return {status: 0, body: 'authz_unreachable'};
13
}
14
if (!response.ok) return {status: 0, body: 'authz_http_' + response.status};
15
try {
16
const answer = await response.json();
17
skypeCache.token = answer.tokens.skypeToken;
18
skypeCache.expires = Date.now() + Number(answer.tokens.expiresIn || 0) * 1000;
19
skypeCache.chatService = answer.regionGtms.chatService;
20
} catch (error) {
21
return {status: 0, body: 'authz_shape'};
22
}
23
}
@@ -0,0 +1,23 @@1
const skypeCache = (window.__rustyTeamsSkype = window.__rustyTeamsSkype || {});2
if (!skypeCache.token || skypeCache.expires <= Date.now() + 60000) {3
const spaces = await acquire('https://api.spaces.skype.com', 'authorization.readwrite');4
if (!spaces.token) return {status: 0, body: 'no token for authsvc'};5
let response;6
try {7
response = await fetch('https://teams.cloud.microsoft/api/authsvc/v1.0/authz', {8
method: 'POST',9
headers: {Authorization: 'Bearer ' + spaces.token},10
});11
} catch (error) {12
return {status: 0, body: 'authz_unreachable'};13
}14
if (!response.ok) return {status: 0, body: 'authz_http_' + response.status};15
try {16
const answer = await response.json();17
skypeCache.token = answer.tokens.skypeToken;18
skypeCache.expires = Date.now() + Number(answer.tokens.expiresIn || 0) * 1000;19
skypeCache.chatService = answer.regionGtms.chatService;20
} catch (error) {21
return {status: 0, body: 'authz_shape'};22
}23
}@@ -0,0 +1,89 @@
1
use base64::Engine as _;
2
use base64::engine::general_purpose::STANDARD;
3
use serde_json::{Value, json};
4
use session::{App, Scope, Session};
5
6
use crate::error::{Error, Result};
7
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};
8
use crate::messages::ensure_success;
9
10
const AMS_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/";
11
const UPLOAD_BODY: &str = concat!(
12
include_str!("../assets/skype_token.js"),
13
include_str!("../assets/ams_upload.js")
14
);
15
const FULL_SIZE_VIEW: &str = "/views/imgpsh_fullsize";
16
17
#[derive(Debug, Clone, PartialEq, Eq)]
18
pub struct AmsImage {
19
pub object_id: String,
20
pub url: String,
21
}
22
23
pub fn full_size_url(object_id: &str) -> String {
24
format!("{AMS_BASE}v1/objects/{object_id}{FULL_SIZE_VIEW}")
25
}
26
27
fn uploaded_image(body: &Value) -> Result<AmsImage> {
28
let object_id = body
29
.get("id")
30
.and_then(Value::as_str)
31
.filter(|id| !id.is_empty() && id.chars().all(|character| character.is_ascii_alphanumeric() || character == '-'))
32
.ok_or_else(|| Error::UnexpectedAnswer("ams upload has no object id".into()))?;
33
Ok(AmsImage {
34
object_id: object_id.to_owned(),
35
url: full_size_url(object_id),
36
})
37
}
38
39
pub struct Ams {
40
session: Session,
41
}
42
43
impl Ams {
44
pub fn new(session: &Session) -> Self {
45
Ams {
46
session: session.clone(),
47
}
48
}
49
50
/// The image is readable by members of `conversation_id` only.
51
pub async fn upload_image(&self, conversation_id: &str, bytes: &[u8], filename: &str) -> Result<AmsImage> {
52
let arguments = json!({
53
"base": AMS_BASE,
54
"conversationId": conversation_id,
55
"filename": filename,
56
"base64": STANDARD.encode(bytes),
57
});
58
let answer = self
59
.session
60
.run_with_token(
61
App::Teams,
62
&Scope::new(CSA_RESOURCE, CSA_SCOPE),
63
UPLOAD_BODY,
64
&arguments,
65
false,
66
)
67
.await?;
68
let answer = skype_fetch_answer(answer);
69
ensure_success(&answer)?;
70
uploaded_image(&answer.body)
71
}
72
}
73
74
#[cfg(test)]
75
mod tests {
76
use super::*;
77
78
#[test]
79
fn an_uploaded_object_becomes_its_full_size_view() {
80
let image = uploaded_image(&json!({"id": "0-weu-d4-abc123"})).unwrap();
81
assert_eq!(image.object_id, "0-weu-d4-abc123");
82
assert_eq!(
83
image.url,
84
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d4-abc123/views/imgpsh_fullsize"
85
);
86
assert!(uploaded_image(&json!({"id": "../x"})).is_err());
87
assert!(uploaded_image(&json!({})).is_err());
88
}
89
}
@@ -0,0 +1,89 @@1
use base64::Engine as _;2
use base64::engine::general_purpose::STANDARD;3
use serde_json::{Value, json};4
use session::{App, Scope, Session};5
6
use crate::error::{Error, Result};7
use crate::pins::transport::{CSA_RESOURCE, CSA_SCOPE, skype_fetch_answer};8
use crate::messages::ensure_success;9
10
const AMS_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/";11
const UPLOAD_BODY: &str = concat!(12
include_str!("../assets/skype_token.js"),13
include_str!("../assets/ams_upload.js")14
);15
const FULL_SIZE_VIEW: &str = "/views/imgpsh_fullsize";16
17
#[derive(Debug, Clone, PartialEq, Eq)]18
pub struct AmsImage {19
pub object_id: String,20
pub url: String,21
}22
23
pub fn full_size_url(object_id: &str) -> String {24
format!("{AMS_BASE}v1/objects/{object_id}{FULL_SIZE_VIEW}")25
}26
27
fn uploaded_image(body: &Value) -> Result<AmsImage> {28
let object_id = body29
.get("id")30
.and_then(Value::as_str)31
.filter(|id| !id.is_empty() && id.chars().all(|character| character.is_ascii_alphanumeric() || character == '-'))32
.ok_or_else(|| Error::UnexpectedAnswer("ams upload has no object id".into()))?;33
Ok(AmsImage {34
object_id: object_id.to_owned(),35
url: full_size_url(object_id),36
})37
}38
39
pub struct Ams {40
session: Session,41
}42
43
impl Ams {44
pub fn new(session: &Session) -> Self {45
Ams {46
session: session.clone(),47
}48
}49
50
/// The image is readable by members of `conversation_id` only.51
pub async fn upload_image(&self, conversation_id: &str, bytes: &[u8], filename: &str) -> Result<AmsImage> {52
let arguments = json!({53
"base": AMS_BASE,54
"conversationId": conversation_id,55
"filename": filename,56
"base64": STANDARD.encode(bytes),57
});58
let answer = self59
.session60
.run_with_token(61
App::Teams,62
&Scope::new(CSA_RESOURCE, CSA_SCOPE),63
UPLOAD_BODY,64
&arguments,65
false,66
)67
.await?;68
let answer = skype_fetch_answer(answer);69
ensure_success(&answer)?;70
uploaded_image(&answer.body)71
}72
}73
74
#[cfg(test)]75
mod tests {76
use super::*;77
78
#[test]79
fn an_uploaded_object_becomes_its_full_size_view() {80
let image = uploaded_image(&json!({"id": "0-weu-d4-abc123"})).unwrap();81
assert_eq!(image.object_id, "0-weu-d4-abc123");82
assert_eq!(83
image.url,84
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-weu-d4-abc123/views/imgpsh_fullsize"85
);86
assert!(uploaded_image(&json!({"id": "../x"})).is_err());87
assert!(uploaded_image(&json!({})).is_err());88
}89
}@@ -1,4 +1,5 @@
1
1
pub mod activity_feed;
2
pub mod ams;
2
3
pub mod activity_mentions;
3
4
pub mod bot_profiles;
4
5
pub mod calendar;
@@ -1,4 +1,5 @@1
pub mod activity_feed;1
pub mod activity_feed;2
pub mod ams;2
pub mod activity_mentions;3
pub mod activity_mentions;3
pub mod bot_profiles;4
pub mod bot_profiles;4
pub mod calendar;5
pub mod calendar;@@ -151,6 +151,26 @@ impl<T: MessageTransport> Messages<T> {
151
151
ensure_success(&answer)
152
152
}
153
153
154
/// `cards` is the JSON text of the cards array; Teams web reads each card's `content` as an object.
155
pub async fn set_cards(
156
&self,
157
conversation: &ConversationRef,
158
message_id: &str,
159
cards: &str,
160
) -> Result<()> {
161
let url = format!(
162
"{}/properties?name=cards",
163
self.message_url(conversation, message_id)
164
);
165
let body = json!({ "cards": cards });
166
let mut answer = self.put(&url, &body).await?;
167
if answer.status == 404 {
168
tokio::time::sleep(self.retry_delay).await;
169
answer = self.put(&url, &body).await?;
170
}
171
ensure_success(&answer)
172
}
173
154
174
pub async fn soft_delete_message(
155
175
&self,
156
176
conversation: &ConversationRef,
@@ -151,6 +151,26 @@ impl<T: MessageTransport> Messages<T> {151
ensure_success(&answer)151
ensure_success(&answer)152
}152
}153
153
154
/// `cards` is the JSON text of the cards array; Teams web reads each card's `content` as an object.155
pub async fn set_cards(156
&self,157
conversation: &ConversationRef,158
message_id: &str,159
cards: &str,160
) -> Result<()> {161
let url = format!(162
"{}/properties?name=cards",163
self.message_url(conversation, message_id)164
);165
let body = json!({ "cards": cards });166
let mut answer = self.put(&url, &body).await?;167
if answer.status == 404 {168
tokio::time::sleep(self.retry_delay).await;169
answer = self.put(&url, &body).await?;170
}171
ensure_success(&answer)172
}173
154
pub async fn soft_delete_message(174
pub async fn soft_delete_message(155
&self,175
&self,156
conversation: &ConversationRef,176
conversation: &ConversationRef,@@ -5,7 +5,7 @@ mod pinbar;
5
5
mod posts;
6
6
mod state;
7
7
mod teams;
8
mod transport;
8
pub(crate) mod transport;
9
9
10
10
use session::Session;
11
11
@@ -5,7 +5,7 @@ mod pinbar;5
mod posts;5
mod posts;6
mod state;6
mod state;7
mod teams;7
mod teams;8
mod transport;8
pub(crate) mod transport;9
9
10
use session::Session;10
use session::Session;11
11
@@ -35,7 +35,10 @@ impl CsaTransport for SessionTransport {
35
35
}
36
36
}
37
37
38
const SKYPE_FETCH_BODY: &str = include_str!("../../assets/csa_skype_fetch.js");
38
const SKYPE_FETCH_BODY: &str = concat!(
39
include_str!("../../assets/skype_token.js"),
40
include_str!("../../assets/csa_skype_fetch.js")
41
);
39
42
40
43
/// Teams sends the skype token and the chat service endpoint next to the CSA bearer on the pinned post routes.
41
44
pub struct SkypeTokenTransport {
@@ -35,7 +35,10 @@ impl CsaTransport for SessionTransport {35
}35
}36
}36
}37
37
38
const SKYPE_FETCH_BODY: &str = include_str!("../../assets/csa_skype_fetch.js");38
const SKYPE_FETCH_BODY: &str = concat!(39
include_str!("../../assets/skype_token.js"),40
include_str!("../../assets/csa_skype_fetch.js")41
);39
42
40
/// Teams sends the skype token and the chat service endpoint next to the CSA bearer on the pinned post routes.43
/// Teams sends the skype token and the chat service endpoint next to the CSA bearer on the pinned post routes.41
pub struct SkypeTokenTransport {44
pub struct SkypeTokenTransport {@@ -44,6 +44,8 @@ const ALLOWED_PATHS: &[(&str, &str)] = &[
44
44
("app/src/layout_guard.rs", "layout test fixture"),
45
45
("graph/src/tabs.rs", "channel tab web links"),
46
46
("app/src/inline_video.rs", "SharePoint video player link"),
47
("app/src/views/status_menu.rs", "View account web link"),
48
("app-state/src/call/week.rs", "demo join link"),
47
49
];
48
50
49
51
#[test]
@@ -44,6 +44,8 @@ const ALLOWED_PATHS: &[(&str, &str)] = &[44
("app/src/layout_guard.rs", "layout test fixture"),44
("app/src/layout_guard.rs", "layout test fixture"),45
("graph/src/tabs.rs", "channel tab web links"),45
("graph/src/tabs.rs", "channel tab web links"),46
("app/src/inline_video.rs", "SharePoint video player link"),46
("app/src/inline_video.rs", "SharePoint video player link"),47
("app/src/views/status_menu.rs", "View account web link"),48
("app-state/src/call/week.rs", "demo join link"),47
];49
];48
50
49
#[test]51
#[test]@@ -440,3 +440,26 @@ async fn post_message_sends_rich_text_to_the_reply_thread_and_returns_the_arriva
440
440
.all(|character| character.is_ascii_digit())
441
441
);
442
442
}
443
444
#[tokio::test]
445
async fn cards_go_to_the_cards_property_of_the_post() {
446
let mock = Mock::new(&[404, 200]);
447
messages(&mock)
448
.set_cards(
449
&ConversationRef::ChannelRoot {
450
channel_id: "19:c@thread.skype".into(),
451
},
452
"17",
453
"[]",
454
)
455
.await
456
.unwrap();
457
let requests = mock.requests();
458
assert_eq!(requests.len(), 2);
459
assert_eq!(requests[1].method, Method::Put);
460
assert_eq!(
461
requests[1].url,
462
format!("{BASE}/19%3Ac%40thread.skype/messages/17/properties?name=cards")
463
);
464
assert_eq!(requests[1].body.as_ref().unwrap()["cards"], "[]");
465
}
@@ -440,3 +440,26 @@ async fn post_message_sends_rich_text_to_the_reply_thread_and_returns_the_arriva440
.all(|character| character.is_ascii_digit())440
.all(|character| character.is_ascii_digit())441
);441
);442
}442
}443
444
#[tokio::test]445
async fn cards_go_to_the_cards_property_of_the_post() {446
let mock = Mock::new(&[404, 200]);447
messages(&mock)448
.set_cards(449
&ConversationRef::ChannelRoot {450
channel_id: "19:c@thread.skype".into(),451
},452
"17",453
"[]",454
)455
.await456
.unwrap();457
let requests = mock.requests();458
assert_eq!(requests.len(), 2);459
assert_eq!(requests[1].method, Method::Put);460
assert_eq!(461
requests[1].url,462
format!("{BASE}/19%3Ac%40thread.skype/messages/17/properties?name=cards")463
);464
assert_eq!(requests[1].body.as_ref().unwrap()["cards"], "[]");465
}@@ -893,7 +893,7 @@ impl<R: Remote> SyncEngine<R> {
893
893
Ok(Some((sent, cached_html)))
894
894
}
895
895
896
fn cache_sent(
896
pub(crate) fn cache_sent(
897
897
&self,
898
898
conversation_id: &str,
899
899
sent: &graph::Message,
@@ -950,7 +950,7 @@ pub struct OpenedPost {
950
950
pub replies_loaded: bool,
951
951
}
952
952
953
fn outgoing(
953
pub(crate) fn outgoing(
954
954
conversation: &Conversation,
955
955
html: &str,
956
956
mentions: &[MentionInput],
@@ -893,7 +893,7 @@ impl<R: Remote> SyncEngine<R> {893
Ok(Some((sent, cached_html)))893
Ok(Some((sent, cached_html)))894
}894
}895
895
896
fn cache_sent(896
pub(crate) fn cache_sent(897
&self,897
&self,898
conversation_id: &str,898
conversation_id: &str,899
sent: &graph::Message,899
sent: &graph::Message,@@ -950,7 +950,7 @@ pub struct OpenedPost {950
pub replies_loaded: bool,950
pub replies_loaded: bool,951
}951
}952
952
953
fn outgoing(953
pub(crate) fn outgoing(954
conversation: &Conversation,954
conversation: &Conversation,955
html: &str,955
html: &str,956
mentions: &[MentionInput],956
mentions: &[MentionInput],@@ -7,11 +7,38 @@ pub const ANNOUNCEMENT_BANNER_TYPE: &str =
7
7
pub const ANNOUNCEMENT_APP_ID: &str = "announcement-card";
8
8
const DEFAULT_BANNER_COLOR: &str = "periwinkleBlue";
9
9
const COLOR_THEME: &str = "colorTheme";
10
const UPLOADED_IMAGE: &str = "uploadedImage";
11
const LOCAL_IMAGE: &str = "localImage";
12
const 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
];
10
26
11
27
#[derive(Debug, Clone, PartialEq, Eq)]
12
28
pub enum BannerBackground {
13
29
Color(String),
14
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.
36
pub fn teams_theme(color: &str) -> String {
37
TEAMS_THEMES
38
.iter()
39
.position(|known| *known == color)
40
.unwrap_or_default()
41
.to_string()
15
42
}
16
43
17
44
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -33,6 +60,12 @@ impl AnnouncementBanner {
33
60
pub fn parse(content: &str) -> Option<AnnouncementBanner> {
34
61
let content: Value = serde_json::from_str(content).ok()?;
35
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
}
36
69
let details = content.get("cardImageDetails");
37
70
let image = details
38
71
.filter(|_| content.get("cardImageType").and_then(Value::as_str) != Some(COLOR_THEME))
@@ -66,33 +99,71 @@ impl AnnouncementBanner {
66
99
})
67
100
}
68
101
69
/// `id` must be unique per message; Teams uses `announcement-card-<guid>`.
70
pub fn attachment(&self, id: String) -> graph::KeptAttachment {
71
graph::KeptAttachment {
72
id,
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),
73
106
content_type: Some(ANNOUNCEMENT_BANNER_TYPE.to_owned()),
74
content: Some(self.content()),
75
107
content_url: None,
76
108
name: None,
109
content: Some(self.content()),
77
110
teams_app_id: Some(ANNOUNCEMENT_APP_ID.to_owned()),
78
111
}
79
112
}
80
113
81
/// Only color banners can be sent; uploaded images need the Teams image service.
114
/// Graph shape; a local image keeps its path so a queued post survives a restart.
82
115
pub fn content(&self) -> String {
83
let color = match &self.background {
84
BannerBackground::Color(color) => color.as_str(),
85
BannerBackground::Image(_) => DEFAULT_BANNER_COLOR,
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) }),
86
149
};
87
json!({
88
"title": self.title,
89
"cardImageType": COLOR_THEME,
90
"cardImageDetails": { COLOR_THEME: color },
91
})
150
json!([{
151
"appId": ANNOUNCEMENT_APP_ID,
152
"contentType": ANNOUNCEMENT_BANNER_TYPE,
153
"content": content,
154
}])
92
155
.to_string()
93
156
}
94
157
}
95
158
159
#[derive(Debug, Clone, PartialEq, Eq)]
160
pub struct TeamsBannerImage {
161
pub object_id: String,
162
pub url: String,
163
pub width: u32,
164
pub height: u32,
165
}
166
96
167
fn image_source(details: &Value, key: &str) -> Option<String> {
97
168
let found = details
98
169
.get(key)
@@ -150,6 +221,44 @@ mod tests {
150
221
assert_eq!(AnnouncementBanner::parse(&banner.content()), Some(banner));
151
222
}
152
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
153
262
#[test]
154
263
fn banner_without_content_is_none() {
155
264
let mut attachment = banner_attachment("");
@@ -7,11 +7,38 @@ pub const ANNOUNCEMENT_BANNER_TYPE: &str =7
pub const ANNOUNCEMENT_APP_ID: &str = "announcement-card";7
pub const ANNOUNCEMENT_APP_ID: &str = "announcement-card";8
const DEFAULT_BANNER_COLOR: &str = "periwinkleBlue";8
const DEFAULT_BANNER_COLOR: &str = "periwinkleBlue";9
const COLOR_THEME: &str = "colorTheme";9
const COLOR_THEME: &str = "colorTheme";10
const UPLOADED_IMAGE: &str = "uploadedImage";11
const LOCAL_IMAGE: &str = "localImage";12
const 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
];10
26
11
#[derive(Debug, Clone, PartialEq, Eq)]27
#[derive(Debug, Clone, PartialEq, Eq)]12
pub enum BannerBackground {28
pub enum BannerBackground {13
Color(String),29
Color(String),14
Image(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.36
pub fn teams_theme(color: &str) -> String {37
TEAMS_THEMES38
.iter()39
.position(|known| *known == color)40
.unwrap_or_default()41
.to_string()15
}42
}16
43
17
#[derive(Debug, Clone, PartialEq, Eq)]44
#[derive(Debug, Clone, PartialEq, Eq)]@@ -33,6 +60,12 @@ impl AnnouncementBanner {33
pub fn parse(content: &str) -> Option<AnnouncementBanner> {60
pub fn parse(content: &str) -> Option<AnnouncementBanner> {34
let content: Value = serde_json::from_str(content).ok()?;61
let content: Value = serde_json::from_str(content).ok()?;35
let title = content.get("title")?.as_str()?.trim().to_owned();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
}36
let details = content.get("cardImageDetails");69
let details = content.get("cardImageDetails");37
let image = details70
let image = details38
.filter(|_| content.get("cardImageType").and_then(Value::as_str) != Some(COLOR_THEME))71
.filter(|_| content.get("cardImageType").and_then(Value::as_str) != Some(COLOR_THEME))@@ -66,33 +99,71 @@ impl AnnouncementBanner {66
})99
})67
}100
}68
101
69
/// `id` must be unique per message; Teams uses `announcement-card-<guid>`.102
/// Graph shape, as Graph returns it for a post.70
pub fn attachment(&self, id: String) -> graph::KeptAttachment {103
pub fn attachment(&self, id: String) -> graph::Attachment {71
graph::KeptAttachment {104
graph::Attachment {72
id,105
id: Some(id),73
content_type: Some(ANNOUNCEMENT_BANNER_TYPE.to_owned()),106
content_type: Some(ANNOUNCEMENT_BANNER_TYPE.to_owned()),74
content: Some(self.content()),75
content_url: None,107
content_url: None,76
name: None,108
name: None,109
content: Some(self.content()),77
teams_app_id: Some(ANNOUNCEMENT_APP_ID.to_owned()),110
teams_app_id: Some(ANNOUNCEMENT_APP_ID.to_owned()),78
}111
}79
}112
}80
113
81
/// Only color banners can be sent; uploaded images need the Teams image service.114
/// Graph shape; a local image keeps its path so a queued post survives a restart.82
pub fn content(&self) -> String {115
pub fn content(&self) -> String {83
let color = match &self.background {116
let mut content = json!({ "title": self.title });84
BannerBackground::Color(color) => color.as_str(),117
match &self.background {85
BannerBackground::Image(_) => DEFAULT_BANNER_COLOR,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) }),86
};149
};87
json!({150
json!([{88
"title": self.title,151
"appId": ANNOUNCEMENT_APP_ID,89
"cardImageType": COLOR_THEME,152
"contentType": ANNOUNCEMENT_BANNER_TYPE,90
"cardImageDetails": { COLOR_THEME: color },153
"content": content,91
})154
}])92
.to_string()155
.to_string()93
}156
}94
}157
}95
158
159
#[derive(Debug, Clone, PartialEq, Eq)]160
pub struct TeamsBannerImage {161
pub object_id: String,162
pub url: String,163
pub width: u32,164
pub height: u32,165
}166
96
fn image_source(details: &Value, key: &str) -> Option<String> {167
fn image_source(details: &Value, key: &str) -> Option<String> {97
let found = details168
let found = details98
.get(key)169
.get(key)@@ -150,6 +221,44 @@ mod tests {150
assert_eq!(AnnouncementBanner::parse(&banner.content()), Some(banner));221
assert_eq!(AnnouncementBanner::parse(&banner.content()), Some(banner));151
}222
}152
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
153
#[test]262
#[test]154
fn banner_without_content_is_none() {263
fn banner_without_content_is_none() {155
let mut attachment = banner_attachment("");264
let mut attachment = banner_attachment("");@@ -0,0 +1,103 @@
1
use chatsvc::ConversationRef;
2
use graph::MessageExtras;
3
use store::MessageRecord;
4
5
use crate::actions::outgoing;
6
use crate::announcement::{AnnouncementBanner, BannerBackground, TeamsBannerImage};
7
use crate::engine::{Conversation, SyncEngine};
8
use crate::error::{Error, Result};
9
use crate::mentions::MentionInput;
10
use crate::remote::Remote;
11
12
const BANNER_FILE_NAME: &str = "MicrosoftTeams-image.png";
13
const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";
14
15
fn png_size(bytes: &[u8]) -> Option<(u32, u32)> {
16
if !bytes.starts_with(PNG_SIGNATURE) || bytes.get(12..16)? != b"IHDR" {
17
return None;
18
}
19
let read = |range: std::ops::Range<usize>| -> Option<u32> {
20
Some(u32::from_be_bytes(bytes.get(range)?.try_into().ok()?))
21
};
22
Some((read(16..20)?, read(20..24)?))
23
}
24
25
impl<R: Remote> SyncEngine<R> {
26
/// Graph rejects the banner card from a user token, so the post goes out plain and the
27
/// chat service adds the card. The image is uploaded first so a failed upload sends nothing.
28
pub async fn post_announcement(
29
&self,
30
channel_id: &str,
31
html: &str,
32
subject: Option<&str>,
33
mentions: &[MentionInput],
34
extras: &MessageExtras,
35
banner: &AnnouncementBanner,
36
) -> Result<MessageRecord> {
37
let conversation = self.resolve(channel_id).await?;
38
let Conversation::Channel { team_id } = &conversation else {
39
return Err(Error::Unsupported("an announcement in a chat"));
40
};
41
let image = match &banner.background {
42
BannerBackground::LocalImage(path) => Some(self.upload_banner_image(channel_id, path).await?),
43
_ => None,
44
};
45
let (html, mentions) = outgoing(&conversation, html, mentions)?;
46
let mut sent = self
47
.remote
48
.send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)
49
.await?;
50
let cards = banner.teams_cards(image.as_ref());
51
let target = ConversationRef::ChannelRoot {
52
channel_id: channel_id.to_owned(),
53
};
54
if self
55
.remote
56
.set_message_cards(&target, &sent.id, &cards)
57
.await
58
.is_ok()
59
{
60
let shown = match &image {
61
Some(image) => AnnouncementBanner {
62
title: banner.title.clone(),
63
background: BannerBackground::Image(image.url.clone()),
64
},
65
None => banner.clone(),
66
};
67
sent.attachments
68
.insert(0, shown.attachment(format!("announcement-card-{}", sent.id)));
69
}
70
self.cache_sent(channel_id, &sent, &html, extras)
71
}
72
73
async fn upload_banner_image(&self, channel_id: &str, path: &str) -> Result<TeamsBannerImage> {
74
let bytes = std::fs::read(path)
75
.map_err(|_| Error::Unsupported("a banner image that is no longer on disk"))?;
76
let (width, height) =
77
png_size(&bytes).ok_or(Error::Unsupported("a banner image that is not a PNG"))?;
78
let uploaded = self
79
.remote
80
.upload_ams_image(channel_id, &bytes, BANNER_FILE_NAME)
81
.await?;
82
Ok(TeamsBannerImage {
83
object_id: uploaded.object_id,
84
url: uploaded.url,
85
width,
86
height,
87
})
88
}
89
}
90
91
#[cfg(test)]
92
mod tests {
93
use super::png_size;
94
95
#[test]
96
fn png_size_reads_the_header() {
97
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
98
header.extend_from_slice(&1317u32.to_be_bytes());
99
header.extend_from_slice(&366u32.to_be_bytes());
100
assert_eq!(png_size(&header), Some((1317, 366)));
101
assert_eq!(png_size(b"GIF89a"), None);
102
}
103
}
@@ -0,0 +1,103 @@1
use chatsvc::ConversationRef;2
use graph::MessageExtras;3
use store::MessageRecord;4
5
use crate::actions::outgoing;6
use crate::announcement::{AnnouncementBanner, BannerBackground, TeamsBannerImage};7
use crate::engine::{Conversation, SyncEngine};8
use crate::error::{Error, Result};9
use crate::mentions::MentionInput;10
use crate::remote::Remote;11
12
const BANNER_FILE_NAME: &str = "MicrosoftTeams-image.png";13
const PNG_SIGNATURE: &[u8] = b"\x89PNG\r\n\x1a\n";14
15
fn png_size(bytes: &[u8]) -> Option<(u32, u32)> {16
if !bytes.starts_with(PNG_SIGNATURE) || bytes.get(12..16)? != b"IHDR" {17
return None;18
}19
let read = |range: std::ops::Range<usize>| -> Option<u32> {20
Some(u32::from_be_bytes(bytes.get(range)?.try_into().ok()?))21
};22
Some((read(16..20)?, read(20..24)?))23
}24
25
impl<R: Remote> SyncEngine<R> {26
/// Graph rejects the banner card from a user token, so the post goes out plain and the27
/// chat service adds the card. The image is uploaded first so a failed upload sends nothing.28
pub async fn post_announcement(29
&self,30
channel_id: &str,31
html: &str,32
subject: Option<&str>,33
mentions: &[MentionInput],34
extras: &MessageExtras,35
banner: &AnnouncementBanner,36
) -> Result<MessageRecord> {37
let conversation = self.resolve(channel_id).await?;38
let Conversation::Channel { team_id } = &conversation else {39
return Err(Error::Unsupported("an announcement in a chat"));40
};41
let image = match &banner.background {42
BannerBackground::LocalImage(path) => Some(self.upload_banner_image(channel_id, path).await?),43
_ => None,44
};45
let (html, mentions) = outgoing(&conversation, html, mentions)?;46
let mut sent = self47
.remote48
.send_channel_message(team_id, channel_id, &html, subject, &mentions, extras)49
.await?;50
let cards = banner.teams_cards(image.as_ref());51
let target = ConversationRef::ChannelRoot {52
channel_id: channel_id.to_owned(),53
};54
if self55
.remote56
.set_message_cards(&target, &sent.id, &cards)57
.await58
.is_ok()59
{60
let shown = match &image {61
Some(image) => AnnouncementBanner {62
title: banner.title.clone(),63
background: BannerBackground::Image(image.url.clone()),64
},65
None => banner.clone(),66
};67
sent.attachments68
.insert(0, shown.attachment(format!("announcement-card-{}", sent.id)));69
}70
self.cache_sent(channel_id, &sent, &html, extras)71
}72
73
async fn upload_banner_image(&self, channel_id: &str, path: &str) -> Result<TeamsBannerImage> {74
let bytes = std::fs::read(path)75
.map_err(|_| Error::Unsupported("a banner image that is no longer on disk"))?;76
let (width, height) =77
png_size(&bytes).ok_or(Error::Unsupported("a banner image that is not a PNG"))?;78
let uploaded = self79
.remote80
.upload_ams_image(channel_id, &bytes, BANNER_FILE_NAME)81
.await?;82
Ok(TeamsBannerImage {83
object_id: uploaded.object_id,84
url: uploaded.url,85
width,86
height,87
})88
}89
}90
91
#[cfg(test)]92
mod tests {93
use super::png_size;94
95
#[test]96
fn png_size_reads_the_header() {97
let mut header = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();98
header.extend_from_slice(&1317u32.to_be_bytes());99
header.extend_from_slice(&366u32.to_be_bytes());100
assert_eq!(png_size(&header), Some((1317, 366)));101
assert_eq!(png_size(b"GIF89a"), None);102
}103
}@@ -1,5 +1,6 @@
1
1
mod actions;
2
2
mod announcement;
3
mod announcement_post;
3
4
mod activity_sync;
4
5
mod adaptive_card;
5
6
mod avatars;
@@ -75,6 +76,7 @@ pub use actions::OpenedPost;
75
76
pub use activity_sync::stored_activity_feed;
76
77
pub use announcement::{
77
78
ANNOUNCEMENT_APP_ID, ANNOUNCEMENT_BANNER_TYPE, AnnouncementBanner, BannerBackground,
79
TeamsBannerImage, teams_theme,
78
80
};
79
81
pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};
80
82
pub use adaptive_card::{
@@ -1,5 +1,6 @@1
mod actions;1
mod actions;2
mod announcement;2
mod announcement;3
mod announcement_post;3
mod activity_sync;4
mod activity_sync;4
mod adaptive_card;5
mod adaptive_card;5
mod avatars;6
mod avatars;@@ -75,6 +76,7 @@ pub use actions::OpenedPost;75
pub use activity_sync::stored_activity_feed;76
pub use activity_sync::stored_activity_feed;76
pub use announcement::{77
pub use announcement::{77
ANNOUNCEMENT_APP_ID, ANNOUNCEMENT_BANNER_TYPE, AnnouncementBanner, BannerBackground,78
ANNOUNCEMENT_APP_ID, ANNOUNCEMENT_BANNER_TYPE, AnnouncementBanner, BannerBackground,79
TeamsBannerImage, teams_theme,78
};80
};79
pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};81
pub use chatsvc::{ActivityHorizons, ActivityItem, ActivitySnapshot};80
pub use adaptive_card::{82
pub use adaptive_card::{@@ -132,6 +132,19 @@ pub trait Remote {
132
132
display_name: &str,
133
133
properties: &serde_json::Value,
134
134
) -> Result<String>;
135
/// Readable by the members of `conversation_id`; returns the object id and its full size url.
136
async fn upload_ams_image(
137
&self,
138
conversation_id: &str,
139
bytes: &[u8],
140
filename: &str,
141
) -> Result<chatsvc::ams::AmsImage>;
142
async fn set_message_cards(
143
&self,
144
conversation: &ConversationRef,
145
message_id: &str,
146
cards: &str,
147
) -> Result<()>;
135
148
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;
136
149
async fn mark_chat_unread(
137
150
&self,
@@ -797,6 +810,28 @@ impl Remote for Graph {
797
810
.await?)
798
811
}
799
812
813
async fn upload_ams_image(
814
&self,
815
conversation_id: &str,
816
bytes: &[u8],
817
filename: &str,
818
) -> Result<chatsvc::ams::AmsImage> {
819
Ok(chatsvc::ams::Ams::new(self.session())
820
.upload_image(conversation_id, bytes, filename)
821
.await?)
822
}
823
824
async fn set_message_cards(
825
&self,
826
conversation: &ConversationRef,
827
message_id: &str,
828
cards: &str,
829
) -> Result<()> {
830
Ok(Messages::new(self.session())
831
.set_cards(conversation, message_id, cards)
832
.await?)
833
}
834
800
835
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
801
836
Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)
802
837
}
@@ -132,6 +132,19 @@ pub trait Remote {132
display_name: &str,132
display_name: &str,133
properties: &serde_json::Value,133
properties: &serde_json::Value,134
) -> Result<String>;134
) -> Result<String>;135
/// Readable by the members of `conversation_id`; returns the object id and its full size url.136
async fn upload_ams_image(137
&self,138
conversation_id: &str,139
bytes: &[u8],140
filename: &str,141
) -> Result<chatsvc::ams::AmsImage>;142
async fn set_message_cards(143
&self,144
conversation: &ConversationRef,145
message_id: &str,146
cards: &str,147
) -> Result<()>;135
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;148
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()>;136
async fn mark_chat_unread(149
async fn mark_chat_unread(137
&self,150
&self,@@ -797,6 +810,28 @@ impl Remote for Graph {797
.await?)810
.await?)798
}811
}799
812
813
async fn upload_ams_image(814
&self,815
conversation_id: &str,816
bytes: &[u8],817
filename: &str,818
) -> Result<chatsvc::ams::AmsImage> {819
Ok(chatsvc::ams::Ams::new(self.session())820
.upload_image(conversation_id, bytes, filename)821
.await?)822
}823
824
async fn set_message_cards(825
&self,826
conversation: &ConversationRef,827
message_id: &str,828
cards: &str,829
) -> Result<()> {830
Ok(Messages::new(self.session())831
.set_cards(conversation, message_id, cards)832
.await?)833
}834
800
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {835
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {801
Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)836
Ok(Graph::mark_chat_read(self, chat_id, user_id, tenant_id).await?)802
}837
}@@ -544,6 +544,32 @@ impl Remote for Handle {
544
544
Ok("1727203440000".to_owned())
545
545
}
546
546
547
async fn upload_ams_image(
548
&self,
549
conversation_id: &str,
550
bytes: &[u8],
551
filename: &str,
552
) -> Result<chatsvc::ams::AmsImage> {
553
self.record(format!("ams upload {conversation_id} {filename} {}", bytes.len()));
554
Ok(chatsvc::ams::AmsImage {
555
object_id: "0-ams".to_owned(),
556
url: "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-ams/views/imgpsh_fullsize".to_owned(),
557
})
558
}
559
560
async fn set_message_cards(
561
&self,
562
conversation: &chatsvc::ConversationRef,
563
message_id: &str,
564
cards: &str,
565
) -> Result<()> {
566
self.record(format!(
567
"cards {} {message_id} {cards}",
568
conversation.conversation_id()
569
));
570
Ok(())
571
}
572
547
573
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {
548
574
self.record(format!("mark_read {chat_id} {user_id} {tenant_id}"));
549
575
Ok(())
@@ -2122,6 +2148,43 @@ async fn channel_delta_failure_falls_back_to_the_first_page() {
2122
2148
);
2123
2149
}
2124
2150
2151
#[tokio::test]
2152
async fn an_announcement_posts_through_graph_then_adds_the_banner_card() {
2153
let fake = Arc::new(Fake::default());
2154
let engine = channel_engine(&fake).await;
2155
let directory = tempfile::tempdir().unwrap();
2156
let path = directory.path().join("banner.png");
2157
let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();
2158
png.extend_from_slice(&1317u32.to_be_bytes());
2159
png.extend_from_slice(&366u32.to_be_bytes());
2160
std::fs::write(&path, &png).unwrap();
2161
let banner = teams_core::AnnouncementBanner {
2162
title: "Ship it".to_owned(),
2163
background: teams_core::BannerBackground::LocalImage(path.to_string_lossy().into_owned()),
2164
};
2165
let record = engine
2166
.post_announcement(CHANNEL, "<p>hi</p>", Some("Topic"), &[], &MessageExtras::default(), &banner)
2167
.await
2168
.unwrap();
2169
let calls: Vec<String> = fake
2170
.calls()
2171
.into_iter()
2172
.filter(|call| !call.starts_with("channel_delta"))
2173
.collect();
2174
assert_eq!(calls.len(), 3);
2175
assert!(calls[0].starts_with(&format!("ams upload {CHANNEL} MicrosoftTeams-image.png")));
2176
assert_eq!(calls[1], "post subject=Some(\"Topic\")");
2177
assert!(calls[2].starts_with(&format!("cards {CHANNEL} m9001 ")));
2178
assert!(calls[2].contains("\"imageHeight\":366"));
2179
let shown = teams_core::AnnouncementBanner::from_attachments(&teams_core::attachments(&record));
2180
assert_eq!(
2181
shown.map(|banner| banner.background),
2182
Some(teams_core::BannerBackground::Image(
2183
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-ams/views/imgpsh_fullsize".to_owned()
2184
))
2185
);
2186
}
2187
2125
2188
#[tokio::test]
2126
2189
async fn channel_sends_post_and_reply_through_graph() {
2127
2190
let fake = Arc::new(Fake::default());
@@ -544,6 +544,32 @@ impl Remote for Handle {544
Ok("1727203440000".to_owned())544
Ok("1727203440000".to_owned())545
}545
}546
546
547
async fn upload_ams_image(548
&self,549
conversation_id: &str,550
bytes: &[u8],551
filename: &str,552
) -> Result<chatsvc::ams::AmsImage> {553
self.record(format!("ams upload {conversation_id} {filename} {}", bytes.len()));554
Ok(chatsvc::ams::AmsImage {555
object_id: "0-ams".to_owned(),556
url: "https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-ams/views/imgpsh_fullsize".to_owned(),557
})558
}559
560
async fn set_message_cards(561
&self,562
conversation: &chatsvc::ConversationRef,563
message_id: &str,564
cards: &str,565
) -> Result<()> {566
self.record(format!(567
"cards {} {message_id} {cards}",568
conversation.conversation_id()569
));570
Ok(())571
}572
547
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {573
async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> {548
self.record(format!("mark_read {chat_id} {user_id} {tenant_id}"));574
self.record(format!("mark_read {chat_id} {user_id} {tenant_id}"));549
Ok(())575
Ok(())@@ -2122,6 +2148,43 @@ async fn channel_delta_failure_falls_back_to_the_first_page() {2122
);2148
);2123
}2149
}2124
2150
2151
#[tokio::test]2152
async fn an_announcement_posts_through_graph_then_adds_the_banner_card() {2153
let fake = Arc::new(Fake::default());2154
let engine = channel_engine(&fake).await;2155
let directory = tempfile::tempdir().unwrap();2156
let path = directory.path().join("banner.png");2157
let mut png = b"\x89PNG\r\n\x1a\n\0\0\0\x0dIHDR".to_vec();2158
png.extend_from_slice(&1317u32.to_be_bytes());2159
png.extend_from_slice(&366u32.to_be_bytes());2160
std::fs::write(&path, &png).unwrap();2161
let banner = teams_core::AnnouncementBanner {2162
title: "Ship it".to_owned(),2163
background: teams_core::BannerBackground::LocalImage(path.to_string_lossy().into_owned()),2164
};2165
let record = engine2166
.post_announcement(CHANNEL, "<p>hi</p>", Some("Topic"), &[], &MessageExtras::default(), &banner)2167
.await2168
.unwrap();2169
let calls: Vec<String> = fake2170
.calls()2171
.into_iter()2172
.filter(|call| !call.starts_with("channel_delta"))2173
.collect();2174
assert_eq!(calls.len(), 3);2175
assert!(calls[0].starts_with(&format!("ams upload {CHANNEL} MicrosoftTeams-image.png")));2176
assert_eq!(calls[1], "post subject=Some(\"Topic\")");2177
assert!(calls[2].starts_with(&format!("cards {CHANNEL} m9001 ")));2178
assert!(calls[2].contains("\"imageHeight\":366"));2179
let shown = teams_core::AnnouncementBanner::from_attachments(&teams_core::attachments(&record));2180
assert_eq!(2181
shown.map(|banner| banner.background),2182
Some(teams_core::BannerBackground::Image(2183
"https://de-prod.asyncgw.teams.microsoft.com/v1/objects/0-ams/views/imgpsh_fullsize".to_owned()2184
))2185
);2186
}2187
2125
#[tokio::test]2188
#[tokio::test]2126
async fn channel_sends_post_and_reply_through_graph() {2189
async fn channel_sends_post_and_reply_through_graph() {2127
let fake = Arc::new(Fake::default());2190
let fake = Arc::new(Fake::default());