BlueGit

ict rusty-teams

Files

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

demo.rs

demo.rs 91.2 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 seed_agent_access(store);
925}
926
927pub fn agent_meeting_draft() -> mcp::MeetingDraft {
928 let start = at(-1, 10, 0);
929 mcp::MeetingDraft {
930 subject: "Release 42 go/no-go".to_owned(),
931 start,
932 end: start + Duration::minutes(30),
933 attendees: vec![
934 "mara.lindqvist@example.com".to_owned(),
935 "jonas.ortega@example.com".to_owned(),
936 ],
937 description:
938 "Walk through the regression results and decide on Friday's rollout.\nOwner: Mara"
939 .to_owned(),
940 }
941}
942
943const AGENT_DEMO_PROPOSAL: &str = "I ran the regression suite on staging: 412 passed, 0 failed. The release candidate is good to ship, @Mara Lindqvist.";
944
945fn seed_agent_access(store: &Store) {
946 let selected =
947 |ids: &[&str]| mcp::Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect());
948 mcp::save_policy(
949 store,
950 &mcp::AgentPolicy {
951 enabled: true,
952 chats: selected(&[RELEASE_CHAT, "demo-chat-mara", "demo-chat-meeting-standup"]),
953 channels: selected(&["demo-channel-1-1"]),
954 write: true,
955 calendar: true,
956 transcripts: false,
957 meetings: true,
958 ..mcp::AgentPolicy::default()
959 },
960 );
961 let _ = store.insert_agent_proposal(&store::AgentProposalRecord {
962 id: "demo-proposal".to_owned(),
963 conversation_id: RELEASE_CHAT.to_owned(),
964 reply_to_message_id: Some("m1".to_owned()),
965 text: AGENT_DEMO_PROPOSAL.to_owned(),
966 mentions: vec![store::AgentProposalMention {
967 user_id: MARA_ID.to_owned(),
968 name: "Mara Lindqvist".to_owned(),
969 }],
970 images: vec![store::AttachmentImage {
971 name: "image-1.png".to_owned(),
972 format: "image/png".to_owned(),
973 bytes: encode_png(&MARA),
974 width: Some(PHOTO_SIZE as u32),
975 height: Some(PHOTO_SIZE as u32),
976 }],
977 agent: Some("claude".to_owned()),
978 session_id: None,
979 created_at: Utc::now() - Duration::minutes(1),
980 state: "pending".to_owned(),
981 resolved_at: None,
982 });
983 let _ = store.insert_agent_reaction(&store::AgentReactionRecord {
984 id: "demo-reaction".to_owned(),
985 conversation_id: "demo-chat-mara".to_owned(),
986 message_id: "ml1".to_owned(),
987 emoji: "\u{1F44D}".to_owned(),
988 agent: Some("claude".to_owned()),
989 session_id: None,
990 created_at: Utc::now() - Duration::minutes(1),
991 state: "pending".to_owned(),
992 resolved_at: None,
993 });
994}
995
996fn photo(palette: &Palette) -> AvatarState {
997 crate::data::avatar_state_from("image/png", encode_png(palette), false)
998}
999
1000pub fn seed_directory(state: &mut AppState) {
1001 state.own_status = crate::own_status::demo_status();
1002 state.own_email = DEMO_USER_EMAIL.to_owned();
1003 state.own_time_zone = Some(DEMO_TIME_ZONE.to_owned());
1004 state.translation.settings = Some(language_settings());
1005 state.apply_regional_format();
1006 state.translation.languages = language_list();
1007 let directory = &mut state.directory;
1008 directory.me = Some(Person {
1009 user_id: DEMO_USER_ID.to_owned(),
1010 display_name: DEMO_USER_NAME.to_owned(),
1011 });
1012 let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
1013 directory.folders = vec![
1014 FolderInfo {
1015 id: FAVORITES_ID.to_owned(),
1016 name: String::new(),
1017 kind: FolderKind::Favorites,
1018 expanded: None,
1019 conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
1020 },
1021 FolderInfo {
1022 id: CUSTOMERS_FOLDER.to_owned(),
1023 name: "Customers".to_owned(),
1024 kind: FolderKind::UserCreated,
1025 expanded: None,
1026 conversation_ids: ids(&[
1027 "demo-chat-customer-1",
1028 "demo-chat-customer-2",
1029 "demo-chat-customer-3",
1030 "demo-chat-customer-4",
1031 ]),
1032 },
1033 FolderInfo {
1034 id: ATLAS_FOLDER.to_owned(),
1035 name: "Project Atlas".to_owned(),
1036 kind: FolderKind::UserCreated,
1037 expanded: None,
1038 conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
1039 },
1040 FolderInfo {
1041 id: TODO_FOLDER.to_owned(),
1042 name: "To do".to_owned(),
1043 kind: FolderKind::UserCreated,
1044 expanded: None,
1045 conversation_ids: Vec::new(),
1046 },
1047 ];
1048 state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]);
1049 let directory = &mut state.directory;
1050 directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
1051 directory
1052 .unread_counts
1053 .insert("demo-chat-atlas".to_owned(), 5);
1054 directory
1055 .unread_counts
1056 .insert("demo-chat-customer-1".to_owned(), 2);
1057 directory
1058 .unread_counts
1059 .insert("demo-chat-customer-2".to_owned(), 1);
1060 directory
1061 .unread_counts
1062 .insert("demo-chat-allhands".to_owned(), 120);
1063 directory
1064 .unread_importance
1065 .insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent);
1066 directory
1067 .unread_importance
1068 .insert("demo-chat-customer-1".to_owned(), MessageImportance::High);
1069 directory.set_avatar(MARA_ID, photo(&MARA));
1070 directory.set_avatar(PRIYA_ID, photo(&PRIYA));
1071 directory.set_avatar(TOBIAS_ID, photo(&TOBIAS));
1072 for (user_id, kind) in [
1073 (MARA_ID, PresenceKind::Available),
1074 (JONAS_ID, PresenceKind::Busy),
1075 (PRIYA_ID, PresenceKind::Away),
1076 (TOBIAS_ID, PresenceKind::Offline),
1077 (LEA_ID, PresenceKind::Busy),
1078 (DEMO_USER_ID, PresenceKind::Available),
1079 ] {
1080 directory.set_presence(user_id, kind);
1081 }
1082 directory.set_activity(JONAS_ID, Some(Activity::InACall));
1083 directory.set_activity(LEA_ID, Some(Activity::InAConferenceCall));
1084 let directory_path = image_directory();
1085 if std::fs::create_dir_all(&directory_path).is_ok() {
1086 let path = directory_path.join("staging-dashboard.png");
1087 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
1088 if std::fs::write(&path, png).is_ok() {
1089 state.directory.set_image(STAGING_IMAGE_KEY, &path);
1090 state.directory.set_image(LINK_IMAGE_KEY, &path);
1091 state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path);
1092 }
1093 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
1094 state.directory.set_image(
1095 demo_gifs::RECEIVED_GIF_KEY,
1096 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
1097 );
1098 }
1099 state.typing.start(
1100 "demo-chat-mara",
1101 MARA_ID,
1102 "Mara Lindqvist",
1103 Instant::now(),
1104 Utc::now(),
1105 );
1106 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
1107 state.last_sync = Some(Utc::now());
1108 state.apply_bot_titles();
1109 seed_message_actions(state);
1110}
1111
1112fn seed_message_actions(state: &mut AppState) {
1113 state.pins.insert(
1114 PINNED_CHANNEL.to_owned(),
1115 vec![PinnedMessage {
1116 message_id: PINNED_POST.to_owned(),
1117 pinned_at: Some(at(0, 9, 45)),
1118 parent_id: None,
1119 }],
1120 );
1121 state.pins.insert(
1122 RELEASE_CHAT.to_owned(),
1123 vec![PinnedMessage {
1124 message_id: PINNED_MESSAGE.to_owned(),
1125 pinned_at: Some(at(0, 11, 30)),
1126 parent_id: None,
1127 }],
1128 );
1129 let ids: Vec<String> = SAVED_MESSAGES.iter().map(|id| (*id).to_owned()).collect();
1130 let records = state
1131 .store
1132 .messages_by_id(RELEASE_CHAT, &ids)
1133 .unwrap_or_default();
1134 let saved = SAVED_MESSAGES
1135 .iter()
1136 .enumerate()
1137 .filter_map(|(position, id)| {
1138 let record = records.get(*id)?;
1139 Some(SavedMessage {
1140 conversation_id: record.conversation_id.clone(),
1141 message_id: record.message_id.clone(),
1142 root_id: record.message_id.clone(),
1143 author_id: record.sender_id.clone(),
1144 author_name: record.sender_name.clone(),
1145 preview: crate::rows::reply_excerpt(record),
1146 saved_at: at(position as i64, 15, 20),
1147 topic: None,
1148 })
1149 })
1150 .collect();
1151 state.saved.replace(saved);
1152}
1153
1154pub fn forwarded_message(
1155 chat: &ChatRecord,
1156 source: &ForwardSource,
1157 comment: &str,
1158 now: DateTime<Utc>,
1159) -> (ChatRecord, MessageRecord) {
1160 let comment_html = if comment.is_empty() {
1161 String::new()
1162 } else {
1163 format!("<p>{}</p>", teams_core::escape_html(comment))
1164 };
1165 let quotes: String = source
1166 .messages
1167 .iter()
1168 .map(|item| {
1169 format!(
1170 "<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
1171 teams_core::escape_html(&item.message_id),
1172 teams_core::escape_html(&item.author),
1173 teams_core::escape_html(&item.text),
1174 )
1175 })
1176 .collect();
1177 let preview = source
1178 .messages
1179 .first()
1180 .map(|item| item.text.as_str())
1181 .unwrap_or_default();
1182 send_in_chat(chat, preview, &format!("{comment_html}{quotes}"), now)
1183}
1184
1185#[allow(clippy::too_many_arguments)]
1186fn message(
1187 conversation: &str,
1188 id: &str,
1189 reply_to: Option<&str>,
1190 sender: (&str, &str),
1191 time: DateTime<Utc>,
1192 html: &str,
1193 reactions_json: &str,
1194 edited: bool,
1195) -> MessageRecord {
1196 MessageRecord {
1197 conversation_id: conversation.to_owned(),
1198 message_id: id.to_owned(),
1199 reply_to_id: reply_to.map(str::to_owned),
1200 sender_id: Some(sender.0.to_owned()),
1201 sender_name: Some(sender.1.to_owned()),
1202 sender_application_id: None,
1203 links_json: "[]".to_owned(),
1204 created_at: time,
1205 edited_at: edited.then_some(time + Duration::minutes(2)),
1206 deleted: false,
1207 body_html: html.to_owned(),
1208 attachments_json: "[]".to_owned(),
1209 reactions_json: reactions_json.to_owned(),
1210 mentions_json: "[]".to_owned(),
1211 subject: None,
1212 call_event_json: None,
1213 importance: Default::default(),
1214 }
1215}
1216
1217pub fn roster_record(
1218 conversation: &str,
1219 id: &str,
1220 time: DateTime<Utc>,
1221 event: &teams_core::roster_event::RosterEvent,
1222) -> MessageRecord {
1223 MessageRecord {
1224 conversation_id: conversation.to_owned(),
1225 message_id: id.to_owned(),
1226 created_at: time,
1227 links_json: "[]".to_owned(),
1228 attachments_json: "[]".to_owned(),
1229 reactions_json: "[]".to_owned(),
1230 mentions_json: "[]".to_owned(),
1231 call_event_json: Some(event.to_json()),
1232 ..MessageRecord::default()
1233 }
1234}
1235
1236fn call_record(
1237 conversation: &str,
1238 id: &str,
1239 time: DateTime<Utc>,
1240 event: CallEvent,
1241) -> MessageRecord {
1242 MessageRecord {
1243 conversation_id: conversation.to_owned(),
1244 message_id: id.to_owned(),
1245 created_at: time,
1246 links_json: "[]".to_owned(),
1247 attachments_json: "[]".to_owned(),
1248 reactions_json: "[]".to_owned(),
1249 mentions_json: "[]".to_owned(),
1250 call_event_json: Some(event.to_json()),
1251 ..MessageRecord::default()
1252 }
1253}
1254
1255fn call_event(
1256 phase: CallPhase,
1257 call_id: &str,
1258 initiator: (&str, &str),
1259 duration_seconds: Option<u64>,
1260 participant_ids: &[&str],
1261) -> CallEvent {
1262 CallEvent {
1263 phase,
1264 call_type: CallType::Call,
1265 call_id: call_id.to_owned(),
1266 duration_seconds,
1267 initiator_id: Some(initiator.0.to_owned()),
1268 initiator_name: Some(initiator.1.to_owned()),
1269 participant_ids: participant_ids.iter().map(|id| (*id).to_owned()).collect(),
1270 participant_names: Vec::new(),
1271 recording: None,
1272 }
1273}
1274
1275fn call_messages() -> Vec<MessageRecord> {
1276 let mara = (MARA_ID, "Mara Lindqvist");
1277 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1278 let jonas = (JONAS_ID, "Jonas Ortega");
1279 let both = [DEMO_USER_ID, MARA_ID];
1280 vec![
1281 call_record(
1282 "demo-chat-mara",
1283 "call-1-started",
1284 at(0, 12, 4),
1285 call_event(CallPhase::Started, "demo-call-1", me, None, &[]),
1286 ),
1287 call_record(
1288 "demo-chat-mara",
1289 "call-1-ended",
1290 at(0, 12, 16),
1291 call_event(CallPhase::Ended, "demo-call-1", me, Some(723), &both),
1292 ),
1293 call_record(
1294 "demo-chat-mara",
1295 "call-2-started",
1296 at(0, 13, 9),
1297 call_event(CallPhase::Started, "demo-call-2", mara, None, &[]),
1298 ),
1299 call_record(
1300 "demo-chat-mara",
1301 "call-2-ended",
1302 at(0, 13, 10),
1303 call_event(CallPhase::Ended, "demo-call-2", mara, Some(60), &[MARA_ID]),
1304 ),
1305 call_record(
1306 "demo-chat-meeting-standup",
1307 "call-3-started",
1308 at(0, 9, 50),
1309 CallEvent {
1310 call_type: CallType::Meeting,
1311 ..call_event(CallPhase::Started, "demo-call-3", jonas, None, &[])
1312 },
1313 ),
1314 ]
1315}
1316
1317fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord {
1318 record.importance = importance;
1319 record
1320}
1321
1322fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1323 record.subject = Some(subject.to_owned());
1324 record
1325}
1326
1327/// A Graph forward of a Teams video clip, as Teams sends a forwarded phone recording.
1328fn forwarded_clip_attachments(message_id: &str, sender_id: &str) -> String {
1329 let content = serde_json::json!({
1330 "originalMessageId": message_id,
1331 "originalMessageContent": format!(
1332 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>"#
1333 ),
1334 "originalMessageSender": {"user": {"id": sender_id, "displayName": null}},
1335 });
1336 serde_json::json!([{
1337 "content_type": "forwardedMessageReference",
1338 "id": message_id,
1339 "content": content.to_string(),
1340 }])
1341 .to_string()
1342}
1343
1344fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
1345 record.attachments_json = attachments_json.to_owned();
1346 record
1347}
1348
1349fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {
1350 record.links_json = links_json;
1351 record
1352}
1353
1354pub fn link_preview(url: &str) -> Option<LinkPreview> {
1355 Some(LinkPreview {
1356 url: url.to_owned(),
1357 title: Some("Release checklist Q4".to_owned()),
1358 description: Some(
1359 "Everything that has to be green before the release candidate goes out on Friday."
1360 .to_owned(),
1361 ),
1362 image_url: Some(LINK_IMAGE_KEY.to_owned()),
1363 image_width: Some(LINK_IMAGE_SIZE.0),
1364 image_height: Some(LINK_IMAGE_SIZE.1),
1365 })
1366}
1367
1368fn bot_messages() -> Vec<MessageRecord> {
1369 let card = serde_json::json!({
1370 "type": "AdaptiveCard",
1371 "body": [
1372 {"type": "ColumnSet", "columns": [
1373 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
1374 {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"}
1375 ]},
1376 {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [
1377 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"}
1378 ]}
1379 ]},
1380 {"type": "ColumnSet", "separator": true, "columns": [
1381 {"type": "Column", "width": "auto", "items": [
1382 {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"}
1383 ]},
1384 {"type": "Column", "width": "stretch", "items": [
1385 {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"},
1386 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
1387 ]}
1388 ]},
1389 {"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."},
1390 {"type": "ActionSet", "actions": [
1391 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
1392 {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
1393 {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
1394 {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}},
1395 {"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}},
1396 {"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]},
1397 {"type": "Action.ShowCard", "title": "Details", "card": {"body": [
1398 {"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."}
1399 ]}}
1400 ]}
1401 ]
1402 });
1403 let mut messages = vec![
1404 bot_card_message("b1", at(0, 13, 45), &card),
1405 bot_card_message("b2", at(0, 13, 52), &input_card()),
1406 bot_card_message(
1407 "b3",
1408 at(0, 13, 58),
1409 &crate::demo_input_cards::all_inputs_card(),
1410 ),
1411 ];
1412 messages.extend(
1413 crate::demo_cards::behaviour_cards()
1414 .iter()
1415 .zip(0u32..)
1416 .map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),
1417 );
1418 messages.extend(crate::demo_chart_cards::cards().iter().zip(0..).map(
1419 |(chart_card, minute)| {
1420 bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)
1421 },
1422 ));
1423 let mut webhook = bot_card_message("w1", at(0, 16, 0), &connector_card());
1424 webhook.attachments_json = webhook.attachments_json.replace(
1425 "application/vnd.microsoft.card.adaptive",
1426 "application/vnd.microsoft.teams.card.o365connector",
1427 );
1428 messages.push(webhook);
1429 messages
1430}
1431
1432fn connector_card() -> serde_json::Value {
1433 serde_json::json!({
1434 "@type": "MessageCard",
1435 "summary": "Build failed",
1436 "title": "Pipeline main",
1437 "sections": [{
1438 "activityTitle": "Build 128 failed",
1439 "activitySubtitle": "on agent 3",
1440 "facts": [{"name": "Branch", "value": "main"}, {"name": "Duration", "value": "4 min"}],
1441 "text": "See the log for details."
1442 }],
1443 "potentialAction": [{
1444 "@type": "OpenUri",
1445 "name": "Open log",
1446 "targets": [{"os": "default", "uri": "https://example.com/ci/128"}]
1447 }]
1448 })
1449}
1450
1451fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
1452 let attachments = serde_json::json!([{
1453 "content_type": "application/vnd.microsoft.card.adaptive",
1454 "name": null,
1455 "url": null,
1456 "text": null,
1457 "content": card.to_string()
1458 }]);
1459 let mut record = with_attachments(
1460 message(
1461 BOT_CHAT,
1462 id,
1463 None,
1464 ("", BOT_NAME),
1465 time,
1466 &format!("<attachment id=\"{id}\"></attachment>"),
1467 "[]",
1468 false,
1469 ),
1470 &attachments.to_string(),
1471 );
1472 record.sender_id = None;
1473 record.sender_application_id = Some(BOT_ID.to_owned());
1474 record
1475}
1476
1477fn input_card() -> serde_json::Value {
1478 serde_json::json!({
1479 "type": "AdaptiveCard",
1480 "body": [
1481 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"},
1482 {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"},
1483 {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true},
1484 {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"},
1485 {"type": "ColumnSet", "columns": [
1486 {"type": "Column", "width": "stretch", "items": [
1487 {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4}
1488 ]},
1489 {"type": "Column", "width": "stretch", "items": [
1490 {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"}
1491 ]},
1492 {"type": "Column", "width": "stretch", "items": [
1493 {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"}
1494 ]}
1495 ]},
1496 {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [
1497 {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"}
1498 ]},
1499 {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [
1500 {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"}
1501 ]},
1502 {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [
1503 {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"}
1504 ]},
1505 {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"}
1506 ],
1507 "actions": [
1508 {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}},
1509 {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}}
1510 ]
1511 })
1512}
1513
1514fn bot_app() -> ChatApp {
1515 ChatApp {
1516 app_id: "demo-app-wiki".to_owned(),
1517 name: BOT_APP_NAME.to_owned(),
1518 bot_ids: vec![BOT_ID.to_owned()],
1519 small_image_url: None,
1520 accent_color: None,
1521 web_application_resource: None,
1522 }
1523}
1524
1525pub async fn card_answer(task: CardTask) -> CardAnswer {
1526 tokio::time::sleep(CARD_ANSWER_DELAY).await;
1527 let data = match task {
1528 CardTask::Submit(_) => {
1529 return Ok((
1530 CardActionOutcome::Message("Settings saved".into()),
1531 Some((bot_app(), BOT_ID.to_owned())),
1532 ));
1533 }
1534 CardTask::Action(action) => match action.invoke_payload() {
1535 Some(payload) => payload.value,
1536 None => return Err("Not supported".to_owned()),
1537 },
1538 };
1539 let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch")
1540 {
1541 CardActionOutcome::Dialog(TaskDialog {
1542 title: None,
1543 width: 520,
1544 height: 300,
1545 kind: TaskDialogKind::Card(settings_card().to_string()),
1546 })
1547 } else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") {
1548 CardActionOutcome::Failed("The app answered 500: demo failure".into())
1549 } else {
1550 CardActionOutcome::Sent
1551 };
1552 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
1553}
1554
1555pub async fn refresh_answer() -> CardAnswer {
1556 tokio::time::sleep(CARD_ANSWER_DELAY).await;
1557 Ok((
1558 CardActionOutcome::ReplaceCard(crate::demo_cards::refreshed_card().to_string()),
1559 Some((bot_app(), BOT_ID.to_owned())),
1560 ))
1561}
1562
1563fn settings_card() -> serde_json::Value {
1564 serde_json::json!({
1565 "type": "AdaptiveCard",
1566 "body": [
1567 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
1568 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."},
1569 {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [
1570 {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"}
1571 ]},
1572 {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"}
1573 ],
1574 "actions": [
1575 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
1576 ]
1577 })
1578}
1579
1580pub const DEMO_TENANT_ID: &str = "demo-tenant";
1581const 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";
1582
1583fn meeting_link_messages() -> Vec<MessageRecord> {
1584 let mara = (MARA_ID, "Mara Lindqvist");
1585 vec![message(
1586 "demo-chat-mara",
1587 "ml1",
1588 None,
1589 mara,
1590 at(0, 13, 38),
1591 &format!(
1592 "<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"
1593 ),
1594 "[]",
1595 false,
1596 )]
1597}
1598
1599fn standup_messages() -> Vec<MessageRecord> {
1600 let jonas = (JONAS_ID, "Jonas Ortega");
1601 let priya = (PRIYA_ID, "Priya Nair");
1602 vec![
1603 with_attachments(
1604 message(
1605 "demo-chat-meeting-standup",
1606 "su1",
1607 None,
1608 priya,
1609 at(0, 9, 30),
1610 "<p>Notes from today.</p>",
1611 "[]",
1612 false,
1613 ),
1614 r#"[{"content_type":"reference","name":"Standup-notes.docx","url":"https://example.com/files/standup-notes.docx","text":null,"size":38900}]"#,
1615 ),
1616 with_attachments(
1617 message(
1618 "demo-chat-meeting-standup",
1619 "su2",
1620 None,
1621 jonas,
1622 at(0, 9, 45),
1623 "<p>Recording is available</p>",
1624 "[]",
1625 false,
1626 ),
1627 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}]"#,
1628 ),
1629 with_links(
1630 message(
1631 "demo-chat-meeting-standup",
1632 "su3",
1633 None,
1634 jonas,
1635 at(0, 9, 50),
1636 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1637 "[]",
1638 false,
1639 ),
1640 link_preview("https://example.com/checklist")
1641 .map(|preview| preview.links_json())
1642 .unwrap_or_default(),
1643 ),
1644 message(
1645 "demo-chat-meeting-standup",
1646 "su4",
1647 None,
1648 priya,
1649 at(0, 9, 52),
1650 "<p>I will quickly fix the comments and then push the final version before the review starts.</p>",
1651 "[]",
1652 false,
1653 ),
1654 ]
1655}
1656
1657fn notes_messages() -> Vec<MessageRecord> {
1658 vec![message(
1659 NOTES_CHAT_ID,
1660 "n1",
1661 None,
1662 (DEMO_USER_ID, DEMO_USER_NAME),
1663 at(0, 8, 20),
1664 "<p>Release notes draft</p>",
1665 "[]",
1666 false,
1667 )]
1668}
1669
1670fn priority_messages() -> Vec<MessageRecord> {
1671 let priya = (PRIYA_ID, "Priya Nair");
1672 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1673 vec![
1674 message(
1675 PRIORITY_CHAT,
1676 "p1",
1677 None,
1678 me,
1679 at(0, 10, 40),
1680 "<p>Have you seen the error on staging yet?</p>",
1681 "[]",
1682 false,
1683 ),
1684 message(
1685 PRIORITY_CHAT,
1686 "p2",
1687 None,
1688 priya,
1689 at(0, 10, 47),
1690 &format!(
1691 "<p>Yes, here is the screenshot:</p><img src=\"{PENDING_IMAGE_KEY}\" width=\"1280\" height=\"720\">"
1692 ),
1693 "[]",
1694 false,
1695 ),
1696 ]
1697 .into_iter()
1698 .map(|record| match record.message_id.as_str() {
1699 "p2" => with_importance(record, MessageImportance::High),
1700 _ => record,
1701 })
1702 .collect()
1703}
1704
1705fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
1706 users
1707 .iter()
1708 .map(|(user_id, user_name, created_at)| {
1709 serde_json::json!({
1710 "reaction_type": kind,
1711 "user_id": user_id,
1712 "user_name": user_name,
1713 "created_at": created_at,
1714 })
1715 })
1716 .collect()
1717}
1718
1719fn reactions_json(groups: Vec<Vec<serde_json::Value>>) -> String {
1720 serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string()
1721}
1722
1723fn release_messages() -> Vec<MessageRecord> {
1724 let chat = RELEASE_CHAT;
1725 let mara = (MARA_ID, "Mara Lindqvist");
1726 let jonas = (JONAS_ID, "Jonas Ortega");
1727 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1728 let jonas_name = "Jonas Ortega";
1729 let priya_name = "Priya Nair";
1730 let lea_name = "Lea Schneider";
1731 let mara_name = "Mara Lindqvist";
1732 let tobias_name = "Tobias Klein";
1733 let likes = reactions_json(vec![reaction(
1734 "like",
1735 &[
1736 (JONAS_ID, jonas_name, at(1, 16, 30)),
1737 (PRIYA_ID, priya_name, at(1, 17, 2)),
1738 (LEA_ID, lea_name, at(0, 8, 15)),
1739 ],
1740 )]);
1741 let hearts = reactions_json(vec![reaction(
1742 "heart",
1743 &[
1744 (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)),
1745 (JONAS_ID, jonas_name, at(0, 10, 33)),
1746 ],
1747 )]);
1748 let single = reactions_json(vec![reaction(
1749 "laugh",
1750 &[(PRIYA_ID, priya_name, at(0, 9, 10))],
1751 )]);
1752 let many = reactions_json(vec![
1753 reaction(
1754 "like",
1755 &[
1756 (MARA_ID, mara_name, at(0, 13, 37)),
1757 (JONAS_ID, jonas_name, at(0, 13, 38)),
1758 (PRIYA_ID, priya_name, at(0, 13, 40)),
1759 (LEA_ID, lea_name, at(0, 13, 45)),
1760 (TOBIAS_ID, tobias_name, at(0, 13, 50)),
1761 ],
1762 ),
1763 reaction(
1764 "heart",
1765 &[
1766 (LEA_ID, lea_name, at(0, 13, 46)),
1767 (TOBIAS_ID, tobias_name, at(0, 13, 51)),
1768 ],
1769 ),
1770 reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]),
1771 ]);
1772 vec![
1773 message(
1774 chat,
1775 "m1",
1776 None,
1777 mara,
1778 at(1, 16, 20),
1779 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
1780 "[]",
1781 false,
1782 ),
1783 message(
1784 chat,
1785 "m2",
1786 None,
1787 mara,
1788 at(1, 16, 22),
1789 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
1790 &likes,
1791 false,
1792 ),
1793 with_links(
1794 message(
1795 chat,
1796 "m2a",
1797 None,
1798 mara,
1799 at(1, 16, 23),
1800 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1801 "[]",
1802 false,
1803 ),
1804 link_preview("https://example.com/checklist")
1805 .map(|preview| preview.links_json())
1806 .unwrap_or_default(),
1807 ),
1808 message(
1809 chat,
1810 "m2b",
1811 None,
1812 mara,
1813 at(1, 16, 40),
1814 &format!(
1815 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
1816 STAGING_SIZE.0, STAGING_SIZE.1
1817 ),
1818 "[]",
1819 false,
1820 ),
1821 with_attachments(
1822 message(
1823 chat,
1824 "m2c",
1825 None,
1826 mara,
1827 at(1, 16, 41),
1828 "<p>Checklist and rollout plan attached.</p>",
1829 "[]",
1830 false,
1831 ),
1832 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}]"#,
1833 ),
1834 message(
1835 chat,
1836 "m3",
1837 None,
1838 me,
1839 at(0, 9, 2),
1840 "<p>I'll take the changelog.</p>",
1841 &single,
1842 false,
1843 ),
1844 message(
1845 chat,
1846 "m4",
1847 None,
1848 jonas,
1849 at(0, 10, 14),
1850 "<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>",
1851 "[]",
1852 false,
1853 ),
1854 message(
1855 chat,
1856 "m5",
1857 None,
1858 mara,
1859 at(0, 10, 31),
1860 "<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>",
1861 &hearts,
1862 true,
1863 ),
1864 message(
1865 chat,
1866 "m5b",
1867 None,
1868 mara,
1869 at(0, 10, 40),
1870 "<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>",
1871 "[]",
1872 false,
1873 ),
1874 message(
1875 chat,
1876 "m5c",
1877 None,
1878 jonas,
1879 at(0, 11, 5),
1880 "<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>",
1881 "[]",
1882 false,
1883 ),
1884 message(
1885 chat,
1886 "m5d",
1887 None,
1888 (PRIYA_ID, priya_name),
1889 at(0, 12, 20),
1890 &format!(
1891 "<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>"
1892 ),
1893 "[]",
1894 false,
1895 ),
1896 message(
1897 chat,
1898 "m5e",
1899 None,
1900 jonas,
1901 at(0, 12, 40),
1902 "<p>Context from the old planning chat.</p><attachment id=\"1789000000000\"></attachment>",
1903 r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"id":"1789000000000","content":null,"unavailable":true}]"#,
1904 false,
1905 ),
1906 with_attachments(
1907 message(
1908 chat,
1909 "m5f",
1910 None,
1911 (PRIYA_ID, priya_name),
1912 at(0, 12, 45),
1913 "<attachment id=\"1791000000000\"></attachment>",
1914 "[]",
1915 false,
1916 ),
1917 &forwarded_clip_attachments("1791000000000", TOBIAS_ID),
1918 ),
1919 message(
1920 chat,
1921 "m6",
1922 None,
1923 me,
1924 at(0, 13, 35),
1925 "<p>Thanks, renamed. Tagging now.</p>",
1926 "[]",
1927 false,
1928 ),
1929 message(
1930 chat,
1931 "m7",
1932 None,
1933 me,
1934 at(0, 13, 36),
1935 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
1936 &many,
1937 false,
1938 ),
1939 with_links(
1940 message(
1941 chat,
1942 "m7a",
1943 None,
1944 me,
1945 at(0, 13, 37),
1946 "<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",
1947 "[]",
1948 false,
1949 ),
1950 LinkPreview {
1951 url: "https://example.com/notes".to_owned(),
1952 title: Some("Release notes 0.2".to_owned()),
1953 description: Some("What changed since 0.1".to_owned()),
1954 image_url: None,
1955 image_width: None,
1956 image_height: None,
1957 }
1958 .links_json(),
1959 ),
1960 message(
1961 chat,
1962 "m8",
1963 None,
1964 jonas,
1965 at(0, 13, 40),
1966 "<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>",
1967 "[]",
1968 false,
1969 ),
1970 message(
1971 chat,
1972 "m9",
1973 None,
1974 (PRIYA_ID, priya_name),
1975 at(0, 13, 45),
1976 &format!(
1977 "<p>Ship it!</p><img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"Party\" itemtype=\"http://schema.skype.com/Giphy\">",
1978 demo_gifs::RECEIVED_GIF_KEY,
1979 demo_gifs::RECEIVED_GIF_SIZE.0,
1980 demo_gifs::RECEIVED_GIF_SIZE.1
1981 ),
1982 "[]",
1983 false,
1984 ),
1985 message(
1986 chat,
1987 FRENCH_MESSAGE,
1988 None,
1989 (LEA_ID, lea_name),
1990 at(0, 13, 47),
1991 "<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>",
1992 "[]",
1993 false,
1994 ),
1995 message(
1996 chat,
1997 SPANISH_MESSAGE,
1998 None,
1999 jonas,
2000 at(0, 13, 49),
2001 "<p>Gracias por el aviso. Probar\u{e9} la compilaci\u{f3}n esta tarde y os dir\u{e9} si algo falla.</p>",
2002 "[]",
2003 false,
2004 ),
2005 message(
2006 chat,
2007 "m10",
2008 None,
2009 (PRIYA_ID, priya_name),
2010 at(0, 13, 50),
2011 "<p><emoji id=\"heart\" alt=\"\u{2764}\u{fe0f}\" title=\"Heart\"></emoji></p>",
2012 &many,
2013 false,
2014 ),
2015 message(
2016 chat,
2017 "m11",
2018 None,
2019 me,
2020 at(0, 13, 51),
2021 "<p>\u{1f44d}\u{1f389}</p>",
2022 "[]",
2023 false,
2024 ),
2025 message(
2026 chat,
2027 "m12",
2028 None,
2029 (LEA_ID, lea_name),
2030 at(0, 13, 52),
2031 "<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>",
2032 "[]",
2033 false,
2034 ),
2035 ]
2036}
2037
2038fn unread_messages() -> Vec<MessageRecord> {
2039 let me = (DEMO_USER_ID, DEMO_USER_NAME);
2040 let lea = (LEA_ID, "Lea Schneider");
2041 let tobias = (TOBIAS_ID, "Tobias Klein");
2042 let rows = [
2043 (
2044 "u1",
2045 me,
2046 at(1, 17, 5),
2047 "<p>Can you enable access for North?</p>",
2048 ),
2049 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
2050 (
2051 "u3",
2052 lea,
2053 at(0, 12, 40),
2054 "<p>Good morning, access is ready.</p>",
2055 ),
2056 (
2057 "u4",
2058 lea,
2059 at(0, 12, 41),
2060 "<p>Sign in with your company ID, no password needed.</p>",
2061 ),
2062 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
2063 ];
2064 rows.into_iter()
2065 .map(|(id, sender, time, html)| {
2066 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
2067 })
2068 .map(|record| match record.message_id.as_str() {
2069 "u5" => with_importance(record, MessageImportance::Urgent),
2070 _ => record,
2071 })
2072 .collect()
2073}
2074
2075const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2";
2076const DEMO_EXTRA_TABS: [&str; 6] = [
2077 "Incident dashboard",
2078 "Postmortems",
2079 "Escalation policy",
2080 "Status page",
2081 "Vendor contacts",
2082 "On-call calendar",
2083];
2084
2085fn demo_tab(
2086 channel_id: &str,
2087 name: &str,
2088 definition_id: &str,
2089 open_url: Option<&str>,
2090) -> ChannelTabRecord {
2091 ChannelTabRecord {
2092 tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")),
2093 name: name.to_owned(),
2094 definition_id: definition_id.to_owned(),
2095 open_url: open_url.map(str::to_owned),
2096 }
2097}
2098
2099fn demo_channel_tabs(channel_id: &str) -> Vec<ChannelTabRecord> {
2100 let mut tabs = vec![
2101 demo_tab(
2102 channel_id,
2103 "Runbook",
2104 "com.microsoft.teamspace.tab.web",
2105 Some("https://wiki.example.com/display/TEAM/Runbook"),
2106 ),
2107 demo_tab(
2108 channel_id,
2109 "Sprint board",
2110 "com.microsoft.teamspace.tab.planner",
2111 None,
2112 ),
2113 demo_tab(
2114 channel_id,
2115 "Team notes",
2116 "0d820ecd-def2-4297-adad-78056cde7c78",
2117 Some("https://onenote.example.com/notes"),
2118 ),
2119 ];
2120 if channel_id == DEMO_EXTRA_TABS_CHANNEL {
2121 tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| {
2122 demo_tab(
2123 channel_id,
2124 name,
2125 "com.microsoft.teamspace.tab.web",
2126 Some("https://wiki.example.com/display/TEAM/Page"),
2127 )
2128 }));
2129 }
2130 tabs
2131}
2132
2133fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
2134 DEMO_TEAM_ORDER
2135 .iter()
2136 .map(|team_id| TeamLayoutRecord {
2137 rights: store::TeamRights {
2138 add_channel: true,
2139 add_private_channel: true,
2140 ..Default::default()
2141 },
2142 team_id: (*team_id).to_owned(),
2143 hidden: *team_id == DEMO_HIDDEN_TEAM,
2144 channels: channels
2145 .iter()
2146 .filter(|channel| channel.team_id == *team_id)
2147 .map(|channel| ChannelLayoutRecord {
2148 substrate_group_id: None,
2149 channel_id: channel.id.clone(),
2150 general: channel.name == "General",
2151 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
2152 tabs: demo_channel_tabs(&channel.id),
2153 notifications: DEMO_CHANNEL_NOTIFICATIONS
2154 .iter()
2155 .find(|(id, _, _)| *id == channel.id)
2156 .map(|(_, level, include_replies)| ChannelNotifications {
2157 level: *level,
2158 include_replies: *include_replies,
2159 })
2160 .unwrap_or_default(),
2161 })
2162 .collect(),
2163 })
2164 .collect()
2165}
2166
2167const ROLLOUT_REPLIES: [(&str, &str); 12] = [
2168 (MARA_ID, "Staging looks good on my side."),
2169 (JONAS_ID, "Smoke tests passed, no regressions."),
2170 (PRIYA_ID, "Docs for the new settings page are merged."),
2171 (LEA_ID, "Support is briefed, nothing blocking."),
2172 (MARA_ID, "Can we keep the old export for one more release?"),
2173 (JONAS_ID, "Yes, behind a flag. I will add it today."),
2174 (PRIYA_ID, "Changelog draft is ready for review."),
2175 (LEA_ID, "Customer success wants a heads-up the day before."),
2176 (MARA_ID, "I will send that mail on Thursday."),
2177 (JONAS_ID, "Flag is in, rebuilding staging now."),
2178 (PRIYA_ID, "Rollback steps are in the runbook."),
2179 (LEA_ID, "All green from QA. Go for Friday."),
2180];
2181
2182fn channel_messages() -> Vec<MessageRecord> {
2183 let channel = "demo-channel-1-1";
2184 let mara = (MARA_ID, "Mara Lindqvist");
2185 let tobias = (TOBIAS_ID, "Tobias Klein");
2186 let people = [
2187 (MARA_ID, "Mara Lindqvist"),
2188 (JONAS_ID, "Jonas Ortega"),
2189 (PRIYA_ID, "Priya Nair"),
2190 (LEA_ID, "Lea Schneider"),
2191 ];
2192 let rollout_replies = ROLLOUT_REPLIES
2193 .iter()
2194 .enumerate()
2195 .map(|(index, (sender, text))| {
2196 let sender = people
2197 .iter()
2198 .copied()
2199 .find(|(id, _)| id == sender)
2200 .expect("known person");
2201 message(
2202 channel,
2203 &format!("t3r{}", index + 1),
2204 Some("t3"),
2205 sender,
2206 at(0, 9, 40) + Duration::minutes(6 * index as i64),
2207 &format!("<p>{text}</p>"),
2208 "[]",
2209 false,
2210 )
2211 });
2212 let mut records = vec![
2213 message(
2214 channel,
2215 "t1",
2216 None,
2217 mara,
2218 at(0, 8, 0),
2219 "<p>Weekly sync notes are up.</p>",
2220 "[]",
2221 false,
2222 ),
2223 message(
2224 channel,
2225 "t1r1",
2226 Some("t1"),
2227 tobias,
2228 at(0, 8, 20),
2229 "<p>Thanks, adding my items.</p>",
2230 "[]",
2231 false,
2232 ),
2233 with_subject(
2234 message(
2235 channel,
2236 "t3",
2237 None,
2238 tobias,
2239 at(0, 9, 30),
2240 "<p>Release build 42 is green, deploying to staging now.</p>",
2241 "[]",
2242 false,
2243 ),
2244 "Release 42 rollout",
2245 ),
2246 message(
2247 channel,
2248 "t2",
2249 None,
2250 tobias,
2251 at(0, 10, 0),
2252 "<p>Who owns the on-call handover?</p>",
2253 "[]",
2254 false,
2255 ),
2256 message(
2257 channel,
2258 "t4",
2259 None,
2260 mara,
2261 at(3, 8, 42),
2262 "<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>",
2263 "[]",
2264 false,
2265 ),
2266 message(
2267 channel,
2268 "t4r1",
2269 Some("t4"),
2270 tobias,
2271 at(0, 9, 15),
2272 "<p>Yes, all done.</p>",
2273 "[]",
2274 false,
2275 ),
2276 ];
2277 records.extend(rollout_replies);
2278 records.extend(code_post(channel, tobias));
2279 records.extend(shared_channel_messages(channel, mara, tobias));
2280 records
2281}
2282
2283fn code_post(channel: &str, tobias: (&str, &str)) -> Vec<MessageRecord> {
2284 let laughs = reactions_json(vec![reaction(
2285 "laugh",
2286 &[
2287 (PRIYA_ID, "Priya Nair", at(0, 11, 20)),
2288 (JONAS_ID, "Jonas Ortega", at(0, 11, 22)),
2289 ],
2290 )]);
2291 vec![
2292 with_subject(
2293 message(
2294 channel,
2295 "t8",
2296 None,
2297 tobias,
2298 at(0, 11, 5),
2299 "<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>",
2300 &laughs,
2301 false,
2302 ),
2303 "Build script error",
2304 ),
2305 message(
2306 channel,
2307 "t8r1",
2308 Some("t8"),
2309 (JONAS_ID, "Jonas Ortega"),
2310 at(0, 11, 30),
2311 "<p>Add <code>-UseBasicParsing</code> to the call, that fixes it.</p>",
2312 "[]",
2313 false,
2314 ),
2315 with_attachments(
2316 with_subject(
2317 message(
2318 channel,
2319 "t9",
2320 None,
2321 tobias,
2322 at(0, 12, 10),
2323 "<attachment id=\"announcement-card-demo\"></attachment><p>Please merge your last changes by Thursday 18:00. Anything later goes into release 44.</p>",
2324 "[]",
2325 false,
2326 ),
2327 "Code freeze starts Thursday",
2328 ),
2329 &format!(
2330 r#"[{{"content_type":"{ANNOUNCEMENT_BANNER_TYPE}","id":"announcement-card-demo","name":null,"url":null,"text":null,"content":{}}}]"#,
2331 serde_json::Value::String(
2332 r#"{"title":"Release 43 ships Friday","cardImageType":"colorTheme","cardImageDetails":{"colorTheme":"periwinkleBlue"}}"#.to_owned()
2333 )
2334 ),
2335 ),
2336 ]
2337}
2338
2339fn shared_channel_messages(
2340 channel: &str,
2341 mara: (&str, &str),
2342 tobias: (&str, &str),
2343) -> Vec<MessageRecord> {
2344 let priya = (PRIYA_ID, "Priya Nair");
2345 let jonas = (JONAS_ID, "Jonas Ortega");
2346 let reference = |name: &str, size: u64| {
2347 format!(
2348 r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"#
2349 )
2350 };
2351 vec![
2352 with_attachments(
2353 with_subject(
2354 message(
2355 channel,
2356 "t5",
2357 None,
2358 priya,
2359 at(1, 14, 5),
2360 "<p>Roadmap deck and checklist for Q4 are attached.</p>",
2361 "[]",
2362 false,
2363 ),
2364 "Q4 planning files",
2365 ),
2366 &format!(
2367 "[{},{}]",
2368 reference("Roadmap-Q4.pptx", 3_412_000),
2369 reference("Release-Checklist-Q4.xlsx", 48_213)
2370 ),
2371 ),
2372 message(
2373 channel,
2374 "t5r1",
2375 Some("t5"),
2376 jonas,
2377 at(1, 14, 30),
2378 "<p>Rollback steps are here: <a href=\"https://docs.example.org/runbooks/rollback\">https://docs.example.org/runbooks/rollback</a></p>",
2379 "[]",
2380 false,
2381 ),
2382 with_attachments(
2383 message(
2384 channel,
2385 "t6",
2386 None,
2387 mara,
2388 at(12, 10, 0),
2389 "<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>",
2390 "[]",
2391 false,
2392 ),
2393 &format!("[{}]", reference("Postmortem-Draft.docx", 91_400)),
2394 ),
2395 with_attachments(
2396 message(
2397 channel,
2398 "t7",
2399 None,
2400 tobias,
2401 at(20, 9, 0),
2402 "<p>Rollout plan for the new export, please review.</p>",
2403 "[]",
2404 false,
2405 ),
2406 &format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)),
2407 ),
2408 ]
2409}
2410
2411fn crc32(bytes: &[u8]) -> u32 {
2412 let mut crc = 0xffff_ffffu32;
2413 for byte in bytes {
2414 crc ^= u32::from(*byte);
2415 for _ in 0..8 {
2416 crc = if crc & 1 == 1 {
2417 (crc >> 1) ^ 0xedb8_8320
2418 } else {
2419 crc >> 1
2420 };
2421 }
2422 }
2423 !crc
2424}
2425
2426fn adler32(bytes: &[u8]) -> u32 {
2427 let (mut low, mut high) = (1u32, 0u32);
2428 for byte in bytes {
2429 low = (low + u32::from(*byte)) % 65521;
2430 high = (high + low) % 65521;
2431 }
2432 (high << 16) | low
2433}
2434
2435fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
2436 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
2437 let mut body = kind.to_vec();
2438 body.extend_from_slice(data);
2439 output.extend_from_slice(&body);
2440 output.extend_from_slice(&crc32(&body).to_be_bytes());
2441}
2442
2443fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
2444 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
2445}
2446
2447fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
2448 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
2449 let (x, y) = (column as f32, row as f32);
2450 let shade = y / height;
2451 let background = [
2452 (30. - 14. * shade) as u8,
2453 (41. - 16. * shade) as u8,
2454 (59. - 14. * shade) as u8,
2455 ];
2456 let bar_width = width / 14.;
2457 let slot = (x / bar_width) as usize;
2458 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
2459 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
2460 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
2461 let header = y < height * 0.1;
2462 if header {
2463 [22, 30, 45]
2464 } else if on_bars {
2465 if slot % 4 == 3 {
2466 [226, 87, 47]
2467 } else {
2468 [88, 133, 196]
2469 }
2470 } else if (y - height * 0.86).abs() < 1.5 {
2471 [71, 85, 105]
2472 } else {
2473 background
2474 }
2475}
2476
2477fn encode_png(palette: &Palette) -> Vec<u8> {
2478 let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32;
2479 encode_rgb(DEMO_PHOTO_SIDE, DEMO_PHOTO_SIDE, |column, row| {
2480 let (x, y) = ((column as f32 + 0.5) * scale, (row as f32 + 0.5) * scale);
2481 if inside(x, y, (24., 21.), (8.5, 9.5)) {
2482 palette.skin
2483 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
2484 palette.hair
2485 } else if inside(x, y, (24., 50.), (22., 19.)) {
2486 palette.shirt
2487 } else {
2488 palette.background
2489 }
2490 })
2491}
2492
2493fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
2494 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
2495 for row in 0..height {
2496 raw.push(0);
2497 for column in 0..width {
2498 raw.extend_from_slice(&pixel(column, row));
2499 }
2500 }
2501 let mut zlib = vec![0x78, 0x01];
2502 let mut blocks = raw.chunks(65535).peekable();
2503 while let Some(block) = blocks.next() {
2504 zlib.push(u8::from(blocks.peek().is_none()));
2505 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
2506 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
2507 zlib.extend_from_slice(block);
2508 }
2509 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
2510 let mut header = Vec::new();
2511 header.extend_from_slice(&(width as u32).to_be_bytes());
2512 header.extend_from_slice(&(height as u32).to_be_bytes());
2513 header.extend_from_slice(&[8, 2, 0, 0, 0]);
2514 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
2515 png_chunk(&mut png, b"IHDR", &header);
2516 png_chunk(&mut png, b"IDAT", &zlib);
2517 png_chunk(&mut png, b"IEND", &[]);
2518 png
2519}
2520
2521pub fn team_members() -> Vec<crate::manage_team::TeamMember> {
2522 std::iter::once((DEMO_USER_ID, DEMO_USER_NAME, DEMO_USER_EMAIL))
2523 .chain(
2524 PEOPLE_DIRECTORY
2525 .iter()
2526 .map(|(user_id, name, _, email)| (*user_id, *name, *email)),
2527 )
2528 .enumerate()
2529 .map(
2530 |(index, (user_id, name, email))| crate::manage_team::TeamMember {
2531 user_id: Some(user_id.to_owned()),
2532 name: name.to_owned(),
2533 email: Some(email.to_owned()),
2534 owner: index == 1 || index == 3,
2535 },
2536 )
2537 .collect()
2538}
2539
2540#[cfg(test)]
2541mod tests {
2542 use super::*;
2543
2544 #[test]
2545 fn the_demo_has_one_important_and_one_urgent_message() {
2546 let store = Store::open_in_memory().unwrap();
2547 seed(&store);
2548 let importance = |chat: &str, message_id: &str| {
2549 store
2550 .messages(chat, None, 50)
2551 .unwrap()
2552 .into_iter()
2553 .find(|record| record.message_id == message_id)
2554 .map(|record| record.importance)
2555 };
2556 assert_eq!(
2557 importance(PRIORITY_CHAT, "p2"),
2558 Some(MessageImportance::High)
2559 );
2560 assert_eq!(
2561 importance(UNREAD_CHAT, "u5"),
2562 Some(MessageImportance::Urgent)
2563 );
2564 }
2565
2566 #[test]
2567 fn a_multi_forward_quotes_each_message_in_order_after_the_comment() {
2568 let store = Store::open_in_memory().unwrap();
2569 seed(&store);
2570 let chat = store
2571 .recent_chats(100)
2572 .unwrap()
2573 .into_iter()
2574 .find(|chat| chat.id == PRIORITY_CHAT)
2575 .unwrap();
2576 let item = |message_id: &str, text: &str| crate::message_actions::ForwardItem {
2577 message_id: message_id.to_owned(),
2578 author: "Synthetic Sender".to_owned(),
2579 time: "09:00".to_owned(),
2580 text: text.to_owned(),
2581 };
2582 let source = ForwardSource {
2583 conversation_id: PRIORITY_CHAT.to_owned(),
2584 messages: vec![item("m1", "first"), item("m2", "second")],
2585 };
2586 let (_, record) = forwarded_message(&chat, &source, "fyi", Utc::now());
2587 let html = &record.body_html;
2588 assert!(html.starts_with("<p>fyi</p>"));
2589 assert_eq!(html.matches(FORWARD_ITEMTYPE).count(), 2);
2590 assert!(html.find("first").unwrap() < html.find("second").unwrap());
2591 }
2592
2593 #[test]
2594 fn png_has_signature_and_ends_with_iend() {
2595 let png = encode_png(&MARA);
2596 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
2597 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
2598 }
2599
2600 #[test]
2601 fn crc_and_adler_match_known_values() {
2602 assert_eq!(crc32(b"IEND"), 0xae42_6082);
2603 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
2604 }
2605
2606 #[test]
2607 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
2608 let chat = mention_candidates("demo-chat-release", "ma");
2609 assert_eq!(chat.len(), 1);
2610 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
2611 let channel = mention_candidates("demo-channel-1-1", "gen");
2612 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
2613 let all = mention_candidates("demo-chat-release", "");
2614 assert_eq!(all.len(), 6);
2615 assert!(matches!(all[0], MentionCandidate::Everyone { .. }));
2616 assert!(
2617 mention_candidates("demo-chat-mara", "")
2618 .iter()
2619 .all(|candidate| !matches!(candidate, MentionCandidate::Everyone { .. }))
2620 );
2621 assert!(matches!(
2622 mention_candidates("demo-channel-1-1", "desi")[0],
2623 MentionCandidate::Tag { .. }
2624 ));
2625 }
2626
2627 #[test]
2628 fn new_group_chat_gets_a_title_and_the_first_message() {
2629 let people = vec![
2630 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
2631 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
2632 ];
2633 let now = Utc::now();
2634 let (chat, record) = new_chat(
2635 &[],
2636 &people,
2637 Some("Crew"),
2638 "Hello all",
2639 "Hello <i>all</i>",
2640 now,
2641 );
2642 assert_eq!(chat.id, "demo-chat-new-1");
2643 assert_eq!(chat.kind, "group");
2644 assert_eq!(chat.title, "Crew");
2645 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
2646 assert_eq!(chat.members.len(), 3);
2647 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
2648 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
2649 assert_eq!(chat.last_message_at, Some(now));
2650 assert_eq!(record.conversation_id, chat.id);
2651 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
2652 assert!(record.body_html.contains("Hello"));
2653 }
2654
2655 #[test]
2656 fn new_one_on_one_chat_has_no_title_and_counts_up() {
2657 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
2658 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
2659 assert_eq!(first.kind, "oneOnOne");
2660 assert!(first.title.is_empty());
2661 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
2662 assert_eq!(second.id, "demo-chat-new-2");
2663 }
2664
2665 #[test]
2666 fn sending_into_a_chat_refreshes_its_preview() {
2667 let base = ChatRecord {
2668 id: "demo-chat-x".to_owned(),
2669 unread: true,
2670 ..Default::default()
2671 };
2672 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
2673 assert!(!chat.unread);
2674 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
2675 assert_eq!(record.conversation_id, "demo-chat-x");
2676 }
2677
2678 #[test]
2679 fn demo_covers_the_sidebar_edge_cases() {
2680 let chats = demo_chats();
2681 assert!(chats.iter().any(|chat| chat.deleted));
2682 assert!(chats.iter().any(|chat| chat.title.len() > 40));
2683 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
2684 }
2685}