fix(messages): show only the unfurl card for a link like Teams
- Teams writes previewenabled false on the link when it attaches the richInfo unfurl card; the URL preview needs previewenabled true, two of thumbnail/title/description and the first link of the message - an unfurl card (Graph teamsAppId 4623DD0C-... or id prefix app-preview-card) also hides the URL preview; teamsAppId is now kept on attachments - Media without a poster uses the YouTube still (maxresdefault, then hqdefault) like Teams - Deviation: the video opens in the browser, Teams plays it inline - tests with a synthetic YouTube link + unfurl card fixture Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -107,6 +107,7 @@ mod tests {
107
107
r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:c@thread.v2/messages/1728/hostedContents/aWQ9/$value" alt="a chart" width="300" height="120"></p>"#,
108
108
r#"<p><img src="https://media0.giphy.com/media/abc/giphy.gif"></p>"#,
109
109
r#"<attachment id="F1"></attachment>"#,
110
r#"<p><a href="https://news.example.com/story">https://news.example.com/story</a></p>"#,
110
111
)
111
112
.to_owned(),
112
113
attachments_json: r#"[
@@ -107,6 +107,7 @@ mod tests {107
r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:c@thread.v2/messages/1728/hostedContents/aWQ9/$value" alt="a chart" width="300" height="120"></p>"#,107
r#"<p><img src="https://graph.microsoft.com/v1.0/chats/19:c@thread.v2/messages/1728/hostedContents/aWQ9/$value" alt="a chart" width="300" height="120"></p>"#,108
r#"<p><img src="https://media0.giphy.com/media/abc/giphy.gif"></p>"#,108
r#"<p><img src="https://media0.giphy.com/media/abc/giphy.gif"></p>"#,109
r#"<attachment id="F1"></attachment>"#,109
r#"<attachment id="F1"></attachment>"#,110
r#"<p><a href="https://news.example.com/story">https://news.example.com/story</a></p>"#,110
)111
)111
.to_owned(),112
.to_owned(),112
attachments_json: r#"[113
attachments_json: r#"[@@ -1775,7 +1775,7 @@ fn release_messages() -> Vec<MessageRecord> {
1775
1775
LinkPreview {
1776
1776
url: "https://example.com/notes".to_owned(),
1777
1777
title: Some("Release notes 0.2".to_owned()),
1778
description: None,
1778
description: Some("What changed since 0.1".to_owned()),
1779
1779
image_url: None,
1780
1780
image_width: None,
1781
1781
image_height: None,
@@ -1775,7 +1775,7 @@ fn release_messages() -> Vec<MessageRecord> {1775
LinkPreview {1775
LinkPreview {1776
url: "https://example.com/notes".to_owned(),1776
url: "https://example.com/notes".to_owned(),1777
title: Some("Release notes 0.2".to_owned()),1777
title: Some("Release notes 0.2".to_owned()),1778
description: None,1778
description: Some("What changed since 0.1".to_owned()),1779
image_url: None,1779
image_url: None,1780
image_width: None,1780
image_width: None,1781
image_height: None,1781
image_height: None,@@ -2,7 +2,7 @@ use gpui_kit::assets::IconName;
2
2
use gpui_kit::component::tooltip::Tooltip;
3
3
use gpui_kit::prelude::FluentBuilder as _;
4
4
use gpui_kit::*;
5
use teams_core::CardMedia;
5
use teams_core::{CardMedia, fallback_poster_url};
6
6
7
7
use super::widgets::icon;
8
8
use crate::theme;
@@ -19,13 +19,17 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
19
19
let source_url = media.source_url.clone();
20
20
let alt_text = media.alt_text.clone();
21
21
let poster = match &media.poster_url {
22
Some(url) => img(url.clone())
23
.size_full()
24
.rounded(px(MEDIA_RADIUS))
25
.object_fit(ObjectFit::Cover)
26
.with_loading(placeholder)
27
.with_fallback(placeholder)
28
.into_any_element(),
22
Some(url) => {
23
let fallback_url = fallback_poster_url(url);
24
poster_image(url.clone())
25
.with_fallback(move || match fallback_url.clone() {
26
Some(fallback_url) => poster_image(fallback_url)
27
.with_fallback(placeholder)
28
.into_any_element(),
29
None => placeholder(),
30
})
31
.into_any_element()
32
}
29
33
None => placeholder(),
30
34
};
31
35
div()
@@ -71,6 +75,14 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {
71
75
.into_any_element()
72
76
}
73
77
78
fn poster_image(url: String) -> Img {
79
img(url)
80
.size_full()
81
.rounded(px(MEDIA_RADIUS))
82
.object_fit(ObjectFit::Cover)
83
.with_loading(placeholder)
84
}
85
74
86
fn placeholder() -> AnyElement {
75
87
div()
76
88
.size_full()
@@ -2,7 +2,7 @@ use gpui_kit::assets::IconName;2
use gpui_kit::component::tooltip::Tooltip;2
use gpui_kit::component::tooltip::Tooltip;3
use gpui_kit::prelude::FluentBuilder as _;3
use gpui_kit::prelude::FluentBuilder as _;4
use gpui_kit::*;4
use gpui_kit::*;5
use teams_core::CardMedia;5
use teams_core::{CardMedia, fallback_poster_url};6
6
7
use super::widgets::icon;7
use super::widgets::icon;8
use crate::theme;8
use crate::theme;@@ -19,13 +19,17 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {19
let source_url = media.source_url.clone();19
let source_url = media.source_url.clone();20
let alt_text = media.alt_text.clone();20
let alt_text = media.alt_text.clone();21
let poster = match &media.poster_url {21
let poster = match &media.poster_url {22
Some(url) => img(url.clone())22
Some(url) => {23
.size_full()23
let fallback_url = fallback_poster_url(url);24
.rounded(px(MEDIA_RADIUS))24
poster_image(url.clone())25
.object_fit(ObjectFit::Cover)25
.with_fallback(move || match fallback_url.clone() {26
.with_loading(placeholder)26
Some(fallback_url) => poster_image(fallback_url)27
.with_fallback(placeholder)27
.with_fallback(placeholder)28
.into_any_element(),28
.into_any_element(),29
None => placeholder(),30
})31
.into_any_element()32
}29
None => placeholder(),33
None => placeholder(),30
};34
};31
div()35
div()@@ -71,6 +75,14 @@ pub fn media_view(media: &CardMedia, id: &str) -> AnyElement {71
.into_any_element()75
.into_any_element()72
}76
}73
77
78
fn poster_image(url: String) -> Img {79
img(url)80
.size_full()81
.rounded(px(MEDIA_RADIUS))82
.object_fit(ObjectFit::Cover)83
.with_loading(placeholder)84
}85
74
fn placeholder() -> AnyElement {86
fn placeholder() -> AnyElement {75
div()87
div()76
.size_full()88
.size_full()@@ -1025,7 +1025,8 @@ fn parse_media(value: &Value) -> Option<CardMedia> {
1025
1025
Some(CardMedia {
1026
1026
poster_url: string_field(value, "poster")
1027
1027
.filter(|url| url.starts_with(IMAGE_URL_SCHEME))
1028
.map(str::to_owned),
1028
.map(str::to_owned)
1029
.or_else(|| crate::youtube::poster_url(source_url)),
1029
1030
source_url: source_url.to_owned(),
1030
1031
alt_text: string_field(value, "altText")
1031
1032
.filter(|text| !text.trim().is_empty())
@@ -1025,7 +1025,8 @@ fn parse_media(value: &Value) -> Option<CardMedia> {1025
Some(CardMedia {1025
Some(CardMedia {1026
poster_url: string_field(value, "poster")1026
poster_url: string_field(value, "poster")1027
.filter(|url| url.starts_with(IMAGE_URL_SCHEME))1027
.filter(|url| url.starts_with(IMAGE_URL_SCHEME))1028
.map(str::to_owned),1028
.map(str::to_owned)1029
.or_else(|| crate::youtube::poster_url(source_url)),1029
source_url: source_url.to_owned(),1030
source_url: source_url.to_owned(),1030
alt_text: string_field(value, "altText")1031
alt_text: string_field(value, "altText")1031
.filter(|text| !text.trim().is_empty())1032
.filter(|text| !text.trim().is_empty())@@ -64,6 +64,7 @@ mod table;
64
64
mod time_zone;
65
65
mod translate_sync;
66
66
mod translation;
67
mod youtube;
67
68
68
69
pub use adaptive_card::{
69
70
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,
@@ -145,6 +146,7 @@ pub use graph::{
145
146
pub use images::StoredImage;
146
147
pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};
147
148
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};
149
pub use youtube::fallback_poster_url;
148
150
pub use mapping::{chat_record, message_record};
149
151
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};
150
152
pub use meeting_join::{
@@ -64,6 +64,7 @@ mod table;64
mod time_zone;64
mod time_zone;65
mod translate_sync;65
mod translate_sync;66
mod translation;66
mod translation;67
mod youtube;67
68
68
pub use adaptive_card::{69
pub use adaptive_card::{69
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,70
ActionSplit, AdaptiveCard, CARD_THEME, CardAction, CardActionIcon, CardActionKind, CardColumn,@@ -145,6 +146,7 @@ pub use graph::{145
pub use images::StoredImage;146
pub use images::StoredImage;146
pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};147
pub use jumbo::{JumboEmoji, MAX_JUMBO_EMOJI, jumbo_emoji};147
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};148
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview, public_links};149
pub use youtube::fallback_poster_url;148
pub use mapping::{chat_record, message_record};150
pub use mapping::{chat_record, message_record};149
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};151
pub use markdown::{card_markdown_to_html, escape_html, markdown_to_html, plain_text_to_html};150
pub use meeting_join::{152
pub use meeting_join::{@@ -5,7 +5,7 @@ use scraper::{Html, Selector};
5
5
use serde_json::{Value, json};
6
6
use store::MessageRecord;
7
7
8
use crate::stored::ImageRef;
8
use crate::stored::{AttachmentInfo, ImageRef, attachments};
9
9
10
10
pub const EMPTY_LINKS: &str = "[]";
11
11
@@ -90,7 +90,12 @@ impl LinkPreview {
90
90
}
91
91
92
92
fn is_showable(&self) -> bool {
93
self.title.is_some() || self.image_url.is_some()
93
let parts = [
94
self.image_url.is_some(),
95
self.title.is_some(),
96
self.description.is_some(),
97
];
98
parts.into_iter().filter(|present| *present).count() >= 2
94
99
}
95
100
}
96
101
@@ -103,10 +108,11 @@ pub fn has_stored_links(links_json: &str) -> bool {
103
108
}
104
109
105
110
pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {
106
if record.deleted {
111
if record.deleted || has_link_unfurl_card(record) {
107
112
return None;
108
113
}
109
select_preview(&record.links_json)
114
let first_link = first_link(&record.body_html)?;
115
select_preview(&record.links_json).filter(|preview| same_link(&preview.url, &first_link))
110
116
}
111
117
112
118
pub fn select_preview(links_json: &str) -> Option<LinkPreview> {
@@ -114,8 +120,27 @@ pub fn select_preview(links_json: &str) -> Option<LinkPreview> {
114
120
entries.iter().find_map(entry_preview)
115
121
}
116
122
123
fn has_link_unfurl_card(record: &MessageRecord) -> bool {
124
attachments(record)
125
.iter()
126
.any(AttachmentInfo::is_link_unfurl_card)
127
}
128
129
fn first_link(html: &str) -> Option<String> {
130
let selector = Selector::parse("a[href]").ok()?;
131
Html::parse_fragment(html)
132
.select(&selector)
133
.find_map(|anchor| anchor.value().attr("href"))
134
.map(str::to_owned)
135
}
136
137
fn same_link(first: &str, second: &str) -> bool {
138
let normalize = |url: &str| url.trim().trim_end_matches('/').to_ascii_lowercase();
139
normalize(first) == normalize(second)
140
}
141
117
142
fn entry_preview(entry: &Value) -> Option<LinkPreview> {
118
if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) {
143
if entry.get("previewenabled").and_then(Value::as_bool) != Some(true) {
119
144
return None;
120
145
}
121
146
let url = entry.get("url")?.as_str()?;
@@ -268,12 +293,13 @@ mod tests {
268
293
}
269
294
270
295
#[test]
271
fn picks_the_first_public_link_with_a_title() {
296
fn picks_the_first_enabled_public_link_with_two_parts() {
272
297
let preview = select_preview(&links(json!([
273
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true},
298
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File", "description": "F"}, "previewenabled": true},
274
299
{"url": "https://a.example/x", "preview": {}, "previewenabled": true},
275
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}},
276
{"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true},
300
{"url": "https://n.example/x", "preview": {"title": "N", "description": "No flag"}},
301
{"url": "https://t.example/x", "preview": {"title": "Title only"}, "previewenabled": true},
302
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}, "previewenabled": true},
277
303
])))
278
304
.unwrap();
279
305
assert_eq!(preview.url, "https://b.example/y");
@@ -283,9 +309,15 @@ mod tests {
283
309
}
284
310
285
311
#[test]
286
fn an_image_alone_is_enough() {
312
fn an_image_needs_a_title_or_description() {
313
assert_eq!(
314
select_preview(&links(json!([
315
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL}, "previewenabled": true},
316
]))),
317
None
318
);
287
319
let preview = select_preview(&links(json!([
288
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null},
320
{"url": "https://a.example", "preview": {"description": "D", "previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": true},
289
321
])))
290
322
.unwrap();
291
323
assert_eq!(preview.title, None);
@@ -299,8 +331,7 @@ mod tests {
299
331
#[test]
300
332
fn reads_the_camel_case_meta_and_null_meta() {
301
333
let preview = select_preview(&links(json!([
302
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}},
303
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
334
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}, "previewenabled": true},
304
335
])))
305
336
.unwrap();
306
337
assert_eq!(
@@ -308,12 +339,99 @@ mod tests {
308
339
(Some(20), Some(10))
309
340
);
310
341
let second = select_preview(&links(json!([
311
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
342
{"url": "https://b.example", "preview": {"title": "B", "description": "D", "previewmeta": null}, "previewenabled": true},
312
343
])))
313
344
.unwrap();
314
345
assert_eq!(second.image_width, None);
315
346
}
316
347
348
fn linked_record(body_html: &str, links_json: Value, attachments_json: Value) -> MessageRecord {
349
MessageRecord {
350
body_html: body_html.to_owned(),
351
links_json: links(links_json),
352
attachments_json: attachments_json.to_string(),
353
..demo_record()
354
}
355
}
356
357
fn video_link_entry(previewenabled: Value) -> Value {
358
json!([{
359
"@type": HYPERLINK_TYPE,
360
"itemid": "0",
361
"url": "https://www.youtube.com/watch?v=video_id_01",
362
"preview": {"title": "Sample video", "description": "1K views", "previewurl": THUMBNAIL},
363
"previewenabled": previewenabled,
364
}])
365
}
366
367
fn unfurl_card(id: &str, teams_app_id: Option<&str>) -> Value {
368
let content = json!({
369
"type": "AdaptiveCard",
370
"version": "1.5",
371
"body": [
372
{"type": "Media", "sources": [{"mimeType": "video/mp4", "url": "https://www.youtube.com/watch?v=video_id_01"}]},
373
{"type": "TextBlock", "text": "Sample video"},
374
{"type": "TextBlock", "text": "Sample channel"},
375
],
376
"actions": [{"type": "Action.OpenUrl", "title": "Open", "url": "https://www.youtube.com/watch?v=video_id_01"}],
377
});
378
json!([{
379
"content_type": "application/vnd.microsoft.card.adaptive",
380
"name": null,
381
"url": null,
382
"text": null,
383
"id": id,
384
"content": content.to_string(),
385
"teams_app_id": teams_app_id,
386
}])
387
}
388
389
const VIDEO_BODY: &str = "<p><a href=\"https://www.youtube.com/watch?v=video_id_01\">https://www.youtube.com/watch?v=video_id_01</a></p>";
390
391
#[test]
392
fn a_video_link_with_its_unfurl_card_shows_only_the_card() {
393
let teams_sent = linked_record(
394
VIDEO_BODY,
395
video_link_entry(json!(false)),
396
unfurl_card("app-preview-card-1", None),
397
);
398
assert_eq!(link_preview(&teams_sent), None);
399
let flagged_on = linked_record(
400
VIDEO_BODY,
401
video_link_entry(json!(true)),
402
unfurl_card(
403
"74d20c7f34aa4a7f",
404
Some("4623dd0c-d55c-4c95-9290-ad31619b577a"),
405
),
406
);
407
assert_eq!(link_preview(&flagged_on), None);
408
let by_card_id = linked_record(
409
VIDEO_BODY,
410
video_link_entry(json!(true)),
411
unfurl_card("app-preview-card-2", None),
412
);
413
assert_eq!(link_preview(&by_card_id), None);
414
let cards = crate::stored::adaptive_cards(&flagged_on);
415
assert_eq!(cards.len(), 1);
416
}
417
418
#[test]
419
fn a_video_link_without_a_card_keeps_its_preview() {
420
let record = linked_record(VIDEO_BODY, video_link_entry(json!(true)), json!([]));
421
let preview = link_preview(&record).unwrap();
422
assert_eq!(preview.domain(), "youtube.com");
423
let missing_flag = linked_record(VIDEO_BODY, video_link_entry(Value::Null), json!([]));
424
assert_eq!(link_preview(&missing_flag), None);
425
}
426
427
#[test]
428
fn only_the_first_link_of_the_message_gets_a_preview() {
429
let body = "<p><a href=\"https://other.example/\">other</a> <a href=\"https://www.youtube.com/watch?v=video_id_01\">video</a></p>";
430
let record = linked_record(body, video_link_entry(json!(true)), json!([]));
431
assert_eq!(link_preview(&record), None);
432
assert!(same_link("https://A.example/x/", "https://a.example/x"));
433
}
434
317
435
#[test]
318
436
fn a_removed_preview_is_not_shown() {
319
437
assert_eq!(
@@ -417,7 +535,10 @@ mod tests {
417
535
fn deleted_messages_show_no_preview() {
418
536
let record = MessageRecord {
419
537
deleted: true,
420
links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])),
538
body_html: "<p><a href=\"https://a.example\">a</a></p>".to_owned(),
539
links_json: links(
540
json!([{"url": "https://a.example", "preview": {"title": "A", "description": "D"}, "previewenabled": true}]),
541
),
421
542
..MessageRecord::default()
422
543
};
423
544
assert_eq!(link_preview(&record), None);
@@ -5,7 +5,7 @@ use scraper::{Html, Selector};5
use serde_json::{Value, json};5
use serde_json::{Value, json};6
use store::MessageRecord;6
use store::MessageRecord;7
7
8
use crate::stored::ImageRef;8
use crate::stored::{AttachmentInfo, ImageRef, attachments};9
9
10
pub const EMPTY_LINKS: &str = "[]";10
pub const EMPTY_LINKS: &str = "[]";11
11
@@ -90,7 +90,12 @@ impl LinkPreview {90
}90
}91
91
92
fn is_showable(&self) -> bool {92
fn is_showable(&self) -> bool {93
self.title.is_some() || self.image_url.is_some()93
let parts = [94
self.image_url.is_some(),95
self.title.is_some(),96
self.description.is_some(),97
];98
parts.into_iter().filter(|present| *present).count() >= 294
}99
}95
}100
}96
101
@@ -103,10 +108,11 @@ pub fn has_stored_links(links_json: &str) -> bool {103
}108
}104
109
105
pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {110
pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {106
if record.deleted {111
if record.deleted || has_link_unfurl_card(record) {107
return None;112
return None;108
}113
}109
select_preview(&record.links_json)114
let first_link = first_link(&record.body_html)?;115
select_preview(&record.links_json).filter(|preview| same_link(&preview.url, &first_link))110
}116
}111
117
112
pub fn select_preview(links_json: &str) -> Option<LinkPreview> {118
pub fn select_preview(links_json: &str) -> Option<LinkPreview> {@@ -114,8 +120,27 @@ pub fn select_preview(links_json: &str) -> Option<LinkPreview> {114
entries.iter().find_map(entry_preview)120
entries.iter().find_map(entry_preview)115
}121
}116
122
123
fn has_link_unfurl_card(record: &MessageRecord) -> bool {124
attachments(record)125
.iter()126
.any(AttachmentInfo::is_link_unfurl_card)127
}128
129
fn first_link(html: &str) -> Option<String> {130
let selector = Selector::parse("a[href]").ok()?;131
Html::parse_fragment(html)132
.select(&selector)133
.find_map(|anchor| anchor.value().attr("href"))134
.map(str::to_owned)135
}136
137
fn same_link(first: &str, second: &str) -> bool {138
let normalize = |url: &str| url.trim().trim_end_matches('/').to_ascii_lowercase();139
normalize(first) == normalize(second)140
}141
117
fn entry_preview(entry: &Value) -> Option<LinkPreview> {142
fn entry_preview(entry: &Value) -> Option<LinkPreview> {118
if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) {143
if entry.get("previewenabled").and_then(Value::as_bool) != Some(true) {119
return None;144
return None;120
}145
}121
let url = entry.get("url")?.as_str()?;146
let url = entry.get("url")?.as_str()?;@@ -268,12 +293,13 @@ mod tests {268
}293
}269
294
270
#[test]295
#[test]271
fn picks_the_first_public_link_with_a_title() {296
fn picks_the_first_enabled_public_link_with_two_parts() {272
let preview = select_preview(&links(json!([297
let preview = select_preview(&links(json!([273
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true},298
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File", "description": "F"}, "previewenabled": true},274
{"url": "https://a.example/x", "preview": {}, "previewenabled": true},299
{"url": "https://a.example/x", "preview": {}, "previewenabled": true},275
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}},300
{"url": "https://n.example/x", "preview": {"title": "N", "description": "No flag"}},276
{"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true},301
{"url": "https://t.example/x", "preview": {"title": "Title only"}, "previewenabled": true},302
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}, "previewenabled": true},277
])))303
])))278
.unwrap();304
.unwrap();279
assert_eq!(preview.url, "https://b.example/y");305
assert_eq!(preview.url, "https://b.example/y");@@ -283,9 +309,15 @@ mod tests {283
}309
}284
310
285
#[test]311
#[test]286
fn an_image_alone_is_enough() {312
fn an_image_needs_a_title_or_description() {313
assert_eq!(314
select_preview(&links(json!([315
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL}, "previewenabled": true},316
]))),317
None318
);287
let preview = select_preview(&links(json!([319
let preview = select_preview(&links(json!([288
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null},320
{"url": "https://a.example", "preview": {"description": "D", "previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": true},289
])))321
])))290
.unwrap();322
.unwrap();291
assert_eq!(preview.title, None);323
assert_eq!(preview.title, None);@@ -299,8 +331,7 @@ mod tests {299
#[test]331
#[test]300
fn reads_the_camel_case_meta_and_null_meta() {332
fn reads_the_camel_case_meta_and_null_meta() {301
let preview = select_preview(&links(json!([333
let preview = select_preview(&links(json!([302
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}},334
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}, "previewenabled": true},303
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},304
])))335
])))305
.unwrap();336
.unwrap();306
assert_eq!(337
assert_eq!(@@ -308,12 +339,99 @@ mod tests {308
(Some(20), Some(10))339
(Some(20), Some(10))309
);340
);310
let second = select_preview(&links(json!([341
let second = select_preview(&links(json!([311
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},342
{"url": "https://b.example", "preview": {"title": "B", "description": "D", "previewmeta": null}, "previewenabled": true},312
])))343
])))313
.unwrap();344
.unwrap();314
assert_eq!(second.image_width, None);345
assert_eq!(second.image_width, None);315
}346
}316
347
348
fn linked_record(body_html: &str, links_json: Value, attachments_json: Value) -> MessageRecord {349
MessageRecord {350
body_html: body_html.to_owned(),351
links_json: links(links_json),352
attachments_json: attachments_json.to_string(),353
..demo_record()354
}355
}356
357
fn video_link_entry(previewenabled: Value) -> Value {358
json!([{359
"@type": HYPERLINK_TYPE,360
"itemid": "0",361
"url": "https://www.youtube.com/watch?v=video_id_01",362
"preview": {"title": "Sample video", "description": "1K views", "previewurl": THUMBNAIL},363
"previewenabled": previewenabled,364
}])365
}366
367
fn unfurl_card(id: &str, teams_app_id: Option<&str>) -> Value {368
let content = json!({369
"type": "AdaptiveCard",370
"version": "1.5",371
"body": [372
{"type": "Media", "sources": [{"mimeType": "video/mp4", "url": "https://www.youtube.com/watch?v=video_id_01"}]},373
{"type": "TextBlock", "text": "Sample video"},374
{"type": "TextBlock", "text": "Sample channel"},375
],376
"actions": [{"type": "Action.OpenUrl", "title": "Open", "url": "https://www.youtube.com/watch?v=video_id_01"}],377
});378
json!([{379
"content_type": "application/vnd.microsoft.card.adaptive",380
"name": null,381
"url": null,382
"text": null,383
"id": id,384
"content": content.to_string(),385
"teams_app_id": teams_app_id,386
}])387
}388
389
const VIDEO_BODY: &str = "<p><a href=\"https://www.youtube.com/watch?v=video_id_01\">https://www.youtube.com/watch?v=video_id_01</a></p>";390
391
#[test]392
fn a_video_link_with_its_unfurl_card_shows_only_the_card() {393
let teams_sent = linked_record(394
VIDEO_BODY,395
video_link_entry(json!(false)),396
unfurl_card("app-preview-card-1", None),397
);398
assert_eq!(link_preview(&teams_sent), None);399
let flagged_on = linked_record(400
VIDEO_BODY,401
video_link_entry(json!(true)),402
unfurl_card(403
"74d20c7f34aa4a7f",404
Some("4623dd0c-d55c-4c95-9290-ad31619b577a"),405
),406
);407
assert_eq!(link_preview(&flagged_on), None);408
let by_card_id = linked_record(409
VIDEO_BODY,410
video_link_entry(json!(true)),411
unfurl_card("app-preview-card-2", None),412
);413
assert_eq!(link_preview(&by_card_id), None);414
let cards = crate::stored::adaptive_cards(&flagged_on);415
assert_eq!(cards.len(), 1);416
}417
418
#[test]419
fn a_video_link_without_a_card_keeps_its_preview() {420
let record = linked_record(VIDEO_BODY, video_link_entry(json!(true)), json!([]));421
let preview = link_preview(&record).unwrap();422
assert_eq!(preview.domain(), "youtube.com");423
let missing_flag = linked_record(VIDEO_BODY, video_link_entry(Value::Null), json!([]));424
assert_eq!(link_preview(&missing_flag), None);425
}426
427
#[test]428
fn only_the_first_link_of_the_message_gets_a_preview() {429
let body = "<p><a href=\"https://other.example/\">other</a> <a href=\"https://www.youtube.com/watch?v=video_id_01\">video</a></p>";430
let record = linked_record(body, video_link_entry(json!(true)), json!([]));431
assert_eq!(link_preview(&record), None);432
assert!(same_link("https://A.example/x/", "https://a.example/x"));433
}434
317
#[test]435
#[test]318
fn a_removed_preview_is_not_shown() {436
fn a_removed_preview_is_not_shown() {319
assert_eq!(437
assert_eq!(@@ -417,7 +535,10 @@ mod tests {417
fn deleted_messages_show_no_preview() {535
fn deleted_messages_show_no_preview() {418
let record = MessageRecord {536
let record = MessageRecord {419
deleted: true,537
deleted: true,420
links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])),538
body_html: "<p><a href=\"https://a.example\">a</a></p>".to_owned(),539
links_json: links(540
json!([{"url": "https://a.example", "preview": {"title": "A", "description": "D"}, "previewenabled": true}]),541
),421
..MessageRecord::default()542
..MessageRecord::default()422
};543
};423
assert_eq!(link_preview(&record), None);544
assert_eq!(link_preview(&record), None);@@ -239,6 +239,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {
239
239
)
240
240
}),
241
241
unavailable: false,
242
teams_app_id: attachment.teams_app_id.clone(),
242
243
}
243
244
}
244
245
@@ -239,6 +239,7 @@ pub(crate) fn attachment_info(attachment: &Attachment) -> AttachmentInfo {239
)239
)240
}),240
}),241
unavailable: false,241
unavailable: false,242
teams_app_id: attachment.teams_app_id.clone(),242
}243
}243
}244
}244
245
@@ -12,6 +12,8 @@ use crate::spans::{Span, html_to_spans};
12
12
13
13
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";
14
14
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";
15
const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";
16
const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";
15
17
16
18
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
17
19
pub struct AttachmentInfo {
@@ -31,6 +33,8 @@ pub struct AttachmentInfo {
31
33
/// A forward whose original Graph did not return; it is not fetched again.
32
34
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
33
35
pub unavailable: bool,
36
#[serde(default, skip_serializing_if = "Option::is_none")]
37
pub teams_app_id: Option<String>,
34
38
}
35
39
36
40
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
@@ -108,6 +112,18 @@ impl AttachmentInfo {
108
112
.is_some_and(|content_type| content_type.contains("card"))
109
113
}
110
114
115
pub fn is_link_unfurl_card(&self) -> bool {
116
self.is_card()
117
&& (self
118
.teams_app_id
119
.as_deref()
120
.is_some_and(|app_id| app_id.eq_ignore_ascii_case(LINK_UNFURL_APP_ID))
121
|| self
122
.id
123
.as_deref()
124
.is_some_and(|id| id.starts_with(LINK_UNFURL_CARD_PREFIX)))
125
}
126
111
127
pub fn adaptive_card(&self) -> Option<AdaptiveCard> {
112
128
self.content
113
129
.as_deref()
@@ -1052,6 +1068,7 @@ mod tests {
1052
1068
id: None,
1053
1069
content: None,
1054
1070
unavailable: false,
1071
teams_app_id: None,
1055
1072
}
1056
1073
.file_kind()
1057
1074
};
@@ -1106,6 +1123,7 @@ mod tests {
1106
1123
content_type: Some("messageReference".to_owned()),
1107
1124
content_url: None,
1108
1125
name: None,
1126
teams_app_id: None,
1109
1127
content: Some(
1110
1128
r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),
1111
1129
),
@@ -12,6 +12,8 @@ use crate::spans::{Span, html_to_spans};12
12
13
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";13
const EMOJI_ITEMTYPE: &str = "schema.skype.com/Emoji";14
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";14
const REPLY_ITEMTYPE: &str = "schema.skype.com/Reply";15
const LINK_UNFURL_APP_ID: &str = "4623DD0C-D55C-4C95-9290-AD31619B577A";16
const LINK_UNFURL_CARD_PREFIX: &str = "app-preview-card";15
17
16
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]18
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]17
pub struct AttachmentInfo {19
pub struct AttachmentInfo {@@ -31,6 +33,8 @@ pub struct AttachmentInfo {31
/// A forward whose original Graph did not return; it is not fetched again.33
/// A forward whose original Graph did not return; it is not fetched again.32
#[serde(default, skip_serializing_if = "std::ops::Not::not")]34
#[serde(default, skip_serializing_if = "std::ops::Not::not")]33
pub unavailable: bool,35
pub unavailable: bool,36
#[serde(default, skip_serializing_if = "Option::is_none")]37
pub teams_app_id: Option<String>,34
}38
}35
39
36
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]40
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]@@ -108,6 +112,18 @@ impl AttachmentInfo {108
.is_some_and(|content_type| content_type.contains("card"))112
.is_some_and(|content_type| content_type.contains("card"))109
}113
}110
114
115
pub fn is_link_unfurl_card(&self) -> bool {116
self.is_card()117
&& (self118
.teams_app_id119
.as_deref()120
.is_some_and(|app_id| app_id.eq_ignore_ascii_case(LINK_UNFURL_APP_ID))121
|| self122
.id123
.as_deref()124
.is_some_and(|id| id.starts_with(LINK_UNFURL_CARD_PREFIX)))125
}126
111
pub fn adaptive_card(&self) -> Option<AdaptiveCard> {127
pub fn adaptive_card(&self) -> Option<AdaptiveCard> {112
self.content128
self.content113
.as_deref()129
.as_deref()@@ -1052,6 +1068,7 @@ mod tests {1052
id: None,1068
id: None,1053
content: None,1069
content: None,1054
unavailable: false,1070
unavailable: false,1071
teams_app_id: None,1055
}1072
}1056
.file_kind()1073
.file_kind()1057
};1074
};@@ -1106,6 +1123,7 @@ mod tests {1106
content_type: Some("messageReference".to_owned()),1123
content_type: Some("messageReference".to_owned()),1107
content_url: None,1124
content_url: None,1108
name: None,1125
name: None,1126
teams_app_id: None,1109
content: Some(1127
content: Some(1110
r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),1128
r#"{"messageId":"1728","messagePreview":"Hello","messageSender":{"user":{"displayName":"Adele"}}}"#.to_owned(),1111
),1129
),@@ -0,0 +1,87 @@
1
use url::Url;
2
3
const POSTER_FILE: &str = "maxresdefault.jpg";
4
const FALLBACK_POSTER_FILE: &str = "hqdefault.jpg";
5
6
pub fn video_id(link: &str) -> Option<String> {
7
let parsed = Url::parse(link).ok()?;
8
let host = parsed.host_str()?.to_ascii_lowercase();
9
let host = host
10
.strip_prefix("www.")
11
.or_else(|| host.strip_prefix("m."))
12
.unwrap_or(&host);
13
let mut segments = parsed.path_segments()?;
14
let candidate = match host {
15
"youtu.be" => segments.next().map(str::to_owned),
16
"youtube.com" | "youtube-nocookie.com" => match segments.next()? {
17
"watch" => parsed
18
.query_pairs()
19
.find(|(key, _)| key == "v")
20
.map(|(_, value)| value.into_owned()),
21
"shorts" | "embed" | "live" | "v" => segments.next().map(str::to_owned),
22
_ => None,
23
},
24
_ => None,
25
}?;
26
let valid = !candidate.is_empty()
27
&& candidate
28
.chars()
29
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'));
30
valid.then_some(candidate)
31
}
32
33
pub fn poster_url(link: &str) -> Option<String> {
34
video_id(link).map(|id| format!("https://img.youtube.com/vi/{id}/{POSTER_FILE}"))
35
}
36
37
pub fn fallback_poster_url(poster: &str) -> Option<String> {
38
poster
39
.strip_suffix(POSTER_FILE)
40
.filter(|base| base.starts_with("https://img.youtube.com/vi/"))
41
.map(|base| format!("{base}{FALLBACK_POSTER_FILE}"))
42
}
43
44
#[cfg(test)]
45
mod tests {
46
use super::*;
47
48
#[test]
49
fn reads_the_video_id_from_every_link_form() {
50
for link in [
51
"https://www.youtube.com/watch?v=abc_DEF-123&t=42",
52
"https://youtube.com/watch?feature=share&v=abc_DEF-123",
53
"https://m.youtube.com/watch?v=abc_DEF-123",
54
"https://youtu.be/abc_DEF-123?t=7",
55
"https://www.youtube.com/shorts/abc_DEF-123",
56
"https://www.youtube.com/embed/abc_DEF-123",
57
] {
58
assert_eq!(video_id(link).as_deref(), Some("abc_DEF-123"), "{link}");
59
}
60
}
61
62
#[test]
63
fn other_links_have_no_video() {
64
for link in [
65
"https://example.com/watch?v=abc",
66
"https://www.youtube.com/channel/xyz",
67
"https://www.youtube.com/watch?v=bad%20id",
68
"not a url",
69
] {
70
assert_eq!(video_id(link), None, "{link}");
71
}
72
}
73
74
#[test]
75
fn the_poster_falls_back_to_the_smaller_still() {
76
let poster = poster_url("https://youtu.be/abc").unwrap();
77
assert_eq!(poster, "https://img.youtube.com/vi/abc/maxresdefault.jpg");
78
assert_eq!(
79
fallback_poster_url(&poster).as_deref(),
80
Some("https://img.youtube.com/vi/abc/hqdefault.jpg")
81
);
82
assert_eq!(
83
fallback_poster_url("https://example.com/maxresdefault.jpg"),
84
None
85
);
86
}
87
}
@@ -0,0 +1,87 @@1
use url::Url;2
3
const POSTER_FILE: &str = "maxresdefault.jpg";4
const FALLBACK_POSTER_FILE: &str = "hqdefault.jpg";5
6
pub fn video_id(link: &str) -> Option<String> {7
let parsed = Url::parse(link).ok()?;8
let host = parsed.host_str()?.to_ascii_lowercase();9
let host = host10
.strip_prefix("www.")11
.or_else(|| host.strip_prefix("m."))12
.unwrap_or(&host);13
let mut segments = parsed.path_segments()?;14
let candidate = match host {15
"youtu.be" => segments.next().map(str::to_owned),16
"youtube.com" | "youtube-nocookie.com" => match segments.next()? {17
"watch" => parsed18
.query_pairs()19
.find(|(key, _)| key == "v")20
.map(|(_, value)| value.into_owned()),21
"shorts" | "embed" | "live" | "v" => segments.next().map(str::to_owned),22
_ => None,23
},24
_ => None,25
}?;26
let valid = !candidate.is_empty()27
&& candidate28
.chars()29
.all(|character| character.is_ascii_alphanumeric() || matches!(character, '-' | '_'));30
valid.then_some(candidate)31
}32
33
pub fn poster_url(link: &str) -> Option<String> {34
video_id(link).map(|id| format!("https://img.youtube.com/vi/{id}/{POSTER_FILE}"))35
}36
37
pub fn fallback_poster_url(poster: &str) -> Option<String> {38
poster39
.strip_suffix(POSTER_FILE)40
.filter(|base| base.starts_with("https://img.youtube.com/vi/"))41
.map(|base| format!("{base}{FALLBACK_POSTER_FILE}"))42
}43
44
#[cfg(test)]45
mod tests {46
use super::*;47
48
#[test]49
fn reads_the_video_id_from_every_link_form() {50
for link in [51
"https://www.youtube.com/watch?v=abc_DEF-123&t=42",52
"https://youtube.com/watch?feature=share&v=abc_DEF-123",53
"https://m.youtube.com/watch?v=abc_DEF-123",54
"https://youtu.be/abc_DEF-123?t=7",55
"https://www.youtube.com/shorts/abc_DEF-123",56
"https://www.youtube.com/embed/abc_DEF-123",57
] {58
assert_eq!(video_id(link).as_deref(), Some("abc_DEF-123"), "{link}");59
}60
}61
62
#[test]63
fn other_links_have_no_video() {64
for link in [65
"https://example.com/watch?v=abc",66
"https://www.youtube.com/channel/xyz",67
"https://www.youtube.com/watch?v=bad%20id",68
"not a url",69
] {70
assert_eq!(video_id(link), None, "{link}");71
}72
}73
74
#[test]75
fn the_poster_falls_back_to_the_smaller_still() {76
let poster = poster_url("https://youtu.be/abc").unwrap();77
assert_eq!(poster, "https://img.youtube.com/vi/abc/maxresdefault.jpg");78
assert_eq!(79
fallback_poster_url(&poster).as_deref(),80
Some("https://img.youtube.com/vi/abc/hqdefault.jpg")81
);82
assert_eq!(83
fallback_poster_url("https://example.com/maxresdefault.jpg"),84
None85
);86
}87
}@@ -1022,6 +1022,7 @@ impl Remote for Handle {
1022
1022
Ok(chatsvc::LinkInfo {
1023
1023
url: url.to_owned(),
1024
1024
title: Some("Example".into()),
1025
description: Some("Example page".into()),
1025
1026
..chatsvc::LinkInfo::default()
1026
1027
})
1027
1028
}
@@ -1022,6 +1022,7 @@ impl Remote for Handle {1022
Ok(chatsvc::LinkInfo {1022
Ok(chatsvc::LinkInfo {1023
url: url.to_owned(),1023
url: url.to_owned(),1024
title: Some("Example".into()),1024
title: Some("Example".into()),1025
description: Some("Example page".into()),1025
..chatsvc::LinkInfo::default()1026
..chatsvc::LinkInfo::default()1026
})1027
})1027
}1028
}@@ -95,6 +95,7 @@ pub struct Attachment {
95
95
pub content_url: Option<String>,
96
96
pub name: Option<String>,
97
97
pub content: Option<String>,
98
pub teams_app_id: Option<String>,
98
99
}
99
100
100
101
#[derive(Debug, Clone, Deserialize, PartialEq)]
@@ -95,6 +95,7 @@ pub struct Attachment {95
pub content_url: Option<String>,95
pub content_url: Option<String>,96
pub name: Option<String>,96
pub name: Option<String>,97
pub content: Option<String>,97
pub content: Option<String>,98
pub teams_app_id: Option<String>,98
}99
}99
100
100
#[derive(Debug, Clone, Deserialize, PartialEq)]101
#[derive(Debug, Clone, Deserialize, PartialEq)]