BlueGit

ict rusty-teams

Files

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

rows.rs

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