use std::collections::HashMap; use std::path::PathBuf; use std::sync::OnceLock; use std::time::Instant; use chrono::{DateTime, Duration, Local, TimeZone, Utc}; use gpui_kit::{App, Entity}; use store::{ ChannelLayoutRecord, ChannelMentions, ChannelNotificationLevel, ChannelNotifications, ChannelRecord, ChannelTabRecord, ChatRecord, MemberRecord, MessageImportance, MessageRecord, Store, TeamLayoutRecord, TeamRecord, }; use teams_core::{ ANNOUNCEMENT_BANNER_TYPE, Activity, ActivityHorizons, ActivityItem, ActivitySnapshot, CallEvent, CallPhase, CallType, CardActionOutcome, ChatApp, Gif, Language, LanguageSettings, LinkPreview, MentionCandidate, NOTES_CHAT_ID, OrgEmoji, PersonCandidate, PersonSource, PinnedMessage, custom_emoji_html, SavedMessage, TaskDialog, TaskDialogKind, Translation, TranslationBehavior, TranslationStatus, }; use crate::app_state::{AppState, Selection}; use crate::card_actions::{CardAnswer, CardTask}; use crate::data::{AvatarState, FolderInfo, FolderKind, Person, PresenceKind}; use crate::demo_gifs; use crate::message_actions::ForwardSource; static SEARCHABLE_GIFS: OnceLock> = OnceLock::new(); static DEMO_ORG_EMOJIS: OnceLock> = OnceLock::new(); pub const DEMO_USER_ID: &str = "demo-me"; const DEMO_USER_NAME: &str = "Dana Demo"; const DEMO_USER_EMAIL: &str = "dana.demo@example.com"; const DEMO_TIME_ZONE: &str = "W. Europe Standard Time"; const PHOTO_SIZE: usize = 48; const DEMO_PHOTO_SIDE: usize = 240; const STAGING_IMAGE_KEY: &str = "demo://staging-dashboard"; const PENDING_IMAGE_KEY: &str = "demo://pending-screenshot"; const STAGING_SIZE: (usize, usize) = (960, 540); const LINK_IMAGE_KEY: &str = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/image/Thumbnail?url=demo"; const LINK_IMAGE_SIZE: (u32, u32) = (320, 180); const DEMO_CLIP_URL: &str = "https://eu-api.asm.skype.com/v1/objects/0-weu-d1-democlip/views/video"; const DEMO_CLIP_THUMBNAIL_KEY: &str = "https://eu-api.asm.skype.com/v1/objects/0-weu-d1-democlip/views/thumbnail"; const PRIORITY_CHAT: &str = "demo-chat-priya"; const BOT_CHAT: &str = "demo-chat-wiki-bot"; const BOT_NAME: &str = "Wiki Bot"; const ECHO_CHAT: &str = "demo-chat-echo"; const ECHO_BOT_ID: &str = "28:demo-echo"; const BOT_APP_NAME: &str = "Wiki Cloud"; const BOT_ID: &str = "00000000-0000-0000-0000-00000000b07a"; const CARD_ANSWER_DELAY: std::time::Duration = std::time::Duration::from_millis(700); const CARD_PERSON_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64"; const CARD_PAGE_URL: &str = "https://avatars.githubusercontent.com/u/9919?s=64"; const NEW_CHAT_PREFIX: &str = "demo-chat-new-"; const PEOPLE_DIRECTORY: [(&str, &str, &str, &str); 5] = [ ( MARA_ID, "Mara Lindqvist", "Product Owner", "mara.lindqvist@example.com", ), ( JONAS_ID, "Jonas Ortega", "Backend Engineer", "jonas.ortega@example.com", ), ( PRIYA_ID, "Priya Nair", "Engineering Manager", "priya.nair@example.com", ), ( LEA_ID, "Lea Schneider", "Customer Success", "lea.schneider@example.com", ), ( TOBIAS_ID, "Tobias Klein", "Support Engineer", "tobias.klein@example.com", ), ]; struct Palette { background: [u8; 3], skin: [u8; 3], hair: [u8; 3], shirt: [u8; 3], } const MARA: Palette = Palette { background: [0x3f, 0x5f, 0x7a], skin: [0xe0, 0xb2, 0x93], hair: [0xd9, 0xa4, 0x41], shirt: [0x1e, 0x29, 0x3b], }; const PRIYA: Palette = Palette { background: [0x4b, 0x3b, 0x5c], skin: [0x9a, 0x6a, 0x4a], hair: [0x1c, 0x19, 0x17], shirt: [0xbe, 0x12, 0x3c], }; const TOBIAS: Palette = Palette { background: [0x3b, 0x4a, 0x3f], skin: [0xf1, 0xc7, 0xa5], hair: [0x57, 0x53, 0x4e], shirt: [0x0f, 0x76, 0x6e], }; pub const MARA_ID: &str = "demo-mara"; pub const JONAS_ID: &str = "demo-jonas"; pub const PRIYA_ID: &str = "demo-priya"; pub const LEA_ID: &str = "demo-lea"; pub const TOBIAS_ID: &str = "demo-tobias"; const DEMO_PRIVATE_CHANNEL: &str = "Runbooks"; const DEMO_TEAMS: [(&str, &str, [&str; 3]); 4] = [ ( "demo-team-1", "Platform", ["General", "Incidents", "Releases"], ), ("demo-team-2", "Product", ["General", "Roadmap", "Feedback"]), ( "demo-team-3", "Operations", ["General", "On call", "Runbooks"], ), ( "demo-team-4", "Archive 2025", ["General", "Trade fair", "Office move"], ), ]; const DEMO_TEAM_ORDER: [&str; 4] = ["demo-team-2", "demo-team-1", "demo-team-3", "demo-team-4"]; const DEMO_HIDDEN_TEAM: &str = "demo-team-4"; const DEMO_HIDDEN_CHANNEL: &str = "demo-channel-3-3"; const DEMO_CHANNEL_MENTIONS: [(&str, ChannelMentions); 4] = [ ("demo-channel-1-2", mentions(2, 0, 0)), ("demo-channel-2-1", mentions(0, 1, 0)), (DEMO_HIDDEN_CHANNEL, mentions(1, 0, 0)), ("demo-channel-4-2", mentions(1, 0, 1)), ]; const PINNED_CHANNEL: &str = "demo-channel-1-1"; const PINNED_POST: &str = "t3"; const fn mentions(personal: u32, channel: u32, team: u32) -> ChannelMentions { ChannelMentions { personal, channel, team, } } const DEMO_CHANNEL_NOTIFICATIONS: [(&str, ChannelNotificationLevel, bool); 4] = [ ( "demo-channel-1-1", ChannelNotificationLevel::BannerAndFeed, false, ), ( "demo-channel-1-2", ChannelNotificationLevel::BannerAndFeed, true, ), ("demo-channel-1-3", ChannelNotificationLevel::Off, false), ("demo-channel-2-2", ChannelNotificationLevel::Off, false), ]; const UNREAD_CHAT: &str = "demo-chat-atlas"; const RELEASE_CHAT: &str = "demo-chat-release"; const PINNED_MESSAGE: &str = "m5b"; const FRENCH_MESSAGE: &str = "m10"; const SPANISH_MESSAGE: &str = "m11"; const SAVED_MESSAGES: [&str; 2] = ["m4", "m5c"]; const FORWARD_ITEMTYPE: &str = "http://schema.skype.com/Forward"; const FAVORITES_ID: &str = "demo-folder-favorites"; const CUSTOMERS_FOLDER: &str = "demo-folder-customers"; const ATLAS_FOLDER: &str = "demo-folder-atlas"; const TODO_FOLDER: &str = "demo-folder-todo"; const MUTED_CHATS: [&str; 6] = [ "demo-chat-muted-lunch", "demo-chat-muted-offsite", "demo-chat-muted-kudos", "demo-chat-muted-bikes", "demo-chat-muted-book", "demo-chat-muted-games", ]; fn member(user_id: &str, name: &str) -> MemberRecord { MemberRecord { user_id: Some(user_id.to_owned()), display_name: name.to_owned(), } } fn people(extra: &[(&str, &str)]) -> Vec { std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME)) .chain(extra.iter().map(|(id, name)| member(id, name))) .collect() } pub fn at(days_ago: i64, hour: u32, minute: u32) -> DateTime { let day = Local::now().date_naive() - Duration::days(days_ago); let local = day.and_hms_opt(hour, minute, 0).expect("valid time"); Local .from_local_datetime(&local) .earliest() .map_or_else(Utc::now, |time| time.with_timezone(&Utc)) } struct DemoChat { id: &'static str, kind: &'static str, title: &'static str, members: Vec, time: DateTime, unread: bool, preview: Option<(&'static str, &'static str, &'static str)>, deleted: bool, } fn demo_chats() -> Vec { let group = |extra: &[(&str, &str)]| people(extra); vec![ DemoChat { id: BOT_CHAT, kind: "oneOnOne", title: BOT_NAME, members: people(&[]), time: at(0, 13, 45), unread: true, preview: Some(("", BOT_NAME, "Mara Lindqvist edited your page")), deleted: false, }, DemoChat { id: "demo-chat-mara", kind: "oneOnOne", title: "Mara Lindqvist", members: people(&[(MARA_ID, "Mara Lindqvist")]), time: at(0, 13, 40), unread: false, preview: Some((MARA_ID, "Mara Lindqvist", "Sure, 2 pm works")), deleted: false, }, DemoChat { id: RELEASE_CHAT, kind: "group", title: "Release planning", members: group(&[ (MARA_ID, "Mara Lindqvist"), (JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider"), ]), time: at(0, 13, 35), unread: false, preview: Some(( DEMO_USER_ID, DEMO_USER_NAME, "Build 42 is green, see pipeline", )), deleted: false, }, DemoChat { id: "demo-chat-customer-1", kind: "group", title: "Customer North - Operations", members: group(&[(LEA_ID, "Lea Schneider"), (TOBIAS_ID, "Tobias Klein")]), time: at(0, 12, 50), unread: true, preview: Some((LEA_ID, "Lea Schneider", "Access is enabled now")), deleted: false, }, DemoChat { id: "demo-chat-customer-2", kind: "group", title: "Customer South - Rollout", members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]), time: at(0, 9, 5), unread: true, preview: Some((JONAS_ID, "Jonas Ortega", "Meeting is set for Friday")), deleted: false, }, DemoChat { id: "demo-chat-customer-3", kind: "group", title: "Customer West - Support", members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]), time: at(1, 16, 0), unread: false, preview: Some((TOBIAS_ID, "Tobias Klein", "Ticket is closed")), deleted: false, }, DemoChat { id: "demo-chat-customer-4", kind: "group", title: "Customer East - Pilot", members: group(&[(MARA_ID, "Mara Lindqvist"), (PRIYA_ID, "Priya Nair")]), time: at(3, 10, 0), unread: false, preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "I'll send the documents")), deleted: false, }, DemoChat { id: "demo-chat-atlas", kind: "group", title: "Atlas core team", members: group(&[ (PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider"), (MARA_ID, "Mara Lindqvist"), ]), time: at(0, 13, 12), unread: true, preview: Some((PRIYA_ID, "Priya Nair", "Who is taking the review?")), deleted: false, }, DemoChat { id: ECHO_CHAT, kind: "oneOnOne", title: "Echo", members: people(&[(ECHO_BOT_ID, "Echo")]), time: at(0, 11, 20), unread: false, preview: Some(("", "", "Recording is ready")), deleted: false, }, DemoChat { id: NOTES_CHAT_ID, kind: "oneOnOne", title: "Dana Demo (You)", members: people(&[]), time: at(0, 8, 20), unread: false, preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Release notes draft")), deleted: false, }, DemoChat { id: "demo-chat-jonas", kind: "oneOnOne", title: "Jonas Ortega", members: people(&[(JONAS_ID, "Jonas Ortega")]), time: at(0, 11, 2), unread: false, preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Thanks, it's merged")), deleted: false, }, DemoChat { id: "demo-chat-priya", kind: "oneOnOne", title: "Priya Nair", members: people(&[(PRIYA_ID, "Priya Nair")]), time: at(0, 10, 47), unread: false, preview: Some((PRIYA_ID, "Priya Nair", "Sent an image")), deleted: false, }, DemoChat { id: "demo-chat-tobias", kind: "oneOnOne", title: "Tobias Klein", members: people(&[(TOBIAS_ID, "Tobias Klein")]), time: at(2, 9, 30), unread: false, preview: Some((DEMO_USER_ID, DEMO_USER_NAME, "Forwarded a message")), deleted: false, }, DemoChat { id: "demo-chat-allhands", kind: "group", title: "All-hands announcements", members: group(&[(LEA_ID, "Lea Schneider"), (MARA_ID, "Mara Lindqvist")]), time: at(0, 9, 0), unread: true, preview: Some((LEA_ID, "Lea Schneider", "New vacation policy from November")), deleted: false, }, DemoChat { id: "demo-chat-design", kind: "group", title: "Design review", members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]), time: at(2, 15, 0), unread: false, preview: Some((MARA_ID, "Mara Lindqvist", "alt")), deleted: true, }, DemoChat { id: "demo-chat-quarterly", kind: "group", title: "Quarterly numbers, finance review and planning 2027", members: group(&[(LEA_ID, "Lea Schneider"), (JONAS_ID, "Jonas Ortega")]), time: at(4, 11, 0), unread: false, preview: Some((LEA_ID, "Lea Schneider", "Draft attached")), deleted: false, }, DemoChat { id: "demo-chat-meeting-standup", kind: "meeting", title: "Daily standup", members: group(&[(JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair")]), time: at(0, 9, 45), unread: true, preview: Some(("", "", "Recording is ready")), deleted: false, }, DemoChat { id: "demo-chat-meeting-retro", kind: "meeting", title: "Sprint retrospective", members: group(&[(MARA_ID, "Mara Lindqvist"), (TOBIAS_ID, "Tobias Klein")]), time: at(3, 15, 30), unread: false, preview: Some((MARA_ID, "Mara Lindqvist", "Notes are in the wiki")), deleted: false, }, DemoChat { id: "demo-chat-muted-lunch", kind: "group", title: "Lunch crew", members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]), time: at(0, 12, 5), unread: true, preview: Some((JONAS_ID, "Jonas Ortega", "\u{1F4F7} GIF")), deleted: false, }, DemoChat { id: "demo-chat-muted-offsite", kind: "group", title: "Team offsite 2027", members: group(&[(LEA_ID, "Lea Schneider"), (LEA_ID, "Lea Schneider")]), time: at(1, 16, 20), unread: false, preview: Some((LEA_ID, "Lea Schneider", "Voting closes tomorrow")), deleted: false, }, DemoChat { id: "demo-chat-muted-kudos", kind: "group", title: "Kudos corner", members: group(&[(MARA_ID, "Mara Lindqvist"), (LEA_ID, "Lea Schneider")]), time: at(2, 10, 0), unread: false, preview: Some((MARA_ID, "Mara Lindqvist", "Thanks for the release!")), deleted: false, }, DemoChat { id: "demo-chat-muted-bikes", kind: "group", title: "Bike to work", members: group(&[(TOBIAS_ID, "Tobias Klein"), (LEA_ID, "Lea Schneider")]), time: at(4, 8, 15), unread: false, preview: Some((TOBIAS_ID, "Tobias Klein", "Sent a file")), deleted: false, }, DemoChat { id: "demo-chat-muted-book", kind: "group", title: "Book club", members: group(&[(PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider")]), time: at(6, 19, 40), unread: false, preview: Some((PRIYA_ID, "Priya Nair", "Sent a card")), deleted: false, }, DemoChat { id: "demo-chat-muted-games", kind: "group", title: "Board game night", members: group(&[(JONAS_ID, "Jonas Ortega"), (LEA_ID, "Lea Schneider")]), time: at(9, 18, 0), unread: false, preview: Some((JONAS_ID, "Jonas Ortega", "Who brings the snacks?")), deleted: false, }, ] } pub fn mention_candidates(conversation_id: &str, query: &str) -> Vec { let needle = query.trim().to_lowercase(); let matches = |name: &str| needle.is_empty() || name.to_lowercase().contains(&needle); let people = PEOPLE_DIRECTORY .iter() .filter(|(_, name, _, _)| matches(name)) .map(|(user_id, name, job_title, mail)| { MentionCandidate::Person(PersonCandidate { user_id: (*user_id).to_owned(), display_name: (*name).to_owned(), mail: Some((*mail).to_owned()), job_title: Some((*job_title).to_owned()), source: PersonSource::Member, }) }); let everyone = demo_chats() .into_iter() .find(|chat| chat.id == conversation_id && chat.kind == "group") .map(|chat| MentionCandidate::Everyone { chat_id: chat.id.to_owned(), }) .filter(|candidate| matches(candidate.display_name())); let scope: Vec = if conversation_id.starts_with("demo-channel") { [ MentionCandidate::Channel { channel_id: conversation_id.to_owned(), name: "General".to_owned(), }, MentionCandidate::Team { team_id: "demo-team-1".to_owned(), name: "Platform".to_owned(), }, MentionCandidate::Tag { tag_id: "demo-tag-design".to_owned(), name: "Designers".to_owned(), member_count: Some(3), }, ] .into_iter() .filter(|candidate| matches(candidate.display_name())) .collect() } else { Vec::new() }; everyone.into_iter().chain(people).chain(scope).collect() } pub fn send_in_chat( chat: &ChatRecord, preview: &str, html: &str, now: DateTime, ) -> (ChatRecord, MessageRecord) { let mut chat = chat.clone(); chat.last_message_at = Some(now); chat.preview_at = Some(now); chat.last_message_preview = Some(preview.to_owned()); chat.last_message_sender_id = Some(DEMO_USER_ID.to_owned()); chat.last_message_sender_name = Some(DEMO_USER_NAME.to_owned()); chat.last_message_deleted = false; chat.unread = false; let record = message( &chat.id, &format!("demo-sent-{}", now.timestamp_millis()), None, (DEMO_USER_ID, DEMO_USER_NAME), now, html, "[]", false, ); (chat, record) } pub fn new_chat( existing: &[ChatRecord], people: &[(String, String)], topic: Option<&str>, preview: &str, html: &str, now: DateTime, ) -> (ChatRecord, MessageRecord) { let number = existing .iter() .filter(|chat| chat.id.starts_with(NEW_CHAT_PREFIX)) .count() + 1; let one_on_one = people.len() == 1; let members = std::iter::once(member(DEMO_USER_ID, DEMO_USER_NAME)) .chain(people.iter().map(|(user_id, name)| member(user_id, name))) .collect(); let chat = ChatRecord { id: format!("{NEW_CHAT_PREFIX}{number}"), kind: if one_on_one { "oneOnOne" } else { "group" }.to_owned(), title: if one_on_one { String::new() } else { topic.unwrap_or_default().to_owned() }, member_summary: people .iter() .map(|(_, name)| name.as_str()) .collect::>() .join(", "), members, ..Default::default() }; send_in_chat(&chat, preview, html, now) } fn image_directory() -> PathBuf { std::env::temp_dir().join("rusty-teams-demo") } pub const DEMO_ORG_KOFIE_ID: &str = "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"; pub const DEMO_ORG_SHIPIT_ID: &str = "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb"; pub const DEMO_ORG_HIGHFIVE_ID: &str = "0-weu-d1-cccccccccccccccccccccccccccccccc"; pub const DEMO_ORG_FEEST_ID: &str = "0-weu-d1-dddddddddddddddddddddddddddddddd"; pub fn org_emoji_demo_url(name: &str) -> String { format!("demo://org-emoji-{name}") } pub fn org_emoji_source(object_id: &str) -> Option { DEMO_ORG_EMOJIS .get() .into_iter() .flatten() .find(|emoji| emoji.document_id == object_id) .and_then(|emoji| emoji.source.clone()) } pub fn org_emoji_image_url(object_id: &str) -> Option { DEMO_ORG_EMOJIS .get() .into_iter() .flatten() .find(|emoji| emoji.document_id == object_id) .map(|emoji| org_emoji_demo_url(&emoji.name)) } pub fn ensure_org_emojis() -> Vec { if let Some(emojis) = DEMO_ORG_EMOJIS.get() { return emojis.clone(); } let emojis = generate_org_emojis(&image_directory()); let _ = DEMO_ORG_EMOJIS.set(emojis.clone()); emojis } fn demo_org_emoji_html(name: &str, document_id: &str) -> String { custom_emoji_html(name, document_id, &org_emoji_demo_url(name)) } pub fn org_emojis() -> Vec { ensure_org_emojis() } pub fn search_org_emojis(query: &str) -> Vec { org_emojis() .into_iter() .filter(|emoji| emoji.matches(query)) .collect() } fn generate_org_emojis(directory: &std::path::Path) -> Vec { const FACES: [(&str, &str, &str, [u8; 3], &[&str]); 4] = [ ("demo-koffie", "0-weu-d1-aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", "koffie", [166, 92, 46], &["koffie", "coffee"]), ("demo-shipit", "0-weu-d1-bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", "ship-it", [47, 133, 90], &["ship", "lancering"]), ("demo-highfive", "0-weu-d1-cccccccccccccccccccccccccccccccc", "high-five", [196, 92, 58], &["highfive", "team"]), ("demo-feest", "0-weu-d1-dddddddddddddddddddddddddddddddd", "feest", [126, 68, 173], &["feest", "party"]), ]; let mut emojis = Vec::new(); let _ = std::fs::create_dir_all(directory); for (id, document_id, name, color, keywords) in FACES { let path = directory.join(format!("org-emoji-{name}.png")); let png = encode_rgb(32, 32, |column, row| { let dx = column as i32 - 16; let dy = row as i32 - 16; if dx * dx + dy * dy <= 13 * 13 { if (dx + dy) < -6 { [ color[0].saturating_add(40).min(255), color[1].saturating_add(40).min(255), color[2].saturating_add(40).min(255), ] } else { color } } else { [255, 255, 255] } }); let source = if std::fs::write(&path, png).is_ok() { Some(path.to_string_lossy().into_owned()) } else { None }; emojis.push(OrgEmoji { id: id.to_owned(), document_id: document_id.to_owned(), name: name.to_owned(), keywords: keywords.iter().map(|keyword| (*keyword).to_owned()).collect(), source, }); } emojis } pub fn search_gifs(query: &str) -> Vec { let query = query.trim().to_lowercase(); SEARCHABLE_GIFS .get() .into_iter() .flatten() .filter(|gif| gif.title.to_lowercase().contains(&query)) .cloned() .collect() } pub fn language_settings() -> LanguageSettings { LanguageSettings { display_locale: Some("en-US".to_owned()), target_locale: Some("en".to_owned()), behavior: TranslationBehavior::Ask, authoring_locales: vec!["de-DE".to_owned(), "en-US".to_owned()], preferences: serde_json::Map::new(), } } pub fn language_list() -> Vec { [ ("de", "German"), ("en", "English"), ("es", "Spanish"), ("fr", "French"), ("it", "Italian"), ("ja", "Japanese"), ("nl", "Dutch"), ("pt", "Portuguese"), ] .into_iter() .map(|(code, name)| Language { code: code.to_owned(), name: name.to_owned(), }) .collect() } pub fn language_stamps(conversation_id: &str) -> HashMap { if conversation_id != RELEASE_CHAT { return HashMap::new(); } HashMap::from([ ( FRENCH_MESSAGE.to_owned(), "languages=fr:100;en:12;length:104;&detector=Bling".to_owned(), ), ( SPANISH_MESSAGE.to_owned(), "languages=es:100;pt:31;length:94;&detector=Bling".to_owned(), ), ]) } pub fn translations(message_ids: &[String]) -> Vec { let translated = |message_id: &str| match message_id { FRENCH_MESSAGE => Some( "

