BlueGit

ict rusty-teams

Files

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

demo.rs

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