BlueGit

ict rusty-teams

Files

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

demo.rs

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