BlueGit

ict rusty-teams

Files

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

rows.rs

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