BlueGit

ict rusty-teams

Files

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

demo.rs

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