BlueGit

ict rusty-teams

Files

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

demo.rs

demo.rs 71.2 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, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings, LinkPreview,
14 MentionCandidate, PersonCandidate, PersonSource, PinnedMessage, SavedMessage, TaskDialog,
15 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", "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((TOBIAS_ID, "Tobias Klein", "ok")),
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((JONAS_ID, "Jonas Ortega", "Recording is available")),
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", "Pizza on Friday?")),
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", "Route map attached")),
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", "Next pick: Dune")),
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(&bot_messages());
788 seed_agent_access(store);
789}
790
791const AGENT_DEMO_PROPOSAL: &str = "I ran the regression suite on staging: 412 passed, 0 failed. The release candidate is good to ship, @Mara Lindqvist.";
792
793fn seed_agent_access(store: &Store) {
794 let selected =
795 |ids: &[&str]| mcp::Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect());
796 mcp::save_policy(
797 store,
798 &mcp::AgentPolicy {
799 enabled: true,
800 chats: selected(&[RELEASE_CHAT, "demo-chat-mara", "demo-chat-meeting-standup"]),
801 channels: selected(&["demo-channel-1-1"]),
802 propose: true,
803 calendar: true,
804 transcripts: false,
805 ..mcp::AgentPolicy::default()
806 },
807 );
808 let _ = store.insert_agent_proposal(&store::AgentProposalRecord {
809 id: "demo-proposal".to_owned(),
810 conversation_id: RELEASE_CHAT.to_owned(),
811 reply_to_message_id: Some("m1".to_owned()),
812 text: AGENT_DEMO_PROPOSAL.to_owned(),
813 mentions: vec![store::AgentProposalMention {
814 user_id: MARA_ID.to_owned(),
815 name: "Mara Lindqvist".to_owned(),
816 }],
817 images: vec![store::AttachmentImage {
818 name: "image-1.png".to_owned(),
819 format: "image/png".to_owned(),
820 bytes: encode_png(&MARA),
821 width: Some(PHOTO_SIZE as u32),
822 height: Some(PHOTO_SIZE as u32),
823 }],
824 agent: Some("claude".to_owned()),
825 session_id: None,
826 created_at: Utc::now() - Duration::minutes(1),
827 state: "pending".to_owned(),
828 resolved_at: None,
829 });
830 let _ = store.insert_agent_reaction(&store::AgentReactionRecord {
831 id: "demo-reaction".to_owned(),
832 conversation_id: "demo-chat-mara".to_owned(),
833 message_id: "ml1".to_owned(),
834 emoji: "\u{1F44D}".to_owned(),
835 agent: Some("claude".to_owned()),
836 session_id: None,
837 created_at: Utc::now() - Duration::minutes(1),
838 state: "pending".to_owned(),
839 resolved_at: None,
840 });
841}
842
843fn photo(palette: &Palette) -> Arc<Image> {
844 crate::data::avatar_image_from("image/png", encode_png(palette))
845}
846
847pub fn seed_directory(state: &mut AppState) {
848 state.own_status = crate::own_status::demo_status();
849 state.own_email = DEMO_USER_EMAIL.to_owned();
850 state.own_time_zone = Some(DEMO_TIME_ZONE.to_owned());
851 state.translation.settings = Some(language_settings());
852 state.translation.languages = language_list();
853 let directory = &mut state.directory;
854 directory.me = Some(Person {
855 user_id: DEMO_USER_ID.to_owned(),
856 display_name: DEMO_USER_NAME.to_owned(),
857 });
858 let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
859 directory.folders = vec![
860 FolderInfo {
861 id: FAVORITES_ID.to_owned(),
862 name: String::new(),
863 kind: FolderKind::Favorites,
864 expanded: None,
865 conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
866 },
867 FolderInfo {
868 id: CUSTOMERS_FOLDER.to_owned(),
869 name: "Customers".to_owned(),
870 kind: FolderKind::UserCreated,
871 expanded: None,
872 conversation_ids: ids(&[
873 "demo-chat-customer-1",
874 "demo-chat-customer-2",
875 "demo-chat-customer-3",
876 "demo-chat-customer-4",
877 ]),
878 },
879 FolderInfo {
880 id: ATLAS_FOLDER.to_owned(),
881 name: "Project Atlas".to_owned(),
882 kind: FolderKind::UserCreated,
883 expanded: None,
884 conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
885 },
886 FolderInfo {
887 id: TODO_FOLDER.to_owned(),
888 name: "To do".to_owned(),
889 kind: FolderKind::UserCreated,
890 expanded: None,
891 conversation_ids: Vec::new(),
892 },
893 ];
894 state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]);
895 let directory = &mut state.directory;
896 directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
897 directory
898 .unread_counts
899 .insert("demo-chat-atlas".to_owned(), 5);
900 directory
901 .unread_counts
902 .insert("demo-chat-customer-1".to_owned(), 2);
903 directory
904 .unread_counts
905 .insert("demo-chat-customer-2".to_owned(), 1);
906 directory
907 .unread_counts
908 .insert("demo-chat-allhands".to_owned(), 120);
909 directory.set_avatar(MARA_ID, Some(photo(&MARA)));
910 directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));
911 directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));
912 for (user_id, kind) in [
913 (MARA_ID, PresenceKind::Available),
914 (JONAS_ID, PresenceKind::Busy),
915 (PRIYA_ID, PresenceKind::Away),
916 (TOBIAS_ID, PresenceKind::Offline),
917 (LEA_ID, PresenceKind::Busy),
918 (DEMO_USER_ID, PresenceKind::Available),
919 ] {
920 directory.set_presence(user_id, kind);
921 }
922 directory.set_activity(JONAS_ID, Some(Activity::InACall));
923 directory.set_activity(LEA_ID, Some(Activity::InAConferenceCall));
924 let directory_path = image_directory();
925 if std::fs::create_dir_all(&directory_path).is_ok() {
926 let path = directory_path.join("staging-dashboard.png");
927 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
928 if std::fs::write(&path, png).is_ok() {
929 state.directory.set_image(STAGING_IMAGE_KEY, &path);
930 state.directory.set_image(LINK_IMAGE_KEY, &path);
931 }
932 let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path));
933 state.directory.set_image(
934 demo_gifs::RECEIVED_GIF_KEY,
935 &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)),
936 );
937 }
938 state.typing.start(
939 "demo-chat-mara",
940 MARA_ID,
941 "Mara Lindqvist",
942 Instant::now(),
943 Utc::now(),
944 );
945 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
946 state.last_sync = Some(Utc::now());
947 state.apply_bot_titles();
948 seed_message_actions(state);
949}
950
951fn seed_message_actions(state: &mut AppState) {
952 state.pins.insert(
953 RELEASE_CHAT.to_owned(),
954 vec![PinnedMessage {
955 message_id: PINNED_MESSAGE.to_owned(),
956 pinned_at: Some(at(0, 11, 30)),
957 parent_id: None,
958 }],
959 );
960 let ids: Vec<String> = SAVED_MESSAGES.iter().map(|id| (*id).to_owned()).collect();
961 let records = state
962 .store
963 .messages_by_id(RELEASE_CHAT, &ids)
964 .unwrap_or_default();
965 let saved = SAVED_MESSAGES
966 .iter()
967 .enumerate()
968 .filter_map(|(position, id)| {
969 let record = records.get(*id)?;
970 Some(SavedMessage {
971 conversation_id: record.conversation_id.clone(),
972 message_id: record.message_id.clone(),
973 root_id: record.message_id.clone(),
974 author_id: record.sender_id.clone(),
975 author_name: record.sender_name.clone(),
976 preview: crate::rows::reply_excerpt(record),
977 saved_at: at(position as i64, 15, 20),
978 topic: None,
979 })
980 })
981 .collect();
982 state.saved.replace(saved);
983}
984
985pub fn forwarded_message(
986 chat: &ChatRecord,
987 source: &ForwardSource,
988 comment: &str,
989 now: DateTime<Utc>,
990) -> (ChatRecord, MessageRecord) {
991 let comment_html = if comment.is_empty() {
992 String::new()
993 } else {
994 format!("<p>{}</p>", teams_core::escape_html(comment))
995 };
996 let html = format!(
997 "{comment_html}<blockquote itemscope=\"\" itemtype=\"{FORWARD_ITEMTYPE}\" itemid=\"{}\"><strong>{}</strong><p>{}</p></blockquote>",
998 teams_core::escape_html(&source.message_id),
999 teams_core::escape_html(&source.author),
1000 teams_core::escape_html(&source.text),
1001 );
1002 send_in_chat(chat, &source.text, &html, now)
1003}
1004
1005#[allow(clippy::too_many_arguments)]
1006fn message(
1007 conversation: &str,
1008 id: &str,
1009 reply_to: Option<&str>,
1010 sender: (&str, &str),
1011 time: DateTime<Utc>,
1012 html: &str,
1013 reactions_json: &str,
1014 edited: bool,
1015) -> MessageRecord {
1016 MessageRecord {
1017 conversation_id: conversation.to_owned(),
1018 message_id: id.to_owned(),
1019 reply_to_id: reply_to.map(str::to_owned),
1020 sender_id: Some(sender.0.to_owned()),
1021 sender_name: Some(sender.1.to_owned()),
1022 sender_application_id: None,
1023 links_json: "[]".to_owned(),
1024 created_at: time,
1025 edited_at: edited.then_some(time + Duration::minutes(2)),
1026 deleted: false,
1027 body_html: html.to_owned(),
1028 attachments_json: "[]".to_owned(),
1029 reactions_json: reactions_json.to_owned(),
1030 mentions_json: "[]".to_owned(),
1031 subject: None,
1032 }
1033}
1034
1035fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord {
1036 record.subject = Some(subject.to_owned());
1037 record
1038}
1039
1040fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
1041 record.attachments_json = attachments_json.to_owned();
1042 record
1043}
1044
1045fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord {
1046 record.links_json = links_json;
1047 record
1048}
1049
1050pub fn link_preview(url: &str) -> Option<LinkPreview> {
1051 Some(LinkPreview {
1052 url: url.to_owned(),
1053 title: Some("Release checklist Q4".to_owned()),
1054 description: Some(
1055 "Everything that has to be green before the release candidate goes out on Friday."
1056 .to_owned(),
1057 ),
1058 image_url: Some(LINK_IMAGE_KEY.to_owned()),
1059 image_width: Some(LINK_IMAGE_SIZE.0),
1060 image_height: Some(LINK_IMAGE_SIZE.1),
1061 })
1062}
1063
1064fn bot_messages() -> Vec<MessageRecord> {
1065 let card = serde_json::json!({
1066 "type": "AdaptiveCard",
1067 "body": [
1068 {"type": "ColumnSet", "columns": [
1069 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
1070 {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"}
1071 ]},
1072 {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [
1073 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"}
1074 ]}
1075 ]},
1076 {"type": "ColumnSet", "separator": true, "columns": [
1077 {"type": "Column", "width": "auto", "items": [
1078 {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"}
1079 ]},
1080 {"type": "Column", "width": "stretch", "items": [
1081 {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"},
1082 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
1083 ]}
1084 ]},
1085 {"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."},
1086 {"type": "ActionSet", "actions": [
1087 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
1088 {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
1089 {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
1090 {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}},
1091 {"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}},
1092 {"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]},
1093 {"type": "Action.ShowCard", "title": "Details", "card": {"body": [
1094 {"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."}
1095 ]}}
1096 ]}
1097 ]
1098 });
1099 let mut messages = vec![
1100 bot_card_message("b1", at(0, 13, 45), &card),
1101 bot_card_message("b2", at(0, 13, 52), &input_card()),
1102 bot_card_message(
1103 "b3",
1104 at(0, 13, 58),
1105 &crate::demo_input_cards::all_inputs_card(),
1106 ),
1107 ];
1108 messages.extend(
1109 crate::demo_cards::behaviour_cards()
1110 .iter()
1111 .zip(0u32..)
1112 .map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)),
1113 );
1114 messages.extend(crate::demo_chart_cards::cards().iter().zip(0..).map(
1115 |(chart_card, minute)| {
1116 bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card)
1117 },
1118 ));
1119 messages
1120}
1121
1122fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
1123 let attachments = serde_json::json!([{
1124 "content_type": "application/vnd.microsoft.card.adaptive",
1125 "name": null,
1126 "url": null,
1127 "text": null,
1128 "content": card.to_string()
1129 }]);
1130 let mut record = with_attachments(
1131 message(
1132 BOT_CHAT,
1133 id,
1134 None,
1135 ("", BOT_NAME),
1136 time,
1137 &format!("<attachment id=\"{id}\"></attachment>"),
1138 "[]",
1139 false,
1140 ),
1141 &attachments.to_string(),
1142 );
1143 record.sender_id = None;
1144 record.sender_application_id = Some(BOT_ID.to_owned());
1145 record
1146}
1147
1148fn input_card() -> serde_json::Value {
1149 serde_json::json!({
1150 "type": "AdaptiveCard",
1151 "body": [
1152 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"},
1153 {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"},
1154 {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true},
1155 {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"},
1156 {"type": "ColumnSet", "columns": [
1157 {"type": "Column", "width": "stretch", "items": [
1158 {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4}
1159 ]},
1160 {"type": "Column", "width": "stretch", "items": [
1161 {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"}
1162 ]},
1163 {"type": "Column", "width": "stretch", "items": [
1164 {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"}
1165 ]}
1166 ]},
1167 {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [
1168 {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"}
1169 ]},
1170 {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [
1171 {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"}
1172 ]},
1173 {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [
1174 {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"}
1175 ]},
1176 {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"}
1177 ],
1178 "actions": [
1179 {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}},
1180 {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}}
1181 ]
1182 })
1183}
1184
1185fn bot_app() -> ChatApp {
1186 ChatApp {
1187 app_id: "demo-app-wiki".to_owned(),
1188 name: BOT_APP_NAME.to_owned(),
1189 bot_ids: vec![BOT_ID.to_owned()],
1190 small_image_url: None,
1191 accent_color: None,
1192 web_application_resource: None,
1193 }
1194}
1195
1196pub async fn card_answer(task: CardTask) -> CardAnswer {
1197 tokio::time::sleep(CARD_ANSWER_DELAY).await;
1198 let data = match task {
1199 CardTask::Submit(_) => {
1200 return Ok((
1201 CardActionOutcome::Message("Settings saved".into()),
1202 Some((bot_app(), BOT_ID.to_owned())),
1203 ));
1204 }
1205 CardTask::Action(action) => match action.invoke_payload() {
1206 Some(payload) => payload.value,
1207 None => return Err("Not supported".to_owned()),
1208 },
1209 };
1210 let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch")
1211 {
1212 CardActionOutcome::Dialog(TaskDialog {
1213 title: None,
1214 width: 520,
1215 height: 300,
1216 kind: TaskDialogKind::Card(settings_card().to_string()),
1217 })
1218 } else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") {
1219 CardActionOutcome::Failed("The app answered 500: demo failure".into())
1220 } else {
1221 CardActionOutcome::Sent
1222 };
1223 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
1224}
1225
1226pub async fn refresh_answer() -> CardAnswer {
1227 tokio::time::sleep(CARD_ANSWER_DELAY).await;
1228 Ok((
1229 CardActionOutcome::ReplaceCard(crate::demo_cards::refreshed_card().to_string()),
1230 Some((bot_app(), BOT_ID.to_owned())),
1231 ))
1232}
1233
1234fn settings_card() -> serde_json::Value {
1235 serde_json::json!({
1236 "type": "AdaptiveCard",
1237 "body": [
1238 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
1239 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."},
1240 {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [
1241 {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"}
1242 ]},
1243 {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"}
1244 ],
1245 "actions": [
1246 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
1247 ]
1248 })
1249}
1250
1251const 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";
1252
1253fn meeting_link_messages() -> Vec<MessageRecord> {
1254 let mara = (MARA_ID, "Mara Lindqvist");
1255 vec![message(
1256 "demo-chat-mara",
1257 "ml1",
1258 None,
1259 mara,
1260 at(0, 13, 38),
1261 &format!(
1262 "<p>Let's sync live, here is the meeting: <a href=\"{DEMO_MEETING_LINK}\">Join the Teams meeting</a></p>"
1263 ),
1264 "[]",
1265 false,
1266 )]
1267}
1268
1269fn standup_messages() -> Vec<MessageRecord> {
1270 let jonas = (JONAS_ID, "Jonas Ortega");
1271 let priya = (PRIYA_ID, "Priya Nair");
1272 vec![
1273 with_attachments(
1274 message(
1275 "demo-chat-meeting-standup",
1276 "su1",
1277 None,
1278 priya,
1279 at(0, 9, 30),
1280 "<p>Notes from today.</p>",
1281 "[]",
1282 false,
1283 ),
1284 r#"[{"content_type":"reference","name":"Standup-notes.docx","url":"https://example.com/files/standup-notes.docx","text":null,"size":38900}]"#,
1285 ),
1286 message(
1287 "demo-chat-meeting-standup",
1288 "su2",
1289 None,
1290 jonas,
1291 at(0, 9, 45),
1292 "<p>Recording is available</p>",
1293 "[]",
1294 false,
1295 ),
1296 ]
1297}
1298
1299fn priority_messages() -> Vec<MessageRecord> {
1300 let priya = (PRIYA_ID, "Priya Nair");
1301 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1302 vec![
1303 message(
1304 PRIORITY_CHAT,
1305 "p1",
1306 None,
1307 me,
1308 at(0, 10, 40),
1309 "<p>Have you seen the error on staging yet?</p>",
1310 "[]",
1311 false,
1312 ),
1313 message(
1314 PRIORITY_CHAT,
1315 "p2",
1316 None,
1317 priya,
1318 at(0, 10, 47),
1319 &format!(
1320 "<p>Yes, here is the screenshot:</p><img src=\"{PENDING_IMAGE_KEY}\" width=\"1280\" height=\"720\">"
1321 ),
1322 "[]",
1323 false,
1324 ),
1325 ]
1326}
1327
1328fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
1329 users
1330 .iter()
1331 .map(|(user_id, user_name, created_at)| {
1332 serde_json::json!({
1333 "reaction_type": kind,
1334 "user_id": user_id,
1335 "user_name": user_name,
1336 "created_at": created_at,
1337 })
1338 })
1339 .collect()
1340}
1341
1342fn reactions_json(groups: Vec<Vec<serde_json::Value>>) -> String {
1343 serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string()
1344}
1345
1346fn release_messages() -> Vec<MessageRecord> {
1347 let chat = RELEASE_CHAT;
1348 let mara = (MARA_ID, "Mara Lindqvist");
1349 let jonas = (JONAS_ID, "Jonas Ortega");
1350 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1351 let jonas_name = "Jonas Ortega";
1352 let priya_name = "Priya Nair";
1353 let lea_name = "Lea Schneider";
1354 let mara_name = "Mara Lindqvist";
1355 let tobias_name = "Tobias Klein";
1356 let likes = reactions_json(vec![reaction(
1357 "like",
1358 &[
1359 (JONAS_ID, jonas_name, at(1, 16, 30)),
1360 (PRIYA_ID, priya_name, at(1, 17, 2)),
1361 (LEA_ID, lea_name, at(0, 8, 15)),
1362 ],
1363 )]);
1364 let hearts = reactions_json(vec![reaction(
1365 "heart",
1366 &[
1367 (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)),
1368 (JONAS_ID, jonas_name, at(0, 10, 33)),
1369 ],
1370 )]);
1371 let single = reactions_json(vec![reaction(
1372 "laugh",
1373 &[(PRIYA_ID, priya_name, at(0, 9, 10))],
1374 )]);
1375 let many = reactions_json(vec![
1376 reaction(
1377 "like",
1378 &[
1379 (MARA_ID, mara_name, at(0, 13, 37)),
1380 (JONAS_ID, jonas_name, at(0, 13, 38)),
1381 (PRIYA_ID, priya_name, at(0, 13, 40)),
1382 (LEA_ID, lea_name, at(0, 13, 45)),
1383 (TOBIAS_ID, tobias_name, at(0, 13, 50)),
1384 ],
1385 ),
1386 reaction(
1387 "heart",
1388 &[
1389 (LEA_ID, lea_name, at(0, 13, 46)),
1390 (TOBIAS_ID, tobias_name, at(0, 13, 51)),
1391 ],
1392 ),
1393 reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]),
1394 ]);
1395 vec![
1396 message(
1397 chat,
1398 "m1",
1399 None,
1400 mara,
1401 at(1, 16, 20),
1402 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
1403 "[]",
1404 false,
1405 ),
1406 message(
1407 chat,
1408 "m2",
1409 None,
1410 mara,
1411 at(1, 16, 22),
1412 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
1413 &likes,
1414 false,
1415 ),
1416 with_links(
1417 message(
1418 chat,
1419 "m2a",
1420 None,
1421 mara,
1422 at(1, 16, 23),
1423 "<p><a href=\"https://example.com/checklist\">https://example.com/checklist</a></p>",
1424 "[]",
1425 false,
1426 ),
1427 link_preview("https://example.com/checklist")
1428 .map(|preview| preview.links_json())
1429 .unwrap_or_default(),
1430 ),
1431 message(
1432 chat,
1433 "m2b",
1434 None,
1435 mara,
1436 at(1, 16, 40),
1437 &format!(
1438 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
1439 STAGING_SIZE.0, STAGING_SIZE.1
1440 ),
1441 "[]",
1442 false,
1443 ),
1444 with_attachments(
1445 message(
1446 chat,
1447 "m2c",
1448 None,
1449 mara,
1450 at(1, 16, 41),
1451 "<p>Checklist and rollout plan attached.</p>",
1452 "[]",
1453 false,
1454 ),
1455 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}]"#,
1456 ),
1457 message(
1458 chat,
1459 "m3",
1460 None,
1461 me,
1462 at(0, 9, 2),
1463 "<p>I'll take the changelog.</p>",
1464 &single,
1465 false,
1466 ),
1467 message(
1468 chat,
1469 "m4",
1470 None,
1471 jonas,
1472 at(0, 10, 14),
1473 "<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>",
1474 "[]",
1475 false,
1476 ),
1477 message(
1478 chat,
1479 "m5",
1480 None,
1481 mara,
1482 at(0, 10, 31),
1483 "<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>",
1484 &hearts,
1485 true,
1486 ),
1487 message(
1488 chat,
1489 "m5b",
1490 None,
1491 mara,
1492 at(0, 10, 40),
1493 "<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>",
1494 "[]",
1495 false,
1496 ),
1497 message(
1498 chat,
1499 "m5c",
1500 None,
1501 jonas,
1502 at(0, 11, 5),
1503 "<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>",
1504 "[]",
1505 false,
1506 ),
1507 message(
1508 chat,
1509 "m5d",
1510 None,
1511 (PRIYA_ID, priya_name),
1512 at(0, 12, 20),
1513 &format!(
1514 "<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>"
1515 ),
1516 "[]",
1517 false,
1518 ),
1519 message(
1520 chat,
1521 "m6",
1522 None,
1523 me,
1524 at(0, 13, 35),
1525 "<p>Thanks, renamed. Tagging now.</p>",
1526 "[]",
1527 false,
1528 ),
1529 message(
1530 chat,
1531 "m7",
1532 None,
1533 me,
1534 at(0, 13, 36),
1535 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
1536 &many,
1537 false,
1538 ),
1539 with_links(
1540 message(
1541 chat,
1542 "m7a",
1543 None,
1544 me,
1545 at(0, 13, 37),
1546 "<p>Notes are in <a href=\"https://example.com/notes\">https://example.com/notes</a></p>",
1547 "[]",
1548 false,
1549 ),
1550 LinkPreview {
1551 url: "https://example.com/notes".to_owned(),
1552 title: Some("Release notes 0.2".to_owned()),
1553 description: None,
1554 image_url: None,
1555 image_width: None,
1556 image_height: None,
1557 }
1558 .links_json(),
1559 ),
1560 message(
1561 chat,
1562 "m8",
1563 None,
1564 jonas,
1565 at(0, 13, 40),
1566 "<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>",
1567 "[]",
1568 false,
1569 ),
1570 message(
1571 chat,
1572 "m9",
1573 None,
1574 (PRIYA_ID, priya_name),
1575 at(0, 13, 45),
1576 &format!(
1577 "<p>Ship it!</p><img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"Party\" itemtype=\"http://schema.skype.com/Giphy\">",
1578 demo_gifs::RECEIVED_GIF_KEY,
1579 demo_gifs::RECEIVED_GIF_SIZE.0,
1580 demo_gifs::RECEIVED_GIF_SIZE.1
1581 ),
1582 "[]",
1583 false,
1584 ),
1585 message(
1586 chat,
1587 FRENCH_MESSAGE,
1588 None,
1589 (LEA_ID, lea_name),
1590 at(0, 13, 47),
1591 "<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>",
1592 "[]",
1593 false,
1594 ),
1595 message(
1596 chat,
1597 SPANISH_MESSAGE,
1598 None,
1599 jonas,
1600 at(0, 13, 49),
1601 "<p>Gracias por el aviso. Probar\u{e9} la compilaci\u{f3}n esta tarde y os dir\u{e9} si algo falla.</p>",
1602 "[]",
1603 false,
1604 ),
1605 ]
1606}
1607
1608fn unread_messages() -> Vec<MessageRecord> {
1609 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1610 let lea = (LEA_ID, "Lea Schneider");
1611 let tobias = (TOBIAS_ID, "Tobias Klein");
1612 let rows = [
1613 (
1614 "u1",
1615 me,
1616 at(1, 17, 5),
1617 "<p>Can you enable access for North?</p>",
1618 ),
1619 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
1620 (
1621 "u3",
1622 lea,
1623 at(0, 12, 40),
1624 "<p>Good morning, access is ready.</p>",
1625 ),
1626 (
1627 "u4",
1628 lea,
1629 at(0, 12, 41),
1630 "<p>Sign in with your company ID, no password needed.</p>",
1631 ),
1632 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
1633 ];
1634 rows.into_iter()
1635 .map(|(id, sender, time, html)| {
1636 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1637 })
1638 .collect()
1639}
1640
1641const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2";
1642const DEMO_EXTRA_TABS: [&str; 6] = [
1643 "Incident dashboard",
1644 "Postmortems",
1645 "Escalation policy",
1646 "Status page",
1647 "Vendor contacts",
1648 "On-call calendar",
1649];
1650
1651fn demo_tab(
1652 channel_id: &str,
1653 name: &str,
1654 definition_id: &str,
1655 open_url: Option<&str>,
1656) -> ChannelTabRecord {
1657 ChannelTabRecord {
1658 tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")),
1659 name: name.to_owned(),
1660 definition_id: definition_id.to_owned(),
1661 open_url: open_url.map(str::to_owned),
1662 }
1663}
1664
1665fn demo_channel_tabs(channel_id: &str) -> Vec<ChannelTabRecord> {
1666 let mut tabs = vec![
1667 demo_tab(
1668 channel_id,
1669 "Runbook",
1670 "com.microsoft.teamspace.tab.web",
1671 Some("https://wiki.example.com/display/TEAM/Runbook"),
1672 ),
1673 demo_tab(
1674 channel_id,
1675 "Sprint board",
1676 "com.microsoft.teamspace.tab.planner",
1677 None,
1678 ),
1679 demo_tab(
1680 channel_id,
1681 "Team notes",
1682 "0d820ecd-def2-4297-adad-78056cde7c78",
1683 Some("https://onenote.example.com/notes"),
1684 ),
1685 ];
1686 if channel_id == DEMO_EXTRA_TABS_CHANNEL {
1687 tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| {
1688 demo_tab(
1689 channel_id,
1690 name,
1691 "com.microsoft.teamspace.tab.web",
1692 Some("https://wiki.example.com/display/TEAM/Page"),
1693 )
1694 }));
1695 }
1696 tabs
1697}
1698
1699fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1700 DEMO_TEAM_ORDER
1701 .iter()
1702 .map(|team_id| TeamLayoutRecord {
1703 team_id: (*team_id).to_owned(),
1704 hidden: *team_id == DEMO_HIDDEN_TEAM,
1705 channels: channels
1706 .iter()
1707 .filter(|channel| channel.team_id == *team_id)
1708 .map(|channel| ChannelLayoutRecord {
1709 channel_id: channel.id.clone(),
1710 general: channel.name == "General",
1711 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
1712 tabs: demo_channel_tabs(&channel.id),
1713 notifications: DEMO_CHANNEL_NOTIFICATIONS
1714 .iter()
1715 .find(|(id, _, _)| *id == channel.id)
1716 .map(|(_, level, include_replies)| ChannelNotifications {
1717 level: *level,
1718 include_replies: *include_replies,
1719 })
1720 .unwrap_or_default(),
1721 })
1722 .collect(),
1723 })
1724 .collect()
1725}
1726
1727const ROLLOUT_REPLIES: [(&str, &str); 12] = [
1728 (MARA_ID, "Staging looks good on my side."),
1729 (JONAS_ID, "Smoke tests passed, no regressions."),
1730 (PRIYA_ID, "Docs for the new settings page are merged."),
1731 (LEA_ID, "Support is briefed, nothing blocking."),
1732 (MARA_ID, "Can we keep the old export for one more release?"),
1733 (JONAS_ID, "Yes, behind a flag. I will add it today."),
1734 (PRIYA_ID, "Changelog draft is ready for review."),
1735 (LEA_ID, "Customer success wants a heads-up the day before."),
1736 (MARA_ID, "I will send that mail on Thursday."),
1737 (JONAS_ID, "Flag is in, rebuilding staging now."),
1738 (PRIYA_ID, "Rollback steps are in the runbook."),
1739 (LEA_ID, "All green from QA. Go for Friday."),
1740];
1741
1742fn channel_messages() -> Vec<MessageRecord> {
1743 let channel = "demo-channel-1-1";
1744 let mara = (MARA_ID, "Mara Lindqvist");
1745 let tobias = (TOBIAS_ID, "Tobias Klein");
1746 let people = [
1747 (MARA_ID, "Mara Lindqvist"),
1748 (JONAS_ID, "Jonas Ortega"),
1749 (PRIYA_ID, "Priya Nair"),
1750 (LEA_ID, "Lea Schneider"),
1751 ];
1752 let rollout_replies = ROLLOUT_REPLIES
1753 .iter()
1754 .enumerate()
1755 .map(|(index, (sender, text))| {
1756 let sender = people
1757 .iter()
1758 .copied()
1759 .find(|(id, _)| id == sender)
1760 .expect("known person");
1761 message(
1762 channel,
1763 &format!("t3r{}", index + 1),
1764 Some("t3"),
1765 sender,
1766 at(0, 9, 40) + Duration::minutes(6 * index as i64),
1767 &format!("<p>{text}</p>"),
1768 "[]",
1769 false,
1770 )
1771 });
1772 let mut records = vec![
1773 message(
1774 channel,
1775 "t1",
1776 None,
1777 mara,
1778 at(0, 8, 0),
1779 "<p>Weekly sync notes are up.</p>",
1780 "[]",
1781 false,
1782 ),
1783 message(
1784 channel,
1785 "t1r1",
1786 Some("t1"),
1787 tobias,
1788 at(0, 8, 20),
1789 "<p>Thanks, adding my items.</p>",
1790 "[]",
1791 false,
1792 ),
1793 with_subject(
1794 message(
1795 channel,
1796 "t3",
1797 None,
1798 tobias,
1799 at(0, 9, 30),
1800 "<p>Release build 42 is green, deploying to staging now.</p>",
1801 "[]",
1802 false,
1803 ),
1804 "Release 42 rollout",
1805 ),
1806 message(
1807 channel,
1808 "t2",
1809 None,
1810 tobias,
1811 at(0, 10, 0),
1812 "<p>Who owns the on-call handover?</p>",
1813 "[]",
1814 false,
1815 ),
1816 message(
1817 channel,
1818 "t4",
1819 None,
1820 mara,
1821 at(3, 8, 42),
1822 "<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>",
1823 "[]",
1824 false,
1825 ),
1826 message(
1827 channel,
1828 "t4r1",
1829 Some("t4"),
1830 tobias,
1831 at(0, 9, 15),
1832 "<p>Yes, all done.</p>",
1833 "[]",
1834 false,
1835 ),
1836 ];
1837 records.extend(rollout_replies);
1838 records.extend(shared_channel_messages(channel, mara, tobias));
1839 records
1840}
1841
1842fn shared_channel_messages(
1843 channel: &str,
1844 mara: (&str, &str),
1845 tobias: (&str, &str),
1846) -> Vec<MessageRecord> {
1847 let priya = (PRIYA_ID, "Priya Nair");
1848 let jonas = (JONAS_ID, "Jonas Ortega");
1849 let reference = |name: &str, size: u64| {
1850 format!(
1851 r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"#
1852 )
1853 };
1854 vec![
1855 with_attachments(
1856 with_subject(
1857 message(
1858 channel,
1859 "t5",
1860 None,
1861 priya,
1862 at(1, 14, 5),
1863 "<p>Roadmap deck and checklist for Q4 are attached.</p>",
1864 "[]",
1865 false,
1866 ),
1867 "Q4 planning files",
1868 ),
1869 &format!(
1870 "[{},{}]",
1871 reference("Roadmap-Q4.pptx", 3_412_000),
1872 reference("Release-Checklist-Q4.xlsx", 48_213)
1873 ),
1874 ),
1875 message(
1876 channel,
1877 "t5r1",
1878 Some("t5"),
1879 jonas,
1880 at(1, 14, 30),
1881 "<p>Rollback steps are here: <a href=\"https://docs.example.org/runbooks/rollback\">https://docs.example.org/runbooks/rollback</a></p>",
1882 "[]",
1883 false,
1884 ),
1885 with_attachments(
1886 message(
1887 channel,
1888 "t6",
1889 None,
1890 mara,
1891 at(12, 10, 0),
1892 "<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>",
1893 "[]",
1894 false,
1895 ),
1896 &format!("[{}]", reference("Postmortem-Draft.docx", 91_400)),
1897 ),
1898 with_attachments(
1899 message(
1900 channel,
1901 "t7",
1902 None,
1903 tobias,
1904 at(20, 9, 0),
1905 "<p>Rollout plan for the new export, please review.</p>",
1906 "[]",
1907 false,
1908 ),
1909 &format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)),
1910 ),
1911 ]
1912}
1913
1914fn crc32(bytes: &[u8]) -> u32 {
1915 let mut crc = 0xffff_ffffu32;
1916 for byte in bytes {
1917 crc ^= u32::from(*byte);
1918 for _ in 0..8 {
1919 crc = if crc & 1 == 1 {
1920 (crc >> 1) ^ 0xedb8_8320
1921 } else {
1922 crc >> 1
1923 };
1924 }
1925 }
1926 !crc
1927}
1928
1929fn adler32(bytes: &[u8]) -> u32 {
1930 let (mut low, mut high) = (1u32, 0u32);
1931 for byte in bytes {
1932 low = (low + u32::from(*byte)) % 65521;
1933 high = (high + low) % 65521;
1934 }
1935 (high << 16) | low
1936}
1937
1938fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
1939 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
1940 let mut body = kind.to_vec();
1941 body.extend_from_slice(data);
1942 output.extend_from_slice(&body);
1943 output.extend_from_slice(&crc32(&body).to_be_bytes());
1944}
1945
1946fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
1947 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
1948}
1949
1950fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
1951 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
1952 let (x, y) = (column as f32, row as f32);
1953 let shade = y / height;
1954 let background = [
1955 (30. - 14. * shade) as u8,
1956 (41. - 16. * shade) as u8,
1957 (59. - 14. * shade) as u8,
1958 ];
1959 let bar_width = width / 14.;
1960 let slot = (x / bar_width) as usize;
1961 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
1962 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
1963 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
1964 let header = y < height * 0.1;
1965 if header {
1966 [22, 30, 45]
1967 } else if on_bars {
1968 if slot % 4 == 3 {
1969 [226, 87, 47]
1970 } else {
1971 [88, 133, 196]
1972 }
1973 } else if (y - height * 0.86).abs() < 1.5 {
1974 [71, 85, 105]
1975 } else {
1976 background
1977 }
1978}
1979
1980fn encode_png(palette: &Palette) -> Vec<u8> {
1981 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
1982 let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
1983 if inside(x, y, (24., 21.), (8.5, 9.5)) {
1984 palette.skin
1985 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
1986 palette.hair
1987 } else if inside(x, y, (24., 50.), (22., 19.)) {
1988 palette.shirt
1989 } else {
1990 palette.background
1991 }
1992 })
1993}
1994
1995fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
1996 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
1997 for row in 0..height {
1998 raw.push(0);
1999 for column in 0..width {
2000 raw.extend_from_slice(&pixel(column, row));
2001 }
2002 }
2003 let mut zlib = vec![0x78, 0x01];
2004 let mut blocks = raw.chunks(65535).peekable();
2005 while let Some(block) = blocks.next() {
2006 zlib.push(u8::from(blocks.peek().is_none()));
2007 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
2008 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
2009 zlib.extend_from_slice(block);
2010 }
2011 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
2012 let mut header = Vec::new();
2013 header.extend_from_slice(&(width as u32).to_be_bytes());
2014 header.extend_from_slice(&(height as u32).to_be_bytes());
2015 header.extend_from_slice(&[8, 2, 0, 0, 0]);
2016 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
2017 png_chunk(&mut png, b"IHDR", &header);
2018 png_chunk(&mut png, b"IDAT", &zlib);
2019 png_chunk(&mut png, b"IEND", &[]);
2020 png
2021}
2022
2023#[cfg(test)]
2024mod tests {
2025 use super::*;
2026
2027 #[test]
2028 fn png_has_signature_and_ends_with_iend() {
2029 let png = encode_png(&MARA);
2030 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
2031 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
2032 }
2033
2034 #[test]
2035 fn crc_and_adler_match_known_values() {
2036 assert_eq!(crc32(b"IEND"), 0xae42_6082);
2037 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
2038 }
2039
2040 #[test]
2041 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
2042 let chat = mention_candidates("demo-chat-release", "ma");
2043 assert_eq!(chat.len(), 1);
2044 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
2045 let channel = mention_candidates("demo-channel-1-1", "gen");
2046 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
2047 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
2048 }
2049
2050 #[test]
2051 fn new_group_chat_gets_a_title_and_the_first_message() {
2052 let people = vec![
2053 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
2054 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
2055 ];
2056 let now = Utc::now();
2057 let (chat, record) = new_chat(
2058 &[],
2059 &people,
2060 Some("Crew"),
2061 "Hello all",
2062 "Hello <i>all</i>",
2063 now,
2064 );
2065 assert_eq!(chat.id, "demo-chat-new-1");
2066 assert_eq!(chat.kind, "group");
2067 assert_eq!(chat.title, "Crew");
2068 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
2069 assert_eq!(chat.members.len(), 3);
2070 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
2071 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
2072 assert_eq!(chat.last_message_at, Some(now));
2073 assert_eq!(record.conversation_id, chat.id);
2074 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
2075 assert!(record.body_html.contains("Hello"));
2076 }
2077
2078 #[test]
2079 fn new_one_on_one_chat_has_no_title_and_counts_up() {
2080 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
2081 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
2082 assert_eq!(first.kind, "oneOnOne");
2083 assert!(first.title.is_empty());
2084 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
2085 assert_eq!(second.id, "demo-chat-new-2");
2086 }
2087
2088 #[test]
2089 fn sending_into_a_chat_refreshes_its_preview() {
2090 let base = ChatRecord {
2091 id: "demo-chat-x".to_owned(),
2092 unread: true,
2093 ..Default::default()
2094 };
2095 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
2096 assert!(!chat.unread);
2097 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
2098 assert_eq!(record.conversation_id, "demo-chat-x");
2099 }
2100
2101 #[test]
2102 fn demo_covers_the_sidebar_edge_cases() {
2103 let chats = demo_chats();
2104 assert!(chats.iter().any(|chat| chat.deleted));
2105 assert!(chats.iter().any(|chat| chat.title.len() > 40));
2106 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
2107 }
2108}