feat(chat): link previews like Teams, received, while typing and sent
- Messages show Teams' own preview card (image, title, description, site) from the chat service links property - The composer shows a preview of the first public link with an X to drop it - After a send the preview is attached to the message, so colleagues in Teams see it too - Internal links (SharePoint, OneDrive, Teams) get no card Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -1086,6 +1086,7 @@ dependencies = [
1086
1086
name = "chatsvc"
1087
1087
version = "0.1.0"
1088
1088
dependencies = [
1089
"base64 0.22.1",
1089
1090
"chrono",
1090
1091
"futures-util",
1091
1092
"percent-encoding",
@@ -1086,6 +1086,7 @@ dependencies = [1086
name = "chatsvc"1086
name = "chatsvc"1087
version = "0.1.0"1087
version = "0.1.0"1088
dependencies = [1088
dependencies = [1089
"base64 0.22.1",1089
"chrono",1090
"chrono",1090
"futures-util",1091
"futures-util",1091
"percent-encoding",1092
"percent-encoding",@@ -15,6 +15,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R
15
15
- Send, edit, delete, react, quote-reply, @mentions
16
16
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste
17
17
- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type
18
- Link previews: card under messages, preview above the composer that goes out with the message
18
19
- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)
19
20
- Read receipts, typing indicator (shown and sent), presence (last known status shown at start), unread jump
20
21
- Select and copy message text, `Ctrl+A` in the composer
@@ -15,6 +15,7 @@ It does chats and channels. Calls, meetings and channel tabs are planned (see [R15
- Send, edit, delete, react, quote-reply, @mentions15
- Send, edit, delete, react, quote-reply, @mentions16
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste16
- Rich text composer: format bar over a selection, `Ctrl+B` / `Ctrl+I` / `Ctrl+U`, lists, quotes, code; Markdown converts as you type or paste17
- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type17
- Emoji by `:` code with English codes and German aliases, `:thumbsup:` and `:)` convert as you type18
- Link previews: card under messages, preview above the composer that goes out with the message18
- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)19
- Inline images, file cards, Adaptive Cards (layout, links, images, buttons: submit, execute, show card, toggle; input fields; task dialogs)19
- Read receipts, typing indicator (shown and sent), presence (last known status shown at start), unread jump20
- Read receipts, typing indicator (shown and sent), presence (last known status shown at start), unread jump20
- Select and copy message text, `Ctrl+A` in the composer21
- Select and copy message text, `Ctrl+A` in the composer@@ -2,7 +2,7 @@
2
2
3
3
Feature parity with the Microsoft Teams desktop client.
4
4
5
**Parity: 65 %** (53 done, 4 partial, 28 missing of 85). Partial counts half.
5
**Parity: 66 %** (54 done, 4 partial, 27 missing of 85). Partial counts half.
6
6
7
7
## By area
8
8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.
10
10
|---|---|---|---|---|
11
11
| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |
12
12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |
13
| [Reading](#reading) | 76 % | 14 | 1 | 4 |
13
| [Reading](#reading) | 82 % | 15 | 1 | 3 |
14
14
| [Writing](#writing) | 75 % | 10 | 1 | 3 |
15
15
| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |
16
16
| [Channels](#channels) | 36 % | 2 | 1 | 4 |
@@ -76,7 +76,7 @@ Feature parity with the Microsoft Teams desktop client.
76
76
| Select and copy message text | Done | |
77
77
| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |
78
78
| Typing indicator | Done | Shows who types in the chat, thread and list preview; sends your own typing |
79
| Link previews | Missing | |
79
| Link previews | Done | One card per message from the chat service, see docs/research/link-previews.md |
80
80
| Loop components | Missing | |
81
81
| Translate a message | Missing | |
82
82
@@ -2,7 +2,7 @@2
2
3
Feature parity with the Microsoft Teams desktop client.3
Feature parity with the Microsoft Teams desktop client.4
4
5
**Parity: 65 %** (53 done, 4 partial, 28 missing of 85). Partial counts half.5
**Parity: 66 %** (54 done, 4 partial, 27 missing of 85). Partial counts half.6
6
7
## By area7
## By area8
8
@@ -10,7 +10,7 @@ Feature parity with the Microsoft Teams desktop client.10
|---|---|---|---|---|10
|---|---|---|---|---|11
| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |11
| [Sign-in and app](#sign-in-and-app) | 75 % | 4 | 1 | 1 |12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |12
| [Chat list](#chat-list) | 90 % | 9 | 0 | 1 |13
| [Reading](#reading) | 76 % | 14 | 1 | 4 |13
| [Reading](#reading) | 82 % | 15 | 1 | 3 |14
| [Writing](#writing) | 75 % | 10 | 1 | 3 |14
| [Writing](#writing) | 75 % | 10 | 1 | 3 |15
| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |15
| [Message actions](#message-actions) | 0 % | 0 | 0 | 4 |16
| [Channels](#channels) | 36 % | 2 | 1 | 4 |16
| [Channels](#channels) | 36 % | 2 | 1 | 4 |@@ -76,7 +76,7 @@ Feature parity with the Microsoft Teams desktop client.76
| Select and copy message text | Done | |76
| Select and copy message text | Done | |77
| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |77
| Adaptive Cards | Partial | Buttons work (submit, execute, show card, toggle, task dialog card). Input fields work in messages and card dialogs (text, number, date, time, toggle, choice set) with validation. URL task dialogs run in a hosted window on Windows (Teams JS SDK host, see docs/research/card-actions.md), in the browser on Linux. Date and time are plain text fields, no picker |78
| Typing indicator | Done | Shows who types in the chat, thread and list preview; sends your own typing |78
| Typing indicator | Done | Shows who types in the chat, thread and list preview; sends your own typing |79
| Link previews | Missing | |79
| Link previews | Done | One card per message from the chat service, see docs/research/link-previews.md |80
| Loop components | Missing | |80
| Loop components | Missing | |81
| Translate a message | Missing | |81
| Translate a message | Missing | |82
82
@@ -9,7 +9,8 @@ use store::{
9
9
TeamLayoutRecord, TeamRecord,
10
10
};
11
11
use teams_core::{
12
CardActionOutcome, ChatApp, MentionCandidate, PersonCandidate, PersonSource, TaskDialog,
12
CardActionOutcome, ChatApp, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,
13
TaskDialog,
13
14
TaskDialogKind,
14
15
};
15
16
@@ -24,6 +25,9 @@ const PHOTO_SIZE: usize = 48;
24
25
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
25
26
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
26
27
const STAGING_SIZE: (usize, usize) = (960, 540);
28
const LINK_IMAGE_KEY: &str =
29
"https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=demo";
30
const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);
27
31
const PRIORITY_CHAT: &str = "demo-chat-priya";
28
32
const BOT_CHAT: &str = "demo-chat-wiki-bot";
29
33
const BOT_NAME: &str = "Wiki Bot";
@@ -649,6 +653,7 @@ pub fn seed_directory(state: &mut AppState) {
649
653
let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
650
654
if std::fs::write(&path, png).is_ok() {
651
655
state.directory.set_image(STAGING_IMAGE_KEY, &path);
656
state.directory.set_image(LINK_IMAGE_KEY, &path);
652
657
}
653
658
}
654
659
state.typing.start(
@@ -681,6 +686,7 @@ fn message(
681
686
sender_id: Some(sender.0.to_owned()),
682
687
sender_name: Some(sender.1.to_owned()),
683
688
sender_application_id: None,
689
links_json: "[]".to_owned(),
684
690
created_at: time,
685
691
edited_at: edited.then_some(time + Duration::minutes(2)),
686
692
deleted: false,
@@ -696,6 +702,25 @@ fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> Messag
696
702
record
697
703
}
698
704
705
fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {
706
record.links_json = links_json;
707
record
708
}
709
710
pub fn link_preview(url: &str) -> Option<LinkPreview> {
711
Some(LinkPreview {
712
url: url.to_owned(),
713
title: Some("Release checklist Q4".to_owned()),
714
description: Some(
715
"Everything that has to be green before the release candidate goes out on Friday."
716
.to_owned(),
717
),
718
image_url: Some(LINK_IMAGE_KEY.to_owned()),
719
image_width: Some(LINK_IMAGE_SIZE.0),
720
image_height: Some(LINK_IMAGE_SIZE.1),
721
})
722
}
723
699
724
fn bot_messages() -> Vec<MessageRecord> {
700
725
let card = serde_json::json!({
701
726
"type": "AdaptiveCard",
@@ -975,6 +1000,21 @@ fn release_messages() -> Vec<MessageRecord> {
975
1000
&likes,
976
1001
false,
977
1002
),
1003
with_links(
1004
message(
1005
chat,
1006
"m2a",
1007
None,
1008
mara,
1009
at(1, 16, 23),
1010
"<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1011
"[]",
1012
false,
1013
),
1014
link_preview("https://example.com/checklist")
1015
.map(|preview| preview.links_json())
1016
.unwrap_or_default(),
1017
),
978
1018
message(
979
1019
chat,
980
1020
"m2b",
@@ -1071,6 +1111,27 @@ fn release_messages() -> Vec<MessageRecord> {
1071
1111
&many,
1072
1112
false,
1073
1113
),
1114
with_links(
1115
message(
1116
chat,
1117
"m7a",
1118
None,
1119
me,
1120
at(0, 13, 37),
1121
"<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",
1122
"[]",
1123
false,
1124
),
1125
LinkPreview {
1126
url: "https://example.com/notes".to_owned(),
1127
title: Some("Release notes 0.2".to_owned()),
1128
description: None,
1129
image_url: None,
1130
image_width: None,
1131
image_height: None,
1132
}
1133
.links_json(),
1134
),
1074
1135
message(
1075
1136
chat,
1076
1137
"m8",
@@ -9,7 +9,8 @@ use store::{9
TeamLayoutRecord, TeamRecord,9
TeamLayoutRecord, TeamRecord,10
};10
};11
use teams_core::{11
use teams_core::{12
CardActionOutcome, ChatApp, MentionCandidate, PersonCandidate, PersonSource, TaskDialog,12
CardActionOutcome, ChatApp, LinkPreview, MentionCandidate, PersonCandidate, PersonSource,13
TaskDialog,13
TaskDialogKind,14
TaskDialogKind,14
};15
};15
16
@@ -24,6 +25,9 @@ const PHOTO_SIZE: usize = 48;24
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";25
const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";25
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";26
const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";26
const STAGING_SIZE: (usize, usize) = (960, 540);27
const STAGING_SIZE: (usize, usize) = (960, 540);28
const LINK_IMAGE_KEY: &str =29
"https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=demo";30
const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);27
const PRIORITY_CHAT: &str = "demo-chat-priya";31
const PRIORITY_CHAT: &str = "demo-chat-priya";28
const BOT_CHAT: &str = "demo-chat-wiki-bot";32
const BOT_CHAT: &str = "demo-chat-wiki-bot";29
const BOT_NAME: &str = "Wiki Bot";33
const BOT_NAME: &str = "Wiki Bot";@@ -649,6 +653,7 @@ pub fn seed_directory(state: &mut AppState) {649
let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);653
let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);650
if std::fs::write(&path, png).is_ok() {654
if std::fs::write(&path, png).is_ok() {651
state.directory.set_image(STAGING_IMAGE_KEY, &path);655
state.directory.set_image(STAGING_IMAGE_KEY, &path);656
state.directory.set_image(LINK_IMAGE_KEY, &path);652
}657
}653
}658
}654
state.typing.start(659
state.typing.start(@@ -681,6 +686,7 @@ fn message(681
sender_id: Some(sender.0.to_owned()),686
sender_id: Some(sender.0.to_owned()),682
sender_name: Some(sender.1.to_owned()),687
sender_name: Some(sender.1.to_owned()),683
sender_application_id: None,688
sender_application_id: None,689
links_json: "[]".to_owned(),684
created_at: time,690
created_at: time,685
edited_at: edited.then_some(time + Duration::minutes(2)),691
edited_at: edited.then_some(time + Duration::minutes(2)),686
deleted: false,692
deleted: false,@@ -696,6 +702,25 @@ fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> Messag696
record702
record697
}703
}698
704
705
fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {706
record.links_json = links_json;707
record708
}709
710
pub fn link_preview(url: &str) -> Option<LinkPreview> {711
Some(LinkPreview {712
url: url.to_owned(),713
title: Some("Release checklist Q4".to_owned()),714
description: Some(715
"Everything that has to be green before the release candidate goes out on Friday."716
.to_owned(),717
),718
image_url: Some(LINK_IMAGE_KEY.to_owned()),719
image_width: Some(LINK_IMAGE_SIZE.0),720
image_height: Some(LINK_IMAGE_SIZE.1),721
})722
}723
699
fn bot_messages() -> Vec<MessageRecord> {724
fn bot_messages() -> Vec<MessageRecord> {700
let card = serde_json::json!({725
let card = serde_json::json!({701
"type": "AdaptiveCard",726
"type": "AdaptiveCard",@@ -975,6 +1000,21 @@ fn release_messages() -> Vec<MessageRecord> {975
&likes,1000
&likes,976
false,1001
false,977
),1002
),1003
with_links(1004
message(1005
chat,1006
"m2a",1007
None,1008
mara,1009
at(1, 16, 23),1010
"<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",1011
"[]",1012
false,1013
),1014
link_preview("https://example.com/checklist")1015
.map(|preview| preview.links_json())1016
.unwrap_or_default(),1017
),978
message(1018
message(979
chat,1019
chat,980
"m2b",1020
"m2b",@@ -1071,6 +1111,27 @@ fn release_messages() -> Vec<MessageRecord> {1071
&many,1111
&many,1072
false,1112
false,1073
),1113
),1114
with_links(1115
message(1116
chat,1117
"m7a",1118
None,1119
me,1120
at(0, 13, 37),1121
"<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",1122
"[]",1123
false,1124
),1125
LinkPreview {1126
url: "https://example.com/notes".to_owned(),1127
title: Some("Release notes 0.2".to_owned()),1128
description: None,1129
image_url: None,1130
image_width: None,1131
image_height: None,1132
}1133
.links_json(),1134
),1074
message(1135
message(1075
chat,1136
chat,1076
"m8",1137
"m8",@@ -271,6 +271,7 @@ mod tests {
271
271
sender_id: Some(sender.into()),
272
272
sender_name: Some("Sender".into()),
273
273
sender_application_id: None,
274
links_json: "[]".to_owned(),
274
275
created_at: at,
275
276
edited_at: None,
276
277
deleted: false,
@@ -271,6 +271,7 @@ mod tests {271
sender_id: Some(sender.into()),271
sender_id: Some(sender.into()),272
sender_name: Some("Sender".into()),272
sender_name: Some("Sender".into()),273
sender_application_id: None,273
sender_application_id: None,274
links_json: "[]".to_owned(),274
created_at: at,275
created_at: at,275
edited_at: None,276
edited_at: None,276
deleted: false,277
deleted: false,@@ -6,8 +6,8 @@ use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6
6
use gpui_kit::Image;
7
7
use store::MessageRecord;
8
8
use teams_core::{
9
AdaptiveCard, Draft, FileCard, ImageRef, ReactionInfo, Span, adaptive_cards, card_texts, files,
10
images, message_spans, reactions,
9
AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,
10
card_texts, files, images, link_preview, message_spans, reactions,
11
11
};
12
12
13
13
use crate::card_state::CardOverride;
@@ -129,6 +129,7 @@ pub struct MessageRow {
129
129
pub images: Vec<ImageRef>,
130
130
pub local_images: Vec<LocalImage>,
131
131
pub files: Vec<FileCard>,
132
pub link_preview: Option<LinkPreview>,
132
133
pub adaptive_cards: Vec<AdaptiveCard>,
133
134
pub reply_count: Option<usize>,
134
135
pub new_marker: bool,
@@ -504,6 +505,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
504
505
images,
505
506
local_images: Vec::new(),
506
507
files: files(record),
508
link_preview: link_preview(record),
507
509
adaptive_cards: match context.card_overrides.get(&record.message_id) {
508
510
Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
509
511
_ => adaptive_cards(record),
@@ -713,6 +715,7 @@ mod tests {
713
715
sender_id: Some("u".into()),
714
716
sender_name: Some("Author".into()),
715
717
sender_application_id: None,
718
links_json: "[]".to_owned(),
716
719
created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
717
720
edited_at: None,
718
721
deleted: false,
@@ -6,8 +6,8 @@ use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};6
use gpui_kit::Image;6
use gpui_kit::Image;7
use store::MessageRecord;7
use store::MessageRecord;8
use teams_core::{8
use teams_core::{9
AdaptiveCard, Draft, FileCard, ImageRef, ReactionInfo, Span, adaptive_cards, card_texts, files,9
AdaptiveCard, Draft, FileCard, ImageRef, LinkPreview, ReactionInfo, Span, adaptive_cards,10
images, message_spans, reactions,10
card_texts, files, images, link_preview, message_spans, reactions,11
};11
};12
12
13
use crate::card_state::CardOverride;13
use crate::card_state::CardOverride;@@ -129,6 +129,7 @@ pub struct MessageRow {129
pub images: Vec<ImageRef>,129
pub images: Vec<ImageRef>,130
pub local_images: Vec<LocalImage>,130
pub local_images: Vec<LocalImage>,131
pub files: Vec<FileCard>,131
pub files: Vec<FileCard>,132
pub link_preview: Option<LinkPreview>,132
pub adaptive_cards: Vec<AdaptiveCard>,133
pub adaptive_cards: Vec<AdaptiveCard>,133
pub reply_count: Option<usize>,134
pub reply_count: Option<usize>,134
pub new_marker: bool,135
pub new_marker: bool,@@ -504,6 +505,7 @@ pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {504
images,505
images,505
local_images: Vec::new(),506
local_images: Vec::new(),506
files: files(record),507
files: files(record),508
link_preview: link_preview(record),507
adaptive_cards: match context.card_overrides.get(&record.message_id) {509
adaptive_cards: match context.card_overrides.get(&record.message_id) {508
Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),510
Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),509
_ => adaptive_cards(record),511
_ => adaptive_cards(record),@@ -713,6 +715,7 @@ mod tests {713
sender_id: Some("u".into()),715
sender_id: Some("u".into()),714
sender_name: Some("Author".into()),716
sender_name: Some("Author".into()),715
sender_application_id: None,717
sender_application_id: None,718
links_json: "[]".to_owned(),716
created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),719
created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),717
edited_at: None,720
edited_at: None,718
deleted: false,721
deleted: false,@@ -21,7 +21,7 @@ use gpui_kit::prelude::FluentBuilder as _;
21
21
use gpui_kit::*;
22
22
use teams_core::{
23
23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,
24
MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
24
LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,
25
25
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,
26
26
};
27
27
@@ -34,6 +34,7 @@ use super::avatar::{person_avatar, square_avatar};
34
34
use super::draft_style::draft_style;
35
35
use super::emoji_popup::{self, EmojiPopup};
36
36
use super::format_toolbar::{self, FormatButton};
37
use super::link_preview::{ComposeLink, draft_link, link_preview_card};
37
38
use super::widgets::{icon, symbol};
38
39
use crate::app_state::AppState;
39
40
use crate::emoji;
@@ -45,6 +46,7 @@ const MIN_ROWS: usize = 1;
45
46
const MAX_ROWS: usize = 8;
46
47
const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);
47
48
const MENTION_LIMIT: usize = 8;
49
const LINK_PREVIEW_DEBOUNCE: Duration = Duration::from_millis(600);
48
50
const MENTION_QUERY_MAX_CHARS: usize = 32;
49
51
const MENTION_QUERY_MAX_WORDS: usize = 3;
50
52
const POPUP_WIDTH: f32 = 380.;
@@ -113,6 +115,7 @@ pub struct Outgoing {
113
115
pub edit: Option<EditPreview>,
114
116
pub images: Vec<OutgoingImage>,
115
117
pub files: Vec<OutgoingFile>,
118
pub link_preview: Option<LinkPreview>,
116
119
}
117
120
118
121
impl Outgoing {
@@ -264,7 +267,8 @@ pub struct Composer {
264
267
demo_failed: HashSet<u64>,
265
268
carry_images_into: Option<String>,
266
269
pending_anchors: HashMap<u64, usize>,
267
_subscriptions: [Subscription; 2],
270
link: ComposeLink,
271
_subscriptions: [Subscription; 3],
268
272
}
269
273
270
274
impl EventEmitter<ComposerEvent> for Composer {}
@@ -401,6 +405,11 @@ impl Composer {
401
405
});
402
406
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);
403
407
let observer = cx.observe(&input, |_, _, cx| cx.notify());
408
let image_observer = cx.observe(&app, |this, _, cx| {
409
if this.link_image_pending(cx) {
410
cx.notify();
411
}
412
});
404
413
let decorations = input.update(cx, |state, cx| {
405
414
(
406
415
state.create_decorations_collection(Vec::new(), cx),
@@ -447,7 +456,8 @@ impl Composer {
447
456
demo_failed: HashSet::new(),
448
457
carry_images_into: None,
449
458
pending_anchors: HashMap::new(),
450
_subscriptions: [subscription, observer],
459
link: ComposeLink::default(),
460
_subscriptions: [subscription, observer, image_observer],
451
461
}
452
462
}
453
463
@@ -463,6 +473,7 @@ impl Composer {
463
473
self.on_change(window, cx);
464
474
self.update_emoji(cx);
465
475
self.update_mention(cx);
476
self.update_link_preview(cx);
466
477
}
467
478
let value = input.read(cx).value();
468
479
if submitted_text(event, &value).is_some()
@@ -1262,6 +1273,86 @@ impl Composer {
1262
1273
cx.notify();
1263
1274
}
1264
1275
1276
fn update_link_preview(&mut self, cx: &mut Context<Self>) {
1277
if self.editing.is_some() {
1278
self.link.reset();
1279
return;
1280
}
1281
let draft = self.current_draft(cx);
1282
if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) {
1283
self.fetch_link_preview(url, cx);
1284
}
1285
cx.notify();
1286
}
1287
1288
fn fetch_link_preview(&mut self, url: String, cx: &mut Context<Self>) {
1289
let (demo, engine) = {
1290
let state = self.app.read(cx);
1291
(state.mode.demo, state.engine.clone())
1292
};
1293
if demo {
1294
let preview = crate::demo::link_preview(&url);
1295
self.finish_link_preview(&url, preview, cx);
1296
return;
1297
}
1298
let Some(engine) = engine else {
1299
return;
1300
};
1301
self.link.lookup = Some(cx.spawn(async move |this, cx| {
1302
cx.background_executor()
1303
.timer(LINK_PREVIEW_DEBOUNCE)
1304
.await;
1305
let task_url = url.clone();
1306
let receiver =
1307
runtime::spawn(async move { engine.link_preview_for(&task_url).await });
1308
if let Ok(Ok(preview)) = receiver.await {
1309
this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx))
1310
.ok();
1311
}
1312
}));
1313
}
1314
1315
fn finish_link_preview(&mut self, url: &str, preview: Option<LinkPreview>, cx: &mut Context<Self>) {
1316
let image = preview.as_ref().and_then(LinkPreview::image);
1317
if !self.link.apply(url, preview) {
1318
return;
1319
}
1320
if let Some(image) = image {
1321
self.app
1322
.update(cx, |state, cx| state.request_images(vec![image], cx));
1323
}
1324
cx.notify();
1325
}
1326
1327
fn link_image_pending(&self, cx: &App) -> bool {
1328
self.link
1329
.shown()
1330
.and_then(LinkPreview::image)
1331
.is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none())
1332
}
1333
1334
fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> {
1335
let preview = self.link.shown()?;
1336
let composer = cx.weak_entity();
1337
let close: super::link_preview::CloseHandler = Rc::new(move |_, cx| {
1338
composer
1339
.update(cx, |this, cx| {
1340
this.link.dismiss();
1341
cx.notify();
1342
})
1343
.ok();
1344
});
1345
Some(
1346
div().w_full().mb(px(6.)).child(link_preview_card(
1347
preview,
1348
"composer-link-preview".to_owned(),
1349
&self.app.read(cx).directory,
1350
true,
1351
Some(close),
1352
)),
1353
)
1354
}
1355
1265
1356
fn popup_is_open(&self) -> bool {
1266
1357
self.emoji_popup.is_some()
1267
1358
|| self
@@ -1345,6 +1436,7 @@ impl Composer {
1345
1436
self.discard_uploaded(dropped, cx);
1346
1437
self.remove_orphan_image_tokens(window, cx);
1347
1438
self.reply = None;
1439
self.link.reset();
1348
1440
if self.editing.take().is_some() {
1349
1441
self.load_draft(Draft::default(), InputContent::new(""), window, cx);
1350
1442
}
@@ -1425,6 +1517,7 @@ impl Composer {
1425
1517
mentions,
1426
1518
reply: self.reply.clone(),
1427
1519
edit: self.editing.clone(),
1520
link_preview: self.link.shown().filter(|_| attachments_apply).cloned(),
1428
1521
images: if attachments_apply {
1429
1522
self.tray.images_in(&image_ids)
1430
1523
} else {
@@ -1864,6 +1957,7 @@ impl Composer {
1864
1957
}
1865
1958
self.reply = None;
1866
1959
self.editing = None;
1960
self.link.reset();
1867
1961
self.close_popup();
1868
1962
cx.emit(ComposerEvent::Submit(Box::new(outgoing)));
1869
1963
cx.notify();
@@ -1904,6 +1998,7 @@ impl Composer {
1904
1998
self.load_draft(outgoing.draft.clone(), content, window, cx);
1905
1999
self.reply = outgoing.reply.clone();
1906
2000
self.editing = outgoing.edit.clone();
2001
self.link.restore(outgoing.link_preview.clone());
1907
2002
self.close_popup();
1908
2003
cx.notify();
1909
2004
}
@@ -1916,6 +2011,7 @@ impl Composer {
1916
2011
self.mention_inputs.clear();
1917
2012
self.update_emoji(cx);
1918
2013
self.update_mention(cx);
2014
self.update_link_preview(cx);
1919
2015
cx.notify();
1920
2016
}
1921
2017
@@ -2480,6 +2576,7 @@ impl Render for Composer {
2480
2576
.children(notice)
2481
2577
.children(self.render_reply_strip(cx))
2482
2578
.children(self.render_edit_strip(cx))
2579
.children(self.render_link_preview(cx))
2483
2580
.child(
2484
2581
div()
2485
2582
.relative()
@@ -2633,6 +2730,7 @@ mod tests {
2633
2730
let outgoing = Outgoing {
2634
2731
draft: teams_core::Draft::default(),
2635
2732
mentions: Vec::new(),
2733
link_preview: None,
2636
2734
reply: None,
2637
2735
edit: None,
2638
2736
images: vec![OutgoingImage {
@@ -2675,6 +2773,7 @@ mod tests {
2675
2773
super::Outgoing {
2676
2774
draft: teams_core::Draft::plain(text),
2677
2775
mentions: Vec::new(),
2776
link_preview: None,
2678
2777
reply: None,
2679
2778
edit: None,
2680
2779
images,
@@ -3662,6 +3761,7 @@ mod tests {
3662
3761
let draft = Outgoing {
3663
3762
draft: teams_core::Draft::plain("old"),
3664
3763
mentions: Vec::new(),
3764
link_preview: None,
3665
3765
reply: None,
3666
3766
edit: Some(EditPreview {
3667
3767
message_id: "m1".into(),
@@ -21,7 +21,7 @@ use gpui_kit::prelude::FluentBuilder as _;21
use gpui_kit::*;21
use gpui_kit::*;22
use teams_core::{22
use teams_core::{23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,23
Draft, DraftLine, Edit, FileReference, FormatState, HostedImage, LineKind, MarkKind,24
MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,24
LinkPreview, MentionCandidate, MentionInput, MessageExtras, OBJECT_MARK, SizeStep, TypingStyle,25
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,25
UploadedFile, changed_span, has_markdown, link_url, map_offset, reverse_edits,26
};26
};27
27
@@ -34,6 +34,7 @@ use super::avatar::{person_avatar, square_avatar};34
use super::draft_style::draft_style;34
use super::draft_style::draft_style;35
use super::emoji_popup::{self, EmojiPopup};35
use super::emoji_popup::{self, EmojiPopup};36
use super::format_toolbar::{self, FormatButton};36
use super::format_toolbar::{self, FormatButton};37
use super::link_preview::{ComposeLink, draft_link, link_preview_card};37
use super::widgets::{icon, symbol};38
use super::widgets::{icon, symbol};38
use crate::app_state::AppState;39
use crate::app_state::AppState;39
use crate::emoji;40
use crate::emoji;@@ -45,6 +46,7 @@ const MIN_ROWS: usize = 1;45
const MAX_ROWS: usize = 8;46
const MAX_ROWS: usize = 8;46
const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);47
const MENTION_DEBOUNCE: Duration = Duration::from_millis(150);47
const MENTION_LIMIT: usize = 8;48
const MENTION_LIMIT: usize = 8;49
const LINK_PREVIEW_DEBOUNCE: Duration = Duration::from_millis(600);48
const MENTION_QUERY_MAX_CHARS: usize = 32;50
const MENTION_QUERY_MAX_CHARS: usize = 32;49
const MENTION_QUERY_MAX_WORDS: usize = 3;51
const MENTION_QUERY_MAX_WORDS: usize = 3;50
const POPUP_WIDTH: f32 = 380.;52
const POPUP_WIDTH: f32 = 380.;@@ -113,6 +115,7 @@ pub struct Outgoing {113
pub edit: Option<EditPreview>,115
pub edit: Option<EditPreview>,114
pub images: Vec<OutgoingImage>,116
pub images: Vec<OutgoingImage>,115
pub files: Vec<OutgoingFile>,117
pub files: Vec<OutgoingFile>,118
pub link_preview: Option<LinkPreview>,116
}119
}117
120
118
impl Outgoing {121
impl Outgoing {@@ -264,7 +267,8 @@ pub struct Composer {264
demo_failed: HashSet<u64>,267
demo_failed: HashSet<u64>,265
carry_images_into: Option<String>,268
carry_images_into: Option<String>,266
pending_anchors: HashMap<u64, usize>,269
pending_anchors: HashMap<u64, usize>,267
_subscriptions: [Subscription; 2],270
link: ComposeLink,271
_subscriptions: [Subscription; 3],268
}272
}269
273
270
impl EventEmitter<ComposerEvent> for Composer {}274
impl EventEmitter<ComposerEvent> for Composer {}@@ -401,6 +405,11 @@ impl Composer {401
});405
});402
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);406
let subscription = cx.subscribe_in(&input, window, Self::on_input_event);403
let observer = cx.observe(&input, |_, _, cx| cx.notify());407
let observer = cx.observe(&input, |_, _, cx| cx.notify());408
let image_observer = cx.observe(&app, |this, _, cx| {409
if this.link_image_pending(cx) {410
cx.notify();411
}412
});404
let decorations = input.update(cx, |state, cx| {413
let decorations = input.update(cx, |state, cx| {405
(414
(406
state.create_decorations_collection(Vec::new(), cx),415
state.create_decorations_collection(Vec::new(), cx),@@ -447,7 +456,8 @@ impl Composer {447
demo_failed: HashSet::new(),456
demo_failed: HashSet::new(),448
carry_images_into: None,457
carry_images_into: None,449
pending_anchors: HashMap::new(),458
pending_anchors: HashMap::new(),450
_subscriptions: [subscription, observer],459
link: ComposeLink::default(),460
_subscriptions: [subscription, observer, image_observer],451
}461
}452
}462
}453
463
@@ -463,6 +473,7 @@ impl Composer {463
self.on_change(window, cx);473
self.on_change(window, cx);464
self.update_emoji(cx);474
self.update_emoji(cx);465
self.update_mention(cx);475
self.update_mention(cx);476
self.update_link_preview(cx);466
}477
}467
let value = input.read(cx).value();478
let value = input.read(cx).value();468
if submitted_text(event, &value).is_some()479
if submitted_text(event, &value).is_some()@@ -1262,6 +1273,86 @@ impl Composer {1262
cx.notify();1273
cx.notify();1263
}1274
}1264
1275
1276
fn update_link_preview(&mut self, cx: &mut Context<Self>) {1277
if self.editing.is_some() {1278
self.link.reset();1279
return;1280
}1281
let draft = self.current_draft(cx);1282
if let Some(url) = self.link.observe(draft_link(&draft), draft.is_blank()) {1283
self.fetch_link_preview(url, cx);1284
}1285
cx.notify();1286
}1287
1288
fn fetch_link_preview(&mut self, url: String, cx: &mut Context<Self>) {1289
let (demo, engine) = {1290
let state = self.app.read(cx);1291
(state.mode.demo, state.engine.clone())1292
};1293
if demo {1294
let preview = crate::demo::link_preview(&url);1295
self.finish_link_preview(&url, preview, cx);1296
return;1297
}1298
let Some(engine) = engine else {1299
return;1300
};1301
self.link.lookup = Some(cx.spawn(async move |this, cx| {1302
cx.background_executor()1303
.timer(LINK_PREVIEW_DEBOUNCE)1304
.await;1305
let task_url = url.clone();1306
let receiver =1307
runtime::spawn(async move { engine.link_preview_for(&task_url).await });1308
if let Ok(Ok(preview)) = receiver.await {1309
this.update(cx, |this, cx| this.finish_link_preview(&url, preview, cx))1310
.ok();1311
}1312
}));1313
}1314
1315
fn finish_link_preview(&mut self, url: &str, preview: Option<LinkPreview>, cx: &mut Context<Self>) {1316
let image = preview.as_ref().and_then(LinkPreview::image);1317
if !self.link.apply(url, preview) {1318
return;1319
}1320
if let Some(image) = image {1321
self.app1322
.update(cx, |state, cx| state.request_images(vec![image], cx));1323
}1324
cx.notify();1325
}1326
1327
fn link_image_pending(&self, cx: &App) -> bool {1328
self.link1329
.shown()1330
.and_then(LinkPreview::image)1331
.is_some_and(|image| self.app.read(cx).directory.image(&image.url).is_none())1332
}1333
1334
fn render_link_preview(&self, cx: &mut Context<Self>) -> Option<Div> {1335
let preview = self.link.shown()?;1336
let composer = cx.weak_entity();1337
let close: super::link_preview::CloseHandler = Rc::new(move |_, cx| {1338
composer1339
.update(cx, |this, cx| {1340
this.link.dismiss();1341
cx.notify();1342
})1343
.ok();1344
});1345
Some(1346
div().w_full().mb(px(6.)).child(link_preview_card(1347
preview,1348
"composer-link-preview".to_owned(),1349
&self.app.read(cx).directory,1350
true,1351
Some(close),1352
)),1353
)1354
}1355
1265
fn popup_is_open(&self) -> bool {1356
fn popup_is_open(&self) -> bool {1266
self.emoji_popup.is_some()1357
self.emoji_popup.is_some()1267
|| self1358
|| self@@ -1345,6 +1436,7 @@ impl Composer {1345
self.discard_uploaded(dropped, cx);1436
self.discard_uploaded(dropped, cx);1346
self.remove_orphan_image_tokens(window, cx);1437
self.remove_orphan_image_tokens(window, cx);1347
self.reply = None;1438
self.reply = None;1439
self.link.reset();1348
if self.editing.take().is_some() {1440
if self.editing.take().is_some() {1349
self.load_draft(Draft::default(), InputContent::new(""), window, cx);1441
self.load_draft(Draft::default(), InputContent::new(""), window, cx);1350
}1442
}@@ -1425,6 +1517,7 @@ impl Composer {1425
mentions,1517
mentions,1426
reply: self.reply.clone(),1518
reply: self.reply.clone(),1427
edit: self.editing.clone(),1519
edit: self.editing.clone(),1520
link_preview: self.link.shown().filter(|_| attachments_apply).cloned(),1428
images: if attachments_apply {1521
images: if attachments_apply {1429
self.tray.images_in(&image_ids)1522
self.tray.images_in(&image_ids)1430
} else {1523
} else {@@ -1864,6 +1957,7 @@ impl Composer {1864
}1957
}1865
self.reply = None;1958
self.reply = None;1866
self.editing = None;1959
self.editing = None;1960
self.link.reset();1867
self.close_popup();1961
self.close_popup();1868
cx.emit(ComposerEvent::Submit(Box::new(outgoing)));1962
cx.emit(ComposerEvent::Submit(Box::new(outgoing)));1869
cx.notify();1963
cx.notify();@@ -1904,6 +1998,7 @@ impl Composer {1904
self.load_draft(outgoing.draft.clone(), content, window, cx);1998
self.load_draft(outgoing.draft.clone(), content, window, cx);1905
self.reply = outgoing.reply.clone();1999
self.reply = outgoing.reply.clone();1906
self.editing = outgoing.edit.clone();2000
self.editing = outgoing.edit.clone();2001
self.link.restore(outgoing.link_preview.clone());1907
self.close_popup();2002
self.close_popup();1908
cx.notify();2003
cx.notify();1909
}2004
}@@ -1916,6 +2011,7 @@ impl Composer {1916
self.mention_inputs.clear();2011
self.mention_inputs.clear();1917
self.update_emoji(cx);2012
self.update_emoji(cx);1918
self.update_mention(cx);2013
self.update_mention(cx);2014
self.update_link_preview(cx);1919
cx.notify();2015
cx.notify();1920
}2016
}1921
2017
@@ -2480,6 +2576,7 @@ impl Render for Composer {2480
.children(notice)2576
.children(notice)2481
.children(self.render_reply_strip(cx))2577
.children(self.render_reply_strip(cx))2482
.children(self.render_edit_strip(cx))2578
.children(self.render_edit_strip(cx))2579
.children(self.render_link_preview(cx))2483
.child(2580
.child(2484
div()2581
div()2485
.relative()2582
.relative()@@ -2633,6 +2730,7 @@ mod tests {2633
let outgoing = Outgoing {2730
let outgoing = Outgoing {2634
draft: teams_core::Draft::default(),2731
draft: teams_core::Draft::default(),2635
mentions: Vec::new(),2732
mentions: Vec::new(),2733
link_preview: None,2636
reply: None,2734
reply: None,2637
edit: None,2735
edit: None,2638
images: vec![OutgoingImage {2736
images: vec![OutgoingImage {@@ -2675,6 +2773,7 @@ mod tests {2675
super::Outgoing {2773
super::Outgoing {2676
draft: teams_core::Draft::plain(text),2774
draft: teams_core::Draft::plain(text),2677
mentions: Vec::new(),2775
mentions: Vec::new(),2776
link_preview: None,2678
reply: None,2777
reply: None,2679
edit: None,2778
edit: None,2680
images,2779
images,@@ -3662,6 +3761,7 @@ mod tests {3662
let draft = Outgoing {3761
let draft = Outgoing {3663
draft: teams_core::Draft::plain("old"),3762
draft: teams_core::Draft::plain("old"),3664
mentions: Vec::new(),3763
mentions: Vec::new(),3764
link_preview: None,3665
reply: None,3765
reply: None,3666
edit: Some(EditPreview {3766
edit: Some(EditPreview {3667
message_id: "m1".into(),3767
message_id: "m1".into(),@@ -16,7 +16,7 @@ use gpui_kit::component::{
16
16
use gpui_kit::prelude::FluentBuilder as _;
17
17
use gpui_kit::*;
18
18
use store::MessageRecord;
19
use teams_core::{FileCard, ImageRef};
19
use teams_core::{FileCard, ImageRef, LinkPreview};
20
20
21
21
use super::adaptive_card::ensure_cards_inputs;
22
22
use super::attachments::FileActions;
@@ -731,7 +731,12 @@ impl ConversationView {
731
731
.enumerate()
732
732
.filter_map(|(index, row)| match row {
733
733
Row::Message(message)
734
if message.images.iter().any(|image| keys.contains(&image.url)) =>
734
if message.images.iter().any(|image| keys.contains(&image.url))
735
|| message
736
.link_preview
737
.as_ref()
738
.and_then(LinkPreview::image)
739
.is_some_and(|image| keys.contains(&image.url)) =>
735
740
{
736
741
Some(index)
737
742
}
@@ -1647,7 +1652,7 @@ impl ConversationView {
1647
1652
let Outgoing {
1648
1653
mentions, reply, ..
1649
1654
} = &sent;
1650
match (&view_mode, reply) {
1655
let record = match (&view_mode, reply) {
1651
1656
(_, Some(reply)) => {
1652
1657
engine
1653
1658
.reply_to_with_extras(
@@ -1686,8 +1691,13 @@ impl ConversationView {
1686
1691
)
1687
1692
.await
1688
1693
}
1694
}?;
1695
if let Some(preview) = &sent.link_preview {
1696
let _ = engine
1697
.attach_link_preview(&conversation_id, &record.message_id, preview)
1698
.await;
1689
1699
}
1690
.map(|_| ())
1700
Ok(())
1691
1701
});
1692
1702
cx.spawn_in(window, async move |this, cx| {
1693
1703
let result = receiver.await;
@@ -1749,6 +1759,7 @@ impl ConversationView {
1749
1759
})
1750
1760
.collect(),
1751
1761
adaptive_cards: Vec::new(),
1762
link_preview: outgoing.link_preview.clone(),
1752
1763
files: outgoing
1753
1764
.files
1754
1765
.iter()
@@ -1848,6 +1859,11 @@ impl ConversationView {
1848
1859
&outgoing.extras(),
1849
1860
)
1850
1861
.await;
1862
if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {
1863
let _ = engine
1864
.attach_link_preview(&chat_id, &record.message_id, preview)
1865
.await;
1866
}
1851
1867
(Some(chat_id), sent.err().map(|error| short_error(&error)))
1852
1868
});
1853
1869
cx.spawn_in(window, async move |this, cx| {
@@ -2160,6 +2176,7 @@ impl ConversationView {
2160
2176
edit: Some(edit),
2161
2177
images: Vec::new(),
2162
2178
files: Vec::new(),
2179
link_preview: None,
2163
2180
};
2164
2181
self.composer
2165
2182
.update(cx, |composer, cx| composer.begin_edit(draft, window, cx));
@@ -2699,8 +2716,9 @@ impl Render for ConversationView {
2699
2716
let missing_images: Vec<ImageRef> = message
2700
2717
.images
2701
2718
.iter()
2702
.filter(|image| app.read(cx).directory.image(&image.url).is_none())
2703
2719
.cloned()
2720
.chain(message.link_preview.as_ref().and_then(LinkPreview::image))
2721
.filter(|image| app.read(cx).directory.image(&image.url).is_none())
2704
2722
.collect();
2705
2723
if !missing_images.is_empty() {
2706
2724
let app = app.clone();
@@ -16,7 +16,7 @@ use gpui_kit::component::{16
use gpui_kit::prelude::FluentBuilder as _;16
use gpui_kit::prelude::FluentBuilder as _;17
use gpui_kit::*;17
use gpui_kit::*;18
use store::MessageRecord;18
use store::MessageRecord;19
use teams_core::{FileCard, ImageRef};19
use teams_core::{FileCard, ImageRef, LinkPreview};20
20
21
use super::adaptive_card::ensure_cards_inputs;21
use super::adaptive_card::ensure_cards_inputs;22
use super::attachments::FileActions;22
use super::attachments::FileActions;@@ -731,7 +731,12 @@ impl ConversationView {731
.enumerate()731
.enumerate()732
.filter_map(|(index, row)| match row {732
.filter_map(|(index, row)| match row {733
Row::Message(message)733
Row::Message(message)734
if message.images.iter().any(|image| keys.contains(&image.url)) =>734
if message.images.iter().any(|image| keys.contains(&image.url))735
|| message736
.link_preview737
.as_ref()738
.and_then(LinkPreview::image)739
.is_some_and(|image| keys.contains(&image.url)) =>735
{740
{736
Some(index)741
Some(index)737
}742
}@@ -1647,7 +1652,7 @@ impl ConversationView {1647
let Outgoing {1652
let Outgoing {1648
mentions, reply, ..1653
mentions, reply, ..1649
} = &sent;1654
} = &sent;1650
match (&view_mode, reply) {1655
let record = match (&view_mode, reply) {1651
(_, Some(reply)) => {1656
(_, Some(reply)) => {1652
engine1657
engine1653
.reply_to_with_extras(1658
.reply_to_with_extras(@@ -1686,8 +1691,13 @@ impl ConversationView {1686
)1691
)1687
.await1692
.await1688
}1693
}1694
}?;1695
if let Some(preview) = &sent.link_preview {1696
let _ = engine1697
.attach_link_preview(&conversation_id, &record.message_id, preview)1698
.await;1689
}1699
}1690
.map(|_| ())1700
Ok(())1691
});1701
});1692
cx.spawn_in(window, async move |this, cx| {1702
cx.spawn_in(window, async move |this, cx| {1693
let result = receiver.await;1703
let result = receiver.await;@@ -1749,6 +1759,7 @@ impl ConversationView {1749
})1759
})1750
.collect(),1760
.collect(),1751
adaptive_cards: Vec::new(),1761
adaptive_cards: Vec::new(),1762
link_preview: outgoing.link_preview.clone(),1752
files: outgoing1763
files: outgoing1753
.files1764
.files1754
.iter()1765
.iter()@@ -1848,6 +1859,11 @@ impl ConversationView {1848
&outgoing.extras(),1859
&outgoing.extras(),1849
)1860
)1850
.await;1861
.await;1862
if let (Ok(record), Some(preview)) = (&sent, &outgoing.link_preview) {1863
let _ = engine1864
.attach_link_preview(&chat_id, &record.message_id, preview)1865
.await;1866
}1851
(Some(chat_id), sent.err().map(|error| short_error(&error)))1867
(Some(chat_id), sent.err().map(|error| short_error(&error)))1852
});1868
});1853
cx.spawn_in(window, async move |this, cx| {1869
cx.spawn_in(window, async move |this, cx| {@@ -2160,6 +2176,7 @@ impl ConversationView {2160
edit: Some(edit),2176
edit: Some(edit),2161
images: Vec::new(),2177
images: Vec::new(),2162
files: Vec::new(),2178
files: Vec::new(),2179
link_preview: None,2163
};2180
};2164
self.composer2181
self.composer2165
.update(cx, |composer, cx| composer.begin_edit(draft, window, cx));2182
.update(cx, |composer, cx| composer.begin_edit(draft, window, cx));@@ -2699,8 +2716,9 @@ impl Render for ConversationView {2699
let missing_images: Vec<ImageRef> = message2716
let missing_images: Vec<ImageRef> = message2700
.images2717
.images2701
.iter()2718
.iter()2702
.filter(|image| app.read(cx).directory.image(&image.url).is_none())2703
.cloned()2719
.cloned()2720
.chain(message.link_preview.as_ref().and_then(LinkPreview::image))2721
.filter(|image| app.read(cx).directory.image(&image.url).is_none())2704
.collect();2722
.collect();2705
if !missing_images.is_empty() {2723
if !missing_images.is_empty() {2706
let app = app.clone();2724
let app = app.clone();@@ -0,0 +1,350 @@
1
use std::rc::Rc;
2
3
use gpui_kit::assets::IconName;
4
use gpui_kit::component::{h_flex, v_flex};
5
use gpui_kit::prelude::FluentBuilder as _;
6
use gpui_kit::*;
7
use teams_core::{LinkPreview, first_public_link};
8
9
use super::widgets::icon;
10
use crate::data::Directory;
11
use crate::theme;
12
13
const CARD_WIDTH: f32 = 360.;
14
const THUMB_WIDTH: f32 = 112.;
15
const THUMB_WIDTH_COMPACT: f32 = 72.;
16
const THUMB_MIN_HEIGHT: f32 = 48.;
17
const THUMB_MAX_HEIGHT: f32 = 112.;
18
const THUMB_RADIUS: f32 = 6.;
19
const CLOSE_SIZE: f32 = 22.;
20
21
pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;
22
23
pub fn thumbnail_size(
24
declared: Option<(u32, u32)>,
25
loaded: Option<(u32, u32)>,
26
width: f32,
27
) -> (f32, f32) {
28
let aspect = declared
29
.or(loaded)
30
.filter(|(width, height)| *width > 0 && *height > 0)
31
.map_or(0.6, |(image_width, image_height)| {
32
image_height as f32 / image_width as f32
33
});
34
(
35
width,
36
(width * aspect)
37
.clamp(THUMB_MIN_HEIGHT, THUMB_MAX_HEIGHT)
38
.round(),
39
)
40
}
41
42
fn thumbnail(
43
preview: &LinkPreview,
44
id: &str,
45
directory: &Directory,
46
width: f32,
47
) -> Option<AnyElement> {
48
let image = preview.image()?;
49
let entry = directory.image(&image.url);
50
let (width, height) = thumbnail_size(
51
image.width.zip(image.height),
52
entry.and_then(|entry| entry.size),
53
width,
54
);
55
let frame = div()
56
.id(ElementId::Name(format!("{id}-thumbnail").into()))
57
.w(px(width))
58
.h(px(height))
59
.flex_none()
60
.rounded(px(THUMB_RADIUS))
61
.overflow_hidden()
62
.bg(theme::background());
63
Some(match entry {
64
Some(entry) => frame
65
.child(
66
img(entry.path.clone())
67
.size_full()
68
.object_fit(ObjectFit::Cover),
69
)
70
.into_any_element(),
71
None => frame
72
.flex()
73
.items_center()
74
.justify_center()
75
.child(icon(IconName::Image, 18., theme::text_muted()))
76
.into_any_element(),
77
})
78
}
79
80
pub fn link_preview_card(
81
preview: &LinkPreview,
82
id: String,
83
directory: &Directory,
84
compact: bool,
85
close: Option<CloseHandler>,
86
) -> AnyElement {
87
let thumb_width = if compact {
88
THUMB_WIDTH_COMPACT
89
} else {
90
THUMB_WIDTH
91
};
92
let url = preview.url.clone();
93
let title = preview.title.clone().unwrap_or_else(|| preview.domain());
94
let close_button = close.map(|close| {
95
div()
96
.id(ElementId::Name(format!("{id}-close").into()))
97
.absolute()
98
.top(px(4.))
99
.right(px(4.))
100
.size(px(CLOSE_SIZE))
101
.flex()
102
.items_center()
103
.justify_center()
104
.rounded(px(6.))
105
.cursor_pointer()
106
.hover(|button| button.bg(theme::row_hover()))
107
.child(icon(IconName::Close, 12., theme::text_muted()))
108
.on_click(move |_, window, cx| {
109
cx.stop_propagation();
110
close(window, cx);
111
})
112
});
113
h_flex()
114
.id(ElementId::Name(id.clone().into()))
115
.relative()
116
.overflow_hidden()
117
.when(compact, |card| card.w_full())
118
.when(!compact, |card| card.w(px(CARD_WIDTH)))
119
.max_w(relative(1.))
120
.gap(px(10.))
121
.p(px(8.))
122
.items_start()
123
.rounded(px(9.))
124
.bg(theme::surface())
125
.border_1()
126
.border_color(theme::border_strong())
127
.cursor_pointer()
128
.hover(|card| card.bg(theme::row_hover()).border_color(theme::accent()))
129
.children(thumbnail(preview, &id, directory, thumb_width))
130
.child(
131
v_flex()
132
.flex_1()
133
.min_w_0()
134
.gap(px(2.))
135
.when(close_button.is_some(), |column| column.pr(px(CLOSE_SIZE)))
136
.child(
137
div()
138
.line_clamp(2)
139
.text_size(px(13.))
140
.font_weight(FontWeight::SEMIBOLD)
141
.text_color(theme::text_strong())
142
.child(title),
143
)
144
.children(preview.description.clone().map(|description| {
145
div()
146
.line_clamp(2)
147
.text_size(px(12.))
148
.text_color(theme::text_muted())
149
.child(description)
150
}))
151
.child(
152
div()
153
.truncate()
154
.text_size(px(11.))
155
.text_color(theme::text_muted())
156
.child(preview.domain()),
157
),
158
)
159
.children(close_button)
160
.on_click(move |_, _, cx| cx.open_url(&url))
161
.into_any_element()
162
}
163
164
#[derive(Default)]
165
pub struct ComposeLink {
166
url: Option<String>,
167
preview: Option<LinkPreview>,
168
dismissed: Option<String>,
169
pub lookup: Option<Task<()>>,
170
}
171
172
impl ComposeLink {
173
pub fn shown(&self) -> Option<&LinkPreview> {
174
self.preview.as_ref()
175
}
176
177
/// The link to look up when the draft's link changed.
178
pub fn observe(&mut self, link: Option<String>, draft_blank: bool) -> Option<String> {
179
if draft_blank {
180
self.reset();
181
return None;
182
}
183
let Some(link) = link else {
184
self.url = None;
185
self.preview = None;
186
self.lookup = None;
187
return None;
188
};
189
if self.url.as_deref() == Some(link.as_str()) {
190
return None;
191
}
192
self.preview = None;
193
self.lookup = None;
194
self.url = Some(link.clone());
195
(self.dismissed.as_deref() != Some(link.as_str())).then_some(link)
196
}
197
198
pub fn apply(&mut self, url: &str, preview: Option<LinkPreview>) -> bool {
199
let current = self.url.as_deref() == Some(url) && self.dismissed.as_deref() != Some(url);
200
if current {
201
self.preview = preview;
202
}
203
current
204
}
205
206
pub fn dismiss(&mut self) {
207
self.dismissed = self.url.clone();
208
self.preview = None;
209
self.lookup = None;
210
}
211
212
pub fn restore(&mut self, preview: Option<LinkPreview>) {
213
self.dismissed = None;
214
self.lookup = None;
215
self.url = preview.as_ref().map(|preview| preview.url.clone());
216
self.preview = preview;
217
}
218
219
pub fn reset(&mut self) {
220
*self = ComposeLink::default();
221
}
222
}
223
224
pub fn draft_link(draft: &teams_core::Draft) -> Option<String> {
225
first_public_link(&draft.to_html()).or_else(|| {
226
draft
227
.plain_text()
228
.split_whitespace()
229
.map(|word| word.trim_end_matches(['.', ',', ';', ':', '!', '?', ')']))
230
.find(|word| {
231
let lower = word.to_ascii_lowercase();
232
(lower.starts_with("http://") || lower.starts_with("https://"))
233
&& teams_core::is_public_link(word)
234
})
235
.map(str::to_owned)
236
})
237
}
238
239
#[cfg(test)]
240
mod tests {
241
use teams_core::LinkPreview;
242
243
use super::{ComposeLink, THUMB_MAX_HEIGHT, THUMB_MIN_HEIGHT, draft_link, thumbnail_size};
244
245
fn preview(url: &str) -> LinkPreview {
246
LinkPreview {
247
url: url.to_owned(),
248
title: Some("Title".to_owned()),
249
description: None,
250
image_url: None,
251
image_width: None,
252
image_height: None,
253
}
254
}
255
256
#[test]
257
fn thumbnails_keep_the_aspect_within_bounds() {
258
assert_eq!(thumbnail_size(Some((320, 160)), None, 112.), (112., 56.));
259
assert_eq!(
260
thumbnail_size(Some((100, 400)), None, 112.),
261
(112., THUMB_MAX_HEIGHT)
262
);
263
assert_eq!(
264
thumbnail_size(Some((400, 20)), None, 112.),
265
(112., THUMB_MIN_HEIGHT)
266
);
267
assert_eq!(thumbnail_size(None, Some((200, 100)), 100.), (100., 50.));
268
assert_eq!(thumbnail_size(None, None, 100.), (100., 60.));
269
}
270
271
#[test]
272
fn a_new_link_is_looked_up_once() {
273
let mut link = ComposeLink::default();
274
assert_eq!(
275
link.observe(Some("https://a.example".into()), false),
276
Some("https://a.example".into())
277
);
278
assert_eq!(link.observe(Some("https://a.example".into()), false), None);
279
assert!(link.apply("https://a.example", Some(preview("https://a.example"))));
280
assert!(link.shown().is_some());
281
assert_eq!(
282
link.observe(Some("https://b.example".into()), false),
283
Some("https://b.example".into())
284
);
285
assert!(link.shown().is_none());
286
}
287
288
#[test]
289
fn a_late_answer_for_an_old_link_is_ignored() {
290
let mut link = ComposeLink::default();
291
link.observe(Some("https://a.example".into()), false);
292
link.observe(Some("https://b.example".into()), false);
293
assert!(!link.apply("https://a.example", Some(preview("https://a.example"))));
294
assert!(link.shown().is_none());
295
}
296
297
#[test]
298
fn a_dismissed_link_stays_hidden_until_the_link_changes_or_the_draft_clears() {
299
let mut link = ComposeLink::default();
300
link.observe(Some("https://a.example".into()), false);
301
link.apply("https://a.example", Some(preview("https://a.example")));
302
link.dismiss();
303
assert!(link.shown().is_none());
304
assert_eq!(link.observe(Some("https://a.example".into()), false), None);
305
assert_eq!(link.observe(None, false), None);
306
assert_eq!(link.observe(Some("https://a.example".into()), false), None);
307
assert!(!link.apply("https://a.example", Some(preview("https://a.example"))));
308
assert_eq!(
309
link.observe(Some("https://b.example".into()), false),
310
Some("https://b.example".into())
311
);
312
link.dismiss();
313
assert_eq!(link.observe(None, true), None);
314
assert_eq!(
315
link.observe(Some("https://b.example".into()), false),
316
Some("https://b.example".into())
317
);
318
}
319
320
#[test]
321
fn removing_the_link_removes_the_card() {
322
let mut link = ComposeLink::default();
323
link.observe(Some("https://a.example".into()), false);
324
link.apply("https://a.example", Some(preview("https://a.example")));
325
assert_eq!(link.observe(None, false), None);
326
assert!(link.shown().is_none());
327
}
328
329
#[test]
330
fn restoring_a_sent_preview_shows_it_without_a_new_lookup() {
331
let mut link = ComposeLink::default();
332
link.restore(Some(preview("https://a.example")));
333
assert!(link.shown().is_some());
334
assert_eq!(link.observe(Some("https://a.example".into()), false), None);
335
assert!(link.shown().is_some());
336
}
337
338
#[test]
339
fn finds_anchors_and_bare_urls_in_a_draft() {
340
let marked = teams_core::Draft::from_markdown("see [docs](https://docs.example/a) now");
341
assert_eq!(
342
draft_link(&marked).as_deref(),
343
Some("https://docs.example/a")
344
);
345
let bare = teams_core::Draft::plain("go to https://b.example/x, ok");
346
assert_eq!(draft_link(&bare).as_deref(), Some("https://b.example/x"));
347
let internal = teams_core::Draft::plain("https://contoso.sharepoint.com/x");
348
assert_eq!(draft_link(&internal), None);
349
}
350
}
@@ -0,0 +1,350 @@1
use std::rc::Rc;2
3
use gpui_kit::assets::IconName;4
use gpui_kit::component::{h_flex, v_flex};5
use gpui_kit::prelude::FluentBuilder as _;6
use gpui_kit::*;7
use teams_core::{LinkPreview, first_public_link};8
9
use super::widgets::icon;10
use crate::data::Directory;11
use crate::theme;12
13
const CARD_WIDTH: f32 = 360.;14
const THUMB_WIDTH: f32 = 112.;15
const THUMB_WIDTH_COMPACT: f32 = 72.;16
const THUMB_MIN_HEIGHT: f32 = 48.;17
const THUMB_MAX_HEIGHT: f32 = 112.;18
const THUMB_RADIUS: f32 = 6.;19
const CLOSE_SIZE: f32 = 22.;20
21
pub type CloseHandler = Rc<dyn Fn(&mut Window, &mut App)>;22
23
pub fn thumbnail_size(24
declared: Option<(u32, u32)>,25
loaded: Option<(u32, u32)>,26
width: f32,27
) -> (f32, f32) {28
let aspect = declared29
.or(loaded)30
.filter(|(width, height)| *width > 0 && *height > 0)31
.map_or(0.6, |(image_width, image_height)| {32
image_height as f32 / image_width as f3233
});34
(35
width,36
(width * aspect)37
.clamp(THUMB_MIN_HEIGHT, THUMB_MAX_HEIGHT)38
.round(),39
)40
}41
42
fn thumbnail(43
preview: &LinkPreview,44
id: &str,45
directory: &Directory,46
width: f32,47
) -> Option<AnyElement> {48
let image = preview.image()?;49
let entry = directory.image(&image.url);50
let (width, height) = thumbnail_size(51
image.width.zip(image.height),52
entry.and_then(|entry| entry.size),53
width,54
);55
let frame = div()56
.id(ElementId::Name(format!("{id}-thumbnail").into()))57
.w(px(width))58
.h(px(height))59
.flex_none()60
.rounded(px(THUMB_RADIUS))61
.overflow_hidden()62
.bg(theme::background());63
Some(match entry {64
Some(entry) => frame65
.child(66
img(entry.path.clone())67
.size_full()68
.object_fit(ObjectFit::Cover),69
)70
.into_any_element(),71
None => frame72
.flex()73
.items_center()74
.justify_center()75
.child(icon(IconName::Image, 18., theme::text_muted()))76
.into_any_element(),77
})78
}79
80
pub fn link_preview_card(81
preview: &LinkPreview,82
id: String,83
directory: &Directory,84
compact: bool,85
close: Option<CloseHandler>,86
) -> AnyElement {87
let thumb_width = if compact {88
THUMB_WIDTH_COMPACT89
} else {90
THUMB_WIDTH91
};92
let url = preview.url.clone();93
let title = preview.title.clone().unwrap_or_else(|| preview.domain());94
let close_button = close.map(|close| {95
div()96
.id(ElementId::Name(format!("{id}-close").into()))97
.absolute()98
.top(px(4.))99
.right(px(4.))100
.size(px(CLOSE_SIZE))101
.flex()102
.items_center()103
.justify_center()104
.rounded(px(6.))105
.cursor_pointer()106
.hover(|button| button.bg(theme::row_hover()))107
.child(icon(IconName::Close, 12., theme::text_muted()))108
.on_click(move |_, window, cx| {109
cx.stop_propagation();110
close(window, cx);111
})112
});113
h_flex()114
.id(ElementId::Name(id.clone().into()))115
.relative()116
.overflow_hidden()117
.when(compact, |card| card.w_full())118
.when(!compact, |card| card.w(px(CARD_WIDTH)))119
.max_w(relative(1.))120
.gap(px(10.))121
.p(px(8.))122
.items_start()123
.rounded(px(9.))124
.bg(theme::surface())125
.border_1()126
.border_color(theme::border_strong())127
.cursor_pointer()128
.hover(|card| card.bg(theme::row_hover()).border_color(theme::accent()))129
.children(thumbnail(preview, &id, directory, thumb_width))130
.child(131
v_flex()132
.flex_1()133
.min_w_0()134
.gap(px(2.))135
.when(close_button.is_some(), |column| column.pr(px(CLOSE_SIZE)))136
.child(137
div()138
.line_clamp(2)139
.text_size(px(13.))140
.font_weight(FontWeight::SEMIBOLD)141
.text_color(theme::text_strong())142
.child(title),143
)144
.children(preview.description.clone().map(|description| {145
div()146
.line_clamp(2)147
.text_size(px(12.))148
.text_color(theme::text_muted())149
.child(description)150
}))151
.child(152
div()153
.truncate()154
.text_size(px(11.))155
.text_color(theme::text_muted())156
.child(preview.domain()),157
),158
)159
.children(close_button)160
.on_click(move |_, _, cx| cx.open_url(&url))161
.into_any_element()162
}163
164
#[derive(Default)]165
pub struct ComposeLink {166
url: Option<String>,167
preview: Option<LinkPreview>,168
dismissed: Option<String>,169
pub lookup: Option<Task<()>>,170
}171
172
impl ComposeLink {173
pub fn shown(&self) -> Option<&LinkPreview> {174
self.preview.as_ref()175
}176
177
/// The link to look up when the draft's link changed.178
pub fn observe(&mut self, link: Option<String>, draft_blank: bool) -> Option<String> {179
if draft_blank {180
self.reset();181
return None;182
}183
let Some(link) = link else {184
self.url = None;185
self.preview = None;186
self.lookup = None;187
return None;188
};189
if self.url.as_deref() == Some(link.as_str()) {190
return None;191
}192
self.preview = None;193
self.lookup = None;194
self.url = Some(link.clone());195
(self.dismissed.as_deref() != Some(link.as_str())).then_some(link)196
}197
198
pub fn apply(&mut self, url: &str, preview: Option<LinkPreview>) -> bool {199
let current = self.url.as_deref() == Some(url) && self.dismissed.as_deref() != Some(url);200
if current {201
self.preview = preview;202
}203
current204
}205
206
pub fn dismiss(&mut self) {207
self.dismissed = self.url.clone();208
self.preview = None;209
self.lookup = None;210
}211
212
pub fn restore(&mut self, preview: Option<LinkPreview>) {213
self.dismissed = None;214
self.lookup = None;215
self.url = preview.as_ref().map(|preview| preview.url.clone());216
self.preview = preview;217
}218
219
pub fn reset(&mut self) {220
*self = ComposeLink::default();221
}222
}223
224
pub fn draft_link(draft: &teams_core::Draft) -> Option<String> {225
first_public_link(&draft.to_html()).or_else(|| {226
draft227
.plain_text()228
.split_whitespace()229
.map(|word| word.trim_end_matches(['.', ',', ';', ':', '!', '?', ')']))230
.find(|word| {231
let lower = word.to_ascii_lowercase();232
(lower.starts_with("http://") || lower.starts_with("https://"))233
&& teams_core::is_public_link(word)234
})235
.map(str::to_owned)236
})237
}238
239
#[cfg(test)]240
mod tests {241
use teams_core::LinkPreview;242
243
use super::{ComposeLink, THUMB_MAX_HEIGHT, THUMB_MIN_HEIGHT, draft_link, thumbnail_size};244
245
fn preview(url: &str) -> LinkPreview {246
LinkPreview {247
url: url.to_owned(),248
title: Some("Title".to_owned()),249
description: None,250
image_url: None,251
image_width: None,252
image_height: None,253
}254
}255
256
#[test]257
fn thumbnails_keep_the_aspect_within_bounds() {258
assert_eq!(thumbnail_size(Some((320, 160)), None, 112.), (112., 56.));259
assert_eq!(260
thumbnail_size(Some((100, 400)), None, 112.),261
(112., THUMB_MAX_HEIGHT)262
);263
assert_eq!(264
thumbnail_size(Some((400, 20)), None, 112.),265
(112., THUMB_MIN_HEIGHT)266
);267
assert_eq!(thumbnail_size(None, Some((200, 100)), 100.), (100., 50.));268
assert_eq!(thumbnail_size(None, None, 100.), (100., 60.));269
}270
271
#[test]272
fn a_new_link_is_looked_up_once() {273
let mut link = ComposeLink::default();274
assert_eq!(275
link.observe(Some("https://a.example".into()), false),276
Some("https://a.example".into())277
);278
assert_eq!(link.observe(Some("https://a.example".into()), false), None);279
assert!(link.apply("https://a.example", Some(preview("https://a.example"))));280
assert!(link.shown().is_some());281
assert_eq!(282
link.observe(Some("https://b.example".into()), false),283
Some("https://b.example".into())284
);285
assert!(link.shown().is_none());286
}287
288
#[test]289
fn a_late_answer_for_an_old_link_is_ignored() {290
let mut link = ComposeLink::default();291
link.observe(Some("https://a.example".into()), false);292
link.observe(Some("https://b.example".into()), false);293
assert!(!link.apply("https://a.example", Some(preview("https://a.example"))));294
assert!(link.shown().is_none());295
}296
297
#[test]298
fn a_dismissed_link_stays_hidden_until_the_link_changes_or_the_draft_clears() {299
let mut link = ComposeLink::default();300
link.observe(Some("https://a.example".into()), false);301
link.apply("https://a.example", Some(preview("https://a.example")));302
link.dismiss();303
assert!(link.shown().is_none());304
assert_eq!(link.observe(Some("https://a.example".into()), false), None);305
assert_eq!(link.observe(None, false), None);306
assert_eq!(link.observe(Some("https://a.example".into()), false), None);307
assert!(!link.apply("https://a.example", Some(preview("https://a.example"))));308
assert_eq!(309
link.observe(Some("https://b.example".into()), false),310
Some("https://b.example".into())311
);312
link.dismiss();313
assert_eq!(link.observe(None, true), None);314
assert_eq!(315
link.observe(Some("https://b.example".into()), false),316
Some("https://b.example".into())317
);318
}319
320
#[test]321
fn removing_the_link_removes_the_card() {322
let mut link = ComposeLink::default();323
link.observe(Some("https://a.example".into()), false);324
link.apply("https://a.example", Some(preview("https://a.example")));325
assert_eq!(link.observe(None, false), None);326
assert!(link.shown().is_none());327
}328
329
#[test]330
fn restoring_a_sent_preview_shows_it_without_a_new_lookup() {331
let mut link = ComposeLink::default();332
link.restore(Some(preview("https://a.example")));333
assert!(link.shown().is_some());334
assert_eq!(link.observe(Some("https://a.example".into()), false), None);335
assert!(link.shown().is_some());336
}337
338
#[test]339
fn finds_anchors_and_bare_urls_in_a_draft() {340
let marked = teams_core::Draft::from_markdown("see [docs](https://docs.example/a) now");341
assert_eq!(342
draft_link(&marked).as_deref(),343
Some("https://docs.example/a")344
);345
let bare = teams_core::Draft::plain("go to https://b.example/x, ok");346
assert_eq!(draft_link(&bare).as_deref(), Some("https://b.example/x"));347
let internal = teams_core::Draft::plain("https://contoso.sharepoint.com/x");348
assert_eq!(draft_link(&internal), None);349
}350
}@@ -7,6 +7,7 @@ use std::time::Duration;
7
7
use super::adaptive_card::cards_view;
8
8
use super::attachments::{FileActions, attachments_view, message_body};
9
9
use super::avatar::{bot_avatar, member_stack, person_avatar};
10
use super::link_preview::link_preview_card;
10
11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};
11
12
use super::reaction_picker::PickHandler;
12
13
use super::reaction_pills::{ReactionControls, reaction_pills};
@@ -146,6 +147,15 @@ fn bubble(
146
147
directory,
147
148
extras.files.as_ref(),
148
149
));
150
content = content.children(row.link_preview.as_ref().map(|preview| {
151
link_preview_card(
152
preview,
153
format!("message-{index}-link"),
154
directory,
155
false,
156
None,
157
)
158
}));
149
159
content = content.children(cards_view(
150
160
&row.adaptive_cards,
151
161
&row.conversation_id,
@@ -478,6 +488,15 @@ fn post_card(
478
488
directory,
479
489
files,
480
490
));
491
body = body.children(row.link_preview.as_ref().map(|preview| {
492
link_preview_card(
493
preview,
494
format!("message-{index}-link"),
495
directory,
496
false,
497
None,
498
)
499
}));
481
500
body = body.children(cards_view(
482
501
&row.adaptive_cards,
483
502
&row.conversation_id,
@@ -7,6 +7,7 @@ use std::time::Duration;7
use super::adaptive_card::cards_view;7
use super::adaptive_card::cards_view;8
use super::attachments::{FileActions, attachments_view, message_body};8
use super::attachments::{FileActions, attachments_view, message_body};9
use super::avatar::{bot_avatar, member_stack, person_avatar};9
use super::avatar::{bot_avatar, member_stack, person_avatar};10
use super::link_preview::link_preview_card;10
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};11
use super::message_actions::{HoverChange, MessageMenu, message_toolbar};11
use super::reaction_picker::PickHandler;12
use super::reaction_picker::PickHandler;12
use super::reaction_pills::{ReactionControls, reaction_pills};13
use super::reaction_pills::{ReactionControls, reaction_pills};@@ -146,6 +147,15 @@ fn bubble(146
directory,147
directory,147
extras.files.as_ref(),148
extras.files.as_ref(),148
));149
));150
content = content.children(row.link_preview.as_ref().map(|preview| {151
link_preview_card(152
preview,153
format!("message-{index}-link"),154
directory,155
false,156
None,157
)158
}));149
content = content.children(cards_view(159
content = content.children(cards_view(150
&row.adaptive_cards,160
&row.adaptive_cards,151
&row.conversation_id,161
&row.conversation_id,@@ -478,6 +488,15 @@ fn post_card(478
directory,488
directory,479
files,489
files,480
));490
));491
body = body.children(row.link_preview.as_ref().map(|preview| {492
link_preview_card(493
preview,494
format!("message-{index}-link"),495
directory,496
false,497
None,498
)499
}));481
body = body.children(cards_view(500
body = body.children(cards_view(482
&row.adaptive_cards,501
&row.adaptive_cards,483
&row.conversation_id,502
&row.conversation_id,@@ -10,6 +10,7 @@ pub mod dialog_overlay;
10
10
pub mod draft_style;
11
11
pub mod emoji_popup;
12
12
pub mod format_toolbar;
13
pub mod link_preview;
13
14
pub mod message_actions;
14
15
pub mod message_row;
15
16
pub mod new_chat;
@@ -10,6 +10,7 @@ pub mod dialog_overlay;10
pub mod draft_style;10
pub mod draft_style;11
pub mod emoji_popup;11
pub mod emoji_popup;12
pub mod format_toolbar;12
pub mod format_toolbar;13
pub mod link_preview;13
pub mod message_actions;14
pub mod message_actions;14
pub mod message_row;15
pub mod message_row;15
pub mod new_chat;16
pub mod new_chat;@@ -6,6 +6,7 @@ license.workspace = true
6
6
publish.workspace = true
7
7
8
8
[dependencies]
9
base64.workspace = true
9
10
chrono.workspace = true
10
11
futures-util.workspace = true
11
12
percent-encoding.workspace = true
@@ -6,6 +6,7 @@ license.workspace = true6
publish.workspace = true6
publish.workspace = true7
7
8
[dependencies]8
[dependencies]9
base64.workspace = true9
chrono.workspace = true10
chrono.workspace = true10
futures-util.workspace = true11
futures-util.workspace = true11
percent-encoding.workspace = true12
percent-encoding.workspace = true@@ -1,6 +1,7 @@
1
1
pub mod cards;
2
2
pub mod conversations;
3
3
mod error;
4
pub mod links;
4
5
mod mask;
5
6
pub mod messages;
6
7
pub mod pins;
@@ -14,6 +15,7 @@ pub use cards::{
14
15
pub use conversations::Conversations;
15
16
pub use error::{Error, Result};
16
17
pub use mask::mask_conversation_id;
18
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};
17
19
pub use messages::{ConversationRef, Messages};
18
20
pub use pins::{
19
21
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,
@@ -1,6 +1,7 @@1
pub mod cards;1
pub mod cards;2
pub mod conversations;2
pub mod conversations;3
mod error;3
mod error;4
pub mod links;4
mod mask;5
mod mask;5
pub mod messages;6
pub mod messages;6
pub mod pins;7
pub mod pins;@@ -14,6 +15,7 @@ pub use cards::{14
pub use conversations::Conversations;15
pub use conversations::Conversations;15
pub use error::{Error, Result};16
pub use error::{Error, Result};16
pub use mask::mask_conversation_id;17
pub use mask::mask_conversation_id;18
pub use links::{LinkImage, LinkInfo, MessageLinks, is_link_image_url};17
pub use messages::{ConversationRef, Messages};19
pub use messages::{ConversationRef, Messages};18
pub use pins::{20
pub use pins::{19
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,21
ChannelLayout, Folder, FolderKind, Folders, PinnedChannels, PinnedChats, Pins, TeamLayout,@@ -0,0 +1,229 @@
1
use base64::Engine as _;
2
use base64::engine::general_purpose::STANDARD;
3
use serde_json::{Value, json};
4
use session::{Method, Request};
5
6
use crate::error::{Error, Result};
7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};
8
9
const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";
10
const IMAGE_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";
11
const LIST_VIEW: &str = "msnp24Equivalent";
12
13
#[derive(Debug, Clone, PartialEq, Eq)]
14
pub struct MessageLinks {
15
pub message_id: String,
16
pub links_json: String,
17
}
18
19
#[derive(Debug, Clone, Default, PartialEq, Eq)]
20
pub struct LinkInfo {
21
pub url: String,
22
pub title: Option<String>,
23
pub description: Option<String>,
24
pub site: Option<String>,
25
pub thumbnail: Option<String>,
26
pub thumbnail_width: Option<u32>,
27
pub thumbnail_height: Option<u32>,
28
}
29
30
#[derive(Debug, Clone, PartialEq, Eq)]
31
pub struct LinkImage {
32
pub bytes: Vec<u8>,
33
pub content_type: String,
34
}
35
36
pub fn is_link_image_url(url: &str) -> bool {
37
url.strip_prefix("https://")
38
.and_then(|rest| rest.split(['/', '?', '#']).next())
39
.is_some_and(|host| host.ends_with(IMAGE_HOST_SUFFIX))
40
}
41
42
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {
43
body.get("messages")
44
.and_then(Value::as_array)
45
.into_iter()
46
.flatten()
47
.filter_map(|message| {
48
let message_id = message.get("id")?.as_str()?.to_owned();
49
let links_json = match message.pointer("/properties/links")? {
50
Value::String(text) => text.clone(),
51
array @ Value::Array(_) => array.to_string(),
52
_ => return None,
53
};
54
Some(MessageLinks {
55
message_id,
56
links_json,
57
})
58
})
59
.collect()
60
}
61
62
pub fn parse_link_info(body: &Value) -> LinkInfo {
63
let text = |key: &str| {
64
body.get(key)
65
.and_then(Value::as_str)
66
.map(str::trim)
67
.filter(|value| !value.is_empty())
68
.map(str::to_owned)
69
};
70
let size = |key: &str| {
71
body.pointer(&format!("/thumbnail_meta/{key}"))
72
.and_then(Value::as_u64)
73
.and_then(|value| u32::try_from(value).ok())
74
.filter(|value| *value > 0)
75
};
76
LinkInfo {
77
url: text("target_url")
78
.or_else(|| text("url"))
79
.unwrap_or_default(),
80
title: text("title"),
81
description: text("description"),
82
site: text("site"),
83
thumbnail: text("thumbnail"),
84
thumbnail_width: size("width"),
85
thumbnail_height: size("height"),
86
}
87
}
88
89
impl<T: MessageTransport> Messages<T> {
90
pub async fn list_message_links(
91
&self,
92
conversation: &ConversationRef,
93
page_size: usize,
94
) -> Result<Vec<MessageLinks>> {
95
let url = format!(
96
"{}/{}/messages?view={LIST_VIEW}&pageSize={page_size}",
97
self.base_url,
98
encode(&conversation.conversation_id())
99
);
100
let answer = self.transport.send(Request::get(&url)).await?;
101
ensure_success(&answer)?;
102
Ok(parse_message_links(&answer.body))
103
}
104
105
pub async fn set_links(
106
&self,
107
conversation: &ConversationRef,
108
message_id: &str,
109
links_json: &str,
110
) -> Result<()> {
111
let url = format!(
112
"{}/properties?name=links",
113
self.message_url(conversation, message_id)
114
);
115
let body = json!({"links": links_json});
116
let answer = self
117
.transport
118
.send(Request::with_body(Method::Put, url, body))
119
.await?;
120
ensure_success(&answer)
121
}
122
123
pub async fn link_info(&self, url: &str) -> Result<LinkInfo> {
124
let request_url = format!("{URLP_BASE}/info?url={}", encode(url));
125
let answer = self.transport.send(Request::get(&request_url)).await?;
126
ensure_success(&answer)?;
127
Ok(parse_link_info(&answer.body))
128
}
129
130
pub async fn link_image(&self, url: &str) -> Result<LinkImage> {
131
if !is_link_image_url(url) {
132
return Err(Error::UnexpectedAnswer(format!(
133
"not a link preview image url: {url}"
134
)));
135
}
136
let answer = self.transport.send(Request::binary_get(url)).await?;
137
ensure_success(&answer)?;
138
let encoded = answer
139
.body
140
.get("base64")
141
.and_then(Value::as_str)
142
.unwrap_or_default();
143
let bytes = STANDARD
144
.decode(encoded.as_bytes())
145
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;
146
let content_type = answer
147
.body
148
.get("contentType")
149
.and_then(Value::as_str)
150
.unwrap_or_default()
151
.to_owned();
152
Ok(LinkImage {
153
bytes,
154
content_type,
155
})
156
}
157
}
158
159
#[cfg(test)]
160
mod tests {
161
use super::*;
162
163
#[test]
164
fn parses_link_info_with_target_url_and_thumbnail_size() {
165
let info = parse_link_info(&json!({
166
"title": " Rust ",
167
"description": "",
168
"site": "GitHub",
169
"thumbnail": "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x",
170
"thumbnail_meta": {"height": 160, "width": 320},
171
"url": "https://github.com/a",
172
"target_url": "https://github.com/rust-lang/rust",
173
}));
174
assert_eq!(info.url, "https://github.com/rust-lang/rust");
175
assert_eq!(info.title.as_deref(), Some("Rust"));
176
assert_eq!(info.description, None);
177
assert_eq!(info.site.as_deref(), Some("GitHub"));
178
assert_eq!(
179
(info.thumbnail_width, info.thumbnail_height),
180
(Some(320), Some(160))
181
);
182
}
183
184
#[test]
185
fn link_info_tolerates_missing_fields() {
186
let info = parse_link_info(&json!({"url": "https://a.example", "thumbnail_meta": null}));
187
assert_eq!(info.url, "https://a.example");
188
assert_eq!(info.title, None);
189
assert_eq!(info.thumbnail, None);
190
assert_eq!(info.thumbnail_width, None);
191
}
192
193
#[test]
194
fn reads_links_as_string_or_array_and_skips_messages_without() {
195
let links = parse_message_links(&json!({"messages": [
196
{"id": "1", "properties": {"links": "[{\"url\":\"https://a\"}]"}},
197
{"id": "2", "properties": {"links": [{"url": "https://b"}]}},
198
{"id": "3", "properties": {}},
199
{"id": "4"},
200
{"properties": {"links": "[]"}},
201
]}));
202
assert_eq!(
203
links,
204
vec![
205
MessageLinks {
206
message_id: "1".into(),
207
links_json: "[{\"url\":\"https://a\"}]".into()
208
},
209
MessageLinks {
210
message_id: "2".into(),
211
links_json: "[{\"url\":\"https://b\"}]".into()
212
},
213
]
214
);
215
}
216
217
#[test]
218
fn only_asyncgw_hosts_receive_the_token() {
219
assert!(is_link_image_url(
220
"https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x"
221
));
222
assert!(!is_link_image_url(
223
"https://evil.example/?a=.asyncgw.teams.microsoft.com"
224
));
225
assert!(!is_link_image_url(
226
"http://de-prod.asyncgw.teams.microsoft.com/x"
227
));
228
}
229
}
@@ -0,0 +1,229 @@1
use base64::Engine as _;2
use base64::engine::general_purpose::STANDARD;3
use serde_json::{Value, json};4
use session::{Method, Request};5
6
use crate::error::{Error, Result};7
use crate::messages::{ConversationRef, MessageTransport, Messages, encode, ensure_success};8
9
const URLP_BASE: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url";10
const IMAGE_HOST_SUFFIX: &str = ".asyncgw.teams.microsoft.com";11
const LIST_VIEW: &str = "msnp24Equivalent";12
13
#[derive(Debug, Clone, PartialEq, Eq)]14
pub struct MessageLinks {15
pub message_id: String,16
pub links_json: String,17
}18
19
#[derive(Debug, Clone, Default, PartialEq, Eq)]20
pub struct LinkInfo {21
pub url: String,22
pub title: Option<String>,23
pub description: Option<String>,24
pub site: Option<String>,25
pub thumbnail: Option<String>,26
pub thumbnail_width: Option<u32>,27
pub thumbnail_height: Option<u32>,28
}29
30
#[derive(Debug, Clone, PartialEq, Eq)]31
pub struct LinkImage {32
pub bytes: Vec<u8>,33
pub content_type: String,34
}35
36
pub fn is_link_image_url(url: &str) -> bool {37
url.strip_prefix("https://")38
.and_then(|rest| rest.split(['/', '?', '#']).next())39
.is_some_and(|host| host.ends_with(IMAGE_HOST_SUFFIX))40
}41
42
pub fn parse_message_links(body: &Value) -> Vec<MessageLinks> {43
body.get("messages")44
.and_then(Value::as_array)45
.into_iter()46
.flatten()47
.filter_map(|message| {48
let message_id = message.get("id")?.as_str()?.to_owned();49
let links_json = match message.pointer("/properties/links")? {50
Value::String(text) => text.clone(),51
array @ Value::Array(_) => array.to_string(),52
_ => return None,53
};54
Some(MessageLinks {55
message_id,56
links_json,57
})58
})59
.collect()60
}61
62
pub fn parse_link_info(body: &Value) -> LinkInfo {63
let text = |key: &str| {64
body.get(key)65
.and_then(Value::as_str)66
.map(str::trim)67
.filter(|value| !value.is_empty())68
.map(str::to_owned)69
};70
let size = |key: &str| {71
body.pointer(&format!("/thumbnail_meta/{key}"))72
.and_then(Value::as_u64)73
.and_then(|value| u32::try_from(value).ok())74
.filter(|value| *value > 0)75
};76
LinkInfo {77
url: text("target_url")78
.or_else(|| text("url"))79
.unwrap_or_default(),80
title: text("title"),81
description: text("description"),82
site: text("site"),83
thumbnail: text("thumbnail"),84
thumbnail_width: size("width"),85
thumbnail_height: size("height"),86
}87
}88
89
impl<T: MessageTransport> Messages<T> {90
pub async fn list_message_links(91
&self,92
conversation: &ConversationRef,93
page_size: usize,94
) -> Result<Vec<MessageLinks>> {95
let url = format!(96
"{}/{}/messages?view={LIST_VIEW}&pageSize={page_size}",97
self.base_url,98
encode(&conversation.conversation_id())99
);100
let answer = self.transport.send(Request::get(&url)).await?;101
ensure_success(&answer)?;102
Ok(parse_message_links(&answer.body))103
}104
105
pub async fn set_links(106
&self,107
conversation: &ConversationRef,108
message_id: &str,109
links_json: &str,110
) -> Result<()> {111
let url = format!(112
"{}/properties?name=links",113
self.message_url(conversation, message_id)114
);115
let body = json!({"links": links_json});116
let answer = self117
.transport118
.send(Request::with_body(Method::Put, url, body))119
.await?;120
ensure_success(&answer)121
}122
123
pub async fn link_info(&self, url: &str) -> Result<LinkInfo> {124
let request_url = format!("{URLP_BASE}/info?url={}", encode(url));125
let answer = self.transport.send(Request::get(&request_url)).await?;126
ensure_success(&answer)?;127
Ok(parse_link_info(&answer.body))128
}129
130
pub async fn link_image(&self, url: &str) -> Result<LinkImage> {131
if !is_link_image_url(url) {132
return Err(Error::UnexpectedAnswer(format!(133
"not a link preview image url: {url}"134
)));135
}136
let answer = self.transport.send(Request::binary_get(url)).await?;137
ensure_success(&answer)?;138
let encoded = answer139
.body140
.get("base64")141
.and_then(Value::as_str)142
.unwrap_or_default();143
let bytes = STANDARD144
.decode(encoded.as_bytes())145
.map_err(|error| Error::UnexpectedAnswer(error.to_string()))?;146
let content_type = answer147
.body148
.get("contentType")149
.and_then(Value::as_str)150
.unwrap_or_default()151
.to_owned();152
Ok(LinkImage {153
bytes,154
content_type,155
})156
}157
}158
159
#[cfg(test)]160
mod tests {161
use super::*;162
163
#[test]164
fn parses_link_info_with_target_url_and_thumbnail_size() {165
let info = parse_link_info(&json!({166
"title": " Rust ",167
"description": "",168
"site": "GitHub",169
"thumbnail": "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x",170
"thumbnail_meta": {"height": 160, "width": 320},171
"url": "https://github.com/a",172
"target_url": "https://github.com/rust-lang/rust",173
}));174
assert_eq!(info.url, "https://github.com/rust-lang/rust");175
assert_eq!(info.title.as_deref(), Some("Rust"));176
assert_eq!(info.description, None);177
assert_eq!(info.site.as_deref(), Some("GitHub"));178
assert_eq!(179
(info.thumbnail_width, info.thumbnail_height),180
(Some(320), Some(160))181
);182
}183
184
#[test]185
fn link_info_tolerates_missing_fields() {186
let info = parse_link_info(&json!({"url": "https://a.example", "thumbnail_meta": null}));187
assert_eq!(info.url, "https://a.example");188
assert_eq!(info.title, None);189
assert_eq!(info.thumbnail, None);190
assert_eq!(info.thumbnail_width, None);191
}192
193
#[test]194
fn reads_links_as_string_or_array_and_skips_messages_without() {195
let links = parse_message_links(&json!({"messages": [196
{"id": "1", "properties": {"links": "[{\"url\":\"https://a\"}]"}},197
{"id": "2", "properties": {"links": [{"url": "https://b"}]}},198
{"id": "3", "properties": {}},199
{"id": "4"},200
{"properties": {"links": "[]"}},201
]}));202
assert_eq!(203
links,204
vec![205
MessageLinks {206
message_id: "1".into(),207
links_json: "[{\"url\":\"https://a\"}]".into()208
},209
MessageLinks {210
message_id: "2".into(),211
links_json: "[{\"url\":\"https://b\"}]".into()212
},213
]214
);215
}216
217
#[test]218
fn only_asyncgw_hosts_receive_the_token() {219
assert!(is_link_image_url(220
"https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x"221
));222
assert!(!is_link_image_url(223
"https://evil.example/?a=.asyncgw.teams.microsoft.com"224
));225
assert!(!is_link_image_url(226
"http://de-prod.asyncgw.teams.microsoft.com/x"227
));228
}229
}@@ -95,8 +95,8 @@ impl MessageTransport for SessionMessageTransport {
95
95
}
96
96
97
97
pub struct Messages<T: MessageTransport = SessionMessageTransport> {
98
transport: T,
99
base_url: String,
98
pub(crate) transport: T,
99
pub(crate) base_url: String,
100
100
retry_delay: Duration,
101
101
}
102
102
@@ -95,8 +95,8 @@ impl MessageTransport for SessionMessageTransport {95
}95
}96
96
97
pub struct Messages<T: MessageTransport = SessionMessageTransport> {97
pub struct Messages<T: MessageTransport = SessionMessageTransport> {98
transport: T,98
pub(crate) transport: T,99
base_url: String,99
pub(crate) base_url: String,100
retry_delay: Duration,100
retry_delay: Duration,101
}101
}102
102
@@ -291,3 +291,78 @@ async fn send_typing_addresses_a_channel_reply_thread() {
291
291
format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")
292
292
);
293
293
}
294
295
#[tokio::test]
296
async fn set_links_puts_the_array_as_a_string() {
297
let mock = Mock::new(&[200]);
298
let links = r#"[{"itemid":"0","url":"https://a.example"}]"#;
299
messages(&mock)
300
.set_links(&ConversationRef::chat("19:a@thread.v2"), "m1", links)
301
.await
302
.unwrap();
303
let requests = mock.requests();
304
assert_eq!(requests[0].method, Method::Put);
305
assert_eq!(
306
requests[0].url,
307
format!("{BASE}/19%3Aa%40thread.v2/messages/m1/properties?name=links")
308
);
309
assert_eq!(requests[0].body.as_ref().unwrap()["links"], links);
310
}
311
312
#[tokio::test]
313
async fn set_links_in_a_channel_reply_targets_the_thread_conversation() {
314
let mock = Mock::new(&[200]);
315
messages(&mock)
316
.set_links(
317
&ConversationRef::channel_reply("19:c@thread.tacv2", "root1"),
318
"r1",
319
"[]",
320
)
321
.await
322
.unwrap();
323
assert_eq!(
324
mock.requests()[0].url,
325
format!(
326
"{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3Droot1/messages/r1/properties?name=links"
327
)
328
);
329
}
330
331
#[tokio::test]
332
async fn link_info_encodes_the_url_for_the_preview_service() {
333
let mock = Mock::new(&[200]);
334
messages(&mock)
335
.link_info("https://a.example/x?y=1&z=2")
336
.await
337
.unwrap();
338
assert_eq!(mock.requests()[0].method, Method::Get);
339
assert_eq!(
340
mock.requests()[0].url,
341
"https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/info?url=https%3A%2F%2Fa.example%2Fx%3Fy%3D1%26z%3D2"
342
);
343
}
344
345
#[tokio::test]
346
async fn link_images_outside_the_preview_service_are_refused_without_a_request() {
347
let mock = Mock::new(&[]);
348
assert!(
349
messages(&mock)
350
.link_image("https://evil.example/a.png")
351
.await
352
.is_err()
353
);
354
assert!(mock.requests().is_empty());
355
}
356
357
#[tokio::test]
358
async fn list_message_links_asks_for_the_msnp24_view() {
359
let mock = Mock::new(&[200]);
360
messages(&mock)
361
.list_message_links(&ConversationRef::channel_root("19:c@thread.tacv2"), 50)
362
.await
363
.unwrap();
364
assert_eq!(
365
mock.requests()[0].url,
366
format!("{BASE}/19%3Ac%40thread.tacv2/messages?view=msnp24Equivalent&pageSize=50")
367
);
368
}
@@ -291,3 +291,78 @@ async fn send_typing_addresses_a_channel_reply_thread() {291
format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")291
format!("{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3D99/messages")292
);292
);293
}293
}294
295
#[tokio::test]296
async fn set_links_puts_the_array_as_a_string() {297
let mock = Mock::new(&[200]);298
let links = r#"[{"itemid":"0","url":"https://a.example"}]"#;299
messages(&mock)300
.set_links(&ConversationRef::chat("19:a@thread.v2"), "m1", links)301
.await302
.unwrap();303
let requests = mock.requests();304
assert_eq!(requests[0].method, Method::Put);305
assert_eq!(306
requests[0].url,307
format!("{BASE}/19%3Aa%40thread.v2/messages/m1/properties?name=links")308
);309
assert_eq!(requests[0].body.as_ref().unwrap()["links"], links);310
}311
312
#[tokio::test]313
async fn set_links_in_a_channel_reply_targets_the_thread_conversation() {314
let mock = Mock::new(&[200]);315
messages(&mock)316
.set_links(317
&ConversationRef::channel_reply("19:c@thread.tacv2", "root1"),318
"r1",319
"[]",320
)321
.await322
.unwrap();323
assert_eq!(324
mock.requests()[0].url,325
format!(326
"{BASE}/19%3Ac%40thread.tacv2%3Bmessageid%3Droot1/messages/r1/properties?name=links"327
)328
);329
}330
331
#[tokio::test]332
async fn link_info_encodes_the_url_for_the_preview_service() {333
let mock = Mock::new(&[200]);334
messages(&mock)335
.link_info("https://a.example/x?y=1&z=2")336
.await337
.unwrap();338
assert_eq!(mock.requests()[0].method, Method::Get);339
assert_eq!(340
mock.requests()[0].url,341
"https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/info?url=https%3A%2F%2Fa.example%2Fx%3Fy%3D1%26z%3D2"342
);343
}344
345
#[tokio::test]346
async fn link_images_outside_the_preview_service_are_refused_without_a_request() {347
let mock = Mock::new(&[]);348
assert!(349
messages(&mock)350
.link_image("https://evil.example/a.png")351
.await352
.is_err()353
);354
assert!(mock.requests().is_empty());355
}356
357
#[tokio::test]358
async fn list_message_links_asks_for_the_msnp24_view() {359
let mock = Mock::new(&[200]);360
messages(&mock)361
.list_message_links(&ConversationRef::channel_root("19:c@thread.tacv2"), 50)362
.await363
.unwrap();364
assert_eq!(365
mock.requests()[0].url,366
format!("{BASE}/19%3Ac%40thread.tacv2/messages?view=msnp24Equivalent&pageSize=50")367
);368
}@@ -7,6 +7,7 @@ use store::MessageRecord;
7
7
8
8
use crate::engine::{Conversation, META_USER_ID, SyncEngine};
9
9
use crate::error::{Error, Result};
10
use crate::links::LinkPreview;
10
11
use crate::mapping::{chat_record, message_record};
11
12
use crate::markdown::markdown_to_html;
12
13
use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};
@@ -328,11 +329,31 @@ impl<R: Remote> SyncEngine<R> {
328
329
let Some(record) = message_record(conversation_id, &message) else {
329
330
return Ok(None);
330
331
};
332
let mut record = record;
331
333
let delta = self.ingest(conversation_id, vec![record.clone()])?;
332
self.announce(conversation_id, !delta.is_empty());
334
let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;
335
self.announce(conversation_id, !delta.is_empty() || links_changed);
333
336
Ok(Some(record))
334
337
}
335
338
339
pub async fn attach_link_preview(
340
&self,
341
conversation_id: &str,
342
message_id: &str,
343
preview: &LinkPreview,
344
) -> Result<()> {
345
let target = self.message_target(conversation_id, message_id)?;
346
let links_json = preview.links_json();
347
self.remote.set_message_links(&target, &links_json).await?;
348
if self
349
.store
350
.set_message_links(conversation_id, message_id, &links_json)?
351
{
352
self.announce(conversation_id, true);
353
}
354
Ok(())
355
}
356
336
357
pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {
337
358
if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {
338
359
return Err(Error::Unsupported("marking a channel as read"));
@@ -7,6 +7,7 @@ use store::MessageRecord;7
7
8
use crate::engine::{Conversation, META_USER_ID, SyncEngine};8
use crate::engine::{Conversation, META_USER_ID, SyncEngine};9
use crate::error::{Error, Result};9
use crate::error::{Error, Result};10
use crate::links::LinkPreview;10
use crate::mapping::{chat_record, message_record};11
use crate::mapping::{chat_record, message_record};11
use crate::markdown::markdown_to_html;12
use crate::markdown::markdown_to_html;12
use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};13
use crate::mentions::{MentionInput, apply_mentions, ensure_allowed_in_chat};@@ -328,11 +329,31 @@ impl<R: Remote> SyncEngine<R> {328
let Some(record) = message_record(conversation_id, &message) else {329
let Some(record) = message_record(conversation_id, &message) else {329
return Ok(None);330
return Ok(None);330
};331
};332
let mut record = record;331
let delta = self.ingest(conversation_id, vec![record.clone()])?;333
let delta = self.ingest(conversation_id, vec![record.clone()])?;332
self.announce(conversation_id, !delta.is_empty());334
let links_changed = self.attach_links(conversation_id, &mut [&mut record]).await;335
self.announce(conversation_id, !delta.is_empty() || links_changed);333
Ok(Some(record))336
Ok(Some(record))334
}337
}335
338
339
pub async fn attach_link_preview(340
&self,341
conversation_id: &str,342
message_id: &str,343
preview: &LinkPreview,344
) -> Result<()> {345
let target = self.message_target(conversation_id, message_id)?;346
let links_json = preview.links_json();347
self.remote.set_message_links(&target, &links_json).await?;348
if self349
.store350
.set_message_links(conversation_id, message_id, &links_json)?351
{352
self.announce(conversation_id, true);353
}354
Ok(())355
}356
336
pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {357
pub async fn mark_read(&self, conversation_id: &str) -> Result<()> {337
if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {358
if !matches!(self.resolve(conversation_id)?, Conversation::Chat) {338
return Err(Error::Unsupported("marking a channel as read"));359
return Err(Error::Unsupported("marking a channel as read"));@@ -11,6 +11,7 @@ use tokio::sync::{OnceCell, broadcast};
11
11
use crate::error::{Error, Result};
12
12
use crate::events::CoreEvent;
13
13
use crate::folders::FolderSource;
14
use crate::links::{LinkPreview, has_stored_links};
14
15
use crate::mapping::{flatten_thread, message_record};
15
16
use crate::people::DirectoryCache;
16
17
use crate::presence::Presence;
@@ -123,6 +124,8 @@ pub struct SyncEngine<R: Remote = Graph> {
123
124
pub(crate) receipts: ReceiptCache,
124
125
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,
125
126
pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
127
pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,
128
pub(crate) links_backfilled: Mutex<HashSet<String>>,
126
129
}
127
130
128
131
impl<R: Remote> SyncEngine<R> {
@@ -151,6 +154,8 @@ impl<R: Remote> SyncEngine<R> {
151
154
receipts: ReceiptCache::default(),
152
155
channel_folders: Mutex::new(HashMap::new()),
153
156
chat_apps: Mutex::new(HashMap::new()),
157
link_previews: Mutex::new(HashMap::new()),
158
links_backfilled: Mutex::new(HashSet::new()),
154
159
}
155
160
}
156
161
@@ -178,13 +183,15 @@ impl<R: Remote> SyncEngine<R> {
178
183
}
179
184
180
185
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {
181
let delta = match self.resolve(conversation_id)? {
186
let mut delta = match self.resolve(conversation_id)? {
182
187
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,
183
188
Conversation::Channel { team_id } => {
184
189
self.fetch_newer_channel(&team_id, conversation_id).await?
185
190
}
186
191
};
187
self.announce(conversation_id, !delta.is_empty());
192
let links_changed = self.attach_delta_links(conversation_id, &mut delta).await
193
| self.backfill_links(conversation_id).await;
194
self.announce(conversation_id, !delta.is_empty() || links_changed);
188
195
Ok(delta)
189
196
}
190
197
@@ -379,13 +386,20 @@ impl<R: Remote> SyncEngine<R> {
379
386
pub(crate) fn ingest(
380
387
&self,
381
388
conversation_id: &str,
382
records: Vec<MessageRecord>,
389
mut records: Vec<MessageRecord>,
383
390
) -> Result<Delta> {
384
391
let ids: Vec<String> = records
385
392
.iter()
386
393
.map(|record| record.message_id.clone())
387
394
.collect();
388
395
let existing = self.store.messages_by_id(conversation_id, &ids)?;
396
for record in &mut records {
397
if let Some(cached) = existing.get(&record.message_id)
398
&& !has_stored_links(&record.links_json)
399
{
400
record.links_json.clone_from(&cached.links_json);
401
}
402
}
389
403
self.store.upsert_messages(&records)?;
390
404
self.update_chat_preview(&records)?;
391
405
let mut delta = Delta::default();
@@ -11,6 +11,7 @@ use tokio::sync::{OnceCell, broadcast};11
use crate::error::{Error, Result};11
use crate::error::{Error, Result};12
use crate::events::CoreEvent;12
use crate::events::CoreEvent;13
use crate::folders::FolderSource;13
use crate::folders::FolderSource;14
use crate::links::{LinkPreview, has_stored_links};14
use crate::mapping::{flatten_thread, message_record};15
use crate::mapping::{flatten_thread, message_record};15
use crate::people::DirectoryCache;16
use crate::people::DirectoryCache;16
use crate::presence::Presence;17
use crate::presence::Presence;@@ -123,6 +124,8 @@ pub struct SyncEngine<R: Remote = Graph> {123
pub(crate) receipts: ReceiptCache,124
pub(crate) receipts: ReceiptCache,124
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,125
pub(crate) channel_folders: Mutex<HashMap<String, DriveFolder>>,125
pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,126
pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,127
pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,128
pub(crate) links_backfilled: Mutex<HashSet<String>>,126
}129
}127
130
128
impl<R: Remote> SyncEngine<R> {131
impl<R: Remote> SyncEngine<R> {@@ -151,6 +154,8 @@ impl<R: Remote> SyncEngine<R> {151
receipts: ReceiptCache::default(),154
receipts: ReceiptCache::default(),152
channel_folders: Mutex::new(HashMap::new()),155
channel_folders: Mutex::new(HashMap::new()),153
chat_apps: Mutex::new(HashMap::new()),156
chat_apps: Mutex::new(HashMap::new()),157
link_previews: Mutex::new(HashMap::new()),158
links_backfilled: Mutex::new(HashSet::new()),154
}159
}155
}160
}156
161
@@ -178,13 +183,15 @@ impl<R: Remote> SyncEngine<R> {178
}183
}179
184
180
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {185
pub async fn fetch_newer(&self, conversation_id: &str) -> Result<Delta> {181
let delta = match self.resolve(conversation_id)? {186
let mut delta = match self.resolve(conversation_id)? {182
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,187
Conversation::Chat => self.fetch_newer_chat(conversation_id).await?,183
Conversation::Channel { team_id } => {188
Conversation::Channel { team_id } => {184
self.fetch_newer_channel(&team_id, conversation_id).await?189
self.fetch_newer_channel(&team_id, conversation_id).await?185
}190
}186
};191
};187
self.announce(conversation_id, !delta.is_empty());192
let links_changed = self.attach_delta_links(conversation_id, &mut delta).await193
| self.backfill_links(conversation_id).await;194
self.announce(conversation_id, !delta.is_empty() || links_changed);188
Ok(delta)195
Ok(delta)189
}196
}190
197
@@ -379,13 +386,20 @@ impl<R: Remote> SyncEngine<R> {379
pub(crate) fn ingest(386
pub(crate) fn ingest(380
&self,387
&self,381
conversation_id: &str,388
conversation_id: &str,382
records: Vec<MessageRecord>,389
mut records: Vec<MessageRecord>,383
) -> Result<Delta> {390
) -> Result<Delta> {384
let ids: Vec<String> = records391
let ids: Vec<String> = records385
.iter()392
.iter()386
.map(|record| record.message_id.clone())393
.map(|record| record.message_id.clone())387
.collect();394
.collect();388
let existing = self.store.messages_by_id(conversation_id, &ids)?;395
let existing = self.store.messages_by_id(conversation_id, &ids)?;396
for record in &mut records {397
if let Some(cached) = existing.get(&record.message_id)398
&& !has_stored_links(&record.links_json)399
{400
record.links_json.clone_from(&cached.links_json);401
}402
}389
self.store.upsert_messages(&records)?;403
self.store.upsert_messages(&records)?;390
self.update_chat_preview(&records)?;404
self.update_chat_preview(&records)?;391
let mut delta = Delta::default();405
let mut delta = Delta::default();@@ -12,6 +12,8 @@ mod events;
12
12
mod folders;
13
13
mod image_size;
14
14
mod images;
15
mod link_sync;
16
mod links;
15
17
mod mapping;
16
18
mod markdown;
17
19
mod mentions;
@@ -52,6 +54,7 @@ pub use graph::{
52
54
UploadedFile,
53
55
};
54
56
pub use images::StoredImage;
57
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};
55
58
pub use mapping::{chat_record, message_record};
56
59
pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};
57
60
pub use mentions::MentionInput;
@@ -12,6 +12,8 @@ mod events;12
mod folders;12
mod folders;13
mod image_size;13
mod image_size;14
mod images;14
mod images;15
mod link_sync;16
mod links;15
mod mapping;17
mod mapping;16
mod markdown;18
mod markdown;17
mod mentions;19
mod mentions;@@ -52,6 +54,7 @@ pub use graph::{52
UploadedFile,54
UploadedFile,53
};55
};54
pub use images::StoredImage;56
pub use images::StoredImage;57
pub use links::{LinkPreview, first_public_link, is_public_link, link_preview};55
pub use mapping::{chat_record, message_record};58
pub use mapping::{chat_record, message_record};56
pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};59
pub use markdown::{escape_html, markdown_to_html, plain_text_to_html};57
pub use mentions::MentionInput;60
pub use mentions::MentionInput;@@ -0,0 +1,201 @@
1
use std::collections::HashSet;
2
3
use chatsvc::{ConversationRef, MessageLinks};
4
use store::MessageRecord;
5
6
use crate::engine::{Conversation, Delta, SyncEngine};
7
use crate::error::Result;
8
use crate::links::{LinkPreview, has_links_markup, has_stored_links, is_public_link};
9
use crate::remote::Remote;
10
11
const LINKS_PAGE_SIZE: usize = 50;
12
const MAX_REPLY_THREADS: usize = 5;
13
14
impl<R: Remote> SyncEngine<R> {
15
/// `None` when the page has no title and no image, or the link is not public.
16
pub async fn link_preview_for(&self, url: &str) -> Result<Option<LinkPreview>> {
17
if !is_public_link(url) {
18
return Ok(None);
19
}
20
let cached = self
21
.link_previews
22
.lock()
23
.unwrap_or_else(|poisoned| poisoned.into_inner())
24
.get(url)
25
.cloned();
26
if let Some(preview) = cached {
27
return Ok(preview);
28
}
29
let info = self.remote.link_info(url).await?;
30
let preview = LinkPreview::from_info(url, &info);
31
self.link_previews
32
.lock()
33
.unwrap_or_else(|poisoned| poisoned.into_inner())
34
.insert(url.to_owned(), preview.clone());
35
Ok(preview)
36
}
37
38
/// Network failures leave the records as they are.
39
pub(crate) async fn attach_delta_links(
40
&self,
41
conversation_id: &str,
42
delta: &mut Delta,
43
) -> bool {
44
let mut records: Vec<&mut MessageRecord> = delta
45
.added
46
.iter_mut()
47
.chain(delta.updated.iter_mut())
48
.collect();
49
self.attach_links(conversation_id, &mut records).await
50
}
51
52
/// Once per conversation and session, for cached messages stored before their links were known.
53
pub(crate) async fn backfill_links(&self, conversation_id: &str) -> bool {
54
let first = self
55
.links_backfilled
56
.lock()
57
.unwrap_or_else(|poisoned| poisoned.into_inner())
58
.insert(conversation_id.to_owned());
59
if !first {
60
return false;
61
}
62
let Ok(mut cached) = self.store.messages(conversation_id, None, LINKS_PAGE_SIZE) else {
63
return false;
64
};
65
let mut records: Vec<&mut MessageRecord> = cached
66
.iter_mut()
67
.filter(|record| !has_stored_links(&record.links_json))
68
.collect();
69
self.attach_links(conversation_id, &mut records).await
70
}
71
72
pub(crate) async fn attach_links(
73
&self,
74
conversation_id: &str,
75
records: &mut [&mut MessageRecord],
76
) -> bool {
77
let Ok(conversation) = self.resolve(conversation_id) else {
78
return false;
79
};
80
let targets = link_conversations(conversation_id, &conversation, records);
81
let mut changed = false;
82
for target in targets {
83
let Ok(found) = self.remote.message_links(&target, LINKS_PAGE_SIZE).await else {
84
continue;
85
};
86
for MessageLinks {
87
message_id,
88
links_json,
89
} in found
90
{
91
if !has_stored_links(&links_json) {
92
continue;
93
}
94
let Some(record) = records.iter_mut().find(|record| {
95
record.message_id == message_id
96
&& has_links_markup(record)
97
&& record.links_json != links_json
98
}) else {
99
continue;
100
};
101
record.links_json = links_json;
102
changed |= self
103
.store
104
.set_message_links(conversation_id, &message_id, &record.links_json)
105
.unwrap_or(false);
106
}
107
}
108
changed
109
}
110
}
111
112
fn link_conversations(
113
conversation_id: &str,
114
conversation: &Conversation,
115
records: &[&mut MessageRecord],
116
) -> Vec<ConversationRef> {
117
let candidates: Vec<&MessageRecord> = records
118
.iter()
119
.map(|record| &**record)
120
.filter(|record| has_links_markup(record))
121
.collect();
122
if candidates.is_empty() {
123
return Vec::new();
124
}
125
match conversation {
126
Conversation::Chat => vec![ConversationRef::chat(conversation_id)],
127
Conversation::Channel { .. } => {
128
let mut targets = Vec::new();
129
if candidates.iter().any(|record| record.reply_to_id.is_none()) {
130
targets.push(ConversationRef::channel_root(conversation_id));
131
}
132
let mut seen = HashSet::new();
133
let roots = candidates
134
.iter()
135
.filter_map(|record| record.reply_to_id.as_deref())
136
.filter(|root_id| seen.insert(*root_id))
137
.take(MAX_REPLY_THREADS);
138
targets.extend(
139
roots.map(|root_id| ConversationRef::channel_reply(conversation_id, root_id)),
140
);
141
targets
142
}
143
}
144
}
145
146
#[cfg(test)]
147
mod tests {
148
use super::*;
149
150
fn record(message_id: &str, reply_to_id: Option<&str>, body_html: &str) -> MessageRecord {
151
MessageRecord {
152
message_id: message_id.to_owned(),
153
reply_to_id: reply_to_id.map(str::to_owned),
154
body_html: body_html.to_owned(),
155
..MessageRecord::default()
156
}
157
}
158
159
fn targets(
160
conversation: &Conversation,
161
mut records: Vec<MessageRecord>,
162
) -> Vec<ConversationRef> {
163
let refs: Vec<&mut MessageRecord> = records.iter_mut().collect();
164
link_conversations("19:c", conversation, &refs)
165
}
166
167
#[test]
168
fn messages_without_anchors_need_no_request() {
169
assert!(targets(&Conversation::Chat, vec![record("1", None, "<p>hi</p>")]).is_empty());
170
}
171
172
#[test]
173
fn a_chat_is_read_once() {
174
let found = targets(
175
&Conversation::Chat,
176
vec![
177
record("1", None, "<a href=\"https://a.example\">a</a>"),
178
record("2", None, "<a href=\"https://b.example\">b</a>"),
179
],
180
);
181
assert_eq!(found, vec![ConversationRef::chat("19:c")]);
182
}
183
184
#[test]
185
fn channel_replies_are_read_per_thread_with_a_cap() {
186
let anchor = "<a href=\"https://a.example\">a</a>";
187
let mut records = vec![record("1", None, anchor)];
188
records.extend(
189
(0..8).map(|index| record(&format!("r{index}"), Some(&format!("root{index}")), anchor)),
190
);
191
let found = targets(
192
&Conversation::Channel {
193
team_id: "t".into(),
194
},
195
records,
196
);
197
assert_eq!(found.len(), 1 + MAX_REPLY_THREADS);
198
assert_eq!(found[0], ConversationRef::channel_root("19:c"));
199
assert_eq!(found[1], ConversationRef::channel_reply("19:c", "root0"));
200
}
201
}
@@ -0,0 +1,201 @@1
use std::collections::HashSet;2
3
use chatsvc::{ConversationRef, MessageLinks};4
use store::MessageRecord;5
6
use crate::engine::{Conversation, Delta, SyncEngine};7
use crate::error::Result;8
use crate::links::{LinkPreview, has_links_markup, has_stored_links, is_public_link};9
use crate::remote::Remote;10
11
const LINKS_PAGE_SIZE: usize = 50;12
const MAX_REPLY_THREADS: usize = 5;13
14
impl<R: Remote> SyncEngine<R> {15
/// `None` when the page has no title and no image, or the link is not public.16
pub async fn link_preview_for(&self, url: &str) -> Result<Option<LinkPreview>> {17
if !is_public_link(url) {18
return Ok(None);19
}20
let cached = self21
.link_previews22
.lock()23
.unwrap_or_else(|poisoned| poisoned.into_inner())24
.get(url)25
.cloned();26
if let Some(preview) = cached {27
return Ok(preview);28
}29
let info = self.remote.link_info(url).await?;30
let preview = LinkPreview::from_info(url, &info);31
self.link_previews32
.lock()33
.unwrap_or_else(|poisoned| poisoned.into_inner())34
.insert(url.to_owned(), preview.clone());35
Ok(preview)36
}37
38
/// Network failures leave the records as they are.39
pub(crate) async fn attach_delta_links(40
&self,41
conversation_id: &str,42
delta: &mut Delta,43
) -> bool {44
let mut records: Vec<&mut MessageRecord> = delta45
.added46
.iter_mut()47
.chain(delta.updated.iter_mut())48
.collect();49
self.attach_links(conversation_id, &mut records).await50
}51
52
/// Once per conversation and session, for cached messages stored before their links were known.53
pub(crate) async fn backfill_links(&self, conversation_id: &str) -> bool {54
let first = self55
.links_backfilled56
.lock()57
.unwrap_or_else(|poisoned| poisoned.into_inner())58
.insert(conversation_id.to_owned());59
if !first {60
return false;61
}62
let Ok(mut cached) = self.store.messages(conversation_id, None, LINKS_PAGE_SIZE) else {63
return false;64
};65
let mut records: Vec<&mut MessageRecord> = cached66
.iter_mut()67
.filter(|record| !has_stored_links(&record.links_json))68
.collect();69
self.attach_links(conversation_id, &mut records).await70
}71
72
pub(crate) async fn attach_links(73
&self,74
conversation_id: &str,75
records: &mut [&mut MessageRecord],76
) -> bool {77
let Ok(conversation) = self.resolve(conversation_id) else {78
return false;79
};80
let targets = link_conversations(conversation_id, &conversation, records);81
let mut changed = false;82
for target in targets {83
let Ok(found) = self.remote.message_links(&target, LINKS_PAGE_SIZE).await else {84
continue;85
};86
for MessageLinks {87
message_id,88
links_json,89
} in found90
{91
if !has_stored_links(&links_json) {92
continue;93
}94
let Some(record) = records.iter_mut().find(|record| {95
record.message_id == message_id96
&& has_links_markup(record)97
&& record.links_json != links_json98
}) else {99
continue;100
};101
record.links_json = links_json;102
changed |= self103
.store104
.set_message_links(conversation_id, &message_id, &record.links_json)105
.unwrap_or(false);106
}107
}108
changed109
}110
}111
112
fn link_conversations(113
conversation_id: &str,114
conversation: &Conversation,115
records: &[&mut MessageRecord],116
) -> Vec<ConversationRef> {117
let candidates: Vec<&MessageRecord> = records118
.iter()119
.map(|record| &**record)120
.filter(|record| has_links_markup(record))121
.collect();122
if candidates.is_empty() {123
return Vec::new();124
}125
match conversation {126
Conversation::Chat => vec![ConversationRef::chat(conversation_id)],127
Conversation::Channel { .. } => {128
let mut targets = Vec::new();129
if candidates.iter().any(|record| record.reply_to_id.is_none()) {130
targets.push(ConversationRef::channel_root(conversation_id));131
}132
let mut seen = HashSet::new();133
let roots = candidates134
.iter()135
.filter_map(|record| record.reply_to_id.as_deref())136
.filter(|root_id| seen.insert(*root_id))137
.take(MAX_REPLY_THREADS);138
targets.extend(139
roots.map(|root_id| ConversationRef::channel_reply(conversation_id, root_id)),140
);141
targets142
}143
}144
}145
146
#[cfg(test)]147
mod tests {148
use super::*;149
150
fn record(message_id: &str, reply_to_id: Option<&str>, body_html: &str) -> MessageRecord {151
MessageRecord {152
message_id: message_id.to_owned(),153
reply_to_id: reply_to_id.map(str::to_owned),154
body_html: body_html.to_owned(),155
..MessageRecord::default()156
}157
}158
159
fn targets(160
conversation: &Conversation,161
mut records: Vec<MessageRecord>,162
) -> Vec<ConversationRef> {163
let refs: Vec<&mut MessageRecord> = records.iter_mut().collect();164
link_conversations("19:c", conversation, &refs)165
}166
167
#[test]168
fn messages_without_anchors_need_no_request() {169
assert!(targets(&Conversation::Chat, vec![record("1", None, "<p>hi</p>")]).is_empty());170
}171
172
#[test]173
fn a_chat_is_read_once() {174
let found = targets(175
&Conversation::Chat,176
vec![177
record("1", None, "<a href=\"https://a.example\">a</a>"),178
record("2", None, "<a href=\"https://b.example\">b</a>"),179
],180
);181
assert_eq!(found, vec![ConversationRef::chat("19:c")]);182
}183
184
#[test]185
fn channel_replies_are_read_per_thread_with_a_cap() {186
let anchor = "<a href=\"https://a.example\">a</a>";187
let mut records = vec![record("1", None, anchor)];188
records.extend(189
(0..8).map(|index| record(&format!("r{index}"), Some(&format!("root{index}")), anchor)),190
);191
let found = targets(192
&Conversation::Channel {193
team_id: "t".into(),194
},195
records,196
);197
assert_eq!(found.len(), 1 + MAX_REPLY_THREADS);198
assert_eq!(found[0], ConversationRef::channel_root("19:c"));199
assert_eq!(found[1], ConversationRef::channel_reply("19:c", "root0"));200
}201
}@@ -0,0 +1,368 @@
1
use std::net::Ipv4Addr;
2
3
use chatsvc::{LinkInfo, is_link_image_url};
4
use scraper::{Html, Selector};
5
use serde_json::{Value, json};
6
use store::MessageRecord;
7
8
use crate::stored::ImageRef;
9
10
pub const EMPTY_LINKS: &str = "[]";
11
12
const HYPERLINK_TYPE: &str = "http://schema.skype.com/HyperLink";
13
const INTERNAL_HOSTS: [&str; 8] = [
14
"sharepoint.com",
15
"onedrive.com",
16
"1drv.ms",
17
"teams.microsoft.com",
18
"teams.cloud.microsoft",
19
"teams.live.com",
20
"office.com",
21
"microsoft365.com",
22
];
23
24
#[derive(Debug, Clone, PartialEq, Eq)]
25
pub struct LinkPreview {
26
pub url: String,
27
pub title: Option<String>,
28
pub description: Option<String>,
29
pub image_url: Option<String>,
30
pub image_width: Option<u32>,
31
pub image_height: Option<u32>,
32
}
33
34
impl LinkPreview {
35
pub fn from_info(url: &str, info: &LinkInfo) -> Option<LinkPreview> {
36
let preview = LinkPreview {
37
url: url.to_owned(),
38
title: info.title.clone(),
39
description: info.description.clone(),
40
image_url: info
41
.thumbnail
42
.clone()
43
.filter(|thumbnail| is_link_image_url(thumbnail)),
44
image_width: info.thumbnail_width,
45
image_height: info.thumbnail_height,
46
};
47
preview.is_showable().then_some(preview)
48
}
49
50
pub fn domain(&self) -> String {
51
let host = link_host(&self.url).unwrap_or_default();
52
host.strip_prefix("www.").unwrap_or(&host).to_owned()
53
}
54
55
pub fn image(&self) -> Option<ImageRef> {
56
Some(ImageRef {
57
id: String::new(),
58
url: self.image_url.clone()?,
59
width: self.image_width,
60
height: self.image_height,
61
})
62
}
63
64
pub fn links_json(&self) -> String {
65
let mut preview = serde_json::Map::new();
66
if let Some(image_url) = &self.image_url {
67
preview.insert("previewurl".into(), json!(image_url));
68
}
69
if let Some((width, height)) = self.image_width.zip(self.image_height) {
70
preview.insert(
71
"previewmeta".into(),
72
json!({"height": height, "width": width}),
73
);
74
}
75
if let Some(title) = &self.title {
76
preview.insert("title".into(), json!(title));
77
}
78
if let Some(description) = &self.description {
79
preview.insert("description".into(), json!(description));
80
}
81
json!([{
82
"@type": HYPERLINK_TYPE,
83
"itemid": "0",
84
"url": self.url,
85
"preview": preview,
86
"previewenabled": true,
87
}])
88
.to_string()
89
}
90
91
fn is_showable(&self) -> bool {
92
self.title.is_some() || self.image_url.is_some()
93
}
94
}
95
96
pub fn has_links_markup(record: &MessageRecord) -> bool {
97
!record.deleted && record.body_html.contains("<a ")
98
}
99
100
pub fn has_stored_links(links_json: &str) -> bool {
101
!matches!(links_json, "" | EMPTY_LINKS)
102
}
103
104
pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {
105
if record.deleted {
106
return None;
107
}
108
select_preview(&record.links_json)
109
}
110
111
pub fn select_preview(links_json: &str) -> Option<LinkPreview> {
112
let entries: Vec<Value> = serde_json::from_str(links_json).ok()?;
113
entries.iter().find_map(entry_preview)
114
}
115
116
fn entry_preview(entry: &Value) -> Option<LinkPreview> {
117
if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) {
118
return None;
119
}
120
let url = entry.get("url")?.as_str()?;
121
if !is_public_link(url) {
122
return None;
123
}
124
let preview = entry.get("preview").filter(|preview| preview.is_object())?;
125
let text = |key: &str| {
126
preview
127
.get(key)
128
.and_then(Value::as_str)
129
.map(str::trim)
130
.filter(|value| !value.is_empty())
131
.map(str::to_owned)
132
};
133
let meta = ["previewmeta", "previewMetadata"]
134
.into_iter()
135
.find_map(|key| preview.get(key).filter(|meta| meta.is_object()));
136
let size = |key: &str| {
137
meta.and_then(|meta| meta.get(key))
138
.and_then(Value::as_u64)
139
.and_then(|value| u32::try_from(value).ok())
140
.filter(|value| *value > 0)
141
};
142
let candidate = LinkPreview {
143
url: url.to_owned(),
144
title: text("title"),
145
description: text("description"),
146
image_url: text("previewurl").filter(|image_url| is_link_image_url(image_url)),
147
image_width: size("width"),
148
image_height: size("height"),
149
};
150
candidate.is_showable().then_some(candidate)
151
}
152
153
pub fn first_public_link(html: &str) -> Option<String> {
154
let selector = Selector::parse("a[href]").ok()?;
155
Html::parse_fragment(html)
156
.select(&selector)
157
.filter_map(|anchor| anchor.value().attr("href"))
158
.find(|href| is_public_link(href))
159
.map(str::to_owned)
160
}
161
162
pub fn is_public_link(url: &str) -> bool {
163
let lower = url.to_ascii_lowercase();
164
if !(lower.starts_with("http://") || lower.starts_with("https://")) {
165
return false;
166
}
167
let Some(host) = link_host(url) else {
168
return false;
169
};
170
if host.starts_with('[') || host == "localhost" || !host.contains('.') {
171
return false;
172
}
173
if INTERNAL_HOSTS
174
.iter()
175
.any(|internal| host == *internal || host.ends_with(&format!(".{internal}")))
176
{
177
return false;
178
}
179
host.parse::<Ipv4Addr>().map_or(true, |address| {
180
!(address.is_private()
181
|| address.is_loopback()
182
|| address.is_link_local()
183
|| address.is_unspecified())
184
})
185
}
186
187
fn link_host(url: &str) -> Option<String> {
188
let (_, rest) = url.split_once("://")?;
189
let authority = rest.split(['/', '?', '#']).next()?;
190
let host_port = authority
191
.rsplit_once('@')
192
.map_or(authority, |(_, host)| host);
193
let host = if host_port.starts_with('[') {
194
host_port
195
} else {
196
host_port.split(':').next()?
197
};
198
let host = host.trim_end_matches('.').to_ascii_lowercase();
199
(!host.is_empty()).then_some(host)
200
}
201
202
#[cfg(test)]
203
mod tests {
204
use super::*;
205
206
const THUMBNAIL: &str =
207
"https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x";
208
209
fn links(entries: Value) -> String {
210
entries.to_string()
211
}
212
213
#[test]
214
fn picks_the_first_public_link_with_a_title() {
215
let preview = select_preview(&links(json!([
216
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true},
217
{"url": "https://a.example/x", "preview": {}, "previewenabled": true},
218
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}},
219
{"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true},
220
])))
221
.unwrap();
222
assert_eq!(preview.url, "https://b.example/y");
223
assert_eq!(preview.title.as_deref(), Some("B"));
224
assert_eq!(preview.description.as_deref(), Some("About B"));
225
assert_eq!(preview.domain(), "b.example");
226
}
227
228
#[test]
229
fn an_image_alone_is_enough() {
230
let preview = select_preview(&links(json!([
231
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null},
232
])))
233
.unwrap();
234
assert_eq!(preview.title, None);
235
assert_eq!(preview.image_url.as_deref(), Some(THUMBNAIL));
236
assert_eq!(
237
(preview.image_width, preview.image_height),
238
(Some(320), Some(160))
239
);
240
}
241
242
#[test]
243
fn reads_the_camel_case_meta_and_null_meta() {
244
let preview = select_preview(&links(json!([
245
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}},
246
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
247
])))
248
.unwrap();
249
assert_eq!(
250
(preview.image_width, preview.image_height),
251
(Some(20), Some(10))
252
);
253
let second = select_preview(&links(json!([
254
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},
255
])))
256
.unwrap();
257
assert_eq!(second.image_width, None);
258
}
259
260
#[test]
261
fn a_removed_preview_is_not_shown() {
262
assert_eq!(
263
select_preview(&links(json!([
264
{"url": "https://a.example", "preview": {"title": "A"}, "previewenabled": false},
265
]))),
266
None
267
);
268
}
269
270
#[test]
271
fn images_outside_the_preview_service_are_dropped() {
272
assert_eq!(
273
select_preview(&links(json!([
274
{"url": "https://a.example", "preview": {"previewurl": "https://evil.example/i.png"}},
275
]))),
276
None
277
);
278
}
279
280
#[test]
281
fn garbage_and_empty_lists_have_no_preview() {
282
assert_eq!(select_preview("[]"), None);
283
assert_eq!(select_preview(""), None);
284
assert_eq!(select_preview("{}"), None);
285
assert_eq!(select_preview("[{\"url\": 3}]"), None);
286
}
287
288
#[test]
289
fn internal_and_private_hosts_are_skipped() {
290
for url in [
291
"https://contoso.sharepoint.com/a",
292
"https://contoso-my.sharepoint.com/a",
293
"https://onedrive.com/a",
294
"https://1drv.ms/a",
295
"https://teams.microsoft.com/l/x",
296
"https://teams.cloud.microsoft/x",
297
"https://teams.live.com/x",
298
"https://www.office.com/x",
299
"https://m365.microsoft365.com/x",
300
"https://localhost/x",
301
"https://intranet/x",
302
"http://192.168.1.2/x",
303
"http://127.0.0.1:8080/x",
304
"ftp://a.example/x",
305
"mailto:a@b.example",
306
] {
307
assert!(!is_public_link(url), "{url}");
308
}
309
for url in [
310
"https://github.com/rust-lang/rust",
311
"http://a.example:8080/x",
312
"https://notsharepoint.com/x",
313
"https://user@example.org/x",
314
] {
315
assert!(is_public_link(url), "{url}");
316
}
317
}
318
319
#[test]
320
fn finds_the_first_public_anchor_in_html() {
321
let html = "<p><a href=\"https://contoso.sharepoint.com/x\">f</a> \
322
<a href=\"https://a.example/?q=1&r=2\">a</a> <a href=\"https://b.example\">b</a></p>";
323
assert_eq!(
324
first_public_link(html).as_deref(),
325
Some("https://a.example/?q=1&r=2")
326
);
327
assert_eq!(first_public_link("<p>no link</p>"), None);
328
}
329
330
#[test]
331
fn outgoing_json_reads_back_as_the_same_preview() {
332
let preview = LinkPreview {
333
url: "https://github.com/rust-lang/rust".into(),
334
title: Some("Rust".into()),
335
description: Some("Empowering".into()),
336
image_url: Some(THUMBNAIL.into()),
337
image_width: Some(320),
338
image_height: Some(160),
339
};
340
let json: Value = serde_json::from_str(&preview.links_json()).unwrap();
341
assert_eq!(json[0]["@type"], HYPERLINK_TYPE);
342
assert_eq!(json[0]["itemid"], "0");
343
assert_eq!(json[0]["previewenabled"], true);
344
assert_eq!(json[0]["preview"]["previewurl"], THUMBNAIL);
345
assert_eq!(select_preview(&preview.links_json()), Some(preview));
346
}
347
348
#[test]
349
fn info_without_title_or_usable_image_makes_no_preview() {
350
let info = LinkInfo {
351
url: "https://a.example".into(),
352
description: Some("only text".into()),
353
thumbnail: Some("https://evil.example/i.png".into()),
354
..LinkInfo::default()
355
};
356
assert_eq!(LinkPreview::from_info("https://a.example", &info), None);
357
}
358
359
#[test]
360
fn deleted_messages_show_no_preview() {
361
let record = MessageRecord {
362
deleted: true,
363
links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])),
364
..MessageRecord::default()
365
};
366
assert_eq!(link_preview(&record), None);
367
}
368
}
@@ -0,0 +1,368 @@1
use std::net::Ipv4Addr;2
3
use chatsvc::{LinkInfo, is_link_image_url};4
use scraper::{Html, Selector};5
use serde_json::{Value, json};6
use store::MessageRecord;7
8
use crate::stored::ImageRef;9
10
pub const EMPTY_LINKS: &str = "[]";11
12
const HYPERLINK_TYPE: &str = "http://schema.skype.com/HyperLink";13
const INTERNAL_HOSTS: [&str; 8] = [14
"sharepoint.com",15
"onedrive.com",16
"1drv.ms",17
"teams.microsoft.com",18
"teams.cloud.microsoft",19
"teams.live.com",20
"office.com",21
"microsoft365.com",22
];23
24
#[derive(Debug, Clone, PartialEq, Eq)]25
pub struct LinkPreview {26
pub url: String,27
pub title: Option<String>,28
pub description: Option<String>,29
pub image_url: Option<String>,30
pub image_width: Option<u32>,31
pub image_height: Option<u32>,32
}33
34
impl LinkPreview {35
pub fn from_info(url: &str, info: &LinkInfo) -> Option<LinkPreview> {36
let preview = LinkPreview {37
url: url.to_owned(),38
title: info.title.clone(),39
description: info.description.clone(),40
image_url: info41
.thumbnail42
.clone()43
.filter(|thumbnail| is_link_image_url(thumbnail)),44
image_width: info.thumbnail_width,45
image_height: info.thumbnail_height,46
};47
preview.is_showable().then_some(preview)48
}49
50
pub fn domain(&self) -> String {51
let host = link_host(&self.url).unwrap_or_default();52
host.strip_prefix("www.").unwrap_or(&host).to_owned()53
}54
55
pub fn image(&self) -> Option<ImageRef> {56
Some(ImageRef {57
id: String::new(),58
url: self.image_url.clone()?,59
width: self.image_width,60
height: self.image_height,61
})62
}63
64
pub fn links_json(&self) -> String {65
let mut preview = serde_json::Map::new();66
if let Some(image_url) = &self.image_url {67
preview.insert("previewurl".into(), json!(image_url));68
}69
if let Some((width, height)) = self.image_width.zip(self.image_height) {70
preview.insert(71
"previewmeta".into(),72
json!({"height": height, "width": width}),73
);74
}75
if let Some(title) = &self.title {76
preview.insert("title".into(), json!(title));77
}78
if let Some(description) = &self.description {79
preview.insert("description".into(), json!(description));80
}81
json!([{82
"@type": HYPERLINK_TYPE,83
"itemid": "0",84
"url": self.url,85
"preview": preview,86
"previewenabled": true,87
}])88
.to_string()89
}90
91
fn is_showable(&self) -> bool {92
self.title.is_some() || self.image_url.is_some()93
}94
}95
96
pub fn has_links_markup(record: &MessageRecord) -> bool {97
!record.deleted && record.body_html.contains("<a ")98
}99
100
pub fn has_stored_links(links_json: &str) -> bool {101
!matches!(links_json, "" | EMPTY_LINKS)102
}103
104
pub fn link_preview(record: &MessageRecord) -> Option<LinkPreview> {105
if record.deleted {106
return None;107
}108
select_preview(&record.links_json)109
}110
111
pub fn select_preview(links_json: &str) -> Option<LinkPreview> {112
let entries: Vec<Value> = serde_json::from_str(links_json).ok()?;113
entries.iter().find_map(entry_preview)114
}115
116
fn entry_preview(entry: &Value) -> Option<LinkPreview> {117
if entry.get("previewenabled").and_then(Value::as_bool) == Some(false) {118
return None;119
}120
let url = entry.get("url")?.as_str()?;121
if !is_public_link(url) {122
return None;123
}124
let preview = entry.get("preview").filter(|preview| preview.is_object())?;125
let text = |key: &str| {126
preview127
.get(key)128
.and_then(Value::as_str)129
.map(str::trim)130
.filter(|value| !value.is_empty())131
.map(str::to_owned)132
};133
let meta = ["previewmeta", "previewMetadata"]134
.into_iter()135
.find_map(|key| preview.get(key).filter(|meta| meta.is_object()));136
let size = |key: &str| {137
meta.and_then(|meta| meta.get(key))138
.and_then(Value::as_u64)139
.and_then(|value| u32::try_from(value).ok())140
.filter(|value| *value > 0)141
};142
let candidate = LinkPreview {143
url: url.to_owned(),144
title: text("title"),145
description: text("description"),146
image_url: text("previewurl").filter(|image_url| is_link_image_url(image_url)),147
image_width: size("width"),148
image_height: size("height"),149
};150
candidate.is_showable().then_some(candidate)151
}152
153
pub fn first_public_link(html: &str) -> Option<String> {154
let selector = Selector::parse("a[href]").ok()?;155
Html::parse_fragment(html)156
.select(&selector)157
.filter_map(|anchor| anchor.value().attr("href"))158
.find(|href| is_public_link(href))159
.map(str::to_owned)160
}161
162
pub fn is_public_link(url: &str) -> bool {163
let lower = url.to_ascii_lowercase();164
if !(lower.starts_with("http://") || lower.starts_with("https://")) {165
return false;166
}167
let Some(host) = link_host(url) else {168
return false;169
};170
if host.starts_with('[') || host == "localhost" || !host.contains('.') {171
return false;172
}173
if INTERNAL_HOSTS174
.iter()175
.any(|internal| host == *internal || host.ends_with(&format!(".{internal}")))176
{177
return false;178
}179
host.parse::<Ipv4Addr>().map_or(true, |address| {180
!(address.is_private()181
|| address.is_loopback()182
|| address.is_link_local()183
|| address.is_unspecified())184
})185
}186
187
fn link_host(url: &str) -> Option<String> {188
let (_, rest) = url.split_once("://")?;189
let authority = rest.split(['/', '?', '#']).next()?;190
let host_port = authority191
.rsplit_once('@')192
.map_or(authority, |(_, host)| host);193
let host = if host_port.starts_with('[') {194
host_port195
} else {196
host_port.split(':').next()?197
};198
let host = host.trim_end_matches('.').to_ascii_lowercase();199
(!host.is_empty()).then_some(host)200
}201
202
#[cfg(test)]203
mod tests {204
use super::*;205
206
const THUMBNAIL: &str =207
"https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=x";208
209
fn links(entries: Value) -> String {210
entries.to_string()211
}212
213
#[test]214
fn picks_the_first_public_link_with_a_title() {215
let preview = select_preview(&links(json!([216
{"url": "https://contoso.sharepoint.com/f", "preview": {"title": "File"}, "previewenabled": true},217
{"url": "https://a.example/x", "preview": {}, "previewenabled": true},218
{"url": "https://b.example/y", "preview": {"title": " B ", "description": "About B"}},219
{"url": "https://c.example/z", "preview": {"title": "C"}, "previewenabled": true},220
])))221
.unwrap();222
assert_eq!(preview.url, "https://b.example/y");223
assert_eq!(preview.title.as_deref(), Some("B"));224
assert_eq!(preview.description.as_deref(), Some("About B"));225
assert_eq!(preview.domain(), "b.example");226
}227
228
#[test]229
fn an_image_alone_is_enough() {230
let preview = select_preview(&links(json!([231
{"url": "https://a.example", "preview": {"previewurl": THUMBNAIL, "previewmeta": {"height": 160, "width": 320}}, "previewenabled": null},232
])))233
.unwrap();234
assert_eq!(preview.title, None);235
assert_eq!(preview.image_url.as_deref(), Some(THUMBNAIL));236
assert_eq!(237
(preview.image_width, preview.image_height),238
(Some(320), Some(160))239
);240
}241
242
#[test]243
fn reads_the_camel_case_meta_and_null_meta() {244
let preview = select_preview(&links(json!([245
{"url": "https://a.example", "preview": {"title": "A", "previewurl": THUMBNAIL, "previewMetadata": {"height": 10, "width": 20}}},246
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},247
])))248
.unwrap();249
assert_eq!(250
(preview.image_width, preview.image_height),251
(Some(20), Some(10))252
);253
let second = select_preview(&links(json!([254
{"url": "https://b.example", "preview": {"title": "B", "previewmeta": null}},255
])))256
.unwrap();257
assert_eq!(second.image_width, None);258
}259
260
#[test]261
fn a_removed_preview_is_not_shown() {262
assert_eq!(263
select_preview(&links(json!([264
{"url": "https://a.example", "preview": {"title": "A"}, "previewenabled": false},265
]))),266
None267
);268
}269
270
#[test]271
fn images_outside_the_preview_service_are_dropped() {272
assert_eq!(273
select_preview(&links(json!([274
{"url": "https://a.example", "preview": {"previewurl": "https://evil.example/i.png"}},275
]))),276
None277
);278
}279
280
#[test]281
fn garbage_and_empty_lists_have_no_preview() {282
assert_eq!(select_preview("[]"), None);283
assert_eq!(select_preview(""), None);284
assert_eq!(select_preview("{}"), None);285
assert_eq!(select_preview("[{\"url\": 3}]"), None);286
}287
288
#[test]289
fn internal_and_private_hosts_are_skipped() {290
for url in [291
"https://contoso.sharepoint.com/a",292
"https://contoso-my.sharepoint.com/a",293
"https://onedrive.com/a",294
"https://1drv.ms/a",295
"https://teams.microsoft.com/l/x",296
"https://teams.cloud.microsoft/x",297
"https://teams.live.com/x",298
"https://www.office.com/x",299
"https://m365.microsoft365.com/x",300
"https://localhost/x",301
"https://intranet/x",302
"http://192.168.1.2/x",303
"http://127.0.0.1:8080/x",304
"ftp://a.example/x",305
"mailto:a@b.example",306
] {307
assert!(!is_public_link(url), "{url}");308
}309
for url in [310
"https://github.com/rust-lang/rust",311
"http://a.example:8080/x",312
"https://notsharepoint.com/x",313
"https://user@example.org/x",314
] {315
assert!(is_public_link(url), "{url}");316
}317
}318
319
#[test]320
fn finds_the_first_public_anchor_in_html() {321
let html = "<p><a href=\"https://contoso.sharepoint.com/x\">f</a> \322
<a href=\"https://a.example/?q=1&r=2\">a</a> <a href=\"https://b.example\">b</a></p>";323
assert_eq!(324
first_public_link(html).as_deref(),325
Some("https://a.example/?q=1&r=2")326
);327
assert_eq!(first_public_link("<p>no link</p>"), None);328
}329
330
#[test]331
fn outgoing_json_reads_back_as_the_same_preview() {332
let preview = LinkPreview {333
url: "https://github.com/rust-lang/rust".into(),334
title: Some("Rust".into()),335
description: Some("Empowering".into()),336
image_url: Some(THUMBNAIL.into()),337
image_width: Some(320),338
image_height: Some(160),339
};340
let json: Value = serde_json::from_str(&preview.links_json()).unwrap();341
assert_eq!(json[0]["@type"], HYPERLINK_TYPE);342
assert_eq!(json[0]["itemid"], "0");343
assert_eq!(json[0]["previewenabled"], true);344
assert_eq!(json[0]["preview"]["previewurl"], THUMBNAIL);345
assert_eq!(select_preview(&preview.links_json()), Some(preview));346
}347
348
#[test]349
fn info_without_title_or_usable_image_makes_no_preview() {350
let info = LinkInfo {351
url: "https://a.example".into(),352
description: Some("only text".into()),353
thumbnail: Some("https://evil.example/i.png".into()),354
..LinkInfo::default()355
};356
assert_eq!(LinkPreview::from_info("https://a.example", &info), None);357
}358
359
#[test]360
fn deleted_messages_show_no_preview() {361
let record = MessageRecord {362
deleted: true,363
links_json: links(json!([{"url": "https://a.example", "preview": {"title": "A"}}])),364
..MessageRecord::default()365
};366
assert_eq!(link_preview(&record), None);367
}368
}@@ -3,6 +3,7 @@ use graph::{Attachment, Chat, Mention, Message, Reaction};
3
3
use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};
4
4
5
5
use crate::adaptive_card::card_content_text;
6
use crate::links::EMPTY_LINKS;
6
7
use crate::markdown::plain_text_to_html;
7
8
use crate::preview::OwnedPreview;
8
9
use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};
@@ -165,6 +166,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag
165
166
.filter_map(mention_info)
166
167
.collect::<Vec<_>>(),
167
168
),
169
links_json: EMPTY_LINKS.to_owned(),
168
170
})
169
171
}
170
172
@@ -3,6 +3,7 @@ use graph::{Attachment, Chat, Mention, Message, Reaction};3
use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};3
use store::{ChannelRecord, ChatRecord, MemberRecord, MessageRecord, TeamRecord};4
4
5
use crate::adaptive_card::card_content_text;5
use crate::adaptive_card::card_content_text;6
use crate::links::EMPTY_LINKS;6
use crate::markdown::plain_text_to_html;7
use crate::markdown::plain_text_to_html;7
use crate::preview::OwnedPreview;8
use crate::preview::OwnedPreview;8
use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};9
use crate::stored::{AttachmentInfo, MentionInfo, QuoteInfo, ReactionInfo};@@ -165,6 +166,7 @@ pub fn message_record(conversation_id: &str, message: &Message) -> Option<Messag165
.filter_map(mention_info)166
.filter_map(mention_info)166
.collect::<Vec<_>>(),167
.collect::<Vec<_>>(),167
),168
),169
links_json: EMPTY_LINKS.to_owned(),168
})170
})169
}171
}170
172
@@ -1,6 +1,6 @@
1
1
use chatsvc::{
2
CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse,
3
MemberHorizon, Messages, Receipts,
2
CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse, LinkInfo,
3
MemberHorizon, MessageLinks, Messages, Receipts,
4
4
};
5
5
use chrono::{DateTime, Utc};
6
6
use graph::{
@@ -217,6 +217,22 @@ pub trait Remote {
217
217
async fn invoke_card(&self, _invoke: InvokeRequest) -> Result<InvokeResponse> {
218
218
Err(Error::Unsupported("card actions"))
219
219
}
220
221
async fn message_links(
222
&self,
223
_conversation: &ConversationRef,
224
_page_size: usize,
225
) -> Result<Vec<MessageLinks>> {
226
Err(Error::Unsupported("link previews"))
227
}
228
229
async fn set_message_links(&self, _target: &MessageTarget, _links_json: &str) -> Result<()> {
230
Err(Error::Unsupported("link previews"))
231
}
232
233
async fn link_info(&self, _url: &str) -> Result<LinkInfo> {
234
Err(Error::Unsupported("link previews"))
235
}
220
236
}
221
237
222
238
impl Remote for Graph {
@@ -531,6 +547,13 @@ impl Remote for Graph {
531
547
}
532
548
533
549
async fn hosted_content(&self, url: &str) -> Result<Photo> {
550
if chatsvc::is_link_image_url(url) {
551
let image = Messages::new(self.session()).link_image(url).await?;
552
return Ok(Photo {
553
bytes: image.bytes,
554
content_type: image.content_type,
555
});
556
}
534
557
Ok(Graph::download_hosted_content(self, url).await?)
535
558
}
536
559
@@ -569,6 +592,26 @@ impl Remote for Graph {
569
592
async fn invoke_card(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {
570
593
Ok(CardActions::new(self.session()).invoke(invoke).await?)
571
594
}
595
596
async fn message_links(
597
&self,
598
conversation: &ConversationRef,
599
page_size: usize,
600
) -> Result<Vec<MessageLinks>> {
601
Ok(Messages::new(self.session())
602
.list_message_links(conversation, page_size)
603
.await?)
604
}
605
606
async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {
607
Ok(Messages::new(self.session())
608
.set_links(&conversation_ref(target), target.message_id(), links_json)
609
.await?)
610
}
611
612
async fn link_info(&self, url: &str) -> Result<LinkInfo> {
613
Ok(Messages::new(self.session()).link_info(url).await?)
614
}
572
615
}
573
616
574
617
fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {
@@ -1,6 +1,6 @@1
use chatsvc::{1
use chatsvc::{2
CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse,2
CardActions, ChatApp, ConversationRef, Conversations, InvokeRequest, InvokeResponse, LinkInfo,3
MemberHorizon, Messages, Receipts,3
MemberHorizon, MessageLinks, Messages, Receipts,4
};4
};5
use chrono::{DateTime, Utc};5
use chrono::{DateTime, Utc};6
use graph::{6
use graph::{@@ -217,6 +217,22 @@ pub trait Remote {217
async fn invoke_card(&self, _invoke: InvokeRequest) -> Result<InvokeResponse> {217
async fn invoke_card(&self, _invoke: InvokeRequest) -> Result<InvokeResponse> {218
Err(Error::Unsupported("card actions"))218
Err(Error::Unsupported("card actions"))219
}219
}220
221
async fn message_links(222
&self,223
_conversation: &ConversationRef,224
_page_size: usize,225
) -> Result<Vec<MessageLinks>> {226
Err(Error::Unsupported("link previews"))227
}228
229
async fn set_message_links(&self, _target: &MessageTarget, _links_json: &str) -> Result<()> {230
Err(Error::Unsupported("link previews"))231
}232
233
async fn link_info(&self, _url: &str) -> Result<LinkInfo> {234
Err(Error::Unsupported("link previews"))235
}220
}236
}221
237
222
impl Remote for Graph {238
impl Remote for Graph {@@ -531,6 +547,13 @@ impl Remote for Graph {531
}547
}532
548
533
async fn hosted_content(&self, url: &str) -> Result<Photo> {549
async fn hosted_content(&self, url: &str) -> Result<Photo> {550
if chatsvc::is_link_image_url(url) {551
let image = Messages::new(self.session()).link_image(url).await?;552
return Ok(Photo {553
bytes: image.bytes,554
content_type: image.content_type,555
});556
}534
Ok(Graph::download_hosted_content(self, url).await?)557
Ok(Graph::download_hosted_content(self, url).await?)535
}558
}536
559
@@ -569,6 +592,26 @@ impl Remote for Graph {569
async fn invoke_card(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {592
async fn invoke_card(&self, invoke: InvokeRequest) -> Result<InvokeResponse> {570
Ok(CardActions::new(self.session()).invoke(invoke).await?)593
Ok(CardActions::new(self.session()).invoke(invoke).await?)571
}594
}595
596
async fn message_links(597
&self,598
conversation: &ConversationRef,599
page_size: usize,600
) -> Result<Vec<MessageLinks>> {601
Ok(Messages::new(self.session())602
.list_message_links(conversation, page_size)603
.await?)604
}605
606
async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {607
Ok(Messages::new(self.session())608
.set_links(&conversation_ref(target), target.message_id(), links_json)609
.await?)610
}611
612
async fn link_info(&self, url: &str) -> Result<LinkInfo> {613
Ok(Messages::new(self.session()).link_info(url).await?)614
}572
}615
}573
616
574
fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {617
fn chatsvc_conversation(target: &MessageTarget) -> Option<ConversationRef> {@@ -597,6 +597,7 @@ mod tests {
597
597
sender_id: Some("u".to_owned()),
598
598
sender_name: None,
599
599
sender_application_id: None,
600
links_json: "[]".to_owned(),
600
601
created_at: Utc::now(),
601
602
edited_at: None,
602
603
deleted: false,
@@ -597,6 +597,7 @@ mod tests {597
sender_id: Some("u".to_owned()),597
sender_id: Some("u".to_owned()),598
sender_name: None,598
sender_name: None,599
sender_application_id: None,599
sender_application_id: None,600
links_json: "[]".to_owned(),600
created_at: Utc::now(),601
created_at: Utc::now(),601
edited_at: None,602
edited_at: None,602
deleted: false,603
deleted: false,@@ -94,6 +94,10 @@ struct Fake {
94
94
invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,
95
95
muted_states: Mutex<Vec<(String, bool)>>,
96
96
muted_fails: Mutex<bool>,
97
link_pages: Mutex<Vec<chatsvc::MessageLinks>>,
98
link_page_calls: Mutex<Vec<String>>,
99
links_put: Mutex<Vec<(String, String)>>,
100
link_info_calls: Mutex<usize>,
97
101
}
98
102
99
103
impl Fake {
@@ -625,6 +629,35 @@ impl Remote for Handle {
625
629
.unwrap_or(chatsvc::InvokeResponse::Empty))
626
630
}
627
631
632
async fn message_links(
633
&self,
634
conversation: &chatsvc::ConversationRef,
635
_page_size: usize,
636
) -> Result<Vec<chatsvc::MessageLinks>> {
637
self.link_page_calls
638
.lock()
639
.unwrap()
640
.push(conversation.conversation_id());
641
Ok(self.link_pages.lock().unwrap().clone())
642
}
643
644
async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {
645
self.links_put
646
.lock()
647
.unwrap()
648
.push((describe(target), links_json.to_owned()));
649
Ok(())
650
}
651
652
async fn link_info(&self, url: &str) -> Result<chatsvc::LinkInfo> {
653
*self.link_info_calls.lock().unwrap() += 1;
654
Ok(chatsvc::LinkInfo {
655
url: url.to_owned(),
656
title: Some("Example".into()),
657
..chatsvc::LinkInfo::default()
658
})
659
}
660
628
661
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {
629
662
let answers = self.presence_answers.lock().unwrap();
630
663
Ok(answers
@@ -3055,3 +3088,104 @@ async fn bot_messages_remember_their_application() {
3055
3088
assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID));
3056
3089
assert_eq!(record.sender_id, None);
3057
3090
}
3091
3092
const PREVIEW_LINKS: &str =
3093
r#"[{"url":"https://a.example/x","preview":{"title":"Example"},"previewenabled":true}]"#;
3094
3095
#[tokio::test]
3096
async fn links_from_the_chat_service_survive_the_next_graph_sync() {
3097
let fake = Arc::new(Fake::default());
3098
let engine = chat_engine(&fake, small_pages()).await;
3099
fake.set_chat_messages(vec![message(
3100
1,
3101
1,
3102
"<p><a href=\"https://a.example/x\">link</a></p>",
3103
)]);
3104
*fake.link_pages.lock().unwrap() = vec![chatsvc::MessageLinks {
3105
message_id: "m0001".into(),
3106
links_json: PREVIEW_LINKS.into(),
3107
}];
3108
3109
let delta = engine.fetch_newer(CHAT).await.unwrap();
3110
assert_eq!(delta.added[0].links_json, PREVIEW_LINKS);
3111
assert_eq!(
3112
engine.open_conversation(CHAT).unwrap()[0].links_json,
3113
PREVIEW_LINKS
3114
);
3115
assert_eq!(*fake.link_page_calls.lock().unwrap(), [CHAT]);
3116
3117
let again = engine.fetch_newer(CHAT).await.unwrap();
3118
assert!(again.is_empty());
3119
assert_eq!(
3120
engine.open_conversation(CHAT).unwrap()[0].links_json,
3121
PREVIEW_LINKS
3122
);
3123
}
3124
3125
#[tokio::test]
3126
async fn messages_without_anchors_do_not_ask_the_chat_service() {
3127
let fake = Arc::new(Fake::default());
3128
let engine = chat_engine(&fake, small_pages()).await;
3129
fake.set_chat_messages(vec![message(1, 1, "<p>plain</p>")]);
3130
engine.fetch_newer(CHAT).await.unwrap();
3131
assert!(fake.link_page_calls.lock().unwrap().is_empty());
3132
}
3133
3134
#[tokio::test]
3135
async fn a_failing_chat_service_leaves_no_preview() {
3136
let fake = Arc::new(Fake::default());
3137
let engine = chat_engine(&fake, small_pages()).await;
3138
fake.set_chat_messages(vec![message(1, 1, "<a href=\"https://a.example\">x</a>")]);
3139
let delta = engine.fetch_newer(CHAT).await.unwrap();
3140
assert_eq!(delta.added[0].links_json, "[]");
3141
}
3142
3143
#[tokio::test]
3144
async fn attaching_a_preview_puts_the_links_and_keeps_them_locally() {
3145
let fake = Arc::new(Fake::default());
3146
let engine = chat_engine(&fake, small_pages()).await;
3147
let sent = engine
3148
.send_message_with_mentions(CHAT, "see https://a.example/x", None, &[])
3149
.await
3150
.unwrap();
3151
let preview = engine
3152
.link_preview_for("https://a.example/x")
3153
.await
3154
.unwrap()
3155
.unwrap();
3156
3157
engine
3158
.attach_link_preview(CHAT, &sent.message_id, &preview)
3159
.await
3160
.unwrap();
3161
3162
let put = fake.links_put.lock().unwrap().clone();
3163
assert_eq!(put.len(), 1);
3164
assert_eq!(put[0].0, sent.message_id);
3165
assert!(put[0].1.contains("\"itemid\":\"0\""));
3166
let stored = engine
3167
.store()
3168
.messages_by_id(CHAT, std::slice::from_ref(&sent.message_id))
3169
.unwrap();
3170
assert_eq!(stored[&sent.message_id].links_json, put[0].1);
3171
}
3172
3173
#[tokio::test]
3174
async fn link_infos_are_fetched_once_per_url_and_internal_links_never() {
3175
let fake = Arc::new(Fake::default());
3176
let engine = chat_engine(&fake, small_pages()).await;
3177
for _ in 0..2 {
3178
engine
3179
.link_preview_for("https://a.example/x")
3180
.await
3181
.unwrap();
3182
}
3183
assert!(
3184
engine
3185
.link_preview_for("https://contoso.sharepoint.com/x")
3186
.await
3187
.unwrap()
3188
.is_none()
3189
);
3190
assert_eq!(*fake.link_info_calls.lock().unwrap(), 1);
3191
}
@@ -94,6 +94,10 @@ struct Fake {94
invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,94
invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>,95
muted_states: Mutex<Vec<(String, bool)>>,95
muted_states: Mutex<Vec<(String, bool)>>,96
muted_fails: Mutex<bool>,96
muted_fails: Mutex<bool>,97
link_pages: Mutex<Vec<chatsvc::MessageLinks>>,98
link_page_calls: Mutex<Vec<String>>,99
links_put: Mutex<Vec<(String, String)>>,100
link_info_calls: Mutex<usize>,97
}101
}98
102
99
impl Fake {103
impl Fake {@@ -625,6 +629,35 @@ impl Remote for Handle {625
.unwrap_or(chatsvc::InvokeResponse::Empty))629
.unwrap_or(chatsvc::InvokeResponse::Empty))626
}630
}627
631
632
async fn message_links(633
&self,634
conversation: &chatsvc::ConversationRef,635
_page_size: usize,636
) -> Result<Vec<chatsvc::MessageLinks>> {637
self.link_page_calls638
.lock()639
.unwrap()640
.push(conversation.conversation_id());641
Ok(self.link_pages.lock().unwrap().clone())642
}643
644
async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> {645
self.links_put646
.lock()647
.unwrap()648
.push((describe(target), links_json.to_owned()));649
Ok(())650
}651
652
async fn link_info(&self, url: &str) -> Result<chatsvc::LinkInfo> {653
*self.link_info_calls.lock().unwrap() += 1;654
Ok(chatsvc::LinkInfo {655
url: url.to_owned(),656
title: Some("Example".into()),657
..chatsvc::LinkInfo::default()658
})659
}660
628
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {661
async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> {629
let answers = self.presence_answers.lock().unwrap();662
let answers = self.presence_answers.lock().unwrap();630
Ok(answers663
Ok(answers@@ -3055,3 +3088,104 @@ async fn bot_messages_remember_their_application() {3055
assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID));3088
assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID));3056
assert_eq!(record.sender_id, None);3089
assert_eq!(record.sender_id, None);3057
}3090
}3091
3092
const PREVIEW_LINKS: &str =3093
r#"[{"url":"https://a.example/x","preview":{"title":"Example"},"previewenabled":true}]"#;3094
3095
#[tokio::test]3096
async fn links_from_the_chat_service_survive_the_next_graph_sync() {3097
let fake = Arc::new(Fake::default());3098
let engine = chat_engine(&fake, small_pages()).await;3099
fake.set_chat_messages(vec![message(3100
1,3101
1,3102
"<p><a href=\"https://a.example/x\">link</a></p>",3103
)]);3104
*fake.link_pages.lock().unwrap() = vec![chatsvc::MessageLinks {3105
message_id: "m0001".into(),3106
links_json: PREVIEW_LINKS.into(),3107
}];3108
3109
let delta = engine.fetch_newer(CHAT).await.unwrap();3110
assert_eq!(delta.added[0].links_json, PREVIEW_LINKS);3111
assert_eq!(3112
engine.open_conversation(CHAT).unwrap()[0].links_json,3113
PREVIEW_LINKS3114
);3115
assert_eq!(*fake.link_page_calls.lock().unwrap(), [CHAT]);3116
3117
let again = engine.fetch_newer(CHAT).await.unwrap();3118
assert!(again.is_empty());3119
assert_eq!(3120
engine.open_conversation(CHAT).unwrap()[0].links_json,3121
PREVIEW_LINKS3122
);3123
}3124
3125
#[tokio::test]3126
async fn messages_without_anchors_do_not_ask_the_chat_service() {3127
let fake = Arc::new(Fake::default());3128
let engine = chat_engine(&fake, small_pages()).await;3129
fake.set_chat_messages(vec![message(1, 1, "<p>plain</p>")]);3130
engine.fetch_newer(CHAT).await.unwrap();3131
assert!(fake.link_page_calls.lock().unwrap().is_empty());3132
}3133
3134
#[tokio::test]3135
async fn a_failing_chat_service_leaves_no_preview() {3136
let fake = Arc::new(Fake::default());3137
let engine = chat_engine(&fake, small_pages()).await;3138
fake.set_chat_messages(vec![message(1, 1, "<a href=\"https://a.example\">x</a>")]);3139
let delta = engine.fetch_newer(CHAT).await.unwrap();3140
assert_eq!(delta.added[0].links_json, "[]");3141
}3142
3143
#[tokio::test]3144
async fn attaching_a_preview_puts_the_links_and_keeps_them_locally() {3145
let fake = Arc::new(Fake::default());3146
let engine = chat_engine(&fake, small_pages()).await;3147
let sent = engine3148
.send_message_with_mentions(CHAT, "see https://a.example/x", None, &[])3149
.await3150
.unwrap();3151
let preview = engine3152
.link_preview_for("https://a.example/x")3153
.await3154
.unwrap()3155
.unwrap();3156
3157
engine3158
.attach_link_preview(CHAT, &sent.message_id, &preview)3159
.await3160
.unwrap();3161
3162
let put = fake.links_put.lock().unwrap().clone();3163
assert_eq!(put.len(), 1);3164
assert_eq!(put[0].0, sent.message_id);3165
assert!(put[0].1.contains("\"itemid\":\"0\""));3166
let stored = engine3167
.store()3168
.messages_by_id(CHAT, std::slice::from_ref(&sent.message_id))3169
.unwrap();3170
assert_eq!(stored[&sent.message_id].links_json, put[0].1);3171
}3172
3173
#[tokio::test]3174
async fn link_infos_are_fetched_once_per_url_and_internal_links_never() {3175
let fake = Arc::new(Fake::default());3176
let engine = chat_engine(&fake, small_pages()).await;3177
for _ in 0..2 {3178
engine3179
.link_preview_for("https://a.example/x")3180
.await3181
.unwrap();3182
}3183
assert!(3184
engine3185
.link_preview_for("https://contoso.sharepoint.com/x")3186
.await3187
.unwrap()3188
.is_none()3189
);3190
assert_eq!(*fake.link_info_calls.lock().unwrap(), 1);3191
}@@ -364,6 +364,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {
364
364
sender_id: None,
365
365
sender_name: None,
366
366
sender_application_id: None,
367
links_json: "[]".to_owned(),
367
368
created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),
368
369
edited_at: None,
369
370
deleted: false,
@@ -364,6 +364,7 @@ fn record_with(body_html: &str, attachments_json: &str) -> MessageRecord {364
sender_id: None,364
sender_id: None,365
sender_name: None,365
sender_name: None,366
sender_application_id: None,366
sender_application_id: None,367
links_json: "[]".to_owned(),367
created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),368
created_at: chrono::DateTime::from_timestamp(1_700_000_000, 0).unwrap(),368
edited_at: None,369
edited_at: None,369
deleted: false,370
deleted: false,@@ -10,7 +10,7 @@ use crate::store::Store;
10
10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};
11
11
12
12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \
13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id";
13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json";
14
14
15
15
impl Store {
16
16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {
@@ -19,14 +19,16 @@ impl Store {
19
19
{
20
20
let mut upsert = transaction.prepare_cached(&format!(
21
21
"INSERT INTO messages ({MESSAGE_COLUMNS})
22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)
22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)
23
23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET
24
24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,
25
25
sender_name = excluded.sender_name, created_at = excluded.created_at,
26
26
edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,
27
27
attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,
28
28
mentions_json = excluded.mentions_json,
29
sender_application_id = excluded.sender_application_id"
29
sender_application_id = excluded.sender_application_id,
30
links_json = CASE WHEN excluded.links_json IN ('', '[]')
31
THEN messages.links_json ELSE excluded.links_json END"
30
32
))?;
31
33
for message in messages {
32
34
upsert.execute(params![
@@ -43,6 +45,7 @@ impl Store {
43
45
message.reactions_json,
44
46
message.mentions_json,
45
47
message.sender_application_id,
48
message.links_json,
46
49
])?;
47
50
index_message(&transaction, message)?;
48
51
}
@@ -50,6 +53,21 @@ impl Store {
50
53
Ok(transaction.commit()?)
51
54
}
52
55
56
pub fn set_message_links(
57
&self,
58
conversation_id: &str,
59
message_id: &str,
60
links_json: &str,
61
) -> Result<bool> {
62
let connection = self.lock()?;
63
let changed = connection.execute(
64
"UPDATE messages SET links_json = ?3
65
WHERE conversation_id = ?1 AND message_id = ?2 AND links_json <> ?3",
66
params![conversation_id, message_id, links_json],
67
)?;
68
Ok(changed > 0)
69
}
70
53
71
pub fn count_messages_after(
54
72
&self,
55
73
conversation_id: &str,
@@ -210,5 +228,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {
210
228
reactions_json: row.get(10)?,
211
229
mentions_json: row.get(11)?,
212
230
sender_application_id: row.get(12)?,
231
links_json: row.get(13)?,
213
232
})
214
233
}
@@ -10,7 +10,7 @@ use crate::store::Store;10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};10
use crate::time::{from_millis, optional_from_millis, optional_to_millis, to_millis};11
11
12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \12
const MESSAGE_COLUMNS: &str = "conversation_id, message_id, reply_to_id, sender_id, sender_name, created_at, \13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id";13
edited_at, deleted, body_html, attachments_json, reactions_json, mentions_json, sender_application_id, links_json";14
14
15
impl Store {15
impl Store {16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {16
pub fn upsert_messages(&self, messages: &[MessageRecord]) -> Result<()> {@@ -19,14 +19,16 @@ impl Store {19
{19
{20
let mut upsert = transaction.prepare_cached(&format!(20
let mut upsert = transaction.prepare_cached(&format!(21
"INSERT INTO messages ({MESSAGE_COLUMNS})21
"INSERT INTO messages ({MESSAGE_COLUMNS})22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13)22
VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14)23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET23
ON CONFLICT (conversation_id, message_id) DO UPDATE SET24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,24
reply_to_id = excluded.reply_to_id, sender_id = excluded.sender_id,25
sender_name = excluded.sender_name, created_at = excluded.created_at,25
sender_name = excluded.sender_name, created_at = excluded.created_at,26
edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,26
edited_at = excluded.edited_at, deleted = excluded.deleted, body_html = excluded.body_html,27
attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,27
attachments_json = excluded.attachments_json, reactions_json = excluded.reactions_json,28
mentions_json = excluded.mentions_json,28
mentions_json = excluded.mentions_json,29
sender_application_id = excluded.sender_application_id"29
sender_application_id = excluded.sender_application_id,30
links_json = CASE WHEN excluded.links_json IN ('', '[]')31
THEN messages.links_json ELSE excluded.links_json END"30
))?;32
))?;31
for message in messages {33
for message in messages {32
upsert.execute(params![34
upsert.execute(params![@@ -43,6 +45,7 @@ impl Store {43
message.reactions_json,45
message.reactions_json,44
message.mentions_json,46
message.mentions_json,45
message.sender_application_id,47
message.sender_application_id,48
message.links_json,46
])?;49
])?;47
index_message(&transaction, message)?;50
index_message(&transaction, message)?;48
}51
}@@ -50,6 +53,21 @@ impl Store {50
Ok(transaction.commit()?)53
Ok(transaction.commit()?)51
}54
}52
55
56
pub fn set_message_links(57
&self,58
conversation_id: &str,59
message_id: &str,60
links_json: &str,61
) -> Result<bool> {62
let connection = self.lock()?;63
let changed = connection.execute(64
"UPDATE messages SET links_json = ?365
WHERE conversation_id = ?1 AND message_id = ?2 AND links_json <> ?3",66
params![conversation_id, message_id, links_json],67
)?;68
Ok(changed > 0)69
}70
53
pub fn count_messages_after(71
pub fn count_messages_after(54
&self,72
&self,55
conversation_id: &str,73
conversation_id: &str,@@ -210,5 +228,6 @@ fn message_from_row(row: &Row<'_>) -> rusqlite::Result<MessageRecord> {210
reactions_json: row.get(10)?,228
reactions_json: row.get(10)?,211
mentions_json: row.get(11)?,229
mentions_json: row.get(11)?,212
sender_application_id: row.get(12)?,230
sender_application_id: row.get(12)?,231
links_json: row.get(13)?,213
})232
})214
}233
}@@ -49,6 +49,10 @@ const MIGRATIONS: &[Migration] = &[
49
49
script: include_str!("migrations/0010_name_lookup_indexes.sql"),
50
50
after: None,
51
51
},
52
Migration {
53
script: include_str!("migrations/0011_message_links.sql"),
54
after: None,
55
},
52
56
];
53
57
54
58
pub fn latest_version() -> i64 {
@@ -49,6 +49,10 @@ const MIGRATIONS: &[Migration] = &[49
script: include_str!("migrations/0010_name_lookup_indexes.sql"),49
script: include_str!("migrations/0010_name_lookup_indexes.sql"),50
after: None,50
after: None,51
},51
},52
Migration {53
script: include_str!("migrations/0011_message_links.sql"),54
after: None,55
},52
];56
];53
57
54
pub fn latest_version() -> i64 {58
pub fn latest_version() -> i64 {@@ -0,0 +1 @@
1
ALTER TABLE messages ADD COLUMN links_json TEXT NOT NULL DEFAULT '[]';
@@ -0,0 +1 @@1
ALTER TABLE messages ADD COLUMN links_json TEXT NOT NULL DEFAULT '[]';@@ -71,6 +71,7 @@ pub struct MessageRecord {
71
71
pub reactions_json: String,
72
72
pub mentions_json: String,
73
73
pub sender_application_id: Option<String>,
74
pub links_json: String,
74
75
}
75
76
76
77
#[derive(Debug, Clone, PartialEq)]
@@ -71,6 +71,7 @@ pub struct MessageRecord {71
pub reactions_json: String,71
pub reactions_json: String,72
pub mentions_json: String,72
pub mentions_json: String,73
pub sender_application_id: Option<String>,73
pub sender_application_id: Option<String>,74
pub links_json: String,74
}75
}75
76
76
#[derive(Debug, Clone, PartialEq)]77
#[derive(Debug, Clone, PartialEq)]@@ -64,6 +64,7 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor
64
64
reactions_json: "[]".to_owned(),
65
65
mentions_json: "[]".to_owned(),
66
66
sender_application_id: None,
67
links_json: "[]".to_owned(),
67
68
}
68
69
}
69
70
@@ -81,6 +82,40 @@ fn sender_application_round_trips() {
81
82
assert_eq!(found["m1"], bot_message);
82
83
}
83
84
85
#[test]
86
fn an_upsert_without_links_keeps_the_stored_links() {
87
let store = Store::open_in_memory().unwrap();
88
store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
89
let links = r#"[{"url":"https://a.example"}]"#;
90
assert!(store.set_message_links("c1", "m1", links).unwrap());
91
assert!(!store.set_message_links("c1", "m1", links).unwrap());
92
93
let edited = MessageRecord {
94
body_html: "<p>edited</p>".to_owned(),
95
..message("c1", "m1", 1)
96
};
97
store.upsert_messages(&[edited]).unwrap();
98
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
99
assert_eq!(found["m1"].links_json, links);
100
assert_eq!(found["m1"].body_html, "<p>edited</p>");
101
102
let replaced = MessageRecord {
103
links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),
104
..message("c1", "m1", 1)
105
};
106
store.upsert_messages(std::slice::from_ref(&replaced)).unwrap();
107
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
108
assert_eq!(found["m1"].links_json, replaced.links_json);
109
}
110
111
#[test]
112
fn new_messages_start_without_links() {
113
let store = Store::open_in_memory().unwrap();
114
store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();
115
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();
116
assert_eq!(found["m1"].links_json, "[]");
117
}
118
84
119
fn ids(messages: &[MessageRecord]) -> Vec<&str> {
85
120
messages
86
121
.iter()
@@ -395,11 +430,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
395
430
let path = directory.path().join("nested").join("cache.sqlite3");
396
431
{
397
432
let store = Store::open(&path).unwrap();
398
assert_eq!(store.schema_version().unwrap(), 10);
433
assert_eq!(store.schema_version().unwrap(), 11);
399
434
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
400
435
}
401
436
let reopened = Store::open(&path).unwrap();
402
assert_eq!(reopened.schema_version().unwrap(), 10);
437
assert_eq!(reopened.schema_version().unwrap(), 11);
403
438
assert_eq!(reopened.message_count("c").unwrap(), 1);
404
439
drop(reopened);
405
440
let mode: String = rusqlite_open(&path)
@@ -431,7 +466,7 @@ fn old_schema_is_upgraded_in_place() {
431
466
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();
432
467
drop(connection);
433
468
let store = Store::open(&path).unwrap();
434
assert_eq!(store.schema_version().unwrap(), 10);
469
assert_eq!(store.schema_version().unwrap(), 11);
435
470
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
436
471
}
437
472
@@ -497,7 +532,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
497
532
let store = Store::open(&path).unwrap();
498
533
let state = store.sync_state("c").unwrap().unwrap();
499
534
assert_eq!(state.delta_link, None);
500
assert_eq!(store.schema_version().unwrap(), 10);
535
assert_eq!(store.schema_version().unwrap(), 11);
501
536
}
502
537
503
538
#[test]
@@ -730,6 +765,7 @@ fn migration_indexes_rows_that_predate_search() {
730
765
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;
731
766
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;
732
767
ALTER TABLE messages DROP COLUMN sender_application_id;
768
ALTER TABLE messages DROP COLUMN links_json;
733
769
ALTER TABLE chats DROP COLUMN muted;
734
770
PRAGMA user_version = 3;",
735
771
)
@@ -64,6 +64,7 @@ fn message(conversation_id: &str, message_id: &str, minute: u32) -> MessageRecor64
reactions_json: "[]".to_owned(),64
reactions_json: "[]".to_owned(),65
mentions_json: "[]".to_owned(),65
mentions_json: "[]".to_owned(),66
sender_application_id: None,66
sender_application_id: None,67
links_json: "[]".to_owned(),67
}68
}68
}69
}69
70
@@ -81,6 +82,40 @@ fn sender_application_round_trips() {81
assert_eq!(found["m1"], bot_message);82
assert_eq!(found["m1"], bot_message);82
}83
}83
84
85
#[test]86
fn an_upsert_without_links_keeps_the_stored_links() {87
let store = Store::open_in_memory().unwrap();88
store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();89
let links = r#"[{"url":"https://a.example"}]"#;90
assert!(store.set_message_links("c1", "m1", links).unwrap());91
assert!(!store.set_message_links("c1", "m1", links).unwrap());92
93
let edited = MessageRecord {94
body_html: "<p>edited</p>".to_owned(),95
..message("c1", "m1", 1)96
};97
store.upsert_messages(&[edited]).unwrap();98
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();99
assert_eq!(found["m1"].links_json, links);100
assert_eq!(found["m1"].body_html, "<p>edited</p>");101
102
let replaced = MessageRecord {103
links_json: r#"[{"url":"https://b.example"}]"#.to_owned(),104
..message("c1", "m1", 1)105
};106
store.upsert_messages(std::slice::from_ref(&replaced)).unwrap();107
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();108
assert_eq!(found["m1"].links_json, replaced.links_json);109
}110
111
#[test]112
fn new_messages_start_without_links() {113
let store = Store::open_in_memory().unwrap();114
store.upsert_messages(&[message("c1", "m1", 1)]).unwrap();115
let found = store.messages_by_id("c1", &["m1".to_owned()]).unwrap();116
assert_eq!(found["m1"].links_json, "[]");117
}118
84
fn ids(messages: &[MessageRecord]) -> Vec<&str> {119
fn ids(messages: &[MessageRecord]) -> Vec<&str> {85
messages120
messages86
.iter()121
.iter()@@ -395,11 +430,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {395
let path = directory.path().join("nested").join("cache.sqlite3");430
let path = directory.path().join("nested").join("cache.sqlite3");396
{431
{397
let store = Store::open(&path).unwrap();432
let store = Store::open(&path).unwrap();398
assert_eq!(store.schema_version().unwrap(), 10);433
assert_eq!(store.schema_version().unwrap(), 11);399
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();434
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();400
}435
}401
let reopened = Store::open(&path).unwrap();436
let reopened = Store::open(&path).unwrap();402
assert_eq!(reopened.schema_version().unwrap(), 10);437
assert_eq!(reopened.schema_version().unwrap(), 11);403
assert_eq!(reopened.message_count("c").unwrap(), 1);438
assert_eq!(reopened.message_count("c").unwrap(), 1);404
drop(reopened);439
drop(reopened);405
let mode: String = rusqlite_open(&path)440
let mode: String = rusqlite_open(&path)@@ -431,7 +466,7 @@ fn old_schema_is_upgraded_in_place() {431
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();466
connection.execute_batch("DROP TABLE messages; DROP TABLE sync_state; DROP TABLE chats; DROP TABLE chat_members; DROP TABLE channels; DROP TABLE teams; DROP TABLE meta; DROP TABLE avatars; DROP TABLE folder_items; DROP TABLE folders; DROP TABLE pinned_channels; DROP TABLE images; DROP TABLE search_keys; DROP TABLE message_search; DROP TABLE title_search; DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity; PRAGMA user_version = 0").unwrap();432
drop(connection);467
drop(connection);433
let store = Store::open(&path).unwrap();468
let store = Store::open(&path).unwrap();434
assert_eq!(store.schema_version().unwrap(), 10);469
assert_eq!(store.schema_version().unwrap(), 11);435
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();470
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();436
}471
}437
472
@@ -497,7 +532,7 @@ fn migration_to_v2_keeps_existing_sync_state() {497
let store = Store::open(&path).unwrap();532
let store = Store::open(&path).unwrap();498
let state = store.sync_state("c").unwrap().unwrap();533
let state = store.sync_state("c").unwrap().unwrap();499
assert_eq!(state.delta_link, None);534
assert_eq!(state.delta_link, None);500
assert_eq!(store.schema_version().unwrap(), 10);535
assert_eq!(store.schema_version().unwrap(), 11);501
}536
}502
537
503
#[test]538
#[test]@@ -730,6 +765,7 @@ fn migration_indexes_rows_that_predate_search() {730
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;765
DROP TABLE team_layout; DROP TABLE channel_layout; DROP TABLE presence; DROP TABLE activity;731
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;766
DROP INDEX messages_by_sender; DROP INDEX chat_members_by_user;732
ALTER TABLE messages DROP COLUMN sender_application_id;767
ALTER TABLE messages DROP COLUMN sender_application_id;768
ALTER TABLE messages DROP COLUMN links_json;733
ALTER TABLE chats DROP COLUMN muted;769
ALTER TABLE chats DROP COLUMN muted;734
PRAGMA user_version = 3;",770
PRAGMA user_version = 3;",735
)771
)