BlueGit

ict rusty-teams

Files

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

rows.rs

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