BlueGit

ict rusty-teams

Files

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

rows.rs

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