Hello everyone, version 0.2 is ready. Can you check the checklist before Friday?

", ), SPANISH_MESSAGE => Some( "

Thanks for the heads-up. I will test the build this afternoon and let you know if anything breaks.

", ), _ => None, }; message_ids .iter() .map(|message_id| Translation { message_id: message_id.clone(), version: None, status: if translated(message_id).is_some() { TranslationStatus::Done } else { TranslationStatus::Failed }, content_html: translated(message_id).map(str::to_owned), subject: None, title: None, }) .collect() } pub fn channel_read_until(channel_id: &str) -> Option> { (channel_id == PINNED_CHANNEL).then(|| at(0, 11, 0)) } pub fn first_unread(conversation_id: &str) -> Option { (conversation_id == UNREAD_CHAT).then(|| "u3".to_owned()) } pub fn read_message_ids(records: &[MessageRecord]) -> std::collections::HashSet { let newest = records.iter().max_by_key(|record| record.created_at); records .iter() .filter(|record| { Some(record.message_id.as_str()) != newest.map(|newest| newest.message_id.as_str()) }) .map(|record| record.message_id.clone()) .collect() } pub fn start_session(state: &Entity, cx: &mut App) { state.update(cx, |state, cx| { seed_directory(state); state.demo_live_meetings(); state.select(first_selection(), cx); }); } pub fn first_selection() -> Selection { Selection::Chat(RELEASE_CHAT.to_owned()) } pub fn activity_snapshot() -> ActivitySnapshot { let item = |message_id: &str, activity_type: &str, subtype: &str, conversation_id: &str, thread_type: &str, source_message_id: &str, actor: (&str, &str), preview: &str, time: DateTime, read: bool| ActivityItem { message_id: message_id.to_owned(), activity_id: message_id.to_owned(), activity_type: activity_type.to_owned(), activity_subtype: subtype.to_owned(), source_thread_id: conversation_id.to_owned(), source_message_id: (!source_message_id.is_empty()).then(|| source_message_id.to_owned()), source_reply_chain_id: (!source_message_id.is_empty()) .then(|| source_message_id.to_owned()), source_user_id: Some(format!("8:orgid:{}", actor.0)), source_user_name: actor.1.to_owned(), preview: preview.to_owned(), preview_template: "hasText".to_owned(), thread_type: Some(thread_type.to_owned()), count: 1, timestamp_ms: time.timestamp_millis(), version_ms: time.timestamp_millis(), read_flag: read, ..ActivityItem::default() }; let items = vec![ item( "demo-activity-1", "replyInChat", "", UNREAD_CHAT, "chat", "u3", (LEA_ID, "Lea Schneider"), "Who is taking the review?", at(0, 13, 12), false, ), ActivityItem { count: 2, ..item( "demo-activity-2", "reactionInChat", "laugh", RELEASE_CHAT, "chat", "m3", (PRIYA_ID, "Priya Nair"), "I'll take the changelog.", at(0, 13, 20), false, ) }, item( "demo-activity-3", "mention", "person", "demo-channel-1-1", "topic", "t1", (MARA_ID, "Mara Lindqvist"), "@Dana can you approve the merge? The pipeline is waiting.", at(0, 11, 40), false, ), item( "demo-activity-4", "mentionInChat", "person", "demo-chat-allhands", "chat", "demo-allhands-policy", (LEA_ID, "Lea Schneider"), "@Dana please read the new vacation policy before Friday.", at(0, 9, 0), false, ), item( "demo-activity-5", "follow", "channelNewMessage", "demo-channel-1-3", "topic", "demo-release-post", (MARA_ID, "Mara Lindqvist"), "Release 4.2 is tagged, notes are in the wiki.", at(1, 17, 30), true, ), item( "demo-activity-6", "call", "missedCall", "demo-chat-customer-3", "chat", "", (TOBIAS_ID, "Tobias Klein"), "", at(1, 16, 0), true, ), ActivityItem { source_thread_id: String::new(), source_message_id: Some("1".to_owned()), source_reply_chain_id: None, source_user_id: None, source_app_name: Some("Meeting Recaps".to_owned()), preview_template: "previewUnavailable".to_owned(), template_parameters: [("subject".to_owned(), "Following: Sprint Review ".to_owned())] .into(), event_start_ms: Some(at(1, 10, 0).timestamp_millis()), event_end_ms: Some(at(1, 11, 0).timestamp_millis()), ..item( "demo-activity-7", "msGraph", "recapIsReadyForFollowedMeetingsV2", "", "", "", ("", "Meeting Recaps"), "You're following this meeting", at(1, 11, 30), true, ) }, ]; ActivitySnapshot { items, horizons: ActivityHorizons::default(), } } pub fn seed(store: &Store) { let _ = ensure_org_emojis(); let chats: Vec = demo_chats() .into_iter() .map(|demo| ChatRecord { id: demo.id.to_owned(), kind: demo.kind.to_owned(), title: if demo.kind == "oneOnOne" { String::new() } else { demo.title.to_owned() }, member_summary: demo.title.to_owned(), last_message_at: Some(demo.time), unread: demo.unread, members: demo.members, last_message_preview: demo.preview.map(|(_, _, text)| text.to_owned()), last_message_sender_id: demo.preview.map(|(id, _, _)| id.to_owned()), last_message_sender_name: demo.preview.map(|(_, name, _)| name.to_owned()), last_message_deleted: demo.deleted, ..Default::default() }) .collect(); let _ = store.upsert_chats(&chats); for chat_id in MUTED_CHATS { let _ = store.set_chat_muted(chat_id, true); } let teams: Vec = DEMO_TEAMS .iter() .map(|(id, name, _)| TeamRecord { id: (*id).to_owned(), name: (*name).to_owned(), }) .collect(); let _ = store.upsert_teams(&teams); let mut channels = Vec::new(); for (team_index, (team_id, _, names)) in DEMO_TEAMS.iter().enumerate() { for (channel_index, name) in names.iter().enumerate() { channels.push(ChannelRecord { id: format!("demo-channel-{}-{}", team_index + 1, channel_index + 1), team_id: (*team_id).to_owned(), name: (*name).to_owned(), membership_type: (*name == DEMO_PRIVATE_CHANNEL).then(|| "private".to_owned()), last_message_at: Some(at(channel_index as i64, 12, 10)), unread: (team_index == 0 && channel_index == 1) || (team_index == 1 && channel_index == 0), }); } } for channel in channels.iter_mut().filter(|channel| { DEMO_CHANNEL_MENTIONS .iter() .any(|(id, _)| *id == channel.id) }) { channel.unread = true; } let _ = store.upsert_channels(&channels); let _ = store.replace_team_layout(&demo_team_layout(&channels)); let _ = store.replace_channel_mentions( &DEMO_CHANNEL_MENTIONS .iter() .map(|(id, mentions)| ((*id).to_owned(), *mentions)) .collect::>(), ); let _ = store.set_meta("me_user_id", DEMO_USER_ID); let _ = store.set_meta("me_display_name", DEMO_USER_NAME); let _ = store.upsert_messages(&release_messages()); let _ = store.upsert_messages(&unread_messages()); let _ = store.upsert_messages(&channel_messages()); let _ = store.upsert_messages(&priority_messages()); let _ = store.upsert_messages(¬es_messages()); let _ = store.upsert_messages(&meeting_link_messages()); let _ = store.upsert_messages(&standup_messages()); let _ = store.upsert_messages(&call_messages()); let _ = store.upsert_messages(&crate::demo_meetings::meeting_messages()); let _ = store.upsert_messages(&bot_messages()); let _ = store.upsert_messages(&crate::kvt_demo::messages()); seed_agent_access(store); } pub fn agent_meeting_draft() -> mcp::MeetingDraft { let start = at(-1, 10, 0); mcp::MeetingDraft { subject: "Release 42 go/no-go".to_owned(), start, end: start + Duration::minutes(30), attendees: vec![ "mara.lindqvist@example.com".to_owned(), "jonas.ortega@example.com".to_owned(), ], description: "Walk through the regression results and decide on Friday's rollout.\nOwner: Mara" .to_owned(), } } const AGENT_DEMO_PROPOSAL: &str = "I ran the regression suite on staging: 412 passed, 0 failed. The release candidate is good to ship, @Mara Lindqvist."; fn seed_agent_access(store: &Store) { let selected = |ids: &[&str]| mcp::Access::Selected(ids.iter().map(|id| (*id).to_owned()).collect()); mcp::save_policy( store, &mcp::AgentPolicy { enabled: true, chats: selected(&[RELEASE_CHAT, "demo-chat-mara", "demo-chat-meeting-standup"]), channels: selected(&["demo-channel-1-1"]), write: true, calendar: true, transcripts: false, meetings: true, ..mcp::AgentPolicy::default() }, ); let _ = store.insert_agent_proposal(&store::AgentProposalRecord { id: "demo-proposal".to_owned(), conversation_id: RELEASE_CHAT.to_owned(), reply_to_message_id: Some("m1".to_owned()), text: AGENT_DEMO_PROPOSAL.to_owned(), mentions: vec![store::AgentProposalMention { user_id: MARA_ID.to_owned(), name: "Mara Lindqvist".to_owned(), }], images: vec![store::AttachmentImage { name: "image-1.png".to_owned(), format: "image/png".to_owned(), bytes: encode_png(&MARA), width: Some(PHOTO_SIZE as u32), height: Some(PHOTO_SIZE as u32), }], agent: Some("claude".to_owned()), session_id: None, created_at: Utc::now() - Duration::minutes(1), state: "pending".to_owned(), resolved_at: None, }); let _ = store.insert_agent_reaction(&store::AgentReactionRecord { id: "demo-reaction".to_owned(), conversation_id: "demo-chat-mara".to_owned(), message_id: "ml1".to_owned(), emoji: "\u{1F44D}".to_owned(), agent: Some("claude".to_owned()), session_id: None, created_at: Utc::now() - Duration::minutes(1), state: "pending".to_owned(), resolved_at: None, }); } fn photo(palette: &Palette) -> AvatarState { crate::data::avatar_state_from("image/png", encode_png(palette), false) } pub fn seed_directory(state: &mut AppState) { state.own_status = crate::own_status::demo_status(); state.own_email = DEMO_USER_EMAIL.to_owned(); state.own_time_zone = Some(DEMO_TIME_ZONE.to_owned()); state.translation.settings = Some(language_settings()); state.apply_regional_format(); state.translation.languages = language_list(); let directory = &mut state.directory; directory.me = Some(Person { user_id: DEMO_USER_ID.to_owned(), display_name: DEMO_USER_NAME.to_owned(), }); let ids = |list: &[&str]| list.iter().map(|id| (*id).to_owned()).collect::>(); directory.folders = vec![ FolderInfo { id: FAVORITES_ID.to_owned(), name: String::new(), kind: FolderKind::Favorites, expanded: None, conversation_ids: ids(&["demo-chat-mara", RELEASE_CHAT]), }, FolderInfo { id: CUSTOMERS_FOLDER.to_owned(), name: "Customers".to_owned(), kind: FolderKind::UserCreated, expanded: None, conversation_ids: ids(&[ "demo-chat-customer-1", "demo-chat-customer-2", "demo-chat-customer-3", "demo-chat-customer-4", ]), }, FolderInfo { id: ATLAS_FOLDER.to_owned(), name: "Project Atlas".to_owned(), kind: FolderKind::UserCreated, expanded: None, conversation_ids: ids(&["demo-chat-atlas", "demo-chat-jonas"]), }, FolderInfo { id: TODO_FOLDER.to_owned(), name: "To do".to_owned(), kind: FolderKind::UserCreated, expanded: None, conversation_ids: Vec::new(), }, ]; state.bot_apps.insert(BOT_CHAT.to_owned(), vec![bot_app()]); let directory = &mut state.directory; directory.pinned_channels = ids(&["demo-channel-1-1", "demo-channel-3-2"]); directory .unread_counts .insert("demo-chat-atlas".to_owned(), 5); directory .unread_counts .insert("demo-chat-customer-1".to_owned(), 2); directory .unread_counts .insert("demo-chat-customer-2".to_owned(), 1); directory .unread_counts .insert("demo-chat-allhands".to_owned(), 120); directory .unread_importance .insert(UNREAD_CHAT.to_owned(), MessageImportance::Urgent); directory .unread_importance .insert("demo-chat-customer-1".to_owned(), MessageImportance::High); directory.set_avatar(MARA_ID, photo(&MARA)); directory.set_avatar(PRIYA_ID, photo(&PRIYA)); directory.set_avatar(TOBIAS_ID, photo(&TOBIAS)); for (user_id, kind) in [ (MARA_ID, PresenceKind::Available), (JONAS_ID, PresenceKind::Busy), (PRIYA_ID, PresenceKind::Away), (TOBIAS_ID, PresenceKind::Offline), (LEA_ID, PresenceKind::Busy), (DEMO_USER_ID, PresenceKind::Available), ] { directory.set_presence(user_id, kind); } directory.set_activity(JONAS_ID, Some(Activity::InACall)); directory.set_activity(LEA_ID, Some(Activity::InAConferenceCall)); let directory_path = image_directory(); if std::fs::create_dir_all(&directory_path).is_ok() { let path = directory_path.join("staging-dashboard.png"); let png = encode_rgb(STAGING_SIZE.0, STAGING_SIZE.1, staging_pixel); if std::fs::write(&path, png).is_ok() { state.directory.set_image(STAGING_IMAGE_KEY, &path); state.directory.set_image(LINK_IMAGE_KEY, &path); state.directory.set_image(DEMO_CLIP_THUMBNAIL_KEY, &path); } let _ = SEARCHABLE_GIFS.set(demo_gifs::generate(&directory_path)); let org_emojis = ensure_org_emojis(); for emoji in &org_emojis { if let Some(path) = emoji.source.as_deref() { state .directory .set_image(&org_emoji_demo_url(&emoji.name), std::path::Path::new(path)); } } state.directory.set_image( demo_gifs::RECEIVED_GIF_KEY, &directory_path.join(demo_gifs::file_name(demo_gifs::RECEIVED_GIF_NAME)), ); } state.typing.start( "demo-chat-mara", MARA_ID, "Mara Lindqvist", Instant::now(), Utc::now(), ); state.collapsed.insert(CUSTOMERS_FOLDER.to_owned()); state.last_sync = Some(Utc::now()); state.apply_bot_titles(); seed_message_actions(state); } fn seed_message_actions(state: &mut AppState) { state.pins.insert( PINNED_CHANNEL.to_owned(), vec![PinnedMessage { message_id: PINNED_POST.to_owned(), pinned_at: Some(at(0, 9, 45)), parent_id: None, }], ); state.pins.insert( RELEASE_CHAT.to_owned(), vec![PinnedMessage { message_id: PINNED_MESSAGE.to_owned(), pinned_at: Some(at(0, 11, 30)), parent_id: None, }], ); let ids: Vec = SAVED_MESSAGES.iter().map(|id| (*id).to_owned()).collect(); let records = state .store .messages_by_id(RELEASE_CHAT, &ids) .unwrap_or_default(); let saved = SAVED_MESSAGES .iter() .enumerate() .filter_map(|(position, id)| { let record = records.get(*id)?; Some(SavedMessage { conversation_id: record.conversation_id.clone(), message_id: record.message_id.clone(), root_id: record.message_id.clone(), author_id: record.sender_id.clone(), author_name: record.sender_name.clone(), preview: crate::rows::reply_excerpt(record), saved_at: at(position as i64, 15, 20), topic: None, }) }) .collect(); state.saved.replace(saved); } pub fn forwarded_message( chat: &ChatRecord, source: &ForwardSource, comment: &str, now: DateTime, ) -> (ChatRecord, MessageRecord) { let comment_html = if comment.is_empty() { String::new() } else { format!("

