fix(chat): forward mentions, names, time label and cache healing
- mentions inside a forwarded original no longer resolve against the forwarder's mention list - forward header uses the app offset and post_time_label, sender via the shared name lookup (view and MCP) - cached forwards without content are re-read by id once per chat and session, replaces migration 0021 - forwards() skips records without a forward attachment before parsing Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -55,14 +55,13 @@ impl TeamsSource for AppSource {
55
55
.filter(|forward| forward.sender.is_none())
56
56
.filter_map(|forward| forward.sender_id.clone())
57
57
.collect();
58
if let Ok(names) = self.store.display_names(&unnamed) {
59
for forward in &mut extras.forwarded {
60
if forward.sender.is_none() {
61
forward.sender = forward
62
.sender_id
63
.as_ref()
64
.and_then(|sender_id| names.get(sender_id).cloned());
65
}
58
let names = crate::people::stored_names(&self.store, &unnamed);
59
for forward in &mut extras.forwarded {
60
if forward.sender.is_none() {
61
forward.sender = forward
62
.sender_id
63
.as_ref()
64
.and_then(|sender_id| names.get(sender_id).cloned());
66
65
}
67
66
}
68
67
extras
@@ -55,14 +55,13 @@ impl TeamsSource for AppSource {55
.filter(|forward| forward.sender.is_none())55
.filter(|forward| forward.sender.is_none())56
.filter_map(|forward| forward.sender_id.clone())56
.filter_map(|forward| forward.sender_id.clone())57
.collect();57
.collect();58
if let Ok(names) = self.store.display_names(&unnamed) {58
let names = crate::people::stored_names(&self.store, &unnamed);59
for forward in &mut extras.forwarded {59
for forward in &mut extras.forwarded {60
if forward.sender.is_none() {60
if forward.sender.is_none() {61
forward.sender = forward61
forward.sender = forward62
.sender_id62
.sender_id63
.as_ref()63
.as_ref()64
.and_then(|sender_id| names.get(sender_id).cloned());64
.and_then(|sender_id| names.get(sender_id).cloned());65
}66
}65
}67
}66
}68
extras67
extras@@ -1,5 +1,7 @@
1
1
use std::collections::HashMap;
2
2
3
use store::Store;
4
3
5
use crate::app_state::AppState;
4
6
5
7
pub fn local_names(state: &AppState) -> HashMap<String, String> {
@@ -31,8 +33,14 @@ pub fn resolve_names(state: &AppState, user_ids: &[String]) -> HashMap<String, S
31
33
.filter(|user_id| !names.contains_key(*user_id))
32
34
.cloned()
33
35
.collect();
34
if let Ok(stored) = state.store.display_names(&missing) {
35
names.extend(stored);
36
}
36
names.extend(stored_names(&state.store, &missing));
37
37
names
38
38
}
39
40
/// Names the cache knows from chat members and sent messages, for people outside the sidebar.
41
pub fn stored_names(store: &Store, user_ids: &[String]) -> HashMap<String, String> {
42
if user_ids.is_empty() {
43
return HashMap::new();
44
}
45
store.display_names(user_ids).unwrap_or_default()
46
}
@@ -1,5 +1,7 @@1
use std::collections::HashMap;1
use std::collections::HashMap;2
2
3
use store::Store;4
3
use crate::app_state::AppState;5
use crate::app_state::AppState;4
6
5
pub fn local_names(state: &AppState) -> HashMap<String, String> {7
pub fn local_names(state: &AppState) -> HashMap<String, String> {@@ -31,8 +33,14 @@ pub fn resolve_names(state: &AppState, user_ids: &[String]) -> HashMap<String, S31
.filter(|user_id| !names.contains_key(*user_id))33
.filter(|user_id| !names.contains_key(*user_id))32
.cloned()34
.cloned()33
.collect();35
.collect();34
if let Ok(stored) = state.store.display_names(&missing) {36
names.extend(stored_names(&state.store, &missing));35
names.extend(stored);36
}37
names37
names38
}38
}39
40
/// Names the cache knows from chat members and sent messages, for people outside the sidebar.41
pub fn stored_names(store: &Store, user_ids: &[String]) -> HashMap<String, String> {42
if user_ids.is_empty() {43
return HashMap::new();44
}45
store.display_names(user_ids).unwrap_or_default()46
}@@ -7,7 +7,8 @@ use gpui_kit::Image;
7
7
use store::MessageRecord;
8
8
use teams_core::{
9
9
JumboEmoji, jumbo_emoji,
10
AdaptiveCard, CallEvent, CallPhase, CallType, Draft, FileCard, ImageRef, LinkPreview,
10
AdaptiveCard, CallEvent, CallPhase, CallType, Draft, FileCard, ForwardHeader, ForwardInfo,
11
ImageRef, LinkPreview, forwards,
11
12
ReactionInfo, Span, adaptive_cards, call_event, card_texts, files, format_duration,
12
13
forwarded_texts, images, is_forwarded, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans, quotes,
13
14
reactions, readable_text, translated_spans,
@@ -688,6 +689,33 @@ pub fn quoted_texts(records: &[MessageRecord]) -> HashMap<String, String> {
688
689
.collect()
689
690
}
690
691
692
fn forward_header(forward: &ForwardInfo, context: &RowContext) -> ForwardHeader {
693
ForwardHeader {
694
sender: forward
695
.sender_id
696
.as_ref()
697
.and_then(|user_id| context.names.get(user_id).cloned()),
698
time: forward
699
.sent_at
700
.map(|time| format::post_time_label(time, context.today, context.offset)),
701
}
702
}
703
704
/// User ids a row needs a name for beyond its author: original senders of forwards.
705
pub fn forward_sender_ids(records: &[MessageRecord]) -> Vec<String> {
706
let mut user_ids: Vec<String> = Vec::new();
707
for user_id in records
708
.iter()
709
.flat_map(forwards)
710
.filter_map(|forward| forward.sender_id)
711
{
712
if !user_ids.contains(&user_id) {
713
user_ids.push(user_id);
714
}
715
}
716
user_ids
717
}
718
691
719
pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
692
720
message_row_with(record, context, &HashMap::new())
693
721
}
@@ -704,15 +732,16 @@ fn message_row_with(
704
732
let images = images(record);
705
733
let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
706
734
let translation = context.translation.resolve(record, own);
735
let forward_header = |forward: &ForwardInfo| forward_header(forward, context);
707
736
let blocks = if record.deleted {
708
737
vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
709
738
} else if let Some(html) = &translation.translated_html {
710
layout_blocks(&translated_spans(record, html))
739
layout_blocks(&translated_spans(record, html, &forward_header))
711
740
} else {
712
741
layout_blocks(&linked_message_spans_with(
713
742
record,
714
743
&|id| quoted.get(id).cloned(),
715
&|user_id| context.names.get(user_id).cloned(),
744
&forward_header,
716
745
))
717
746
};
718
747
let blocks = if images.is_empty() {
@@ -1158,7 +1187,7 @@ mod tests {
1158
1187
panic!("expected one forward quote, got {:?}", row.blocks);
1159
1188
};
1160
1189
let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect();
1161
assert!(lines[0].contains("Priya Nair"), "{lines:?}");
1190
assert!(lines[0].contains("Priya Nair Yesterday 07:00"), "{lines:?}");
1162
1191
assert!(lines.iter().any(|line| line.contains("original words")), "{lines:?}");
1163
1192
assert_eq!(reply_excerpt(&forwarded), "original words");
1164
1193
assert_eq!(message_text(&forwarded), "original words");
@@ -7,7 +7,8 @@ use gpui_kit::Image;7
use store::MessageRecord;7
use store::MessageRecord;8
use teams_core::{8
use teams_core::{9
JumboEmoji, jumbo_emoji,9
JumboEmoji, jumbo_emoji,10
AdaptiveCard, CallEvent, CallPhase, CallType, Draft, FileCard, ImageRef, LinkPreview,10
AdaptiveCard, CallEvent, CallPhase, CallType, Draft, FileCard, ForwardHeader, ForwardInfo,11
ImageRef, LinkPreview, forwards,11
ReactionInfo, Span, adaptive_cards, call_event, card_texts, files, format_duration,12
ReactionInfo, Span, adaptive_cards, call_event, card_texts, files, format_duration,12
forwarded_texts, images, is_forwarded, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans, quotes,13
forwarded_texts, images, is_forwarded, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans, quotes,13
reactions, readable_text, translated_spans,14
reactions, readable_text, translated_spans,@@ -688,6 +689,33 @@ pub fn quoted_texts(records: &[MessageRecord]) -> HashMap<String, String> {688
.collect()689
.collect()689
}690
}690
691
692
fn forward_header(forward: &ForwardInfo, context: &RowContext) -> ForwardHeader {693
ForwardHeader {694
sender: forward695
.sender_id696
.as_ref()697
.and_then(|user_id| context.names.get(user_id).cloned()),698
time: forward699
.sent_at700
.map(|time| format::post_time_label(time, context.today, context.offset)),701
}702
}703
704
/// User ids a row needs a name for beyond its author: original senders of forwards.705
pub fn forward_sender_ids(records: &[MessageRecord]) -> Vec<String> {706
let mut user_ids: Vec<String> = Vec::new();707
for user_id in records708
.iter()709
.flat_map(forwards)710
.filter_map(|forward| forward.sender_id)711
{712
if !user_ids.contains(&user_id) {713
user_ids.push(user_id);714
}715
}716
user_ids717
}718
691
pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {719
pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {692
message_row_with(record, context, &HashMap::new())720
message_row_with(record, context, &HashMap::new())693
}721
}@@ -704,15 +732,16 @@ fn message_row_with(704
let images = images(record);732
let images = images(record);705
let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;733
let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;706
let translation = context.translation.resolve(record, own);734
let translation = context.translation.resolve(record, own);735
let forward_header = |forward: &ForwardInfo| forward_header(forward, context);707
let blocks = if record.deleted {736
let blocks = if record.deleted {708
vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]737
vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]709
} else if let Some(html) = &translation.translated_html {738
} else if let Some(html) = &translation.translated_html {710
layout_blocks(&translated_spans(record, html))739
layout_blocks(&translated_spans(record, html, &forward_header))711
} else {740
} else {712
layout_blocks(&linked_message_spans_with(741
layout_blocks(&linked_message_spans_with(713
record,742
record,714
&|id| quoted.get(id).cloned(),743
&|id| quoted.get(id).cloned(),715
&|user_id| context.names.get(user_id).cloned(),744
&forward_header,716
))745
))717
};746
};718
let blocks = if images.is_empty() {747
let blocks = if images.is_empty() {@@ -1158,7 +1187,7 @@ mod tests {1158
panic!("expected one forward quote, got {:?}", row.blocks);1187
panic!("expected one forward quote, got {:?}", row.blocks);1159
};1188
};1160
let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect();1189
let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect();1161
assert!(lines[0].contains("Priya Nair"), "{lines:?}");1190
assert!(lines[0].contains("Priya Nair Yesterday 07:00"), "{lines:?}");1162
assert!(lines.iter().any(|line| line.contains("original words")), "{lines:?}");1191
assert!(lines.iter().any(|line| line.contains("original words")), "{lines:?}");1163
assert_eq!(reply_excerpt(&forwarded), "original words");1192
assert_eq!(reply_excerpt(&forwarded), "original words");1164
assert_eq!(message_text(&forwarded), "original words");1193
assert_eq!(message_text(&forwarded), "original words");@@ -64,6 +64,7 @@ use crate::read_state::{ReadTrigger, plan_read};
64
64
use crate::rows::{
65
65
Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,
66
66
apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,
67
forward_sender_ids,
67
68
has_own_reaction, message_draft, message_text, own_reaction_glyph, place_local_rows,
68
69
placeholder_rows,
69
70
reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,
@@ -1451,14 +1452,15 @@ impl ConversationView {
1451
1452
};
1452
1453
let sync_has_more = sync_state.as_ref().is_none_or(|state| state.has_more);
1453
1454
let mut context = self.row_context(cx);
1454
let reactor_ids: Vec<String> = records
1455
let unnamed_ids: Vec<String> = records
1455
1456
.iter()
1456
1457
.flat_map(teams_core::reactions)
1457
1458
.filter(|reaction| reaction.user_name.is_none())
1458
1459
.filter_map(|reaction| reaction.user_id)
1460
.chain(forward_sender_ids(&records))
1459
1461
.filter(|user_id| !context.names.contains_key(user_id))
1460
1462
.collect();
1461
for (user_id, name) in resolve_names(self.app.read(cx), &reactor_ids) {
1463
for (user_id, name) in resolve_names(self.app.read(cx), &unnamed_ids) {
1462
1464
context.names.entry(user_id).or_insert(name);
1463
1465
}
1464
1466
for record in &records {
@@ -64,6 +64,7 @@ use crate::read_state::{ReadTrigger, plan_read};64
use crate::rows::{64
use crate::rows::{65
Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,65
Delivery, MessageRow, PendingReactions, Receipt, Row, RowContext, StartInfo, api_reaction,66
apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,66
apply_pending_reactions, assign_series, changed_indices, diff_keys, flat_rows,67
forward_sender_ids,67
has_own_reaction, message_draft, message_text, own_reaction_glyph, place_local_rows,68
has_own_reaction, message_draft, message_text, own_reaction_glyph, place_local_rows,68
placeholder_rows,69
placeholder_rows,69
reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,70
reaction_glyph, reply_excerpt, set_own_reaction, thread_list_rows, thread_rows,@@ -1451,14 +1452,15 @@ impl ConversationView {1451
};1452
};1452
let sync_has_more = sync_state.as_ref().is_none_or(|state| state.has_more);1453
let sync_has_more = sync_state.as_ref().is_none_or(|state| state.has_more);1453
let mut context = self.row_context(cx);1454
let mut context = self.row_context(cx);1454
let reactor_ids: Vec<String> = records1455
let unnamed_ids: Vec<String> = records1455
.iter()1456
.iter()1456
.flat_map(teams_core::reactions)1457
.flat_map(teams_core::reactions)1457
.filter(|reaction| reaction.user_name.is_none())1458
.filter(|reaction| reaction.user_name.is_none())1458
.filter_map(|reaction| reaction.user_id)1459
.filter_map(|reaction| reaction.user_id)1460
.chain(forward_sender_ids(&records))1459
.filter(|user_id| !context.names.contains_key(user_id))1461
.filter(|user_id| !context.names.contains_key(user_id))1460
.collect();1462
.collect();1461
for (user_id, name) in resolve_names(self.app.read(cx), &reactor_ids) {1463
for (user_id, name) in resolve_names(self.app.read(cx), &unnamed_ids) {1462
context.names.entry(user_id).or_insert(name);1464
context.names.entry(user_id).or_insert(name);1463
}1465
}1464
for record in &records {1466
for record in &records {@@ -128,6 +128,7 @@ pub struct SyncEngine<R: Remote = Graph> {
128
128
pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,
129
129
pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,
130
130
pub(crate) links_backfilled: Mutex<HashSet<String>>,
131
pub(crate) forwards_healed: Mutex<HashSet<String>>,
131
132
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,
132
133
pub(crate) chat_paging: Mutex<ChatPaging>,
133
134
pub(crate) locally_hidden_lock: Mutex<()>,
@@ -162,6 +163,7 @@ impl<R: Remote> SyncEngine<R> {
162
163
chat_apps: Mutex::new(HashMap::new()),
163
164
link_previews: Mutex::new(HashMap::new()),
164
165
links_backfilled: Mutex::new(HashSet::new()),
166
forwards_healed: Mutex::new(HashSet::new()),
165
167
chat_states: Mutex::new(HashMap::new()),
166
168
chat_paging,
167
169
locally_hidden_lock: Mutex::new(()),
@@ -198,9 +200,10 @@ impl<R: Remote> SyncEngine<R> {
198
200
self.fetch_newer_channel(&team_id, conversation_id).await?
199
201
}
200
202
};
201
let links_changed = self.attach_delta_links(conversation_id, &mut delta).await
202
| self.backfill_links(conversation_id).await;
203
self.announce(conversation_id, !delta.is_empty() || links_changed);
203
let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await
204
| self.backfill_links(conversation_id).await
205
| self.heal_forwards(conversation_id).await;
206
self.announce(conversation_id, !delta.is_empty() || cache_changed);
204
207
Ok(delta)
205
208
}
206
209
@@ -128,6 +128,7 @@ pub struct SyncEngine<R: Remote = Graph> {128
pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,128
pub(crate) chat_apps: Mutex<HashMap<String, Vec<ChatApp>>>,129
pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,129
pub(crate) link_previews: Mutex<HashMap<String, Option<LinkPreview>>>,130
pub(crate) links_backfilled: Mutex<HashSet<String>>,130
pub(crate) links_backfilled: Mutex<HashSet<String>>,131
pub(crate) forwards_healed: Mutex<HashSet<String>>,131
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,132
pub(crate) chat_states: Mutex<HashMap<String, ConversationState>>,132
pub(crate) chat_paging: Mutex<ChatPaging>,133
pub(crate) chat_paging: Mutex<ChatPaging>,133
pub(crate) locally_hidden_lock: Mutex<()>,134
pub(crate) locally_hidden_lock: Mutex<()>,@@ -162,6 +163,7 @@ impl<R: Remote> SyncEngine<R> {162
chat_apps: Mutex::new(HashMap::new()),163
chat_apps: Mutex::new(HashMap::new()),163
link_previews: Mutex::new(HashMap::new()),164
link_previews: Mutex::new(HashMap::new()),164
links_backfilled: Mutex::new(HashSet::new()),165
links_backfilled: Mutex::new(HashSet::new()),166
forwards_healed: Mutex::new(HashSet::new()),165
chat_states: Mutex::new(HashMap::new()),167
chat_states: Mutex::new(HashMap::new()),166
chat_paging,168
chat_paging,167
locally_hidden_lock: Mutex::new(()),169
locally_hidden_lock: Mutex::new(()),@@ -198,9 +200,10 @@ impl<R: Remote> SyncEngine<R> {198
self.fetch_newer_channel(&team_id, conversation_id).await?200
self.fetch_newer_channel(&team_id, conversation_id).await?199
}201
}200
};202
};201
let links_changed = self.attach_delta_links(conversation_id, &mut delta).await203
let cache_changed = self.attach_delta_links(conversation_id, &mut delta).await202
| self.backfill_links(conversation_id).await;204
| self.backfill_links(conversation_id).await203
self.announce(conversation_id, !delta.is_empty() || links_changed);205
| self.heal_forwards(conversation_id).await;206
self.announce(conversation_id, !delta.is_empty() || cache_changed);204
Ok(delta)207
Ok(delta)205
}208
}206
209
@@ -0,0 +1,43 @@
1
use crate::engine::{Conversation, SyncEngine};
2
use crate::forwarded::{FORWARDED_CONTENT_TYPE, lacks_forward_content};
3
use crate::mapping::message_record;
4
use crate::remote::Remote;
5
6
impl<R: Remote> SyncEngine<R> {
7
/// Once per chat and session, for cached forwards stored before their original message was kept.
8
pub(crate) async fn heal_forwards(&self, conversation_id: &str) -> bool {
9
let first = self
10
.forwards_healed
11
.lock()
12
.unwrap_or_else(|poisoned| poisoned.into_inner())
13
.insert(conversation_id.to_owned());
14
if !first || !matches!(self.resolve_stored(conversation_id), Ok(Conversation::Chat)) {
15
return false;
16
}
17
let Ok(cached) = self
18
.store
19
.messages_with_attachment_type(conversation_id, FORWARDED_CONTENT_TYPE)
20
else {
21
return false;
22
};
23
let stale: Vec<String> = cached
24
.iter()
25
.filter(|record| lacks_forward_content(record))
26
.map(|record| record.message_id.clone())
27
.collect();
28
if stale.is_empty() {
29
return false;
30
}
31
let Ok(answers) = self.remote.chat_messages_by_id(conversation_id, &stale).await else {
32
return false;
33
};
34
let mut records: Vec<_> = answers
35
.iter()
36
.flatten()
37
.filter_map(|message| message_record(conversation_id, message))
38
.collect();
39
self.apply_chat_emotions(conversation_id, &mut records).await;
40
self.ingest(conversation_id, records)
41
.is_ok_and(|delta| !delta.is_empty())
42
}
43
}
@@ -0,0 +1,43 @@1
use crate::engine::{Conversation, SyncEngine};2
use crate::forwarded::{FORWARDED_CONTENT_TYPE, lacks_forward_content};3
use crate::mapping::message_record;4
use crate::remote::Remote;5
6
impl<R: Remote> SyncEngine<R> {7
/// Once per chat and session, for cached forwards stored before their original message was kept.8
pub(crate) async fn heal_forwards(&self, conversation_id: &str) -> bool {9
let first = self10
.forwards_healed11
.lock()12
.unwrap_or_else(|poisoned| poisoned.into_inner())13
.insert(conversation_id.to_owned());14
if !first || !matches!(self.resolve_stored(conversation_id), Ok(Conversation::Chat)) {15
return false;16
}17
let Ok(cached) = self18
.store19
.messages_with_attachment_type(conversation_id, FORWARDED_CONTENT_TYPE)20
else {21
return false;22
};23
let stale: Vec<String> = cached24
.iter()25
.filter(|record| lacks_forward_content(record))26
.map(|record| record.message_id.clone())27
.collect();28
if stale.is_empty() {29
return false;30
}31
let Ok(answers) = self.remote.chat_messages_by_id(conversation_id, &stale).await else {32
return false;33
};34
let mut records: Vec<_> = answers35
.iter()36
.flatten()37
.filter_map(|message| message_record(conversation_id, message))38
.collect();39
self.apply_chat_emotions(conversation_id, &mut records).await;40
self.ingest(conversation_id, records)41
.is_ok_and(|delta| !delta.is_empty())42
}43
}@@ -1,4 +1,7 @@
1
use std::sync::LazyLock;
2
1
3
use chrono::{DateTime, Utc};
4
use regex::Regex;
2
5
use serde::Deserialize;
3
6
use store::MessageRecord;
4
7
@@ -9,6 +12,9 @@ use crate::stored::{AttachmentInfo, attachments, push_plain};
9
12
pub const FORWARDED_CONTENT_TYPE: &str = "forwardedMessageReference";
10
13
pub(crate) const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";
11
14
15
static MENTION_ID: LazyLock<Regex> =
16
LazyLock::new(|| Regex::new(r"<at\b[^>]*>").expect("mention tag pattern"));
17
12
18
/// The original message carried by a Graph `forwardedMessageReference` attachment.
13
19
#[derive(Debug, Clone, PartialEq, Eq)]
14
20
pub struct ForwardInfo {
@@ -62,28 +68,35 @@ impl ForwardInfo {
62
68
text.trim().to_owned()
63
69
}
64
70
65
pub fn html(&self, sender_name: Option<&str>) -> String {
66
let sender = sender_name
71
pub fn html(&self, header: &ForwardHeader) -> String {
72
let sender = header
73
.sender
74
.as_deref()
67
75
.or(self.sender_name.as_deref())
68
76
.map(|name| format!("<strong>{}</strong>", escape_html(name)))
69
77
.unwrap_or_default();
70
let time = self
71
.sent_at
72
.map(|time| {
73
let local = time.with_timezone(&chrono::Local);
74
format!(" <span>{}</span>", local.format("%d/%m/%Y %H:%M"))
75
})
78
let time = header
79
.time
80
.as_deref()
81
.map(|time| format!(" <span>{}</span>", escape_html(time)))
76
82
.unwrap_or_default();
83
let content = MENTION_ID.replace_all(&self.content_html, "<at>");
77
84
format!(
78
"<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{}</blockquote>",
85
"<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{content}</blockquote>",
79
86
escape_html(&self.message_id),
80
self.content_html,
81
87
)
82
88
}
83
89
}
84
90
91
/// What the forward quote names above the original: sender display name and sent time label.
92
#[derive(Debug, Clone, Default, PartialEq, Eq)]
93
pub struct ForwardHeader {
94
pub sender: Option<String>,
95
pub time: Option<String>,
96
}
97
85
98
pub fn forwards(record: &MessageRecord) -> Vec<ForwardInfo> {
86
if record.deleted {
99
if record.deleted || !record.attachments_json.contains(FORWARDED_CONTENT_TYPE) {
87
100
return Vec::new();
88
101
}
89
102
attachments(record)
@@ -104,15 +117,22 @@ pub fn is_forwarded(record: &MessageRecord) -> bool {
104
117
!record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty())
105
118
}
106
119
120
/// A forward attachment cached before its content was kept.
121
pub(crate) fn lacks_forward_content(record: &MessageRecord) -> bool {
122
attachments(record).iter().any(|attachment| {
123
attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE)
124
&& attachment.content.is_none()
125
})
126
}
127
107
128
/// `html` with each forward's `<attachment id>` tag replaced by its forward blockquote; a forward without a tag goes last.
108
129
pub(crate) fn inline_forwards(
109
130
record: &MessageRecord,
110
131
mut html: String,
111
sender_name: &dyn Fn(&str) -> Option<String>,
132
header: &dyn Fn(&ForwardInfo) -> ForwardHeader,
112
133
) -> String {
113
134
for forward in forwards(record) {
114
let name = forward.sender_id.as_deref().and_then(sender_name);
115
let block = forward.html(name.as_deref());
135
let block = forward.html(&header(&forward));
116
136
let tag = forward
117
137
.attachment_id
118
138
.as_deref()
@@ -126,6 +146,10 @@ pub(crate) fn inline_forwards(
126
146
html
127
147
}
128
148
149
pub fn no_forward_header(_: &ForwardInfo) -> ForwardHeader {
150
ForwardHeader::default()
151
}
152
129
153
#[cfg(test)]
130
154
mod tests {
131
155
use super::*;
@@ -174,14 +198,16 @@ mod tests {
174
198
#[test]
175
199
fn the_forward_replaces_its_attachment_tag_with_a_quote_naming_the_original_sender() {
176
200
let record = forwarded_record();
177
let spans = linked_message_spans_with(&record, &|_| None, &|user_id| {
178
(user_id == ORIGINAL_SENDER_ID).then(|| "Ada Original".to_owned())
201
let spans = linked_message_spans_with(&record, &|_| None, &|forward| ForwardHeader {
202
sender: (forward.sender_id.as_deref() == Some(ORIGINAL_SENDER_ID))
203
.then(|| "Ada Original".to_owned()),
204
time: Some("13:11".to_owned()),
179
205
});
180
206
let [Span::BlockQuote(children)] = spans.as_slice() else {
181
207
panic!("expected one forward blockquote, got {spans:?}");
182
208
};
183
209
let text = plain(children);
184
assert!(text.starts_with("Ada Original"), "{text}");
210
assert!(text.starts_with("Ada Original 13:11"), "{text}");
185
211
assert!(text.contains(ORIGINAL_TEXT), "{text}");
186
212
}
187
213
@@ -203,6 +229,52 @@ mod tests {
203
229
);
204
230
}
205
231
232
#[test]
233
fn a_mention_inside_the_forward_does_not_borrow_the_forwarders_mention() {
234
let mut record = forwarded_record();
235
record.body_html = format!(
236
r#"<p><at id="0">Bob Sample</at></p>{}"#,
237
record.body_html
238
);
239
record.attachments_json = record
240
.attachments_json
241
.replace("<p>Keep", r#"<p><at id=\\\"0\\\">Cleo Other</at> Keep"#);
242
record.mentions_json =
243
r#"[{"user_id":"user-bob","name":"Bob Sample","id":0}]"#.to_owned();
244
assert!(forwards(&record)[0].content_html.contains("Cleo Other"));
245
let spans = linked_message_spans_with(&record, &|_| None, &no_forward_header);
246
let mut mentions = Vec::new();
247
collect_mentions(&spans, &mut mentions);
248
assert_eq!(
249
mentions,
250
[
251
("Bob Sample".to_owned(), Some("teams-profile:user-bob".to_owned())),
252
("Cleo Other".to_owned(), None),
253
]
254
);
255
}
256
257
fn collect_mentions(spans: &[Span], found: &mut Vec<(String, Option<String>)>) {
258
for span in spans {
259
match span {
260
Span::Mention { name, id } => found.push((name.clone(), id.clone())),
261
Span::BlockQuote(children) | Span::Bold(children) => {
262
collect_mentions(children, found);
263
}
264
_ => {}
265
}
266
}
267
}
268
269
#[test]
270
fn a_forward_cached_without_its_content_needs_a_refetch() {
271
let mut record = forwarded_record();
272
assert!(!lacks_forward_content(&record));
273
record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();
274
assert!(lacks_forward_content(&record));
275
assert!(forwards(&record).is_empty());
276
}
277
206
278
#[test]
207
279
fn a_deleted_forward_is_not_forwarded() {
208
280
let mut record = forwarded_record();
@@ -1,4 +1,7 @@1
use std::sync::LazyLock;2
1
use chrono::{DateTime, Utc};3
use chrono::{DateTime, Utc};4
use regex::Regex;2
use serde::Deserialize;5
use serde::Deserialize;3
use store::MessageRecord;6
use store::MessageRecord;4
7
@@ -9,6 +12,9 @@ use crate::stored::{AttachmentInfo, attachments, push_plain};9
pub const FORWARDED_CONTENT_TYPE: &str = "forwardedMessageReference";12
pub const FORWARDED_CONTENT_TYPE: &str = "forwardedMessageReference";10
pub(crate) const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";13
pub(crate) const FORWARD_ITEMTYPE: &str = "schema.skype.com/Forward";11
14
15
static MENTION_ID: LazyLock<Regex> =16
LazyLock::new(|| Regex::new(r"<at\b[^>]*>").expect("mention tag pattern"));17
12
/// The original message carried by a Graph `forwardedMessageReference` attachment.18
/// The original message carried by a Graph `forwardedMessageReference` attachment.13
#[derive(Debug, Clone, PartialEq, Eq)]19
#[derive(Debug, Clone, PartialEq, Eq)]14
pub struct ForwardInfo {20
pub struct ForwardInfo {@@ -62,28 +68,35 @@ impl ForwardInfo {62
text.trim().to_owned()68
text.trim().to_owned()63
}69
}64
70
65
pub fn html(&self, sender_name: Option<&str>) -> String {71
pub fn html(&self, header: &ForwardHeader) -> String {66
let sender = sender_name72
let sender = header73
.sender74
.as_deref()67
.or(self.sender_name.as_deref())75
.or(self.sender_name.as_deref())68
.map(|name| format!("<strong>{}</strong>", escape_html(name)))76
.map(|name| format!("<strong>{}</strong>", escape_html(name)))69
.unwrap_or_default();77
.unwrap_or_default();70
let time = self78
let time = header71
.sent_at79
.time72
.map(|time| {80
.as_deref()73
let local = time.with_timezone(&chrono::Local);81
.map(|time| format!(" <span>{}</span>", escape_html(time)))74
format!(" <span>{}</span>", local.format("%d/%m/%Y %H:%M"))75
})76
.unwrap_or_default();82
.unwrap_or_default();83
let content = MENTION_ID.replace_all(&self.content_html, "<at>");77
format!(84
format!(78
"<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{}</blockquote>",85
"<blockquote itemscope=\"\" itemtype=\"http://{FORWARD_ITEMTYPE}\" itemid=\"{}\">{sender}{time}{content}</blockquote>",79
escape_html(&self.message_id),86
escape_html(&self.message_id),80
self.content_html,81
)87
)82
}88
}83
}89
}84
90
91
/// What the forward quote names above the original: sender display name and sent time label.92
#[derive(Debug, Clone, Default, PartialEq, Eq)]93
pub struct ForwardHeader {94
pub sender: Option<String>,95
pub time: Option<String>,96
}97
85
pub fn forwards(record: &MessageRecord) -> Vec<ForwardInfo> {98
pub fn forwards(record: &MessageRecord) -> Vec<ForwardInfo> {86
if record.deleted {99
if record.deleted || !record.attachments_json.contains(FORWARDED_CONTENT_TYPE) {87
return Vec::new();100
return Vec::new();88
}101
}89
attachments(record)102
attachments(record)@@ -104,15 +117,22 @@ pub fn is_forwarded(record: &MessageRecord) -> bool {104
!record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty())117
!record.deleted && (record.body_html.contains(FORWARD_ITEMTYPE) || !forwards(record).is_empty())105
}118
}106
119
120
/// A forward attachment cached before its content was kept.121
pub(crate) fn lacks_forward_content(record: &MessageRecord) -> bool {122
attachments(record).iter().any(|attachment| {123
attachment.content_type.as_deref() == Some(FORWARDED_CONTENT_TYPE)124
&& attachment.content.is_none()125
})126
}127
107
/// `html` with each forward's `<attachment id>` tag replaced by its forward blockquote; a forward without a tag goes last.128
/// `html` with each forward's `<attachment id>` tag replaced by its forward blockquote; a forward without a tag goes last.108
pub(crate) fn inline_forwards(129
pub(crate) fn inline_forwards(109
record: &MessageRecord,130
record: &MessageRecord,110
mut html: String,131
mut html: String,111
sender_name: &dyn Fn(&str) -> Option<String>,132
header: &dyn Fn(&ForwardInfo) -> ForwardHeader,112
) -> String {133
) -> String {113
for forward in forwards(record) {134
for forward in forwards(record) {114
let name = forward.sender_id.as_deref().and_then(sender_name);135
let block = forward.html(&header(&forward));115
let block = forward.html(name.as_deref());116
let tag = forward136
let tag = forward117
.attachment_id137
.attachment_id118
.as_deref()138
.as_deref()@@ -126,6 +146,10 @@ pub(crate) fn inline_forwards(126
html146
html127
}147
}128
148
149
pub fn no_forward_header(_: &ForwardInfo) -> ForwardHeader {150
ForwardHeader::default()151
}152
129
#[cfg(test)]153
#[cfg(test)]130
mod tests {154
mod tests {131
use super::*;155
use super::*;@@ -174,14 +198,16 @@ mod tests {174
#[test]198
#[test]175
fn the_forward_replaces_its_attachment_tag_with_a_quote_naming_the_original_sender() {199
fn the_forward_replaces_its_attachment_tag_with_a_quote_naming_the_original_sender() {176
let record = forwarded_record();200
let record = forwarded_record();177
let spans = linked_message_spans_with(&record, &|_| None, &|user_id| {201
let spans = linked_message_spans_with(&record, &|_| None, &|forward| ForwardHeader {178
(user_id == ORIGINAL_SENDER_ID).then(|| "Ada Original".to_owned())202
sender: (forward.sender_id.as_deref() == Some(ORIGINAL_SENDER_ID))203
.then(|| "Ada Original".to_owned()),204
time: Some("13:11".to_owned()),179
});205
});180
let [Span::BlockQuote(children)] = spans.as_slice() else {206
let [Span::BlockQuote(children)] = spans.as_slice() else {181
panic!("expected one forward blockquote, got {spans:?}");207
panic!("expected one forward blockquote, got {spans:?}");182
};208
};183
let text = plain(children);209
let text = plain(children);184
assert!(text.starts_with("Ada Original"), "{text}");210
assert!(text.starts_with("Ada Original 13:11"), "{text}");185
assert!(text.contains(ORIGINAL_TEXT), "{text}");211
assert!(text.contains(ORIGINAL_TEXT), "{text}");186
}212
}187
213
@@ -203,6 +229,52 @@ mod tests {203
);229
);204
}230
}205
231
232
#[test]233
fn a_mention_inside_the_forward_does_not_borrow_the_forwarders_mention() {234
let mut record = forwarded_record();235
record.body_html = format!(236
r#"<p><at id="0">Bob Sample</at></p>{}"#,237
record.body_html238
);239
record.attachments_json = record240
.attachments_json241
.replace("<p>Keep", r#"<p><at id=\\\"0\\\">Cleo Other</at> Keep"#);242
record.mentions_json =243
r#"[{"user_id":"user-bob","name":"Bob Sample","id":0}]"#.to_owned();244
assert!(forwards(&record)[0].content_html.contains("Cleo Other"));245
let spans = linked_message_spans_with(&record, &|_| None, &no_forward_header);246
let mut mentions = Vec::new();247
collect_mentions(&spans, &mut mentions);248
assert_eq!(249
mentions,250
[251
("Bob Sample".to_owned(), Some("teams-profile:user-bob".to_owned())),252
("Cleo Other".to_owned(), None),253
]254
);255
}256
257
fn collect_mentions(spans: &[Span], found: &mut Vec<(String, Option<String>)>) {258
for span in spans {259
match span {260
Span::Mention { name, id } => found.push((name.clone(), id.clone())),261
Span::BlockQuote(children) | Span::Bold(children) => {262
collect_mentions(children, found);263
}264
_ => {}265
}266
}267
}268
269
#[test]270
fn a_forward_cached_without_its_content_needs_a_refetch() {271
let mut record = forwarded_record();272
assert!(!lacks_forward_content(&record));273
record.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"1792149081221","content":null}]"#.to_owned();274
assert!(lacks_forward_content(&record));275
assert!(forwards(&record).is_empty());276
}277
206
#[test]278
#[test]207
fn a_deleted_forward_is_not_forwarded() {279
fn a_deleted_forward_is_not_forwarded() {208
let mut record = forwarded_record();280
let mut record = forwarded_record();@@ -21,6 +21,7 @@ mod error;
21
21
mod events;
22
22
mod external_image;
23
23
mod folders;
24
mod forward_sync;
24
25
mod forwarded;
25
26
mod gifs;
26
27
mod hidden_chats;
@@ -140,7 +141,7 @@ pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};
140
141
pub use scheduled::NOTES_CHAT_ID;
141
142
pub use skin_tone::{skin_tone, store_account_skin_tone};
142
143
pub use forwarded::{
143
FORWARDED_CONTENT_TYPE, ForwardInfo, forwarded_texts, forwards, is_forwarded,
144
FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,
144
145
};
145
146
pub use spans::{FontSize, Span, html_to_spans};
146
147
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};
@@ -21,6 +21,7 @@ mod error;21
mod events;21
mod events;22
mod external_image;22
mod external_image;23
mod folders;23
mod folders;24
mod forward_sync;24
mod forwarded;25
mod forwarded;25
mod gifs;26
mod gifs;26
mod hidden_chats;27
mod hidden_chats;@@ -140,7 +141,7 @@ pub use remote::{ChatsPage, DeltaPage, Remote, RemotePage};140
pub use scheduled::NOTES_CHAT_ID;141
pub use scheduled::NOTES_CHAT_ID;141
pub use skin_tone::{skin_tone, store_account_skin_tone};142
pub use skin_tone::{skin_tone, store_account_skin_tone};142
pub use forwarded::{143
pub use forwarded::{143
FORWARDED_CONTENT_TYPE, ForwardInfo, forwarded_texts, forwards, is_forwarded,144
FORWARDED_CONTENT_TYPE, ForwardHeader, ForwardInfo, forwarded_texts, forwards, is_forwarded,144
};145
};145
pub use spans::{FontSize, Span, html_to_spans};146
pub use spans::{FontSize, Span, html_to_spans};146
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};147
pub use store::{ConversationHit, HIGHLIGHT_END, HIGHLIGHT_START, SearchHit};@@ -5,7 +5,7 @@ use store::MessageRecord;
5
5
6
6
use crate::adaptive_card::{AdaptiveCard, card_content_text};
7
7
use crate::external_image::{external_image_url, is_giphy_url};
8
use crate::forwarded::{forwarded_texts, inline_forwards};
8
use crate::forwarded::{ForwardHeader, ForwardInfo, forwarded_texts, inline_forwards, no_forward_header};
9
9
use crate::markdown::escape_html;
10
10
use crate::mentions::MentionInput;
11
11
use crate::spans::{Span, html_to_spans};
@@ -239,7 +239,7 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {
239
239
if record.deleted {
240
240
return Vec::new();
241
241
}
242
let fragment = Html::parse_fragment(&inline_forwards(record, record.body_html.clone(), &|_| None));
242
let fragment = Html::parse_fragment(&inline_forwards(record, record.body_html.clone(), &no_forward_header));
243
243
let mut found: Vec<ImageRef> = Vec::new();
244
244
for element in fragment
245
245
.root_element()
@@ -559,17 +559,17 @@ pub const PROFILE_LINK_PREFIX: &str = "teams-profile:";
559
559
560
560
/// Like `message_spans`, with the id of each user mention replaced by a profile link.
561
561
pub fn linked_message_spans(record: &MessageRecord) -> Vec<Span> {
562
linked_message_spans_with(record, &|_| None, &|_| None)
562
linked_message_spans_with(record, &|_| None, &no_forward_header)
563
563
}
564
564
565
/// Like `linked_message_spans`, but a quote shows `quoted_text(message_id)` when known instead of the one-line server preview, and a forward names its original sender by `sender_name(user_id)`.
565
/// Like `linked_message_spans`, but a quote shows `quoted_text(message_id)` when known instead of the one-line server preview, and a forward shows `forward_header(forward)` above the original.
566
566
pub fn linked_message_spans_with(
567
567
record: &MessageRecord,
568
568
quoted_text: &dyn Fn(&str) -> Option<String>,
569
sender_name: &dyn Fn(&str) -> Option<String>,
569
forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader,
570
570
) -> Vec<Span> {
571
571
let infos = mentions(record);
572
let html = inline_forwards(record, with_inline_quotes(record, quoted_text), sender_name);
572
let html = inline_forwards(record, with_inline_quotes(record, quoted_text), forward_header);
573
573
let mut spans = html_to_spans(&html);
574
574
merge_split_mentions(&mut spans, &infos);
575
575
link_user_mentions(&mut spans, &infos);
@@ -577,10 +577,14 @@ pub fn linked_message_spans_with(
577
577
}
578
578
579
579
/// The spans of `record` with its body replaced by the translated html.
580
pub fn translated_spans(record: &MessageRecord, translated_html: &str) -> Vec<Span> {
580
pub fn translated_spans(
581
record: &MessageRecord,
582
translated_html: &str,
583
forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader,
584
) -> Vec<Span> {
581
585
let mut translated = record.clone();
582
586
translated.body_html = translated_html.to_owned();
583
linked_message_spans(&translated)
587
linked_message_spans_with(&translated, &|_| None, forward_header)
584
588
}
585
589
586
590
fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {
@@ -5,7 +5,7 @@ use store::MessageRecord;5
5
6
use crate::adaptive_card::{AdaptiveCard, card_content_text};6
use crate::adaptive_card::{AdaptiveCard, card_content_text};7
use crate::external_image::{external_image_url, is_giphy_url};7
use crate::external_image::{external_image_url, is_giphy_url};8
use crate::forwarded::{forwarded_texts, inline_forwards};8
use crate::forwarded::{ForwardHeader, ForwardInfo, forwarded_texts, inline_forwards, no_forward_header};9
use crate::markdown::escape_html;9
use crate::markdown::escape_html;10
use crate::mentions::MentionInput;10
use crate::mentions::MentionInput;11
use crate::spans::{Span, html_to_spans};11
use crate::spans::{Span, html_to_spans};@@ -239,7 +239,7 @@ pub fn images(record: &MessageRecord) -> Vec<ImageRef> {239
if record.deleted {239
if record.deleted {240
return Vec::new();240
return Vec::new();241
}241
}242
let fragment = Html::parse_fragment(&inline_forwards(record, record.body_html.clone(), &|_| None));242
let fragment = Html::parse_fragment(&inline_forwards(record, record.body_html.clone(), &no_forward_header));243
let mut found: Vec<ImageRef> = Vec::new();243
let mut found: Vec<ImageRef> = Vec::new();244
for element in fragment244
for element in fragment245
.root_element()245
.root_element()@@ -559,17 +559,17 @@ pub const PROFILE_LINK_PREFIX: &str = "teams-profile:";559
559
560
/// Like `message_spans`, with the id of each user mention replaced by a profile link.560
/// Like `message_spans`, with the id of each user mention replaced by a profile link.561
pub fn linked_message_spans(record: &MessageRecord) -> Vec<Span> {561
pub fn linked_message_spans(record: &MessageRecord) -> Vec<Span> {562
linked_message_spans_with(record, &|_| None, &|_| None)562
linked_message_spans_with(record, &|_| None, &no_forward_header)563
}563
}564
564
565
/// Like `linked_message_spans`, but a quote shows `quoted_text(message_id)` when known instead of the one-line server preview, and a forward names its original sender by `sender_name(user_id)`.565
/// Like `linked_message_spans`, but a quote shows `quoted_text(message_id)` when known instead of the one-line server preview, and a forward shows `forward_header(forward)` above the original.566
pub fn linked_message_spans_with(566
pub fn linked_message_spans_with(567
record: &MessageRecord,567
record: &MessageRecord,568
quoted_text: &dyn Fn(&str) -> Option<String>,568
quoted_text: &dyn Fn(&str) -> Option<String>,569
sender_name: &dyn Fn(&str) -> Option<String>,569
forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader,570
) -> Vec<Span> {570
) -> Vec<Span> {571
let infos = mentions(record);571
let infos = mentions(record);572
let html = inline_forwards(record, with_inline_quotes(record, quoted_text), sender_name);572
let html = inline_forwards(record, with_inline_quotes(record, quoted_text), forward_header);573
let mut spans = html_to_spans(&html);573
let mut spans = html_to_spans(&html);574
merge_split_mentions(&mut spans, &infos);574
merge_split_mentions(&mut spans, &infos);575
link_user_mentions(&mut spans, &infos);575
link_user_mentions(&mut spans, &infos);@@ -577,10 +577,14 @@ pub fn linked_message_spans_with(577
}577
}578
578
579
/// The spans of `record` with its body replaced by the translated html.579
/// The spans of `record` with its body replaced by the translated html.580
pub fn translated_spans(record: &MessageRecord, translated_html: &str) -> Vec<Span> {580
pub fn translated_spans(581
record: &MessageRecord,582
translated_html: &str,583
forward_header: &dyn Fn(&ForwardInfo) -> ForwardHeader,584
) -> Vec<Span> {581
let mut translated = record.clone();585
let mut translated = record.clone();582
translated.body_html = translated_html.to_owned();586
translated.body_html = translated_html.to_owned();583
linked_message_spans(&translated)587
linked_message_spans_with(&translated, &|_| None, forward_header)584
}588
}585
589
586
fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {590
fn link_user_mentions(spans: &mut [Span], infos: &[MentionInfo]) {@@ -4483,3 +4483,59 @@ async fn fetch_chat_message_does_not_store_the_message() {
4483
4483
assert_eq!(record.message_id, "m0007");
4484
4484
assert_eq!(engine.store().message_count(CHAT).unwrap(), 0);
4485
4485
}
4486
4487
fn forwarded_message(id: &str, minute: i64) -> Message {
4488
let content = json!({
4489
"originalMessageId": "orig-1",
4490
"originalMessageContent": "<p>original words</p>",
4491
"originalConversationId": "19:origin@thread.v2",
4492
"originalSentDateTime": base().to_rfc3339(),
4493
"originalMessageSender": {"user": {"id": "user-cleo", "displayName": null}},
4494
});
4495
serde_json::from_value(json!({
4496
"id": id,
4497
"messageType": "message",
4498
"createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(),
4499
"from": {"user": {"id": ME, "displayName": null}},
4500
"body": {"contentType": "html", "content": "<attachment id=\"orig-1\"></attachment>"},
4501
"attachments": [{
4502
"id": "orig-1",
4503
"contentType": "forwardedMessageReference",
4504
"content": content.to_string(),
4505
}],
4506
}))
4507
.unwrap()
4508
}
4509
4510
#[tokio::test]
4511
async fn a_forward_cached_without_its_content_is_read_again_once() {
4512
let fake = Arc::new(Fake::default());
4513
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];
4514
let store = Arc::new(Store::open_in_memory().unwrap());
4515
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());
4516
engine.refresh_sidebar().await.unwrap();
4517
let mut messages = numbered(11);
4518
messages.push(forwarded_message("m0000", 0));
4519
fake.set_chat_messages(messages);
4520
let mut stale = teams_core::message_record(CHAT, &forwarded_message("m0000", 0)).unwrap();
4521
stale.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"orig-1","content":null}]"#.to_owned();
4522
store.upsert_messages(&[stale]).unwrap();
4523
4524
engine.fetch_newer(CHAT).await.unwrap();
4525
4526
let healed = store
4527
.messages_by_id(CHAT, &["m0000".to_owned()])
4528
.unwrap()
4529
.remove("m0000")
4530
.unwrap();
4531
assert_eq!(teams_core::forwarded_texts(&healed), ["original words"]);
4532
let reads = |fake: &Fake| {
4533
fake.calls()
4534
.iter()
4535
.filter(|call| *call == "chat_message m0000")
4536
.count()
4537
};
4538
assert_eq!(reads(&fake), 1);
4539
engine.fetch_newer(CHAT).await.unwrap();
4540
assert_eq!(reads(&fake), 1);
4541
}
@@ -4483,3 +4483,59 @@ async fn fetch_chat_message_does_not_store_the_message() {4483
assert_eq!(record.message_id, "m0007");4483
assert_eq!(record.message_id, "m0007");4484
assert_eq!(engine.store().message_count(CHAT).unwrap(), 0);4484
assert_eq!(engine.store().message_count(CHAT).unwrap(), 0);4485
}4485
}4486
4487
fn forwarded_message(id: &str, minute: i64) -> Message {4488
let content = json!({4489
"originalMessageId": "orig-1",4490
"originalMessageContent": "<p>original words</p>",4491
"originalConversationId": "19:origin@thread.v2",4492
"originalSentDateTime": base().to_rfc3339(),4493
"originalMessageSender": {"user": {"id": "user-cleo", "displayName": null}},4494
});4495
serde_json::from_value(json!({4496
"id": id,4497
"messageType": "message",4498
"createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(),4499
"from": {"user": {"id": ME, "displayName": null}},4500
"body": {"contentType": "html", "content": "<attachment id=\"orig-1\"></attachment>"},4501
"attachments": [{4502
"id": "orig-1",4503
"contentType": "forwardedMessageReference",4504
"content": content.to_string(),4505
}],4506
}))4507
.unwrap()4508
}4509
4510
#[tokio::test]4511
async fn a_forward_cached_without_its_content_is_read_again_once() {4512
let fake = Arc::new(Fake::default());4513
*fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)];4514
let store = Arc::new(Store::open_in_memory().unwrap());4515
let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages());4516
engine.refresh_sidebar().await.unwrap();4517
let mut messages = numbered(11);4518
messages.push(forwarded_message("m0000", 0));4519
fake.set_chat_messages(messages);4520
let mut stale = teams_core::message_record(CHAT, &forwarded_message("m0000", 0)).unwrap();4521
stale.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"orig-1","content":null}]"#.to_owned();4522
store.upsert_messages(&[stale]).unwrap();4523
4524
engine.fetch_newer(CHAT).await.unwrap();4525
4526
let healed = store4527
.messages_by_id(CHAT, &["m0000".to_owned()])4528
.unwrap()4529
.remove("m0000")4530
.unwrap();4531
assert_eq!(teams_core::forwarded_texts(&healed), ["original words"]);4532
let reads = |fake: &Fake| {4533
fake.calls()4534
.iter()4535
.filter(|call| *call == "chat_message m0000")4536
.count()4537
};4538
assert_eq!(reads(&fake), 1);4539
engine.fetch_newer(CHAT).await.unwrap();4540
assert_eq!(reads(&fake), 1);4541
}@@ -252,6 +252,23 @@ impl Store {
252
252
Ok(messages)
253
253
}
254
254
255
pub fn messages_with_attachment_type(
256
&self,
257
conversation_id: &str,
258
content_type: &str,
259
) -> Result<Vec<MessageRecord>> {
260
let connection = self.lock()?;
261
let mut statement = connection.prepare_cached(&format!(
262
"SELECT {MESSAGE_COLUMNS} FROM messages
263
WHERE conversation_id = ?1 AND instr(attachments_json, ?2) > 0"
264
))?;
265
let needle = format!("\"content_type\":\"{content_type}\"");
266
let messages = statement
267
.query_map(params![conversation_id, needle], message_from_row)?
268
.collect::<rusqlite::Result<Vec<_>>>()?;
269
Ok(messages)
270
}
271
255
272
pub fn messages_by_id(
256
273
&self,
257
274
conversation_id: &str,
@@ -252,6 +252,23 @@ impl Store {252
Ok(messages)252
Ok(messages)253
}253
}254
254
255
pub fn messages_with_attachment_type(256
&self,257
conversation_id: &str,258
content_type: &str,259
) -> Result<Vec<MessageRecord>> {260
let connection = self.lock()?;261
let mut statement = connection.prepare_cached(&format!(262
"SELECT {MESSAGE_COLUMNS} FROM messages263
WHERE conversation_id = ?1 AND instr(attachments_json, ?2) > 0"264
))?;265
let needle = format!("\"content_type\":\"{content_type}\"");266
let messages = statement267
.query_map(params![conversation_id, needle], message_from_row)?268
.collect::<rusqlite::Result<Vec<_>>>()?;269
Ok(messages)270
}271
255
pub fn messages_by_id(272
pub fn messages_by_id(256
&self,273
&self,257
conversation_id: &str,274
conversation_id: &str,@@ -89,10 +89,6 @@ const MIGRATIONS: &[Migration] = &[
89
89
script: include_str!("migrations/0020_call_events.sql"),
90
90
after: None,
91
91
},
92
Migration {
93
script: include_str!("migrations/0021_forwarded_content.sql"),
94
after: None,
95
},
96
92
];
97
93
98
94
pub fn latest_version() -> i64 {
@@ -89,10 +89,6 @@ const MIGRATIONS: &[Migration] = &[89
script: include_str!("migrations/0020_call_events.sql"),89
script: include_str!("migrations/0020_call_events.sql"),90
after: None,90
after: None,91
},91
},92
Migration {93
script: include_str!("migrations/0021_forwarded_content.sql"),94
after: None,95
},96
];92
];97
93
98
pub fn latest_version() -> i64 {94
pub fn latest_version() -> i64 {@@ -1,4 +0,0 @@
1
DELETE FROM sync_state WHERE conversation_id IN (
2
SELECT DISTINCT conversation_id FROM messages
3
WHERE attachments_json LIKE '%"forwardedMessageReference"%'
4
);
@@ -1,4 +0,0 @@1
DELETE FROM sync_state WHERE conversation_id IN (2
SELECT DISTINCT conversation_id FROM messages3
WHERE attachments_json LIKE '%"forwardedMessageReference"%'4
);@@ -471,11 +471,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {
471
471
let path = directory.path().join("nested").join("cache.sqlite3");
472
472
{
473
473
let store = Store::open(&path).unwrap();
474
assert_eq!(store.schema_version().unwrap(), 21);
474
assert_eq!(store.schema_version().unwrap(), 20);
475
475
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
476
476
}
477
477
let reopened = Store::open(&path).unwrap();
478
assert_eq!(reopened.schema_version().unwrap(), 21);
478
assert_eq!(reopened.schema_version().unwrap(), 20);
479
479
assert_eq!(reopened.message_count("c").unwrap(), 1);
480
480
drop(reopened);
481
481
let mode: String = rusqlite_open(&path)
@@ -507,7 +507,7 @@ fn old_schema_is_upgraded_in_place() {
507
507
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 channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();
508
508
drop(connection);
509
509
let store = Store::open(&path).unwrap();
510
assert_eq!(store.schema_version().unwrap(), 21);
510
assert_eq!(store.schema_version().unwrap(), 20);
511
511
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();
512
512
}
513
513
@@ -573,7 +573,7 @@ fn migration_to_v2_keeps_existing_sync_state() {
573
573
let store = Store::open(&path).unwrap();
574
574
let state = store.sync_state("c").unwrap().unwrap();
575
575
assert_eq!(state.delta_link, None);
576
assert_eq!(store.schema_version().unwrap(), 21);
576
assert_eq!(store.schema_version().unwrap(), 20);
577
577
}
578
578
579
579
#[test]
@@ -1336,7 +1336,7 @@ fn migration_to_v20_adds_the_call_event_column() {
1336
1336
.unwrap();
1337
1337
}
1338
1338
let store = Store::open(&path).unwrap();
1339
assert_eq!(store.schema_version().unwrap(), 21);
1339
assert_eq!(store.schema_version().unwrap(), 20);
1340
1340
let old = store.messages("c", None, 10).unwrap();
1341
1341
assert_eq!(old[0].call_event_json, None);
1342
1342
assert!(store.sync_state("c").unwrap().is_none());
@@ -471,11 +471,11 @@ fn file_database_uses_wal_persists_and_migrates_once() {471
let path = directory.path().join("nested").join("cache.sqlite3");471
let path = directory.path().join("nested").join("cache.sqlite3");472
{472
{473
let store = Store::open(&path).unwrap();473
let store = Store::open(&path).unwrap();474
assert_eq!(store.schema_version().unwrap(), 21);474
assert_eq!(store.schema_version().unwrap(), 20);475
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();475
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();476
}476
}477
let reopened = Store::open(&path).unwrap();477
let reopened = Store::open(&path).unwrap();478
assert_eq!(reopened.schema_version().unwrap(), 21);478
assert_eq!(reopened.schema_version().unwrap(), 20);479
assert_eq!(reopened.message_count("c").unwrap(), 1);479
assert_eq!(reopened.message_count("c").unwrap(), 1);480
drop(reopened);480
drop(reopened);481
let mode: String = rusqlite_open(&path)481
let mode: String = rusqlite_open(&path)@@ -507,7 +507,7 @@ fn old_schema_is_upgraded_in_place() {507
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 channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();507
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 channel_tabs; DROP TABLE presence; DROP TABLE activity; DROP TABLE outbox; DROP TABLE drafts; DROP TABLE attachment_images; DROP TABLE agent_reaction_proposals; DROP TABLE agent_proposals; PRAGMA user_version = 0").unwrap();508
drop(connection);508
drop(connection);509
let store = Store::open(&path).unwrap();509
let store = Store::open(&path).unwrap();510
assert_eq!(store.schema_version().unwrap(), 21);510
assert_eq!(store.schema_version().unwrap(), 20);511
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();511
store.upsert_messages(&[message("c", "m1", 1)]).unwrap();512
}512
}513
513
@@ -573,7 +573,7 @@ fn migration_to_v2_keeps_existing_sync_state() {573
let store = Store::open(&path).unwrap();573
let store = Store::open(&path).unwrap();574
let state = store.sync_state("c").unwrap().unwrap();574
let state = store.sync_state("c").unwrap().unwrap();575
assert_eq!(state.delta_link, None);575
assert_eq!(state.delta_link, None);576
assert_eq!(store.schema_version().unwrap(), 21);576
assert_eq!(store.schema_version().unwrap(), 20);577
}577
}578
578
579
#[test]579
#[test]@@ -1336,7 +1336,7 @@ fn migration_to_v20_adds_the_call_event_column() {1336
.unwrap();1336
.unwrap();1337
}1337
}1338
let store = Store::open(&path).unwrap();1338
let store = Store::open(&path).unwrap();1339
assert_eq!(store.schema_version().unwrap(), 21);1339
assert_eq!(store.schema_version().unwrap(), 20);1340
let old = store.messages("c", None, 10).unwrap();1340
let old = store.messages("c", None, 10).unwrap();1341
assert_eq!(old[0].call_event_json, None);1341
assert_eq!(old[0].call_event_json, None);1342
assert!(store.sync_state("c").unwrap().is_none());1342
assert!(store.sync_state("c").unwrap().is_none());