BlueGit

ict rusty-teams

Files

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

rows.rs

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