BlueGit

ict rusty-teams

Files

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

rows.rs

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