BlueGit

ict rusty-teams

Files

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

demo.rs

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