{}

", teams_core::escape_html(comment)) }; let quotes: String = source .messages .iter() .map(|item| { format!( "
{}

{}

", teams_core::escape_html(&item.message_id), teams_core::escape_html(&item.author), teams_core::escape_html(&item.text), ) }) .collect(); let preview = source .messages .first() .map(|item| item.text.as_str()) .unwrap_or_default(); send_in_chat(chat, preview, &format!("{comment_html}{quotes}"), now) } #[allow(clippy::too_many_arguments)] fn message( conversation: &str, id: &str, reply_to: Option<&str>, sender: (&str, &str), time: DateTime, html: &str, reactions_json: &str, edited: bool, ) -> MessageRecord { MessageRecord { conversation_id: conversation.to_owned(), message_id: id.to_owned(), reply_to_id: reply_to.map(str::to_owned), sender_id: Some(sender.0.to_owned()), sender_name: Some(sender.1.to_owned()), sender_application_id: None, links_json: "[]".to_owned(), created_at: time, edited_at: edited.then_some(time + Duration::minutes(2)), deleted: false, body_html: html.to_owned(), attachments_json: "[]".to_owned(), reactions_json: reactions_json.to_owned(), mentions_json: "[]".to_owned(), subject: None, call_event_json: None, importance: Default::default(), } } pub fn roster_record( conversation: &str, id: &str, time: DateTime, event: &teams_core::roster_event::RosterEvent, ) -> MessageRecord { MessageRecord { conversation_id: conversation.to_owned(), message_id: id.to_owned(), created_at: time, links_json: "[]".to_owned(), attachments_json: "[]".to_owned(), reactions_json: "[]".to_owned(), mentions_json: "[]".to_owned(), call_event_json: Some(event.to_json()), ..MessageRecord::default() } } fn call_record( conversation: &str, id: &str, time: DateTime, event: CallEvent, ) -> MessageRecord { MessageRecord { conversation_id: conversation.to_owned(), message_id: id.to_owned(), created_at: time, links_json: "[]".to_owned(), attachments_json: "[]".to_owned(), reactions_json: "[]".to_owned(), mentions_json: "[]".to_owned(), call_event_json: Some(event.to_json()), ..MessageRecord::default() } } fn call_event( phase: CallPhase, call_id: &str, initiator: (&str, &str), duration_seconds: Option, participant_ids: &[&str], ) -> CallEvent { CallEvent { phase, call_type: CallType::Call, call_id: call_id.to_owned(), duration_seconds, initiator_id: Some(initiator.0.to_owned()), initiator_name: Some(initiator.1.to_owned()), participant_ids: participant_ids.iter().map(|id| (*id).to_owned()).collect(), participant_names: Vec::new(), recording: None, } } fn call_messages() -> Vec { let mara = (MARA_ID, "Mara Lindqvist"); let me = (DEMO_USER_ID, DEMO_USER_NAME); let jonas = (JONAS_ID, "Jonas Ortega"); let both = [DEMO_USER_ID, MARA_ID]; vec![ call_record( "demo-chat-mara", "call-1-started", at(0, 12, 4), call_event(CallPhase::Started, "demo-call-1", me, None, &[]), ), call_record( "demo-chat-mara", "call-1-ended", at(0, 12, 16), call_event(CallPhase::Ended, "demo-call-1", me, Some(723), &both), ), call_record( "demo-chat-mara", "call-2-started", at(0, 13, 9), call_event(CallPhase::Started, "demo-call-2", mara, None, &[]), ), call_record( "demo-chat-mara", "call-2-ended", at(0, 13, 10), call_event(CallPhase::Ended, "demo-call-2", mara, Some(60), &[MARA_ID]), ), call_record( "demo-chat-meeting-standup", "call-3-started", at(0, 9, 50), CallEvent { call_type: CallType::Meeting, ..call_event(CallPhase::Started, "demo-call-3", jonas, None, &[]) }, ), ] } fn with_importance(mut record: MessageRecord, importance: MessageImportance) -> MessageRecord { record.importance = importance; record } fn with_subject(mut record: MessageRecord, subject: &str) -> MessageRecord { record.subject = Some(subject.to_owned()); record } /// A Graph forward of a Teams video clip, as Teams sends a forwarded phone recording. fn forwarded_clip_attachments(message_id: &str, sender_id: &str) -> String { let content = serde_json::json!({ "originalMessageId": message_id, "originalMessageContent": format!( r#"

