BlueGit

ict rusty-teams

Files

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

rows.rs

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