BlueGit

ict rusty-teams

Files

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

rows.rs

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