"# ), "originalMessageSender": {"user": {"id": sender_id, "displayName": null}}, }); serde_json::json!([{ "content_type": "forwardedMessageReference", "id": message_id, "content": content.to_string(), }]) .to_string() } fn with_attachments(mut record: MessageRecord, attachments_json: &str) -> MessageRecord { record.attachments_json = attachments_json.to_owned(); record } fn with_links(mut record: MessageRecord, links_json: String) -> MessageRecord { record.links_json = links_json; record } pub fn link_preview(url: &str) -> Option { Some(LinkPreview { url: url.to_owned(), title: Some("Release checklist Q4".to_owned()), description: Some( "Everything that has to be green before the release candidate goes out on Friday." .to_owned(), ), image_url: Some(LINK_IMAGE_KEY.to_owned()), image_width: Some(LINK_IMAGE_SIZE.0), image_height: Some(LINK_IMAGE_SIZE.1), }) } fn bot_messages() -> Vec { let card = serde_json::json!({ "type": "AdaptiveCard", "body": [ {"type": "ColumnSet", "columns": [ {"type": "Column", "width": "auto", "verticalContentAlignment": "center", "items": [ {"type": "Image", "url": CARD_PERSON_URL, "size": "small", "style": "person", "height": "32px"} ]}, {"type": "Column", "width": "stretch", "verticalContentAlignment": "center", "items": [ {"type": "TextBlock", "size": "medium", "weight": "bolder", "wrap": true, "text": "Mara Lindqvist edited your page"} ]} ]}, {"type": "ColumnSet", "separator": true, "columns": [ {"type": "Column", "width": "auto", "items": [ {"type": "Image", "url": CARD_PAGE_URL, "width": "24px", "height": "24px"} ]}, {"type": "Column", "width": "stretch", "items": [ {"type": "TextBlock", "weight": "bolder", "wrap": true, "text": "[**Release Checklist Q4**](https://example.com/wiki/release-checklist) in [**Platform**](https://example.com/wiki/platform)"}, {"type": "TextBlock", "spacing": "small", "isSubtle": true, "wrap": true, "text": "Owned by: Dana Demo"} ]} ]}, {"type": "TextBlock", "id": "owner-note", "isVisible": false, "isSubtle": true, "wrap": true, "text": "Owner notes are only shown on request."}, {"type": "ActionSet", "actions": [ {"type": "Action.OpenUrl", "title": "View page", "url": "https://example.com/wiki/release-checklist"}, {"type": "Action.OpenUrl", "title": "View changes", "url": "https://example.com/wiki/release-checklist/changes"}, {"type": "Action.Submit", "title": "Watch page", "data": {"action": "watch"}}, {"type": "Action.Submit", "title": "Stop watching", "data": {"action": "unwatch"}}, {"type": "Action.Submit", "title": "Settings", "data": {"msteams": {"type": "task/fetch"}}}, {"type": "Action.ToggleVisibility", "title": "Owner notes", "targetElements": ["owner-note"]}, {"type": "Action.ShowCard", "title": "Details", "card": {"body": [ {"type": "TextBlock", "wrap": true, "text": "Last edited by **Mara Lindqvist** on Tuesday."} ]}} ]} ] }); let mut messages = vec![ bot_card_message("b1", at(0, 13, 45), &card), bot_card_message("b2", at(0, 13, 52), &input_card()), bot_card_message( "b3", at(0, 13, 58), &crate::demo_input_cards::all_inputs_card(), ), ]; messages.extend( crate::demo_cards::behaviour_cards() .iter() .zip(0u32..) .map(|(card, index)| bot_card_message(&format!("g{index}"), at(0, 14, index), card)), ); messages.extend(crate::demo_chart_cards::cards().iter().zip(0..).map( |(chart_card, minute)| { bot_card_message(&format!("c{minute}"), at(0, 15, minute), chart_card) }, )); let mut webhook = bot_card_message("w1", at(0, 16, 0), &connector_card()); webhook.attachments_json = webhook.attachments_json.replace( "application/vnd.microsoft.card.adaptive", "application/vnd.microsoft.teams.card.o365connector", ); messages.push(webhook); messages } fn connector_card() -> serde_json::Value { serde_json::json!({ "@type": "MessageCard", "summary": "Build failed", "title": "Pipeline main", "sections": [{ "activityTitle": "Build 128 failed", "activitySubtitle": "on agent 3", "facts": [{"name": "Branch", "value": "main"}, {"name": "Duration", "value": "4 min"}], "text": "See the log for details." }], "potentialAction": [{ "@type": "OpenUri", "name": "Open log", "targets": [{"os": "default", "uri": "https://example.com/ci/128"}] }] }) } fn bot_card_message(id: &str, time: DateTime, card: &serde_json::Value) -> MessageRecord { let attachments = serde_json::json!([{ "content_type": "application/vnd.microsoft.card.adaptive", "name": null, "url": null, "text": null, "content": card.to_string() }]); let mut record = with_attachments( message( BOT_CHAT, id, None, ("", BOT_NAME), time, &format!(""), "[]", false, ), &attachments.to_string(), ); record.sender_id = None; record.sender_application_id = Some(BOT_ID.to_owned()); record } fn input_card() -> serde_json::Value { serde_json::json!({ "type": "AdaptiveCard", "body": [ {"type": "TextBlock", "size": "medium", "weight": "bolder", "text": "Release request"}, {"type": "Input.Text", "id": "title", "label": "Title", "placeholder": "Short summary", "isRequired": true, "errorMessage": "Give the release a title"}, {"type": "Input.Text", "id": "notes", "label": "Notes", "placeholder": "Anything the reviewers should know", "isMultiline": true}, {"type": "Input.Text", "id": "token", "label": "Access code", "style": "Password", "regex": "^\\d{4}$", "errorMessage": "Enter four digits"}, {"type": "ColumnSet", "columns": [ {"type": "Column", "width": "stretch", "items": [ {"type": "Input.Number", "id": "count", "label": "Servers", "placeholder": "1-20", "min": 1, "max": 20, "value": 4} ]}, {"type": "Column", "width": "stretch", "items": [ {"type": "Input.Date", "id": "day", "label": "Release day", "value": "2026-11-02"} ]}, {"type": "Column", "width": "stretch", "items": [ {"type": "Input.Time", "id": "hour", "label": "Start time", "value": "09:30"} ]} ]}, {"type": "Input.ChoiceSet", "id": "channel", "label": "Channel", "placeholder": "Pick a channel", "isRequired": true, "choices": [ {"title": "Stable", "value": "stable"}, {"title": "Beta", "value": "beta"}, {"title": "Nightly", "value": "nightly"} ]}, {"type": "Input.ChoiceSet", "id": "region", "label": "Region", "style": "expanded", "value": "eu", "choices": [ {"title": "Europe", "value": "eu"}, {"title": "North America", "value": "na"} ]}, {"type": "Input.ChoiceSet", "id": "checks", "label": "Checks", "style": "expanded", "isMultiSelect": true, "value": "lint", "choices": [ {"title": "Lint", "value": "lint"}, {"title": "Unit tests", "value": "unit"}, {"title": "Smoke tests", "value": "smoke"} ]}, {"type": "Input.Toggle", "id": "notify", "title": "Notify the team", "value": "yes", "valueOn": "yes", "valueOff": "no"} ], "actions": [ {"type": "Action.Submit", "title": "Request release", "data": {"action": "release"}}, {"type": "Action.Submit", "title": "Cancel", "associatedInputs": "none", "data": {"action": "cancel"}} ] }) } fn bot_app() -> ChatApp { ChatApp { app_id: "demo-app-wiki".to_owned(), name: BOT_APP_NAME.to_owned(), bot_ids: vec![BOT_ID.to_owned()], small_image_url: None, accent_color: None, web_application_resource: None, } } pub async fn card_answer(task: CardTask) -> CardAnswer { tokio::time::sleep(CARD_ANSWER_DELAY).await; let data = match task { CardTask::Submit(_) => { return Ok(( CardActionOutcome::Message("Settings saved".into()), Some((bot_app(), BOT_ID.to_owned())), )); } CardTask::Action(action) => match action.invoke_payload() { Some(payload) => payload.value, None => return Err("Not supported".to_owned()), }, }; let outcome = if data.pointer("/data/type").and_then(|kind| kind.as_str()) == Some("task/fetch") { CardActionOutcome::Dialog(TaskDialog { title: None, width: 520, height: 300, kind: TaskDialogKind::Card(settings_card().to_string()), }) } else if data.get("action").and_then(|action| action.as_str()) == Some("unwatch") { CardActionOutcome::Failed("The app answered 500: demo failure".into()) } else { CardActionOutcome::Sent }; Ok((outcome, Some((bot_app(), BOT_ID.to_owned())))) } pub async fn refresh_answer() -> CardAnswer { tokio::time::sleep(CARD_ANSWER_DELAY).await; Ok(( CardActionOutcome::ReplaceCard(crate::demo_cards::refreshed_card().to_string()), Some((bot_app(), BOT_ID.to_owned())), )) } fn settings_card() -> serde_json::Value { serde_json::json!({ "type": "AdaptiveCard", "body": [ {"type": "TextBlock", "weight": "bolder", "text": "Notification settings"}, {"type": "TextBlock", "wrap": true, "isSubtle": true, "text": "Choose how the bot tells you about page changes."}, {"type": "Input.ChoiceSet", "id": "frequency", "label": "Frequency", "style": "expanded", "value": "daily", "choices": [ {"title": "Immediately", "value": "now"}, {"title": "Daily digest", "value": "daily"} ]}, {"type": "Input.Toggle", "id": "mentions", "title": "Only when I am mentioned", "value": "false"} ], "actions": [ {"type": "Action.Submit", "title": "Save", "data": {"save": true}} ] }) } pub const DEMO_TENANT_ID: &str = "demo-tenant"; const 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"; fn meeting_link_messages() -> Vec { let mara = (MARA_ID, "Mara Lindqvist"); vec![message( "demo-chat-mara", "ml1", None, mara, at(0, 13, 38), &format!( "

Let's sync live, here is the meeting: Join the Teams meeting

" ), "[]", false, )] } fn standup_messages() -> Vec { let jonas = (JONAS_ID, "Jonas Ortega"); let priya = (PRIYA_ID, "Priya Nair"); vec![ with_attachments( message( "demo-chat-meeting-standup", "su1", None, priya, at(0, 9, 30), "

Notes from today.

", "[]", false, ), r#"[{"content_type":"reference","name":"Standup-notes.docx","url":"https://example.com/files/standup-notes.docx","text":null,"size":38900}]"#, ), with_attachments( message( "demo-chat-meeting-standup", "su2", None, jonas, at(0, 9, 45), "

Recording is available

", "[]", false, ), r#"[{"content_type":"reference","name":"Standup-recording.mp4","url":"https://contoso-my.sharepoint.com/personal/jonas_contoso_com/Documents/Recordings/Standup-recording.mp4","text":null,"size":18400000}]"#, ), with_links( message( "demo-chat-meeting-standup", "su3", None, jonas, at(0, 9, 50), "

https://example.com/checklist

", "[]", false, ), link_preview("https://example.com/checklist") .map(|preview| preview.links_json()) .unwrap_or_default(), ), message( "demo-chat-meeting-standup", "su4", None, priya, at(0, 9, 52), "

I will quickly fix the comments and then push the final version before the review starts.

", "[]", false, ), ] } fn notes_messages() -> Vec { vec![message( NOTES_CHAT_ID, "n1", None, (DEMO_USER_ID, DEMO_USER_NAME), at(0, 8, 20), "

Release notes draft

", "[]", false, )] } fn priority_messages() -> Vec { let priya = (PRIYA_ID, "Priya Nair"); let me = (DEMO_USER_ID, DEMO_USER_NAME); vec![ message( PRIORITY_CHAT, "p1", None, me, at(0, 10, 40), "

Have you seen the error on staging yet?

", "[]", false, ), message( PRIORITY_CHAT, "p2", None, priya, at(0, 10, 47), &format!( "

Yes, here is the screenshot:

" ), "[]", false, ), ] .into_iter() .map(|record| match record.message_id.as_str() { "p2" => with_importance(record, MessageImportance::High), _ => record, }) .collect() } fn reaction(kind: &str, users: &[(&str, &str, DateTime)]) -> Vec { users .iter() .map(|(user_id, user_name, created_at)| { serde_json::json!({ "reaction_type": kind, "user_id": user_id, "user_name": user_name, "created_at": created_at, }) }) .collect() } fn reactions_json(groups: Vec>) -> String { serde_json::Value::Array(groups.into_iter().flatten().collect()).to_string() } fn release_messages() -> Vec { let chat = RELEASE_CHAT; let mara = (MARA_ID, "Mara Lindqvist"); let jonas = (JONAS_ID, "Jonas Ortega"); let me = (DEMO_USER_ID, DEMO_USER_NAME); let jonas_name = "Jonas Ortega"; let priya_name = "Priya Nair"; let lea_name = "Lea Schneider"; let mara_name = "Mara Lindqvist"; let tobias_name = "Tobias Klein"; let likes = reactions_json(vec![reaction( "like", &[ (JONAS_ID, jonas_name, at(1, 16, 30)), (PRIYA_ID, priya_name, at(1, 17, 2)), (LEA_ID, lea_name, at(0, 8, 15)), ], )]); let hearts = reactions_json(vec![reaction( "heart", &[ (DEMO_USER_ID, DEMO_USER_NAME, at(0, 10, 35)), (JONAS_ID, jonas_name, at(0, 10, 33)), ], )]); let single = reactions_json(vec![reaction( "laugh", &[(PRIYA_ID, priya_name, at(0, 9, 10))], )]); let many = reactions_json(vec![ reaction( "like", &[ (MARA_ID, mara_name, at(0, 13, 37)), (JONAS_ID, jonas_name, at(0, 13, 38)), (PRIYA_ID, priya_name, at(0, 13, 40)), (LEA_ID, lea_name, at(0, 13, 45)), (TOBIAS_ID, tobias_name, at(0, 13, 50)), ], ), reaction( "heart", &[ (LEA_ID, lea_name, at(0, 13, 46)), (TOBIAS_ID, tobias_name, at(0, 13, 51)), ], ), reaction("\u{1F389}", &[(MARA_ID, mara_name, at(0, 13, 39))]), ]); vec![ message( chat, "m1", None, mara, at(1, 16, 20), "

Release candidate is on staging. Can someone run the regression suite?

", "[]", false, ), message( chat, "m2", None, mara, at(1, 16, 22), "

Checklist lives in release checklist.

", &likes, false, ), with_links( message( chat, "m2a", None, mara, at(1, 16, 23), "

https://example.com/checklist

", "[]", false, ), link_preview("https://example.com/checklist") .map(|preview| preview.links_json()) .unwrap_or_default(), ), message( chat, "m2b", None, mara, at(1, 16, 40), &format!( "

Staging dashboard right now:

", STAGING_SIZE.0, STAGING_SIZE.1 ), "[]", false, ), with_attachments( message( chat, "m2c", None, mara, at(1, 16, 41), "

Checklist and rollout plan attached.

", "[]", false, ), 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}]"#, ), message( chat, "m3", None, me, at(0, 9, 2), "

I'll take the changelog.

", &single, false, ), message( chat, "m4", None, jonas, at(0, 10, 14), "

Mara Lindqvist can you take a quick look at this? It runs before cargo test.

// only release branches\nfn freeze(branch: &str) -> bool {\n    branch.starts_with(\"release/\")\n}
", "[]", false, ), message( chat, "m5", None, mara, at(0, 10, 31), "
Jonas Ortega

can you take a quick look at this?

Looks good. Small thing: the name could say what it checks.

", &hearts, true, ), message( chat, "m5b", None, mara, at(0, 10, 40), "

Rollout for Friday:

  • Freeze the release branch
  • Run the smoke tests on staging, then post the results in the channel
  • Ship
    • Windows installer
    • Linux .AppImage

Order:

  1. Tag
  2. Build
  3. Announce
", "[]", false, ), message( chat, "m5c", None, jonas, at(0, 11, 5), "

Release notes 0.2

The old sync path is gone.

AreaOwner
SyncPriya
RenderJonas

Measure twice, cut once.

Important: backup first.

Then sync once.

backup --all
sync --once
", "[]", false, ), message( chat, "m5d", None, (PRIYA_ID, priya_name), at(0, 12, 20), &format!( "

FYI, the customer asked for this.

Tobias Klein

Can we move the freeze to Thursday? The customer demo is on Friday morning.

" ), "[]", false, ), message( chat, "m5e", None, jonas, at(0, 12, 40), "

Context from the old planning chat.

", r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"id":"1789000000000","content":null,"unavailable":true}]"#, false, ), with_attachments( message( chat, "m5f", None, (PRIYA_ID, priya_name), at(0, 12, 45), "", "[]", false, ), &forwarded_clip_attachments("1791000000000", TOBIAS_ID), ), message( chat, "m6", None, me, at(0, 13, 35), "

Thanks, renamed. Tagging now.

", "[]", false, ), message( chat, "m7", None, me, at(0, 13, 36), "

Build 42 is green, see pipeline.

", &many, false, ), with_links( message( chat, "m7a", None, me, at(0, 13, 37), "

Notes are in https://example.com/notes

", "[]", false, ), LinkPreview { url: "https://example.com/notes".to_owned(), title: Some("Release notes 0.2".to_owned()), description: Some("What changed since 0.1".to_owned()), image_url: None, image_width: None, image_height: None, } .links_json(), ), message( chat, "m8", None, jonas, at(0, 13, 40), "

Formula check: H2O and x2 + y2. Small print, reviewed by Mara Lindqvist. Big news: the release notes are out.

", "[]", false, ), message( chat, "m9", None, (PRIYA_ID, priya_name), at(0, 13, 45), &format!( "

Ship it!

\"Party\"", demo_gifs::RECEIVED_GIF_KEY, demo_gifs::RECEIVED_GIF_SIZE.0, demo_gifs::RECEIVED_GIF_SIZE.1 ), "[]", false, ), message( chat, FRENCH_MESSAGE, None, (LEA_ID, lea_name), at(0, 13, 47), "

Bonjour \u{e0} tous, la version 0.2 est pr\u{ea}te. Pouvez-vous v\u{e9}rifier la liste de contr\u{f4}le avant vendredi\u{a0}?

", "[]", false, ), message( chat, SPANISH_MESSAGE, None, jonas, at(0, 13, 49), "

Gracias por el aviso. Probar\u{e9} la compilaci\u{f3}n esta tarde y os dir\u{e9} si algo falla.

", "[]", false, ), message( chat, "m10", None, (PRIYA_ID, priya_name), at(0, 13, 50), "

", &many, false, ), message( chat, "m11", None, me, at(0, 13, 51), "

\u{1f44d}\u{1f389}

", "[]", false, ), message( chat, "m12", None, (LEA_ID, lea_name), at(0, 13, 52), "

1\u{fe0f}\u{20e3}Freeze the branch

2\u{fe0f}\u{20e3}Tag the release

3\u{fe0f}\u{20e3} Publish the notes

", "[]", false, ), { let org = reactions_json(vec![ reaction( &format!("koffie;{DEMO_ORG_KOFIE_ID}"), &[ (MARA_ID, mara_name, at(0, 13, 58)), (JONAS_ID, jonas_name, at(0, 13, 59)), ], ), reaction( &format!("feest;{DEMO_ORG_FEEST_ID}"), &[(PRIYA_ID, priya_name, at(0, 14, 0))], ), ]); message( chat, "m13", None, me, at(0, 13, 56), &format!( "

De organisatie-emoji staan erin, bijvoorbeeld {} bij de koffie en {} als we live gaan.

", demo_org_emoji_html("koffie", DEMO_ORG_KOFIE_ID), demo_org_emoji_html("ship-it", DEMO_ORG_SHIPIT_ID), ), &org, false, ) }, ] } fn unread_messages() -> Vec { let me = (DEMO_USER_ID, DEMO_USER_NAME); let lea = (LEA_ID, "Lea Schneider"); let tobias = (TOBIAS_ID, "Tobias Klein"); let rows = [ ( "u1", me, at(1, 17, 5), "

Can you enable access for North?

", ), ("u2", tobias, at(1, 17, 20), "

I'll check with IT.

"), ( "u3", lea, at(0, 12, 40), "

Good morning, access is ready.

", ), ( "u4", lea, at(0, 12, 41), "

Sign in with your company ID, no password needed.

", ), ("u5", lea, at(0, 12, 50), "

Access is enabled now

"), ]; rows.into_iter() .map(|(id, sender, time, html)| { message(UNREAD_CHAT, id, None, sender, time, html, "[]", false) }) .map(|record| match record.message_id.as_str() { "u5" => with_importance(record, MessageImportance::Urgent), _ => record, }) .collect() } const DEMO_EXTRA_TABS_CHANNEL: &str = "demo-channel-1-2"; const DEMO_EXTRA_TABS: [&str; 6] = [ "Incident dashboard", "Postmortems", "Escalation policy", "Status page", "Vendor contacts", "On-call calendar", ]; fn demo_tab( channel_id: &str, name: &str, definition_id: &str, open_url: Option<&str>, ) -> ChannelTabRecord { ChannelTabRecord { tab_id: format!("{channel_id}-{}", name.to_lowercase().replace(' ', "-")), name: name.to_owned(), definition_id: definition_id.to_owned(), open_url: open_url.map(str::to_owned), } } fn demo_channel_tabs(channel_id: &str) -> Vec { let mut tabs = vec![ demo_tab( channel_id, "Runbook", "com.microsoft.teamspace.tab.web", Some("https://wiki.example.com/display/TEAM/Runbook"), ), demo_tab( channel_id, "Sprint board", "com.microsoft.teamspace.tab.planner", None, ), demo_tab( channel_id, "Team notes", "0d820ecd-def2-4297-adad-78056cde7c78", Some("https://onenote.example.com/notes"), ), ]; if channel_id == DEMO_EXTRA_TABS_CHANNEL { tabs.extend(DEMO_EXTRA_TABS.iter().map(|name| { demo_tab( channel_id, name, "com.microsoft.teamspace.tab.web", Some("https://wiki.example.com/display/TEAM/Page"), ) })); } tabs } fn demo_team_layout(channels: &[ChannelRecord]) -> Vec { DEMO_TEAM_ORDER .iter() .map(|team_id| TeamLayoutRecord { rights: store::TeamRights { add_channel: true, add_private_channel: true, ..Default::default() }, team_id: (*team_id).to_owned(), hidden: *team_id == DEMO_HIDDEN_TEAM, channels: channels .iter() .filter(|channel| channel.team_id == *team_id) .map(|channel| ChannelLayoutRecord { substrate_group_id: None, channel_id: channel.id.clone(), general: channel.name == "General", hidden: channel.id == DEMO_HIDDEN_CHANNEL, tabs: demo_channel_tabs(&channel.id), notifications: DEMO_CHANNEL_NOTIFICATIONS .iter() .find(|(id, _, _)| *id == channel.id) .map(|(_, level, include_replies)| ChannelNotifications { level: *level, include_replies: *include_replies, }) .unwrap_or_default(), }) .collect(), }) .collect() } const ROLLOUT_REPLIES: [(&str, &str); 12] = [ (MARA_ID, "Staging looks good on my side."), (JONAS_ID, "Smoke tests passed, no regressions."), (PRIYA_ID, "Docs for the new settings page are merged."), (LEA_ID, "Support is briefed, nothing blocking."), (MARA_ID, "Can we keep the old export for one more release?"), (JONAS_ID, "Yes, behind a flag. I will add it today."), (PRIYA_ID, "Changelog draft is ready for review."), (LEA_ID, "Customer success wants a heads-up the day before."), (MARA_ID, "I will send that mail on Thursday."), (JONAS_ID, "Flag is in, rebuilding staging now."), (PRIYA_ID, "Rollback steps are in the runbook."), (LEA_ID, "All green from QA. Go for Friday."), ]; fn channel_messages() -> Vec { let channel = "demo-channel-1-1"; let mara = (MARA_ID, "Mara Lindqvist"); let tobias = (TOBIAS_ID, "Tobias Klein"); let people = [ (MARA_ID, "Mara Lindqvist"), (JONAS_ID, "Jonas Ortega"), (PRIYA_ID, "Priya Nair"), (LEA_ID, "Lea Schneider"), ]; let rollout_replies = ROLLOUT_REPLIES .iter() .enumerate() .map(|(index, (sender, text))| { let sender = people .iter() .copied() .find(|(id, _)| id == sender) .expect("known person"); message( channel, &format!("t3r{}", index + 1), Some("t3"), sender, at(0, 9, 40) + Duration::minutes(6 * index as i64), &format!("

{text}

"), "[]", false, ) }); let mut records = vec![ message( channel, "t1", None, mara, at(0, 8, 0), "

Weekly sync notes are up.

", "[]", false, ), message( channel, "t1r1", Some("t1"), tobias, at(0, 8, 20), "

Thanks, adding my items.

", "[]", false, ), with_subject( message( channel, "t3", None, tobias, at(0, 9, 30), "

Release build 42 is green, deploying to staging now.

", "[]", false, ), "Release 42 rollout", ), message( channel, "t2", None, tobias, at(0, 10, 0), "

Who owns the on-call handover?

", "[]", false, ), message( channel, "t4", None, mara, at(3, 8, 42), "

Sprint Demos.

I added you both to the sprint. Tobias Klein did you present everything about the migration tool? The spec is at https://wiki.example.com/display/TEAM/Settings+types+and+password+policiesCan you please review it?

", "[]", false, ), message( channel, "t4r1", Some("t4"), tobias, at(0, 9, 15), "

Yes, all done.

", "[]", false, ), ]; records.extend(rollout_replies); records.extend(code_post(channel, tobias)); records.extend(shared_channel_messages(channel, mara, tobias)); records } fn code_post(channel: &str, tobias: (&str, &str)) -> Vec { let laughs = reactions_json(vec![reaction( "laugh", &[ (PRIYA_ID, "Priya Nair", at(0, 11, 20)), (JONAS_ID, "Jonas Ortega", at(0, 11, 22)), ], )]); vec![ with_subject( message( channel, "t8", None, tobias, at(0, 11, 5), "

I got this error message when running \"Invoke-WebRequest\" in the build script:

 

Invoke-WebRequest : The response content cannot be parsed because the Internet Explorer engine is not available, or Internet Explorer's first-launch configuration is not complete. Specify the UseBasicParsing parameter and try again.

", &laughs, false, ), "Build script error", ), message( channel, "t8r1", Some("t8"), (JONAS_ID, "Jonas Ortega"), at(0, 11, 30), "

Add -UseBasicParsing to the call, that fixes it.

", "[]", false, ), with_attachments( with_subject( message( channel, "t9", None, tobias, at(0, 12, 10), "

Please merge your last changes by Thursday 18:00. Anything later goes into release 44.

", "[]", false, ), "Code freeze starts Thursday", ), &format!( r#"[{{"content_type":"{ANNOUNCEMENT_BANNER_TYPE}","id":"announcement-card-demo","name":null,"url":null,"text":null,"content":{}}}]"#, serde_json::Value::String( r#"{"title":"Release 43 ships Friday","cardImageType":"colorTheme","cardImageDetails":{"colorTheme":"periwinkleBlue"}}"#.to_owned() ) ), ), ] } fn shared_channel_messages( channel: &str, mara: (&str, &str), tobias: (&str, &str), ) -> Vec { let priya = (PRIYA_ID, "Priya Nair"); let jonas = (JONAS_ID, "Jonas Ortega"); let reference = |name: &str, size: u64| { format!( r#"{{"content_type":"reference","name":"{name}","url":"https://demo.sharepoint.example/sites/demo/{name}","text":null,"size":{size}}}"# ) }; vec![ with_attachments( with_subject( message( channel, "t5", None, priya, at(1, 14, 5), "

Roadmap deck and checklist for Q4 are attached.

", "[]", false, ), "Q4 planning files", ), &format!( "[{},{}]", reference("Roadmap-Q4.pptx", 3_412_000), reference("Release-Checklist-Q4.xlsx", 48_213) ), ), message( channel, "t5r1", Some("t5"), jonas, at(1, 14, 30), "

Rollback steps are here: https://docs.example.org/runbooks/rollback

", "[]", false, ), with_attachments( message( channel, "t6", None, mara, at(12, 10, 0), "

Postmortem draft for the September outage. Status page: https://status.example.com/incidents/2026-09

", "[]", false, ), &format!("[{}]", reference("Postmortem-Draft.docx", 91_400)), ), with_attachments( message( channel, "t7", None, tobias, at(20, 9, 0), "

Rollout plan for the new export, please review.

", "[]", false, ), &format!("[{}]", reference("Rollout-Plan.pdf", 2_306_867)), ), ] } fn crc32(bytes: &[u8]) -> u32 { let mut crc = 0xffff_ffffu32; for byte in bytes { crc ^= u32::from(*byte); for _ in 0..8 { crc = if crc & 1 == 1 { (crc >> 1) ^ 0xedb8_8320 } else { crc >> 1 }; } } !crc } fn adler32(bytes: &[u8]) -> u32 { let (mut low, mut high) = (1u32, 0u32); for byte in bytes { low = (low + u32::from(*byte)) % 65521; high = (high + low) % 65521; } (high << 16) | low } fn png_chunk(output: &mut Vec, kind: &[u8; 4], data: &[u8]) { output.extend_from_slice(&(data.len() as u32).to_be_bytes()); let mut body = kind.to_vec(); body.extend_from_slice(data); output.extend_from_slice(&body); output.extend_from_slice(&crc32(&body).to_be_bytes()); } fn inside(x: f32, y: f32, center: (f32, f32), radius: (f32, f32)) -> bool { ((x - center.0) / radius.0).powi(2) + ((y - center.1) / radius.1).powi(2) <= 1. } fn staging_pixel(column: usize, row: usize) -> [u8; 3] { let (width, height) = (STAGING_SIZE.0 as f32, STAGING_SIZE.1 as f32); let (x, y) = (column as f32, row as f32); let shade = y / height; let background = [ (30. - 14. * shade) as u8, (41. - 16. * shade) as u8, (59. - 14. * shade) as u8, ]; let bar_width = width / 14.; let slot = (x / bar_width) as usize; let in_bar = x - slot as f32 * bar_width > bar_width * 0.18; let bar_height = height * (0.25 + 0.5 * (((slot * 7 + 3) % 11) as f32 / 11.)); let on_bars = in_bar && y > height * 0.86 - bar_height && y < height * 0.86 && slot < 14; let header = y < height * 0.1; if header { [22, 30, 45] } else if on_bars { if slot % 4 == 3 { [226, 87, 47] } else { [88, 133, 196] } } else if (y - height * 0.86).abs() < 1.5 { [71, 85, 105] } else { background } } fn encode_png(palette: &Palette) -> Vec { let scale = PHOTO_SIZE as f32 / DEMO_PHOTO_SIDE as f32; encode_rgb(DEMO_PHOTO_SIDE, DEMO_PHOTO_SIDE, |column, row| { let (x, y) = ((column as f32 + 0.5) * scale, (row as f32 + 0.5) * scale); if inside(x, y, (24., 21.), (8.5, 9.5)) { palette.skin } else if inside(x, y, (24., 19.), (10.5, 11.)) && y < 22. { palette.hair } else if inside(x, y, (24., 50.), (22., 19.)) { palette.shirt } else { palette.background } }) } fn encode_rgb(width: usize, height: usize, pixel: impl Fn(usize, usize) -> [u8; 3]) -> Vec { let mut raw = Vec::with_capacity(height * (width * 3 + 1)); for row in 0..height { raw.push(0); for column in 0..width { raw.extend_from_slice(&pixel(column, row)); } } let mut zlib = vec![0x78, 0x01]; let mut blocks = raw.chunks(65535).peekable(); while let Some(block) = blocks.next() { zlib.push(u8::from(blocks.peek().is_none())); zlib.extend_from_slice(&(block.len() as u16).to_le_bytes()); zlib.extend_from_slice(&(!(block.len() as u16)).to_le_bytes()); zlib.extend_from_slice(block); } zlib.extend_from_slice(&adler32(&raw).to_be_bytes()); let mut header = Vec::new(); header.extend_from_slice(&(width as u32).to_be_bytes()); header.extend_from_slice(&(height as u32).to_be_bytes()); header.extend_from_slice(&[8, 2, 0, 0, 0]); let mut png = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]; png_chunk(&mut png, b"IHDR", &header); png_chunk(&mut png, b"IDAT", &zlib); png_chunk(&mut png, b"IEND", &[]); png } pub fn team_members() -> Vec { std::iter::once((DEMO_USER_ID, DEMO_USER_NAME, DEMO_USER_EMAIL)) .chain( PEOPLE_DIRECTORY .iter() .map(|(user_id, name, _, email)| (*user_id, *name, *email)), ) .enumerate() .map( |(index, (user_id, name, email))| crate::manage_team::TeamMember { user_id: Some(user_id.to_owned()), name: name.to_owned(), email: Some(email.to_owned()), owner: index == 1 || index == 3, }, ) .collect() } #[cfg(test)] mod tests { use super::*; #[test] fn the_demo_has_one_important_and_one_urgent_message() { let store = Store::open_in_memory().unwrap(); seed(&store); let importance = |chat: &str, message_id: &str| { store .messages(chat, None, 50) .unwrap() .into_iter() .find(|record| record.message_id == message_id) .map(|record| record.importance) }; assert_eq!( importance(PRIORITY_CHAT, "p2"), Some(MessageImportance::High) ); assert_eq!( importance(UNREAD_CHAT, "u5"), Some(MessageImportance::Urgent) ); } #[test] fn a_multi_forward_quotes_each_message_in_order_after_the_comment() { let store = Store::open_in_memory().unwrap(); seed(&store); let chat = store .recent_chats(100) .unwrap() .into_iter() .find(|chat| chat.id == PRIORITY_CHAT) .unwrap(); let item = |message_id: &str, text: &str| crate::message_actions::ForwardItem { message_id: message_id.to_owned(), author: "Synthetic Sender".to_owned(), time: "09:00".to_owned(), text: text.to_owned(), }; let source = ForwardSource { conversation_id: PRIORITY_CHAT.to_owned(), messages: vec![item("m1", "first"), item("m2", "second")], }; let (_, record) = forwarded_message(&chat, &source, "fyi", Utc::now()); let html = &record.body_html; assert!(html.starts_with("

fyi

")); assert_eq!(html.matches(FORWARD_ITEMTYPE).count(), 2); assert!(html.find("first").unwrap() < html.find("second").unwrap()); } #[test] fn png_has_signature_and_ends_with_iend() { let png = encode_png(&MARA); assert_eq!(&png[..8], &[0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a]); assert_eq!(&png[png.len() - 8..png.len() - 4], b"IEND"); } #[test] fn crc_and_adler_match_known_values() { assert_eq!(crc32(b"IEND"), 0xae42_6082); assert_eq!(adler32(b"Wikipedia"), 0x11e6_0398); } #[test] fn mention_candidates_filter_by_name_and_add_scope_in_channels() { let chat = mention_candidates("demo-chat-release", "ma"); assert_eq!(chat.len(), 1); assert_eq!(chat[0].display_name(), "Mara Lindqvist"); let channel = mention_candidates("demo-channel-1-1", "gen"); assert!(matches!(channel[0], MentionCandidate::Channel { .. })); let all = mention_candidates("demo-chat-release", ""); assert_eq!(all.len(), 6); assert!(matches!(all[0], MentionCandidate::Everyone { .. })); assert!( mention_candidates("demo-chat-mara", "") .iter() .all(|candidate| !matches!(candidate, MentionCandidate::Everyone { .. })) ); assert!(matches!( mention_candidates("demo-channel-1-1", "desi")[0], MentionCandidate::Tag { .. } )); } #[test] fn new_group_chat_gets_a_title_and_the_first_message() { let people = vec![ (MARA_ID.to_owned(), "Mara Lindqvist".to_owned()), (JONAS_ID.to_owned(), "Jonas Ortega".to_owned()), ]; let now = Utc::now(); let (chat, record) = new_chat( &[], &people, Some("Crew"), "Hello all", "Hello all", now, ); assert_eq!(chat.id, "demo-chat-new-1"); assert_eq!(chat.kind, "group"); assert_eq!(chat.title, "Crew"); assert_eq!(chat.member_summary, "Mara Lindqvist, Jonas Ortega"); assert_eq!(chat.members.len(), 3); assert_eq!(chat.members[0].user_id.as_deref(), Some(DEMO_USER_ID)); assert_eq!(chat.last_message_preview.as_deref(), Some("Hello all")); assert_eq!(chat.last_message_at, Some(now)); assert_eq!(record.conversation_id, chat.id); assert_eq!(record.sender_id.as_deref(), Some(DEMO_USER_ID)); assert!(record.body_html.contains("Hello")); } #[test] fn new_one_on_one_chat_has_no_title_and_counts_up() { let people = vec![(LEA_ID.to_owned(), "Lea Schneider".to_owned())]; let (first, _) = new_chat(&[], &people, None, "Hi", "Hi", Utc::now()); assert_eq!(first.kind, "oneOnOne"); assert!(first.title.is_empty()); let (second, _) = new_chat(&[first], &people, None, "Hi again", "Hi again", Utc::now()); assert_eq!(second.id, "demo-chat-new-2"); } #[test] fn sending_into_a_chat_refreshes_its_preview() { let base = ChatRecord { id: "demo-chat-x".to_owned(), unread: true, ..Default::default() }; let (chat, record) = send_in_chat(&base, "Ping", "Ping", Utc::now()); assert!(!chat.unread); assert_eq!(chat.last_message_preview.as_deref(), Some("Ping")); assert_eq!(record.conversation_id, "demo-chat-x"); } #[test] fn demo_covers_the_sidebar_edge_cases() { let chats = demo_chats(); assert!(chats.iter().any(|chat| chat.deleted)); assert!(chats.iter().any(|chat| chat.title.len() > 40)); assert!(chats.iter().filter(|chat| chat.unread).count() >= 3); } }