BlueGit

ict rusty-teams

Files

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

demo.rs

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