BlueGit

ict rusty-teams

Files

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

rows.rs

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