BlueGit

ict rusty-teams

Files

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

demo.rs

demo.rs 91.3 KiB Download Raw
1use std::collections::HashMap;
2use std::path::PathBuf;
3use std::sync::OnceLock;
4use std::time::Instant;
5
6use chrono::{DateTime, Duration, Local, TimeZone, Utc};
7use gpui_kit::{App, Entity};
8use store::{
9 ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications,
10 ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord,
11 Store, TeamLayoutRecord, TeamRecord,
12};
13use teams_core::{
14 ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot,
15 CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings,
16 LinkPreview, MentionCandidate, NOTES_CHAT_ID, PersonCandidate, PersonSource, PinnedMessage,
17 SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus,
18};
19
20use crate::app_state::{AppState, Selection};
21use crate::card_actions::{CardAnswer, CardTask};
22use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind};
23use crate::demo_gifs;
24use crate::message_actions::ForwardSource;
25
26static SEARCHABLE_GIFS: OnceLock<Vec<Gif>> = OnceLock::new();
27
28pub const DEMO_USER_ID: &str = "demo-me";
29const DEMO_USER_NAME: &str = "Dana Demo";
30const DEMO_USER_EMAIL: &str = "dana.demo@example.com";
31const DEMO_TIME_ZONE: &str = "W. Europe Standard Time";
32const PHOTO_SIZE: usize = 48;
33const DEMO_PHOTO_SIDE: usize = 240;
34const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
35const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
36const STAGING_SIZE: (usize, usize) = (960, 540);
37const LINK_IMAGE_KEY: &str =
38 "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=demo";
39const LINK_IMAGE_SIZE: (u32, u32) = (320, 180);
40const DEMO_CLIP_URL: &str = "https://eu-api.asm.skype.com/v1/objects/0-weu-d1-democlip/views/video";
41const DEMO_CLIP_THUMBNAIL_KEY: &str =
42 "https://eu-api.asm.skype.com/v1/objects/0-weu-d1-democlip/views/thumbnail";
43const PRIORITY_CHAT: &str = "demo-chat-priya";
44const BOT_CHAT: &str = "demo-chat-wiki-bot";
45const BOT_NAME: &str = "Wiki Bot";
46const ECHO_CHAT: &str = "demo-chat-echo";
47const ECHO_BOT_ID: &str = "28:demo-echo";
48const BOT_APP_NAME: &str = "Wiki Cloud";
49const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";
50const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
51const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
52const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
53const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
54const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
55 (
56 MARA_ID,
57 "Mara Lindqvist",
58 "Product Owner",
59 "mara.lindqvist@example.com",
60 ),
61 (
62 JONAS_ID,
63 "Jonas Ortega",
64 "Backend Engineer",
65 "jonas.ortega@example.com",
66 ),
67 (
68 PRIYA_ID,
69 "Priya Nair",
70 "Engineering Manager",
71 "priya.nair@example.com",
72 ),
73 (
74 LEA_ID,
75 "Lea Schneider",
76 "Customer Success",
77 "lea.schneider@example.com",
78 ),
79 (
80 TOBIAS_ID,
81 "Tobias Klein",
82 "Support Engineer",
83 "tobias.klein@example.com",
84 ),
85];
86
87struct Palette {
88 background: [u8; 3],
89 skin: [u8; 3],
90 hair: [u8; 3],
91 shirt: [u8; 3],
92}
93
94const MARA: Palette = Palette {
95 background: [0x3f, 0x5f, 0x7a],
96 skin: [0xe0, 0xb2, 0x93],
97 hair: [0xd9, 0xa4, 0x41],
98 shirt: [0x1e, 0x29, 0x3b],
99};
100const PRIYA: Palette = Palette {
101 background: [0x4b, 0x3b, 0x5c],
102 skin: [0x9a, 0x6a, 0x4a],
103 hair: [0x1c, 0x19, 0x17],
104 shirt: [0xbe, 0x12, 0x3c],
105};
106const TOBIAS: Palette = Palette {
107 background: [0x3b, 0x4a, 0x3f],
108 skin: [0xf1, 0xc7, 0xa5],
109 hair: [0x57, 0x53, 0x4e],
110 shirt: [0x0f, 0x76, 0x6e],
111};
112
113pub const MARA_ID: &str = "demo-mara";
114pub const JONAS_ID: &str = "demo-jonas";
115pub const PRIYA_ID: &str = "demo-priya";
116pub const LEA_ID: &str = "demo-lea";
117pub const TOBIAS_ID: &str = "demo-tobias";
118
119const DEMO_PRIVATE_CHANNEL: &str = "Runbooks";
120const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
121 (
122 "demo-team-1",
123 "Platform",
124 ["General", "Incidents", "Releases"],
125 ),
126 ("demo-team-2", "Product", ["General", "Roadmap", "Feedback"]),
127 (
128 "demo-team-3",
129 "Operations",
130 ["General", "On call", "Runbooks"],
131 ),
132 (
133 "demo-team-4",
134 "Archive 2025",
135 ["General", "Trade fair", "Office move"],
136 ),
137];
138const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
139const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
140const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
141const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [
142 ("demo-channel-1-2", mentions(2, 0, 0)),
143 ("demo-channel-2-1", mentions(0, 1, 0)),
144 (DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)),
145 ("demo-channel-4-2", mentions(1, 0, 1)),
146];
147const PINNED_CHANNEL: &str = "demo-channel-1-1";
148const PINNED_POST: &str = "t3";
149
150const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions {
151 ChannelMentions {
152 personal,
153 channel,
154 team,
155 }
156}
157const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [
158 (
159 "demo-channel-1-1",
160 ChannelNotificationLevel::BannerAndFeed,
161 false,
162 ),
163 (
164 "demo-channel-1-2",
165 ChannelNotificationLevel::BannerAndFeed,
166 true,
167 ),
168 ("demo-channel-1-3", ChannelNotificationLevel::Off, false),
169 ("demo-channel-2-2", ChannelNotificationLevel::Off, false),
170];
171
172const UNREAD_CHAT: &str = "demo-chat-atlas";
173const RELEASE_CHAT: &str = "demo-chat-release";
174const PINNED_MESSAGE: &str = "m5b";
175const FRENCH_MESSAGE: &str = "m10";
176const SPANISH_MESSAGE: &str = "m11";
177const SAVED_MESSAGES: [&str; 2] = ["m4", "m5c"];
178const FORWARD_ITEMTYPE: &str = "http://schema.skype.com/Forward";
179const FAVORITES_ID: &str = "demo-folder-favorites";
180const CUSTOMERS_FOLDER: &str = "demo-folder-customers";
181const ATLAS_FOLDER: &str = "demo-folder-atlas";
182const TODO_FOLDER: &str = "demo-folder-todo";
183const MUTED_CHATS: [&str; 6] = [
184 "demo-chat-muted-lunch",
185 "demo-chat-muted-offsite",
186 "demo-chat-muted-kudos",
187 "demo-chat-muted-bikes",
188 "demo-chat-muted-book",
189 "demo-chat-muted-games",
190];
191
192fn member(user_id: &str, name: &str) -> MemberRecord {
193 MemberRecord {
194 user_id: Some(user_id.to_owned()),
195 display_name: name.to_owned(),
196 }
197}
198
199fn people(extra: &[(&str, &str)]) -> Vec<MemberRecord> {
200 std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
201 .chain(extra.iter().map(|(id, name)| member(id, name)))
202 .collect()
203}
204
205pub fn at(days_ago: i64, hour: u32, minute: u32) -> DateTime<Utc> {
206 let day = Local::now().date_naive() - Duration::days(days_ago);
207 let local = day.and_hms_opt(hour, minute, 0).expect("valid time");
208 Local
209 .from_local_datetime(&local)
210 .earliest()
211 .map_or_else(Utc::now, |time| time.with_timezone(&Utc))
212}
213
214struct DemoChat {
215 id: &'static str,
216 kind: &'static str,
217 title: &'static str,
218 members: Vec<MemberRecord>,
219 time: DateTime<Utc>,
220 unread: bool,
221 preview: Option<(&'static str, &'static str, &'static str)>,
222 deleted: bool,
223}
224
225fn demo_chats() -> Vec<DemoChat> {
226 let group = |extra: &[(&str, &str)]| people(extra);
227 vec![
228 DemoChat {
229 id: BOT_CHAT,
230 kind: "oneOnOne",
231 title: BOT_NAME,
232 members: people(&[]),
233 time: at(0, 13, 45),
234 unread: true,
235 preview: Some(("", BOT_NAME, "Mara Lindqvist edited your page")),
236 deleted: false,
237 },
238 DemoChat {
239 id: "demo-chat-mara",
240 kind: "oneOnOne",
241 title: "Mara Lindqvist",
242 members: people(&[(MARA_ID, "Mara Lindqvist")]),
243 time: at(0, 13, 40),
244 unread: false,
245 preview: Some((MARA_ID, "Mara Lindqvist", "Sure, 2 pm works")),
246 deleted: false,
247 },
248 DemoChat {
249 id: RELEASE_CHAT,
250 kind: "group",
251 title: "Release planning",
252 members: group(&[
253 (MARA_ID, "Mara Lindqvist"),
254 (JONAS_ID, "Jonas Ortega"),
255 (PRIYA_ID, "Priya Nair"),
256 (LEA_ID, "Lea Schneider"),
257 ]),
258 time: at(0, 13, 35),
259 unread: false,
260 preview: Some((
261 DEMO_USER_ID,
262 DEMO_USER_NAME,
263 "Build 42 is green, see pipeline",
264 )),
265 deleted: false,
266 },
267 DemoChat {
268 id: "demo-chat-customer-1",
269 kind: "group",
270 title: "Customer North - Operations",
271 members: group(&[(LEA_ID, "Lea Schneider"), (TOBIAS_ID, "Tobias Klein")]),
272 time: at(0, 12, 50),
273 unread: true,
274 preview: Some((LEA_ID, "Lea Schneider", "Access is enabled now")),
275 deleted: false,
276 },
277 DemoChat {
278 id: "demo-chat-customer-2",
279 kind: "group",
280 title: "Customer South - Rollout",
281 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
282 time: at(0, 9, 5),
283 unread: true,
284 preview: Some((JONAS_ID, "Jonas Ortega", "Meeting is set for Friday")),
285 deleted: false,
286 },
287 DemoChat {
288 id: "demo-chat-customer-3",
289 kind: "group",
290 title: "Customer West - Support",
291 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
292 time: at(1, 16, 0),
293 unread: false,
294 preview: Some((TOBIAS_ID, "Tobias Klein", "Ticket is closed")),
295 deleted: false,
296 },
297 DemoChat {
298 id: "demo-chat-customer-4",
299 kind: "group",
300 title: "Customer East - Pilot",
301 members: group(&[(MARA_ID, "Mara Lindqvist"), (PRIYA_ID, "Priya Nair")]),
302 time: at(3, 10, 0),
303 unread: false,
304 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "I'll send the documents")),
305 deleted: false,
306 },
307 DemoChat {
308 id: "demo-chat-atlas",
309 kind: "group",
310 title: "Atlas core team",
311 members: group(&[
312 (PRIYA_ID, "Priya Nair"),
313 (LEA_ID, "Lea Schneider"),
314 (MARA_ID, "Mara Lindqvist"),
315 ]),
316 time: at(0, 13, 12),
317 unread: true,
318 preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")),
319 deleted: false,
320 },
321 DemoChat {
322 id: ECHO_CHAT,
323 kind: "oneOnOne",
324 title: "Echo",
325 members: people(&[(ECHO_BOT_ID, "Echo")]),
326 time: at(0, 11, 20),
327 unread: false,
328 preview: Some(("", "", "Recording is ready")),
329 deleted: false,
330 },
331 DemoChat {
332 id: NOTES_CHAT_ID,
333 kind: "oneOnOne",
334 title: "Dana Demo (You)",
335 members: people(&[]),
336 time: at(0, 8, 20),
337 unread: false,
338 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Release notes draft")),
339 deleted: false,
340 },
341 DemoChat {
342 id: "demo-chat-jonas",
343 kind: "oneOnOne",
344 title: "Jonas Ortega",
345 members: people(&[(JONAS_ID, "Jonas Ortega")]),
346 time: at(0, 11, 2),
347 unread: false,
348 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Thanks, it's merged")),
349 deleted: false,
350 },
351 DemoChat {
352 id: "demo-chat-priya",
353 kind: "oneOnOne",
354 title: "Priya Nair",
355 members: people(&[(PRIYA_ID, "Priya Nair")]),
356 time: at(0, 10, 47),
357 unread: false,
358 preview: Some((PRIYA_ID, "Priya Nair", "Sent an image")),
359 deleted: false,
360 },
361 DemoChat {
362 id: "demo-chat-tobias",
363 kind: "oneOnOne",
364 title: "Tobias Klein",
365 members: people(&[(TOBIAS_ID, "Tobias Klein")]),
366 time: at(2, 9, 30),
367 unread: false,
368 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Forwarded a message")),
369 deleted: false,
370 },
371 DemoChat {
372 id: "demo-chat-allhands",
373 kind: "group",
374 title: "All-hands announcements",
375 members: group(&[(LEA_ID, "Lea Schneider"), (MARA_ID, "Mara Lindqvist")]),
376 time: at(0, 9, 0),
377 unread: true,
378 preview: Some((LEA_ID, "Lea Schneider", "New vacation policy from November")),
379 deleted: false,
380 },
381 DemoChat {
382 id: "demo-chat-design",
383 kind: "group",
384 title: "Design review",
385 members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),
386 time: at(2, 15, 0),
387 unread: false,
388 preview: Some((MARA_ID, "Mara Lindqvist", "alt")),
389 deleted: true,
390 },
391 DemoChat {
392 id: "demo-chat-quarterly",
393 kind: "group",
394 title: "Quarterly numbers, finance review and planning 2027",
395 members: group(&[(LEA_ID, "Lea Schneider"), (JONAS_ID, "Jonas Ortega")]),
396 time: at(4, 11, 0),
397 unread: false,
398 preview: Some((LEA_ID, "Lea Schneider", "Draft attached")),
399 deleted: false,
400 },
401 DemoChat {
402 id: "demo-chat-meeting-standup",
403 kind: "meeting",
404 title: "Daily standup",
405 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
406 time: at(0, 9, 45),
407 unread: true,
408 preview: Some(("", "", "Recording is ready")),
409 deleted: false,
410 },
411 DemoChat {
412 id: "demo-chat-meeting-retro",
413 kind: "meeting",
414 title: "Sprint retrospective",
415 members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),
416 time: at(3, 15, 30),
417 unread: false,
418 preview: Some((MARA_ID, "Mara Lindqvist", "Notes are in the wiki")),
419 deleted: false,
420 },
421 DemoChat {
422 id: "demo-chat-muted-lunch",
423 kind: "group",
424 title: "Lunch crew",
425 members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
426 time: at(0, 12, 5),
427 unread: true,
428 preview: Some((JONAS_ID, "Jonas Ortega", "\u{1F4F7} GIF")),
429 deleted: false,
430 },
431 DemoChat {
432 id: "demo-chat-muted-offsite",
433 kind: "group",
434 title: "Team offsite 2027",
435 members: group(&[(LEA_ID, "Lea Schneider"), (LEA_ID, "Lea Schneider")]),
436 time: at(1, 16, 20),
437 unread: false,
438 preview: Some((LEA_ID, "Lea Schneider", "Voting closes tomorrow")),
439 deleted: false,
440 },
441 DemoChat {
442 id: "demo-chat-muted-kudos",
443 kind: "group",
444 title: "Kudos corner",
445 members: group(&[(MARA_ID, "Mara Lindqvist"), (LEA_ID, "Lea Schneider")]),
446 time: at(2, 10, 0),
447 unread: false,
448 preview: Some((MARA_ID, "Mara Lindqvist", "Thanks for the release!")),
449 deleted: false,
450 },
451 DemoChat {
452 id: "demo-chat-muted-bikes",
453 kind: "group",
454 title: "Bike to work",
455 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
456 time: at(4, 8, 15),
457 unread: false,
458 preview: Some((TOBIAS_ID, "Tobias Klein", "Sent a file")),
459 deleted: false,
460 },
461 DemoChat {
462 id: "demo-chat-muted-book",
463 kind: "group",
464 title: "Book club",
465 members: group(&[(PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider")]),
466 time: at(6, 19, 40),
467 unread: false,
468 preview: Some((PRIYA_ID, "Priya Nair", "Sent a card")),
469 deleted: false,
470 },
471 DemoChat {
472 id: "demo-chat-muted-games",
473 kind: "group",
474 title: "Board game night",
475 members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]),
476 time: at(9, 18, 0),
477 unread: false,
478 preview: Some((JONAS_ID, "Jonas Ortega", "Who brings the snacks?")),
479 deleted: false,
480 },
481 ]
482}
483
484pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCandidate> {
485 let needle = query.trim().to_lowercase();
486 let matches = |name: &str| needle.is_empty() || name.to_lowercase().contains(&needle);
487 let people = PEOPLE_DIRECTORY
488 .iter()
489 .filter(|(_, name, _, _)| matches(name))
490 .map(|(user_id, name, job_title, mail)| {
491 MentionCandidate::Person(PersonCandidate {
492 user_id: (*user_id).to_owned(),
493 display_name: (*name).to_owned(),
494 mail: Some((*mail).to_owned()),
495 job_title: Some((*job_title).to_owned()),
496 source: PersonSource::Member,
497 })
498 });
499 let everyone = demo_chats()
500 .into_iter()
501 .find(|chat| chat.id == conversation_id && chat.kind == "group")
502 .map(|chat| MentionCandidate::Everyone {
503 chat_id: chat.id.to_owned(),
504 })
505 .filter(|candidate| matches(candidate.display_name()));
506 let scope: Vec<MentionCandidate> = if conversation_id.starts_with("demo-channel") {
507 [
508 MentionCandidate::Channel {
509 channel_id: conversation_id.to_owned(),
510 name: "General".to_owned(),
511 },
512 MentionCandidate::Team {
513 team_id: "demo-team-1".to_owned(),
514 name: "Platform".to_owned(),
515 },
516 MentionCandidate::Tag {
517 tag_id: "demo-tag-design".to_owned(),
518 name: "Designers".to_owned(),
519 member_count: Some(3),
520 },
521 ]
522 .into_iter()
523 .filter(|candidate| matches(candidate.display_name()))
524 .collect()
525 } else {
526 Vec::new()
527 };
528 everyone.into_iter().chain(people).chain(scope).collect()
529}
530
531pub fn send_in_chat(
532 chat: &ChatRecord,
533 preview: &str,
534 html: &str,
535 now: DateTime<Utc>,
536) -> (ChatRecord, MessageRecord) {
537 let mut chat = chat.clone();
538 chat.last_message_at = Some(now);
539 chat.preview_at = Some(now);
540 chat.last_message_preview = Some(preview.to_owned());
541 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
542 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
543 chat.last_message_deleted = false;
544 chat.unread = false;
545 let record = message(
546 &chat.id,
547 &format!("demo-sent-{}", now.timestamp_millis()),
548 None,
549 (DEMO_USER_ID, DEMO_USER_NAME),
550 now,
551 html,
552 "[]",
553 false,
554 );
555 (chat, record)
556}
557
558pub fn new_chat(
559 existing: &[ChatRecord],
560 people: &[(String, String)],
561 topic: Option<&str>,
562 preview: &str,
563 html: &str,
564 now: DateTime<Utc>,
565) -> (ChatRecord, MessageRecord) {
566 let number = existing
567 .iter()
568 .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX))
569 .count()
570 + 1;
571 let one_on_one = people.len() == 1;
572 let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
573 .chain(people.iter().map(|(user_id, name)| member(user_id, name)))
574 .collect();
575 let chat = ChatRecord {
576 id: format!("{NEW_CHAT_PREFIX}{number}"),
577 kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(),
578 title: if one_on_one {
579 String::new()
580 } else {
581 topic.unwrap_or_default().to_owned()
582 },
583 member_summary: people
584 .iter()
585 .map(|(_, name)| name.as_str())
586 .collect::<Vec<_>>()
587 .join(", "),
588 members,
589 ..Default::default()
590 };
591 send_in_chat(&chat, preview, html, now)
592}
593
594fn image_directory() -> PathBuf {
595 std::env::temp_dir().join("rusty-teams-demo")
596}
597
598pub fn search_gifs(query: &str) -> Vec<Gif> {
599 let query = query.trim().to_lowercase();
600 SEARCHABLE_GIFS
601 .get()
602 .into_iter()
603 .flatten()
604 .filter(|gif| gif.title.to_lowercase().contains(&query))
605 .cloned()
606 .collect()
607}
608
609pub fn language_settings() -> LanguageSettings {
610 LanguageSettings {
611 display_locale: Some("en-US".to_owned()),
612 target_locale: Some("en".to_owned()),
613 behavior: TranslationBehavior::Ask,
614 authoring_locales: vec!["de-DE".to_owned(), "en-US".to_owned()],
615 preferences: serde_json::Map::new(),
616 }
617}
618
619pub fn language_list() -> Vec<Language> {
620 [
621 ("de", "German"),
622 ("en", "English"),
623 ("es", "Spanish"),
624 ("fr", "French"),
625 ("it", "Italian"),
626 ("ja", "Japanese"),
627 ("nl", "Dutch"),
628 ("pt", "Portuguese"),
629 ]
630 .into_iter()
631 .map(|(code, name)| Language {
632 code: code.to_owned(),
633 name: name.to_owned(),
634 })
635 .collect()
636}
637
638pub fn language_stamps(conversation_id: &str) -> HashMap<String, String> {
639 if conversation_id != RELEASE_CHAT {
640 return HashMap::new();
641 }
642 HashMap::from([
643 (
644 FRENCH_MESSAGE.to_owned(),
645 "languages=fr:100;en:12;length:104;&detector=Bling".to_owned(),
646 ),
647 (
648 SPANISH_MESSAGE.to_owned(),
649 "languages=es:100;pt:31;length:94;&detector=Bling".to_owned(),
650 ),
651 ])
652}
653
654pub fn translations(message_ids: &[String]) -> Vec<Translation> {
655 let translated = |message_id: &str| match message_id {
656 FRENCH_MESSAGE => Some(
657 "<p>Hello everyone, <strong>version 0.2</strong> is ready. Can you check the checklist before Friday?</p>",
658 ),
659 SPANISH_MESSAGE => Some(
660 "<p>Thanks for the heads-up. I will test the build this afternoon and let you know if anything breaks.</p>",
661 ),
662 _ => None,
663 };
664 message_ids
665 .iter()
666 .map(|message_id| Translation {
667 message_id: message_id.clone(),
668 version: None,
669 status: if translated(message_id).is_some() {
670 TranslationStatus::Done
671 } else {
672 TranslationStatus::Failed
673 },
674 content_html: translated(message_id).map(str::to_owned),
675 subject: None,
676 title: None,
677 })
678 .collect()
679}
680
681pub fn channel_read_until(channel_id: &str) -> Option<DateTime<Utc>> {
682 (channel_id == PINNED_CHANNEL).then(|| at(0, 11, 0))
683}
684
685pub fn first_unread(conversation_id: &str) -> Option<String> {
686 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
687}
688
689pub fn read_message_ids(records: &[MessageRecord]) -> std::collections::HashSet<String> {
690 let newest = records.iter().max_by_key(|record| record.created_at);
691 records
692 .iter()
693 .filter(|record| {
694 Some(record.message_id.as_str()) != newest.map(|newest| newest.message_id.as_str())
695 })
696 .map(|record| record.message_id.clone())
697 .collect()
698}
699
700pub fn start_session(state: &Entity<AppState>, cx: &mut App) {
701 state.update(cx, |state, cx| {
702 seed_directory(state);
703 state.demo_live_meetings();
704 state.select(first_selection(), cx);
705 });
706}
707
708pub fn first_selection() -> Selection {
709 Selection::Chat(RELEASE_CHAT.to_owned())
710}
711
712pub fn activity_snapshot() -> ActivitySnapshot {
713 let item = |message_id: &str,
714 activity_type: &str,
715 subtype: &str,
716 conversation_id: &str,
717 thread_type: &str,
718 source_message_id: &str,
719 actor: (&str, &str),
720 preview: &str,
721 time: DateTime<Utc>,
722 read: bool| ActivityItem {
723 message_id: message_id.to_owned(),
724 activity_id: message_id.to_owned(),
725 activity_type: activity_type.to_owned(),
726 activity_subtype: subtype.to_owned(),
727 source_thread_id: conversation_id.to_owned(),
728 source_message_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()),
729 source_reply_chain_id: (!source_message_id.is_empty())
730 .then(|| source_message_id.to_owned()),
731 source_user_id: Some(format!("8:orgid:{}", actor.0)),
732 source_user_name: actor.1.to_owned(),
733 preview: preview.to_owned(),
734 preview_template: "hasText".to_owned(),
735 thread_type: Some(thread_type.to_owned()),
736 count: 1,
737 timestamp_ms: time.timestamp_millis(),
738 version_ms: time.timestamp_millis(),
739 read_flag: read,
740 ..ActivityItem::default()
741 };
742 let items = vec![
743 item(
744 "demo-activity-1",
745 "replyInChat",
746 "",
747 UNREAD_CHAT,
748 "chat",
749 "u3",
750 (LEA_ID, "Lea Schneider"),
751 "Who is taking the review?",
752 at(0, 13, 12),
753 false,
754 ),
755 ActivityItem {
756 count: 2,
757 ..item(
758 "demo-activity-2",
759 "reactionInChat",
760 "laugh",
761 RELEASE_CHAT,
762 "chat",
763 "m3",
764 (PRIYA_ID, "Priya Nair"),
765 "I'll take the changelog.",
766 at(0, 13, 20),
767 false,
768 )
769 },
770 item(
771 "demo-activity-3",
772 "mention",
773 "person",
774 "demo-channel-1-1",
775 "topic",
776 "t1",
777 (MARA_ID, "Mara Lindqvist"),
778 "@Dana can you approve the merge? The pipeline is waiting.",
779 at(0, 11, 40),
780 false,
781 ),
782 item(
783 "demo-activity-4",
784 "mentionInChat",
785 "person",
786 "demo-chat-allhands",
787 "chat",
788 "demo-allhands-policy",
789 (LEA_ID, "Lea Schneider"),
790 "@Dana please read the new vacation policy before Friday.",
791 at(0, 9, 0),
792 false,
793 ),
794 item(
795 "demo-activity-5",
796 "follow",
797 "channelNewMessage",
798 "demo-channel-1-3",
799 "topic",
800 "demo-release-post",
801 (MARA_ID, "Mara Lindqvist"),
802 "Release 4.2 is tagged, notes are in the wiki.",
803 at(1, 17, 30),
804 true,
805 ),
806 item(
807 "demo-activity-6",
808 "call",
809 "missedCall",
810 "demo-chat-customer-3",
811 "chat",
812 "",
813 (TOBIAS_ID, "Tobias Klein"),
814 "",
815 at(1, 16, 0),
816 true,
817 ),
818 ActivityItem {
819 source_thread_id: String::new(),
820 source_message_id: Some("1".to_owned()),
821 source_reply_chain_id: None,
822 source_user_id: None,
823 source_app_name: Some("Meeting Recaps".to_owned()),
824 preview_template: "previewUnavailable".to_owned(),
825 template_parameters: [("subject".to_owned(), "Following: Sprint Review ".to_owned())]
826 .into(),
827 event_start_ms: Some(at(1, 10, 0).timestamp_millis()),
828 event_end_ms: Some(at(1, 11, 0).timestamp_millis()),
829 ..item(
830 "demo-activity-7",
831 "msGraph",
832 "recapIsReadyForFollowedMeetingsV2",
833 "",
834 "",
835 "",
836 ("", "Meeting Recaps"),
837 "You're following this meeting",
838 at(1, 11, 30),
839 true,
840 )
841 },
842 ];
843 ActivitySnapshot {
844 items,
845 horizons: ActivityHorizons::default(),
846 }
847}
848
849pub fn seed(store: &Store) {
850 let chats: Vec<ChatRecord> = demo_chats()
851 .into_iter()
852 .map(|demo| ChatRecord {
853 id: demo.id.to_owned(),
854 kind: demo.kind.to_owned(),
855 title: if demo.kind == "oneOnOne" {
856 String::new()
857 } else {
858 demo.title.to_owned()
859 },
860 member_summary: demo.title.to_owned(),
861 last_message_at: Some(demo.time),
862 unread: demo.unread,
863 members: demo.members,
864 last_message_preview: demo.preview.map(|(_, _, text)| text.to_owned()),
865 last_message_sender_id: demo.preview.map(|(id, _, _)| id.to_owned()),
866 last_message_sender_name: demo.preview.map(|(_, name, _)| name.to_owned()),
867 last_message_deleted: demo.deleted,
868 ..Default::default()
869 })
870 .collect();
871 let _ = store.upsert_chats(&chats);
872 for chat_id in MUTED_CHATS {
873 let _ = store.set_chat_muted(chat_id, true);
874 }
875 let teams: Vec<TeamRecord> = DEMO_TEAMS
876 .iter()
877 .map(|(id, name, _)| TeamRecord {
878 id: (*id).to_owned(),
879 name: (*name).to_owned(),
880 })
881 .collect();
882 let _ = store.upsert_teams(&teams);
883 let mut channels = Vec::new();
884 for (team_index, (team_id, _, names)) in DEMO_TEAMS.iter().enumerate() {
885 for (channel_index, name) in names.iter().enumerate() {
886 channels.push(ChannelRecord {
887 id: format!("demo-channel-{}-{}", team_index + 1, channel_index + 1),
888 team_id: (*team_id).to_owned(),
889 name: (*name).to_owned(),
890 membership_type: (*name == DEMO_PRIVATE_CHANNEL).then(|| "private".to_owned()),
891 last_message_at: Some(at(channel_index as i64, 12, 10)),
892 unread: (team_index == 0 && channel_index == 1)
893 || (team_index == 1 && channel_index == 0),
894 });
895 }
896 }
897 for channel in channels.iter_mut().filter(|channel| {
898 DEMO_CHANNEL_MENTIONS
899 .iter()
900 .any(|(id, _)| *id == channel.id)
901 }) {
902 channel.unread = true;
903 }
904 let _ = store.upsert_channels(&channels);
905 let _ = store.replace_team_layout(&demo_team_layout(&channels));
906 let _ = store.replace_channel_mentions(
907 &DEMO_CHANNEL_MENTIONS
908 .iter()
909 .map(|(id, mentions)| ((*id).to_owned(), *mentions))
910 .collect::<Vec<_>>(),
911 );
912 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
913 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
914 let _ = store.upsert_messages(&release_messages());
915 let _ = store.upsert_messages(&unread_messages());
916 let _ = store.upsert_messages(&channel_messages());
917 let _ = store.upsert_messages(&priority_messages());
918 let _ = store.upsert_messages(&notes_messages());
919 let _ = store.upsert_messages(&meeting_link_messages());
920 let _ = store.upsert_messages(&standup_messages());
921 let _ = store.upsert_messages(&call_messages());
922 let _ = store.upsert_messages(&crate::demo_meetings::meeting_messages());
923 let _ = store.upsert_messages(&bot_messages());
924 let _ = store.upsert_messages(&crate::kvt_demo::messages());
925 seed_agent_access(store);
926}
927
928pub fn agent_meeting_draft() -> mcp::MeetingDraft {
929 let start = at(-1, 10, 0);
930 mcp::MeetingDraft {
931 subject: "Release 42 go/no-go".to_owned(),
932 start,
933 end: start + Duration::minutes(30),
934 attendees: vec![
935 "mara.lindqvist@example.com".to_owned(),
936 "jonas.ortega@example.com".to_owned(),
937 ],
938 description:
939 "Walk through the regression results and decide on Friday's rollout.\nOwner: Mara"
940 .to_owned(),
941 }
942}
943
944const AGENT_DEMO_PROPOSAL: &str = "I ran the regression suite on staging: 412 passed, 0 failed. The release candidate is good to ship, @Mara Lindqvist.";
945
946fn seed_agent_access(store: &Store) {
947 let selected =
948 |ids: &[&str]| mcp::Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect());
949 mcp::save_policy(
950 store,
951 &mcp::AgentPolicy {
952 enabled: true,
953 chats: selected(&[RELEASE_CHAT, "demo-chat-mara", "demo-chat-meeting-standup"]),
954 channels: selected(&["demo-channel-1-1"]),
955 write: true,
956 calendar: true,
957 transcripts: false,
958 meetings: true,
959 ..mcp::AgentPolicy::default()
960 },
961 );
962 let _ = store.insert_agent_proposal(&store::AgentProposalRecord {
963 id: "demo-proposal".to_owned(),
964 conversation_id: RELEASE_CHAT.to_owned(),
965 reply_to_message_id: Some("m1".to_owned()),
966 text: AGENT_DEMO_PROPOSAL.to_owned(),
967 mentions: vec![store::AgentProposalMention {
968 user_id: MARA_ID.to_owned(),
969 name: "Mara Lindqvist".to_owned(),
970 }],
971 images: vec![store::AttachmentImage {
972 name: "image-1.png".to_owned(),
973 format: "image/png".to_owned(),
974 bytes: encode_png(&MARA),
975 width: Some(PHOTO_SIZE as u32),
976 height: Some(PHOTO_SIZE as u32),
977 }],
978 agent: Some("claude".to_owned()),
979 session_id: None,
980 created_at: Utc::now() - Duration::minutes(1),
981 state: "pending".to_owned(),
982 resolved_at: None,
983 });
984 let _ = store.insert_agent_reaction(&store::AgentReactionRecord {
985 id: "demo-reaction".to_owned(),
986 conversation_id: "demo-chat-mara".to_owned(),
987 message_id: "ml1".to_owned(),
988 emoji: "\u{1F44D}".to_owned(),
989 agent: Some("claude".to_owned()),
990 session_id: None,
991 created_at: Utc::now() - Duration::minutes(1),
992 state: "pending".to_owned(),
993 resolved_at: None,
994 });
995}
996
997fn photo(palette: &Palette) -> AvatarState {
998 crate::data::avatar_state_from("image/png", encode_png(palette), false)
999}
1000
1001pub fn seed_directory(state: &mut AppState) {
1002 state.own_status = crate::own_status::demo_status();
1003 state.own_email = DEMO_USER_EMAIL.to_owned();
1004 state.own_time_zone = Some(DEMO_TIME_ZONE.to_owned());
1005 state.translation.settings = Some(language_settings());
1006 state.apply_regional_format();
1007 state.translation.languages = language_list();
1008 let directory = &mut state.directory;
1009 directory.me = Some(Person {
1010 user_id: DEMO_USER_ID.to_owned(),
1011 display_name: DEMO_USER_NAME.to_owned(),
1012 });
1013 let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
1014 directory.folders = vec![
1015 FolderInfo {
1016 id: FAVORITES_ID.to_owned(),
1017 name: String::new(),
1018 kind: FolderKind::Favorites,
1019 expanded: None,
1020 conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
1021 },
1022 FolderInfo {
1023 id: CUSTOMERS_FOLDER.to_owned(),
1024 name: "Customers".to_owned(),
1025 kind: FolderKind::UserCreated,
1026 expanded: None,
1027 conversation_ids: ids(&[
1028 "demo-chat-customer-1",
1029 "demo-chat-customer-2",
1030 "demo-chat-customer-3",
1031 "demo-chat-customer-4",
1032 ]),
1033 },
1034 FolderInfo {
1035 id: ATLAS_FOLDER.to_owned(),
1036 name: "Project Atlas".to_owned(),
1037 kind: FolderKind::UserCreated,
1038 expanded: None,
1039 conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
1040 },
1041 FolderInfo {
1042 id: TODO_FOLDER.to_owned(),
1043 name: "To do".to_owned(),
1044 kind: FolderKind::UserCreated,
1045 expanded: None,
1046 conversation_ids: Vec::new(),
1047 },
1048 ];
1049 state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]);
1050 let directory = &mut state.directory;
1051 directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
1052 directory
1053 .unread_counts
1054 .insert("demo-chat-atlas".to_owned(), 5);
1055 directory
1056 .unread_counts
1057 .insert("demo-chat-customer-1".to_owned(), 2);
1058 directory
1059 .unread_counts
1060 .insert("demo-chat-customer-2".to_owned(), 1);
1061 directory
1062 .unread_counts
1063 .insert("demo-chat-allhands".to_owned(), 120);
1064 directory
1065 .unread_importance
1066 .insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);
1067 directory
1068 .unread_importance
1069 .insert("demo-chat-customer-1".to_owned(), MessageImportance::High);
1070 directory.set_avatar(MARA_ID, photo(&MARA));
1071 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
1072 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
1073 for (user_id, kind) in [
1074 (MARA_ID, PresenceKind::Available),
1075 (JONAS_ID, PresenceKind::Busy),
1076 (PRIYA_ID, PresenceKind::Away),
1077 (TOBIAS_ID, PresenceKind::Offline),
1078 (LEA_ID, PresenceKind::Busy),
1079 (DEMO_USER_ID, PresenceKind::Available),
1080 ] {
1081 directory.set_presence(user_id, kind);
1082 }
1083 directory.set_activity(JONAS_ID, Some(Activity::InACall));
1084 directory.set_activity(LEA_ID, Some(Activity::InAConferenceCall));
1085 let directory_path = image_directory();
1086 if std::fs::create_dir_all(&directory_path).is_ok() {
1087 let path = directory_path.join("staging-dashboard.png");
1088 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
1089 if std::fs::write(&path, png).is_ok() {
1090 state.directory.set_image(STAGING_IMAGE_KEY, &path);
1091 state.directory.set_image(LINK_IMAGE_KEY, &path);
1092 state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);
1093 }
1094 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
1095 state.directory.set_image(
1096 demo_gifs::RECEIVED_GIF_KEY,
1097 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
1098 );
1099 }
1100 state.typing.start(
1101 "demo-chat-mara",
1102 MARA_ID,
1103 "Mara Lindqvist",
1104 Instant::now(),
1105 Utc::now(),
1106 );
1107 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
1108 state.last_sync = Some(Utc::now());
1109 state.apply_bot_titles();
1110 seed_message_actions(state);
1111}
1112
1113fn seed_message_actions(state: &mut AppState) {
1114 state.pins.insert(
1115 PINNED_CHANNEL.to_owned(),
1116 vec![PinnedMessage {
1117 message_id: PINNED_POST.to_owned(),
1118 pinned_at: Some(at(0, 9, 45)),
1119 parent_id: None,
1120 }],
1121 );
1122 state.pins.insert(
1123 RELEASE_CHAT.to_owned(),
1124 vec![PinnedMessage {
1125 message_id: PINNED_MESSAGE.to_owned(),
1126 pinned_at: Some(at(0, 11, 30)),
1127 parent_id: None,
1128 }],
1129 );
1130 let ids: Vec<String> = SAVED_MESSAGES.iter().map(|id| (*id).to_owned()).collect();
1131 let records = state
1132 .store
1133 .messages_by_id(RELEASE_CHAT, &ids)
1134 .unwrap_or_default();
1135 let saved = SAVED_MESSAGES
1136 .iter()
1137 .enumerate()
1138 .filter_map(|(position, id)| {
1139 let record = records.get(*id)?;
1140 Some(SavedMessage {
1141 conversation_id: record.conversation_id.clone(),
1142 message_id: record.message_id.clone(),
1143 root_id: record.message_id.clone(),
1144 author_id: record.sender_id.clone(),
1145 author_name: record.sender_name.clone(),
1146 preview: crate::rows::reply_excerpt(record),
1147 saved_at: at(position as i64, 15, 20),
1148 topic: None,
1149 })
1150 })
1151 .collect();
1152 state.saved.replace(saved);
1153}
1154
1155pub fn forwarded_message(
1156 chat: &ChatRecord,
1157 source: &ForwardSource,
1158 comment: &str,
1159 now: DateTime<Utc>,
1160) -> (ChatRecord, MessageRecord) {
1161 let comment_html = if comment.is_empty() {
1162 String::new()
1163 } else {
1164 format!("<p>{}</p>", teams_core::escape_html(comment))
1165 };
1166 let quotes: String = source
1167 .messages
1168 .iter()
1169 .map(|item| {
1170 format!(
1171 "<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
1172 teams_core::escape_html(&item.message_id),
1173 teams_core::escape_html(&item.author),
1174 teams_core::escape_html(&item.text),
1175 )
1176 })
1177 .collect();
1178 let preview = source
1179 .messages
1180 .first()
1181 .map(|item| item.text.as_str())
1182 .unwrap_or_default();
1183 send_in_chat(chat, preview, &format!("{comment_html}{quotes}"), now)
1184}
1185
1186#[allow(clippy::too_many_arguments)]
1187fn message(
1188 conversation: &str,
1189 id: &str,
1190 reply_to: Option<&str>,
1191 sender: (&str, &str),
1192 time: DateTime<Utc>,
1193 html: &str,
1194 reactions_json: &str,
1195 edited: bool,
1196) -> MessageRecord {
1197 MessageRecord {
1198 conversation_id: conversation.to_owned(),
1199 message_id: id.to_owned(),
1200 reply_to_id: reply_to.map(str::to_owned),
1201 sender_id: Some(sender.0.to_owned()),
1202 sender_name: Some(sender.1.to_owned()),
1203 sender_application_id: None,
1204 links_json: "[]".to_owned(),
1205 created_at: time,
1206 edited_at: edited.then_some(time + Duration::minutes(2)),
1207 deleted: false,
1208 body_html: html.to_owned(),
1209 attachments_json: "[]".to_owned(),
1210 reactions_json: reactions_json.to_owned(),
1211 mentions_json: "[]".to_owned(),
1212 subject: None,
1213 call_event_json: None,
1214 importance: Default::default(),
1215 }
1216}
1217
1218pub fn roster_record(
1219 conversation: &str,
1220 id: &str,
1221 time: DateTime<Utc>,
1222 event: &teams_core::roster_event::RosterEvent,
1223) -> MessageRecord {
1224 MessageRecord {
1225 conversation_id: conversation.to_owned(),
1226 message_id: id.to_owned(),
1227 created_at: time,
1228 links_json: "[]".to_owned(),
1229 attachments_json: "[]".to_owned(),
1230 reactions_json: "[]".to_owned(),
1231 mentions_json: "[]".to_owned(),
1232 call_event_json: Some(event.to_json()),
1233 ..MessageRecord::default()
1234 }
1235}
1236
1237fn call_record(
1238 conversation: &str,
1239 id: &str,
1240 time: DateTime<Utc>,
1241 event: CallEvent,
1242) -> MessageRecord {
1243 MessageRecord {
1244 conversation_id: conversation.to_owned(),
1245 message_id: id.to_owned(),
1246 created_at: time,
1247 links_json: "[]".to_owned(),
1248 attachments_json: "[]".to_owned(),
1249 reactions_json: "[]".to_owned(),
1250 mentions_json: "[]".to_owned(),
1251 call_event_json: Some(event.to_json()),
1252 ..MessageRecord::default()
1253 }
1254}
1255
1256fn call_event(
1257 phase: CallPhase,
1258 call_id: &str,
1259 initiator: (&str, &str),
1260 duration_seconds: Option<u64>,
1261 participant_ids: &[&str],
1262) -> CallEvent {
1263 CallEvent {
1264 phase,
1265 call_type: CallType::Call,
1266 call_id: call_id.to_owned(),
1267 duration_seconds,
1268 initiator_id: Some(initiator.0.to_owned()),
1269 initiator_name: Some(initiator.1.to_owned()),
1270 participant_ids: participant_ids.iter().map(|id| (*id).to_owned()).collect(),
1271 participant_names: Vec::new(),
1272 recording: None,
1273 }
1274}
1275
1276fn call_messages() -> Vec<MessageRecord> {
1277 let mara = (MARA_ID, "Mara Lindqvist");
1278 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1279 let jonas = (JONAS_ID, "Jonas Ortega");
1280 let both = [DEMO_USER_ID, MARA_ID];
1281 vec![
1282 call_record(
1283 "demo-chat-mara",
1284 "call-1-started",
1285 at(0, 12, 4),
1286 call_event(CallPhase::Started, "demo-call-1", me, None, &[]),
1287 ),
1288 call_record(
1289 "demo-chat-mara",
1290 "call-1-ended",
1291 at(0, 12, 16),
1292 call_event(CallPhase::Ended, "demo-call-1", me, Some(723), &both),
1293 ),
1294 call_record(
1295 "demo-chat-mara",
1296 "call-2-started",
1297 at(0, 13, 9),
1298 call_event(CallPhase::Started, "demo-call-2", mara, None, &[]),
1299 ),
1300 call_record(
1301 "demo-chat-mara",
1302 "call-2-ended",
1303 at(0, 13, 10),
1304 call_event(CallPhase::Ended, "demo-call-2", mara, Some(60), &[MARA_ID]),
1305 ),
1306 call_record(
1307 "demo-chat-meeting-standup",
1308 "call-3-started",
1309 at(0, 9, 50),
1310 CallEvent {
1311 call_type: CallType::Meeting,
1312 ..call_event(CallPhase::Started, "demo-call-3", jonas, None, &[])
1313 },
1314 ),
1315 ]
1316}
1317
1318fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {
1319 record.importance = importance;
1320 record
1321}
1322
1323fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1324 record.subject = Some(subject.to_owned());
1325 record
1326}
1327
1328/// A Graph forward of a Teams video clip, as Teams sends a forwarded phone recording.
1329fn forwarded_clip_attachments(message_id: &str, sender_id: &str) -> String {
1330 let content = serde_json::json!({
1331 "originalMessageId": message_id,
1332 "originalMessageContent": format!(
1333 r#"<p><video src="{DEMO_CLIP_URL}" itemscope="" itemtype="http://schema.skype.com/AMSVideo" width="720" height="1280" data-duration="PT12S" alt="Media"></video></p>"#
1334 ),
1335 "originalMessageSender": {"user": {"id": sender_id, "displayName": null}},
1336 });
1337 serde_json::json!([{
1338 "content_type": "forwardedMessageReference",
1339 "id": message_id,
1340 "content": content.to_string(),
1341 }])
1342 .to_string()
1343}
1344
1345fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
1346 record.attachments_json = attachments_json.to_owned();
1347 record
1348}
1349
1350fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {
1351 record.links_json = links_json;
1352 record
1353}
1354
1355pub fn link_preview(url: &str) -> Option<LinkPreview> {
1356 Some(LinkPreview {
1357 url: url.to_owned(),
1358 title: Some("Release checklist Q4".to_owned()),
1359 description: Some(
1360 "Everything that has to be green before the release candidate goes out on Friday."
1361 .to_owned(),
1362 ),
1363 image_url: Some(LINK_IMAGE_KEY.to_owned()),
1364 image_width: Some(LINK_IMAGE_SIZE.0),
1365 image_height: Some(LINK_IMAGE_SIZE.1),
1366 })
1367}
1368
1369fn bot_messages() -> Vec<MessageRecord> {
1370 let card = serde_json::json!({
1371 "type": "AdaptiveCard",
1372 "body": [
1373 {"type": "ColumnSet", "columns": [
1374 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
1375 {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"}
1376 ]},
1377 {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [
1378 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"}
1379 ]}
1380 ]},
1381 {"type": "ColumnSet", "separator": true, "columns": [
1382 {"type": "Column", "width": "auto", "items": [
1383 {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"}
1384 ]},
1385 {"type": "Column", "width": "stretch", "items": [
1386 {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"},
1387 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
1388 ]}
1389 ]},
1390 {"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."},
1391 {"type": "ActionSet", "actions": [
1392 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
1393 {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
1394 {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
1395 {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}},
1396 {"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}},
1397 {"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]},
1398 {"type": "Action.ShowCard", "title": "Details", "card": {"body": [
1399 {"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."}
1400 ]}}
1401 ]}
1402 ]
1403 });
1404 let mut messages = vec![
1405 bot_card_message("b1", at(0, 13, 45), &card),
1406 bot_card_message("b2", at(0, 13, 52), &input_card()),
1407 bot_card_message(
1408 "b3",
1409 at(0, 13, 58),
1410 &crate::demo_input_cards::all_inputs_card(),
1411 ),
1412 ];
1413 messages.extend(
1414 crate::demo_cards::behaviour_cards()
1415 .iter()
1416 .zip(0u32..)
1417 .map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),
1418 );
1419 messages.extend(crate::demo_chart_cards::cards().iter().zip(0..).map(
1420 |(chart_card, minute)| {
1421 bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)
1422 },
1423 ));
1424 let mut webhook = bot_card_message("w1", at(0, 16, 0), &connector_card());
1425 webhook.attachments_json = webhook.attachments_json.replace(
1426 "application/vnd.microsoft.card.adaptive",
1427 "application/vnd.microsoft.teams.card.o365connector",
1428 );
1429 messages.push(webhook);
1430 messages
1431}
1432
1433fn connector_card() -> serde_json::Value {
1434 serde_json::json!({
1435 "@type": "MessageCard",
1436 "summary": "Build failed",
1437 "title": "Pipeline main",
1438 "sections": [{
1439 "activityTitle": "Build 128 failed",
1440 "activitySubtitle": "on agent 3",
1441 "facts": [{"name": "Branch", "value": "main"}, {"name": "Duration", "value": "4 min"}],
1442 "text": "See the log for details."
1443 }],
1444 "potentialAction": [{
1445 "@type": "OpenUri",
1446 "name": "Open log",
1447 "targets": [{"os": "default", "uri": "https://example.com/ci/128"}]
1448 }]
1449 })
1450}
1451
1452fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
1453 let attachments = serde_json::json!([{
1454 "content_type": "application/vnd.microsoft.card.adaptive",
1455 "name": null,
1456 "url": null,
1457 "text": null,
1458 "content": card.to_string()
1459 }]);
1460 let mut record = with_attachments(
1461 message(
1462 BOT_CHAT,
1463 id,
1464 None,
1465 ("", BOT_NAME),
1466 time,
1467 &format!("<attachment id=\"{id}\"></attachment>"),
1468 "[]",
1469 false,
1470 ),
1471 &attachments.to_string(),
1472 );
1473 record.sender_id = None;
1474 record.sender_application_id = Some(BOT_ID.to_owned());
1475 record
1476}
1477
1478fn input_card() -> serde_json::Value {
1479 serde_json::json!({
1480 "type": "AdaptiveCard",
1481 "body": [
1482 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"},
1483 {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"},
1484 {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true},
1485 {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"},
1486 {"type": "ColumnSet", "columns": [
1487 {"type": "Column", "width": "stretch", "items": [
1488 {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4}
1489 ]},
1490 {"type": "Column", "width": "stretch", "items": [
1491 {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"}
1492 ]},
1493 {"type": "Column", "width": "stretch", "items": [
1494 {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"}
1495 ]}
1496 ]},
1497 {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [
1498 {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"}
1499 ]},
1500 {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [
1501 {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"}
1502 ]},
1503 {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [
1504 {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"}
1505 ]},
1506 {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"}
1507 ],
1508 "actions": [
1509 {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}},
1510 {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}}
1511 ]
1512 })
1513}
1514
1515fn bot_app() -> ChatApp {
1516 ChatApp {
1517 app_id: "demo-app-wiki".to_owned(),
1518 name: BOT_APP_NAME.to_owned(),
1519 bot_ids: vec![BOT_ID.to_owned()],
1520 small_image_url: None,
1521 accent_color: None,
1522 web_application_resource: None,
1523 }
1524}
1525
1526pub async fn card_answer(task: CardTask) -> CardAnswer {
1527 tokio::time::sleep(CARD_ANSWER_DELAY).await;
1528 let data = match task {
1529 CardTask::Submit(_) => {
1530 return Ok((
1531 CardActionOutcome::Message("Settings saved".into()),
1532 Some((bot_app(), BOT_ID.to_owned())),
1533 ));
1534 }
1535 CardTask::Action(action) => match action.invoke_payload() {
1536 Some(payload) => payload.value,
1537 None => return Err("Not supported".to_owned()),
1538 },
1539 };
1540 let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch")
1541 {
1542 CardActionOutcome::Dialog(TaskDialog {
1543 title: None,
1544 width: 520,
1545 height: 300,
1546 kind: TaskDialogKind::Card(settings_card().to_string()),
1547 })
1548 } else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") {
1549 CardActionOutcome::Failed("The app answered 500: demo failure".into())
1550 } else {
1551 CardActionOutcome::Sent
1552 };
1553 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
1554}
1555
1556pub async fn refresh_answer() -> CardAnswer {
1557 tokio::time::sleep(CARD_ANSWER_DELAY).await;
1558 Ok((
1559 CardActionOutcome::ReplaceCard(crate::demo_cards::refreshed_card().to_string()),
1560 Some((bot_app(), BOT_ID.to_owned())),
1561 ))
1562}
1563
1564fn settings_card() -> serde_json::Value {
1565 serde_json::json!({
1566 "type": "AdaptiveCard",
1567 "body": [
1568 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
1569 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."},
1570 {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [
1571 {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"}
1572 ]},
1573 {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"}
1574 ],
1575 "actions": [
1576 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
1577 ]
1578 })
1579}
1580
1581pub const DEMO_TENANT_ID: &str = "demo-tenant";
1582const DEMO_MEETING_LINK: &str = "https://teams.microsoft.com/l/meetup-join/19%3ameeting_ZGVtbw%40thread.v2/0?context=%7b%22Tid%22%3a%22demo-tenant%22%2c%22Oid%22%3a%22demo-mara%22%7d";
1583
1584fn meeting_link_messages() -> Vec<MessageRecord> {
1585 let mara = (MARA_ID, "Mara Lindqvist");
1586 vec![message(
1587 "demo-chat-mara",
1588 "ml1",
1589 None,
1590 mara,
1591 at(0, 13, 38),
1592 &format!(
1593 "<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"
1594 ),
1595 "[]",
1596 false,
1597 )]
1598}
1599
1600fn standup_messages() -> Vec<MessageRecord> {
1601 let jonas = (JONAS_ID, "Jonas Ortega");
1602 let priya = (PRIYA_ID, "Priya Nair");
1603 vec![
1604 with_attachments(
1605 message(
1606 "demo-chat-meeting-standup",
1607 "su1",
1608 None,
1609 priya,
1610 at(0, 9, 30),
1611 "<p>Notes from today.</p>",
1612 "[]",
1613 false,
1614 ),
1615 r#"[{"content_type":"reference","name":"Standup-notes.docx","url":"https://example.com/files/standup-notes.docx","text":null,"size":38900}]"#,
1616 ),
1617 with_attachments(
1618 message(
1619 "demo-chat-meeting-standup",
1620 "su2",
1621 None,
1622 jonas,
1623 at(0, 9, 45),
1624 "<p>Recording is available</p>",
1625 "[]",
1626 false,
1627 ),
1628 r#"[{"content_type":"reference","name":"Standup-recording.mp4","url":"https://contoso-my.sharepoint.com/personal/jonas_contoso_com/Documents/Recordings/Standup-recording.mp4","text":null,"size":18400000}]"#,
1629 ),
1630 with_links(
1631 message(
1632 "demo-chat-meeting-standup",
1633 "su3",
1634 None,
1635 jonas,
1636 at(0, 9, 50),
1637 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1638 "[]",
1639 false,
1640 ),
1641 link_preview("https://example.com/checklist")
1642 .map(|preview| preview.links_json())
1643 .unwrap_or_default(),
1644 ),
1645 message(
1646 "demo-chat-meeting-standup",
1647 "su4",
1648 None,
1649 priya,
1650 at(0, 9, 52),
1651 "<p>I will quickly fix the comments and then push the final version before the review starts.</p>",
1652 "[]",
1653 false,
1654 ),
1655 ]
1656}
1657
1658fn notes_messages() -> Vec<MessageRecord> {
1659 vec![message(
1660 NOTES_CHAT_ID,
1661 "n1",
1662 None,
1663 (DEMO_USER_ID, DEMO_USER_NAME),
1664 at(0, 8, 20),
1665 "<p>Release notes draft</p>",
1666 "[]",
1667 false,
1668 )]
1669}
1670
1671fn priority_messages() -> Vec<MessageRecord> {
1672 let priya = (PRIYA_ID, "Priya Nair");
1673 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1674 vec![
1675 message(
1676 PRIORITY_CHAT,
1677 "p1",
1678 None,
1679 me,
1680 at(0, 10, 40),
1681 "<p>Have you seen the error on staging yet?</p>",
1682 "[]",
1683 false,
1684 ),
1685 message(
1686 PRIORITY_CHAT,
1687 "p2",
1688 None,
1689 priya,
1690 at(0, 10, 47),
1691 &format!(
1692 "<p>Yes, here is the screenshot:</p><img src=\"{PENDING_IMAGE_KEY}\" width=\"1280\" height=\"720\">"
1693 ),
1694 "[]",
1695 false,
1696 ),
1697 ]
1698 .into_iter()
1699 .map(|record| match record.message_id.as_str() {
1700 "p2" => with_importance(record, MessageImportance::High),
1701 _ => record,
1702 })
1703 .collect()
1704}
1705
1706fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
1707 users
1708 .iter()
1709 .map(|(user_id, user_name, created_at)| {
1710 serde_json::json!({
1711 "reaction_type": kind,
1712 "user_id": user_id,
1713 "user_name": user_name,
1714 "created_at": created_at,
1715 })
1716 })
1717 .collect()
1718}
1719
1720fn reactions_json(groups: Vec<Vec<serde_json::Value>>) -> String {
1721 serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string()
1722}
1723
1724fn release_messages() -> Vec<MessageRecord> {
1725 let chat = RELEASE_CHAT;
1726 let mara = (MARA_ID, "Mara Lindqvist");
1727 let jonas = (JONAS_ID, "Jonas Ortega");
1728 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1729 let jonas_name = "Jonas Ortega";
1730 let priya_name = "Priya Nair";
1731 let lea_name = "Lea Schneider";
1732 let mara_name = "Mara Lindqvist";
1733 let tobias_name = "Tobias Klein";
1734 let likes = reactions_json(vec![reaction(
1735 "like",
1736 &[
1737 (JONAS_ID, jonas_name, at(1, 16, 30)),
1738 (PRIYA_ID, priya_name, at(1, 17, 2)),
1739 (LEA_ID, lea_name, at(0, 8, 15)),
1740 ],
1741 )]);
1742 let hearts = reactions_json(vec![reaction(
1743 "heart",
1744 &[
1745 (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)),
1746 (JONAS_ID, jonas_name, at(0, 10, 33)),
1747 ],
1748 )]);
1749 let single = reactions_json(vec![reaction(
1750 "laugh",
1751 &[(PRIYA_ID, priya_name, at(0, 9, 10))],
1752 )]);
1753 let many = reactions_json(vec![
1754 reaction(
1755 "like",
1756 &[
1757 (MARA_ID, mara_name, at(0, 13, 37)),
1758 (JONAS_ID, jonas_name, at(0, 13, 38)),
1759 (PRIYA_ID, priya_name, at(0, 13, 40)),
1760 (LEA_ID, lea_name, at(0, 13, 45)),
1761 (TOBIAS_ID, tobias_name, at(0, 13, 50)),
1762 ],
1763 ),
1764 reaction(
1765 "heart",
1766 &[
1767 (LEA_ID, lea_name, at(0, 13, 46)),
1768 (TOBIAS_ID, tobias_name, at(0, 13, 51)),
1769 ],
1770 ),
1771 reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]),
1772 ]);
1773 vec![
1774 message(
1775 chat,
1776 "m1",
1777 None,
1778 mara,
1779 at(1, 16, 20),
1780 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
1781 "[]",
1782 false,
1783 ),
1784 message(
1785 chat,
1786 "m2",
1787 None,
1788 mara,
1789 at(1, 16, 22),
1790 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
1791 &likes,
1792 false,
1793 ),
1794 with_links(
1795 message(
1796 chat,
1797 "m2a",
1798 None,
1799 mara,
1800 at(1, 16, 23),
1801 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1802 "[]",
1803 false,
1804 ),
1805 link_preview("https://example.com/checklist")
1806 .map(|preview| preview.links_json())
1807 .unwrap_or_default(),
1808 ),
1809 message(
1810 chat,
1811 "m2b",
1812 None,
1813 mara,
1814 at(1, 16, 40),
1815 &format!(
1816 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
1817 STAGING_SIZE.0, STAGING_SIZE.1
1818 ),
1819 "[]",
1820 false,
1821 ),
1822 with_attachments(
1823 message(
1824 chat,
1825 "m2c",
1826 None,
1827 mara,
1828 at(1, 16, 41),
1829 "<p>Checklist and rollout plan attached.</p>",
1830 "[]",
1831 false,
1832 ),
1833 r#"[{"content_type":"reference","name":"Release-Checklist-Q4.xlsx","url":"https://example.com/files/checklist.xlsx","text":null,"size":48213},{"content_type":"reference","name":"Rollout-Plan.pdf","url":"https://example.com/files/plan.pdf","text":null,"size":2306867}]"#,
1834 ),
1835 message(
1836 chat,
1837 "m3",
1838 None,
1839 me,
1840 at(0, 9, 2),
1841 "<p>I'll take the changelog.</p>",
1842 &single,
1843 false,
1844 ),
1845 message(
1846 chat,
1847 "m4",
1848 None,
1849 jonas,
1850 at(0, 10, 14),
1851 "<p><at id=\"0\">Mara Lindqvist</at> can you take a quick look at this? It runs before <code>cargo test</code>.</p><pre><code class=\"language-rust\">// only release branches\nfn freeze(branch: &amp;str) -&gt; bool {\n branch.starts_with(\"release/\")\n}</code></pre>",
1852 "[]",
1853 false,
1854 ),
1855 message(
1856 chat,
1857 "m5",
1858 None,
1859 mara,
1860 at(0, 10, 31),
1861 "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m4\"><strong itemprop=\"mri\">Jonas Ortega</strong><p itemprop=\"preview\">can you take a quick look at this?</p></blockquote><p>Looks good. Small thing: the name could say what it checks.</p>",
1862 &hearts,
1863 true,
1864 ),
1865 message(
1866 chat,
1867 "m5b",
1868 None,
1869 mara,
1870 at(0, 10, 40),
1871 "<p>Rollout for Friday:</p><ul><li>Freeze the release branch</li><li>Run the smoke tests on staging, then post the results in the channel</li><li>Ship<ul><li>Windows installer</li><li>Linux <code>.AppImage</code></li></ul></li></ul><p>Order:</p><ol><li>Tag</li><li>Build</li><li>Announce</li></ol>",
1872 "[]",
1873 false,
1874 ),
1875 message(
1876 chat,
1877 "m5c",
1878 None,
1879 jonas,
1880 at(0, 11, 5),
1881 "<h2>Release notes 0.2</h2><p>The <s>old sync path</s> <u>is gone</u>.</p><table><thead><tr><th>Area</th><th>Owner</th></tr></thead><tbody><tr><td>Sync</td><td>Priya</td></tr><tr><td>Render</td><td>Jonas</td></tr></tbody></table><hr><blockquote>Measure twice, cut once.</blockquote><p><span style=\"background-color: rgb(255, 255, 0)\">Important:</span> <span style=\"color: #c00000\">backup first</span>.</p><p style=\"margin-left:40px;\">Then <span style=\"color:#1E53A3;\">sync</span> <span style=\"background-color:#82CDA8;\">once</span>.</p><pre class=\"language-plaintext skipProofing\" spellcheck=\"false\"><code>backup --all<br>sync --once</code></pre>",
1882 "[]",
1883 false,
1884 ),
1885 message(
1886 chat,
1887 "m5d",
1888 None,
1889 (PRIYA_ID, priya_name),
1890 at(0, 12, 20),
1891 &format!(
1892 "<p>FYI, the customer asked for this.</p><blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"1790000000000\"><strong>Tobias Klein</strong><p>Can we move the freeze to Thursday? The customer demo is on Friday morning.</p></blockquote>"
1893 ),
1894 "[]",
1895 false,
1896 ),
1897 message(
1898 chat,
1899 "m5e",
1900 None,
1901 jonas,
1902 at(0, 12, 40),
1903 "<p>Context from the old planning chat.</p><attachment id=\"1789000000000\"></attachment>",
1904 r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"id":"1789000000000","content":null,"unavailable":true}]"#,
1905 false,
1906 ),
1907 with_attachments(
1908 message(
1909 chat,
1910 "m5f",
1911 None,
1912 (PRIYA_ID, priya_name),
1913 at(0, 12, 45),
1914 "<attachment id=\"1791000000000\"></attachment>",
1915 "[]",
1916 false,
1917 ),
1918 &forwarded_clip_attachments("1791000000000", TOBIAS_ID),
1919 ),
1920 message(
1921 chat,
1922 "m6",
1923 None,
1924 me,
1925 at(0, 13, 35),
1926 "<p>Thanks, renamed. Tagging now.</p>",
1927 "[]",
1928 false,
1929 ),
1930 message(
1931 chat,
1932 "m7",
1933 None,
1934 me,
1935 at(0, 13, 36),
1936 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
1937 &many,
1938 false,
1939 ),
1940 with_links(
1941 message(
1942 chat,
1943 "m7a",
1944 None,
1945 me,
1946 at(0, 13, 37),
1947 "<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",
1948 "[]",
1949 false,
1950 ),
1951 LinkPreview {
1952 url: "https://example.com/notes".to_owned(),
1953 title: Some("Release notes 0.2".to_owned()),
1954 description: Some("What changed since 0.1".to_owned()),
1955 image_url: None,
1956 image_width: None,
1957 image_height: None,
1958 }
1959 .links_json(),
1960 ),
1961 message(
1962 chat,
1963 "m8",
1964 None,
1965 jonas,
1966 at(0, 13, 40),
1967 "<p>Formula check: H<sub>2</sub>O and x<sup>2</sup> + y<sup>2</sup>. <span style=\"font-size:xx-small;\">Small print, reviewed by <at id=\"0\">Mara Lindqvist</at>.</span> <span style=\"font-size:x-large;\">Big news:</span> the <span style=\"font-size:x-large;\"><a href=\"https://example.com/notes\">release notes</a></span> are out.</p>",
1968 "[]",
1969 false,
1970 ),
1971 message(
1972 chat,
1973 "m9",
1974 None,
1975 (PRIYA_ID, priya_name),
1976 at(0, 13, 45),
1977 &format!(
1978 "<p>Ship it!</p><img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"Party\" itemtype=\"http://schema.skype.com/Giphy\">",
1979 demo_gifs::RECEIVED_GIF_KEY,
1980 demo_gifs::RECEIVED_GIF_SIZE.0,
1981 demo_gifs::RECEIVED_GIF_SIZE.1
1982 ),
1983 "[]",
1984 false,
1985 ),
1986 message(
1987 chat,
1988 FRENCH_MESSAGE,
1989 None,
1990 (LEA_ID, lea_name),
1991 at(0, 13, 47),
1992 "<p>Bonjour \u{e0} tous, la <strong>version 0.2</strong> est pr\u{ea}te. Pouvez-vous v\u{e9}rifier la liste de contr\u{f4}le avant vendredi\u{a0}?</p>",
1993 "[]",
1994 false,
1995 ),
1996 message(
1997 chat,
1998 SPANISH_MESSAGE,
1999 None,
2000 jonas,
2001 at(0, 13, 49),
2002 "<p>Gracias por el aviso. Probar\u{e9} la compilaci\u{f3}n esta tarde y os dir\u{e9} si algo falla.</p>",
2003 "[]",
2004 false,
2005 ),
2006 message(
2007 chat,
2008 "m10",
2009 None,
2010 (PRIYA_ID, priya_name),
2011 at(0, 13, 50),
2012 "<p><emoji id=\"heart\" alt=\"\u{2764}\u{fe0f}\" title=\"Heart\"></emoji></p>",
2013 &many,
2014 false,
2015 ),
2016 message(
2017 chat,
2018 "m11",
2019 None,
2020 me,
2021 at(0, 13, 51),
2022 "<p>\u{1f44d}\u{1f389}</p>",
2023 "[]",
2024 false,
2025 ),
2026 message(
2027 chat,
2028 "m12",
2029 None,
2030 (LEA_ID, lea_name),
2031 at(0, 13, 52),
2032 "<p><strong>1\u{fe0f}\u{20e3}Freeze the branch</strong></p><p><strong>2\u{fe0f}\u{20e3}Tag the release</strong></p><p>3\u{fe0f}\u{20e3} Publish the notes</p>",
2033 "[]",
2034 false,
2035 ),
2036 ]
2037}
2038
2039fn unread_messages() -> Vec<MessageRecord> {
2040 let me = (DEMO_USER_ID, DEMO_USER_NAME);
2041 let lea = (LEA_ID, "Lea Schneider");
2042 let tobias = (TOBIAS_ID, "Tobias Klein");
2043 let rows = [
2044 (
2045 "u1",
2046 me,
2047 at(1, 17, 5),
2048 "<p>Can you enable access for North?</p>",
2049 ),
2050 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
2051 (
2052 "u3",
2053 lea,
2054 at(0, 12, 40),
2055 "<p>Good morning, access is ready.</p>",
2056 ),
2057 (
2058 "u4",
2059 lea,
2060 at(0, 12, 41),
2061 "<p>Sign in with your company ID, no password needed.</p>",
2062 ),
2063 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
2064 ];
2065 rows.into_iter()
2066 .map(|(id, sender, time, html)| {
2067 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
2068 })
2069 .map(|record| match record.message_id.as_str() {
2070 "u5" => with_importance(record, MessageImportance::Urgent),
2071 _ => record,
2072 })
2073 .collect()
2074}
2075
2076const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2";
2077const DEMO_EXTRA_TABS: [&str; 6] = [
2078 "Incident dashboard",
2079 "Postmortems",
2080 "Escalation policy",
2081 "Status page",
2082 "Vendor contacts",
2083 "On-call calendar",
2084];
2085
2086fn demo_tab(
2087 channel_id: &str,
2088 name: &str,
2089 definition_id: &str,
2090 open_url: Option<&str>,
2091) -> ChannelTabRecord {
2092 ChannelTabRecord {
2093 tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")),
2094 name: name.to_owned(),
2095 definition_id: definition_id.to_owned(),
2096 open_url: open_url.map(str::to_owned),
2097 }
2098}
2099
2100fn demo_channel_tabs(channel_id: &str) -> Vec<ChannelTabRecord> {
2101 let mut tabs = vec![
2102 demo_tab(
2103 channel_id,
2104 "Runbook",
2105 "com.microsoft.teamspace.tab.web",
2106 Some("https://wiki.example.com/display/TEAM/Runbook"),
2107 ),
2108 demo_tab(
2109 channel_id,
2110 "Sprint board",
2111 "com.microsoft.teamspace.tab.planner",
2112 None,
2113 ),
2114 demo_tab(
2115 channel_id,
2116 "Team notes",
2117 "0d820ecd-def2-4297-adad-78056cde7c78",
2118 Some("https://onenote.example.com/notes"),
2119 ),
2120 ];
2121 if channel_id == DEMO_EXTRA_TABS_CHANNEL {
2122 tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| {
2123 demo_tab(
2124 channel_id,
2125 name,
2126 "com.microsoft.teamspace.tab.web",
2127 Some("https://wiki.example.com/display/TEAM/Page"),
2128 )
2129 }));
2130 }
2131 tabs
2132}
2133
2134fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
2135 DEMO_TEAM_ORDER
2136 .iter()
2137 .map(|team_id| TeamLayoutRecord {
2138 rights: store::TeamRights {
2139 add_channel: true,
2140 add_private_channel: true,
2141 ..Default::default()
2142 },
2143 team_id: (*team_id).to_owned(),
2144 hidden: *team_id == DEMO_HIDDEN_TEAM,
2145 channels: channels
2146 .iter()
2147 .filter(|channel| channel.team_id == *team_id)
2148 .map(|channel| ChannelLayoutRecord {
2149 substrate_group_id: None,
2150 channel_id: channel.id.clone(),
2151 general: channel.name == "General",
2152 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
2153 tabs: demo_channel_tabs(&channel.id),
2154 notifications: DEMO_CHANNEL_NOTIFICATIONS
2155 .iter()
2156 .find(|(id, _, _)| *id == channel.id)
2157 .map(|(_, level, include_replies)| ChannelNotifications {
2158 level: *level,
2159 include_replies: *include_replies,
2160 })
2161 .unwrap_or_default(),
2162 })
2163 .collect(),
2164 })
2165 .collect()
2166}
2167
2168const ROLLOUT_REPLIES: [(&str, &str); 12] = [
2169 (MARA_ID, "Staging looks good on my side."),
2170 (JONAS_ID, "Smoke tests passed, no regressions."),
2171 (PRIYA_ID, "Docs for the new settings page are merged."),
2172 (LEA_ID, "Support is briefed, nothing blocking."),
2173 (MARA_ID, "Can we keep the old export for one more release?"),
2174 (JONAS_ID, "Yes, behind a flag. I will add it today."),
2175 (PRIYA_ID, "Changelog draft is ready for review."),
2176 (LEA_ID, "Customer success wants a heads-up the day before."),
2177 (MARA_ID, "I will send that mail on Thursday."),
2178 (JONAS_ID, "Flag is in, rebuilding staging now."),
2179 (PRIYA_ID, "Rollback steps are in the runbook."),
2180 (LEA_ID, "All green from QA. Go for Friday."),
2181];
2182
2183fn channel_messages() -> Vec<MessageRecord> {
2184 let channel = "demo-channel-1-1";
2185 let mara = (MARA_ID, "Mara Lindqvist");
2186 let tobias = (TOBIAS_ID, "Tobias Klein");
2187 let people = [
2188 (MARA_ID, "Mara Lindqvist"),
2189 (JONAS_ID, "Jonas Ortega"),
2190 (PRIYA_ID, "Priya Nair"),
2191 (LEA_ID, "Lea Schneider"),
2192 ];
2193 let rollout_replies = ROLLOUT_REPLIES
2194 .iter()
2195 .enumerate()
2196 .map(|(index, (sender, text))| {
2197 let sender = people
2198 .iter()
2199 .copied()
2200 .find(|(id, _)| id == sender)
2201 .expect("known person");
2202 message(
2203 channel,
2204 &format!("t3r{}", index + 1),
2205 Some("t3"),
2206 sender,
2207 at(0, 9, 40) + Duration::minutes(6 * index as i64),
2208 &format!("<p>{text}</p>"),
2209 "[]",
2210 false,
2211 )
2212 });
2213 let mut records = vec![
2214 message(
2215 channel,
2216 "t1",
2217 None,
2218 mara,
2219 at(0, 8, 0),
2220 "<p>Weekly sync notes are up.</p>",
2221 "[]",
2222 false,
2223 ),
2224 message(
2225 channel,
2226 "t1r1",
2227 Some("t1"),
2228 tobias,
2229 at(0, 8, 20),
2230 "<p>Thanks, adding my items.</p>",
2231 "[]",
2232 false,
2233 ),
2234 with_subject(
2235 message(
2236 channel,
2237 "t3",
2238 None,
2239 tobias,
2240 at(0, 9, 30),
2241 "<p>Release build 42 is green, deploying to staging now.</p>",
2242 "[]",
2243 false,
2244 ),
2245 "Release 42 rollout",
2246 ),
2247 message(
2248 channel,
2249 "t2",
2250 None,
2251 tobias,
2252 at(0, 10, 0),
2253 "<p>Who owns the on-call handover?</p>",
2254 "[]",
2255 false,
2256 ),
2257 message(
2258 channel,
2259 "t4",
2260 None,
2261 mara,
2262 at(3, 8, 42),
2263 "<p>Sprint Demos.</p><p>I added you both to the sprint. <at id=\"0\">Tobias Klein</at> did you present everything about the migration tool? The spec is at <a href=\"https://wiki.example.com/display/TEAM/Settings+types+and+password+policies\">https://wiki.example.com/display/TEAM/Settings+types+and+password+policies</a>Can you please review it?</p>",
2264 "[]",
2265 false,
2266 ),
2267 message(
2268 channel,
2269 "t4r1",
2270 Some("t4"),
2271 tobias,
2272 at(0, 9, 15),
2273 "<p>Yes, all done.</p>",
2274 "[]",
2275 false,
2276 ),
2277 ];
2278 records.extend(rollout_replies);
2279 records.extend(code_post(channel, tobias));
2280 records.extend(shared_channel_messages(channel, mara, tobias));
2281 records
2282}
2283
2284fn code_post(channel: &str, tobias: (&str, &str)) -> Vec<MessageRecord> {
2285 let laughs = reactions_json(vec![reaction(
2286 "laugh",
2287 &[
2288 (PRIYA_ID, "Priya Nair", at(0, 11, 20)),
2289 (JONAS_ID, "Jonas Ortega", at(0, 11, 22)),
2290 ],
2291 )]);
2292 vec![
2293 with_subject(
2294 message(
2295 channel,
2296 "t8",
2297 None,
2298 tobias,
2299 at(0, 11, 5),
2300 "<p>I got this error message when running \"Invoke-WebRequest\" in the build script:</p><p>&nbsp;</p><p><code>Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.</code></p>",
2301 &laughs,
2302 false,
2303 ),
2304 "Build script error",
2305 ),
2306 message(
2307 channel,
2308 "t8r1",
2309 Some("t8"),
2310 (JONAS_ID, "Jonas Ortega"),
2311 at(0, 11, 30),
2312 "<p>Add <code>-UseBasicParsing</code> to the call, that fixes it.</p>",
2313 "[]",
2314 false,
2315 ),
2316 with_attachments(
2317 with_subject(
2318 message(
2319 channel,
2320 "t9",
2321 None,
2322 tobias,
2323 at(0, 12, 10),
2324 "<attachment id=\"announcement-card-demo\"></attachment><p>Please merge your last changes by Thursday 18:00. Anything later goes into release 44.</p>",
2325 "[]",
2326 false,
2327 ),
2328 "Code freeze starts Thursday",
2329 ),
2330 &format!(
2331 r#"[{{"content_type":"{ANNOUNCEMENT_BANNER_TYPE}","id":"announcement-card-demo","name":null,"url":null,"text":null,"content":{}}}]"#,
2332 serde_json::Value::String(
2333 r#"{"title":"Release 43 ships Friday","cardImageType":"colorTheme","cardImageDetails":{"colorTheme":"periwinkleBlue"}}"#.to_owned()
2334 )
2335 ),
2336 ),
2337 ]
2338}
2339
2340fn shared_channel_messages(
2341 channel: &str,
2342 mara: (&str, &str),
2343 tobias: (&str, &str),
2344) -> Vec<MessageRecord> {
2345 let priya = (PRIYA_ID, "Priya Nair");
2346 let jonas = (JONAS_ID, "Jonas Ortega");
2347 let reference = |name: &str, size: u64| {
2348 format!(
2349 r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"#
2350 )
2351 };
2352 vec![
2353 with_attachments(
2354 with_subject(
2355 message(
2356 channel,
2357 "t5",
2358 None,
2359 priya,
2360 at(1, 14, 5),
2361 "<p>Roadmap deck and checklist for Q4 are attached.</p>",
2362 "[]",
2363 false,
2364 ),
2365 "Q4 planning files",
2366 ),
2367 &format!(
2368 "[{},{}]",
2369 reference("Roadmap-Q4.pptx", 3_412_000),
2370 reference("Release-Checklist-Q4.xlsx", 48_213)
2371 ),
2372 ),
2373 message(
2374 channel,
2375 "t5r1",
2376 Some("t5"),
2377 jonas,
2378 at(1, 14, 30),
2379 "<p>Rollback steps are here: <a href=\"https://docs.example.org/runbooks/rollback\">https://docs.example.org/runbooks/rollback</a></p>",
2380 "[]",
2381 false,
2382 ),
2383 with_attachments(
2384 message(
2385 channel,
2386 "t6",
2387 None,
2388 mara,
2389 at(12, 10, 0),
2390 "<p>Postmortem draft for the September outage. Status page: <a href=\"https://status.example.com/incidents/2026-09\">https://status.example.com/incidents/2026-09</a></p>",
2391 "[]",
2392 false,
2393 ),
2394 &format!("[{}]", reference("Postmortem-Draft.docx", 91_400)),
2395 ),
2396 with_attachments(
2397 message(
2398 channel,
2399 "t7",
2400 None,
2401 tobias,
2402 at(20, 9, 0),
2403 "<p>Rollout plan for the new export, please review.</p>",
2404 "[]",
2405 false,
2406 ),
2407 &format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)),
2408 ),
2409 ]
2410}
2411
2412fn crc32(bytes: &[u8]) -> u32 {
2413 let mut crc = 0xffff_ffffu32;
2414 for byte in bytes {
2415 crc ^= u32::from(*byte);
2416 for _ in 0..8 {
2417 crc = if crc & 1 == 1 {
2418 (crc >> 1) ^ 0xedb8_8320
2419 } else {
2420 crc >> 1
2421 };
2422 }
2423 }
2424 !crc
2425}
2426
2427fn adler32(bytes: &[u8]) -> u32 {
2428 let (mut low, mut high) = (1u32, 0u32);
2429 for byte in bytes {
2430 low = (low + u32::from(*byte)) % 65521;
2431 high = (high + low) % 65521;
2432 }
2433 (high << 16) | low
2434}
2435
2436fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
2437 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
2438 let mut body = kind.to_vec();
2439 body.extend_from_slice(data);
2440 output.extend_from_slice(&body);
2441 output.extend_from_slice(&crc32(&body).to_be_bytes());
2442}
2443
2444fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
2445 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
2446}
2447
2448fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
2449 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
2450 let (x, y) = (column as f32, row as f32);
2451 let shade = y / height;
2452 let background = [
2453 (30. - 14. * shade) as u8,
2454 (41. - 16. * shade) as u8,
2455 (59. - 14. * shade) as u8,
2456 ];
2457 let bar_width = width / 14.;
2458 let slot = (x / bar_width) as usize;
2459 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
2460 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
2461 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
2462 let header = y < height * 0.1;
2463 if header {
2464 [22, 30, 45]
2465 } else if on_bars {
2466 if slot % 4 == 3 {
2467 [226, 87, 47]
2468 } else {
2469 [88, 133, 196]
2470 }
2471 } else if (y - height * 0.86).abs() < 1.5 {
2472 [71, 85, 105]
2473 } else {
2474 background
2475 }
2476}
2477
2478fn encode_png(palette: &Palette) -> Vec<u8> {
2479 let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32;
2480 encode_rgb(DEMO_PHOTO_SIDE, DEMO_PHOTO_SIDE, |column, row| {
2481 let (x, y) = ((column as f32 + 0.5) * scale, (row as f32 + 0.5) * scale);
2482 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2483 palette.skin
2484 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
2485 palette.hair
2486 } else if inside(x, y, (24., 50.), (22., 19.)) {
2487 palette.shirt
2488 } else {
2489 palette.background
2490 }
2491 })
2492}
2493
2494fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
2495 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
2496 for row in 0..height {
2497 raw.push(0);
2498 for column in 0..width {
2499 raw.extend_from_slice(&pixel(column, row));
2500 }
2501 }
2502 let mut zlib = vec![0x78, 0x01];
2503 let mut blocks = raw.chunks(65535).peekable();
2504 while let Some(block) = blocks.next() {
2505 zlib.push(u8::from(blocks.peek().is_none()));
2506 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
2507 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
2508 zlib.extend_from_slice(block);
2509 }
2510 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
2511 let mut header = Vec::new();
2512 header.extend_from_slice(&(width as u32).to_be_bytes());
2513 header.extend_from_slice(&(height as u32).to_be_bytes());
2514 header.extend_from_slice(&[8, 2, 0, 0, 0]);
2515 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
2516 png_chunk(&mut png, b"IHDR", &header);
2517 png_chunk(&mut png, b"IDAT", &zlib);
2518 png_chunk(&mut png, b"IEND", &[]);
2519 png
2520}
2521
2522pub fn team_members() -> Vec<crate::manage_team::TeamMember> {
2523 std::iter::once((DEMO_USER_ID, DEMO_USER_NAME, DEMO_USER_EMAIL))
2524 .chain(
2525 PEOPLE_DIRECTORY
2526 .iter()
2527 .map(|(user_id, name, _, email)| (*user_id, *name, *email)),
2528 )
2529 .enumerate()
2530 .map(
2531 |(index, (user_id, name, email))| crate::manage_team::TeamMember {
2532 user_id: Some(user_id.to_owned()),
2533 name: name.to_owned(),
2534 email: Some(email.to_owned()),
2535 owner: index == 1 || index == 3,
2536 },
2537 )
2538 .collect()
2539}
2540
2541#[cfg(test)]
2542mod tests {
2543 use super::*;
2544
2545 #[test]
2546 fn the_demo_has_one_important_and_one_urgent_message() {
2547 let store = Store::open_in_memory().unwrap();
2548 seed(&store);
2549 let importance = |chat: &str, message_id: &str| {
2550 store
2551 .messages(chat, None, 50)
2552 .unwrap()
2553 .into_iter()
2554 .find(|record| record.message_id == message_id)
2555 .map(|record| record.importance)
2556 };
2557 assert_eq!(
2558 importance(PRIORITY_CHAT, "p2"),
2559 Some(MessageImportance::High)
2560 );
2561 assert_eq!(
2562 importance(UNREAD_CHAT, "u5"),
2563 Some(MessageImportance::Urgent)
2564 );
2565 }
2566
2567 #[test]
2568 fn a_multi_forward_quotes_each_message_in_order_after_the_comment() {
2569 let store = Store::open_in_memory().unwrap();
2570 seed(&store);
2571 let chat = store
2572 .recent_chats(100)
2573 .unwrap()
2574 .into_iter()
2575 .find(|chat| chat.id == PRIORITY_CHAT)
2576 .unwrap();
2577 let item = |message_id: &str, text: &str| crate::message_actions::ForwardItem {
2578 message_id: message_id.to_owned(),
2579 author: "Synthetic Sender".to_owned(),
2580 time: "09:00".to_owned(),
2581 text: text.to_owned(),
2582 };
2583 let source = ForwardSource {
2584 conversation_id: PRIORITY_CHAT.to_owned(),
2585 messages: vec![item("m1", "first"), item("m2", "second")],
2586 };
2587 let (_, record) = forwarded_message(&chat, &source, "fyi", Utc::now());
2588 let html = &record.body_html;
2589 assert!(html.starts_with("<p>fyi</p>"));
2590 assert_eq!(html.matches(FORWARD_ITEMTYPE).count(), 2);
2591 assert!(html.find("first").unwrap() < html.find("second").unwrap());
2592 }
2593
2594 #[test]
2595 fn png_has_signature_and_ends_with_iend() {
2596 let png = encode_png(&MARA);
2597 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
2598 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
2599 }
2600
2601 #[test]
2602 fn crc_and_adler_match_known_values() {
2603 assert_eq!(crc32(b"IEND"), 0xae42_6082);
2604 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
2605 }
2606
2607 #[test]
2608 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
2609 let chat = mention_candidates("demo-chat-release", "ma");
2610 assert_eq!(chat.len(), 1);
2611 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
2612 let channel = mention_candidates("demo-channel-1-1", "gen");
2613 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
2614 let all = mention_candidates("demo-chat-release", "");
2615 assert_eq!(all.len(), 6);
2616 assert!(matches!(all[0], MentionCandidate::Everyone { .. }));
2617 assert!(
2618 mention_candidates("demo-chat-mara", "")
2619 .iter()
2620 .all(|candidate| !matches!(candidate, MentionCandidate::Everyone { .. }))
2621 );
2622 assert!(matches!(
2623 mention_candidates("demo-channel-1-1", "desi")[0],
2624 MentionCandidate::Tag { .. }
2625 ));
2626 }
2627
2628 #[test]
2629 fn new_group_chat_gets_a_title_and_the_first_message() {
2630 let people = vec![
2631 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
2632 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
2633 ];
2634 let now = Utc::now();
2635 let (chat, record) = new_chat(
2636 &[],
2637 &people,
2638 Some("Crew"),
2639 "Hello all",
2640 "Hello <i>all</i>",
2641 now,
2642 );
2643 assert_eq!(chat.id, "demo-chat-new-1");
2644 assert_eq!(chat.kind, "group");
2645 assert_eq!(chat.title, "Crew");
2646 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
2647 assert_eq!(chat.members.len(), 3);
2648 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
2649 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
2650 assert_eq!(chat.last_message_at, Some(now));
2651 assert_eq!(record.conversation_id, chat.id);
2652 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
2653 assert!(record.body_html.contains("Hello"));
2654 }
2655
2656 #[test]
2657 fn new_one_on_one_chat_has_no_title_and_counts_up() {
2658 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
2659 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
2660 assert_eq!(first.kind, "oneOnOne");
2661 assert!(first.title.is_empty());
2662 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
2663 assert_eq!(second.id, "demo-chat-new-2");
2664 }
2665
2666 #[test]
2667 fn sending_into_a_chat_refreshes_its_preview() {
2668 let base = ChatRecord {
2669 id: "demo-chat-x".to_owned(),
2670 unread: true,
2671 ..Default::default()
2672 };
2673 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
2674 assert!(!chat.unread);
2675 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
2676 assert_eq!(record.conversation_id, "demo-chat-x");
2677 }
2678
2679 #[test]
2680 fn demo_covers_the_sidebar_edge_cases() {
2681 let chats = demo_chats();
2682 assert!(chats.iter().any(|chat| chat.deleted));
2683 assert!(chats.iter().any(|chat| chat.title.len() > 40));
2684 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
2685 }
2686}