BlueGit

ict rusty-teams

Files

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

demo.rs

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