BlueGit

ict rusty-teams

Files

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

rows.rs

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