BlueGit

ict rusty-teams

Files

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

demo.rs

demo.rs 47.6 KiB Download Raw
1use std::path::PathBuf;
2use std::sync::Arc;
3use std::time::Instant;
4
5use chrono::{DateTime, Duration, Local, TimeZone, Utc};
6use gpui_kit::Image;
7use store::{
8 ChannelLayoutRecord, ChannelRecord, ChatRecord, MemberRecord, MessageRecord, Store,
9 TeamLayoutRecord, TeamRecord,
10};
11use teams_core::{
12 CardActionOutcome, ChatApp, MentionCandidate, PersonCandidate, PersonSource, TaskDialog,
13 TaskDialogKind,
14};
15
16use crate::activity::{Actor, Entry, Kind};
17use crate::app_state::{AppState, Selection};
18use crate::card_actions::{CardAnswer, CardTask};
19use crate::data::{FolderInfo, FolderKind, Person, PresenceKind};
20
21pub const DEMO_USER_ID: &str = "demo-me";
22const DEMO_USER_NAME: &str = "Dana Demo";
23const PHOTO_SIZE: usize = 48;
24const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard";
25const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot";
26const STAGING_SIZE: (usize, usize) = (960, 540);
27const PRIORITY_CHAT: &str = "demo-chat-priya";
28const BOT_CHAT: &str = "demo-chat-wiki-bot";
29const BOT_NAME: &str = "Wiki Bot";
30const BOT_APP_NAME: &str = "Wiki Cloud";
31const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a";
32const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700);
33const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
34const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64";
35const NEW_CHAT_PREFIX: &str = "demo-chat-new-";
36const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [
37 (
38 MARA_ID,
39 "Mara Lindqvist",
40 "Product Owner",
41 "mara.lindqvist@example.com",
42 ),
43 (
44 JONAS_ID,
45 "Jonas Ortega",
46 "Backend Engineer",
47 "jonas.ortega@example.com",
48 ),
49 (
50 PRIYA_ID,
51 "Priya Nair",
52 "Engineering Manager",
53 "priya.nair@example.com",
54 ),
55 (
56 LEA_ID,
57 "Lea Schneider",
58 "Customer Success",
59 "lea.schneider@example.com",
60 ),
61 (
62 TOBIAS_ID,
63 "Tobias Klein",
64 "Support Engineer",
65 "tobias.klein@example.com",
66 ),
67];
68
69struct Palette {
70 background: [u8; 3],
71 skin: [u8; 3],
72 hair: [u8; 3],
73 shirt: [u8; 3],
74}
75
76const MARA: Palette = Palette {
77 background: [0x3f, 0x5f, 0x7a],
78 skin: [0xe0, 0xb2, 0x93],
79 hair: [0xd9, 0xa4, 0x41],
80 shirt: [0x1e, 0x29, 0x3b],
81};
82const PRIYA: Palette = Palette {
83 background: [0x4b, 0x3b, 0x5c],
84 skin: [0x9a, 0x6a, 0x4a],
85 hair: [0x1c, 0x19, 0x17],
86 shirt: [0xbe, 0x12, 0x3c],
87};
88const TOBIAS: Palette = Palette {
89 background: [0x3b, 0x4a, 0x3f],
90 skin: [0xf1, 0xc7, 0xa5],
91 hair: [0x57, 0x53, 0x4e],
92 shirt: [0x0f, 0x76, 0x6e],
93};
94
95const MARA_ID: &str = "demo-mara";
96const JONAS_ID: &str = "demo-jonas";
97const PRIYA_ID: &str = "demo-priya";
98const LEA_ID: &str = "demo-lea";
99const TOBIAS_ID: &str = "demo-tobias";
100
101const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [
102 (
103 "demo-team-1",
104 "Platform",
105 ["General", "Incidents", "Releases"],
106 ),
107 ("demo-team-2", "Product", ["General", "Roadmap", "Feedback"]),
108 (
109 "demo-team-3",
110 "Operations",
111 ["General", "On call", "Runbooks"],
112 ),
113 (
114 "demo-team-4",
115 "Archive 2025",
116 ["General", "Trade fair", "Office move"],
117 ),
118];
119const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"];
120const DEMO_HIDDEN_TEAM: &str = "demo-team-4";
121const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3";
122
123const UNREAD_CHAT: &str = "demo-chat-atlas";
124const RELEASE_CHAT: &str = "demo-chat-release";
125const FAVORITES_ID: &str = "demo-folder-favorites";
126const CUSTOMERS_FOLDER: &str = "demo-folder-customers";
127const ATLAS_FOLDER: &str = "demo-folder-atlas";
128const TODO_FOLDER: &str = "demo-folder-todo";
129
130fn member(user_id: &str, name: &str) -> MemberRecord {
131 MemberRecord {
132 user_id: Some(user_id.to_owned()),
133 display_name: name.to_owned(),
134 }
135}
136
137fn people(extra: &[(&str, &str)]) -> Vec<MemberRecord> {
138 std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
139 .chain(extra.iter().map(|(id, name)| member(id, name)))
140 .collect()
141}
142
143pub fn at(days_ago: i64, hour: u32, minute: u32) -> DateTime<Utc> {
144 let day = Local::now().date_naive() - Duration::days(days_ago);
145 let local = day.and_hms_opt(hour, minute, 0).expect("valid time");
146 Local
147 .from_local_datetime(&local)
148 .earliest()
149 .map_or_else(Utc::now, |time| time.with_timezone(&Utc))
150}
151
152struct DemoChat {
153 id: &'static str,
154 kind: &'static str,
155 title: &'static str,
156 members: Vec<MemberRecord>,
157 time: DateTime<Utc>,
158 unread: bool,
159 preview: Option<(&'static str, &'static str, &'static str)>,
160 deleted: bool,
161}
162
163fn demo_chats() -> Vec<DemoChat> {
164 let group = |extra: &[(&str, &str)]| people(extra);
165 vec![
166 DemoChat {
167 id: BOT_CHAT,
168 kind: "oneOnOne",
169 title: BOT_NAME,
170 members: people(&[]),
171 time: at(0, 13, 45),
172 unread: true,
173 preview: Some(("", BOT_NAME, "Mara Lindqvist edited your page")),
174 deleted: false,
175 },
176 DemoChat {
177 id: "demo-chat-mara",
178 kind: "oneOnOne",
179 title: "Mara Lindqvist",
180 members: people(&[(MARA_ID, "Mara Lindqvist")]),
181 time: at(0, 13, 40),
182 unread: false,
183 preview: Some((MARA_ID, "Mara Lindqvist", "Sure, 2 pm works")),
184 deleted: false,
185 },
186 DemoChat {
187 id: RELEASE_CHAT,
188 kind: "group",
189 title: "Release planning",
190 members: group(&[
191 (MARA_ID, "Mara Lindqvist"),
192 (JONAS_ID, "Jonas Ortega"),
193 (PRIYA_ID, "Priya Nair"),
194 (LEA_ID, "Lea Schneider"),
195 ]),
196 time: at(0, 13, 35),
197 unread: false,
198 preview: Some((
199 DEMO_USER_ID,
200 DEMO_USER_NAME,
201 "Build 42 is green, see pipeline",
202 )),
203 deleted: false,
204 },
205 DemoChat {
206 id: "demo-chat-customer-1",
207 kind: "group",
208 title: "Customer North - Operations",
209 members: group(&[(LEA_ID, "Lea Schneider"), (TOBIAS_ID, "Tobias Klein")]),
210 time: at(0, 12, 50),
211 unread: true,
212 preview: Some((LEA_ID, "Lea Schneider", "Access is enabled now")),
213 deleted: false,
214 },
215 DemoChat {
216 id: "demo-chat-customer-2",
217 kind: "group",
218 title: "Customer South - Rollout",
219 members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]),
220 time: at(0, 9, 5),
221 unread: true,
222 preview: Some((JONAS_ID, "Jonas Ortega", "Meeting is set for Friday")),
223 deleted: false,
224 },
225 DemoChat {
226 id: "demo-chat-customer-3",
227 kind: "group",
228 title: "Customer West - Support",
229 members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]),
230 time: at(1, 16, 0),
231 unread: false,
232 preview: Some((TOBIAS_ID, "Tobias Klein", "Ticket is closed")),
233 deleted: false,
234 },
235 DemoChat {
236 id: "demo-chat-customer-4",
237 kind: "group",
238 title: "Customer East - Pilot",
239 members: group(&[(MARA_ID, "Mara Lindqvist"), (PRIYA_ID, "Priya Nair")]),
240 time: at(3, 10, 0),
241 unread: false,
242 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "I'll send the documents")),
243 deleted: false,
244 },
245 DemoChat {
246 id: "demo-chat-atlas",
247 kind: "group",
248 title: "Atlas core team",
249 members: group(&[
250 (PRIYA_ID, "Priya Nair"),
251 (LEA_ID, "Lea Schneider"),
252 (MARA_ID, "Mara Lindqvist"),
253 ]),
254 time: at(0, 13, 12),
255 unread: true,
256 preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")),
257 deleted: false,
258 },
259 DemoChat {
260 id: "demo-chat-jonas",
261 kind: "oneOnOne",
262 title: "Jonas Ortega",
263 members: people(&[(JONAS_ID, "Jonas Ortega")]),
264 time: at(0, 11, 2),
265 unread: false,
266 preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Thanks, it's merged")),
267 deleted: false,
268 },
269 DemoChat {
270 id: "demo-chat-priya",
271 kind: "oneOnOne",
272 title: "Priya Nair",
273 members: people(&[(PRIYA_ID, "Priya Nair")]),
274 time: at(0, 10, 47),
275 unread: false,
276 preview: Some((PRIYA_ID, "Priya Nair", "Image")),
277 deleted: false,
278 },
279 DemoChat {
280 id: "demo-chat-tobias",
281 kind: "oneOnOne",
282 title: "Tobias Klein",
283 members: people(&[(TOBIAS_ID, "Tobias Klein")]),
284 time: at(2, 9, 30),
285 unread: false,
286 preview: Some((TOBIAS_ID, "Tobias Klein", "ok")),
287 deleted: false,
288 },
289 DemoChat {
290 id: "demo-chat-allhands",
291 kind: "group",
292 title: "All-hands announcements",
293 members: group(&[(LEA_ID, "Lea Schneider"), (MARA_ID, "Mara Lindqvist")]),
294 time: at(0, 9, 0),
295 unread: true,
296 preview: Some((LEA_ID, "Lea Schneider", "New vacation policy from November")),
297 deleted: false,
298 },
299 DemoChat {
300 id: "demo-chat-design",
301 kind: "group",
302 title: "Design review",
303 members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]),
304 time: at(2, 15, 0),
305 unread: false,
306 preview: Some((MARA_ID, "Mara Lindqvist", "alt")),
307 deleted: true,
308 },
309 DemoChat {
310 id: "demo-chat-quarterly",
311 kind: "group",
312 title: "Quarterly numbers, finance review and planning 2027",
313 members: group(&[(LEA_ID, "Lea Schneider"), (JONAS_ID, "Jonas Ortega")]),
314 time: at(4, 11, 0),
315 unread: false,
316 preview: Some((LEA_ID, "Lea Schneider", "Draft attached")),
317 deleted: false,
318 },
319 ]
320}
321
322pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec<MentionCandidate> {
323 let needle = query.trim().to_lowercase();
324 let matches = |name: &str| needle.is_empty() || name.to_lowercase().contains(&needle);
325 let people = PEOPLE_DIRECTORY
326 .iter()
327 .filter(|(_, name, _, _)| matches(name))
328 .map(|(user_id, name, job_title, mail)| {
329 MentionCandidate::Person(PersonCandidate {
330 user_id: (*user_id).to_owned(),
331 display_name: (*name).to_owned(),
332 mail: Some((*mail).to_owned()),
333 job_title: Some((*job_title).to_owned()),
334 source: PersonSource::Member,
335 })
336 });
337 let scope: Vec<MentionCandidate> = if conversation_id.starts_with("demo-channel") {
338 [
339 MentionCandidate::Channel {
340 channel_id: conversation_id.to_owned(),
341 name: "General".to_owned(),
342 },
343 MentionCandidate::Team {
344 team_id: "demo-team-1".to_owned(),
345 name: "Platform".to_owned(),
346 },
347 ]
348 .into_iter()
349 .filter(|candidate| matches(candidate.display_name()))
350 .collect()
351 } else {
352 Vec::new()
353 };
354 people.chain(scope).collect()
355}
356
357pub fn send_in_chat(
358 chat: &ChatRecord,
359 preview: &str,
360 html: &str,
361 now: DateTime<Utc>,
362) -> (ChatRecord, MessageRecord) {
363 let mut chat = chat.clone();
364 chat.last_message_at = Some(now);
365 chat.last_message_preview = Some(preview.to_owned());
366 chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned());
367 chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned());
368 chat.last_message_deleted = false;
369 chat.unread = false;
370 let record = message(
371 &chat.id,
372 &format!("demo-sent-{}", now.timestamp_millis()),
373 None,
374 (DEMO_USER_ID, DEMO_USER_NAME),
375 now,
376 html,
377 "[]",
378 false,
379 );
380 (chat, record)
381}
382
383pub fn new_chat(
384 existing: &[ChatRecord],
385 people: &[(String, String)],
386 topic: Option<&str>,
387 preview: &str,
388 html: &str,
389 now: DateTime<Utc>,
390) -> (ChatRecord, MessageRecord) {
391 let number = existing
392 .iter()
393 .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX))
394 .count()
395 + 1;
396 let one_on_one = people.len() == 1;
397 let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME))
398 .chain(people.iter().map(|(user_id, name)| member(user_id, name)))
399 .collect();
400 let chat = ChatRecord {
401 id: format!("{NEW_CHAT_PREFIX}{number}"),
402 kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(),
403 title: if one_on_one {
404 String::new()
405 } else {
406 topic.unwrap_or_default().to_owned()
407 },
408 member_summary: people
409 .iter()
410 .map(|(_, name)| name.as_str())
411 .collect::<Vec<_>>()
412 .join(", "),
413 members,
414 ..Default::default()
415 };
416 send_in_chat(&chat, preview, html, now)
417}
418
419fn image_directory() -> PathBuf {
420 std::env::temp_dir().join("rusty-teams-demo")
421}
422
423pub fn first_unread(conversation_id: &str) -> Option<String> {
424 (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned())
425}
426
427pub fn read_message_ids(records: &[MessageRecord]) -> std::collections::HashSet<String> {
428 let newest = records.iter().max_by_key(|record| record.created_at);
429 records
430 .iter()
431 .filter(|record| {
432 Some(record.message_id.as_str()) != newest.map(|newest| newest.message_id.as_str())
433 })
434 .map(|record| record.message_id.clone())
435 .collect()
436}
437
438pub fn first_selection() -> Selection {
439 Selection::Chat(RELEASE_CHAT.to_owned())
440}
441
442pub fn activity_entries() -> Vec<Entry> {
443 let actor = |user_id: &str, name: &str| Actor {
444 user_id: Some(user_id.to_owned()),
445 name: name.to_owned(),
446 };
447 let entry = |conversation_id: &str,
448 kind: Kind,
449 message_id: &str,
450 actors: Vec<Actor>,
451 preview: &str,
452 count: u32,
453 updated_at: DateTime<Utc>,
454 read: bool| Entry {
455 id: 0,
456 conversation_id: conversation_id.to_owned(),
457 kind,
458 message_id: message_id.to_owned(),
459 actors,
460 preview: preview.to_owned(),
461 glyphs: Vec::new(),
462 count,
463 updated_at,
464 read,
465 };
466 let reaction = Entry {
467 glyphs: vec!["\u{1F602}".to_owned(), "\u{1F44D}".to_owned()],
468 ..entry(
469 RELEASE_CHAT,
470 Kind::Reaction,
471 "m3",
472 vec![
473 actor(PRIYA_ID, "Priya Nair"),
474 actor(LEA_ID, "Lea Schneider"),
475 ],
476 "I'll take the changelog.",
477 2,
478 at(0, 13, 20),
479 false,
480 )
481 };
482 vec![
483 entry(
484 UNREAD_CHAT,
485 Kind::Messages,
486 "u3",
487 vec![
488 actor(LEA_ID, "Lea Schneider"),
489 actor(PRIYA_ID, "Priya Nair"),
490 ],
491 "Who is taking the review?",
492 3,
493 at(0, 13, 12),
494 false,
495 ),
496 entry(
497 "demo-channel-1-1",
498 Kind::Mention,
499 "t1",
500 vec![actor(MARA_ID, "Mara Lindqvist")],
501 "@Dana can you approve the merge? The pipeline is waiting.",
502 1,
503 at(0, 11, 40),
504 false,
505 ),
506 reaction,
507 entry(
508 "demo-chat-customer-3",
509 Kind::Messages,
510 "demo-customer-3-closed",
511 vec![actor(TOBIAS_ID, "Tobias Klein")],
512 "Ticket is closed",
513 1,
514 at(1, 16, 0),
515 true,
516 ),
517 ]
518}
519
520pub fn seed(store: &Store) {
521 let chats: Vec<ChatRecord> = demo_chats()
522 .into_iter()
523 .map(|demo| ChatRecord {
524 id: demo.id.to_owned(),
525 kind: demo.kind.to_owned(),
526 title: if demo.kind == "oneOnOne" {
527 String::new()
528 } else {
529 demo.title.to_owned()
530 },
531 member_summary: demo.title.to_owned(),
532 last_message_at: Some(demo.time),
533 unread: demo.unread,
534 members: demo.members,
535 last_message_preview: demo.preview.map(|(_, _, text)| text.to_owned()),
536 last_message_sender_id: demo.preview.map(|(id, _, _)| id.to_owned()),
537 last_message_sender_name: demo.preview.map(|(_, name, _)| name.to_owned()),
538 last_message_deleted: demo.deleted,
539 ..Default::default()
540 })
541 .collect();
542 let _ = store.upsert_chats(&chats);
543 let teams: Vec<TeamRecord> = DEMO_TEAMS
544 .iter()
545 .map(|(id, name, _)| TeamRecord {
546 id: (*id).to_owned(),
547 name: (*name).to_owned(),
548 })
549 .collect();
550 let _ = store.upsert_teams(&teams);
551 let mut channels = Vec::new();
552 for (team_index, (team_id, _, names)) in DEMO_TEAMS.iter().enumerate() {
553 for (channel_index, name) in names.iter().enumerate() {
554 channels.push(ChannelRecord {
555 id: format!("demo-channel-{}-{}", team_index + 1, channel_index + 1),
556 team_id: (*team_id).to_owned(),
557 name: (*name).to_owned(),
558 membership_type: None,
559 last_message_at: Some(at(channel_index as i64, 12, 10)),
560 unread: (team_index == 0 && channel_index == 1)
561 || (team_index == 1 && channel_index == 0),
562 });
563 }
564 }
565 let _ = store.upsert_channels(&channels);
566 let _ = store.replace_team_layout(&demo_team_layout(&channels));
567 let _ = store.set_meta("me_user_id", DEMO_USER_ID);
568 let _ = store.set_meta("me_display_name", DEMO_USER_NAME);
569 let _ = store.upsert_messages(&release_messages());
570 let _ = store.upsert_messages(&unread_messages());
571 let _ = store.upsert_messages(&channel_messages());
572 let _ = store.upsert_messages(&priority_messages());
573 let _ = store.upsert_messages(&bot_messages());
574}
575
576fn photo(palette: &Palette) -> Arc<Image> {
577 crate::data::avatar_image_from("image/png", encode_png(palette))
578}
579
580pub fn seed_directory(state: &mut AppState) {
581 let directory = &mut state.directory;
582 directory.me = Some(Person {
583 user_id: DEMO_USER_ID.to_owned(),
584 display_name: DEMO_USER_NAME.to_owned(),
585 });
586 let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::<Vec<_>>();
587 directory.folders = vec![
588 FolderInfo {
589 id: FAVORITES_ID.to_owned(),
590 name: String::new(),
591 kind: FolderKind::Favorites,
592 conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]),
593 },
594 FolderInfo {
595 id: CUSTOMERS_FOLDER.to_owned(),
596 name: "Customers".to_owned(),
597 kind: FolderKind::UserCreated,
598 conversation_ids: ids(&[
599 "demo-chat-customer-1",
600 "demo-chat-customer-2",
601 "demo-chat-customer-3",
602 "demo-chat-customer-4",
603 ]),
604 },
605 FolderInfo {
606 id: ATLAS_FOLDER.to_owned(),
607 name: "Project Atlas".to_owned(),
608 kind: FolderKind::UserCreated,
609 conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]),
610 },
611 FolderInfo {
612 id: TODO_FOLDER.to_owned(),
613 name: "To do".to_owned(),
614 kind: FolderKind::UserCreated,
615 conversation_ids: Vec::new(),
616 },
617 ];
618 state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]);
619 let directory = &mut state.directory;
620 directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]);
621 directory
622 .unread_counts
623 .insert("demo-chat-atlas".to_owned(), 5);
624 directory
625 .unread_counts
626 .insert("demo-chat-customer-1".to_owned(), 2);
627 directory
628 .unread_counts
629 .insert("demo-chat-customer-2".to_owned(), 1);
630 directory
631 .unread_counts
632 .insert("demo-chat-allhands".to_owned(), 120);
633 directory.set_avatar(MARA_ID, Some(photo(&MARA)));
634 directory.set_avatar(PRIYA_ID, Some(photo(&PRIYA)));
635 directory.set_avatar(TOBIAS_ID, Some(photo(&TOBIAS)));
636 for (user_id, kind) in [
637 (MARA_ID, PresenceKind::Available),
638 (JONAS_ID, PresenceKind::DoNotDisturb),
639 (PRIYA_ID, PresenceKind::Away),
640 (TOBIAS_ID, PresenceKind::Offline),
641 (LEA_ID, PresenceKind::DoNotDisturb),
642 (DEMO_USER_ID, PresenceKind::Available),
643 ] {
644 directory.set_presence(user_id, kind);
645 }
646 let directory_path = image_directory();
647 if std::fs::create_dir_all(&directory_path).is_ok() {
648 let path = directory_path.join("staging-dashboard.png");
649 let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel);
650 if std::fs::write(&path, png).is_ok() {
651 state.directory.set_image(STAGING_IMAGE_KEY, &path);
652 }
653 }
654 state.typing.start(
655 "demo-chat-mara",
656 MARA_ID,
657 "Mara Lindqvist",
658 Instant::now(),
659 Utc::now(),
660 );
661 state.collapsed.insert(CUSTOMERS_FOLDER.to_owned());
662 state.last_sync = Some(Utc::now());
663 state.apply_bot_titles();
664}
665
666#[allow(clippy::too_many_arguments)]
667fn message(
668 conversation: &str,
669 id: &str,
670 reply_to: Option<&str>,
671 sender: (&str, &str),
672 time: DateTime<Utc>,
673 html: &str,
674 reactions_json: &str,
675 edited: bool,
676) -> MessageRecord {
677 MessageRecord {
678 conversation_id: conversation.to_owned(),
679 message_id: id.to_owned(),
680 reply_to_id: reply_to.map(str::to_owned),
681 sender_id: Some(sender.0.to_owned()),
682 sender_name: Some(sender.1.to_owned()),
683 sender_application_id: None,
684 created_at: time,
685 edited_at: edited.then_some(time + Duration::minutes(2)),
686 deleted: false,
687 body_html: html.to_owned(),
688 attachments_json: "[]".to_owned(),
689 reactions_json: reactions_json.to_owned(),
690 mentions_json: "[]".to_owned(),
691 }
692}
693
694fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord {
695 record.attachments_json = attachments_json.to_owned();
696 record
697}
698
699fn bot_messages() -> Vec<MessageRecord> {
700 let card = serde_json::json!({
701 "type": "AdaptiveCard",
702 "body": [
703 {"type": "ColumnSet", "columns": [
704 {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [
705 {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"}
706 ]},
707 {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [
708 {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"}
709 ]}
710 ]},
711 {"type": "ColumnSet", "separator": true, "columns": [
712 {"type": "Column", "width": "auto", "items": [
713 {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"}
714 ]},
715 {"type": "Column", "width": "stretch", "items": [
716 {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"},
717 {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"}
718 ]}
719 ]},
720 {"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."},
721 {"type": "ActionSet", "actions": [
722 {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"},
723 {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"},
724 {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}},
725 {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}},
726 {"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}},
727 {"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]},
728 {"type": "Action.ShowCard", "title": "Details", "card": {"body": [
729 {"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."}
730 ]}}
731 ]}
732 ]
733 });
734 vec![
735 bot_card_message("b1", at(0, 13, 45), &card),
736 bot_card_message("b2", at(0, 13, 52), &input_card()),
737 ]
738}
739
740fn bot_card_message(id: &str, time: DateTime<Utc>, card: &serde_json::Value) -> MessageRecord {
741 let attachments = serde_json::json!([{
742 "content_type": "application/vnd.microsoft.card.adaptive",
743 "name": null,
744 "url": null,
745 "text": null,
746 "content": card.to_string()
747 }]);
748 let mut record = with_attachments(
749 message(
750 BOT_CHAT,
751 id,
752 None,
753 ("", BOT_NAME),
754 time,
755 &format!("<attachment id=\"{id}\"></attachment>"),
756 "[]",
757 false,
758 ),
759 &attachments.to_string(),
760 );
761 record.sender_id = None;
762 record.sender_application_id = Some(BOT_ID.to_owned());
763 record
764}
765
766fn input_card() -> serde_json::Value {
767 serde_json::json!({
768 "type": "AdaptiveCard",
769 "body": [
770 {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"},
771 {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"},
772 {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true},
773 {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"},
774 {"type": "ColumnSet", "columns": [
775 {"type": "Column", "width": "stretch", "items": [
776 {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4}
777 ]},
778 {"type": "Column", "width": "stretch", "items": [
779 {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"}
780 ]},
781 {"type": "Column", "width": "stretch", "items": [
782 {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"}
783 ]}
784 ]},
785 {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [
786 {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"}
787 ]},
788 {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [
789 {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"}
790 ]},
791 {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [
792 {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"}
793 ]},
794 {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"}
795 ],
796 "actions": [
797 {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}},
798 {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}}
799 ]
800 })
801}
802
803fn bot_app() -> ChatApp {
804 ChatApp {
805 app_id: "demo-app-wiki".to_owned(),
806 name: BOT_APP_NAME.to_owned(),
807 bot_ids: vec![BOT_ID.to_owned()],
808 small_image_url: None,
809 accent_color: None,
810 web_application_resource: None,
811 }
812}
813
814pub async fn card_answer(task: CardTask) -> CardAnswer {
815 tokio::time::sleep(CARD_ANSWER_DELAY).await;
816 let data = match task {
817 CardTask::Submit(_) => {
818 return Ok((
819 CardActionOutcome::Message("Settings saved".into()),
820 Some((bot_app(), BOT_ID.to_owned())),
821 ));
822 }
823 CardTask::Action(action) => match action.invoke_payload() {
824 Some(payload) => payload.value,
825 None => return Err("Not supported".to_owned()),
826 },
827 };
828 let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch")
829 {
830 CardActionOutcome::Dialog(TaskDialog {
831 title: None,
832 width: 520,
833 height: 300,
834 kind: TaskDialogKind::Card(settings_card().to_string()),
835 })
836 } else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") {
837 CardActionOutcome::Failed("The app answered 500: demo failure".into())
838 } else {
839 CardActionOutcome::Sent
840 };
841 Ok((outcome, Some((bot_app(), BOT_ID.to_owned()))))
842}
843
844fn settings_card() -> serde_json::Value {
845 serde_json::json!({
846 "type": "AdaptiveCard",
847 "body": [
848 {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"},
849 {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."},
850 {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [
851 {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"}
852 ]},
853 {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"}
854 ],
855 "actions": [
856 {"type": "Action.Submit", "title": "Save", "data": {"save": true}}
857 ]
858 })
859}
860
861fn priority_messages() -> Vec<MessageRecord> {
862 let priya = (PRIYA_ID, "Priya Nair");
863 let me = (DEMO_USER_ID, DEMO_USER_NAME);
864 vec![
865 message(
866 PRIORITY_CHAT,
867 "p1",
868 None,
869 me,
870 at(0, 10, 40),
871 "<p>Have you seen the error on staging yet?</p>",
872 "[]",
873 false,
874 ),
875 message(
876 PRIORITY_CHAT,
877 "p2",
878 None,
879 priya,
880 at(0, 10, 47),
881 &format!(
882 "<p>Yes, here is the screenshot:</p><img src=\"{PENDING_IMAGE_KEY}\" width=\"1280\" height=\"720\">"
883 ),
884 "[]",
885 false,
886 ),
887 ]
888}
889
890fn reaction(kind: &str, users: &[(&str, &str, DateTime<Utc>)]) -> Vec<serde_json::Value> {
891 users
892 .iter()
893 .map(|(user_id, user_name, created_at)| {
894 serde_json::json!({
895 "reaction_type": kind,
896 "user_id": user_id,
897 "user_name": user_name,
898 "created_at": created_at,
899 })
900 })
901 .collect()
902}
903
904fn reactions_json(groups: Vec<Vec<serde_json::Value>>) -> String {
905 serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string()
906}
907
908fn release_messages() -> Vec<MessageRecord> {
909 let chat = RELEASE_CHAT;
910 let mara = (MARA_ID, "Mara Lindqvist");
911 let jonas = (JONAS_ID, "Jonas Ortega");
912 let me = (DEMO_USER_ID, DEMO_USER_NAME);
913 let jonas_name = "Jonas Ortega";
914 let priya_name = "Priya Nair";
915 let lea_name = "Lea Schneider";
916 let mara_name = "Mara Lindqvist";
917 let tobias_name = "Tobias Klein";
918 let likes = reactions_json(vec![reaction(
919 "like",
920 &[
921 (JONAS_ID, jonas_name, at(1, 16, 30)),
922 (PRIYA_ID, priya_name, at(1, 17, 2)),
923 (LEA_ID, lea_name, at(0, 8, 15)),
924 ],
925 )]);
926 let hearts = reactions_json(vec![reaction(
927 "heart",
928 &[
929 (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)),
930 (JONAS_ID, jonas_name, at(0, 10, 33)),
931 ],
932 )]);
933 let single = reactions_json(vec![reaction(
934 "laugh",
935 &[(PRIYA_ID, priya_name, at(0, 9, 10))],
936 )]);
937 let many = reactions_json(vec![
938 reaction(
939 "like",
940 &[
941 (MARA_ID, mara_name, at(0, 13, 37)),
942 (JONAS_ID, jonas_name, at(0, 13, 38)),
943 (PRIYA_ID, priya_name, at(0, 13, 40)),
944 (LEA_ID, lea_name, at(0, 13, 45)),
945 (TOBIAS_ID, tobias_name, at(0, 13, 50)),
946 ],
947 ),
948 reaction(
949 "heart",
950 &[
951 (LEA_ID, lea_name, at(0, 13, 46)),
952 (TOBIAS_ID, tobias_name, at(0, 13, 51)),
953 ],
954 ),
955 reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]),
956 ]);
957 vec![
958 message(
959 chat,
960 "m1",
961 None,
962 mara,
963 at(1, 16, 20),
964 "<p>Release candidate is on staging. Can someone run the regression suite?</p>",
965 "[]",
966 false,
967 ),
968 message(
969 chat,
970 "m2",
971 None,
972 mara,
973 at(1, 16, 22),
974 "<p>Checklist lives in <a href=\"https://example.com/checklist\">release checklist</a>.</p>",
975 &likes,
976 false,
977 ),
978 message(
979 chat,
980 "m2b",
981 None,
982 mara,
983 at(1, 16, 40),
984 &format!(
985 "<p>Staging dashboard right now:</p><img src=\"{STAGING_IMAGE_KEY}\" width=\"{}\" height=\"{}\">",
986 STAGING_SIZE.0, STAGING_SIZE.1
987 ),
988 "[]",
989 false,
990 ),
991 with_attachments(
992 message(
993 chat,
994 "m2c",
995 None,
996 mara,
997 at(1, 16, 41),
998 "<p>Checklist and rollout plan attached.</p>",
999 "[]",
1000 false,
1001 ),
1002 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}]"#,
1003 ),
1004 message(
1005 chat,
1006 "m3",
1007 None,
1008 me,
1009 at(0, 9, 2),
1010 "<p>I'll take the changelog.</p>",
1011 &single,
1012 false,
1013 ),
1014 message(
1015 chat,
1016 "m4",
1017 None,
1018 jonas,
1019 at(0, 10, 14),
1020 "<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>",
1021 "[]",
1022 false,
1023 ),
1024 message(
1025 chat,
1026 "m5",
1027 None,
1028 mara,
1029 at(0, 10, 31),
1030 "<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>",
1031 &hearts,
1032 true,
1033 ),
1034 message(
1035 chat,
1036 "m5b",
1037 None,
1038 mara,
1039 at(0, 10, 40),
1040 "<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>",
1041 "[]",
1042 false,
1043 ),
1044 message(
1045 chat,
1046 "m5c",
1047 None,
1048 jonas,
1049 at(0, 11, 5),
1050 "<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>",
1051 "[]",
1052 false,
1053 ),
1054 message(
1055 chat,
1056 "m6",
1057 None,
1058 me,
1059 at(0, 13, 35),
1060 "<p>Thanks, renamed. Tagging now.</p>",
1061 "[]",
1062 false,
1063 ),
1064 message(
1065 chat,
1066 "m7",
1067 None,
1068 me,
1069 at(0, 13, 36),
1070 "<p>Build 42 is green, see <a href=\"https://example.com/build/42\">pipeline</a>.</p>",
1071 &many,
1072 false,
1073 ),
1074 message(
1075 chat,
1076 "m8",
1077 None,
1078 jonas,
1079 at(0, 13, 40),
1080 "<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>",
1081 "[]",
1082 false,
1083 ),
1084 ]
1085}
1086
1087fn unread_messages() -> Vec<MessageRecord> {
1088 let me = (DEMO_USER_ID, DEMO_USER_NAME);
1089 let lea = (LEA_ID, "Lea Schneider");
1090 let tobias = (TOBIAS_ID, "Tobias Klein");
1091 let rows = [
1092 (
1093 "u1",
1094 me,
1095 at(1, 17, 5),
1096 "<p>Can you enable access for North?</p>",
1097 ),
1098 ("u2", tobias, at(1, 17, 20), "<p>I'll check with IT.</p>"),
1099 (
1100 "u3",
1101 lea,
1102 at(0, 12, 40),
1103 "<p>Good morning, access is ready.</p>",
1104 ),
1105 (
1106 "u4",
1107 lea,
1108 at(0, 12, 41),
1109 "<p>Sign in with your company ID, no password needed.</p>",
1110 ),
1111 ("u5", lea, at(0, 12, 50), "<p>Access is enabled now</p>"),
1112 ];
1113 rows.into_iter()
1114 .map(|(id, sender, time, html)| {
1115 message(UNREAD_CHAT, id, None, sender, time, html, "[]", false)
1116 })
1117 .collect()
1118}
1119
1120fn demo_team_layout(channels: &[ChannelRecord]) -> Vec<TeamLayoutRecord> {
1121 DEMO_TEAM_ORDER
1122 .iter()
1123 .map(|team_id| TeamLayoutRecord {
1124 team_id: (*team_id).to_owned(),
1125 hidden: *team_id == DEMO_HIDDEN_TEAM,
1126 channels: channels
1127 .iter()
1128 .filter(|channel| channel.team_id == *team_id)
1129 .map(|channel| ChannelLayoutRecord {
1130 channel_id: channel.id.clone(),
1131 general: channel.name == "General",
1132 hidden: channel.id == DEMO_HIDDEN_CHANNEL,
1133 })
1134 .collect(),
1135 })
1136 .collect()
1137}
1138
1139fn channel_messages() -> Vec<MessageRecord> {
1140 let channel = "demo-channel-1-1";
1141 let mara = (MARA_ID, "Mara Lindqvist");
1142 let tobias = (TOBIAS_ID, "Tobias Klein");
1143 vec![
1144 message(
1145 channel,
1146 "t1",
1147 None,
1148 mara,
1149 at(0, 8, 0),
1150 "<p>Weekly sync notes are up.</p>",
1151 "[]",
1152 false,
1153 ),
1154 message(
1155 channel,
1156 "t1r1",
1157 Some("t1"),
1158 tobias,
1159 at(0, 8, 20),
1160 "<p>Thanks, adding my items.</p>",
1161 "[]",
1162 false,
1163 ),
1164 message(
1165 channel,
1166 "t3",
1167 None,
1168 tobias,
1169 at(0, 11, 30),
1170 "<p>Release build 42 is green, deploying to staging now.</p>",
1171 "[]",
1172 false,
1173 ),
1174 message(
1175 channel,
1176 "t2",
1177 None,
1178 tobias,
1179 at(0, 11, 0),
1180 "<p>Who owns the on-call handover?</p>",
1181 "[]",
1182 false,
1183 ),
1184 message(
1185 channel,
1186 "t4",
1187 None,
1188 mara,
1189 at(3, 8, 42),
1190 "<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>",
1191 "[]",
1192 false,
1193 ),
1194 message(
1195 channel,
1196 "t4r1",
1197 Some("t4"),
1198 tobias,
1199 at(0, 9, 15),
1200 "<p>Yes, all done.</p>",
1201 "[]",
1202 false,
1203 ),
1204 ]
1205}
1206
1207fn crc32(bytes: &[u8]) -> u32 {
1208 let mut crc = 0xffff_ffffu32;
1209 for byte in bytes {
1210 crc ^= u32::from(*byte);
1211 for _ in 0..8 {
1212 crc = if crc & 1 == 1 {
1213 (crc >> 1) ^ 0xedb8_8320
1214 } else {
1215 crc >> 1
1216 };
1217 }
1218 }
1219 !crc
1220}
1221
1222fn adler32(bytes: &[u8]) -> u32 {
1223 let (mut low, mut high) = (1u32, 0u32);
1224 for byte in bytes {
1225 low = (low + u32::from(*byte)) % 65521;
1226 high = (high + low) % 65521;
1227 }
1228 (high << 16) | low
1229}
1230
1231fn png_chunk(output: &mut Vec<u8>, kind: &[u8; 4], data: &[u8]) {
1232 output.extend_from_slice(&(data.len() as u32).to_be_bytes());
1233 let mut body = kind.to_vec();
1234 body.extend_from_slice(data);
1235 output.extend_from_slice(&body);
1236 output.extend_from_slice(&crc32(&body).to_be_bytes());
1237}
1238
1239fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool {
1240 ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1.
1241}
1242
1243fn staging_pixel(column: usize, row: usize) -> [u8; 3] {
1244 let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32);
1245 let (x, y) = (column as f32, row as f32);
1246 let shade = y / height;
1247 let background = [
1248 (30. - 14. * shade) as u8,
1249 (41. - 16. * shade) as u8,
1250 (59. - 14. * shade) as u8,
1251 ];
1252 let bar_width = width / 14.;
1253 let slot = (x / bar_width) as usize;
1254 let in_bar = x - slot as f32 * bar_width > bar_width * 0.18;
1255 let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.));
1256 let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14;
1257 let header = y < height * 0.1;
1258 if header {
1259 [22, 30, 45]
1260 } else if on_bars {
1261 if slot % 4 == 3 {
1262 [226, 87, 47]
1263 } else {
1264 [88, 133, 196]
1265 }
1266 } else if (y - height * 0.86).abs() < 1.5 {
1267 [71, 85, 105]
1268 } else {
1269 background
1270 }
1271}
1272
1273fn encode_png(palette: &Palette) -> Vec<u8> {
1274 encode_rgb(PHOTO_SIZE, PHOTO_SIZE, |column, row| {
1275 let (x, y) = (column as f32 + 0.5, row as f32 + 0.5);
1276 if inside(x, y, (24., 21.), (8.5, 9.5)) {
1277 palette.skin
1278 } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. {
1279 palette.hair
1280 } else if inside(x, y, (24., 50.), (22., 19.)) {
1281 palette.shirt
1282 } else {
1283 palette.background
1284 }
1285 })
1286}
1287
1288fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec<u8> {
1289 let mut raw = Vec::with_capacity(height * (width * 3 + 1));
1290 for row in 0..height {
1291 raw.push(0);
1292 for column in 0..width {
1293 raw.extend_from_slice(&pixel(column, row));
1294 }
1295 }
1296 let mut zlib = vec![0x78, 0x01];
1297 let mut blocks = raw.chunks(65535).peekable();
1298 while let Some(block) = blocks.next() {
1299 zlib.push(u8::from(blocks.peek().is_none()));
1300 zlib.extend_from_slice(&(block.len() as u16).to_le_bytes());
1301 zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes());
1302 zlib.extend_from_slice(block);
1303 }
1304 zlib.extend_from_slice(&adler32(&raw).to_be_bytes());
1305 let mut header = Vec::new();
1306 header.extend_from_slice(&(width as u32).to_be_bytes());
1307 header.extend_from_slice(&(height as u32).to_be_bytes());
1308 header.extend_from_slice(&[8, 2, 0, 0, 0]);
1309 let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
1310 png_chunk(&mut png, b"IHDR", &header);
1311 png_chunk(&mut png, b"IDAT", &zlib);
1312 png_chunk(&mut png, b"IEND", &[]);
1313 png
1314}
1315
1316#[cfg(test)]
1317mod tests {
1318 use super::*;
1319
1320 #[test]
1321 fn png_has_signature_and_ends_with_iend() {
1322 let png = encode_png(&MARA);
1323 assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]);
1324 assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND");
1325 }
1326
1327 #[test]
1328 fn crc_and_adler_match_known_values() {
1329 assert_eq!(crc32(b"IEND"), 0xae42_6082);
1330 assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398);
1331 }
1332
1333 #[test]
1334 fn mention_candidates_filter_by_name_and_add_scope_in_channels() {
1335 let chat = mention_candidates("demo-chat-release", "ma");
1336 assert_eq!(chat.len(), 1);
1337 assert_eq!(chat[0].display_name(), "Mara Lindqvist");
1338 let channel = mention_candidates("demo-channel-1-1", "gen");
1339 assert!(matches!(channel[0], MentionCandidate::Channel { .. }));
1340 assert_eq!(mention_candidates("demo-chat-release", "").len(), 5);
1341 }
1342
1343 #[test]
1344 fn new_group_chat_gets_a_title_and_the_first_message() {
1345 let people = vec![
1346 (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()),
1347 (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()),
1348 ];
1349 let now = Utc::now();
1350 let (chat, record) = new_chat(
1351 &[],
1352 &people,
1353 Some("Crew"),
1354 "Hello all",
1355 "Hello <i>all</i>",
1356 now,
1357 );
1358 assert_eq!(chat.id, "demo-chat-new-1");
1359 assert_eq!(chat.kind, "group");
1360 assert_eq!(chat.title, "Crew");
1361 assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega");
1362 assert_eq!(chat.members.len(), 3);
1363 assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID));
1364 assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all"));
1365 assert_eq!(chat.last_message_at, Some(now));
1366 assert_eq!(record.conversation_id, chat.id);
1367 assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID));
1368 assert!(record.body_html.contains("Hello"));
1369 }
1370
1371 #[test]
1372 fn new_one_on_one_chat_has_no_title_and_counts_up() {
1373 let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())];
1374 let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now());
1375 assert_eq!(first.kind, "oneOnOne");
1376 assert!(first.title.is_empty());
1377 let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now());
1378 assert_eq!(second.id, "demo-chat-new-2");
1379 }
1380
1381 #[test]
1382 fn sending_into_a_chat_refreshes_its_preview() {
1383 let base = ChatRecord {
1384 id: "demo-chat-x".to_owned(),
1385 unread: true,
1386 ..Default::default()
1387 };
1388 let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now());
1389 assert!(!chat.unread);
1390 assert_eq!(chat.last_message_preview.as_deref(), Some("Ping"));
1391 assert_eq!(record.conversation_id, "demo-chat-x");
1392 }
1393
1394 #[test]
1395 fn demo_covers_the_sidebar_edge_cases() {
1396 let chats = demo_chats();
1397 assert!(chats.iter().any(|chat| chat.deleted));
1398 assert!(chats.iter().any(|chat| chat.title.len() > 40));
1399 assert!(chats.iter().filter(|chat| chat.unread).count() >= 3);
1400 }
1401}