BlueGit

ict rusty-teams

Files

rusty-teams / crates / app-state / src / rows.rs

rows.rs

rows.rs 77.7 KiB Download Raw
1use std::collections::{BTreeMap, HashMap};
2use std::ops::Range;
3use std::sync::Arc;
4
5use chrono::{DateTime, Duration, FixedOffset, NaiveDate, Utc};
6use gpui_kit::Image;
7use store::{MessageImportance, MessageRecord};
8use teams_core::roster_event::{RosterEvent, roster_event};
9use teams_core::{
10 AnnouncementBanner, attachments,
11 JumboEmoji, jumbo_emoji,
12 AdaptiveCard, CallEvent, CallPhase, Draft, FileCard, ForwardHeader, ForwardInfo,
13 ImageRef, LinkPreview, forwards,
14 ReactionInfo, Span, adaptive_cards, call_event, card_texts, files,
15 forwarded_texts, images, is_forwarded, link_preview, linked_message_spans_with, meeting_link_in_html, message_spans, quotes,
16 reactions, readable_text, translated_spans,
17};
18
19pub use crate::call_rows::{
20 CallCard, CallIcon, CallNotice, CallParticipant, MeetingInfo, MeetingSlot, RecapCard,
21 RecordingCard,
22};
23use crate::call_rows::{CallClock, CallNames, CallSource, CallTimeline, call_card, roster_card};
24use crate::card_state::CardOverride;
25use crate::format;
26use crate::reaction_model::{Reactor, UNKNOWN_REACTOR};
27use crate::render::blocks::{Inline, strip_image_placeholders};
28use crate::render::{Block, layout_blocks};
29use crate::translation::{TranslationContext, TranslationLine};
30
31const POST_VISIBLE_REPLIES: usize = 3;
32
33pub const LOAD_OLDER_KEY: &str = "load-older";
34pub const LOAD_NEWER_KEY: &str = "load-newer";
35const UNKNOWN_AUTHOR: &str = "Unknown";
36const DELETED_TEXT: &str = "Message deleted";
37const SERIES_GAP_MINUTES: i64 = 5;
38const CORNER_RADIUS: f32 = 14.;
39const CORNER_SERIES: f32 = 4.;
40
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct ReactionChip {
43 pub reaction_type: String,
44 pub label: String,
45 pub click_glyph: String,
46 pub count: usize,
47 pub mine: bool,
48 pub reactors: Vec<Reactor>,
49}
50
51impl ReactionChip {
52 pub fn glyph(&self) -> String {
53 reaction_glyph(&self.reaction_type)
54 }
55
56 pub fn custom_emoji_image(&self) -> Option<ImageRef> {
57 custom_emoji_image(&self.reaction_type)
58 }
59}
60
61/// Text for places without images: the org emoji's name instead of its raw key.
62pub fn reaction_text(reaction_type: &str) -> String {
63 match chatsvc::custom_emoji(reaction_type) {
64 Some(emoji) => format!(":{}:", emoji.name),
65 None => reaction_glyph(reaction_type),
66 }
67}
68
69pub fn custom_emoji_image(reaction_type: &str) -> Option<ImageRef> {
70 let emoji = chatsvc::custom_emoji(reaction_type)?;
71 Some(ImageRef {
72 id: emoji.object_id.to_owned(),
73 url: emoji.image_url(),
74 width: None,
75 height: None,
76 alt: Some(emoji.name.to_owned()),
77 })
78}
79
80#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
81pub struct Series {
82 pub has_prev: bool,
83 pub has_next: bool,
84}
85
86#[derive(Debug, Clone, Copy, PartialEq)]
87pub struct Corners {
88 pub top_left: f32,
89 pub top_right: f32,
90 pub bottom_right: f32,
91 pub bottom_left: f32,
92}
93
94pub fn bubble_corners(own: bool, series: Series) -> Corners {
95 let joined = |joined: bool| if joined { CORNER_SERIES } else { CORNER_RADIUS };
96 if own {
97 Corners {
98 top_left: CORNER_RADIUS,
99 top_right: joined(series.has_prev),
100 bottom_right: joined(series.has_next),
101 bottom_left: CORNER_RADIUS,
102 }
103 } else {
104 Corners {
105 top_left: joined(series.has_prev),
106 top_right: CORNER_RADIUS,
107 bottom_right: CORNER_RADIUS,
108 bottom_left: joined(series.has_next),
109 }
110 }
111}
112
113#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
114pub enum Receipt {
115 #[default]
116 Hidden,
117 Sent,
118 Read,
119 ReadLive,
120}
121
122pub fn receipt_label(state: &teams_core::ReceiptState) -> Option<String> {
123 match state {
124 teams_core::ReceiptState::Sent => Some("Sent".to_owned()),
125 teams_core::ReceiptState::Read { readers, total_others } if *total_others > 1 => {
126 if readers.len() >= *total_others {
127 Some("Seen by everyone".to_owned())
128 } else {
129 let names: Vec<&str> = readers.iter().map(|reader| reader.name.as_str()).collect();
130 Some(format!("Seen by {}", names.join(", ")))
131 }
132 }
133 teams_core::ReceiptState::Read { .. } => Some("Seen".to_owned()),
134 teams_core::ReceiptState::Unknown => None,
135 }
136}
137
138#[derive(Debug, Clone, Copy, PartialEq, Eq)]
139pub enum ScheduledState {
140 Waiting,
141 DeliveryFailed,
142 ChangeFailed,
143}
144
145#[derive(Debug, Clone, PartialEq, Eq)]
146pub enum Delivery {
147 Delivered,
148 Sending,
149 Failed(String),
150 Scheduled(ScheduledState),
151}
152
153/// An image of a message that is still being sent, shown from its local bytes.
154#[derive(Debug, Clone, PartialEq)]
155pub struct LocalImage {
156 pub image: Arc<Image>,
157 pub size: Option<(u32, u32)>,
158}
159
160#[derive(Debug, Clone, PartialEq)]
161pub struct MessageRow {
162 pub key: String,
163 pub conversation_id: String,
164 pub author: String,
165 pub sender_id: Option<String>,
166 pub application_id: Option<String>,
167 pub created_at: DateTime<Utc>,
168 pub series: Series,
169 pub time: String,
170 pub day_header: Option<String>,
171 pub blocks: Vec<Block>,
172 pub jumbo: Option<Vec<JumboEmoji>>,
173 pub edited: bool,
174 pub deleted: bool,
175 pub reactions: Vec<ReactionChip>,
176 pub images: Vec<ImageRef>,
177 pub local_images: Vec<LocalImage>,
178 pub files: Vec<FileCard>,
179 pub link_preview: Option<LinkPreview>,
180 pub meeting_link: Option<String>,
181 pub adaptive_cards: Vec<AdaptiveCard>,
182 pub subject: Option<String>,
183 pub banner: Option<AnnouncementBanner>,
184 pub importance: MessageImportance,
185 pub new_marker: bool,
186 pub reply_root: Option<String>,
187 pub delivery: Delivery,
188 pub own: bool,
189 pub receipt: Receipt,
190 pub receipt_label: Option<String>,
191 pub forwarded: bool,
192 pub translation: Option<TranslationLine>,
193 pub call: Option<CallCard>,
194}
195
196#[derive(Debug, Clone, PartialEq, Eq)]
197pub struct StartInfo {
198 pub title: String,
199 pub user_id: Option<String>,
200 pub avatar_name: String,
201 pub notes: bool,
202}
203
204pub const START_KEY: &str = "conversation-start";
205
206#[derive(Debug, Clone, PartialEq)]
207pub enum Row {
208 LoadOlder,
209 LoadNewer,
210 Start(StartInfo),
211 Skeleton(Skeleton),
212 Message(Box<MessageRow>),
213 Post(Box<PostRow>),
214}
215
216#[derive(Debug, Clone, Copy, PartialEq)]
217pub struct Skeleton {
218 pub key: &'static str,
219 pub own: bool,
220 pub width_ratio: f32,
221 pub lines: u8,
222}
223
224const SKELETON_PLACEHOLDERS: [Skeleton; 4] = [
225 Skeleton {
226 key: "skeleton-0",
227 own: false,
228 width_ratio: 0.42,
229 lines: 1,
230 },
231 Skeleton {
232 key: "skeleton-1",
233 own: true,
234 width_ratio: 0.3,
235 lines: 1,
236 },
237 Skeleton {
238 key: "skeleton-2",
239 own: true,
240 width_ratio: 0.48,
241 lines: 2,
242 },
243 Skeleton {
244 key: "skeleton-3",
245 own: false,
246 width_ratio: 0.26,
247 lines: 1,
248 },
249];
250
251pub fn placeholder_rows() -> Vec<Row> {
252 SKELETON_PLACEHOLDERS
253 .into_iter()
254 .map(Row::Skeleton)
255 .collect()
256}
257
258fn sender_key(row: &MessageRow) -> &str {
259 row.sender_id.as_deref().unwrap_or(&row.author)
260}
261
262fn continues_series(previous: &MessageRow, next: &MessageRow) -> bool {
263 previous.call.is_none()
264 && next.call.is_none()
265 && next.day_header.is_none()
266 && !next.new_marker
267 && sender_key(previous) == sender_key(next)
268 && next.created_at - previous.created_at < Duration::minutes(SERIES_GAP_MINUTES)
269 && next.created_at >= previous.created_at
270}
271
272pub fn assign_series(rows: &mut [Row]) {
273 let mut previous: Option<usize> = None;
274 for index in 0..rows.len() {
275 let Row::Message(_) = &rows[index] else {
276 previous = None;
277 continue;
278 };
279 if let Some(before) = previous {
280 let joined = match (&rows[before], &rows[index]) {
281 (Row::Message(a), Row::Message(b)) => continues_series(a, b),
282 _ => false,
283 };
284 if joined {
285 if let Row::Message(a) = &mut rows[before] {
286 a.series.has_next = true;
287 }
288 if let Row::Message(b) = &mut rows[index] {
289 b.series.has_prev = true;
290 }
291 }
292 }
293 previous = Some(index);
294 }
295}
296
297impl Row {
298 pub fn key(&self) -> &str {
299 match self {
300 Row::LoadOlder => LOAD_OLDER_KEY,
301 Row::LoadNewer => LOAD_NEWER_KEY,
302 Row::Start(_) => START_KEY,
303 Row::Skeleton(skeleton) => skeleton.key,
304 Row::Message(message) => &message.key,
305 Row::Post(post) => &post.root.key,
306 }
307 }
308
309 pub fn messages(&self) -> Box<dyn Iterator<Item = &MessageRow> + '_> {
310 match self {
311 Row::Message(message) => Box::new(std::iter::once(message.as_ref())),
312 Row::Post(post) => Box::new(post.messages()),
313 Row::LoadOlder | Row::LoadNewer | Row::Start(_) | Row::Skeleton(_) => {
314 Box::new(std::iter::empty())
315 }
316 }
317 }
318}
319
320#[derive(Debug, Clone, PartialEq)]
321pub struct PostRow {
322 pub root: MessageRow,
323 pub replies: Vec<MessageRow>,
324 pub hidden_reply_count: usize,
325 pub hidden_repliers: Vec<String>,
326 pub is_new: bool,
327}
328
329impl PostRow {
330 pub fn local(root: MessageRow) -> Self {
331 PostRow {
332 root,
333 replies: Vec::new(),
334 hidden_reply_count: 0,
335 hidden_repliers: Vec::new(),
336 is_new: false,
337 }
338 }
339
340 pub fn messages(&self) -> impl Iterator<Item = &MessageRow> {
341 std::iter::once(&self.root).chain(&self.replies)
342 }
343
344 /// Teams marks a post "New" when someone else posted it after the channel's read horizon.
345 pub fn mark_new_after(&mut self, read_until: DateTime<Utc>) {
346 self.is_new = !self.root.own && self.root.created_at > read_until;
347 }
348
349 pub fn hidden_replies_label(&self) -> Option<String> {
350 (self.hidden_reply_count > 0)
351 .then(|| replies_label(self.hidden_reply_count, &self.hidden_repliers))
352 }
353}
354
355fn first_name(name: &str) -> &str {
356 name.split_whitespace().next().unwrap_or(name)
357}
358
359pub fn replies_label(count: usize, repliers: &[String]) -> String {
360 let noun = if count == 1 { "reply" } else { "replies" };
361 let mut names: Vec<&str> = Vec::new();
362 for name in repliers.iter().map(|name| first_name(name)) {
363 if !names.contains(&name) {
364 names.push(name);
365 }
366 }
367 let people = match names.as_slice() {
368 [] => return format!("{count} {noun}"),
369 [only] => (*only).to_owned(),
370 [first, second] => format!("{first} and {second}"),
371 [first, second, third] => format!("{first}, {second} and {third}"),
372 [first, second, rest @ ..] => format!("{first}, {second} and {} others", rest.len()),
373 };
374 format!("{count} {noun} from {people}")
375}
376
377#[derive(Debug, Clone, PartialEq, Eq)]
378pub struct Thread {
379 pub root_id: String,
380 pub reply_ids: Vec<String>,
381}
382
383pub fn clock_label(time: DateTime<Utc>, offset: FixedOffset) -> String {
384 time.with_timezone(&offset).format("%H:%M").to_string()
385}
386
387pub fn reaction_label(reaction_type: &str) -> String {
388 match reaction_type {
389 "like" => "\u{1F44D}".to_owned(),
390 "heart" => "\u{2764}".to_owned(),
391 "laugh" => "\u{1F606}".to_owned(),
392 "surprised" => "\u{1F62E}".to_owned(),
393 "sad" => "\u{1F641}".to_owned(),
394 "angry" => "\u{1F620}".to_owned(),
395 other => other.to_owned(),
396 }
397}
398
399pub fn reaction_glyph(reaction_type: &str) -> String {
400 let label = reaction_label(reaction_type);
401 let glyph = if label == reaction_type {
402 chatsvc::reaction_glyph_for_key(reaction_type).unwrap_or(label)
403 } else {
404 label
405 };
406 glyph.trim_end_matches('\u{FE0F}').to_owned()
407}
408
409fn same_reaction(left: &str, right: &str) -> bool {
410 crate::emoticons::without_tone(left) == crate::emoticons::without_tone(right)
411}
412
413/// Graph rejects the legacy names ("Unicode 'like' in the payload is not supported").
414pub fn api_reaction(glyph: &str) -> String {
415 match glyph {
416 "\u{2764}" => "\u{2764}\u{FE0F}".to_owned(),
417 other => other.to_owned(),
418 }
419}
420
421/// The reaction type Teams uses for a glyph: the legacy name for the six classic ones.
422pub fn reaction_type_for(glyph: &str) -> String {
423 let bare = glyph.trim_end_matches('\u{FE0F}');
424 ["like", "heart", "laugh", "surprised", "sad", "angry"]
425 .into_iter()
426 .find(|name| reaction_label(name) == bare)
427 .map_or_else(|| bare.to_owned(), str::to_owned)
428}
429
430const MAX_TONE_VARIANTS: usize = 3;
431
432pub type PendingReactions = HashMap<String, Vec<(String, bool)>>;
433
434fn is_own_reaction(reaction: &ReactionInfo, wanted: &str, my_user_id: Option<&str>) -> bool {
435 my_user_id.is_some()
436 && reaction.user_id.as_deref() == my_user_id
437 && same_reaction(&reaction_glyph(&reaction.reaction_type), wanted)
438}
439
440/// The glyph of the own reaction that matches `glyph` regardless of skin tone.
441pub fn own_reaction_glyph(
442 reactions: &[ReactionInfo],
443 glyph: &str,
444 my_user_id: Option<&str>,
445) -> Option<String> {
446 let wanted = reaction_glyph(glyph);
447 reactions
448 .iter()
449 .find(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
450 .map(|reaction| reaction_glyph(&reaction.reaction_type))
451}
452
453pub fn has_own_reaction(reactions: &[ReactionInfo], glyph: &str, my_user_id: Option<&str>) -> bool {
454 let wanted = reaction_glyph(glyph);
455 reactions
456 .iter()
457 .any(|reaction| is_own_reaction(reaction, &wanted, my_user_id))
458}
459
460pub fn set_own_reaction(
461 reactions: &mut Vec<ReactionInfo>,
462 glyph: &str,
463 my_user_id: Option<&str>,
464 present: bool,
465 now: DateTime<Utc>,
466) {
467 let wanted = reaction_glyph(glyph);
468 if !present {
469 reactions.retain(|reaction| !is_own_reaction(reaction, &wanted, my_user_id));
470 } else if !has_own_reaction(reactions, glyph, my_user_id) {
471 reactions.push(ReactionInfo {
472 reaction_type: reaction_type_for(glyph),
473 user_id: my_user_id.map(str::to_owned),
474 user_name: Some("You".to_owned()),
475 created_at: Some(now),
476 });
477 }
478}
479
480pub fn apply_pending_reactions(
481 reactions: &mut Vec<ReactionInfo>,
482 pending: Option<&Vec<(String, bool)>>,
483 my_user_id: Option<&str>,
484 now: DateTime<Utc>,
485) {
486 for (glyph, present) in pending.into_iter().flatten() {
487 set_own_reaction(reactions, glyph, my_user_id, *present, now);
488 }
489}
490
491pub fn reaction_chips(reactions: &[ReactionInfo], context: &RowContext) -> Vec<ReactionChip> {
492 let my_user_id = context.my_user_id.as_deref();
493 let mut chips: Vec<ReactionChip> = Vec::new();
494 let mut variants: Vec<Vec<String>> = Vec::new();
495 for reaction in reactions {
496 let glyph = reaction_glyph(&reaction.reaction_type);
497 let position = match chips
498 .iter()
499 .position(|chip| same_reaction(&chip.glyph(), &glyph))
500 {
501 Some(position) => position,
502 None => {
503 chips.push(ReactionChip {
504 reaction_type: reaction.reaction_type.clone(),
505 label: String::new(),
506 click_glyph: crate::emoticons::with_tone(&glyph, context.skin_tone),
507 count: 0,
508 mine: false,
509 reactors: Vec::new(),
510 });
511 variants.push(Vec::new());
512 chips.len() - 1
513 }
514 };
515 let label = glyph;
516 let shown = &mut variants[position];
517 if shown.len() < MAX_TONE_VARIANTS && !shown.contains(&label) {
518 shown.push(label);
519 }
520 let chip = &mut chips[position];
521 chip.count += 1;
522 chip.mine |= my_user_id.is_some() && reaction.user_id.as_deref() == my_user_id;
523 chip.reactors.push(Reactor {
524 user_id: reaction.user_id.clone(),
525 name: reactor_name(reaction, context),
526 created_at: reaction.created_at,
527 });
528 }
529 for (chip, shown) in chips.iter_mut().zip(variants) {
530 chip.label = shown.concat();
531 }
532 chips
533}
534
535fn reactor_name(reaction: &ReactionInfo, context: &RowContext) -> String {
536 reaction
537 .user_name
538 .clone()
539 .or_else(|| {
540 reaction
541 .user_id
542 .as_ref()
543 .and_then(|user_id| context.names.get(user_id).cloned())
544 })
545 .unwrap_or_else(|| UNKNOWN_REACTOR.to_owned())
546}
547
548const REPLY_EXCERPT_CHARS: usize = 90;
549
550pub fn message_text(record: &MessageRecord) -> String {
551 let own_spans: Vec<Span> = message_spans(record)
552 .into_iter()
553 .filter(|span| !matches!(span, Span::Quote { .. }))
554 .collect();
555 strip_image_placeholders(layout_blocks(&own_spans))
556 .into_iter()
557 .filter_map(|block| block.markdown())
558 .chain(forwarded_texts(record))
559 .collect::<Vec<_>>()
560 .join("\n")
561}
562
563/// The message as the composer edits it, formatting kept.
564pub fn message_draft(record: &MessageRecord) -> Draft {
565 let own_spans: Vec<Span> = message_spans(record)
566 .into_iter()
567 .filter(|span| !matches!(span, Span::Quote { .. }))
568 .collect();
569 Draft::from_spans(&own_spans).trimmed()
570}
571
572pub fn reply_excerpt(record: &MessageRecord) -> String {
573 let own_spans: Vec<Span> = message_spans(record)
574 .into_iter()
575 .filter(|span| !matches!(span, Span::Quote { .. }))
576 .collect();
577 let text = strip_image_placeholders(layout_blocks(&own_spans))
578 .into_iter()
579 .find_map(|block| block.first_line())
580 .unwrap_or_default();
581 let first_line = text.lines().map(str::trim).find(|line| !line.is_empty());
582 let excerpt = match first_line {
583 Some(line) => line.to_owned(),
584 None if let Some(line) = forwarded_texts(record)
585 .iter()
586 .flat_map(|text| text.lines())
587 .map(str::trim)
588 .find(|line| !line.is_empty()) =>
589 {
590 line.to_owned()
591 }
592 None if !images(record).is_empty() => "Image".to_owned(),
593 None if let Some(line) = card_texts(record)
594 .iter()
595 .flat_map(|text| text.lines())
596 .next() =>
597 {
598 line.to_owned()
599 }
600 None => files(record)
601 .into_iter()
602 .next()
603 .map_or_else(|| "Message".to_owned(), |card| card.name),
604 };
605 if excerpt.chars().count() > REPLY_EXCERPT_CHARS {
606 let cut: String = excerpt.chars().take(REPLY_EXCERPT_CHARS).collect();
607 format!("{}...", cut.trim_end())
608 } else {
609 excerpt
610 }
611}
612
613pub struct RowContext {
614 pub offset: FixedOffset,
615 pub today: NaiveDate,
616 pub my_user_id: Option<String>,
617 pub names: HashMap<String, String>,
618 pub pending_reactions: PendingReactions,
619 pub card_overrides: HashMap<String, CardOverride>,
620 pub translation: TranslationContext,
621 pub skin_tone: u8,
622 pub meeting: MeetingInfo,
623}
624
625fn visible_reactions(record: &MessageRecord, context: &RowContext) -> Vec<ReactionInfo> {
626 let mut visible = reactions(record);
627 apply_pending_reactions(
628 &mut visible,
629 context.pending_reactions.get(&record.message_id),
630 context.my_user_id.as_deref(),
631 Utc::now(),
632 );
633 visible
634}
635
636fn call_row(
637 record: &MessageRecord,
638 event: &CallEvent,
639 context: &RowContext,
640 timeline: &CallTimeline,
641) -> MessageRow {
642 let my_user_id = context.my_user_id.as_deref();
643 let time = clock_label(record.created_at, context.offset);
644 let names = CallNames {
645 my_user_id,
646 names: &context.names,
647 };
648 let author = event
649 .initiator_name
650 .clone()
651 .or_else(|| {
652 event
653 .initiator_id
654 .as_ref()
655 .and_then(|user_id| context.names.get(user_id).cloned())
656 })
657 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
658 let card = call_card(
659 CallSource {
660 event,
661 message_id: &record.message_id,
662 created_at: record.created_at,
663 time: &time,
664 },
665 &names,
666 &CallClock {
667 offset: context.offset,
668 today: context.today,
669 meeting: &context.meeting,
670 },
671 timeline,
672 );
673 event_row(
674 record,
675 context,
676 EventAuthor {
677 sender_id: event.initiator_id.clone(),
678 name: author,
679 own: event.initiated_by(my_user_id),
680 },
681 card,
682 time,
683 )
684}
685
686fn roster_row(record: &MessageRecord, event: &RosterEvent, context: &RowContext) -> MessageRow {
687 let my_user_id = context.my_user_id.as_deref();
688 let names = CallNames {
689 my_user_id,
690 names: &context.names,
691 };
692 let card = roster_card(
693 event,
694 record.created_at,
695 &names,
696 &CallClock {
697 offset: context.offset,
698 today: context.today,
699 meeting: &context.meeting,
700 },
701 );
702 let author = event
703 .initiator_name
704 .clone()
705 .or_else(|| {
706 event
707 .initiator_id
708 .as_ref()
709 .and_then(|user_id| context.names.get(user_id).cloned())
710 })
711 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
712 let own = my_user_id.is_some() && event.initiator_id.as_deref() == my_user_id;
713 event_row(
714 record,
715 context,
716 EventAuthor {
717 sender_id: event.initiator_id.clone(),
718 name: author,
719 own,
720 },
721 card,
722 clock_label(record.created_at, context.offset),
723 )
724}
725
726struct EventAuthor {
727 sender_id: Option<String>,
728 name: String,
729 own: bool,
730}
731
732fn event_row(
733 record: &MessageRecord,
734 context: &RowContext,
735 author: EventAuthor,
736 card: CallCard,
737 time: String,
738) -> MessageRow {
739 MessageRow {
740 key: record.message_id.clone(),
741 conversation_id: record.conversation_id.clone(),
742 sender_id: author.sender_id,
743 application_id: None,
744 created_at: record.created_at,
745 series: Series::default(),
746 author: author.name,
747 day_header: Some(format::day_label(
748 record
749 .created_at
750 .with_timezone(&context.offset)
751 .date_naive(),
752 context.today,
753 )),
754 blocks: Vec::new(),
755 jumbo: None,
756 edited: false,
757 deleted: false,
758 reactions: Vec::new(),
759 images: Vec::new(),
760 local_images: Vec::new(),
761 files: Vec::new(),
762 link_preview: None,
763 meeting_link: None,
764 adaptive_cards: Vec::new(),
765 subject: None,
766 banner: None,
767 importance: MessageImportance::Normal,
768 new_marker: false,
769 reply_root: None,
770 delivery: Delivery::Delivered,
771 receipt: Receipt::Hidden,
772 receipt_label: None,
773 own: author.own,
774 forwarded: false,
775 translation: None,
776 call: Some(card),
777 time,
778 }
779}
780
781const QUOTE_LINES: usize = 5;
782
783pub fn quoted_texts(records: &[MessageRecord]) -> HashMap<String, String> {
784 let wanted: std::collections::HashSet<String> = records
785 .iter()
786 .flat_map(quotes)
787 .map(|quote| quote.message_id)
788 .collect();
789 records
790 .iter()
791 .filter(|record| !record.deleted && wanted.contains(&record.message_id))
792 .map(|record| {
793 let mut text = readable_text(record);
794 if text.is_empty() {
795 text = forwarded_texts(record).join("\n");
796 }
797 let lines: Vec<&str> = text.lines().filter(|line| !line.trim().is_empty()).collect();
798 let mut shown = lines.iter().take(QUOTE_LINES).copied().collect::<Vec<_>>().join("\n");
799 if lines.len() > QUOTE_LINES {
800 shown.push_str(" …");
801 }
802 (record.message_id.clone(), shown)
803 })
804 .collect()
805}
806
807fn forward_header(forward: &ForwardInfo, context: &RowContext) -> ForwardHeader {
808 ForwardHeader {
809 sender: forward
810 .sender_id
811 .as_ref()
812 .and_then(|user_id| context.names.get(user_id).cloned()),
813 time: forward
814 .sent_at
815 .map(|time| format::post_time_label(time, context.today, context.offset)),
816 }
817}
818
819/// User ids a row needs a name for beyond its author: original senders of forwards.
820pub fn forward_sender_ids(records: &[MessageRecord]) -> Vec<String> {
821 let mut user_ids: Vec<String> = Vec::new();
822 for user_id in records
823 .iter()
824 .flat_map(forwards)
825 .filter_map(|forward| forward.sender_id)
826 {
827 if !user_ids.contains(&user_id) {
828 user_ids.push(user_id);
829 }
830 }
831 user_ids
832}
833
834pub fn message_row(record: &MessageRecord, context: &RowContext) -> MessageRow {
835 message_row_with(record, context, &HashMap::new())
836}
837
838fn message_row_with(
839 record: &MessageRecord,
840 context: &RowContext,
841 quoted: &HashMap<String, String>,
842) -> MessageRow {
843 if let Some(event) = call_event(record) {
844 let events = [Some(event.clone())];
845 return call_row(record, &event, context, &CallTimeline::new(&events));
846 }
847 if let Some(event) = roster_event(record) {
848 return roster_row(record, &event, context);
849 }
850 let local = record.created_at.with_timezone(&context.offset);
851 let images = images(record);
852 let own = context.my_user_id.is_some() && record.sender_id == context.my_user_id;
853 let translation = context.translation.resolve(record, own);
854 let forward_header = |forward: &ForwardInfo| forward_header(forward, context);
855 let blocks = if record.deleted {
856 vec![Block::Paragraph(Inline::plain(DELETED_TEXT))]
857 } else if let Some(html) = &translation.translated_html {
858 layout_blocks(&translated_spans(record, html, &forward_header))
859 } else {
860 layout_blocks(&linked_message_spans_with(
861 record,
862 &|id| quoted.get(id).cloned(),
863 &forward_header,
864 ))
865 };
866 let blocks = if images.is_empty() {
867 blocks
868 } else {
869 strip_image_placeholders(blocks)
870 };
871 MessageRow {
872 key: record.message_id.clone(),
873 conversation_id: record.conversation_id.clone(),
874 sender_id: record.sender_id.clone(),
875 application_id: record.sender_application_id.clone(),
876 created_at: record.created_at,
877 series: Series::default(),
878 author: record
879 .sender_name
880 .clone()
881 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned()),
882 time: clock_label(record.created_at, context.offset),
883 day_header: Some(format::day_label(local.date_naive(), context.today)),
884 blocks,
885 jumbo: (!record.deleted && !is_forwarded(record))
886 .then(|| jumbo_emoji(&record.body_html))
887 .flatten(),
888 edited: record.edited_at.is_some() && !record.deleted,
889 deleted: record.deleted,
890 reactions: reaction_chips(&visible_reactions(record, context), context),
891 images,
892 local_images: Vec::new(),
893 files: files(record),
894 link_preview: link_preview(record),
895 meeting_link: (!record.deleted)
896 .then(|| meeting_link_in_html(&record.body_html))
897 .flatten(),
898 adaptive_cards: match context.card_overrides.get(&record.message_id) {
899 Some(replaced) if replaced.basis == record.attachments_json => replaced.cards.clone(),
900 _ => adaptive_cards(record),
901 },
902 subject: record.subject.clone(),
903 banner: AnnouncementBanner::from_attachments(&attachments(record)),
904 importance: if record.deleted {
905 MessageImportance::Normal
906 } else {
907 record.importance
908 },
909 new_marker: false,
910 reply_root: record.reply_to_id.clone(),
911 delivery: Delivery::Delivered,
912 receipt: Receipt::Hidden,
913 receipt_label: None,
914 own,
915 forwarded: is_forwarded(record),
916 translation: translation.line,
917 call: None,
918 }
919}
920
921pub fn flat_rows(records: &[MessageRecord], context: &RowContext, has_older: bool) -> Vec<Row> {
922 let mut rows = Vec::with_capacity(records.len() + 1);
923 if has_older {
924 rows.push(Row::LoadOlder);
925 }
926 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
927 let timeline = CallTimeline::with_records(&events, &records.iter().collect::<Vec<_>>());
928 let mut previous_day: Option<NaiveDate> = None;
929 let quoted = quoted_texts(records);
930 for (index, (record, event)) in records.iter().zip(&events).enumerate() {
931 if timeline.hides(index) {
932 continue;
933 }
934 let mut row = match event {
935 Some(event) => call_row(record, event, context, &timeline),
936 None => message_row_with(record, context, &quoted),
937 };
938 if let Some(call) = row.call.as_mut() {
939 call.started &= timeline.is_live_start(index);
940 }
941 let day = record
942 .created_at
943 .with_timezone(&context.offset)
944 .date_naive();
945 if previous_day == Some(day) {
946 row.day_header = None;
947 }
948 previous_day = Some(day);
949 rows.push(Row::Message(Box::new(row)));
950 }
951 assign_series(&mut rows);
952 rows
953}
954
955pub fn group_threads(records: &[MessageRecord]) -> Vec<Thread> {
956 let mut threads: Vec<Thread> = Vec::new();
957 let mut index_by_root: BTreeMap<&str, usize> = BTreeMap::new();
958 for record in records.iter().filter(|record| record.reply_to_id.is_none()) {
959 index_by_root.insert(record.message_id.as_str(), threads.len());
960 threads.push(Thread {
961 root_id: record.message_id.clone(),
962 reply_ids: Vec::new(),
963 });
964 }
965 for record in records {
966 let Some(root_id) = record.reply_to_id.as_deref() else {
967 continue;
968 };
969 if let Some(&index) = index_by_root.get(root_id) {
970 threads[index].reply_ids.push(record.message_id.clone());
971 }
972 }
973 threads
974}
975
976fn last_activity(thread: &Thread, by_id: &BTreeMap<&str, &MessageRecord>) -> DateTime<Utc> {
977 thread
978 .reply_ids
979 .iter()
980 .chain(std::iter::once(&thread.root_id))
981 .filter_map(|id| by_id.get(id.as_str()))
982 .map(|record| record.created_at)
983 .max()
984 .unwrap_or_default()
985}
986
987fn post_message_row(
988 record: &MessageRecord,
989 context: &RowContext,
990 timeline: &CallTimeline,
991) -> MessageRow {
992 let mut row = match call_event(record) {
993 Some(event) => call_row(record, &event, context, timeline),
994 None => message_row(record, context),
995 };
996 row.day_header = None;
997 row.time = format::post_time_label(record.created_at, context.today, context.offset);
998 row
999}
1000
1001fn meeting_root_row(
1002 root: &MessageRecord,
1003 started: &CallEvent,
1004 ended: Option<(&MessageRecord, CallEvent)>,
1005 context: &RowContext,
1006 timeline: &CallTimeline,
1007) -> MessageRow {
1008 let Some((ended_record, ended_event)) = ended else {
1009 let mut row = post_message_row(root, context, timeline);
1010 if let Some(call) = row.call.as_mut() {
1011 call.started = !timeline.finished(&started.call_id);
1012 }
1013 return row;
1014 };
1015 let mut summary = CallEvent {
1016 initiator_id: started.initiator_id.clone(),
1017 initiator_name: started
1018 .initiator_name
1019 .clone()
1020 .or(ended_event.initiator_name.clone()),
1021 ..ended_event
1022 };
1023 summary.call_type = started.call_type;
1024 let mut row = call_row(ended_record, &summary, context, timeline);
1025 row.key = root.message_id.clone();
1026 row.created_at = root.created_at;
1027 row.reply_root = None;
1028 row.day_header = None;
1029 row.time = format::post_time_label(root.created_at, context.today, context.offset);
1030 row
1031}
1032
1033fn distinct_names<'a>(records: impl Iterator<Item = &'a MessageRecord>) -> Vec<String> {
1034 let mut names: Vec<String> = Vec::new();
1035 for record in records.filter(|record| record.call_event_json.is_none()) {
1036 let name = record
1037 .sender_name
1038 .clone()
1039 .unwrap_or_else(|| UNKNOWN_AUTHOR.to_owned());
1040 if !names.contains(&name) {
1041 names.push(name);
1042 }
1043 }
1044 names
1045}
1046
1047fn post_row(
1048 root: MessageRow,
1049 mut replies: Vec<&MessageRecord>,
1050 context: &RowContext,
1051 timeline: &CallTimeline,
1052) -> PostRow {
1053 replies.sort_by_key(|reply| reply.created_at);
1054 let hidden = replies.len().saturating_sub(POST_VISIBLE_REPLIES);
1055 PostRow {
1056 root,
1057 hidden_reply_count: hidden,
1058 hidden_repliers: distinct_names(replies[..hidden].iter().copied()),
1059 replies: replies[hidden..]
1060 .iter()
1061 .map(|reply| post_message_row(reply, context, timeline))
1062 .collect(),
1063 is_new: false,
1064 }
1065}
1066
1067/// Channel feed: Teams shows a Meet now meeting as its own post and keeps the other call notices
1068/// inside the thread; a saved recording stays visible as a reply.
1069fn shows_in_feed(record: &MessageRecord, event: Option<&CallEvent>) -> bool {
1070 match event {
1071 None => true,
1072 Some(event) if record.reply_to_id.is_none() => event.phase == CallPhase::Started,
1073 Some(event) => event.phase == CallPhase::RecordingSaved,
1074 }
1075}
1076
1077pub fn thread_list_rows(
1078 records: &[MessageRecord],
1079 context: &RowContext,
1080 has_older: bool,
1081) -> Vec<Row> {
1082 let events: Vec<Option<CallEvent>> = records.iter().map(call_event).collect();
1083 let timeline = CallTimeline::new(&events);
1084 let ended: HashMap<&str, (&MessageRecord, &CallEvent)> = records
1085 .iter()
1086 .zip(&events)
1087 .filter_map(|(record, event)| {
1088 let event = event
1089 .as_ref()
1090 .filter(|event| event.phase == CallPhase::Ended)?;
1091 Some((event.call_id.as_str(), (record, event)))
1092 })
1093 .collect();
1094 let by_id: BTreeMap<&str, (&MessageRecord, Option<&CallEvent>)> = records
1095 .iter()
1096 .zip(&events)
1097 .filter(|(record, event)| shows_in_feed(record, event.as_ref()))
1098 .map(|(record, event)| (record.message_id.as_str(), (record, event.as_ref())))
1099 .collect();
1100 let records_by_id: BTreeMap<&str, &MessageRecord> = by_id
1101 .iter()
1102 .map(|(id, (record, _))| (*id, *record))
1103 .collect();
1104 let mut threads = group_threads(records);
1105 threads.sort_by_key(|thread| std::cmp::Reverse(last_activity(thread, &records_by_id)));
1106 let mut rows: Vec<Row> = threads
1107 .iter()
1108 .filter_map(|thread| {
1109 let (root, root_event) = by_id.get(thread.root_id.as_str())?;
1110 let root_row = match root_event {
1111 Some(started) => meeting_root_row(
1112 root,
1113 started,
1114 ended
1115 .get(started.call_id.as_str())
1116 .map(|(record, event)| (*record, (*event).clone())),
1117 context,
1118 &timeline,
1119 ),
1120 None => post_message_row(root, context, &timeline),
1121 };
1122 let replies = thread
1123 .reply_ids
1124 .iter()
1125 .filter_map(|id| records_by_id.get(id.as_str()).copied())
1126 .collect();
1127 Some(Row::Post(Box::new(post_row(
1128 root_row, replies, context, &timeline,
1129 ))))
1130 })
1131 .collect();
1132 if has_older {
1133 rows.push(Row::LoadOlder);
1134 }
1135 rows
1136}
1137
1138pub fn place_local_rows(rows: &mut Vec<Row>, local: Vec<MessageRow>) {
1139 for message in local {
1140 let Some(root_id) = message.reply_root.clone() else {
1141 rows.insert(0, Row::Post(Box::new(PostRow::local(message))));
1142 continue;
1143 };
1144 let position = rows
1145 .iter()
1146 .position(|row| matches!(row, Row::Post(post) if post.root.key == root_id));
1147 if let Some(position) = position {
1148 let mut row = rows.remove(position);
1149 if let Row::Post(post) = &mut row {
1150 post.replies.push(message);
1151 }
1152 rows.insert(0, row);
1153 }
1154 }
1155}
1156
1157pub fn thread_rows(records: &[MessageRecord], root_id: &str, context: &RowContext) -> Vec<Row> {
1158 let members: Vec<MessageRecord> = records
1159 .iter()
1160 .filter(|record| {
1161 record.message_id == root_id || record.reply_to_id.as_deref() == Some(root_id)
1162 })
1163 .cloned()
1164 .collect();
1165 flat_rows(&members, context, false)
1166}
1167
1168#[derive(Debug, Clone, PartialEq, Eq)]
1169pub struct Splice {
1170 pub range: Range<usize>,
1171 pub count: usize,
1172}
1173
1174pub fn diff_keys(old: &[String], new: &[String]) -> Option<Splice> {
1175 if old == new {
1176 return None;
1177 }
1178 let prefix = old
1179 .iter()
1180 .zip(new)
1181 .take_while(|(left, right)| left == right)
1182 .count();
1183 let suffix = old[prefix..]
1184 .iter()
1185 .rev()
1186 .zip(new[prefix..].iter().rev())
1187 .take_while(|(left, right)| left == right)
1188 .count();
1189 Some(Splice {
1190 range: prefix..old.len() - suffix,
1191 count: new.len() - prefix - suffix,
1192 })
1193}
1194
1195pub fn changed_indices(old: &[Row], new: &[Row]) -> Vec<usize> {
1196 let prefix = old
1197 .iter()
1198 .zip(new)
1199 .take_while(|(left, right)| left.key() == right.key())
1200 .count();
1201 let suffix = old[prefix..]
1202 .iter()
1203 .rev()
1204 .zip(new[prefix..].iter().rev())
1205 .take_while(|(left, right)| left.key() == right.key())
1206 .count();
1207 let mut changed: Vec<usize> = (0..prefix)
1208 .filter(|&index| old[index] != new[index])
1209 .collect();
1210 changed.extend((0..suffix).filter_map(|offset| {
1211 let old_index = old.len() - 1 - offset;
1212 let new_index = new.len() - 1 - offset;
1213 (old[old_index] != new[new_index]).then_some(new_index)
1214 }));
1215 changed
1216}
1217
1218#[cfg(test)]
1219mod tests {
1220 use chrono::TimeZone;
1221 use teams_core::CallType;
1222
1223 use super::*;
1224
1225 #[test]
1226 fn the_receipt_label_names_who_saw_a_group_message() {
1227 let reader = |name: &str| teams_core::ReceiptReader {
1228 name: name.into(),
1229 at: Utc::now(),
1230 };
1231 let read = |readers: Vec<teams_core::ReceiptReader>, total_others| {
1232 receipt_label(&teams_core::ReceiptState::Read { readers, total_others })
1233 };
1234 assert_eq!(read(vec![reader("Bea")], 1).as_deref(), Some("Seen"));
1235 assert_eq!(read(vec![reader("Bea"), reader("Cy")], 2).as_deref(), Some("Seen by everyone"));
1236 assert_eq!(read(vec![reader("Bea")], 3).as_deref(), Some("Seen by Bea"));
1237 assert_eq!(receipt_label(&teams_core::ReceiptState::Sent).as_deref(), Some("Sent"));
1238 assert_eq!(receipt_label(&teams_core::ReceiptState::Unknown), None);
1239 }
1240
1241 fn record(id: &str, reply_to: Option<&str>, hour: u32, day: u32) -> MessageRecord {
1242 MessageRecord {
1243 conversation_id: "c".into(),
1244 message_id: id.into(),
1245 reply_to_id: reply_to.map(str::to_owned),
1246 sender_id: Some("u".into()),
1247 sender_name: Some("Author".into()),
1248 sender_application_id: None,
1249 links_json: "[]".to_owned(),
1250 created_at: Utc.with_ymd_and_hms(2026, 10, day, hour, 0, 0).unwrap(),
1251 edited_at: None,
1252 deleted: false,
1253 body_html: format!("<p>text {id}</p>"),
1254 attachments_json: "[]".into(),
1255 reactions_json: "[]".into(),
1256 mentions_json: "[]".into(),
1257 subject: None,
1258 call_event_json: None,
1259 importance: Default::default(),
1260 }
1261 }
1262
1263 #[test]
1264 fn a_quote_shows_the_lines_of_the_quoted_message_when_it_is_loaded() {
1265 let mut quoted = record("q1", None, 8, 6);
1266 quoted.body_html = "<p>first link</p><p>second link</p>".into();
1267 let mut answer = record("a1", None, 9, 6);
1268 answer.body_html = "<attachment id=\"q1\"></attachment><p>please again</p>".into();
1269 answer.attachments_json = r#"[{"content_type":"messageReference","name":null,"url":null,"text":null,"id":"q1","quote":{"message_id":"q1","preview":"first link second link","sender_name":"Robin"}}]"#.into();
1270 let rows = flat_rows(&[quoted, answer], &context(), false);
1271 let reply = rows
1272 .iter()
1273 .find_map(|row| match row {
1274 Row::Message(row) if row.key == "a1" => Some(row.blocks.clone()),
1275 _ => None,
1276 })
1277 .unwrap();
1278 let Some(Block::Reply { children, .. }) = reply.first() else { panic!("{reply:?}") };
1279 let text = format!("{children:?}");
1280 assert!(text.contains(r"first link\nsecond link"), "{text}");
1281 }
1282
1283 fn own_reaction(reaction_type: &str) -> ReactionInfo {
1284 ReactionInfo {
1285 reaction_type: reaction_type.into(),
1286 user_id: Some("me".into()),
1287 user_name: None,
1288 created_at: None,
1289 }
1290 }
1291
1292 #[test]
1293 fn setting_a_reaction_is_idempotent_and_only_touches_mine() {
1294 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1295 let other = ReactionInfo {
1296 user_id: Some("them".into()),
1297 ..own_reaction("like")
1298 };
1299 let mut reactions = vec![other.clone()];
1300 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
1301 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), true, now);
1302 assert_eq!(reactions.len(), 2);
1303 assert_eq!(reactions[1].reaction_type, "like");
1304 assert_eq!(reactions[1].user_id.as_deref(), Some("me"));
1305 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
1306 set_own_reaction(&mut reactions, "\u{1F44D}", Some("me"), false, now);
1307 assert_eq!(reactions, vec![other]);
1308 }
1309
1310 #[test]
1311 fn setting_matches_legacy_names_and_variation_selectors() {
1312 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1313 let mut reactions = vec![own_reaction("heart")];
1314 assert!(has_own_reaction(&reactions, "\u{2764}\u{FE0F}", Some("me")));
1315 set_own_reaction(&mut reactions, "\u{2764}\u{FE0F}", Some("me"), false, now);
1316 assert!(reactions.is_empty());
1317 set_own_reaction(&mut reactions, "\u{1F389}", Some("me"), true, now);
1318 assert_eq!(reactions[0].reaction_type, "\u{1F389}");
1319 }
1320
1321 #[test]
1322 fn setting_without_a_known_user_never_matches() {
1323 let now = Utc.with_ymd_and_hms(2026, 10, 1, 8, 0, 0).unwrap();
1324 let mut reactions = Vec::new();
1325 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
1326 set_own_reaction(&mut reactions, "\u{1F44D}", None, true, now);
1327 assert_eq!(reactions.len(), 2);
1328 }
1329
1330 #[test]
1331 fn pending_reactions_overlay_the_stored_ones() {
1332 let mut stored = record("a", None, 8, 6);
1333 stored.reactions_json = serde_json::to_string(&[own_reaction("like")]).unwrap();
1334 let mut context = context();
1335 context.my_user_id = Some("me".into());
1336 context.pending_reactions.insert(
1337 "a".into(),
1338 vec![("\u{1F44D}".into(), false), ("\u{1F389}".into(), true)],
1339 );
1340 let chips = message_row(&stored, &context).reactions;
1341 assert_eq!(chips.len(), 1);
1342 assert_eq!(chips[0].reaction_type, "\u{1F389}");
1343 assert!(chips[0].mine);
1344 }
1345
1346 #[test]
1347 fn org_emoji_shows_its_name_and_loads_its_image() {
1348 let key = "absolute-cinema;0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8";
1349 assert_eq!(reaction_text(key), ":absolute-cinema:");
1350 assert_eq!(reaction_text("like"), "\u{1F44D}");
1351 let image = custom_emoji_image(key).expect("image");
1352 assert!(image.url.ends_with("/0-wcde-d3-5f5e4f463d6bb959b08614fd1d9680b8/views/imgt2_anim"));
1353 assert_eq!(custom_emoji_image("like"), None);
1354 }
1355
1356 #[test]
1357 fn reaction_type_maps_classic_glyphs_to_names() {
1358 assert_eq!(reaction_type_for("\u{1F44D}"), "like");
1359 assert_eq!(reaction_type_for("\u{2764}\u{FE0F}"), "heart");
1360 assert_eq!(reaction_type_for("\u{1F389}"), "\u{1F389}");
1361 assert_eq!(reaction_glyph("like"), reaction_glyph("\u{1F44D}"));
1362 assert_eq!(reaction_glyph("heart"), reaction_glyph("\u{2764}\u{FE0F}"));
1363 assert_eq!(api_reaction(&reaction_glyph("heart")), "\u{2764}\u{FE0F}");
1364 assert_eq!(api_reaction(&reaction_glyph("like")), "\u{1F44D}");
1365 }
1366
1367 #[test]
1368 fn forwarded_messages_are_detected_by_the_forward_blockquote() {
1369 let mut forwarded = record("f", None, 8, 6);
1370 forwarded.body_html =
1371 r#"<p>fyi</p><blockquote itemscope="" itemtype="http://schema.skype.com/Forward" itemid="1">text</blockquote>"#.into();
1372 assert!(message_row(&forwarded, &context()).forwarded);
1373 forwarded.body_html =
1374 r#"<blockquote itemtype="http://schema.skype.com/Reply">text</blockquote>"#.into();
1375 assert!(!message_row(&forwarded, &context()).forwarded);
1376 forwarded.body_html =
1377 r#"<blockquote itemtype="http://schema.skype.com/Forward">text</blockquote>"#.into();
1378 forwarded.deleted = true;
1379 assert!(!message_row(&forwarded, &context()).forwarded);
1380 }
1381
1382 #[test]
1383 fn a_graph_forward_shows_the_original_sender_and_text_in_a_quote() {
1384 let mut forwarded = record("f", None, 8, 6);
1385 forwarded.body_html = r#"<attachment id="9"></attachment>"#.into();
1386 forwarded.attachments_json = serde_json::json!([{
1387 "content_type": "forwardedMessageReference",
1388 "name": null, "url": null, "text": null, "id": "9",
1389 "content": serde_json::json!({
1390 "originalMessageId": "9",
1391 "originalMessageContent": "<p>original words</p>",
1392 "originalSentDateTime": "2026-10-06T07:00:00.000+00:00",
1393 "originalMessageSender": {"user": {"id": "orig", "displayName": null}}
1394 }).to_string()
1395 }])
1396 .to_string();
1397 let mut context = context();
1398 context.names.insert("orig".into(), "Priya Nair".into());
1399 let row = message_row(&forwarded, &context);
1400 assert!(row.forwarded);
1401 assert!(row.jumbo.is_none());
1402 let [Block::Quote(children)] = row.blocks.as_slice() else {
1403 panic!("expected one forward quote, got {:?}", row.blocks);
1404 };
1405 let lines: Vec<String> = children.iter().filter_map(Block::markdown).collect();
1406 assert!(lines[0].contains("Priya Nair Yesterday 07:00"), "{lines:?}");
1407 assert!(lines.iter().any(|line| line.contains("original words")), "{lines:?}");
1408 assert_eq!(reply_excerpt(&forwarded), "original words");
1409 assert_eq!(message_text(&forwarded), "original words");
1410 }
1411
1412 #[test]
1413 fn editing_loads_the_message_formatted_without_its_reply_quote() {
1414 let mut edited = record("a", None, 8, 6);
1415 edited.body_html =
1416 "<blockquote itemtype=\"http://schema.skype.com/Reply\">old</blockquote>\
1417 <p><b>Plan</b> for <a href=\"https://x.test\">today</a></p>\
1418 <ol><li>one</li><li>two</li></ol>"
1419 .into();
1420 let draft = message_draft(&edited);
1421 assert_eq!(draft.text(), "Plan for today\n1. one\n2. two");
1422 assert_eq!(
1423 draft.to_html(),
1424 "<b>Plan</b> for <a href=\"https://x.test\">today</a><ol><li>one</li><li>two</li></ol>"
1425 );
1426 }
1427
1428 #[test]
1429 fn reply_excerpt_uses_the_first_line_or_the_attachment() {
1430 let mut text = record("a", None, 8, 6);
1431 text.body_html = "<p>first line</p><p>second</p>".into();
1432 assert_eq!(reply_excerpt(&text), "first line");
1433 let mut quoted = record("q", None, 8, 6);
1434 quoted.body_html = r#"<blockquote itemtype="http://schema.skype.com/Reply">Jonas<br>old text</blockquote><p>my answer</p>"#.into();
1435 assert_eq!(reply_excerpt(&quoted), "my answer");
1436 let mut image = record("b", None, 8, 6);
1437 image.body_html = "<img src=\"u\">".into();
1438 assert_eq!(reply_excerpt(&image), "Image");
1439 let mut long = record("c", None, 8, 6);
1440 long.body_html = format!("<p>{}</p>", "x".repeat(200));
1441 assert!(reply_excerpt(&long).ends_with("..."));
1442 assert_eq!(
1443 reply_excerpt(&long).chars().count(),
1444 REPLY_EXCERPT_CHARS + 3
1445 );
1446 }
1447
1448 fn context() -> RowContext {
1449 RowContext {
1450 offset: FixedOffset::east_opt(0).unwrap(),
1451 today: NaiveDate::from_ymd_opt(2026, 10, 7).unwrap(),
1452 my_user_id: None,
1453 names: HashMap::new(),
1454 pending_reactions: HashMap::new(),
1455 card_overrides: HashMap::new(),
1456 translation: TranslationContext::default(),
1457 skin_tone: 0,
1458 meeting: MeetingInfo::default(),
1459 }
1460 }
1461
1462 fn keys(rows: &[Row]) -> Vec<String> {
1463 rows.iter().map(|row| row.key().to_owned()).collect()
1464 }
1465
1466 fn translation_context(shown: bool) -> RowContext {
1467 use crate::translation::CachedTranslation;
1468 let mut context = context();
1469 context.translation.enabled = true;
1470 context.translation.target = "en".into();
1471 context.translation.stamps.insert(
1472 "a".into(),
1473 "languages=fr:100;length:80;&detector=Bling".into(),
1474 );
1475 context.my_user_id = Some("me".into());
1476 if shown {
1477 context.translation.cached.insert(
1478 ("a".into(), 0),
1479 CachedTranslation {
1480 html: "<p><strong>translated</strong> body</p>".into(),
1481 source: Some("fr".into()),
1482 },
1483 );
1484 context.translation.shown.insert("a".into());
1485 }
1486 context
1487 }
1488
1489 #[test]
1490 fn a_foreign_message_carries_the_offer_and_keeps_its_text() {
1491 let row = message_row(&record("a", None, 8, 6), &translation_context(false));
1492 assert!(matches!(
1493 row.translation,
1494 Some(TranslationLine::Offer { ref language_code, .. }) if language_code == "fr"
1495 ));
1496 assert_eq!(
1497 row.blocks,
1498 layout_blocks(&teams_core::linked_message_spans(&record("a", None, 8, 6)))
1499 );
1500 }
1501
1502 #[test]
1503 fn a_shown_translation_replaces_the_body_and_the_original_comes_back() {
1504 let original = message_row(&record("a", None, 8, 6), &translation_context(false)).blocks;
1505 let translated = message_row(&record("a", None, 8, 6), &translation_context(true));
1506 assert_ne!(translated.blocks, original);
1507 assert_eq!(
1508 translated.translation,
1509 Some(TranslationLine::Translated {
1510 language: Some("French".into()),
1511 showing_original: false
1512 })
1513 );
1514 let mut hidden = translation_context(true);
1515 hidden.translation.shown.clear();
1516 let back = message_row(&record("a", None, 8, 6), &hidden);
1517 assert_eq!(back.blocks, original);
1518 assert_eq!(
1519 back.translation,
1520 Some(TranslationLine::Translated {
1521 language: Some("French".into()),
1522 showing_original: true
1523 })
1524 );
1525 }
1526
1527 #[test]
1528 fn own_messages_get_no_offer() {
1529 let mut own = record("a", None, 8, 6);
1530 own.sender_id = Some("me".into());
1531 assert_eq!(
1532 message_row(&own, &translation_context(false)).translation,
1533 None
1534 );
1535 }
1536
1537 #[test]
1538 fn day_header_only_on_first_message_of_a_day() {
1539 let records = vec![
1540 record("a", None, 8, 6),
1541 record("b", None, 9, 6),
1542 record("c", None, 9, 7),
1543 ];
1544 let rows = flat_rows(&records, &context(), false);
1545 let headers: Vec<Option<String>> = rows
1546 .iter()
1547 .map(|row| match row {
1548 Row::Message(message) => message.day_header.clone(),
1549 Row::LoadOlder
1550 | Row::LoadNewer
1551 | Row::Start(_)
1552 | Row::Skeleton(_)
1553 | Row::Post(_) => None,
1554 })
1555 .collect();
1556 assert_eq!(
1557 headers,
1558 vec![Some("Yesterday".into()), None, Some("Today".into())]
1559 );
1560 }
1561
1562 #[test]
1563 fn load_older_row_only_when_more_exists() {
1564 let records = vec![record("a", None, 8, 6)];
1565 assert_eq!(
1566 keys(&flat_rows(&records, &context(), true))[0],
1567 LOAD_OLDER_KEY
1568 );
1569 assert_eq!(keys(&flat_rows(&records, &context(), false)), vec!["a"]);
1570 }
1571
1572 #[test]
1573 fn threads_group_replies_by_root() {
1574 let records = vec![
1575 record("r1", None, 8, 6),
1576 record("r2", None, 9, 6),
1577 record("x1", Some("r1"), 10, 6),
1578 record("x2", Some("r1"), 11, 6),
1579 record("orphan", Some("missing"), 12, 6),
1580 ];
1581 let threads = group_threads(&records);
1582 assert_eq!(threads.len(), 2);
1583 assert_eq!(threads[0].reply_ids, vec!["x1", "x2"]);
1584 assert!(threads[1].reply_ids.is_empty());
1585 }
1586
1587 fn post_of(row: &Row) -> &PostRow {
1588 let Row::Post(post) = row else {
1589 panic!("post expected")
1590 };
1591 post
1592 }
1593
1594 fn reply_by(id: &str, root: &str, sender: &str, hour: u32) -> MessageRecord {
1595 let mut reply = record(id, Some(root), hour, 6);
1596 reply.sender_name = Some(sender.into());
1597 reply
1598 }
1599
1600 #[test]
1601 fn feed_orders_posts_by_last_activity_newest_first() {
1602 let records = vec![
1603 record("r1", None, 8, 6),
1604 record("r2", None, 9, 6),
1605 record("r3", None, 10, 6),
1606 record("x1", Some("r1"), 11, 6),
1607 ];
1608 let rows = thread_list_rows(&records, &context(), false);
1609 assert_eq!(keys(&rows), vec!["r1", "r3", "r2"]);
1610 }
1611
1612 #[test]
1613 fn feed_puts_load_older_at_the_bottom() {
1614 let records = vec![record("r1", None, 8, 6), record("r2", None, 9, 6)];
1615 let rows = thread_list_rows(&records, &context(), true);
1616 assert_eq!(keys(&rows), vec!["r2", "r1", LOAD_OLDER_KEY]);
1617 }
1618
1619 #[test]
1620 fn post_shows_the_last_three_replies_oldest_first() {
1621 let mut records = vec![record("r1", None, 1, 6)];
1622 for hour in 2..=6 {
1623 records.push(reply_by(&format!("x{hour}"), "r1", "Ada Lovelace", hour));
1624 }
1625 records.reverse();
1626 let rows = thread_list_rows(&records, &context(), false);
1627 let post = post_of(&rows[0]);
1628 let shown: Vec<&str> = post
1629 .replies
1630 .iter()
1631 .map(|reply| reply.key.as_str())
1632 .collect();
1633 assert_eq!(shown, vec!["x4", "x5", "x6"]);
1634 assert_eq!(post.hidden_reply_count, 2);
1635 assert_eq!(post.hidden_repliers, vec!["Ada Lovelace"]);
1636 }
1637
1638 #[test]
1639 fn post_without_hidden_replies_has_no_link() {
1640 let records = vec![
1641 record("r1", None, 1, 6),
1642 reply_by("x1", "r1", "Ada", 2),
1643 reply_by("x2", "r1", "Ben", 3),
1644 reply_by("x3", "r1", "Cy", 4),
1645 ];
1646 let rows = thread_list_rows(&records, &context(), false);
1647 assert_eq!(post_of(&rows[0]).hidden_replies_label(), None);
1648 assert_eq!(post_of(&rows[0]).replies.len(), 3);
1649 }
1650
1651 fn label_for(repliers: &[&str]) -> String {
1652 let mut records = vec![record("r1", None, 1, 6)];
1653 for (index, name) in repliers.iter().enumerate() {
1654 records.push(reply_by(&format!("h{index}"), "r1", name, 2 + index as u32));
1655 }
1656 for index in 0..POST_VISIBLE_REPLIES {
1657 records.push(reply_by(
1658 &format!("v{index}"),
1659 "r1",
1660 "Shown",
1661 20 + index as u32,
1662 ));
1663 }
1664 let rows = thread_list_rows(&records, &context(), false);
1665 post_of(&rows[0]).hidden_replies_label().unwrap()
1666 }
1667
1668 #[test]
1669 fn replies_label_names_one_to_three_people() {
1670 assert_eq!(label_for(&["Anna Meier"]), "1 reply from Anna");
1671 assert_eq!(
1672 label_for(&["Anna Meier", "Anna Meier", "Ben Roth"]),
1673 "3 replies from Anna and Ben"
1674 );
1675 assert_eq!(
1676 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Ben Roth"]),
1677 "4 replies from Anna, Ben and Clara"
1678 );
1679 }
1680
1681 #[test]
1682 fn replies_label_counts_the_others_beyond_three_people() {
1683 assert_eq!(
1684 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox", "Eve Ray"]),
1685 "5 replies from Anna, Ben and 3 others"
1686 );
1687 assert_eq!(
1688 label_for(&["Anna Meier", "Ben Roth", "Clara Voss", "Dan Fox"]),
1689 "4 replies from Anna, Ben and 2 others"
1690 );
1691 }
1692
1693 #[test]
1694 fn local_reply_lands_in_its_post_and_local_post_on_top() {
1695 let records = vec![
1696 record("r1", None, 8, 6),
1697 record("r2", None, 9, 6),
1698 reply_by("x1", "r1", "Ada", 10),
1699 ];
1700 let mut rows = thread_list_rows(&records, &context(), true);
1701 let mut pending_reply = message_row(&record("pending-1", Some("r2"), 12, 6), &context());
1702 pending_reply.reply_root = Some("r2".into());
1703 let pending_post = message_row(&record("pending-2", None, 12, 6), &context());
1704 place_local_rows(&mut rows, vec![pending_reply, pending_post]);
1705 assert_eq!(keys(&rows), vec!["pending-2", "r2", "r1", LOAD_OLDER_KEY]);
1706 let replies: Vec<&str> = post_of(&rows[1])
1707 .replies
1708 .iter()
1709 .map(|reply| reply.key.as_str())
1710 .collect();
1711 assert_eq!(replies, vec!["pending-1"]);
1712 }
1713
1714 #[test]
1715 fn local_reply_to_an_unloaded_post_is_not_shown() {
1716 let mut rows = thread_list_rows(&[record("r1", None, 8, 6)], &context(), false);
1717 let mut orphan = message_row(&record("pending-1", Some("gone"), 12, 6), &context());
1718 orphan.reply_root = Some("gone".into());
1719 place_local_rows(&mut rows, vec![orphan]);
1720 assert_eq!(keys(&rows), vec!["r1"]);
1721 }
1722
1723 #[test]
1724 fn subject_reaches_the_post_root() {
1725 let mut with_subject = record("r1", None, 8, 6);
1726 with_subject.subject = Some("Release plan".into());
1727 let rows = thread_list_rows(&[with_subject, record("r2", None, 7, 6)], &context(), false);
1728 assert_eq!(
1729 post_of(&rows[0]).root.subject.as_deref(),
1730 Some("Release plan")
1731 );
1732 assert_eq!(post_of(&rows[1]).root.subject, None);
1733 }
1734
1735 #[test]
1736 fn thread_view_has_root_then_replies() {
1737 let records = vec![
1738 record("r1", None, 8, 6),
1739 record("r2", None, 9, 6),
1740 record("x1", Some("r1"), 10, 6),
1741 ];
1742 assert_eq!(
1743 keys(&thread_rows(&records, "r1", &context())),
1744 vec!["r1", "x1"]
1745 );
1746 }
1747
1748 #[test]
1749 fn reactions_are_counted_in_first_seen_order() {
1750 let reaction = |kind: &str| ReactionInfo {
1751 reaction_type: kind.into(),
1752 user_id: None,
1753 user_name: None,
1754 created_at: None,
1755 };
1756 let chips = reaction_chips(
1757 &[reaction("heart"), reaction("like"), reaction("heart")],
1758 &context(),
1759 );
1760 assert_eq!(chips.len(), 2);
1761 assert_eq!(chips[0].count, 2);
1762 assert_eq!(chips[1].label, reaction_label("like"));
1763 }
1764
1765 #[test]
1766 fn legacy_laugh_and_sad_use_the_teams_glyphs() {
1767 assert_eq!(reaction_label("laugh"), "\u{1F606}");
1768 assert_eq!(reaction_label("sad"), "\u{1F641}");
1769 assert_eq!(reaction_type_for("\u{1F606}"), "laugh");
1770 assert_eq!(reaction_type_for("\u{1F641}"), "sad");
1771 }
1772
1773 #[test]
1774 fn legacy_and_emoji_reactions_share_a_chip() {
1775 let reaction = |kind: &str| ReactionInfo {
1776 reaction_type: kind.into(),
1777 user_id: None,
1778 user_name: Some("Lea".into()),
1779 created_at: None,
1780 };
1781 let chips = reaction_chips(&[reaction("like"), reaction("\u{1F44D}")], &context());
1782 assert_eq!(chips.len(), 1);
1783 assert_eq!(chips[0].count, 2);
1784 }
1785
1786 #[test]
1787 fn skin_tones_share_a_chip_showing_up_to_three_variants() {
1788 let reaction = |kind: &str| ReactionInfo {
1789 reaction_type: kind.into(),
1790 user_id: Some(kind.into()),
1791 user_name: Some("Lea".into()),
1792 created_at: None,
1793 };
1794 let kinds = ["yes-tone2", "👍🏿", "like", "👍🏻", "yes-tone2"];
1795 let mut context = context();
1796 context.skin_tone = 3;
1797 let chips = reaction_chips(&kinds.map(reaction), &context);
1798 assert_eq!(chips.len(), 1);
1799 assert_eq!(chips[0].count, 5);
1800 assert_eq!(chips[0].label, "👍🏼👍🏿👍");
1801 assert_eq!(chips[0].click_glyph, "👍🏽");
1802 }
1803
1804 #[test]
1805 fn own_toned_reaction_matches_the_plain_glyph() {
1806 let mine = ReactionInfo {
1807 reaction_type: "👍🏼".into(),
1808 user_id: Some("me".into()),
1809 user_name: None,
1810 created_at: None,
1811 };
1812 let reactions = vec![mine];
1813 assert!(has_own_reaction(&reactions, "\u{1F44D}", Some("me")));
1814 assert_eq!(
1815 own_reaction_glyph(&reactions, "like", Some("me")).as_deref(),
1816 Some("👍🏼")
1817 );
1818 assert_eq!(reaction_glyph("yes-tone5"), "👍🏿");
1819 }
1820
1821 #[test]
1822 fn reactor_name_falls_back_to_directory_then_unknown() {
1823 let reaction = |user: &str| ReactionInfo {
1824 reaction_type: "like".into(),
1825 user_id: Some(user.into()),
1826 user_name: None,
1827 created_at: None,
1828 };
1829 let mut context = context();
1830 context.names.insert("known".into(), "Priya Nair".into());
1831 let chips = reaction_chips(&[reaction("known"), reaction("other")], &context);
1832 assert_eq!(chips[0].reactors[0].name, "Priya Nair");
1833 assert_eq!(chips[0].reactors[1].name, "Unknown");
1834 }
1835
1836 fn record_by(id: &str, sender: &str, hour: u32, minute: u32, day: u32) -> MessageRecord {
1837 let mut record = record(id, None, hour, day);
1838 record.sender_id = Some(sender.into());
1839 record.created_at = Utc
1840 .with_ymd_and_hms(2026, 10, day, hour, minute, 0)
1841 .unwrap();
1842 record
1843 }
1844
1845 fn series_of(rows: &[Row]) -> Vec<(bool, bool)> {
1846 rows.iter()
1847 .filter_map(|row| match row {
1848 Row::Message(message) => Some((message.series.has_prev, message.series.has_next)),
1849 Row::LoadOlder
1850 | Row::LoadNewer
1851 | Row::Start(_)
1852 | Row::Skeleton(_)
1853 | Row::Post(_) => None,
1854 })
1855 .collect()
1856 }
1857
1858 #[test]
1859 fn series_joins_same_sender_within_five_minutes() {
1860 let records = vec![
1861 record_by("a", "ada", 9, 0, 7),
1862 record_by("b", "ada", 9, 4, 7),
1863 record_by("c", "ada", 9, 20, 7),
1864 record_by("d", "bob", 9, 21, 7),
1865 record_by("e", "ada", 9, 22, 7),
1866 ];
1867 let rows = flat_rows(&records, &context(), false);
1868 assert_eq!(
1869 series_of(&rows),
1870 vec![
1871 (false, true),
1872 (true, false),
1873 (false, false),
1874 (false, false),
1875 (false, false)
1876 ]
1877 );
1878 }
1879
1880 #[test]
1881 fn series_window_ends_exactly_at_the_gap_constant() {
1882 let gap = SERIES_GAP_MINUTES as u32;
1883 let records = vec![
1884 record_by("a", "ada", 9, 0, 7),
1885 record_by("b", "ada", 9, gap - 1, 7),
1886 record_by("c", "ada", 9, 2 * gap - 1 + gap, 7),
1887 ];
1888 let rows = flat_rows(&records, &context(), false);
1889 assert_eq!(
1890 series_of(&rows),
1891 vec![(false, true), (true, false), (false, false)]
1892 );
1893 }
1894
1895 #[test]
1896 fn series_breaks_at_a_new_day() {
1897 let records = vec![
1898 record_by("a", "ada", 23, 58, 6),
1899 record_by("b", "ada", 0, 1, 7),
1900 ];
1901 let rows = flat_rows(&records, &context(), false);
1902 assert_eq!(series_of(&rows), vec![(false, false), (false, false)]);
1903 }
1904
1905 fn corners(own: bool, has_prev: bool, has_next: bool) -> [f32; 4] {
1906 let corners = bubble_corners(own, Series { has_prev, has_next });
1907 [
1908 corners.top_left,
1909 corners.top_right,
1910 corners.bottom_right,
1911 corners.bottom_left,
1912 ]
1913 }
1914
1915 #[test]
1916 fn corners_match_the_mockup_for_other_senders() {
1917 assert_eq!(corners(false, false, false), [14., 14., 14., 14.]);
1918 assert_eq!(corners(false, false, true), [14., 14., 14., 4.]);
1919 assert_eq!(corners(false, true, true), [4., 14., 14., 4.]);
1920 assert_eq!(corners(false, true, false), [4., 14., 14., 14.]);
1921 }
1922
1923 #[test]
1924 fn corners_match_the_mockup_for_own_messages() {
1925 assert_eq!(corners(true, false, false), [14., 14., 14., 14.]);
1926 assert_eq!(corners(true, false, true), [14., 14., 4., 14.]);
1927 assert_eq!(corners(true, true, true), [14., 4., 4., 14.]);
1928 assert_eq!(corners(true, true, false), [14., 4., 14., 14.]);
1929 }
1930
1931 #[test]
1932 fn own_reaction_is_marked() {
1933 let reaction = |user: &str| ReactionInfo {
1934 reaction_type: "like".into(),
1935 user_id: Some(user.into()),
1936 user_name: None,
1937 created_at: None,
1938 };
1939 let mut context = context();
1940 context.my_user_id = Some("me".into());
1941 let chips = reaction_chips(&[reaction("x"), reaction("me")], &context);
1942 assert!(chips[0].mine);
1943 assert!(!reaction_chips(&[reaction("x")], &context)[0].mine);
1944 }
1945
1946 fn strings(values: &[&str]) -> Vec<String> {
1947 values.iter().map(|value| (*value).to_owned()).collect()
1948 }
1949
1950 #[test]
1951 fn diff_detects_append_prepend_and_replace() {
1952 let base = strings(&["a", "b"]);
1953 assert_eq!(diff_keys(&base, &base), None);
1954 assert_eq!(
1955 diff_keys(&base, &strings(&["a", "b", "c"])),
1956 Some(Splice {
1957 range: 2..2,
1958 count: 1
1959 })
1960 );
1961 assert_eq!(
1962 diff_keys(&base, &strings(&["x", "a", "b"])),
1963 Some(Splice {
1964 range: 0..0,
1965 count: 1
1966 })
1967 );
1968 assert_eq!(
1969 diff_keys(
1970 &strings(&["load-older", "a"]),
1971 &strings(&["load-older", "x", "y", "a"])
1972 ),
1973 Some(Splice {
1974 range: 1..1,
1975 count: 2
1976 })
1977 );
1978 assert_eq!(
1979 diff_keys(&strings(&["load-older", "a"]), &strings(&["a"])),
1980 Some(Splice {
1981 range: 0..1,
1982 count: 0
1983 })
1984 );
1985 assert_eq!(
1986 diff_keys(&base, &strings(&["x"])),
1987 Some(Splice {
1988 range: 0..2,
1989 count: 1
1990 })
1991 );
1992 }
1993
1994 #[test]
1995 fn changed_indices_find_edited_rows() {
1996 let old = flat_rows(
1997 &[record("a", None, 8, 6), record("b", None, 9, 6)],
1998 &context(),
1999 false,
2000 );
2001 let mut edited = record("b", None, 9, 6);
2002 edited.body_html = "<p>changed</p>".into();
2003 let new = flat_rows(&[record("a", None, 8, 6), edited], &context(), false);
2004 assert_eq!(changed_indices(&old, &new), vec![1]);
2005 }
2006
2007 fn call_record(id: &str, hour: u32, event: CallEvent) -> MessageRecord {
2008 MessageRecord {
2009 sender_id: None,
2010 sender_name: None,
2011 body_html: String::new(),
2012 call_event_json: Some(event.to_json()),
2013 ..record(id, None, hour, 7)
2014 }
2015 }
2016
2017 fn call_event_of(
2018 phase: CallPhase,
2019 call_id: &str,
2020 initiator: &str,
2021 seconds: Option<u64>,
2022 participants: &[&str],
2023 ) -> CallEvent {
2024 CallEvent {
2025 phase,
2026 call_type: CallType::Call,
2027 call_id: call_id.into(),
2028 duration_seconds: seconds,
2029 initiator_id: Some(initiator.into()),
2030 initiator_name: Some(format!("Name {initiator}")),
2031 participant_ids: participants.iter().map(|id| (*id).to_owned()).collect(),
2032 participant_names: Vec::new(),
2033 recording: None,
2034 }
2035 }
2036
2037 fn call_context() -> RowContext {
2038 let mut context = context();
2039 context.my_user_id = Some("me".into());
2040 context
2041 }
2042
2043 fn call_of(row: &Row) -> &CallCard {
2044 let Row::Message(message) = row else {
2045 panic!("not a message row")
2046 };
2047 message.call.as_ref().expect("call row")
2048 }
2049
2050 #[test]
2051 fn started_call_is_hidden_when_the_same_call_ended() {
2052 let records = [
2053 call_record(
2054 "s1",
2055 9,
2056 call_event_of(CallPhase::Started, "one", "u", None, &[]),
2057 ),
2058 call_record(
2059 "e1",
2060 10,
2061 call_event_of(CallPhase::Ended, "one", "u", Some(723), &["u", "me"]),
2062 ),
2063 call_record(
2064 "s2",
2065 11,
2066 call_event_of(CallPhase::Started, "two", "u", None, &[]),
2067 ),
2068 ];
2069 let rows = flat_rows(&records, &call_context(), false);
2070 assert_eq!(keys(&rows), ["e1", "s2"]);
2071 assert_eq!(call_of(&rows[0]).title, "Call ended");
2072 assert_eq!(call_of(&rows[0]).detail, "12m 3s \u{b7} 10:00");
2073 assert_eq!(call_of(&rows[1]).title, "Call started");
2074 assert_eq!(call_of(&rows[1]).detail, "11:00");
2075 assert!(call_of(&rows[1]).started);
2076 }
2077
2078 #[test]
2079 fn only_the_newest_open_start_can_be_joined() {
2080 let records = [
2081 call_record(
2082 "old",
2083 9,
2084 call_event_of(CallPhase::Started, "lost", "u", None, &[]),
2085 ),
2086 call_record(
2087 "new",
2088 11,
2089 call_event_of(CallPhase::Started, "live", "u", None, &[]),
2090 ),
2091 ];
2092 let rows = flat_rows(&records, &call_context(), false);
2093 assert_eq!(keys(&rows), ["old", "new"]);
2094 assert!(!call_of(&rows[0]).started);
2095 assert!(call_of(&rows[1]).started);
2096 }
2097
2098 #[test]
2099 fn missed_call_needs_an_incoming_call_with_fewer_than_two_participants() {
2100 let rows = flat_rows(
2101 &[
2102 call_record(
2103 "incoming",
2104 9,
2105 call_event_of(CallPhase::Ended, "a", "u", Some(60), &["u"]),
2106 ),
2107 call_record(
2108 "outgoing",
2109 10,
2110 call_event_of(CallPhase::Ended, "b", "me", Some(60), &["me"]),
2111 ),
2112 call_record(
2113 "answered",
2114 11,
2115 call_event_of(CallPhase::Ended, "c", "u", Some(60), &["u", "me"]),
2116 ),
2117 ],
2118 &call_context(),
2119 false,
2120 );
2121 let missed = call_of(&rows[0]);
2122 assert!(missed.missed);
2123 assert_eq!(missed.title, "Missed call");
2124 assert_eq!(missed.detail, "09:00");
2125 assert_eq!(missed.icon, CallIcon::Missed);
2126 let outgoing = call_of(&rows[1]);
2127 assert!(!outgoing.missed);
2128 assert_eq!(outgoing.title, "Call ended");
2129 assert_eq!(outgoing.detail, "1m \u{b7} 10:00");
2130 assert!(!call_of(&rows[2]).missed);
2131 }
2132
2133 #[test]
2134 fn call_side_follows_the_initiator() {
2135 let rows = flat_rows(
2136 &[
2137 call_record(
2138 "mine",
2139 9,
2140 call_event_of(CallPhase::Ended, "a", "me", Some(5), &["me", "u"]),
2141 ),
2142 call_record(
2143 "theirs",
2144 10,
2145 call_event_of(CallPhase::Ended, "b", "u", Some(5), &["me", "u"]),
2146 ),
2147 ],
2148 &call_context(),
2149 false,
2150 );
2151 let sides: Vec<(bool, Option<&str>)> = rows
2152 .iter()
2153 .map(|row| match row {
2154 Row::Message(message) => (message.own, message.sender_id.as_deref()),
2155 _ => unreachable!(),
2156 })
2157 .collect();
2158 assert_eq!(sides, [(true, Some("me")), (false, Some("u"))]);
2159 }
2160
2161 #[test]
2162 fn meeting_events_use_the_video_icon_and_meeting_titles() {
2163 let mut event = call_event_of(CallPhase::Ended, "m", "u", Some(3723), &["u", "me", "x"]);
2164 event.call_type = CallType::Meeting;
2165 let rows = flat_rows(&[call_record("m", 9, event)], &call_context(), false);
2166 let card = call_of(&rows[0]);
2167 assert_eq!(card.title, "Meeting ended");
2168 assert_eq!(card.icon, CallIcon::Video);
2169 assert_eq!(card.detail, "1h 2m 3s \u{b7} 09:00");
2170 }
2171
2172 #[test]
2173 fn call_rows_never_join_a_series() {
2174 let mut records = vec![
2175 record_by("a", "u", 9, 0, 7),
2176 call_record(
2177 "c",
2178 9,
2179 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
2180 ),
2181 ];
2182 records.push(record_by("b", "u", 9, 1, 7));
2183 let rows = flat_rows(&records, &call_context(), false);
2184 let series: Vec<Series> = rows
2185 .iter()
2186 .map(|row| match row {
2187 Row::Message(message) => message.series,
2188 _ => unreachable!(),
2189 })
2190 .collect();
2191 assert!(series.iter().all(|series| *series == Series::default()));
2192 }
2193
2194 fn fixture_records(name: &str) -> Vec<MessageRecord> {
2195 let path = format!(
2196 "{}/../core/tests/fixtures/call_events/{name}",
2197 env!("CARGO_MANIFEST_DIR")
2198 );
2199 let thread: graph::Message =
2200 serde_json::from_str(&std::fs::read_to_string(path).unwrap()).unwrap();
2201 std::iter::once(&thread)
2202 .chain(&thread.replies)
2203 .filter_map(|message| teams_core::message_record("channel", message))
2204 .collect()
2205 }
2206
2207 fn feed_post(row: &Row) -> &PostRow {
2208 let Row::Post(post) = row else {
2209 panic!("not a post")
2210 };
2211 post
2212 }
2213
2214 #[test]
2215 fn posts_from_others_after_the_read_horizon_are_new() {
2216 let records = vec![
2217 record_by("old", "u", 9, 0, 7),
2218 record_by("fresh", "u", 11, 0, 7),
2219 record_by("mine", "me", 12, 0, 7),
2220 ];
2221 let read_until = Utc.with_ymd_and_hms(2026, 10, 7, 10, 0, 0).unwrap();
2222 let new: Vec<(String, bool)> = thread_list_rows(&records, &call_context(), false)
2223 .into_iter()
2224 .map(|row| {
2225 let Row::Post(mut post) = row else {
2226 panic!("not a post")
2227 };
2228 post.mark_new_after(read_until);
2229 (post.root.key.clone(), post.is_new)
2230 })
2231 .collect();
2232 assert!(new.contains(&("fresh".to_owned(), true)));
2233 assert!(new.contains(&("old".to_owned(), false)));
2234 assert!(new.contains(&("mine".to_owned(), false)));
2235 }
2236
2237 #[test]
2238 fn meet_now_root_is_a_post_with_the_ended_meeting_card() {
2239 let records = fixture_records("channel_adhoc_meeting.json");
2240 assert_eq!(records.len(), 2);
2241 let rows = thread_list_rows(&records, &call_context(), false);
2242 assert_eq!(rows.len(), 1);
2243 let post = feed_post(&rows[0]);
2244 assert_eq!(post.root.key, records[0].message_id);
2245 assert!(post.replies.is_empty());
2246 assert_eq!(post.hidden_reply_count, 0);
2247 let card = post.root.call.as_ref().unwrap();
2248 assert_eq!(card.title, "Meeting ended");
2249 assert!(card.detail.starts_with("3h 19m 35s"));
2250 assert!(!card.started);
2251 assert_eq!(card.participants.len(), 3);
2252 assert_eq!(card.extra_participants, 0);
2253 }
2254
2255 #[test]
2256 fn meet_now_root_without_an_end_can_be_joined() {
2257 let mut records = fixture_records("channel_adhoc_meeting.json");
2258 records.truncate(1);
2259 let rows = thread_list_rows(&records, &call_context(), false);
2260 let card = feed_post(&rows[0]).root.call.clone().unwrap();
2261 assert_eq!(card.title, "Meeting started");
2262 assert!(card.started);
2263 }
2264
2265 #[test]
2266 fn scheduled_meeting_post_keeps_call_notices_in_the_thread() {
2267 let mut records = fixture_records("channel_scheduled_meeting.json");
2268 records.sort_by_key(|record| record.created_at);
2269 assert_eq!(records.len(), 3);
2270 let rows = thread_list_rows(&records, &call_context(), false);
2271 let post = feed_post(&rows[0]);
2272 assert!(post.root.call.is_none());
2273 assert!(post.replies.is_empty());
2274 let thread = thread_rows(&records, &records[0].message_id, &call_context());
2275 let titles: Vec<String> = thread
2276 .iter()
2277 .filter_map(|row| match row {
2278 Row::Message(message) => message.call.as_ref().map(|call| call.title.clone()),
2279 _ => None,
2280 })
2281 .collect();
2282 assert_eq!(titles, ["Meeting started", "Meeting ended"]);
2283 }
2284
2285 #[test]
2286 fn saved_recording_shows_in_the_channel_feed_as_a_reply() {
2287 let mut records = fixture_records("channel_adhoc_meeting.json");
2288 let root_id = records[0].message_id.clone();
2289 let page: serde_json::Value = serde_json::from_str(
2290 &std::fs::read_to_string(format!(
2291 "{}/../core/tests/fixtures/call_events/meeting_chat_recording.json",
2292 env!("CARGO_MANIFEST_DIR")
2293 ))
2294 .unwrap(),
2295 )
2296 .unwrap();
2297 for message in page["value"].as_array().unwrap() {
2298 let message: graph::Message = serde_json::from_value(message.clone()).unwrap();
2299 let mut record = teams_core::message_record("channel", &message).unwrap();
2300 record.reply_to_id = Some(root_id.clone());
2301 records.push(record);
2302 }
2303 let rows = thread_list_rows(&records, &call_context(), false);
2304 let post = feed_post(&rows[0]);
2305 assert_eq!(post.replies.len(), 1);
2306 assert_eq!(post.hidden_reply_count, 0);
2307 let saved = post.replies[0].call.as_ref().unwrap();
2308 assert_eq!(saved.icon, CallIcon::Saved);
2309 assert_eq!(
2310 saved.notice.as_ref().unwrap().text,
2311 "Recording has been saved to OneDrive."
2312 );
2313 let thread = thread_rows(&records, &root_id, &call_context());
2314 let calls = thread
2315 .iter()
2316 .filter(|row| matches!(row, Row::Message(message) if message.call.is_some()))
2317 .count();
2318 assert_eq!(calls, 7);
2319 }
2320
2321 #[test]
2322 fn thread_lists_leave_call_events_out() {
2323 let records = [call_record(
2324 "c",
2325 9,
2326 call_event_of(CallPhase::Ended, "x", "u", Some(5), &["u", "me"]),
2327 )];
2328 assert!(thread_list_rows(&records, &call_context(), false).is_empty());
2329 }
2330}