| 1 | use std::collections::HashMap; |
| 2 | use std::sync::{Arc, Mutex}; |
| 3 | |
| 4 | use chatsvc::ConversationRef; |
| 5 | use chrono::{DateTime, Duration, TimeZone, Utc}; |
| 6 | use graph::{ |
| 7 | Channel, Chat, DriveFolder, HostedImage, Member, Message, MessageExtras, MessageTarget, |
| 8 | OutgoingMention, Photo, Presence, SharedFile, Team, UploadDestination, UploadedFile, User, |
| 9 | }; |
| 10 | use serde_json::json; |
| 11 | use store::{ChannelLayoutRecord, ChannelRecord, Store, TeamLayoutRecord, TeamRecord}; |
| 12 | use teams_core::{ |
| 13 | Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent, |
| 14 | DeltaPage, Error, FolderKind, FolderSource, MentionCandidate, MentionInput, MentionTarget, |
| 15 | PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine, |
| 16 | }; |
| 17 | |
| 18 | const ME: &str = "user-me"; |
| 19 | const CHAT: &str = "19:chat@thread.v2"; |
| 20 | const CHANNEL: &str = "19:channel@thread.tacv2"; |
| 21 | |
| 22 | fn base() -> DateTime<Utc> { |
| 23 | Utc.with_ymd_and_hms(2026, 10, 6, 8, 0, 0).unwrap() |
| 24 | } |
| 25 | |
| 26 | fn message(id: u32, minute: i64, body: &str) -> Message { |
| 27 | serde_json::from_value(json!({ |
| 28 | "id": format!("m{id:04}"), |
| 29 | "messageType": "message", |
| 30 | "createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(), |
| 31 | "from": {"user": {"id": "user-ada", "displayName": "Ada Example"}}, |
| 32 | "body": {"contentType": "html", "content": body}, |
| 33 | })) |
| 34 | .unwrap() |
| 35 | } |
| 36 | |
| 37 | fn numbered(count: u32) -> Vec<Message> { |
| 38 | (1..=count) |
| 39 | .map(|index| message(index, i64::from(index), &format!("<p>n{index}</p>"))) |
| 40 | .collect() |
| 41 | } |
| 42 | |
| 43 | fn chat( |
| 44 | id: &str, |
| 45 | topic: Option<&str>, |
| 46 | last_minute: i64, |
| 47 | read_minute: i64, |
| 48 | from: &str, |
| 49 | hidden: bool, |
| 50 | ) -> Chat { |
| 51 | serde_json::from_value(json!({ |
| 52 | "id": id, |
| 53 | "topic": topic, |
| 54 | "chatType": if topic.is_some() { "group" } else { "oneOnOne" }, |
| 55 | "lastUpdatedDateTime": (base() + Duration::minutes(last_minute)).to_rfc3339(), |
| 56 | "members": [ |
| 57 | {"userId": ME, "displayName": "Me Myself"}, |
| 58 | {"userId": "user-ada", "displayName": "Ada Example"} |
| 59 | ], |
| 60 | "lastMessagePreview": {"id": "p", "createdDateTime": (base() + Duration::minutes(last_minute)).to_rfc3339(), "from": {"user": {"id": from}}}, |
| 61 | "viewpoint": {"lastMessageReadDateTime": (base() + Duration::minutes(read_minute)).to_rfc3339(), "isHidden": hidden}, |
| 62 | })) |
| 63 | .unwrap() |
| 64 | } |
| 65 | |
| 66 | type ScheduledCall = (String, String, DateTime<Utc>, String); |
| 67 | |
| 68 | #[derive(Default)] |
| 69 | struct Fake { |
| 70 | chats: Mutex<Vec<Chat>>, |
| 71 | chat_messages: Mutex<Vec<Message>>, |
| 72 | channel_pages: Mutex<Vec<Vec<Message>>>, |
| 73 | teams: Mutex<Vec<Team>>, |
| 74 | failing_team: Mutex<Option<String>>, |
| 75 | sent: Mutex<Vec<String>>, |
| 76 | chat_calls: Mutex<usize>, |
| 77 | chat_page_calls: Mutex<usize>, |
| 78 | team_calls: Mutex<usize>, |
| 79 | calls: Mutex<Vec<String>>, |
| 80 | delta_items: Mutex<Vec<Message>>, |
| 81 | thread_replies: Mutex<Vec<Message>>, |
| 82 | delta_fails: Mutex<bool>, |
| 83 | photos: Mutex<HashMap<String, Vec<u8>>>, |
| 84 | photo_requests: Mutex<Vec<Vec<String>>>, |
| 85 | presence_answers: Mutex<Vec<Presence>>, |
| 86 | presence_subscriptions: Mutex<Vec<(String, Vec<String>, bool)>>, |
| 87 | hosted_requests: Mutex<Vec<String>>, |
| 88 | external_requests: Mutex<Vec<String>>, |
| 89 | mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>, |
| 90 | extras_sent: Mutex<Vec<MessageExtras>>, |
| 91 | folder_requests: Mutex<usize>, |
| 92 | directory_users: Mutex<Vec<User>>, |
| 93 | horizons: Mutex<Vec<chatsvc::MemberHorizon>>, |
| 94 | horizon_calls: Mutex<usize>, |
| 95 | apps: Mutex<Vec<chatsvc::ChatApp>>, |
| 96 | app_calls: Mutex<usize>, |
| 97 | invokes: Mutex<Vec<chatsvc::InvokeRequest>>, |
| 98 | invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>, |
| 99 | muted_states: Mutex<Vec<(String, bool)>>, |
| 100 | muted_fails: Mutex<bool>, |
| 101 | link_pages: Mutex<Vec<chatsvc::MessageLinks>>, |
| 102 | link_page_calls: Mutex<Vec<String>>, |
| 103 | links_put: Mutex<Vec<(String, String)>>, |
| 104 | link_info_calls: Mutex<usize>, |
| 105 | scheduled: Mutex<Vec<ScheduledCall>>, |
| 106 | own_status_answer: Mutex<chatsvc::PresenceStatus>, |
| 107 | availability_puts: Mutex<Vec<Option<chatsvc::ForcedAvailability>>>, |
| 108 | note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>, |
| 109 | } |
| 110 | |
| 111 | impl Fake { |
| 112 | fn set_chat_messages(&self, messages: Vec<Message>) { |
| 113 | *self.chat_messages.lock().unwrap() = messages; |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | fn page_of(items: Vec<Message>, next_link: Option<String>) -> Result<RemotePage> { |
| 118 | Ok(RemotePage { items, next_link }) |
| 119 | } |
| 120 | |
| 121 | struct Handle(Arc<Fake>); |
| 122 | |
| 123 | impl std::ops::Deref for Handle { |
| 124 | type Target = Fake; |
| 125 | |
| 126 | fn deref(&self) -> &Fake { |
| 127 | &self.0 |
| 128 | } |
| 129 | } |
| 130 | |
| 131 | fn describe(target: &MessageTarget) -> String { |
| 132 | match target { |
| 133 | MessageTarget::Chat { message_id, .. } => message_id.clone(), |
| 134 | MessageTarget::Channel { |
| 135 | message_id, |
| 136 | root_id, |
| 137 | .. |
| 138 | } => format!("channel:{}:{message_id}", root_id.as_deref().unwrap_or("-")), |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | fn unsupported<T>() -> Result<T> { |
| 143 | Err(Error::Unsupported("not faked")) |
| 144 | } |
| 145 | |
| 146 | impl Fake { |
| 147 | fn record(&self, call: String) { |
| 148 | self.calls.lock().unwrap().push(call); |
| 149 | } |
| 150 | |
| 151 | fn calls(&self) -> Vec<String> { |
| 152 | self.calls.lock().unwrap().clone() |
| 153 | } |
| 154 | |
| 155 | fn sorted_chats(&self) -> Vec<Chat> { |
| 156 | let mut chats = self.chats.lock().unwrap().clone(); |
| 157 | chats.sort_by_key(|chat| std::cmp::Reverse(chat.last_message_time())); |
| 158 | chats |
| 159 | } |
| 160 | |
| 161 | fn chats_from(&self, offset: usize, top: usize) -> ChatsPage { |
| 162 | *self.chat_page_calls.lock().unwrap() += 1; |
| 163 | let chats = self.sorted_chats(); |
| 164 | let items: Vec<Chat> = chats.iter().skip(offset).take(top).cloned().collect(); |
| 165 | let next_link = |
| 166 | (offset + top < chats.len()).then(|| format!("chats:{}:{top}", offset + top)); |
| 167 | ChatsPage { items, next_link } |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | impl Remote for Handle { |
| 172 | async fn me(&self) -> Result<User> { |
| 173 | Ok(serde_json::from_value(json!({"id": ME, "displayName": "Me Myself"})).unwrap()) |
| 174 | } |
| 175 | |
| 176 | async fn chats_page(&self, top: usize) -> Result<ChatsPage> { |
| 177 | Ok(self.chats_from(0, top)) |
| 178 | } |
| 179 | |
| 180 | async fn chats_at(&self, next_link: &str) -> Result<ChatsPage> { |
| 181 | let mut parts = next_link.trim_start_matches("chats:").split(':'); |
| 182 | let offset = parts.next().unwrap().parse().unwrap(); |
| 183 | let top = parts.next().unwrap().parse().unwrap(); |
| 184 | Ok(self.chats_from(offset, top)) |
| 185 | } |
| 186 | |
| 187 | async fn chat(&self, _chat_id: &str) -> Result<Chat> { |
| 188 | unsupported() |
| 189 | } |
| 190 | |
| 191 | async fn chat_members(&self, _chat_id: &str) -> Result<Vec<Member>> { |
| 192 | Ok(vec![ |
| 193 | serde_json::from_value( |
| 194 | json!({"userId": ME, "tenantId": "tenant-1", "displayName": "Me Myself"}), |
| 195 | ) |
| 196 | .unwrap(), |
| 197 | ]) |
| 198 | } |
| 199 | |
| 200 | async fn joined_teams(&self) -> Result<Vec<Team>> { |
| 201 | *self.team_calls.lock().unwrap() += 1; |
| 202 | Ok(self.teams.lock().unwrap().clone()) |
| 203 | } |
| 204 | |
| 205 | async fn channels_for_teams(&self, team_ids: &[String]) -> Result<Vec<Result<Vec<Channel>>>> { |
| 206 | let failing = self.failing_team.lock().unwrap().clone(); |
| 207 | Ok(team_ids |
| 208 | .iter() |
| 209 | .map(|team_id| { |
| 210 | if failing.as_deref() == Some(team_id.as_str()) { |
| 211 | return Err(Error::Unsupported("forced failure")); |
| 212 | } |
| 213 | Ok(vec![serde_json::from_value(json!({"id": CHANNEL, "displayName": "General", "membershipType": "standard"})).unwrap()]) |
| 214 | }) |
| 215 | .collect()) |
| 216 | } |
| 217 | |
| 218 | async fn chat_messages( |
| 219 | &self, |
| 220 | _chat_id: &str, |
| 221 | before: Option<DateTime<Utc>>, |
| 222 | top: usize, |
| 223 | ) -> Result<RemotePage> { |
| 224 | *self.chat_calls.lock().unwrap() += 1; |
| 225 | let mut matching: Vec<Message> = self |
| 226 | .chat_messages |
| 227 | .lock() |
| 228 | .unwrap() |
| 229 | .iter() |
| 230 | .filter(|message| { |
| 231 | before.is_none_or(|before| message.created_date_time.unwrap() < before) |
| 232 | }) |
| 233 | .cloned() |
| 234 | .collect(); |
| 235 | matching.sort_by_key(|message| std::cmp::Reverse(message.created_date_time)); |
| 236 | let has_more = matching.len() > top; |
| 237 | matching.truncate(top); |
| 238 | page_of( |
| 239 | matching, |
| 240 | has_more.then(|| "https://graph.microsoft.com/v1.0/next".to_owned()), |
| 241 | ) |
| 242 | } |
| 243 | |
| 244 | async fn chat_message(&self, _chat_id: &str, message_id: &str) -> Result<Message> { |
| 245 | self.record(format!("chat_message {message_id}")); |
| 246 | self.chat_messages |
| 247 | .lock() |
| 248 | .unwrap() |
| 249 | .iter() |
| 250 | .find(|message| message.id == message_id) |
| 251 | .cloned() |
| 252 | .ok_or(Error::Unsupported("missing message")) |
| 253 | } |
| 254 | |
| 255 | async fn channel_messages( |
| 256 | &self, |
| 257 | _team_id: &str, |
| 258 | _channel_id: &str, |
| 259 | _top: usize, |
| 260 | ) -> Result<RemotePage> { |
| 261 | let pages = self.channel_pages.lock().unwrap(); |
| 262 | page_of( |
| 263 | pages[0].clone(), |
| 264 | (pages.len() > 1).then(|| "page:1".to_owned()), |
| 265 | ) |
| 266 | } |
| 267 | |
| 268 | async fn channel_messages_at(&self, next_link: &str) -> Result<RemotePage> { |
| 269 | let index: usize = next_link.trim_start_matches("page:").parse().unwrap(); |
| 270 | let pages = self.channel_pages.lock().unwrap(); |
| 271 | page_of( |
| 272 | pages[index].clone(), |
| 273 | (pages.len() > index + 1).then(|| format!("page:{}", index + 1)), |
| 274 | ) |
| 275 | } |
| 276 | |
| 277 | async fn channel_message( |
| 278 | &self, |
| 279 | _team_id: &str, |
| 280 | _channel_id: &str, |
| 281 | message_id: &str, |
| 282 | ) -> Result<Message> { |
| 283 | self.record(format!("channel_message {message_id}")); |
| 284 | self.channel_pages |
| 285 | .lock() |
| 286 | .unwrap() |
| 287 | .iter() |
| 288 | .flatten() |
| 289 | .find(|message| message.id == message_id) |
| 290 | .cloned() |
| 291 | .ok_or(Error::Unsupported("missing message")) |
| 292 | } |
| 293 | |
| 294 | async fn channel_reply( |
| 295 | &self, |
| 296 | _team_id: &str, |
| 297 | _channel_id: &str, |
| 298 | message_id: &str, |
| 299 | reply_id: &str, |
| 300 | ) -> Result<Message> { |
| 301 | self.record(format!("channel_reply {message_id} {reply_id}")); |
| 302 | self.channel_pages |
| 303 | .lock() |
| 304 | .unwrap() |
| 305 | .iter() |
| 306 | .flatten() |
| 307 | .filter(|root| root.id == message_id) |
| 308 | .flat_map(|root| root.replies.iter()) |
| 309 | .find(|reply| reply.id == reply_id) |
| 310 | .cloned() |
| 311 | .ok_or(Error::Unsupported("missing reply")) |
| 312 | } |
| 313 | |
| 314 | async fn channel_delta( |
| 315 | &self, |
| 316 | _team_id: &str, |
| 317 | _channel_id: &str, |
| 318 | modified_after: Option<DateTime<Utc>>, |
| 319 | ) -> Result<DeltaPage> { |
| 320 | self.record(format!("channel_delta since={}", modified_after.is_some())); |
| 321 | if *self.delta_fails.lock().unwrap() { |
| 322 | return unsupported(); |
| 323 | } |
| 324 | Ok(DeltaPage { |
| 325 | items: self.delta_items.lock().unwrap().clone(), |
| 326 | next_link: None, |
| 327 | delta_link: Some("delta:1".to_owned()), |
| 328 | }) |
| 329 | } |
| 330 | |
| 331 | async fn channel_delta_at(&self, link: &str) -> Result<DeltaPage> { |
| 332 | self.record(format!("channel_delta_at {link}")); |
| 333 | if *self.delta_fails.lock().unwrap() { |
| 334 | return unsupported(); |
| 335 | } |
| 336 | Ok(DeltaPage { |
| 337 | items: std::mem::take(&mut *self.delta_items.lock().unwrap()), |
| 338 | next_link: None, |
| 339 | delta_link: Some("delta:2".to_owned()), |
| 340 | }) |
| 341 | } |
| 342 | |
| 343 | async fn channel_replies( |
| 344 | &self, |
| 345 | _team_id: &str, |
| 346 | _channel_id: &str, |
| 347 | root_ids: &[String], |
| 348 | ) -> Result<Vec<Result<Vec<Message>>>> { |
| 349 | let replies = self.thread_replies.lock().unwrap().clone(); |
| 350 | Ok(root_ids |
| 351 | .iter() |
| 352 | .map(|root_id| { |
| 353 | Ok(replies |
| 354 | .iter() |
| 355 | .filter(|reply| reply.reply_to_id.as_deref() == Some(root_id.as_str())) |
| 356 | .cloned() |
| 357 | .collect()) |
| 358 | }) |
| 359 | .collect()) |
| 360 | } |
| 361 | |
| 362 | async fn send_chat_message( |
| 363 | &self, |
| 364 | _chat_id: &str, |
| 365 | html: &str, |
| 366 | mentions: &[OutgoingMention], |
| 367 | extras: &MessageExtras, |
| 368 | ) -> Result<Message> { |
| 369 | self.sent.lock().unwrap().push(html.to_owned()); |
| 370 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 371 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 372 | Ok(message(9000, 500, html)) |
| 373 | } |
| 374 | |
| 375 | async fn send_channel_message( |
| 376 | &self, |
| 377 | _team_id: &str, |
| 378 | _channel_id: &str, |
| 379 | html: &str, |
| 380 | subject: Option<&str>, |
| 381 | mentions: &[OutgoingMention], |
| 382 | extras: &MessageExtras, |
| 383 | ) -> Result<Message> { |
| 384 | self.record(format!("post subject={subject:?}")); |
| 385 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 386 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 387 | Ok(message(9001, 501, html)) |
| 388 | } |
| 389 | |
| 390 | async fn reply_to_channel_message( |
| 391 | &self, |
| 392 | _team_id: &str, |
| 393 | _channel_id: &str, |
| 394 | message_id: &str, |
| 395 | html: &str, |
| 396 | mentions: &[OutgoingMention], |
| 397 | extras: &MessageExtras, |
| 398 | ) -> Result<Message> { |
| 399 | self.record(format!("reply to {message_id}")); |
| 400 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 401 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 402 | Ok(message(9002, 502, html)) |
| 403 | } |
| 404 | |
| 405 | async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> { |
| 406 | self.record(format!("mark_read {chat_id} {user_id} {tenant_id}")); |
| 407 | Ok(()) |
| 408 | } |
| 409 | |
| 410 | async fn mark_chat_unread( |
| 411 | &self, |
| 412 | chat_id: &str, |
| 413 | user_id: &str, |
| 414 | tenant_id: &str, |
| 415 | last_read_at: DateTime<Utc>, |
| 416 | ) -> Result<()> { |
| 417 | self.record(format!( |
| 418 | "mark_unread {chat_id} {user_id} {tenant_id} {}", |
| 419 | last_read_at.timestamp_millis() |
| 420 | )); |
| 421 | Ok(()) |
| 422 | } |
| 423 | |
| 424 | async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> { |
| 425 | self.record(format!("hide {chat_id} {user_id} {tenant_id}")); |
| 426 | Ok(()) |
| 427 | } |
| 428 | |
| 429 | async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> { |
| 430 | self.record(format!("unhide {chat_id} {user_id} {tenant_id}")); |
| 431 | Ok(()) |
| 432 | } |
| 433 | |
| 434 | async fn leave_chat(&self, chat_id: &str, user_id: &str) -> Result<()> { |
| 435 | self.record(format!("leave {chat_id} {user_id}")); |
| 436 | Ok(()) |
| 437 | } |
| 438 | |
| 439 | async fn muted_chat_states(&self) -> Result<Vec<(String, bool)>> { |
| 440 | if *self.muted_fails.lock().unwrap() { |
| 441 | return Err(Error::Unsupported("forced failure")); |
| 442 | } |
| 443 | Ok(self.muted_states.lock().unwrap().clone()) |
| 444 | } |
| 445 | |
| 446 | async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> { |
| 447 | self.record(format!("mute {chat_id} {muted}")); |
| 448 | Ok(()) |
| 449 | } |
| 450 | |
| 451 | async fn set_channel_notifications( |
| 452 | &self, |
| 453 | channel_id: &str, |
| 454 | notifications: store::ChannelNotifications, |
| 455 | ) -> Result<()> { |
| 456 | self.record(format!( |
| 457 | "channel notifications {channel_id} {} {}", |
| 458 | notifications.level.key(), |
| 459 | notifications.include_replies |
| 460 | )); |
| 461 | Ok(()) |
| 462 | } |
| 463 | |
| 464 | async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> { |
| 465 | self.record(format!( |
| 466 | "typing {} {active}", |
| 467 | conversation.conversation_id() |
| 468 | )); |
| 469 | Ok(()) |
| 470 | } |
| 471 | |
| 472 | async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> { |
| 473 | self.record(format!("set_reaction {} {reaction_type}", describe(target))); |
| 474 | Ok(()) |
| 475 | } |
| 476 | |
| 477 | async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> { |
| 478 | self.record(format!( |
| 479 | "unset_reaction {} {reaction_type}", |
| 480 | describe(target) |
| 481 | )); |
| 482 | Ok(()) |
| 483 | } |
| 484 | |
| 485 | async fn edit_message( |
| 486 | &self, |
| 487 | target: &MessageTarget, |
| 488 | html: &str, |
| 489 | mentions: &[OutgoingMention], |
| 490 | extras: &MessageExtras, |
| 491 | ) -> Result<()> { |
| 492 | self.record(format!("edit {} {html}", describe(target))); |
| 493 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 494 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 495 | Ok(()) |
| 496 | } |
| 497 | |
| 498 | async fn delete_file(&self, file: &UploadedFile) -> Result<()> { |
| 499 | self.record(format!("delete_file {}", file.item_id)); |
| 500 | Ok(()) |
| 501 | } |
| 502 | |
| 503 | async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> { |
| 504 | self.record(format!("soft_delete {user_id} {}", describe(target))); |
| 505 | Ok(()) |
| 506 | } |
| 507 | |
| 508 | async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> { |
| 509 | self.record(format!("one_on_one {my_user_id} {user_id}")); |
| 510 | Ok(chat("19:new@thread.v2", None, 40, 40, ME, false)) |
| 511 | } |
| 512 | |
| 513 | async fn create_group( |
| 514 | &self, |
| 515 | my_user_id: &str, |
| 516 | user_ids: &[String], |
| 517 | topic: Option<&str>, |
| 518 | ) -> Result<Chat> { |
| 519 | self.record(format!( |
| 520 | "group {my_user_id} {} {topic:?}", |
| 521 | user_ids.join(",") |
| 522 | )); |
| 523 | Ok(chat("19:group@thread.v2", topic, 41, 41, ME, false)) |
| 524 | } |
| 525 | |
| 526 | async fn reply_with_quote( |
| 527 | &self, |
| 528 | chat_id: &str, |
| 529 | quoted_message_id: &str, |
| 530 | html: &str, |
| 531 | mentions: &[OutgoingMention], |
| 532 | extras: &MessageExtras, |
| 533 | ) -> Result<Message> { |
| 534 | self.record(format!("quote_reply {chat_id} {quoted_message_id} {html}")); |
| 535 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 536 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 537 | Ok(message(9003, 503, html)) |
| 538 | } |
| 539 | |
| 540 | async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> { |
| 541 | *self.folder_requests.lock().unwrap() += 1; |
| 542 | self.record(format!("files_folder {team_id} {channel_id}")); |
| 543 | Ok(DriveFolder { |
| 544 | drive_id: "drive-1".into(), |
| 545 | item_id: "folder-1".into(), |
| 546 | }) |
| 547 | } |
| 548 | |
| 549 | async fn upload_file( |
| 550 | &self, |
| 551 | destination: &UploadDestination, |
| 552 | file_name: &str, |
| 553 | bytes: &[u8], |
| 554 | progress: &(dyn Fn(u8) + Send + Sync), |
| 555 | ) -> Result<UploadedFile> { |
| 556 | let target = match destination { |
| 557 | UploadDestination::ChatFiles => "chat-files".to_owned(), |
| 558 | UploadDestination::Folder(folder) => format!("{}/{}", folder.drive_id, folder.item_id), |
| 559 | }; |
| 560 | self.record(format!("upload {target} {file_name} {}", bytes.len())); |
| 561 | progress(50); |
| 562 | progress(100); |
| 563 | Ok(UploadedFile { |
| 564 | drive_id: "drive-1".into(), |
| 565 | item_id: "item-1".into(), |
| 566 | name: file_name.to_owned(), |
| 567 | web_url: "https://files.example/web".into(), |
| 568 | web_dav_url: Some("https://files.example/dav".into()), |
| 569 | etag: "\"{GUID-1},2\"".into(), |
| 570 | }) |
| 571 | } |
| 572 | |
| 573 | async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> { |
| 574 | self.record(format!("resolve {open_url}")); |
| 575 | Ok(SharedFile { |
| 576 | name: "big.bin".into(), |
| 577 | size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3, |
| 578 | download_url: if open_url.contains("short") { |
| 579 | "https://dl.example/short".into() |
| 580 | } else if open_url.contains("grown") { |
| 581 | "https://dl.example/grown".into() |
| 582 | } else { |
| 583 | "https://dl.example/big".into() |
| 584 | }, |
| 585 | }) |
| 586 | } |
| 587 | |
| 588 | async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> { |
| 589 | self.record(format!("resolve item {drive_id}/{item_id}")); |
| 590 | Ok(SharedFile { |
| 591 | name: "big.bin".into(), |
| 592 | size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3, |
| 593 | download_url: "https://dl.example/fresh".into(), |
| 594 | }) |
| 595 | } |
| 596 | |
| 597 | async fn download_range( |
| 598 | &self, |
| 599 | download_url: &str, |
| 600 | start: u64, |
| 601 | end: Option<u64>, |
| 602 | ) -> Result<Vec<u8>> { |
| 603 | let total = 2 * graph::DOWNLOAD_CHUNK_BYTES + 3; |
| 604 | let shown_end = end.map_or(String::new(), |end| end.to_string()); |
| 605 | self.record(format!("range {download_url} {start}-{shown_end}")); |
| 606 | let length = match end { |
| 607 | _ if download_url.contains("short") => 1, |
| 608 | Some(end) => end - start + 1, |
| 609 | None if download_url.contains("grown") => total - start + 10, |
| 610 | None => total - start, |
| 611 | }; |
| 612 | Ok(vec![7; length as usize]) |
| 613 | } |
| 614 | |
| 615 | async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> { |
| 616 | self.record(format!("share {} {}", file.item_id, user_ids.join(","))); |
| 617 | Ok(()) |
| 618 | } |
| 619 | |
| 620 | async fn external_image(&self, url: &str) -> Result<Photo> { |
| 621 | self.external_requests.lock().unwrap().push(url.to_owned()); |
| 622 | self.hosted_content(url).await |
| 623 | } |
| 624 | |
| 625 | async fn hosted_content(&self, url: &str) -> Result<Photo> { |
| 626 | self.hosted_requests.lock().unwrap().push(url.to_owned()); |
| 627 | if url.contains("broken") { |
| 628 | return unsupported(); |
| 629 | } |
| 630 | let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); |
| 631 | bytes.extend([ |
| 632 | 0, 0, 0, 13, b'I', b'H', b'D', b'R', 0, 0, 0, 40, 0, 0, 0, 20, |
| 633 | ]); |
| 634 | Ok(Photo { |
| 635 | bytes, |
| 636 | content_type: String::new(), |
| 637 | }) |
| 638 | } |
| 639 | |
| 640 | async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> { |
| 641 | self.photo_requests.lock().unwrap().push(user_ids.to_vec()); |
| 642 | let photos = self.photos.lock().unwrap(); |
| 643 | Ok(user_ids |
| 644 | .iter() |
| 645 | .map(|user_id| { |
| 646 | Ok(photos.get(user_id).map(|bytes| Photo { |
| 647 | bytes: bytes.clone(), |
| 648 | content_type: "image/jpeg".to_owned(), |
| 649 | })) |
| 650 | }) |
| 651 | .collect()) |
| 652 | } |
| 653 | |
| 654 | async fn consumption_horizons( |
| 655 | &self, |
| 656 | _conversation_id: &str, |
| 657 | ) -> Result<Vec<chatsvc::MemberHorizon>> { |
| 658 | *self.horizon_calls.lock().unwrap() += 1; |
| 659 | Ok(self.horizons.lock().unwrap().clone()) |
| 660 | } |
| 661 | |
| 662 | async fn forward_messages( |
| 663 | &self, |
| 664 | source_conversation_id: &str, |
| 665 | target_conversation_id: &str, |
| 666 | message_ids: &[String], |
| 667 | comment_html: &str, |
| 668 | ) -> Result<chatsvc::ForwardResult> { |
| 669 | self.record(format!( |
| 670 | "forward {source_conversation_id} {target_conversation_id} {} {comment_html}", |
| 671 | message_ids.join(",") |
| 672 | )); |
| 673 | Ok(chatsvc::ForwardResult { |
| 674 | thread_id: target_conversation_id.to_owned(), |
| 675 | message_id: "99".to_owned(), |
| 676 | }) |
| 677 | } |
| 678 | |
| 679 | async fn set_saved( |
| 680 | &self, |
| 681 | conversation_id: &str, |
| 682 | root_id: &str, |
| 683 | message_id: &str, |
| 684 | saved: bool, |
| 685 | ) -> Result<()> { |
| 686 | self.record(format!( |
| 687 | "save {conversation_id} {root_id} {message_id} {saved}" |
| 688 | )); |
| 689 | Ok(()) |
| 690 | } |
| 691 | |
| 692 | async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> { |
| 693 | self.record(format!("pin {chat_id} {message_id}")); |
| 694 | Ok(()) |
| 695 | } |
| 696 | |
| 697 | async fn unpin_message( |
| 698 | &self, |
| 699 | chat_id: &str, |
| 700 | message_id: &str, |
| 701 | parent_id: Option<&str>, |
| 702 | ) -> Result<()> { |
| 703 | self.record(format!("unpin {chat_id} {message_id} {parent_id:?}")); |
| 704 | Ok(()) |
| 705 | } |
| 706 | |
| 707 | async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> { |
| 708 | *self.app_calls.lock().unwrap() += 1; |
| 709 | Ok(self.apps.lock().unwrap().clone()) |
| 710 | } |
| 711 | |
| 712 | async fn create_scheduled( |
| 713 | &self, |
| 714 | inner_thread_id: &str, |
| 715 | html: &str, |
| 716 | send_at: DateTime<Utc>, |
| 717 | display_name: &str, |
| 718 | ) -> Result<chatsvc::ScheduledDraft> { |
| 719 | self.scheduled.lock().unwrap().push(( |
| 720 | inner_thread_id.to_owned(), |
| 721 | html.to_owned(), |
| 722 | send_at, |
| 723 | display_name.to_owned(), |
| 724 | )); |
| 725 | Ok(chatsvc::ScheduledDraft { |
| 726 | id: "d1".to_owned(), |
| 727 | client_message_id: "1".to_owned(), |
| 728 | inner_thread_id: inner_thread_id.to_owned(), |
| 729 | send_at, |
| 730 | html: html.to_owned(), |
| 731 | delivery_state: None, |
| 732 | }) |
| 733 | } |
| 734 | |
| 735 | async fn invoke_card(&self, invoke: chatsvc::InvokeRequest) -> Result<chatsvc::InvokeResponse> { |
| 736 | self.invokes.lock().unwrap().push(invoke); |
| 737 | Ok(self |
| 738 | .invoke_answer |
| 739 | .lock() |
| 740 | .unwrap() |
| 741 | .clone() |
| 742 | .unwrap_or(chatsvc::InvokeResponse::Empty)) |
| 743 | } |
| 744 | |
| 745 | async fn message_links( |
| 746 | &self, |
| 747 | conversation: &chatsvc::ConversationRef, |
| 748 | _page_size: usize, |
| 749 | ) -> Result<Vec<chatsvc::MessageLinks>> { |
| 750 | self.link_page_calls |
| 751 | .lock() |
| 752 | .unwrap() |
| 753 | .push(conversation.conversation_id()); |
| 754 | Ok(self.link_pages.lock().unwrap().clone()) |
| 755 | } |
| 756 | |
| 757 | async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> { |
| 758 | self.links_put |
| 759 | .lock() |
| 760 | .unwrap() |
| 761 | .push((describe(target), links_json.to_owned())); |
| 762 | Ok(()) |
| 763 | } |
| 764 | |
| 765 | async fn link_info(&self, url: &str) -> Result<chatsvc::LinkInfo> { |
| 766 | *self.link_info_calls.lock().unwrap() += 1; |
| 767 | Ok(chatsvc::LinkInfo { |
| 768 | url: url.to_owned(), |
| 769 | title: Some("Example".into()), |
| 770 | ..chatsvc::LinkInfo::default() |
| 771 | }) |
| 772 | } |
| 773 | |
| 774 | async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> { |
| 775 | let answers = self.presence_answers.lock().unwrap(); |
| 776 | Ok(answers |
| 777 | .iter() |
| 778 | .filter(|presence| user_ids.contains(&presence.user_id)) |
| 779 | .cloned() |
| 780 | .collect()) |
| 781 | } |
| 782 | |
| 783 | async fn subscribe_presence( |
| 784 | &self, |
| 785 | endpoint_id: &str, |
| 786 | _trouter_uri: &str, |
| 787 | user_ids: &[String], |
| 788 | purge: bool, |
| 789 | ) -> Result<()> { |
| 790 | self.presence_subscriptions.lock().unwrap().push(( |
| 791 | endpoint_id.to_owned(), |
| 792 | user_ids.to_vec(), |
| 793 | purge, |
| 794 | )); |
| 795 | Ok(()) |
| 796 | } |
| 797 | |
| 798 | async fn own_status(&self, _user_id: &str) -> Result<chatsvc::PresenceStatus> { |
| 799 | Ok(self.own_status_answer.lock().unwrap().clone()) |
| 800 | } |
| 801 | |
| 802 | async fn set_availability(&self, forced: Option<&chatsvc::ForcedAvailability>) -> Result<()> { |
| 803 | self.availability_puts.lock().unwrap().push(forced.copied()); |
| 804 | Ok(()) |
| 805 | } |
| 806 | |
| 807 | async fn set_status_note(&self, note: Option<&chatsvc::StatusNote>) -> Result<()> { |
| 808 | self.note_puts.lock().unwrap().push(note.cloned()); |
| 809 | Ok(()) |
| 810 | } |
| 811 | |
| 812 | async fn search_people(&self, query: &str) -> Result<Vec<User>> { |
| 813 | self.record(format!("search {query}")); |
| 814 | let configured = self.directory_users.lock().unwrap().clone(); |
| 815 | if !configured.is_empty() { |
| 816 | return Ok(configured); |
| 817 | } |
| 818 | Ok(vec![ |
| 819 | serde_json::from_value(json!({"id": "user-ada", "displayName": "Ada Example"})) |
| 820 | .unwrap(), |
| 821 | ]) |
| 822 | } |
| 823 | } |
| 824 | |
| 825 | fn engine_with(fake: &Arc<Fake>, config: SyncConfig) -> SyncEngine<Handle> { |
| 826 | SyncEngine::with_config( |
| 827 | Handle(fake.clone()), |
| 828 | Arc::new(Store::open_in_memory().unwrap()), |
| 829 | config, |
| 830 | ) |
| 831 | } |
| 832 | |
| 833 | fn small_pages() -> SyncConfig { |
| 834 | SyncConfig { |
| 835 | page_size: 10, |
| 836 | open_limit: 10, |
| 837 | ..SyncConfig::default() |
| 838 | } |
| 839 | } |
| 840 | |
| 841 | async fn chat_engine(fake: &Arc<Fake>, config: SyncConfig) -> SyncEngine<Handle> { |
| 842 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 843 | let engine = engine_with(fake, config); |
| 844 | engine.refresh_sidebar().await.unwrap(); |
| 845 | engine |
| 846 | } |
| 847 | |
| 848 | #[tokio::test] |
| 849 | async fn refresh_sidebar_fills_chats_teams_and_channels() { |
| 850 | let fake = Arc::new(Fake::default()); |
| 851 | *fake.chats.lock().unwrap() = vec![ |
| 852 | chat("19:read@thread.v2", Some("Read"), 10, 10, "user-ada", false), |
| 853 | chat("19:unread@thread.v2", None, 30, 10, "user-ada", false), |
| 854 | chat("19:mine@thread.v2", Some("Mine"), 20, 5, ME, false), |
| 855 | chat( |
| 856 | "19:hidden@thread.v2", |
| 857 | Some("Hidden"), |
| 858 | 40, |
| 859 | 1, |
| 860 | "user-ada", |
| 861 | true, |
| 862 | ), |
| 863 | ]; |
| 864 | *fake.teams.lock().unwrap() = |
| 865 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 866 | let engine = engine_with(&fake, SyncConfig::default()); |
| 867 | let mut events = engine.subscribe(); |
| 868 | |
| 869 | let summary = engine.refresh_sidebar().await.unwrap(); |
| 870 | assert_eq!( |
| 871 | ( |
| 872 | summary.chats, |
| 873 | summary.teams, |
| 874 | summary.channels, |
| 875 | summary.failed_teams |
| 876 | ), |
| 877 | (4, 1, 1, 0) |
| 878 | ); |
| 879 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 880 | |
| 881 | let sidebar = engine.sidebar().unwrap(); |
| 882 | let order: Vec<(&str, bool)> = sidebar |
| 883 | .chats |
| 884 | .iter() |
| 885 | .map(|chat| (chat.title.as_str(), chat.unread)) |
| 886 | .collect(); |
| 887 | assert_eq!( |
| 888 | order, |
| 889 | [("Ada Example", true), ("Mine", false), ("Read", false)] |
| 890 | ); |
| 891 | assert_eq!(sidebar.chats[0].kind, "oneOnOne"); |
| 892 | assert_eq!(sidebar.chats[1].member_summary, "Ada Example"); |
| 893 | assert_eq!(sidebar.teams[0].channels[0].name, "General"); |
| 894 | } |
| 895 | |
| 896 | #[tokio::test] |
| 897 | async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails() { |
| 898 | let fake = Arc::new(Fake::default()); |
| 899 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 900 | fake.muted_states |
| 901 | .lock() |
| 902 | .unwrap() |
| 903 | .push((CHAT.to_owned(), true)); |
| 904 | let engine = engine_with(&fake, SyncConfig::default()); |
| 905 | engine.refresh_sidebar().await.unwrap(); |
| 906 | assert!(engine.sidebar().unwrap().chats[0].muted); |
| 907 | |
| 908 | *fake.muted_fails.lock().unwrap() = true; |
| 909 | fake.muted_states.lock().unwrap().clear(); |
| 910 | let mut events = engine.subscribe(); |
| 911 | engine.refresh_sidebar().await.unwrap(); |
| 912 | assert!(engine.sidebar().unwrap().chats[0].muted); |
| 913 | let mut reported = false; |
| 914 | while let Ok(event) = events.try_recv() { |
| 915 | reported |= matches!(event, CoreEvent::Error { .. }); |
| 916 | } |
| 917 | assert!(reported); |
| 918 | |
| 919 | *fake.muted_fails.lock().unwrap() = false; |
| 920 | engine.refresh_sidebar().await.unwrap(); |
| 921 | assert!(engine.sidebar().unwrap().chats[0].muted); |
| 922 | |
| 923 | fake.muted_states |
| 924 | .lock() |
| 925 | .unwrap() |
| 926 | .push((CHAT.to_owned(), false)); |
| 927 | engine.refresh_sidebar().await.unwrap(); |
| 928 | assert!(!engine.sidebar().unwrap().chats[0].muted); |
| 929 | } |
| 930 | |
| 931 | #[tokio::test] |
| 932 | async fn chat_state_actions_call_remote_and_update_the_store() { |
| 933 | let fake = Arc::new(Fake::default()); |
| 934 | let engine = chat_engine(&fake, small_pages()).await; |
| 935 | let mut events = engine.subscribe(); |
| 936 | |
| 937 | engine.mark_unread(CHAT).await.unwrap(); |
| 938 | let last_message_millis = (base() + Duration::minutes(5)).timestamp_millis(); |
| 939 | assert_eq!( |
| 940 | fake.calls().last().unwrap(), |
| 941 | &format!( |
| 942 | "mark_unread {CHAT} {ME} tenant-1 {}", |
| 943 | last_message_millis - 1 |
| 944 | ) |
| 945 | ); |
| 946 | let unread = engine.sidebar().unwrap().chats[0].clone(); |
| 947 | assert!(unread.unread); |
| 948 | assert_eq!( |
| 949 | unread.last_read_at.unwrap().timestamp_millis(), |
| 950 | last_message_millis - 1 |
| 951 | ); |
| 952 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 953 | |
| 954 | engine.set_chat_muted(CHAT, true).await.unwrap(); |
| 955 | assert_eq!(fake.calls().last().unwrap(), &format!("mute {CHAT} true")); |
| 956 | assert!(engine.sidebar().unwrap().chats[0].muted); |
| 957 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 958 | engine.set_chat_muted(CHAT, false).await.unwrap(); |
| 959 | assert!(!engine.sidebar().unwrap().chats[0].muted); |
| 960 | } |
| 961 | |
| 962 | #[tokio::test] |
| 963 | async fn hide_removes_the_chat_and_unhide_brings_it_back() { |
| 964 | let fake = Arc::new(Fake::default()); |
| 965 | let engine = chat_engine(&fake, small_pages()).await; |
| 966 | let mut events = engine.subscribe(); |
| 967 | |
| 968 | engine.hide_chat(CHAT).await.unwrap(); |
| 969 | assert_eq!( |
| 970 | fake.calls().last().unwrap(), |
| 971 | &format!("hide {CHAT} {ME} tenant-1") |
| 972 | ); |
| 973 | assert!(engine.sidebar().unwrap().chats.is_empty()); |
| 974 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 975 | |
| 976 | engine.unhide_chat(CHAT).await.unwrap(); |
| 977 | assert_eq!( |
| 978 | fake.calls().last().unwrap(), |
| 979 | &format!("unhide {CHAT} {ME} tenant-1") |
| 980 | ); |
| 981 | assert_eq!(engine.sidebar().unwrap().chats.len(), 1); |
| 982 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 983 | } |
| 984 | |
| 985 | #[tokio::test] |
| 986 | async fn leave_removes_the_chat() { |
| 987 | let fake = Arc::new(Fake::default()); |
| 988 | let engine = chat_engine(&fake, small_pages()).await; |
| 989 | let mut events = engine.subscribe(); |
| 990 | |
| 991 | engine.leave_chat(CHAT).await.unwrap(); |
| 992 | assert_eq!(fake.calls().last().unwrap(), &format!("leave {CHAT} {ME}")); |
| 993 | assert!(engine.sidebar().unwrap().chats.is_empty()); |
| 994 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 995 | } |
| 996 | |
| 997 | #[tokio::test] |
| 998 | async fn failing_channel_listing_is_reported_not_fatal() { |
| 999 | let fake = Arc::new(Fake::default()); |
| 1000 | *fake.teams.lock().unwrap() = vec![ |
| 1001 | serde_json::from_value(json!({"id": "team-ok", "displayName": "Fine"})).unwrap(), |
| 1002 | serde_json::from_value(json!({"id": "team-bad", "displayName": "Broken"})).unwrap(), |
| 1003 | ]; |
| 1004 | *fake.failing_team.lock().unwrap() = Some("team-bad".to_owned()); |
| 1005 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1006 | let mut events = engine.subscribe(); |
| 1007 | let summary = engine.refresh_sidebar().await.unwrap(); |
| 1008 | assert_eq!( |
| 1009 | (summary.teams, summary.channels, summary.failed_teams), |
| 1010 | (2, 1, 1) |
| 1011 | ); |
| 1012 | assert!(matches!( |
| 1013 | events.try_recv().unwrap(), |
| 1014 | CoreEvent::Error { .. } |
| 1015 | )); |
| 1016 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 1017 | } |
| 1018 | |
| 1019 | #[tokio::test] |
| 1020 | async fn cold_open_then_delta() { |
| 1021 | let fake = Arc::new(Fake::default()); |
| 1022 | fake.set_chat_messages(numbered(25)); |
| 1023 | let engine = chat_engine(&fake, small_pages()).await; |
| 1024 | let mut events = engine.subscribe(); |
| 1025 | |
| 1026 | assert!(engine.open_conversation(CHAT).unwrap().is_empty()); |
| 1027 | let first = engine.fetch_newer(CHAT).await.unwrap(); |
| 1028 | assert_eq!(first.added.len(), 10); |
| 1029 | assert!(first.updated.is_empty()); |
| 1030 | assert_eq!( |
| 1031 | events.try_recv().unwrap(), |
| 1032 | CoreEvent::MessagesChanged { |
| 1033 | conversation_id: CHAT.to_owned() |
| 1034 | } |
| 1035 | ); |
| 1036 | |
| 1037 | let cached = engine.open_conversation(CHAT).unwrap(); |
| 1038 | assert_eq!(cached.len(), 10); |
| 1039 | assert_eq!(cached.first().unwrap().message_id, "m0016"); |
| 1040 | assert_eq!(cached.last().unwrap().message_id, "m0025"); |
| 1041 | *fake.chat_calls.lock().unwrap() = 0; |
| 1042 | |
| 1043 | let mut all = numbered(25); |
| 1044 | all.extend((26..=28).map(|index| message(index, i64::from(index), "<p>fresh</p>"))); |
| 1045 | all[24] = message(25, 25, "<p>edited</p>"); |
| 1046 | fake.set_chat_messages(all); |
| 1047 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 1048 | let added: Vec<&str> = delta |
| 1049 | .added |
| 1050 | .iter() |
| 1051 | .map(|record| record.message_id.as_str()) |
| 1052 | .collect(); |
| 1053 | assert_eq!(added, ["m0026", "m0027", "m0028"]); |
| 1054 | assert_eq!(delta.updated.len(), 1); |
| 1055 | assert_eq!(delta.updated[0].body_html, "<p>edited</p>"); |
| 1056 | assert_eq!(*fake.chat_calls.lock().unwrap(), 1); |
| 1057 | |
| 1058 | while events.try_recv().is_ok() {} |
| 1059 | let unchanged = engine.fetch_newer(CHAT).await.unwrap(); |
| 1060 | assert!(unchanged.is_empty()); |
| 1061 | assert!(events.try_recv().is_err()); |
| 1062 | } |
| 1063 | |
| 1064 | #[tokio::test] |
| 1065 | async fn catch_up_walks_several_pages_until_the_known_message() { |
| 1066 | let fake = Arc::new(Fake::default()); |
| 1067 | fake.set_chat_messages(numbered(5)); |
| 1068 | let engine = chat_engine(&fake, small_pages()).await; |
| 1069 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1070 | |
| 1071 | fake.set_chat_messages(numbered(35)); |
| 1072 | *fake.chat_calls.lock().unwrap() = 0; |
| 1073 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 1074 | assert_eq!(delta.added.len(), 30); |
| 1075 | assert_eq!(*fake.chat_calls.lock().unwrap(), 4); |
| 1076 | assert_eq!(engine.store().message_count(CHAT).unwrap(), 35); |
| 1077 | } |
| 1078 | |
| 1079 | #[tokio::test] |
| 1080 | async fn load_older_pages_back_to_the_start() { |
| 1081 | let fake = Arc::new(Fake::default()); |
| 1082 | fake.set_chat_messages(numbered(25)); |
| 1083 | let engine = chat_engine(&fake, small_pages()).await; |
| 1084 | |
| 1085 | let older = engine.load_older(CHAT).await.unwrap(); |
| 1086 | assert_eq!(older.len(), 10); |
| 1087 | assert_eq!(older[0].message_id, "m0006"); |
| 1088 | |
| 1089 | let older = engine.load_older(CHAT).await.unwrap(); |
| 1090 | assert_eq!(older.first().unwrap().message_id, "m0001"); |
| 1091 | assert_eq!(older.len(), 5); |
| 1092 | assert!(!engine.store().sync_state(CHAT).unwrap().unwrap().has_more); |
| 1093 | assert_eq!(engine.store().message_count(CHAT).unwrap(), 25); |
| 1094 | |
| 1095 | *fake.chat_calls.lock().unwrap() = 0; |
| 1096 | assert!(engine.load_older(CHAT).await.unwrap().is_empty()); |
| 1097 | assert_eq!(*fake.chat_calls.lock().unwrap(), 0); |
| 1098 | } |
| 1099 | |
| 1100 | #[tokio::test] |
| 1101 | async fn system_messages_are_not_cached() { |
| 1102 | let fake = Arc::new(Fake::default()); |
| 1103 | let system: Message = serde_json::from_value(json!({ |
| 1104 | "id": "sys", "messageType": "systemEventMessage", |
| 1105 | "createdDateTime": (base() + Duration::minutes(50)).to_rfc3339(), |
| 1106 | "body": {"contentType": "html", "content": "<systemEventMessage/>"} |
| 1107 | })) |
| 1108 | .unwrap(); |
| 1109 | fake.set_chat_messages(vec![message(1, 1, "<p>a</p>"), system]); |
| 1110 | let engine = chat_engine(&fake, small_pages()).await; |
| 1111 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 1112 | assert_eq!(delta.added.len(), 1); |
| 1113 | } |
| 1114 | |
| 1115 | #[tokio::test] |
| 1116 | async fn deleted_and_text_messages_are_normalised() { |
| 1117 | let fake = Arc::new(Fake::default()); |
| 1118 | let deleted: Message = serde_json::from_value(json!({ |
| 1119 | "id": "gone", "messageType": "message", |
| 1120 | "createdDateTime": (base() + Duration::minutes(1)).to_rfc3339(), |
| 1121 | "deletedDateTime": (base() + Duration::minutes(2)).to_rfc3339(), |
| 1122 | "body": {"contentType": "html", "content": "<p>secret</p>"} |
| 1123 | })) |
| 1124 | .unwrap(); |
| 1125 | let text: Message = serde_json::from_value(json!({ |
| 1126 | "id": "plain", "messageType": "message", |
| 1127 | "createdDateTime": (base() + Duration::minutes(3)).to_rfc3339(), |
| 1128 | "from": {"application": {"id": "bot", "displayName": "Build Bot"}}, |
| 1129 | "body": {"contentType": "text", "content": " a < b\nnext "} |
| 1130 | })) |
| 1131 | .unwrap(); |
| 1132 | fake.set_chat_messages(vec![deleted, text]); |
| 1133 | let engine = chat_engine(&fake, small_pages()).await; |
| 1134 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1135 | let cached = engine.open_conversation(CHAT).unwrap(); |
| 1136 | assert!(cached[0].deleted); |
| 1137 | assert_eq!(cached[0].body_html, ""); |
| 1138 | assert_eq!(cached[1].body_html, "a < b<br>next"); |
| 1139 | assert_eq!(cached[1].sender_name.as_deref(), Some("Build Bot")); |
| 1140 | assert_eq!(cached[1].sender_id, None); |
| 1141 | } |
| 1142 | |
| 1143 | #[tokio::test] |
| 1144 | async fn send_message_converts_markdown_and_caches_the_answer() { |
| 1145 | let fake = Arc::new(Fake::default()); |
| 1146 | fake.set_chat_messages(numbered(3)); |
| 1147 | let engine = chat_engine(&fake, small_pages()).await; |
| 1148 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1149 | let mut events = engine.subscribe(); |
| 1150 | |
| 1151 | let record = engine |
| 1152 | .send_message(CHAT, "hi **there** <x>", None) |
| 1153 | .await |
| 1154 | .unwrap(); |
| 1155 | assert_eq!( |
| 1156 | fake.sent.lock().unwrap().as_slice(), |
| 1157 | ["hi <b>there</b> <x>"] |
| 1158 | ); |
| 1159 | assert_eq!(record.message_id, "m9000"); |
| 1160 | assert_eq!(engine.store().message_count(CHAT).unwrap(), 4); |
| 1161 | assert_eq!( |
| 1162 | events.try_recv().unwrap(), |
| 1163 | CoreEvent::MessagesChanged { |
| 1164 | conversation_id: CHAT.to_owned() |
| 1165 | } |
| 1166 | ); |
| 1167 | assert!( |
| 1168 | engine |
| 1169 | .store() |
| 1170 | .sync_state(CHAT) |
| 1171 | .unwrap() |
| 1172 | .unwrap() |
| 1173 | .newest_seen |
| 1174 | .unwrap() |
| 1175 | >= record.created_at |
| 1176 | ); |
| 1177 | } |
| 1178 | |
| 1179 | #[tokio::test] |
| 1180 | async fn unknown_conversation_is_an_error() { |
| 1181 | let fake = Arc::new(Fake::default()); |
| 1182 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1183 | assert!(matches!( |
| 1184 | engine.fetch_newer("nope").await, |
| 1185 | Err(Error::UnknownConversation(_)) |
| 1186 | )); |
| 1187 | } |
| 1188 | |
| 1189 | fn thread(id: u32, minute: i64, reply_count: u32) -> Message { |
| 1190 | let mut value = json!({ |
| 1191 | "id": format!("m{id:04}"), |
| 1192 | "messageType": "message", |
| 1193 | "createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(), |
| 1194 | "body": {"contentType": "html", "content": "<p>root</p>"}, |
| 1195 | "replies": (0..reply_count).map(|reply| json!({ |
| 1196 | "id": format!("r{id:04}-{reply}"), |
| 1197 | "messageType": "message", |
| 1198 | "replyToId": format!("m{id:04}"), |
| 1199 | "createdDateTime": (base() + Duration::minutes(minute + 1 + i64::from(reply))).to_rfc3339(), |
| 1200 | "body": {"contentType": "html", "content": "<p>reply</p>"} |
| 1201 | })).collect::<Vec<_>>() |
| 1202 | }); |
| 1203 | value["from"] = json!({"user": {"id": "user-ada", "displayName": "Ada Example"}}); |
| 1204 | serde_json::from_value(value).unwrap() |
| 1205 | } |
| 1206 | |
| 1207 | #[tokio::test] |
| 1208 | async fn channel_threads_are_flattened_and_paged_by_cursor() { |
| 1209 | let fake = Arc::new(Fake::default()); |
| 1210 | *fake.teams.lock().unwrap() = |
| 1211 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 1212 | *fake.channel_pages.lock().unwrap() = vec![ |
| 1213 | vec![thread(30, 30, 2), thread(20, 20, 0)], |
| 1214 | vec![thread(10, 10, 1)], |
| 1215 | ]; |
| 1216 | let engine = engine_with(&fake, small_pages()); |
| 1217 | engine.refresh_sidebar().await.unwrap(); |
| 1218 | |
| 1219 | let delta = engine.fetch_newer(CHANNEL).await.unwrap(); |
| 1220 | assert_eq!(delta.added.len(), 4); |
| 1221 | let reply = delta |
| 1222 | .added |
| 1223 | .iter() |
| 1224 | .find(|record| record.message_id == "r0030-1") |
| 1225 | .unwrap(); |
| 1226 | assert_eq!(reply.reply_to_id.as_deref(), Some("m0030")); |
| 1227 | let state = engine.store().sync_state(CHANNEL).unwrap().unwrap(); |
| 1228 | assert_eq!(state.older_cursor.as_deref(), Some("page:1")); |
| 1229 | assert!(state.has_more); |
| 1230 | |
| 1231 | let older = engine.load_older(CHANNEL).await.unwrap(); |
| 1232 | assert_eq!(older.len(), 2); |
| 1233 | assert!( |
| 1234 | !engine |
| 1235 | .store() |
| 1236 | .sync_state(CHANNEL) |
| 1237 | .unwrap() |
| 1238 | .unwrap() |
| 1239 | .has_more |
| 1240 | ); |
| 1241 | assert!(engine.load_older(CHANNEL).await.unwrap().is_empty()); |
| 1242 | assert_eq!(engine.store().message_count(CHANNEL).unwrap(), 6); |
| 1243 | |
| 1244 | assert!(matches!( |
| 1245 | engine.send_message(CHANNEL, "x", None).await, |
| 1246 | Err(Error::Unsupported(_)) |
| 1247 | )); |
| 1248 | } |
| 1249 | |
| 1250 | fn many_chats(count: i64) -> Vec<Chat> { |
| 1251 | (1..=count) |
| 1252 | .map(|index| { |
| 1253 | chat( |
| 1254 | &format!("19:c{index:03}@thread.v2"), |
| 1255 | Some("Topic"), |
| 1256 | index, |
| 1257 | index, |
| 1258 | "user-ada", |
| 1259 | false, |
| 1260 | ) |
| 1261 | }) |
| 1262 | .collect() |
| 1263 | } |
| 1264 | |
| 1265 | #[tokio::test] |
| 1266 | async fn warm_refresh_stops_after_the_first_unchanged_page() { |
| 1267 | let fake = Arc::new(Fake::default()); |
| 1268 | *fake.chats.lock().unwrap() = many_chats(120); |
| 1269 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1270 | let cold = engine.refresh_sidebar().await.unwrap(); |
| 1271 | assert!(cold.full_chat_refresh); |
| 1272 | assert_eq!(cold.chat_pages, 5); |
| 1273 | assert_eq!(engine.store().chat_count().unwrap(), 120); |
| 1274 | |
| 1275 | *fake.chat_page_calls.lock().unwrap() = 0; |
| 1276 | *fake.team_calls.lock().unwrap() = 0; |
| 1277 | let warm = engine.refresh_sidebar().await.unwrap(); |
| 1278 | assert!(!warm.full_chat_refresh); |
| 1279 | assert_eq!(warm.chat_pages, 1); |
| 1280 | assert_eq!(*fake.chat_page_calls.lock().unwrap(), 1); |
| 1281 | assert_eq!(*fake.team_calls.lock().unwrap(), 0); |
| 1282 | assert!(!warm.teams_refreshed); |
| 1283 | } |
| 1284 | |
| 1285 | #[tokio::test] |
| 1286 | async fn warm_refresh_walks_on_while_pages_hold_new_activity() { |
| 1287 | let fake = Arc::new(Fake::default()); |
| 1288 | *fake.chats.lock().unwrap() = many_chats(120); |
| 1289 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1290 | engine.refresh_sidebar().await.unwrap(); |
| 1291 | |
| 1292 | let mut chats = many_chats(120); |
| 1293 | for chat in chats.iter_mut().take(30) { |
| 1294 | *chat = self::chat(&chat.id.clone(), Some("Topic"), 500, 1, "user-ada", false); |
| 1295 | } |
| 1296 | *fake.chats.lock().unwrap() = chats; |
| 1297 | *fake.chat_page_calls.lock().unwrap() = 0; |
| 1298 | let warm = engine.refresh_sidebar().await.unwrap(); |
| 1299 | assert_eq!(warm.chat_pages, 3); |
| 1300 | } |
| 1301 | |
| 1302 | #[tokio::test] |
| 1303 | async fn full_refresh_prunes_chats_the_user_left() { |
| 1304 | let fake = Arc::new(Fake::default()); |
| 1305 | *fake.chats.lock().unwrap() = many_chats(5); |
| 1306 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1307 | engine.refresh_sidebar().await.unwrap(); |
| 1308 | assert_eq!(engine.store().chat_count().unwrap(), 5); |
| 1309 | |
| 1310 | *fake.chats.lock().unwrap() = many_chats(3); |
| 1311 | engine.refresh_sidebar_full().await.unwrap(); |
| 1312 | assert_eq!(engine.store().chat_count().unwrap(), 3); |
| 1313 | } |
| 1314 | |
| 1315 | #[tokio::test] |
| 1316 | async fn teams_refresh_is_skipped_inside_the_interval() { |
| 1317 | let fake = Arc::new(Fake::default()); |
| 1318 | *fake.teams.lock().unwrap() = |
| 1319 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 1320 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1321 | assert!(engine.refresh_sidebar().await.unwrap().teams_refreshed); |
| 1322 | assert!(!engine.refresh_sidebar().await.unwrap().teams_refreshed); |
| 1323 | assert!(engine.refresh_sidebar_full().await.unwrap().teams_refreshed); |
| 1324 | assert_eq!(*fake.team_calls.lock().unwrap(), 2); |
| 1325 | } |
| 1326 | |
| 1327 | async fn channel_engine(fake: &Arc<Fake>) -> SyncEngine<Handle> { |
| 1328 | *fake.teams.lock().unwrap() = |
| 1329 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 1330 | *fake.channel_pages.lock().unwrap() = vec![vec![thread(30, 30, 1)]]; |
| 1331 | let engine = engine_with(fake, small_pages()); |
| 1332 | engine.refresh_sidebar().await.unwrap(); |
| 1333 | engine |
| 1334 | } |
| 1335 | |
| 1336 | #[tokio::test] |
| 1337 | async fn refreshing_a_thread_stores_every_reply_of_that_root() { |
| 1338 | let fake = Arc::new(Fake::default()); |
| 1339 | let engine = channel_engine(&fake).await; |
| 1340 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 1341 | let root_id = engine.open_conversation(CHANNEL).unwrap()[0] |
| 1342 | .message_id |
| 1343 | .clone(); |
| 1344 | let reply = |id: u32, minute: i64, root: &str| -> Message { |
| 1345 | let mut reply = message(id, minute, &format!("<p>reply {id}</p>")); |
| 1346 | reply.reply_to_id = Some(root.to_owned()); |
| 1347 | reply |
| 1348 | }; |
| 1349 | *fake.thread_replies.lock().unwrap() = vec![ |
| 1350 | reply(7001, 90, &root_id), |
| 1351 | reply(7002, 91, &root_id), |
| 1352 | reply(7003, 92, "other-root"), |
| 1353 | ]; |
| 1354 | let delta = engine.refresh_thread(CHANNEL, &root_id).await.unwrap(); |
| 1355 | assert_eq!(delta.added.len(), 2); |
| 1356 | let thread = engine.store().thread_messages(CHANNEL, &root_id).unwrap(); |
| 1357 | assert_eq!(thread.len(), 4); |
| 1358 | } |
| 1359 | |
| 1360 | #[tokio::test] |
| 1361 | async fn channel_delta_picks_up_new_and_edited_posts_and_stores_the_link() { |
| 1362 | let fake = Arc::new(Fake::default()); |
| 1363 | let engine = channel_engine(&fake).await; |
| 1364 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 1365 | let state = engine.store().sync_state(CHANNEL).unwrap().unwrap(); |
| 1366 | assert_eq!(state.delta_link.as_deref(), Some("delta:1")); |
| 1367 | |
| 1368 | let mut edited = thread(30, 30, 0); |
| 1369 | edited.body = |
| 1370 | serde_json::from_value(json!({"contentType": "html", "content": "<p>edited root</p>"})) |
| 1371 | .unwrap(); |
| 1372 | *fake.delta_items.lock().unwrap() = vec![edited, thread(40, 40, 0)]; |
| 1373 | let delta = engine.fetch_newer(CHANNEL).await.unwrap(); |
| 1374 | assert_eq!( |
| 1375 | delta |
| 1376 | .added |
| 1377 | .iter() |
| 1378 | .map(|record| record.message_id.as_str()) |
| 1379 | .collect::<Vec<_>>(), |
| 1380 | ["m0040"] |
| 1381 | ); |
| 1382 | assert_eq!(delta.updated.len(), 1); |
| 1383 | assert_eq!(delta.updated[0].body_html, "<p>edited root</p>"); |
| 1384 | assert!( |
| 1385 | fake.calls() |
| 1386 | .iter() |
| 1387 | .any(|call| call == "channel_delta_at delta:1") |
| 1388 | ); |
| 1389 | assert_eq!( |
| 1390 | engine |
| 1391 | .store() |
| 1392 | .sync_state(CHANNEL) |
| 1393 | .unwrap() |
| 1394 | .unwrap() |
| 1395 | .delta_link |
| 1396 | .as_deref(), |
| 1397 | Some("delta:2") |
| 1398 | ); |
| 1399 | } |
| 1400 | |
| 1401 | #[tokio::test] |
| 1402 | async fn channel_delta_failure_falls_back_to_the_first_page() { |
| 1403 | let fake = Arc::new(Fake::default()); |
| 1404 | let engine = channel_engine(&fake).await; |
| 1405 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 1406 | |
| 1407 | *fake.delta_fails.lock().unwrap() = true; |
| 1408 | *fake.channel_pages.lock().unwrap() = vec![vec![thread(50, 50, 0), thread(30, 30, 1)]]; |
| 1409 | let delta = engine.fetch_newer(CHANNEL).await.unwrap(); |
| 1410 | assert_eq!( |
| 1411 | delta |
| 1412 | .added |
| 1413 | .iter() |
| 1414 | .map(|record| record.message_id.as_str()) |
| 1415 | .collect::<Vec<_>>(), |
| 1416 | ["m0050"] |
| 1417 | ); |
| 1418 | assert_eq!( |
| 1419 | engine |
| 1420 | .store() |
| 1421 | .sync_state(CHANNEL) |
| 1422 | .unwrap() |
| 1423 | .unwrap() |
| 1424 | .delta_link, |
| 1425 | None |
| 1426 | ); |
| 1427 | } |
| 1428 | |
| 1429 | #[tokio::test] |
| 1430 | async fn channel_sends_post_and_reply_through_graph() { |
| 1431 | let fake = Arc::new(Fake::default()); |
| 1432 | let engine = channel_engine(&fake).await; |
| 1433 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 1434 | |
| 1435 | engine |
| 1436 | .post_to_channel(CHANNEL, "hello", Some("Topic")) |
| 1437 | .await |
| 1438 | .unwrap(); |
| 1439 | let reply = engine |
| 1440 | .send_message(CHANNEL, "answer", Some("m0030")) |
| 1441 | .await |
| 1442 | .unwrap(); |
| 1443 | assert_eq!(reply.message_id, "m9002"); |
| 1444 | let sends: Vec<String> = fake |
| 1445 | .calls() |
| 1446 | .into_iter() |
| 1447 | .filter(|call| !call.starts_with("channel_delta")) |
| 1448 | .collect(); |
| 1449 | assert_eq!(sends, ["post subject=Some(\"Topic\")", "reply to m0030"]); |
| 1450 | assert!(engine.post_to_channel(CHAT, "x", None).await.is_err()); |
| 1451 | } |
| 1452 | |
| 1453 | #[tokio::test] |
| 1454 | async fn chat_upload_goes_to_chat_files_and_is_shared_with_the_other_members() { |
| 1455 | let fake = Arc::new(Fake::default()); |
| 1456 | let engine = chat_engine(&fake, small_pages()).await; |
| 1457 | let steps = Arc::new(Mutex::new(Vec::new())); |
| 1458 | let seen = steps.clone(); |
| 1459 | |
| 1460 | let reference = engine |
| 1461 | .upload_attachment(CHAT, "plan.pdf", &[1, 2, 3], move |percent| { |
| 1462 | seen.lock().unwrap().push(percent) |
| 1463 | }) |
| 1464 | .await |
| 1465 | .unwrap(); |
| 1466 | |
| 1467 | assert_eq!( |
| 1468 | fake.calls(), |
| 1469 | ["upload chat-files plan.pdf 3", "share item-1 user-ada"] |
| 1470 | ); |
| 1471 | assert_eq!(*steps.lock().unwrap(), [50, 100]); |
| 1472 | assert_eq!(reference.attachment_id, "GUID-1"); |
| 1473 | assert_eq!(reference.content_url, "https://files.example/dav"); |
| 1474 | assert_eq!(reference.name, "plan.pdf"); |
| 1475 | } |
| 1476 | |
| 1477 | #[tokio::test] |
| 1478 | async fn channel_upload_uses_the_cached_files_folder_and_shares_nothing() { |
| 1479 | let fake = Arc::new(Fake::default()); |
| 1480 | let engine = channel_engine(&fake).await; |
| 1481 | |
| 1482 | engine |
| 1483 | .upload_attachment(CHANNEL, "a.pdf", &[1], |_| {}) |
| 1484 | .await |
| 1485 | .unwrap(); |
| 1486 | engine |
| 1487 | .upload_attachment(CHANNEL, "b.pdf", &[1, 2], |_| {}) |
| 1488 | .await |
| 1489 | .unwrap(); |
| 1490 | |
| 1491 | assert_eq!(*fake.folder_requests.lock().unwrap(), 1); |
| 1492 | let uploads: Vec<String> = fake |
| 1493 | .calls() |
| 1494 | .into_iter() |
| 1495 | .filter(|call| call.starts_with("upload") || call.starts_with("share")) |
| 1496 | .collect(); |
| 1497 | assert_eq!( |
| 1498 | uploads, |
| 1499 | [ |
| 1500 | "upload drive-1/folder-1 a.pdf 1", |
| 1501 | "upload drive-1/folder-1 b.pdf 2" |
| 1502 | ] |
| 1503 | ); |
| 1504 | } |
| 1505 | |
| 1506 | fn uploaded() -> UploadedFile { |
| 1507 | UploadedFile { |
| 1508 | drive_id: "drive-1".into(), |
| 1509 | item_id: "item-1".into(), |
| 1510 | name: "a.pdf".into(), |
| 1511 | web_url: "https://files.example/web".into(), |
| 1512 | web_dav_url: None, |
| 1513 | etag: "\"{GUID-1},2\"".into(), |
| 1514 | } |
| 1515 | } |
| 1516 | |
| 1517 | #[tokio::test] |
| 1518 | async fn sharing_fails_loudly_when_the_chat_members_are_unknown() { |
| 1519 | let fake = Arc::new(Fake::default()); |
| 1520 | let engine = chat_engine(&fake, small_pages()).await; |
| 1521 | engine |
| 1522 | .store() |
| 1523 | .upsert_chats(&[store::ChatRecord { |
| 1524 | id: "19:bare@thread.v2".into(), |
| 1525 | ..Default::default() |
| 1526 | }]) |
| 1527 | .unwrap(); |
| 1528 | |
| 1529 | let error = engine |
| 1530 | .share_attachment("19:bare@thread.v2", &uploaded()) |
| 1531 | .await |
| 1532 | .unwrap_err(); |
| 1533 | assert!(error.to_string().contains("Chat members not loaded yet.")); |
| 1534 | engine.share_attachment(CHAT, &uploaded()).await.unwrap(); |
| 1535 | assert!(fake.calls().contains(&"share item-1 user-ada".to_owned())); |
| 1536 | } |
| 1537 | |
| 1538 | #[tokio::test] |
| 1539 | async fn discarding_an_upload_deletes_the_drive_item() { |
| 1540 | let fake = Arc::new(Fake::default()); |
| 1541 | let engine = chat_engine(&fake, small_pages()).await; |
| 1542 | engine.discard_attachment(&uploaded()).await.unwrap(); |
| 1543 | assert_eq!(fake.calls(), ["delete_file item-1"]); |
| 1544 | } |
| 1545 | |
| 1546 | #[tokio::test] |
| 1547 | async fn an_edit_keeps_the_images_and_files_of_the_original() { |
| 1548 | let fake = Arc::new(Fake::default()); |
| 1549 | let engine = chat_engine(&fake, small_pages()).await; |
| 1550 | engine |
| 1551 | .store() |
| 1552 | .upsert_messages(&[store::MessageRecord { |
| 1553 | conversation_id: CHAT.into(), |
| 1554 | message_id: "m-edit".into(), |
| 1555 | created_at: base(), |
| 1556 | body_html: "<p>old</p><p><img src=\"https://graph.microsoft.com/v1.0/chats/c/messages/1/hostedContents/9/$value\"></p><attachment id=\"G1\"></attachment>".into(), |
| 1557 | attachments_json: r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}]"#.into(), |
| 1558 | reactions_json: "[]".into(), |
| 1559 | mentions_json: "[]".into(), |
| 1560 | ..Default::default() |
| 1561 | }]) |
| 1562 | .unwrap(); |
| 1563 | |
| 1564 | let _ = engine.edit_message(CHAT, "m-edit", "new").await; |
| 1565 | |
| 1566 | let call = fake |
| 1567 | .calls() |
| 1568 | .into_iter() |
| 1569 | .find(|call| call.starts_with("edit")) |
| 1570 | .unwrap(); |
| 1571 | assert!(call.contains("new<p><img src=\"https://graph.microsoft.com/")); |
| 1572 | let extras = fake.extras_sent.lock().unwrap(); |
| 1573 | assert_eq!(extras[0].files[0].attachment_id, "G1"); |
| 1574 | assert_eq!(extras[0].files[0].content_url, "https://x/a.pdf"); |
| 1575 | } |
| 1576 | |
| 1577 | #[tokio::test] |
| 1578 | async fn download_streams_every_chunk_and_reports_progress() { |
| 1579 | let fake = Arc::new(Fake::default()); |
| 1580 | let engine = chat_engine(&fake, small_pages()).await; |
| 1581 | let written = Mutex::new(0usize); |
| 1582 | let percents = Mutex::new(Vec::new()); |
| 1583 | let shared = engine |
| 1584 | .download_file( |
| 1585 | "https://files.example/doc", |
| 1586 | |bytes| { |
| 1587 | *written.lock().unwrap() += bytes.len(); |
| 1588 | Ok(()) |
| 1589 | }, |
| 1590 | |percent| percents.lock().unwrap().push(percent), |
| 1591 | ) |
| 1592 | .await |
| 1593 | .unwrap(); |
| 1594 | assert_eq!(*written.lock().unwrap() as u64, shared.size); |
| 1595 | let chunk = graph::DOWNLOAD_CHUNK_BYTES; |
| 1596 | let ranges: Vec<String> = fake |
| 1597 | .calls() |
| 1598 | .into_iter() |
| 1599 | .filter(|call| call.starts_with("range")) |
| 1600 | .collect(); |
| 1601 | assert_eq!( |
| 1602 | ranges, |
| 1603 | vec![ |
| 1604 | format!("range https://dl.example/big 0-{}", chunk - 1), |
| 1605 | format!("range https://dl.example/big {chunk}-{}", 2 * chunk - 1), |
| 1606 | format!("range https://dl.example/big {}-", 2 * chunk), |
| 1607 | ] |
| 1608 | ); |
| 1609 | let percents = percents.lock().unwrap(); |
| 1610 | assert_eq!(percents.first(), Some(&0)); |
| 1611 | assert_eq!(percents.last(), Some(&100)); |
| 1612 | assert!(percents.windows(2).all(|pair| pair[0] <= pair[1])); |
| 1613 | } |
| 1614 | |
| 1615 | #[tokio::test] |
| 1616 | async fn library_download_uses_the_listing_url_and_refetches_the_item_without_one() { |
| 1617 | let library_file = |cached_url: Option<&str>| teams_core::LibraryFile { |
| 1618 | drive_id: "drive".into(), |
| 1619 | item_id: "item".into(), |
| 1620 | name: "big.bin".into(), |
| 1621 | size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3, |
| 1622 | cached_url: cached_url.map(str::to_owned), |
| 1623 | }; |
| 1624 | let fake = Arc::new(Fake::default()); |
| 1625 | let engine = chat_engine(&fake, small_pages()).await; |
| 1626 | engine |
| 1627 | .download_library_file( |
| 1628 | &library_file(Some("https://dl.example/listed")), |
| 1629 | |_| Ok(()), |
| 1630 | |_| {}, |
| 1631 | ) |
| 1632 | .await |
| 1633 | .unwrap(); |
| 1634 | let calls = fake.calls(); |
| 1635 | assert!(!calls.iter().any(|call| call.starts_with("resolve"))); |
| 1636 | assert!( |
| 1637 | calls |
| 1638 | .iter() |
| 1639 | .any(|call| call.starts_with("range https://dl.example/listed ")) |
| 1640 | ); |
| 1641 | engine |
| 1642 | .download_library_file(&library_file(None), |_| Ok(()), |_| {}) |
| 1643 | .await |
| 1644 | .unwrap(); |
| 1645 | let calls = fake.calls(); |
| 1646 | assert!(calls.contains(&"resolve item drive/item".to_owned())); |
| 1647 | assert!( |
| 1648 | calls |
| 1649 | .iter() |
| 1650 | .any(|call| call.starts_with("range https://dl.example/fresh ")) |
| 1651 | ); |
| 1652 | } |
| 1653 | |
| 1654 | #[tokio::test] |
| 1655 | async fn download_keeps_a_file_that_grew_past_the_reported_size() { |
| 1656 | let fake = Arc::new(Fake::default()); |
| 1657 | let engine = chat_engine(&fake, small_pages()).await; |
| 1658 | let written = Mutex::new(0usize); |
| 1659 | let percents = Mutex::new(Vec::new()); |
| 1660 | let shared = engine |
| 1661 | .download_file( |
| 1662 | "https://files.example/grown", |
| 1663 | |bytes| { |
| 1664 | *written.lock().unwrap() += bytes.len(); |
| 1665 | Ok(()) |
| 1666 | }, |
| 1667 | |percent| percents.lock().unwrap().push(percent), |
| 1668 | ) |
| 1669 | .await |
| 1670 | .unwrap(); |
| 1671 | assert_eq!(*written.lock().unwrap() as u64, shared.size + 10); |
| 1672 | assert!( |
| 1673 | percents |
| 1674 | .lock() |
| 1675 | .unwrap() |
| 1676 | .iter() |
| 1677 | .all(|percent| *percent <= 100) |
| 1678 | ); |
| 1679 | } |
| 1680 | |
| 1681 | #[tokio::test] |
| 1682 | async fn download_rejects_a_short_chunk() { |
| 1683 | let fake = Arc::new(Fake::default()); |
| 1684 | let engine = chat_engine(&fake, small_pages()).await; |
| 1685 | let result = engine |
| 1686 | .download_file("https://files.example/short", |_| Ok(()), |_| {}) |
| 1687 | .await; |
| 1688 | assert!(result.is_err()); |
| 1689 | } |
| 1690 | |
| 1691 | #[tokio::test] |
| 1692 | async fn download_stops_when_the_writer_fails() { |
| 1693 | let fake = Arc::new(Fake::default()); |
| 1694 | let engine = chat_engine(&fake, small_pages()).await; |
| 1695 | let result = engine |
| 1696 | .download_file( |
| 1697 | "https://files.example/doc", |
| 1698 | |_| Err(std::io::Error::other("disk full")), |
| 1699 | |_| {}, |
| 1700 | ) |
| 1701 | .await; |
| 1702 | assert!(matches!(result, Err(Error::Io(_)))); |
| 1703 | let ranges = fake |
| 1704 | .calls() |
| 1705 | .into_iter() |
| 1706 | .filter(|call| call.starts_with("range")) |
| 1707 | .count(); |
| 1708 | assert_eq!(ranges, 1); |
| 1709 | } |
| 1710 | |
| 1711 | #[tokio::test] |
| 1712 | async fn upload_to_an_unknown_conversation_fails() { |
| 1713 | let fake = Arc::new(Fake::default()); |
| 1714 | let engine = chat_engine(&fake, small_pages()).await; |
| 1715 | assert!( |
| 1716 | engine |
| 1717 | .upload_attachment("unknown", "a.pdf", &[1], |_| {}) |
| 1718 | .await |
| 1719 | .is_err() |
| 1720 | ); |
| 1721 | } |
| 1722 | |
| 1723 | #[tokio::test] |
| 1724 | async fn send_with_extras_hands_images_and_files_to_the_remote() { |
| 1725 | let fake = Arc::new(Fake::default()); |
| 1726 | let engine = chat_engine(&fake, small_pages()).await; |
| 1727 | let extras = MessageExtras { |
| 1728 | kept: Vec::new(), |
| 1729 | images: vec![HostedImage { |
| 1730 | content_type: "image/png".into(), |
| 1731 | bytes: Arc::new(vec![9]), |
| 1732 | }], |
| 1733 | files: Vec::new(), |
| 1734 | }; |
| 1735 | |
| 1736 | engine |
| 1737 | .send_message_with_extras(CHAT, "look", None, &[], &extras) |
| 1738 | .await |
| 1739 | .unwrap(); |
| 1740 | engine.send_message(CHAT, "plain", None).await.unwrap(); |
| 1741 | |
| 1742 | let sent = fake.extras_sent.lock().unwrap(); |
| 1743 | assert_eq!(sent[0], extras); |
| 1744 | assert!(sent[1].is_empty()); |
| 1745 | } |
| 1746 | |
| 1747 | #[tokio::test] |
| 1748 | async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() { |
| 1749 | let fake = Arc::new(Fake::default()); |
| 1750 | fake.set_chat_messages(numbered(5)); |
| 1751 | let engine = chat_engine(&fake, small_pages()).await; |
| 1752 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1753 | let mut events = engine.subscribe(); |
| 1754 | |
| 1755 | let mut changed = numbered(5); |
| 1756 | changed[1] = message(2, 2, "<p>old but edited</p>"); |
| 1757 | fake.set_chat_messages(changed); |
| 1758 | let record = engine |
| 1759 | .refresh_message(CHAT, "m0002") |
| 1760 | .await |
| 1761 | .unwrap() |
| 1762 | .unwrap(); |
| 1763 | assert_eq!(record.body_html, "<p>old but edited</p>"); |
| 1764 | assert_eq!( |
| 1765 | engine.open_conversation(CHAT).unwrap()[1].body_html, |
| 1766 | "<p>old but edited</p>" |
| 1767 | ); |
| 1768 | assert_eq!( |
| 1769 | events.try_recv().unwrap(), |
| 1770 | CoreEvent::MessagesChanged { |
| 1771 | conversation_id: CHAT.to_owned() |
| 1772 | } |
| 1773 | ); |
| 1774 | |
| 1775 | assert!(engine.refresh_message(CHAT, "m0999").await.is_err()); |
| 1776 | } |
| 1777 | |
| 1778 | #[tokio::test] |
| 1779 | async fn send_typing_addresses_chats_channels_and_threads() { |
| 1780 | let chat_fake = Arc::new(Fake::default()); |
| 1781 | let chat_engine = chat_engine(&chat_fake, small_pages()).await; |
| 1782 | chat_engine.send_typing(CHAT, None, true).await.unwrap(); |
| 1783 | chat_engine.send_typing(CHAT, None, false).await.unwrap(); |
| 1784 | assert!( |
| 1785 | chat_engine |
| 1786 | .send_typing("19:unknown@thread.v2", None, true) |
| 1787 | .await |
| 1788 | .is_err() |
| 1789 | ); |
| 1790 | assert_eq!( |
| 1791 | chat_fake.calls(), |
| 1792 | [ |
| 1793 | format!("typing {CHAT} true"), |
| 1794 | format!("typing {CHAT} false") |
| 1795 | ] |
| 1796 | ); |
| 1797 | |
| 1798 | let channel_fake = Arc::new(Fake::default()); |
| 1799 | let channel_engine = channel_engine(&channel_fake).await; |
| 1800 | channel_engine |
| 1801 | .send_typing(CHANNEL, None, true) |
| 1802 | .await |
| 1803 | .unwrap(); |
| 1804 | channel_engine |
| 1805 | .send_typing(CHANNEL, Some("m0042"), true) |
| 1806 | .await |
| 1807 | .unwrap(); |
| 1808 | assert_eq!( |
| 1809 | channel_fake.calls(), |
| 1810 | [ |
| 1811 | format!("typing {CHANNEL} true"), |
| 1812 | format!("typing {CHANNEL};messageid=m0042 true"), |
| 1813 | ] |
| 1814 | ); |
| 1815 | } |
| 1816 | |
| 1817 | #[tokio::test] |
| 1818 | async fn chat_actions_call_graph_with_the_right_ids() { |
| 1819 | let fake = Arc::new(Fake::default()); |
| 1820 | fake.set_chat_messages(numbered(3)); |
| 1821 | let engine = chat_engine(&fake, small_pages()).await; |
| 1822 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1823 | |
| 1824 | engine.mark_read(CHAT).await.unwrap(); |
| 1825 | engine.set_reaction(CHAT, "m0001", "like").await.unwrap(); |
| 1826 | engine.unset_reaction(CHAT, "m0001", "like").await.unwrap(); |
| 1827 | engine |
| 1828 | .edit_message(CHAT, "m0002", "new **text**") |
| 1829 | .await |
| 1830 | .unwrap(); |
| 1831 | engine.soft_delete_message(CHAT, "m0003").await.unwrap(); |
| 1832 | let calls = fake.calls(); |
| 1833 | assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1")); |
| 1834 | assert!(calls.contains(&"set_reaction m0001 like".to_owned())); |
| 1835 | assert!(calls.contains(&"unset_reaction m0001 like".to_owned())); |
| 1836 | assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned())); |
| 1837 | assert!(calls.contains(&format!("soft_delete {ME} m0003"))); |
| 1838 | assert!(!engine.sidebar().unwrap().chats[0].unread); |
| 1839 | } |
| 1840 | |
| 1841 | #[tokio::test] |
| 1842 | async fn new_chats_are_cached_and_people_are_searched() { |
| 1843 | let fake = Arc::new(Fake::default()); |
| 1844 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1845 | let one_on_one = engine.create_one_on_one("user-ada").await.unwrap(); |
| 1846 | let group = engine |
| 1847 | .create_group( |
| 1848 | &["user-ada".to_owned(), "user-bob".to_owned()], |
| 1849 | Some("Crew"), |
| 1850 | ) |
| 1851 | .await |
| 1852 | .unwrap(); |
| 1853 | assert_eq!( |
| 1854 | (one_on_one.as_str(), group.as_str()), |
| 1855 | ("19:new@thread.v2", "19:group@thread.v2") |
| 1856 | ); |
| 1857 | assert_eq!(engine.store().chat_count().unwrap(), 2); |
| 1858 | assert_eq!( |
| 1859 | fake.calls()[1], |
| 1860 | format!("group {ME} user-ada,user-bob Some(\"Crew\")") |
| 1861 | ); |
| 1862 | assert_eq!(engine.search_people("ada").await.unwrap().len(), 1); |
| 1863 | } |
| 1864 | |
| 1865 | fn chat_with_preview( |
| 1866 | id: &str, |
| 1867 | minute: i64, |
| 1868 | content_type: &str, |
| 1869 | content: &str, |
| 1870 | deleted: bool, |
| 1871 | ) -> Chat { |
| 1872 | let mut chat = chat(id, Some("Planning"), minute, 0, "user-ada", false); |
| 1873 | let preview = chat.last_message_preview.as_mut().unwrap(); |
| 1874 | preview.body = Some(graph::Body { |
| 1875 | content_type: content_type.to_owned(), |
| 1876 | content: Some(content.to_owned()), |
| 1877 | }); |
| 1878 | preview.from = |
| 1879 | serde_json::from_value(json!({"user": {"id": "user-ada", "displayName": "Ada Example"}})) |
| 1880 | .unwrap(); |
| 1881 | preview.message_type = Some("message".to_owned()); |
| 1882 | if deleted { |
| 1883 | preview.deleted_date_time = Some(base()); |
| 1884 | } |
| 1885 | chat |
| 1886 | } |
| 1887 | |
| 1888 | #[tokio::test] |
| 1889 | async fn sidebar_sync_fills_the_last_message_preview() { |
| 1890 | let fake = Arc::new(Fake::default()); |
| 1891 | *fake.chats.lock().unwrap() = vec![ |
| 1892 | chat_with_preview( |
| 1893 | "c-html", |
| 1894 | 5, |
| 1895 | "html", |
| 1896 | "<p>Hello <b>team</b></p><p>second</p>", |
| 1897 | false, |
| 1898 | ), |
| 1899 | chat_with_preview("c-gone", 4, "html", "<p>secret</p>", true), |
| 1900 | chat_with_preview("c-image", 3, "html", "<p><img src=\"x\"></p>", false), |
| 1901 | chat_with_preview("c-text", 2, "text", &"x".repeat(500), false), |
| 1902 | ]; |
| 1903 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1904 | engine.refresh_sidebar().await.unwrap(); |
| 1905 | let chats = engine.sidebar().unwrap().chats; |
| 1906 | let by_id = |id: &str| chats.iter().find(|chat| chat.id == id).unwrap().clone(); |
| 1907 | let html = by_id("c-html"); |
| 1908 | assert_eq!( |
| 1909 | html.last_message_preview.as_deref(), |
| 1910 | Some("Hello team second") |
| 1911 | ); |
| 1912 | assert_eq!( |
| 1913 | html.last_message_sender_name.as_deref(), |
| 1914 | Some("Ada Example") |
| 1915 | ); |
| 1916 | assert_eq!(html.last_message_sender_id.as_deref(), Some("user-ada")); |
| 1917 | assert!(!html.last_message_deleted); |
| 1918 | let gone = by_id("c-gone"); |
| 1919 | assert!(gone.last_message_deleted); |
| 1920 | assert_eq!(gone.last_message_preview, None); |
| 1921 | assert_eq!(by_id("c-image").last_message_preview, None); |
| 1922 | assert_eq!( |
| 1923 | by_id("c-text") |
| 1924 | .last_message_preview |
| 1925 | .unwrap() |
| 1926 | .chars() |
| 1927 | .count(), |
| 1928 | 200 |
| 1929 | ); |
| 1930 | assert!( |
| 1931 | html.members |
| 1932 | .iter() |
| 1933 | .all(|member| member.user_id.is_some() && !member.display_name.is_empty()) |
| 1934 | ); |
| 1935 | } |
| 1936 | |
| 1937 | #[tokio::test] |
| 1938 | async fn a_newer_message_updates_the_preview_and_announces_the_sidebar() { |
| 1939 | let fake = Arc::new(Fake::default()); |
| 1940 | fake.set_chat_messages(numbered(3)); |
| 1941 | let engine = chat_engine(&fake, SyncConfig::default()).await; |
| 1942 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1943 | let mut events = engine.subscribe(); |
| 1944 | let mut all = numbered(3); |
| 1945 | all.push(message(4, 40, "<p>brand <i>new</i></p>")); |
| 1946 | fake.set_chat_messages(all); |
| 1947 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1948 | let record = engine.sidebar().unwrap().chats.remove(0); |
| 1949 | assert_eq!(record.last_message_preview.as_deref(), Some("brand new")); |
| 1950 | assert_eq!( |
| 1951 | record.last_message_sender_name.as_deref(), |
| 1952 | Some("Ada Example") |
| 1953 | ); |
| 1954 | assert_eq!(record.last_message_at, Some(base() + Duration::minutes(40))); |
| 1955 | let mut seen = Vec::new(); |
| 1956 | while let Ok(event) = events.try_recv() { |
| 1957 | seen.push(event); |
| 1958 | } |
| 1959 | assert!(seen.contains(&CoreEvent::SidebarChanged)); |
| 1960 | } |
| 1961 | |
| 1962 | #[tokio::test] |
| 1963 | async fn an_edited_old_message_leaves_the_preview_alone() { |
| 1964 | let fake = Arc::new(Fake::default()); |
| 1965 | fake.set_chat_messages(numbered(3)); |
| 1966 | let engine = chat_engine(&fake, SyncConfig::default()).await; |
| 1967 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1968 | let before = engine.sidebar().unwrap().chats.remove(0); |
| 1969 | let mut all = numbered(3); |
| 1970 | all[0] = message(1, 1, "<p>edited early</p>"); |
| 1971 | fake.set_chat_messages(all); |
| 1972 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1973 | assert_eq!(engine.sidebar().unwrap().chats.remove(0), before); |
| 1974 | } |
| 1975 | |
| 1976 | #[tokio::test] |
| 1977 | async fn me_is_known_after_the_first_sync() { |
| 1978 | let fake = Arc::new(Fake::default()); |
| 1979 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1980 | assert_eq!(engine.me(), None); |
| 1981 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 1982 | engine.refresh_sidebar().await.unwrap(); |
| 1983 | let me = engine.me().unwrap(); |
| 1984 | assert_eq!(me.user_id, ME); |
| 1985 | assert_eq!(me.display_name, "Me Myself"); |
| 1986 | } |
| 1987 | |
| 1988 | #[tokio::test] |
| 1989 | async fn unread_count_uses_cached_messages_after_the_read_time() { |
| 1990 | let fake = Arc::new(Fake::default()); |
| 1991 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 10, 2, "user-ada", false)]; |
| 1992 | fake.set_chat_messages(numbered(5)); |
| 1993 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1994 | engine.refresh_sidebar().await.unwrap(); |
| 1995 | assert_eq!(engine.unread_count(CHAT), 1); |
| 1996 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1997 | assert_eq!(engine.unread_count(CHAT), 3); |
| 1998 | assert_eq!(engine.unread_count("unknown"), 0); |
| 1999 | engine.mark_read(CHAT).await.unwrap(); |
| 2000 | assert_eq!(engine.unread_count(CHAT), 0); |
| 2001 | } |
| 2002 | |
| 2003 | fn ids(values: &[&str]) -> Vec<String> { |
| 2004 | values.iter().map(|value| value.to_string()).collect() |
| 2005 | } |
| 2006 | |
| 2007 | #[tokio::test] |
| 2008 | async fn avatars_are_fetched_cached_and_not_refetched_inside_seven_days() { |
| 2009 | let fake = Arc::new(Fake::default()); |
| 2010 | fake.photos |
| 2011 | .lock() |
| 2012 | .unwrap() |
| 2013 | .insert("ada".into(), vec![1, 2, 3]); |
| 2014 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2015 | let mut events = engine.subscribe(); |
| 2016 | engine |
| 2017 | .fetch_avatars(&ids(&["ada", "nobody", "ada"])) |
| 2018 | .await |
| 2019 | .unwrap(); |
| 2020 | assert_eq!( |
| 2021 | *fake.photo_requests.lock().unwrap(), |
| 2022 | vec![ids(&["ada", "nobody"])] |
| 2023 | ); |
| 2024 | let avatar = engine.avatar("ada").unwrap(); |
| 2025 | assert_eq!(avatar.bytes, [1, 2, 3]); |
| 2026 | assert_eq!(avatar.content_type, "image/jpeg"); |
| 2027 | assert!(engine.avatar("nobody").is_none()); |
| 2028 | assert_eq!( |
| 2029 | events.try_recv().unwrap(), |
| 2030 | CoreEvent::AvatarsChanged { |
| 2031 | user_ids: ids(&["ada"]) |
| 2032 | } |
| 2033 | ); |
| 2034 | engine |
| 2035 | .fetch_avatars(&ids(&["ada", "nobody"])) |
| 2036 | .await |
| 2037 | .unwrap(); |
| 2038 | assert_eq!(fake.photo_requests.lock().unwrap().len(), 1); |
| 2039 | assert!(events.try_recv().is_err()); |
| 2040 | } |
| 2041 | |
| 2042 | #[tokio::test] |
| 2043 | async fn stale_avatars_are_fetched_again() { |
| 2044 | let fake = Arc::new(Fake::default()); |
| 2045 | fake.photos.lock().unwrap().insert("ada".into(), vec![9]); |
| 2046 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2047 | engine |
| 2048 | .store() |
| 2049 | .upsert_avatar(&store::AvatarRecord { |
| 2050 | user_id: "ada".into(), |
| 2051 | bytes: None, |
| 2052 | content_type: String::new(), |
| 2053 | fetched_at: chrono::Utc::now() - Duration::days(8), |
| 2054 | }) |
| 2055 | .unwrap(); |
| 2056 | engine.fetch_avatars(&ids(&["ada"])).await.unwrap(); |
| 2057 | assert_eq!(engine.avatar("ada").unwrap().bytes, [9]); |
| 2058 | } |
| 2059 | |
| 2060 | #[tokio::test] |
| 2061 | async fn presence_maps_availability_and_announces_changes_once() { |
| 2062 | let fake = Arc::new(Fake::default()); |
| 2063 | let entry = |user_id: &str, availability: &str| Presence { |
| 2064 | user_id: user_id.to_owned(), |
| 2065 | availability: availability.to_owned(), |
| 2066 | activity: None, |
| 2067 | }; |
| 2068 | *fake.presence_answers.lock().unwrap() = vec![ |
| 2069 | entry("ada", "BusyIdle"), |
| 2070 | entry("bob", "BeRightBack"), |
| 2071 | entry("cy", "PresenceUnknown"), |
| 2072 | entry("di", "DoNotDisturb"), |
| 2073 | ]; |
| 2074 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2075 | let mut events = engine.subscribe(); |
| 2076 | assert!(engine.presence("ada").is_none()); |
| 2077 | let wanted = ids(&["ada", "bob", "cy", "di"]); |
| 2078 | engine.refresh_presence(&wanted).await.unwrap(); |
| 2079 | assert_eq!( |
| 2080 | engine.presence("ada").unwrap().availability, |
| 2081 | Availability::Busy |
| 2082 | ); |
| 2083 | assert_eq!( |
| 2084 | engine.presence("bob").unwrap().availability, |
| 2085 | Availability::Away |
| 2086 | ); |
| 2087 | assert_eq!( |
| 2088 | engine.presence("cy").unwrap().availability, |
| 2089 | Availability::Unknown |
| 2090 | ); |
| 2091 | assert_eq!( |
| 2092 | engine.presence("di").unwrap().availability, |
| 2093 | Availability::DoNotDisturb |
| 2094 | ); |
| 2095 | assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged); |
| 2096 | engine.refresh_presence(&wanted).await.unwrap(); |
| 2097 | assert!(events.try_recv().is_err()); |
| 2098 | } |
| 2099 | |
| 2100 | #[tokio::test] |
| 2101 | async fn setting_own_availability_writes_then_reads_back_and_announces() { |
| 2102 | let fake = Arc::new(Fake::default()); |
| 2103 | *fake.own_status_answer.lock().unwrap() = chatsvc::PresenceStatus { |
| 2104 | availability: "Busy".into(), |
| 2105 | ..chatsvc::PresenceStatus::default() |
| 2106 | }; |
| 2107 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2108 | let mut events = engine.subscribe(); |
| 2109 | let forced = chatsvc::ForcedAvailability { |
| 2110 | kind: chatsvc::ForcedKind::Busy, |
| 2111 | expires_at: None, |
| 2112 | }; |
| 2113 | engine.set_own_availability(Some(forced)).await.unwrap(); |
| 2114 | assert_eq!(*fake.availability_puts.lock().unwrap(), vec![Some(forced)]); |
| 2115 | assert_eq!( |
| 2116 | engine.presence(ME).unwrap().availability, |
| 2117 | Availability::Busy |
| 2118 | ); |
| 2119 | assert!(matches!( |
| 2120 | events.try_recv().unwrap(), |
| 2121 | CoreEvent::PresenceStatusChanged(status) if status.availability == "Busy" |
| 2122 | )); |
| 2123 | assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged); |
| 2124 | } |
| 2125 | |
| 2126 | #[tokio::test] |
| 2127 | async fn setting_the_own_note_forwards_the_note() { |
| 2128 | let fake = Arc::new(Fake::default()); |
| 2129 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2130 | engine.set_own_status_note(None).await.unwrap(); |
| 2131 | assert_eq!(*fake.note_puts.lock().unwrap(), vec![None]); |
| 2132 | } |
| 2133 | |
| 2134 | fn trouter_endpoint(endpoint_id: &str) -> chatsvc::TrouterEndpoint { |
| 2135 | chatsvc::TrouterEndpoint { |
| 2136 | endpoint_id: endpoint_id.to_owned(), |
| 2137 | trouter_uri: "https://go-eu.trouter.teams.microsoft.com/v4/f/x/unifiedPresenceService" |
| 2138 | .to_owned(), |
| 2139 | } |
| 2140 | } |
| 2141 | |
| 2142 | #[tokio::test] |
| 2143 | async fn presence_subscribes_watched_users_once_the_endpoint_is_known() { |
| 2144 | let fake = Arc::new(Fake::default()); |
| 2145 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2146 | engine.watch_presence(&ids(&["ada", "bob"])).await.unwrap(); |
| 2147 | assert!(fake.presence_subscriptions.lock().unwrap().is_empty()); |
| 2148 | engine |
| 2149 | .presence_endpoint(trouter_endpoint("e1")) |
| 2150 | .await |
| 2151 | .unwrap(); |
| 2152 | engine.watch_presence(&ids(&["bob", "cy"])).await.unwrap(); |
| 2153 | engine.watch_presence(&ids(&["cy"])).await.unwrap(); |
| 2154 | assert_eq!( |
| 2155 | *fake.presence_subscriptions.lock().unwrap(), |
| 2156 | vec![ |
| 2157 | ("e1".to_owned(), ids(&["ada", "bob"]), true), |
| 2158 | ("e1".to_owned(), ids(&["cy"]), false), |
| 2159 | ] |
| 2160 | ); |
| 2161 | engine |
| 2162 | .presence_endpoint(trouter_endpoint("e1")) |
| 2163 | .await |
| 2164 | .unwrap(); |
| 2165 | assert_eq!(fake.presence_subscriptions.lock().unwrap().len(), 2); |
| 2166 | engine.resubscribe_presence().await.unwrap(); |
| 2167 | engine |
| 2168 | .presence_endpoint(trouter_endpoint("e2")) |
| 2169 | .await |
| 2170 | .unwrap(); |
| 2171 | assert_eq!( |
| 2172 | fake.presence_subscriptions.lock().unwrap()[2..], |
| 2173 | [ |
| 2174 | ("e1".to_owned(), ids(&["ada", "bob", "cy"]), true), |
| 2175 | ("e2".to_owned(), ids(&["ada", "bob", "cy"]), true), |
| 2176 | ] |
| 2177 | ); |
| 2178 | } |
| 2179 | |
| 2180 | #[tokio::test] |
| 2181 | async fn pushed_presence_announces_changes_once() { |
| 2182 | let fake = Arc::new(Fake::default()); |
| 2183 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2184 | let mut events = engine.subscribe(); |
| 2185 | let update = |user_id: &str, availability: &str| chatsvc::PresenceUpdate { |
| 2186 | user_id: user_id.to_owned(), |
| 2187 | availability: availability.to_owned(), |
| 2188 | activity: None, |
| 2189 | }; |
| 2190 | let updates = vec![update("ada", "Busy"), update("bob", "Away")]; |
| 2191 | engine.apply_presence(&updates); |
| 2192 | assert_eq!( |
| 2193 | engine.presence("ada").unwrap().availability, |
| 2194 | Availability::Busy |
| 2195 | ); |
| 2196 | assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged); |
| 2197 | assert!(events.try_recv().is_err()); |
| 2198 | engine.apply_presence(&updates); |
| 2199 | assert!(events.try_recv().is_err()); |
| 2200 | } |
| 2201 | |
| 2202 | struct FakeFolders { |
| 2203 | state: Mutex<Vec<ChatFolder>>, |
| 2204 | channels: Vec<String>, |
| 2205 | layout: Vec<TeamLayoutRecord>, |
| 2206 | settings: ChatSectionSettings, |
| 2207 | calls: Mutex<Vec<String>>, |
| 2208 | } |
| 2209 | |
| 2210 | impl FakeFolders { |
| 2211 | fn new() -> Arc<Self> { |
| 2212 | let folder = |id: &str, kind, items: &[&str]| ChatFolder { |
| 2213 | id: id.to_owned(), |
| 2214 | name: id.to_owned(), |
| 2215 | kind, |
| 2216 | expanded: true, |
| 2217 | conversation_ids: ids(items), |
| 2218 | }; |
| 2219 | Arc::new(FakeFolders { |
| 2220 | state: Mutex::new(vec![ |
| 2221 | folder("fav", FolderKind::Favorites, &["a", "b"]), |
| 2222 | folder("work", FolderKind::UserCreated, &["c"]), |
| 2223 | ]), |
| 2224 | channels: ids(&["ch1", "ch2"]), |
| 2225 | layout: Vec::new(), |
| 2226 | settings: ChatSectionSettings::default(), |
| 2227 | calls: Mutex::new(Vec::new()), |
| 2228 | }) |
| 2229 | } |
| 2230 | } |
| 2231 | |
| 2232 | impl FolderSource for FakeFolders { |
| 2233 | fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> { |
| 2234 | Box::pin(async { Ok(self.state.lock().unwrap().clone()) }) |
| 2235 | } |
| 2236 | |
| 2237 | fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> { |
| 2238 | Box::pin(async { Ok(self.channels.clone()) }) |
| 2239 | } |
| 2240 | |
| 2241 | fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> { |
| 2242 | Box::pin(async { Ok(self.layout.clone()) }) |
| 2243 | } |
| 2244 | |
| 2245 | fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> { |
| 2246 | Box::pin(async { Ok(self.settings) }) |
| 2247 | } |
| 2248 | |
| 2249 | fn set_section_enabled( |
| 2250 | &self, |
| 2251 | section: ChatSection, |
| 2252 | enabled: bool, |
| 2253 | ) -> BoxFuture<'_, Result<()>> { |
| 2254 | Box::pin(async move { |
| 2255 | self.calls |
| 2256 | .lock() |
| 2257 | .unwrap() |
| 2258 | .push(format!("section {section:?} {enabled}")); |
| 2259 | Ok(()) |
| 2260 | }) |
| 2261 | } |
| 2262 | |
| 2263 | fn set_folder_expanded<'a>( |
| 2264 | &'a self, |
| 2265 | folder_id: &'a str, |
| 2266 | expanded: bool, |
| 2267 | ) -> BoxFuture<'a, Result<()>> { |
| 2268 | Box::pin(async move { |
| 2269 | self.calls |
| 2270 | .lock() |
| 2271 | .unwrap() |
| 2272 | .push(format!("expanded {folder_id} {expanded}")); |
| 2273 | Ok(()) |
| 2274 | }) |
| 2275 | } |
| 2276 | |
| 2277 | fn move_to_folder<'a>( |
| 2278 | &'a self, |
| 2279 | conversation_id: &'a str, |
| 2280 | target_folder_id: &'a str, |
| 2281 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> { |
| 2282 | Box::pin(async move { |
| 2283 | self.calls |
| 2284 | .lock() |
| 2285 | .unwrap() |
| 2286 | .push(format!("move {conversation_id} {target_folder_id}")); |
| 2287 | let mut state = self.state.lock().unwrap(); |
| 2288 | for folder in state |
| 2289 | .iter_mut() |
| 2290 | .filter(|folder| folder.kind == FolderKind::UserCreated) |
| 2291 | { |
| 2292 | folder.conversation_ids.retain(|id| id != conversation_id); |
| 2293 | } |
| 2294 | state |
| 2295 | .iter_mut() |
| 2296 | .find(|folder| folder.id == target_folder_id) |
| 2297 | .unwrap() |
| 2298 | .conversation_ids |
| 2299 | .push(conversation_id.to_owned()); |
| 2300 | Ok(state.clone()) |
| 2301 | }) |
| 2302 | } |
| 2303 | |
| 2304 | fn remove_from_folder<'a>( |
| 2305 | &'a self, |
| 2306 | conversation_id: &'a str, |
| 2307 | folder_id: &'a str, |
| 2308 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> { |
| 2309 | Box::pin(async move { |
| 2310 | self.calls |
| 2311 | .lock() |
| 2312 | .unwrap() |
| 2313 | .push(format!("remove {conversation_id} {folder_id}")); |
| 2314 | let mut state = self.state.lock().unwrap(); |
| 2315 | state |
| 2316 | .iter_mut() |
| 2317 | .find(|folder| folder.id == folder_id) |
| 2318 | .unwrap() |
| 2319 | .conversation_ids |
| 2320 | .retain(|id| id != conversation_id); |
| 2321 | Ok(state.clone()) |
| 2322 | }) |
| 2323 | } |
| 2324 | } |
| 2325 | |
| 2326 | #[tokio::test] |
| 2327 | async fn folders_refresh_move_and_remove_go_through_the_source_and_cache() { |
| 2328 | let fake = Arc::new(Fake::default()); |
| 2329 | let source = FakeFolders::new(); |
| 2330 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 2331 | assert!(engine.chat_folders().unwrap().is_empty()); |
| 2332 | let mut events = engine.subscribe(); |
| 2333 | |
| 2334 | engine.refresh_folders().await.unwrap(); |
| 2335 | let folders = engine.chat_folders().unwrap(); |
| 2336 | assert_eq!(folders.len(), 2); |
| 2337 | assert_eq!(folders[0].kind, FolderKind::Favorites); |
| 2338 | assert_eq!(folders[0].conversation_ids, ids(&["a", "b"])); |
| 2339 | assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch1", "ch2"])); |
| 2340 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 2341 | |
| 2342 | engine.refresh_folders().await.unwrap(); |
| 2343 | assert!(events.try_recv().is_err()); |
| 2344 | |
| 2345 | engine.move_to_folder("a", "work").await.unwrap(); |
| 2346 | assert_eq!( |
| 2347 | engine.chat_folders().unwrap()[1].conversation_ids, |
| 2348 | ids(&["c", "a"]) |
| 2349 | ); |
| 2350 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 2351 | assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch1", "ch2"])); |
| 2352 | |
| 2353 | engine.remove_from_folder("a", "work").await.unwrap(); |
| 2354 | assert_eq!( |
| 2355 | engine.chat_folders().unwrap()[1].conversation_ids, |
| 2356 | ids(&["c"]) |
| 2357 | ); |
| 2358 | assert_eq!( |
| 2359 | *source.calls.lock().unwrap(), |
| 2360 | ["move a work", "remove a work"] |
| 2361 | ); |
| 2362 | } |
| 2363 | |
| 2364 | #[tokio::test] |
| 2365 | async fn collapse_and_section_settings_go_through_the_source() { |
| 2366 | let fake = Arc::new(Fake::default()); |
| 2367 | let mut source = FakeFolders::new(); |
| 2368 | Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings { |
| 2369 | muted: Some(false), |
| 2370 | meeting: Some(true), |
| 2371 | }; |
| 2372 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 2373 | let mut events = engine.subscribe(); |
| 2374 | engine.refresh_folders().await.unwrap(); |
| 2375 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 2376 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 2377 | assert_eq!( |
| 2378 | teams_core::stored_section_settings(engine.store()), |
| 2379 | ChatSectionSettings { |
| 2380 | muted: Some(false), |
| 2381 | meeting: Some(true), |
| 2382 | } |
| 2383 | ); |
| 2384 | |
| 2385 | engine.set_folder_expanded("work", false).await.unwrap(); |
| 2386 | engine |
| 2387 | .set_section_enabled(ChatSection::Meeting, false) |
| 2388 | .await |
| 2389 | .unwrap(); |
| 2390 | assert_eq!( |
| 2391 | *source.calls.lock().unwrap(), |
| 2392 | ["expanded work false", "section Meeting false"] |
| 2393 | ); |
| 2394 | } |
| 2395 | |
| 2396 | #[tokio::test] |
| 2397 | async fn team_layout_from_teams_orders_and_hides_the_sidebar() { |
| 2398 | let fake = Arc::new(Fake::default()); |
| 2399 | let mut source = FakeFolders::new(); |
| 2400 | Arc::get_mut(&mut source).unwrap().layout = vec![ |
| 2401 | TeamLayoutRecord { |
| 2402 | team_id: "zeta".into(), |
| 2403 | hidden: false, |
| 2404 | channels: vec![ChannelLayoutRecord { |
| 2405 | channel_id: "zeta-old".into(), |
| 2406 | general: false, |
| 2407 | hidden: true, |
| 2408 | tabs: Vec::new(), |
| 2409 | notifications: Default::default(), |
| 2410 | }], |
| 2411 | }, |
| 2412 | TeamLayoutRecord { |
| 2413 | team_id: "alpha".into(), |
| 2414 | hidden: true, |
| 2415 | channels: Vec::new(), |
| 2416 | }, |
| 2417 | ]; |
| 2418 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 2419 | let team = |id: &str| TeamRecord { |
| 2420 | id: id.into(), |
| 2421 | name: id.into(), |
| 2422 | }; |
| 2423 | engine |
| 2424 | .store() |
| 2425 | .upsert_teams(&[team("alpha"), team("zeta")]) |
| 2426 | .unwrap(); |
| 2427 | let channel = |id: &str, name: &str| ChannelRecord { |
| 2428 | id: id.into(), |
| 2429 | team_id: "zeta".into(), |
| 2430 | name: name.into(), |
| 2431 | membership_type: None, |
| 2432 | last_message_at: None, |
| 2433 | unread: false, |
| 2434 | }; |
| 2435 | engine |
| 2436 | .store() |
| 2437 | .upsert_channels(&[ |
| 2438 | channel("zeta-old", "Archiv"), |
| 2439 | channel("zeta-general", "General"), |
| 2440 | ]) |
| 2441 | .unwrap(); |
| 2442 | let mut events = engine.subscribe(); |
| 2443 | |
| 2444 | engine.refresh_folders().await.unwrap(); |
| 2445 | |
| 2446 | let teams = engine.store().sidebar().unwrap().teams; |
| 2447 | let order: Vec<&str> = teams.iter().map(|entry| entry.team.id.as_str()).collect(); |
| 2448 | assert_eq!(order, ["zeta", "alpha"]); |
| 2449 | assert!(teams[1].hidden); |
| 2450 | assert_eq!(teams[0].channels[0].id, "zeta-general"); |
| 2451 | assert_eq!(teams[0].hidden_channel_ids, ids(&["zeta-old"])); |
| 2452 | let received: Vec<CoreEvent> = std::iter::from_fn(|| events.try_recv().ok()).collect(); |
| 2453 | assert!(received.contains(&CoreEvent::SidebarChanged)); |
| 2454 | } |
| 2455 | |
| 2456 | #[tokio::test] |
| 2457 | async fn channel_notifications_go_to_the_service_then_the_store() { |
| 2458 | let fake = Arc::new(Fake::default()); |
| 2459 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2460 | engine |
| 2461 | .store() |
| 2462 | .upsert_teams(&[TeamRecord { |
| 2463 | id: "alpha".into(), |
| 2464 | name: "alpha".into(), |
| 2465 | }]) |
| 2466 | .unwrap(); |
| 2467 | engine |
| 2468 | .store() |
| 2469 | .upsert_channels(&[ChannelRecord { |
| 2470 | id: "alpha-news".into(), |
| 2471 | team_id: "alpha".into(), |
| 2472 | name: "News".into(), |
| 2473 | membership_type: None, |
| 2474 | last_message_at: None, |
| 2475 | unread: false, |
| 2476 | }]) |
| 2477 | .unwrap(); |
| 2478 | let mut events = engine.subscribe(); |
| 2479 | let banner = store::ChannelNotifications { |
| 2480 | level: store::ChannelNotificationLevel::BannerAndFeed, |
| 2481 | include_replies: true, |
| 2482 | }; |
| 2483 | |
| 2484 | engine |
| 2485 | .set_channel_notifications("alpha-news", banner) |
| 2486 | .await |
| 2487 | .unwrap(); |
| 2488 | |
| 2489 | assert_eq!( |
| 2490 | fake.calls().last().unwrap(), |
| 2491 | "channel notifications alpha-news banner true" |
| 2492 | ); |
| 2493 | let teams = engine.store().sidebar().unwrap().teams; |
| 2494 | assert_eq!(teams[0].channel_notifications("alpha-news"), banner); |
| 2495 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 2496 | } |
| 2497 | |
| 2498 | #[tokio::test] |
| 2499 | async fn folders_without_a_source_are_unsupported() { |
| 2500 | let fake = Arc::new(Fake::default()); |
| 2501 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2502 | assert!(matches!( |
| 2503 | engine.refresh_folders().await, |
| 2504 | Err(Error::Unsupported(_)) |
| 2505 | )); |
| 2506 | assert!(matches!( |
| 2507 | engine.move_to_folder("a", "b").await, |
| 2508 | Err(Error::Unsupported(_)) |
| 2509 | )); |
| 2510 | } |
| 2511 | |
| 2512 | const HOSTED: &str = |
| 2513 | "https://graph.microsoft.com/v1.0/chats/c/messages/m0001/hostedContents/h1/$value"; |
| 2514 | |
| 2515 | fn message_with_image(id: u32, minute: i64, url: &str) -> Message { |
| 2516 | message( |
| 2517 | id, |
| 2518 | minute, |
| 2519 | &format!("<p>look</p><img src=\"{url}\" width=\"300\" height=\"150\">"), |
| 2520 | ) |
| 2521 | } |
| 2522 | |
| 2523 | #[tokio::test] |
| 2524 | async fn images_are_fetched_once_cached_and_announced() { |
| 2525 | let fake = Arc::new(Fake::default()); |
| 2526 | fake.set_chat_messages(vec![message_with_image(1, 1, HOSTED)]); |
| 2527 | let engine = chat_engine(&fake, small_pages()).await; |
| 2528 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2529 | let record = engine.open_conversation(CHAT).unwrap().remove(0); |
| 2530 | let found = teams_core::images(&record); |
| 2531 | assert_eq!(found.len(), 1); |
| 2532 | assert_eq!((found[0].width, found[0].height), (Some(300), Some(150))); |
| 2533 | assert_eq!(found[0].id, "h1"); |
| 2534 | assert!(engine.image(found[0].key()).is_none()); |
| 2535 | |
| 2536 | let mut events = engine.subscribe(); |
| 2537 | engine.fetch_image(&found[0]).await.unwrap(); |
| 2538 | engine.fetch_image(&found[0]).await.unwrap(); |
| 2539 | assert_eq!(fake.hosted_requests.lock().unwrap().len(), 1); |
| 2540 | assert_eq!( |
| 2541 | events.try_recv().unwrap(), |
| 2542 | CoreEvent::ImagesChanged { |
| 2543 | keys: vec![HOSTED.to_owned()] |
| 2544 | } |
| 2545 | ); |
| 2546 | let stored = engine.image(found[0].key()).unwrap(); |
| 2547 | assert_eq!(stored.content_type, "image/png"); |
| 2548 | assert_eq!((stored.width, stored.height), (Some(40), Some(20))); |
| 2549 | } |
| 2550 | |
| 2551 | #[tokio::test] |
| 2552 | async fn gif_and_sticker_images_load_without_graph_and_keep_their_cache_key() { |
| 2553 | let fake = Arc::new(Fake::default()); |
| 2554 | let engine = chat_engine(&fake, small_pages()).await; |
| 2555 | let proxied = "https://de-prod.asyncgw.teams.microsoft.com/urlp/v1/url/content?url=https%3a%2f%2fstatics.teams.cdn.office.net%2fx%2fa.png"; |
| 2556 | let image = teams_core::ImageRef { |
| 2557 | id: "x".to_owned(), |
| 2558 | url: proxied.to_owned(), |
| 2559 | width: None, |
| 2560 | height: None, |
| 2561 | }; |
| 2562 | engine.fetch_image(&image).await.unwrap(); |
| 2563 | assert_eq!( |
| 2564 | *fake.external_requests.lock().unwrap(), |
| 2565 | ["https://statics.teams.cdn.office.net/x/a.png"] |
| 2566 | ); |
| 2567 | assert!(engine.image(proxied).is_some()); |
| 2568 | } |
| 2569 | |
| 2570 | #[tokio::test] |
| 2571 | async fn a_failed_image_fetch_is_an_error_and_can_be_retried() { |
| 2572 | let fake = Arc::new(Fake::default()); |
| 2573 | let engine = chat_engine(&fake, small_pages()).await; |
| 2574 | let image = teams_core::ImageRef { |
| 2575 | id: "x".to_owned(), |
| 2576 | url: "https://graph.microsoft.com/v1.0/chats/broken".to_owned(), |
| 2577 | width: None, |
| 2578 | height: None, |
| 2579 | }; |
| 2580 | assert!(engine.fetch_image(&image).await.is_err()); |
| 2581 | assert!(engine.fetch_image(&image).await.is_err()); |
| 2582 | assert_eq!(fake.hosted_requests.lock().unwrap().len(), 2); |
| 2583 | } |
| 2584 | |
| 2585 | #[tokio::test] |
| 2586 | async fn local_search_finds_cached_messages_and_titles() { |
| 2587 | let fake = Arc::new(Fake::default()); |
| 2588 | fake.set_chat_messages(vec![ |
| 2589 | message(1, 1, "<p>quarterly <b>budget</b> review</p>"), |
| 2590 | message(2, 2, "<p>lunch?</p>"), |
| 2591 | ]); |
| 2592 | let engine = chat_engine(&fake, small_pages()).await; |
| 2593 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2594 | let hits = engine.search_messages("budg", 10).unwrap(); |
| 2595 | assert_eq!(hits.len(), 1); |
| 2596 | assert_eq!( |
| 2597 | ( |
| 2598 | hits[0].conversation_id.as_str(), |
| 2599 | hits[0].message_id.as_str() |
| 2600 | ), |
| 2601 | (CHAT, "m0001") |
| 2602 | ); |
| 2603 | assert!(hits[0].snippet.contains("\u{1}budget\u{2}")); |
| 2604 | assert_eq!( |
| 2605 | engine.search_messages_in(CHAT, "lunch", 10).unwrap().len(), |
| 2606 | 1 |
| 2607 | ); |
| 2608 | assert!( |
| 2609 | engine |
| 2610 | .search_messages_in("other", "lunch", 10) |
| 2611 | .unwrap() |
| 2612 | .is_empty() |
| 2613 | ); |
| 2614 | assert_eq!( |
| 2615 | engine.search_conversations("plann", 10).unwrap()[0].conversation_id, |
| 2616 | CHAT |
| 2617 | ); |
| 2618 | } |
| 2619 | |
| 2620 | #[tokio::test] |
| 2621 | async fn first_unread_is_the_first_message_from_others_after_the_read_time() { |
| 2622 | let fake = Arc::new(Fake::default()); |
| 2623 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 10, 2, "user-ada", false)]; |
| 2624 | fake.set_chat_messages(numbered(5)); |
| 2625 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2626 | engine.refresh_sidebar().await.unwrap(); |
| 2627 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2628 | assert_eq!( |
| 2629 | engine.first_unread_message_id(CHAT).as_deref(), |
| 2630 | Some("m0003") |
| 2631 | ); |
| 2632 | assert!(engine.first_unread_message_id("unknown").is_none()); |
| 2633 | engine.mark_read(CHAT).await.unwrap(); |
| 2634 | assert!(engine.first_unread_message_id(CHAT).is_none()); |
| 2635 | } |
| 2636 | |
| 2637 | #[tokio::test] |
| 2638 | async fn chat_reply_quotes_and_channel_reply_uses_the_thread_root() { |
| 2639 | let fake = Arc::new(Fake::default()); |
| 2640 | fake.set_chat_messages(numbered(2)); |
| 2641 | let engine = chat_engine(&fake, small_pages()).await; |
| 2642 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2643 | let sent = engine |
| 2644 | .reply_to(CHAT, "m0001", "answer **bold**") |
| 2645 | .await |
| 2646 | .unwrap(); |
| 2647 | assert_eq!(sent.message_id, "m9003"); |
| 2648 | assert!( |
| 2649 | fake.calls() |
| 2650 | .contains(&format!("quote_reply {CHAT} m0001 answer <b>bold</b>")) |
| 2651 | ); |
| 2652 | |
| 2653 | let channel_fake = Arc::new(Fake::default()); |
| 2654 | let channel = channel_engine(&channel_fake).await; |
| 2655 | channel.fetch_newer(CHANNEL).await.unwrap(); |
| 2656 | channel.reply_to(CHANNEL, "m0030", "hi").await.unwrap(); |
| 2657 | assert!(channel_fake.calls().contains(&"reply to m0030".to_owned())); |
| 2658 | assert!(engine.reply_to("unknown", "m1", "x").await.is_err()); |
| 2659 | } |
| 2660 | |
| 2661 | #[tokio::test] |
| 2662 | async fn can_edit_and_delete_need_an_own_live_chat_message() { |
| 2663 | let fake = Arc::new(Fake::default()); |
| 2664 | let mut own = message(1, 1, "<p>mine</p>"); |
| 2665 | own.from = |
| 2666 | serde_json::from_value(json!({"user": {"id": ME, "displayName": "Me Myself"}})).unwrap(); |
| 2667 | fake.set_chat_messages(vec![own, message(2, 2, "<p>theirs</p>")]); |
| 2668 | let engine = chat_engine(&fake, small_pages()).await; |
| 2669 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2670 | let records = engine.open_conversation(CHAT).unwrap(); |
| 2671 | assert!(engine.can_edit(&records[0]) && engine.can_delete(&records[0])); |
| 2672 | assert!(!engine.can_edit(&records[1]) && !engine.can_delete(&records[1])); |
| 2673 | let mut deleted = records[0].clone(); |
| 2674 | deleted.deleted = true; |
| 2675 | assert!(!engine.can_edit(&deleted)); |
| 2676 | assert!(teams_core::can_edit(&records[0], ME)); |
| 2677 | assert!(!teams_core::can_delete(&deleted, ME)); |
| 2678 | } |
| 2679 | |
| 2680 | #[tokio::test] |
| 2681 | async fn channel_posts_and_replies_can_be_reacted_edited_and_deleted() { |
| 2682 | let fake = Arc::new(Fake::default()); |
| 2683 | let engine = channel_engine(&fake).await; |
| 2684 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2685 | let reply_id = engine |
| 2686 | .open_conversation(CHANNEL) |
| 2687 | .unwrap() |
| 2688 | .into_iter() |
| 2689 | .find(|record| record.reply_to_id.is_some()) |
| 2690 | .unwrap() |
| 2691 | .message_id; |
| 2692 | |
| 2693 | engine.set_reaction(CHANNEL, "m0030", "like").await.unwrap(); |
| 2694 | engine |
| 2695 | .unset_reaction(CHANNEL, &reply_id, "like") |
| 2696 | .await |
| 2697 | .unwrap(); |
| 2698 | engine |
| 2699 | .edit_message(CHANNEL, &reply_id, "new **text**") |
| 2700 | .await |
| 2701 | .unwrap(); |
| 2702 | engine.edit_message(CHANNEL, "m0030", "root").await.unwrap(); |
| 2703 | engine |
| 2704 | .soft_delete_message(CHANNEL, &reply_id) |
| 2705 | .await |
| 2706 | .unwrap(); |
| 2707 | engine.soft_delete_message(CHANNEL, "m0030").await.unwrap(); |
| 2708 | |
| 2709 | let calls = fake.calls(); |
| 2710 | assert!(calls.contains(&"set_reaction channel:-:m0030 like".to_owned())); |
| 2711 | assert!(calls.contains(&format!("unset_reaction channel:m0030:{reply_id} like"))); |
| 2712 | assert!(calls.contains(&format!("edit channel:m0030:{reply_id} new <b>text</b>"))); |
| 2713 | assert!(calls.contains(&"edit channel:-:m0030 root".to_owned())); |
| 2714 | assert!(calls.contains(&format!("soft_delete {ME} channel:m0030:{reply_id}"))); |
| 2715 | assert!(calls.contains(&format!("soft_delete {ME} channel:-:m0030"))); |
| 2716 | assert!(engine.set_reaction("unknown", "m1", "like").await.is_err()); |
| 2717 | } |
| 2718 | |
| 2719 | #[tokio::test] |
| 2720 | async fn channel_messages_of_mine_are_editable_and_deletable() { |
| 2721 | let fake = Arc::new(Fake::default()); |
| 2722 | let engine = channel_engine(&fake).await; |
| 2723 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2724 | let mut record = engine.open_conversation(CHANNEL).unwrap().remove(0); |
| 2725 | assert!(!engine.can_edit(&record)); |
| 2726 | record.sender_id = Some(ME.to_owned()); |
| 2727 | assert!(engine.can_edit(&record) && engine.can_delete(&record)); |
| 2728 | } |
| 2729 | |
| 2730 | #[tokio::test] |
| 2731 | async fn chat_mentions_become_at_tags_and_a_mentions_array() { |
| 2732 | let fake = Arc::new(Fake::default()); |
| 2733 | let engine = chat_engine(&fake, small_pages()).await; |
| 2734 | engine |
| 2735 | .send_message_with_mentions( |
| 2736 | CHAT, |
| 2737 | "hi @Ada Example & co", |
| 2738 | None, |
| 2739 | &[MentionInput::user("user-ada", "Ada Example")], |
| 2740 | ) |
| 2741 | .await |
| 2742 | .unwrap(); |
| 2743 | assert_eq!( |
| 2744 | fake.sent.lock().unwrap()[0], |
| 2745 | "hi <at id=\"0\">Ada Example</at> & co" |
| 2746 | ); |
| 2747 | let mentions = fake.mentions_sent.lock().unwrap()[0].clone(); |
| 2748 | assert_eq!(mentions.len(), 1); |
| 2749 | assert_eq!(mentions[0].id, 0); |
| 2750 | assert_eq!( |
| 2751 | mentions[0].target, |
| 2752 | MentionTarget::User { |
| 2753 | user_id: "user-ada".to_owned() |
| 2754 | } |
| 2755 | ); |
| 2756 | assert!( |
| 2757 | engine |
| 2758 | .send_message_with_mentions(CHAT, "@Squad", None, &[MentionInput::team("t", "Squad")]) |
| 2759 | .await |
| 2760 | .is_err() |
| 2761 | ); |
| 2762 | } |
| 2763 | |
| 2764 | #[tokio::test] |
| 2765 | async fn channel_mentions_cover_users_channel_and_team_on_post_reply_and_edit() { |
| 2766 | let fake = Arc::new(Fake::default()); |
| 2767 | let engine = channel_engine(&fake).await; |
| 2768 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2769 | let everyone = [ |
| 2770 | MentionInput::user("user-ada", "Ada Example"), |
| 2771 | MentionInput::channel(CHANNEL, "General"), |
| 2772 | MentionInput::team("team-1", "Squad"), |
| 2773 | ]; |
| 2774 | let text = "@Ada Example @General @Squad"; |
| 2775 | engine |
| 2776 | .post_to_channel_with_mentions(CHANNEL, text, None, &everyone) |
| 2777 | .await |
| 2778 | .unwrap(); |
| 2779 | engine |
| 2780 | .reply_to_with_mentions(CHANNEL, "m0030", text, &everyone) |
| 2781 | .await |
| 2782 | .unwrap(); |
| 2783 | engine |
| 2784 | .edit_message_with_mentions(CHANNEL, "m0030", text, &everyone) |
| 2785 | .await |
| 2786 | .unwrap(); |
| 2787 | for mentions in fake.mentions_sent.lock().unwrap().iter() { |
| 2788 | assert_eq!(mentions.len(), 3); |
| 2789 | assert_eq!( |
| 2790 | mentions |
| 2791 | .iter() |
| 2792 | .map(|mention| mention.id) |
| 2793 | .collect::<Vec<_>>(), |
| 2794 | [0, 1, 2] |
| 2795 | ); |
| 2796 | assert!(matches!(mentions[1].target, MentionTarget::Channel { .. })); |
| 2797 | assert!(matches!(mentions[2].target, MentionTarget::Team { .. })); |
| 2798 | } |
| 2799 | assert_eq!(fake.mentions_sent.lock().unwrap().len(), 3); |
| 2800 | } |
| 2801 | |
| 2802 | fn directory_user(id: &str, name: &str) -> User { |
| 2803 | serde_json::from_value( |
| 2804 | json!({"id": id, "displayName": name, "mail": format!("{id}@example.test")}), |
| 2805 | ) |
| 2806 | .unwrap() |
| 2807 | } |
| 2808 | |
| 2809 | #[tokio::test] |
| 2810 | async fn people_candidates_list_members_first_then_the_directory_without_duplicates() { |
| 2811 | let fake = Arc::new(Fake::default()); |
| 2812 | *fake.directory_users.lock().unwrap() = vec![ |
| 2813 | directory_user("user-me", "Me Myself"), |
| 2814 | directory_user("user-ada", "Ada Example"), |
| 2815 | directory_user("user-adam", "Adam Directory"), |
| 2816 | ]; |
| 2817 | let engine = chat_engine(&fake, small_pages()).await; |
| 2818 | |
| 2819 | let everyone = engine.mention_candidates(CHAT, "", 10).await.unwrap(); |
| 2820 | assert_eq!(everyone.len(), 1); |
| 2821 | assert_eq!(everyone[0].display_name(), "Ada Example"); |
| 2822 | assert!(!fake.calls().iter().any(|call| call.starts_with("search"))); |
| 2823 | |
| 2824 | let found = engine.mention_candidates(CHAT, "@ada", 10).await.unwrap(); |
| 2825 | let names: Vec<&str> = found |
| 2826 | .iter() |
| 2827 | .map(|candidate| candidate.display_name()) |
| 2828 | .collect(); |
| 2829 | assert_eq!(names, ["Ada Example", "Adam Directory"]); |
| 2830 | assert!( |
| 2831 | matches!(&found[0], MentionCandidate::Person(person) if person.source == PersonSource::Member) |
| 2832 | ); |
| 2833 | assert!( |
| 2834 | matches!(&found[1], MentionCandidate::Person(person) if person.source == PersonSource::Directory) |
| 2835 | ); |
| 2836 | |
| 2837 | engine.mention_candidates(CHAT, "ada", 10).await.unwrap(); |
| 2838 | engine.search_people("ADA").await.unwrap(); |
| 2839 | let searches = fake |
| 2840 | .calls() |
| 2841 | .into_iter() |
| 2842 | .filter(|call| call.starts_with("search")) |
| 2843 | .count(); |
| 2844 | assert_eq!(searches, 1); |
| 2845 | |
| 2846 | assert_eq!( |
| 2847 | engine |
| 2848 | .mention_candidates(CHAT, "ada", 1) |
| 2849 | .await |
| 2850 | .unwrap() |
| 2851 | .len(), |
| 2852 | 1 |
| 2853 | ); |
| 2854 | assert!(engine.mention_candidates("unknown", "a", 5).await.is_err()); |
| 2855 | } |
| 2856 | |
| 2857 | #[tokio::test] |
| 2858 | async fn channel_candidates_offer_recent_senders_the_channel_and_its_team() { |
| 2859 | let fake = Arc::new(Fake::default()); |
| 2860 | let engine = channel_engine(&fake).await; |
| 2861 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2862 | let all = engine.mention_candidates(CHANNEL, "", 10).await.unwrap(); |
| 2863 | assert_eq!(all.len(), 3); |
| 2864 | assert!(matches!(&all[0], MentionCandidate::Person(person) if person.user_id == "user-ada")); |
| 2865 | assert!( |
| 2866 | matches!(&all[1], MentionCandidate::Channel { channel_id, .. } if channel_id == CHANNEL) |
| 2867 | ); |
| 2868 | assert!(matches!(&all[2], MentionCandidate::Team { team_id, .. } if team_id == "team-1")); |
| 2869 | let squad = engine.mention_candidates(CHANNEL, "squ", 10).await.unwrap(); |
| 2870 | assert_eq!(squad[0].to_mention(), MentionInput::team("team-1", "Squad")); |
| 2871 | } |
| 2872 | |
| 2873 | #[tokio::test] |
| 2874 | async fn images_land_as_lru_files_and_are_served_by_path() { |
| 2875 | let directory = tempfile::tempdir().unwrap(); |
| 2876 | let fake = Arc::new(Fake::default()); |
| 2877 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 2878 | let engine = engine_with(&fake, small_pages()) |
| 2879 | .with_image_dir(directory.path(), 1024 * 1024) |
| 2880 | .unwrap(); |
| 2881 | engine.refresh_sidebar().await.unwrap(); |
| 2882 | let image = teams_core::ImageRef { |
| 2883 | id: "h1".to_owned(), |
| 2884 | url: HOSTED.to_owned(), |
| 2885 | width: None, |
| 2886 | height: None, |
| 2887 | }; |
| 2888 | assert!(engine.image_path(&image).is_none()); |
| 2889 | let mut events = engine.subscribe(); |
| 2890 | let path = engine.fetch_image(&image).await.unwrap().unwrap(); |
| 2891 | assert_eq!(path.extension().unwrap(), "png"); |
| 2892 | assert!(path.starts_with(directory.path())); |
| 2893 | assert_eq!(engine.image_path(&image), Some(path.clone())); |
| 2894 | assert_eq!(engine.fetch_image(&image).await.unwrap(), Some(path)); |
| 2895 | assert_eq!(fake.hosted_requests.lock().unwrap().len(), 1); |
| 2896 | assert!(matches!( |
| 2897 | events.try_recv().unwrap(), |
| 2898 | CoreEvent::ImagesChanged { .. } |
| 2899 | )); |
| 2900 | let stored = engine.image(HOSTED).unwrap(); |
| 2901 | assert_eq!((stored.width, stored.height), (Some(40), Some(20))); |
| 2902 | assert!(engine.store().image(HOSTED).unwrap().is_none()); |
| 2903 | } |
| 2904 | |
| 2905 | #[tokio::test] |
| 2906 | async fn a_read_chat_has_no_first_unread_message() { |
| 2907 | let fake = Arc::new(Fake::default()); |
| 2908 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 10, 10, "user-ada", false)]; |
| 2909 | fake.set_chat_messages(numbered(5)); |
| 2910 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2911 | engine.refresh_sidebar().await.unwrap(); |
| 2912 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2913 | assert!(engine.first_unread_message_id(CHAT).is_none()); |
| 2914 | } |
| 2915 | |
| 2916 | fn millis(minute: i64) -> i64 { |
| 2917 | (base() + Duration::minutes(minute)).timestamp_millis() |
| 2918 | } |
| 2919 | |
| 2920 | fn horizon_of(user: &str, read_minute: i64, at_minute: i64) -> chatsvc::MemberHorizon { |
| 2921 | chatsvc::receipts::parse_horizon( |
| 2922 | &format!("8:orgid:{user}"), |
| 2923 | &format!( |
| 2924 | "{};{};6638000000000000001", |
| 2925 | millis(read_minute), |
| 2926 | millis(at_minute) |
| 2927 | ), |
| 2928 | ) |
| 2929 | .unwrap() |
| 2930 | } |
| 2931 | |
| 2932 | fn own_message(id: u32, minute: i64) -> Message { |
| 2933 | serde_json::from_value(json!({ |
| 2934 | "id": format!("m{id:04}"), |
| 2935 | "messageType": "message", |
| 2936 | "createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(), |
| 2937 | "from": {"user": {"id": ME, "displayName": "Me Myself"}}, |
| 2938 | "body": {"contentType": "html", "content": "<p>mine</p>"}, |
| 2939 | })) |
| 2940 | .unwrap() |
| 2941 | } |
| 2942 | |
| 2943 | fn group_chat(id: &str) -> Chat { |
| 2944 | serde_json::from_value(json!({ |
| 2945 | "id": id, |
| 2946 | "topic": "Planning", |
| 2947 | "chatType": "group", |
| 2948 | "lastUpdatedDateTime": base().to_rfc3339(), |
| 2949 | "members": [ |
| 2950 | {"userId": ME, "displayName": "Me Myself"}, |
| 2951 | {"userId": "user-ada", "displayName": "Ada Example"}, |
| 2952 | {"userId": "user-bob", "displayName": "Bob Example"}, |
| 2953 | {"userId": "user-cy", "displayName": "Cy Example"} |
| 2954 | ], |
| 2955 | "viewpoint": {"lastMessageReadDateTime": base().to_rfc3339(), "isHidden": false}, |
| 2956 | })) |
| 2957 | .unwrap() |
| 2958 | } |
| 2959 | |
| 2960 | async fn receipt_engine(fake: &Arc<Fake>, chats: Vec<Chat>) -> SyncEngine<Handle> { |
| 2961 | *fake.chats.lock().unwrap() = chats; |
| 2962 | fake.set_chat_messages(vec![ |
| 2963 | own_message(1, 1), |
| 2964 | message(2, 2, "<p>theirs</p>"), |
| 2965 | own_message(3, 3), |
| 2966 | ]); |
| 2967 | let engine = engine_with(fake, small_pages()) |
| 2968 | .with_receipt_debounce(std::time::Duration::from_millis(60)); |
| 2969 | engine.refresh_sidebar().await.unwrap(); |
| 2970 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2971 | engine |
| 2972 | } |
| 2973 | |
| 2974 | fn one_on_one() -> Chat { |
| 2975 | chat(CHAT, None, 5, 5, ME, false) |
| 2976 | } |
| 2977 | |
| 2978 | #[tokio::test] |
| 2979 | async fn one_on_one_read_up_to_horizon() { |
| 2980 | let fake = Arc::new(Fake::default()); |
| 2981 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 2982 | *fake.horizons.lock().unwrap() = |
| 2983 | vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 2, 9)]; |
| 2984 | let mut events = engine.subscribe(); |
| 2985 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 2986 | assert_eq!( |
| 2987 | events.try_recv().unwrap(), |
| 2988 | CoreEvent::ReceiptsChanged { |
| 2989 | conversation_id: CHAT.into() |
| 2990 | } |
| 2991 | ); |
| 2992 | assert_eq!( |
| 2993 | engine.receipt_state(CHAT, "m0001"), |
| 2994 | teams_core::ReceiptState::Read { |
| 2995 | readers: vec![teams_core::ReceiptReader { |
| 2996 | name: "Ada Example".into(), |
| 2997 | at: base() + Duration::minutes(9), |
| 2998 | }], |
| 2999 | total_others: 1, |
| 3000 | } |
| 3001 | ); |
| 3002 | assert_eq!( |
| 3003 | engine.receipt_state(CHAT, "m0003"), |
| 3004 | teams_core::ReceiptState::Sent |
| 3005 | ); |
| 3006 | assert_eq!( |
| 3007 | engine.receipt_state(CHAT, "m0002"), |
| 3008 | teams_core::ReceiptState::Unknown |
| 3009 | ); |
| 3010 | assert_eq!( |
| 3011 | engine.receipt_state(CHAT, "missing"), |
| 3012 | teams_core::ReceiptState::Unknown |
| 3013 | ); |
| 3014 | } |
| 3015 | |
| 3016 | #[tokio::test] |
| 3017 | async fn horizon_equal_to_creation_time_counts_as_read() { |
| 3018 | let fake = Arc::new(Fake::default()); |
| 3019 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3020 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 3)]; |
| 3021 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3022 | assert!(matches!( |
| 3023 | engine.receipt_state(CHAT, "m0003"), |
| 3024 | teams_core::ReceiptState::Read { .. } |
| 3025 | )); |
| 3026 | } |
| 3027 | |
| 3028 | #[tokio::test] |
| 3029 | async fn nobody_read_means_sent() { |
| 3030 | let fake = Arc::new(Fake::default()); |
| 3031 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3032 | *fake.horizons.lock().unwrap() = |
| 3033 | vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 0, 0)]; |
| 3034 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3035 | assert_eq!( |
| 3036 | engine.receipt_state(CHAT, "m0001"), |
| 3037 | teams_core::ReceiptState::Sent |
| 3038 | ); |
| 3039 | assert_eq!( |
| 3040 | engine.receipt_state(CHAT, "m0003"), |
| 3041 | teams_core::ReceiptState::Sent |
| 3042 | ); |
| 3043 | } |
| 3044 | |
| 3045 | #[tokio::test] |
| 3046 | async fn group_partial_read_lists_who_and_total() { |
| 3047 | let fake = Arc::new(Fake::default()); |
| 3048 | let engine = receipt_engine(&fake, vec![group_chat(CHAT)]).await; |
| 3049 | *fake.horizons.lock().unwrap() = vec![ |
| 3050 | horizon_of("user-me", 3, 3), |
| 3051 | horizon_of("user-cy", 3, 8), |
| 3052 | horizon_of("user-ada", 1, 6), |
| 3053 | horizon_of("user-bob", 0, 0), |
| 3054 | ]; |
| 3055 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3056 | let names = |state: teams_core::ReceiptState| match state { |
| 3057 | teams_core::ReceiptState::Read { |
| 3058 | readers, |
| 3059 | total_others, |
| 3060 | } => ( |
| 3061 | readers |
| 3062 | .into_iter() |
| 3063 | .map(|reader| reader.name) |
| 3064 | .collect::<Vec<_>>(), |
| 3065 | total_others, |
| 3066 | ), |
| 3067 | other => panic!("expected read, got {other:?}"), |
| 3068 | }; |
| 3069 | assert_eq!( |
| 3070 | names(engine.receipt_state(CHAT, "m0001")), |
| 3071 | (vec!["Ada Example".to_owned(), "Cy Example".to_owned()], 3) |
| 3072 | ); |
| 3073 | assert_eq!( |
| 3074 | names(engine.receipt_state(CHAT, "m0003")), |
| 3075 | (vec!["Cy Example".to_owned()], 3) |
| 3076 | ); |
| 3077 | } |
| 3078 | |
| 3079 | #[tokio::test] |
| 3080 | async fn disabled_receipts_are_unknown() { |
| 3081 | let fake = Arc::new(Fake::default()); |
| 3082 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3083 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3084 | assert_eq!( |
| 3085 | engine.receipt_state(CHAT, "m0001"), |
| 3086 | teams_core::ReceiptState::Unknown |
| 3087 | ); |
| 3088 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-me", 3, 3)]; |
| 3089 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3090 | assert_eq!( |
| 3091 | engine.receipt_state(CHAT, "m0001"), |
| 3092 | teams_core::ReceiptState::Unknown |
| 3093 | ); |
| 3094 | } |
| 3095 | |
| 3096 | #[tokio::test] |
| 3097 | async fn disabling_after_reading_clears_the_state_and_announces() { |
| 3098 | let fake = Arc::new(Fake::default()); |
| 3099 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3100 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 3)]; |
| 3101 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3102 | let mut events = engine.subscribe(); |
| 3103 | fake.horizons.lock().unwrap().clear(); |
| 3104 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3105 | assert_eq!( |
| 3106 | events.try_recv().unwrap(), |
| 3107 | CoreEvent::ReceiptsChanged { |
| 3108 | conversation_id: CHAT.into() |
| 3109 | } |
| 3110 | ); |
| 3111 | assert_eq!( |
| 3112 | engine.receipt_state(CHAT, "m0001"), |
| 3113 | teams_core::ReceiptState::Unknown |
| 3114 | ); |
| 3115 | } |
| 3116 | |
| 3117 | #[tokio::test] |
| 3118 | async fn unchanged_horizons_announce_nothing() { |
| 3119 | let fake = Arc::new(Fake::default()); |
| 3120 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3121 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 3)]; |
| 3122 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3123 | let mut events = engine.subscribe(); |
| 3124 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3125 | assert!(events.try_recv().is_err()); |
| 3126 | } |
| 3127 | |
| 3128 | #[tokio::test] |
| 3129 | async fn channels_and_deleted_messages_have_no_state() { |
| 3130 | let fake = Arc::new(Fake::default()); |
| 3131 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3132 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 3)]; |
| 3133 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3134 | let mut deleted = engine.open_conversation(CHAT).unwrap().remove(0); |
| 3135 | deleted.deleted = true; |
| 3136 | assert_eq!( |
| 3137 | engine.receipt_state_for(&deleted), |
| 3138 | teams_core::ReceiptState::Unknown |
| 3139 | ); |
| 3140 | engine.refresh_receipts(CHANNEL).await.unwrap_err(); |
| 3141 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 1); |
| 3142 | } |
| 3143 | |
| 3144 | #[tokio::test] |
| 3145 | async fn read_event_burst_triggers_one_fetch() { |
| 3146 | let fake = Arc::new(Fake::default()); |
| 3147 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3148 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 1, 4)]; |
| 3149 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3150 | let before = *fake.horizon_calls.lock().unwrap(); |
| 3151 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 7)]; |
| 3152 | let event = read_event(Some(CHAT)); |
| 3153 | let started = std::time::Instant::now(); |
| 3154 | tokio::join!( |
| 3155 | engine.handle_receipt_event(&event), |
| 3156 | engine.handle_receipt_event(&event), |
| 3157 | engine.handle_receipt_event(&event), |
| 3158 | ); |
| 3159 | assert!(started.elapsed() >= std::time::Duration::from_millis(60)); |
| 3160 | assert_eq!(*fake.horizon_calls.lock().unwrap(), before + 1); |
| 3161 | assert!(matches!( |
| 3162 | engine.receipt_state(CHAT, "m0003"), |
| 3163 | teams_core::ReceiptState::Read { .. } |
| 3164 | )); |
| 3165 | } |
| 3166 | |
| 3167 | fn read_event(conversation_id: Option<&str>) -> chatsvc::MessageEvent { |
| 3168 | chatsvc::MessageEvent { |
| 3169 | resource_type: "NewMessage".into(), |
| 3170 | kind: chatsvc::EventKind::ReadReceipt, |
| 3171 | conversation_id: conversation_id.map(str::to_owned), |
| 3172 | message_id: None, |
| 3173 | received_at: base(), |
| 3174 | } |
| 3175 | } |
| 3176 | |
| 3177 | #[tokio::test] |
| 3178 | async fn events_for_other_kinds_or_unopened_chats_do_nothing() { |
| 3179 | let fake = Arc::new(Fake::default()); |
| 3180 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3181 | let mut typing = read_event(Some(CHAT)); |
| 3182 | typing.kind = chatsvc::EventKind::Typing; |
| 3183 | engine.handle_receipt_event(&typing).await; |
| 3184 | engine.handle_receipt_event(&read_event(Some(CHAT))).await; |
| 3185 | engine.handle_receipt_event(&read_event(None)).await; |
| 3186 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 0); |
| 3187 | } |
| 3188 | |
| 3189 | #[tokio::test] |
| 3190 | async fn reconnect_refetches_known_chats_only() { |
| 3191 | let fake = Arc::new(Fake::default()); |
| 3192 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 3193 | let status = |kind| chatsvc::StatusEvent { |
| 3194 | kind, |
| 3195 | detail: String::new(), |
| 3196 | }; |
| 3197 | engine |
| 3198 | .handle_receipt_status(&status(chatsvc::StatusKind::Connected)) |
| 3199 | .await; |
| 3200 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 0); |
| 3201 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 1, 4)]; |
| 3202 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 3203 | engine |
| 3204 | .handle_receipt_status(&status(chatsvc::StatusKind::Disconnected)) |
| 3205 | .await; |
| 3206 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 1); |
| 3207 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 7)]; |
| 3208 | let mut events = engine.subscribe(); |
| 3209 | engine |
| 3210 | .handle_receipt_status(&status(chatsvc::StatusKind::MessageLoss)) |
| 3211 | .await; |
| 3212 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 2); |
| 3213 | assert!(matches!( |
| 3214 | events.try_recv().unwrap(), |
| 3215 | CoreEvent::ReceiptsChanged { .. } |
| 3216 | )); |
| 3217 | } |
| 3218 | |
| 3219 | const BOT_GUID: &str = "0000aaaa-0000-0000-0000-000000000001"; |
| 3220 | |
| 3221 | fn chat_app(app_id: &str, name: &str, bot_ids: &[&str]) -> chatsvc::ChatApp { |
| 3222 | chatsvc::ChatApp { |
| 3223 | app_id: app_id.to_owned(), |
| 3224 | name: name.to_owned(), |
| 3225 | bot_ids: bot_ids.iter().map(|bot| (*bot).to_owned()).collect(), |
| 3226 | small_image_url: None, |
| 3227 | accent_color: None, |
| 3228 | web_application_resource: None, |
| 3229 | } |
| 3230 | } |
| 3231 | |
| 3232 | fn bot_message(application_id: &str) -> Message { |
| 3233 | serde_json::from_value(json!({ |
| 3234 | "id": "m0001", |
| 3235 | "messageType": "message", |
| 3236 | "createdDateTime": base().to_rfc3339(), |
| 3237 | "from": {"application": {"id": application_id, "displayName": "Wiki Bot"}}, |
| 3238 | "body": {"contentType": "html", "content": "<attachment id=\"a1\"></attachment>"}, |
| 3239 | })) |
| 3240 | .unwrap() |
| 3241 | } |
| 3242 | |
| 3243 | async fn card_engine(fake: &Arc<Fake>, application_id: &str) -> SyncEngine<Handle> { |
| 3244 | let engine = chat_engine(fake, small_pages()).await; |
| 3245 | fake.set_chat_messages(vec![bot_message(application_id)]); |
| 3246 | engine.fetch_newer(CHAT).await.unwrap(); |
| 3247 | engine |
| 3248 | } |
| 3249 | |
| 3250 | fn submit_action(data: serde_json::Value) -> teams_core::CardAction { |
| 3251 | let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [ |
| 3252 | {"type": "Action.Submit", "title": "Go", "data": data} |
| 3253 | ]}); |
| 3254 | teams_core::AdaptiveCard::parse(&card.to_string()) |
| 3255 | .unwrap() |
| 3256 | .actions |
| 3257 | .remove(0) |
| 3258 | } |
| 3259 | |
| 3260 | #[tokio::test] |
| 3261 | async fn card_submit_invokes_the_matching_bot_and_caches_the_apps() { |
| 3262 | let fake = Arc::new(Fake::default()); |
| 3263 | *fake.apps.lock().unwrap() = vec![ |
| 3264 | chat_app( |
| 3265 | "app-other", |
| 3266 | "Other", |
| 3267 | &["0000bbbb-0000-0000-0000-000000000002"], |
| 3268 | ), |
| 3269 | chat_app("app-wiki", "Wiki", &[BOT_GUID]), |
| 3270 | ]; |
| 3271 | let engine = card_engine(&fake, BOT_GUID).await; |
| 3272 | let action = submit_action(json!({"type": "unwatch"})); |
| 3273 | |
| 3274 | let first = engine.card_action(CHAT, "m0001", &action).await.unwrap(); |
| 3275 | let second = engine.card_action(CHAT, "m0001", &action).await.unwrap(); |
| 3276 | |
| 3277 | assert_eq!(first, teams_core::CardActionOutcome::Sent); |
| 3278 | assert_eq!(second, first); |
| 3279 | assert_eq!(*fake.app_calls.lock().unwrap(), 1); |
| 3280 | let invokes = fake.invokes.lock().unwrap(); |
| 3281 | assert_eq!(invokes[0].app_id, "app-wiki"); |
| 3282 | assert_eq!(invokes[0].bot_id, BOT_GUID); |
| 3283 | assert_eq!(invokes[0].name, "messageback"); |
| 3284 | assert_eq!(invokes[0].value, json!({"type": "unwatch"})); |
| 3285 | assert_eq!(invokes[0].server_message_id, "m0001"); |
| 3286 | assert_eq!(invokes[0].conversation_id, CHAT); |
| 3287 | assert_eq!(invokes[0].display_name, "Me Myself"); |
| 3288 | } |
| 3289 | |
| 3290 | #[tokio::test] |
| 3291 | async fn card_action_falls_back_to_the_only_bot_app() { |
| 3292 | let fake = Arc::new(Fake::default()); |
| 3293 | *fake.apps.lock().unwrap() = vec![ |
| 3294 | chat_app("app-tabs", "Tabs", &[]), |
| 3295 | chat_app("app-wiki", "Wiki", &[BOT_GUID]), |
| 3296 | ]; |
| 3297 | let engine = card_engine(&fake, "unrelated-id").await; |
| 3298 | engine |
| 3299 | .card_action(CHAT, "m0001", &submit_action(json!({}))) |
| 3300 | .await |
| 3301 | .unwrap(); |
| 3302 | let invokes = fake.invokes.lock().unwrap(); |
| 3303 | assert_eq!(invokes[0].app_id, "app-wiki"); |
| 3304 | assert_eq!(invokes[0].bot_id, BOT_GUID); |
| 3305 | } |
| 3306 | |
| 3307 | #[tokio::test] |
| 3308 | async fn card_action_with_several_unmatched_bot_apps_is_an_error() { |
| 3309 | let fake = Arc::new(Fake::default()); |
| 3310 | *fake.apps.lock().unwrap() = vec![ |
| 3311 | chat_app("app-one", "One", &["bot-1"]), |
| 3312 | chat_app("app-two", "Two", &["bot-2"]), |
| 3313 | ]; |
| 3314 | let engine = card_engine(&fake, "unrelated-id").await; |
| 3315 | let outcome = engine |
| 3316 | .card_action(CHAT, "m0001", &submit_action(json!({}))) |
| 3317 | .await; |
| 3318 | assert!(outcome.is_err()); |
| 3319 | assert!(fake.invokes.lock().unwrap().is_empty()); |
| 3320 | } |
| 3321 | |
| 3322 | #[tokio::test] |
| 3323 | async fn card_answers_map_to_outcomes() { |
| 3324 | use chatsvc::{InvokeResponse, TaskContent, TaskContinue, TaskResponse}; |
| 3325 | use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind}; |
| 3326 | |
| 3327 | let fake = Arc::new(Fake::default()); |
| 3328 | *fake.apps.lock().unwrap() = vec![chat_app("app-wiki", "Wiki", &[BOT_GUID])]; |
| 3329 | let engine = card_engine(&fake, BOT_GUID).await; |
| 3330 | let action = submit_action(json!({"msteams": {"type": "task/fetch"}})); |
| 3331 | let answers = [ |
| 3332 | ( |
| 3333 | InvokeResponse::Card(json!({"type": "AdaptiveCard"})), |
| 3334 | CardActionOutcome::ReplaceCard(json!({"type": "AdaptiveCard"}).to_string()), |
| 3335 | ), |
| 3336 | ( |
| 3337 | InvokeResponse::Message("Saved".into()), |
| 3338 | CardActionOutcome::Message("Saved".into()), |
| 3339 | ), |
| 3340 | ( |
| 3341 | InvokeResponse::Task(TaskResponse::Message("Done".into())), |
| 3342 | CardActionOutcome::Message("Done".into()), |
| 3343 | ), |
| 3344 | ( |
| 3345 | InvokeResponse::Failed { |
| 3346 | status_code: 500, |
| 3347 | message: "Broken".into(), |
| 3348 | }, |
| 3349 | CardActionOutcome::Failed("The app answered 500: Broken".into()), |
| 3350 | ), |
| 3351 | ( |
| 3352 | InvokeResponse::Task(TaskResponse::Continue(TaskContinue { |
| 3353 | title: Some("Settings".into()), |
| 3354 | width: None, |
| 3355 | height: Some(300), |
| 3356 | content: TaskContent::Url { |
| 3357 | url: "https://bot.example/task".into(), |
| 3358 | fallback_url: None, |
| 3359 | }, |
| 3360 | })), |
| 3361 | CardActionOutcome::Dialog(TaskDialog { |
| 3362 | title: Some("Settings".into()), |
| 3363 | width: 520, |
| 3364 | height: 300, |
| 3365 | kind: TaskDialogKind::Url { |
| 3366 | url: "https://bot.example/task".into(), |
| 3367 | fallback_url: "https://bot.example/task".into(), |
| 3368 | }, |
| 3369 | }), |
| 3370 | ), |
| 3371 | ( |
| 3372 | InvokeResponse::Task(TaskResponse::Continue(TaskContinue { |
| 3373 | title: None, |
| 3374 | width: Some(600), |
| 3375 | height: Some(400), |
| 3376 | content: TaskContent::Card(json!({"type": "AdaptiveCard"})), |
| 3377 | })), |
| 3378 | CardActionOutcome::Dialog(TaskDialog { |
| 3379 | title: None, |
| 3380 | width: 600, |
| 3381 | height: 400, |
| 3382 | kind: TaskDialogKind::Card(json!({"type": "AdaptiveCard"}).to_string()), |
| 3383 | }), |
| 3384 | ), |
| 3385 | ]; |
| 3386 | for (answer, expected) in answers { |
| 3387 | *fake.invoke_answer.lock().unwrap() = Some(answer); |
| 3388 | assert_eq!( |
| 3389 | engine.card_action(CHAT, "m0001", &action).await.unwrap(), |
| 3390 | expected |
| 3391 | ); |
| 3392 | } |
| 3393 | assert_eq!(fake.invokes.lock().unwrap()[0].name, "task/fetch"); |
| 3394 | } |
| 3395 | |
| 3396 | #[tokio::test] |
| 3397 | async fn task_submit_wraps_the_data_for_the_dialog() { |
| 3398 | let fake = Arc::new(Fake::default()); |
| 3399 | *fake.apps.lock().unwrap() = vec![chat_app("app-wiki", "Wiki", &[BOT_GUID])]; |
| 3400 | let engine = card_engine(&fake, BOT_GUID).await; |
| 3401 | engine |
| 3402 | .task_submit(CHAT, "m0001", json!({"choice": "a"})) |
| 3403 | .await |
| 3404 | .unwrap(); |
| 3405 | let invokes = fake.invokes.lock().unwrap(); |
| 3406 | assert_eq!(invokes[0].name, "task/submit"); |
| 3407 | assert_eq!( |
| 3408 | invokes[0].value, |
| 3409 | json!({"data": {"choice": "a"}, "context": {"theme": "dark"}}) |
| 3410 | ); |
| 3411 | } |
| 3412 | |
| 3413 | #[tokio::test] |
| 3414 | async fn dialog_identity_names_the_user_and_the_tenant() { |
| 3415 | let fake = Arc::new(Fake::default()); |
| 3416 | let engine = card_engine(&fake, BOT_GUID).await; |
| 3417 | let identity = engine.dialog_identity(CHAT).await.unwrap(); |
| 3418 | assert_eq!(identity.user_id, ME); |
| 3419 | assert_eq!(identity.display_name, "Me Myself"); |
| 3420 | assert_eq!(identity.tenant_id, "tenant-1"); |
| 3421 | } |
| 3422 | |
| 3423 | #[tokio::test] |
| 3424 | async fn card_actions_without_a_payload_are_rejected() { |
| 3425 | let fake = Arc::new(Fake::default()); |
| 3426 | let engine = card_engine(&fake, BOT_GUID).await; |
| 3427 | let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [ |
| 3428 | {"type": "Action.OpenUrl", "title": "Open", "url": "https://example.com"} |
| 3429 | ]}); |
| 3430 | let action = teams_core::AdaptiveCard::parse(&card.to_string()) |
| 3431 | .unwrap() |
| 3432 | .actions |
| 3433 | .remove(0); |
| 3434 | assert!(engine.card_action(CHAT, "m0001", &action).await.is_err()); |
| 3435 | } |
| 3436 | |
| 3437 | #[tokio::test] |
| 3438 | async fn bot_messages_remember_their_application() { |
| 3439 | let fake = Arc::new(Fake::default()); |
| 3440 | let engine = card_engine(&fake, BOT_GUID).await; |
| 3441 | let record = engine.open_conversation(CHAT).unwrap().remove(0); |
| 3442 | assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID)); |
| 3443 | assert_eq!(record.sender_id, None); |
| 3444 | } |
| 3445 | |
| 3446 | const PREVIEW_LINKS: &str = |
| 3447 | r#"[{"url":"https://a.example/x","preview":{"title":"Example"},"previewenabled":true}]"#; |
| 3448 | |
| 3449 | #[tokio::test] |
| 3450 | async fn links_from_the_chat_service_survive_the_next_graph_sync() { |
| 3451 | let fake = Arc::new(Fake::default()); |
| 3452 | let engine = chat_engine(&fake, small_pages()).await; |
| 3453 | fake.set_chat_messages(vec![message( |
| 3454 | 1, |
| 3455 | 1, |
| 3456 | "<p><a href=\"https://a.example/x\">link</a></p>", |
| 3457 | )]); |
| 3458 | *fake.link_pages.lock().unwrap() = vec![chatsvc::MessageLinks { |
| 3459 | message_id: "m0001".into(), |
| 3460 | links_json: PREVIEW_LINKS.into(), |
| 3461 | }]; |
| 3462 | |
| 3463 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 3464 | assert_eq!(delta.added[0].links_json, PREVIEW_LINKS); |
| 3465 | assert_eq!( |
| 3466 | engine.open_conversation(CHAT).unwrap()[0].links_json, |
| 3467 | PREVIEW_LINKS |
| 3468 | ); |
| 3469 | assert_eq!(*fake.link_page_calls.lock().unwrap(), [CHAT]); |
| 3470 | |
| 3471 | let again = engine.fetch_newer(CHAT).await.unwrap(); |
| 3472 | assert!(again.is_empty()); |
| 3473 | assert_eq!( |
| 3474 | engine.open_conversation(CHAT).unwrap()[0].links_json, |
| 3475 | PREVIEW_LINKS |
| 3476 | ); |
| 3477 | } |
| 3478 | |
| 3479 | #[tokio::test] |
| 3480 | async fn messages_without_anchors_do_not_ask_the_chat_service() { |
| 3481 | let fake = Arc::new(Fake::default()); |
| 3482 | let engine = chat_engine(&fake, small_pages()).await; |
| 3483 | fake.set_chat_messages(vec![message(1, 1, "<p>plain</p>")]); |
| 3484 | engine.fetch_newer(CHAT).await.unwrap(); |
| 3485 | assert!(fake.link_page_calls.lock().unwrap().is_empty()); |
| 3486 | } |
| 3487 | |
| 3488 | #[tokio::test] |
| 3489 | async fn a_failing_chat_service_leaves_no_preview() { |
| 3490 | let fake = Arc::new(Fake::default()); |
| 3491 | let engine = chat_engine(&fake, small_pages()).await; |
| 3492 | fake.set_chat_messages(vec![message(1, 1, "<a href=\"https://a.example\">x</a>")]); |
| 3493 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 3494 | assert_eq!(delta.added[0].links_json, "[]"); |
| 3495 | } |
| 3496 | |
| 3497 | #[tokio::test] |
| 3498 | async fn attaching_a_preview_puts_the_links_and_keeps_them_locally() { |
| 3499 | let fake = Arc::new(Fake::default()); |
| 3500 | let engine = chat_engine(&fake, small_pages()).await; |
| 3501 | let sent = engine |
| 3502 | .send_message_with_mentions(CHAT, "see https://a.example/x", None, &[]) |
| 3503 | .await |
| 3504 | .unwrap(); |
| 3505 | let preview = engine |
| 3506 | .link_preview_for("https://a.example/x") |
| 3507 | .await |
| 3508 | .unwrap() |
| 3509 | .unwrap(); |
| 3510 | |
| 3511 | engine |
| 3512 | .attach_link_preview(CHAT, &sent.message_id, &preview) |
| 3513 | .await |
| 3514 | .unwrap(); |
| 3515 | |
| 3516 | let put = fake.links_put.lock().unwrap().clone(); |
| 3517 | assert_eq!(put.len(), 1); |
| 3518 | assert_eq!(put[0].0, sent.message_id); |
| 3519 | assert!(put[0].1.contains("\"itemid\":\"0\"")); |
| 3520 | let stored = engine |
| 3521 | .store() |
| 3522 | .messages_by_id(CHAT, std::slice::from_ref(&sent.message_id)) |
| 3523 | .unwrap(); |
| 3524 | assert_eq!(stored[&sent.message_id].links_json, put[0].1); |
| 3525 | } |
| 3526 | |
| 3527 | #[tokio::test] |
| 3528 | async fn link_infos_are_fetched_once_per_url_and_internal_links_never() { |
| 3529 | let fake = Arc::new(Fake::default()); |
| 3530 | let engine = chat_engine(&fake, small_pages()).await; |
| 3531 | for _ in 0..2 { |
| 3532 | engine |
| 3533 | .link_preview_for("https://a.example/x") |
| 3534 | .await |
| 3535 | .unwrap(); |
| 3536 | } |
| 3537 | assert!( |
| 3538 | engine |
| 3539 | .link_preview_for("https://contoso.sharepoint.com/x") |
| 3540 | .await |
| 3541 | .unwrap() |
| 3542 | .is_none() |
| 3543 | ); |
| 3544 | assert_eq!(*fake.link_info_calls.lock().unwrap(), 1); |
| 3545 | } |
| 3546 | |
| 3547 | #[tokio::test] |
| 3548 | async fn schedule_message_resolves_the_inner_thread_id() { |
| 3549 | let fake = Arc::new(Fake::default()); |
| 3550 | *fake.teams.lock().unwrap() = |
| 3551 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 3552 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 3553 | let engine = engine_with(&fake, small_pages()); |
| 3554 | engine.refresh_sidebar().await.unwrap(); |
| 3555 | let send_at = base() + Duration::days(1); |
| 3556 | |
| 3557 | let draft = engine |
| 3558 | .schedule_message(CHAT, None, "<p>a</p>", send_at) |
| 3559 | .await |
| 3560 | .unwrap(); |
| 3561 | assert_eq!(draft.id, "d1"); |
| 3562 | engine |
| 3563 | .schedule_message(CHANNEL, None, "<p>b</p>", send_at) |
| 3564 | .await |
| 3565 | .unwrap(); |
| 3566 | engine |
| 3567 | .schedule_message(CHANNEL, Some("m0030"), "<p>c</p>", send_at) |
| 3568 | .await |
| 3569 | .unwrap(); |
| 3570 | |
| 3571 | let created = fake.scheduled.lock().unwrap().clone(); |
| 3572 | let thread_ids: Vec<&str> = created.iter().map(|entry| entry.0.as_str()).collect(); |
| 3573 | assert_eq!( |
| 3574 | thread_ids, |
| 3575 | [CHAT, CHANNEL, "19:channel@thread.tacv2;messageid=m0030"] |
| 3576 | ); |
| 3577 | assert_eq!(created[0].3, "Me Myself"); |
| 3578 | } |
| 3579 | |
| 3580 | #[tokio::test] |
| 3581 | async fn schedule_message_rejects_notes_and_chat_threads() { |
| 3582 | let fake = Arc::new(Fake::default()); |
| 3583 | let engine = chat_engine(&fake, small_pages()).await; |
| 3584 | let send_at = base(); |
| 3585 | assert!(matches!( |
| 3586 | engine |
| 3587 | .schedule_message(teams_core::NOTES_CHAT_ID, None, "<p>a</p>", send_at) |
| 3588 | .await, |
| 3589 | Err(Error::Unsupported(_)) |
| 3590 | )); |
| 3591 | assert!(matches!( |
| 3592 | engine |
| 3593 | .schedule_message(CHAT, Some("m1"), "<p>a</p>", send_at) |
| 3594 | .await, |
| 3595 | Err(Error::Unsupported(_)) |
| 3596 | )); |
| 3597 | assert!(fake.scheduled.lock().unwrap().is_empty()); |
| 3598 | } |
| 3599 | |
| 3600 | #[tokio::test] |
| 3601 | async fn mark_unread_from_a_message_backs_up_one_millisecond() { |
| 3602 | let fake = Arc::new(Fake::default()); |
| 3603 | let engine = chat_engine(&fake, small_pages()).await; |
| 3604 | let created_at = base() + Duration::minutes(2); |
| 3605 | engine.mark_unread_from(CHAT, created_at).await.unwrap(); |
| 3606 | assert_eq!( |
| 3607 | fake.calls().last().unwrap(), |
| 3608 | &format!( |
| 3609 | "mark_unread {CHAT} {ME} tenant-1 {}", |
| 3610 | created_at.timestamp_millis() - 1 |
| 3611 | ) |
| 3612 | ); |
| 3613 | } |
| 3614 | |
| 3615 | #[tokio::test] |
| 3616 | async fn forward_converts_the_comment_and_fetches_the_target() { |
| 3617 | let fake = Arc::new(Fake::default()); |
| 3618 | let engine = chat_engine(&fake, small_pages()).await; |
| 3619 | fake.set_chat_messages(vec![message(1, 1, "<p>one</p>")]); |
| 3620 | let ids = vec!["m0001".to_owned(), "m0002".to_owned()]; |
| 3621 | let result = engine |
| 3622 | .forward_messages("19:source@thread.v2", CHAT, &ids, "**fyi**") |
| 3623 | .await |
| 3624 | .unwrap(); |
| 3625 | assert_eq!(result.message_id, "99"); |
| 3626 | assert_eq!( |
| 3627 | fake.calls().last().unwrap(), |
| 3628 | &format!( |
| 3629 | "forward 19:source@thread.v2 {CHAT} m0001,m0002 {}", |
| 3630 | teams_core::markdown_to_html("**fyi**") |
| 3631 | ) |
| 3632 | ); |
| 3633 | assert_eq!(engine.open_conversation(CHAT).unwrap().len(), 1); |
| 3634 | engine |
| 3635 | .forward_messages("19:source@thread.v2", CHAT, &ids, "") |
| 3636 | .await |
| 3637 | .unwrap(); |
| 3638 | assert_eq!( |
| 3639 | fake.calls().last().unwrap(), |
| 3640 | &format!("forward 19:source@thread.v2 {CHAT} m0001,m0002 ") |
| 3641 | ); |
| 3642 | } |
| 3643 | |
| 3644 | #[tokio::test] |
| 3645 | async fn save_uses_the_message_id_as_root_in_chats() { |
| 3646 | let fake = Arc::new(Fake::default()); |
| 3647 | let engine = chat_engine(&fake, small_pages()).await; |
| 3648 | engine.set_saved(CHAT, "5", None, true).await.unwrap(); |
| 3649 | assert_eq!( |
| 3650 | fake.calls().last().unwrap(), |
| 3651 | &format!("save {CHAT} 5 5 true") |
| 3652 | ); |
| 3653 | engine |
| 3654 | .set_saved(CHANNEL, "7", Some("3"), false) |
| 3655 | .await |
| 3656 | .unwrap(); |
| 3657 | assert_eq!( |
| 3658 | fake.calls().last().unwrap(), |
| 3659 | &format!("save {CHANNEL} 3 7 false") |
| 3660 | ); |
| 3661 | } |
| 3662 | |
| 3663 | #[tokio::test] |
| 3664 | async fn pinning_announces_and_is_refused_in_channels() { |
| 3665 | let fake = Arc::new(Fake::default()); |
| 3666 | let engine = channel_engine(&fake).await; |
| 3667 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 3668 | engine.refresh_sidebar().await.unwrap(); |
| 3669 | let mut events = engine.subscribe(); |
| 3670 | engine.pin_message(CHAT, "5").await.unwrap(); |
| 3671 | assert_eq!( |
| 3672 | events.try_recv().unwrap(), |
| 3673 | CoreEvent::PinsChanged { |
| 3674 | conversation_id: CHAT.to_owned() |
| 3675 | } |
| 3676 | ); |
| 3677 | engine |
| 3678 | .unpin_message(CHAT, "5", Some("folder-1")) |
| 3679 | .await |
| 3680 | .unwrap(); |
| 3681 | assert_eq!( |
| 3682 | fake.calls().last().unwrap(), |
| 3683 | &format!("unpin {CHAT} 5 Some(\"folder-1\")") |
| 3684 | ); |
| 3685 | assert!(matches!( |
| 3686 | engine.pin_message(CHANNEL, "5").await, |
| 3687 | Err(Error::Unsupported(_)) |
| 3688 | )); |
| 3689 | } |
| 3690 | |
| 3691 | #[tokio::test] |
| 3692 | async fn pin_events_become_core_events() { |
| 3693 | let fake = Arc::new(Fake::default()); |
| 3694 | let engine = chat_engine(&fake, small_pages()).await; |
| 3695 | let mut events = engine.subscribe(); |
| 3696 | let mut event = read_event(Some(CHAT)); |
| 3697 | engine.handle_pin_event(&event); |
| 3698 | assert!(events.try_recv().is_err()); |
| 3699 | event.kind = chatsvc::EventKind::PinsChanged; |
| 3700 | engine.handle_pin_event(&event); |
| 3701 | assert_eq!( |
| 3702 | events.try_recv().unwrap(), |
| 3703 | CoreEvent::PinsChanged { |
| 3704 | conversation_id: CHAT.to_owned() |
| 3705 | } |
| 3706 | ); |
| 3707 | } |
| 3708 | |
| 3709 | #[tokio::test] |
| 3710 | async fn message_links_resolve_chat_notes_and_channel() { |
| 3711 | let fake = Arc::new(Fake::default()); |
| 3712 | let engine = channel_engine(&fake).await; |
| 3713 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 3714 | engine.refresh_sidebar().await.unwrap(); |
| 3715 | assert_eq!( |
| 3716 | engine.message_link(CHAT, "5").await.unwrap(), |
| 3717 | teams_core::chat_message_link(CHAT, "5", None) |
| 3718 | ); |
| 3719 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 3720 | let root = engine.open_conversation(CHANNEL).unwrap()[0].clone(); |
| 3721 | assert_eq!( |
| 3722 | engine |
| 3723 | .message_link(CHANNEL, &root.message_id) |
| 3724 | .await |
| 3725 | .unwrap(), |
| 3726 | teams_core::channel_message_link(&teams_core::ChannelLinkInput { |
| 3727 | tenant_id: "tenant-1".into(), |
| 3728 | group_id: "team-1".into(), |
| 3729 | channel_id: CHANNEL.into(), |
| 3730 | team_name: "Squad".into(), |
| 3731 | channel_name: "General".into(), |
| 3732 | root_id: root.message_id.clone(), |
| 3733 | message_id: root.message_id.clone(), |
| 3734 | created_ms: root.created_at.timestamp_millis(), |
| 3735 | }) |
| 3736 | ); |
| 3737 | } |