| 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::{ |
| 12 | ChannelLayoutRecord, ChannelRecord, ChannelTabRecord, Store, TeamLayoutRecord, TeamRecord, |
| 13 | }; |
| 14 | use teams_core::{ |
| 15 | Availability, BoxFuture, ChatFolder, ChatSection, ChatSectionSettings, ChatsPage, CoreEvent, |
| 16 | DeltaPage, Error, FolderChange, FolderKind, FolderSource, MentionCandidate, MentionInput, |
| 17 | MentionTarget, NOTES_CHAT_ID, PersonSource, Remote, RemotePage, Result, SyncConfig, SyncEngine, |
| 18 | substrate_search, |
| 19 | }; |
| 20 | |
| 21 | const ME: &str = "user-me"; |
| 22 | const CHAT: &str = "19:chat@thread.v2"; |
| 23 | const CHANNEL: &str = "19:channel@thread.tacv2"; |
| 24 | |
| 25 | fn base() -> DateTime<Utc> { |
| 26 | Utc.with_ymd_and_hms(2026, 10, 6, 8, 0, 0).unwrap() |
| 27 | } |
| 28 | |
| 29 | fn message(id: u32, minute: i64, body: &str) -> Message { |
| 30 | serde_json::from_value(json!({ |
| 31 | "id": format!("m{id:04}"), |
| 32 | "messageType": "message", |
| 33 | "createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(), |
| 34 | "from": {"user": {"id": "user-ada", "displayName": "Ada Example"}}, |
| 35 | "body": {"contentType": "html", "content": body}, |
| 36 | })) |
| 37 | .unwrap() |
| 38 | } |
| 39 | |
| 40 | fn numbered(count: u32) -> Vec<Message> { |
| 41 | (1..=count) |
| 42 | .map(|index| message(index, i64::from(index), &format!("<p>n{index}</p>"))) |
| 43 | .collect() |
| 44 | } |
| 45 | |
| 46 | fn chat( |
| 47 | id: &str, |
| 48 | topic: Option<&str>, |
| 49 | last_minute: i64, |
| 50 | read_minute: i64, |
| 51 | from: &str, |
| 52 | hidden: bool, |
| 53 | ) -> Chat { |
| 54 | serde_json::from_value(json!({ |
| 55 | "id": id, |
| 56 | "topic": topic, |
| 57 | "chatType": if topic.is_some() { "group" } else { "oneOnOne" }, |
| 58 | "lastUpdatedDateTime": (base() + Duration::minutes(last_minute)).to_rfc3339(), |
| 59 | "members": [ |
| 60 | {"userId": ME, "displayName": "Me Myself"}, |
| 61 | {"userId": "user-ada", "displayName": "Ada Example"} |
| 62 | ], |
| 63 | "lastMessagePreview": {"id": "p", "createdDateTime": (base() + Duration::minutes(last_minute)).to_rfc3339(), "from": {"user": {"id": from}}}, |
| 64 | "viewpoint": {"lastMessageReadDateTime": (base() + Duration::minutes(read_minute)).to_rfc3339(), "isHidden": hidden}, |
| 65 | })) |
| 66 | .unwrap() |
| 67 | } |
| 68 | |
| 69 | fn translated(messages: &[chatsvc::TranslateRequest]) -> Vec<chatsvc::Translation> { |
| 70 | messages |
| 71 | .iter() |
| 72 | .map(|request| chatsvc::Translation { |
| 73 | message_id: request.message_id.clone(), |
| 74 | version: None, |
| 75 | status: chatsvc::TranslationStatus::Done, |
| 76 | content_html: Some("<p>translated</p>".to_owned()), |
| 77 | subject: None, |
| 78 | title: None, |
| 79 | }) |
| 80 | .collect() |
| 81 | } |
| 82 | |
| 83 | type ScheduledCall = (String, String, DateTime<Utc>, String); |
| 84 | |
| 85 | #[derive(Default)] |
| 86 | struct Fake { |
| 87 | chats: Mutex<Vec<Chat>>, |
| 88 | fetchable_chats: Mutex<Vec<Chat>>, |
| 89 | single_chat_calls: Mutex<usize>, |
| 90 | chat_messages: Mutex<Vec<Message>>, |
| 91 | lagging_message: Mutex<Option<(usize, Message)>>, |
| 92 | channel_pages: Mutex<Vec<Vec<Message>>>, |
| 93 | teams: Mutex<Vec<Team>>, |
| 94 | failing_team: Mutex<Option<String>>, |
| 95 | sent: Mutex<Vec<String>>, |
| 96 | chat_calls: Mutex<usize>, |
| 97 | chat_page_calls: Mutex<usize>, |
| 98 | team_calls: Mutex<usize>, |
| 99 | calls: Mutex<Vec<String>>, |
| 100 | delta_items: Mutex<Vec<Message>>, |
| 101 | thread_replies: Mutex<Vec<Message>>, |
| 102 | delta_fails: Mutex<bool>, |
| 103 | photos: Mutex<HashMap<String, Vec<u8>>>, |
| 104 | photo_requests: Mutex<Vec<Vec<String>>>, |
| 105 | presence_answers: Mutex<Vec<Presence>>, |
| 106 | presence_subscriptions: Mutex<Vec<(String, Vec<String>, bool)>>, |
| 107 | hosted_requests: Mutex<Vec<String>>, |
| 108 | external_requests: Mutex<Vec<String>>, |
| 109 | mentions_sent: Mutex<Vec<Vec<OutgoingMention>>>, |
| 110 | extras_sent: Mutex<Vec<MessageExtras>>, |
| 111 | chatsvc_posts: Mutex<Vec<(String, String, String, serde_json::Value)>>, |
| 112 | send_answer_body: Mutex<Option<String>>, |
| 113 | folder_requests: Mutex<usize>, |
| 114 | directory_users: Mutex<Vec<User>>, |
| 115 | horizons: Mutex<Vec<chatsvc::MemberHorizon>>, |
| 116 | horizon_calls: Mutex<usize>, |
| 117 | apps: Mutex<Vec<chatsvc::ChatApp>>, |
| 118 | app_calls: Mutex<usize>, |
| 119 | invokes: Mutex<Vec<chatsvc::InvokeRequest>>, |
| 120 | invoke_answer: Mutex<Option<chatsvc::InvokeResponse>>, |
| 121 | muted_states: Mutex<Vec<(String, bool)>>, |
| 122 | hidden_states: Mutex<Vec<(String, bool)>>, |
| 123 | read_states: Mutex<Vec<(String, chatsvc::ReadHorizon)>>, |
| 124 | notes_placeholder: Mutex<bool>, |
| 125 | chats_fail: Mutex<bool>, |
| 126 | muted_fails: Mutex<bool>, |
| 127 | link_pages: Mutex<Vec<chatsvc::MessageLinks>>, |
| 128 | link_page_calls: Mutex<Vec<String>>, |
| 129 | links_put: Mutex<Vec<(String, String)>>, |
| 130 | link_info_calls: Mutex<usize>, |
| 131 | translate_calls: Mutex<Vec<String>>, |
| 132 | scheduled: Mutex<Vec<ScheduledCall>>, |
| 133 | own_status_answer: Mutex<chatsvc::PresenceStatus>, |
| 134 | availability_puts: Mutex<Vec<Option<chatsvc::ForcedAvailability>>>, |
| 135 | note_puts: Mutex<Vec<Option<chatsvc::StatusNote>>>, |
| 136 | window_answer: Mutex<Option<chatsvc::MessageWindow>>, |
| 137 | window_requests: Mutex<Vec<(String, chatsvc::WindowDirection)>>, |
| 138 | search_identities: Mutex<Vec<substrate_search::SearchIdentity>>, |
| 139 | member_requests: Mutex<Vec<String>>, |
| 140 | activity_feed: Mutex<chatsvc::ActivitySnapshot>, |
| 141 | app_channel_horizon_ms: Mutex<i64>, |
| 142 | } |
| 143 | |
| 144 | impl Fake { |
| 145 | fn set_chat_messages(&self, messages: Vec<Message>) { |
| 146 | *self.chat_messages.lock().unwrap() = messages; |
| 147 | } |
| 148 | } |
| 149 | |
| 150 | fn page_of(items: Vec<Message>, next_link: Option<String>) -> Result<RemotePage> { |
| 151 | Ok(RemotePage { items, next_link }) |
| 152 | } |
| 153 | |
| 154 | struct Handle(Arc<Fake>); |
| 155 | |
| 156 | impl std::ops::Deref for Handle { |
| 157 | type Target = Fake; |
| 158 | |
| 159 | fn deref(&self) -> &Fake { |
| 160 | &self.0 |
| 161 | } |
| 162 | } |
| 163 | |
| 164 | fn describe(target: &MessageTarget) -> String { |
| 165 | match target { |
| 166 | MessageTarget::Chat { message_id, .. } => message_id.clone(), |
| 167 | MessageTarget::Channel { |
| 168 | message_id, |
| 169 | root_id, |
| 170 | .. |
| 171 | } => format!("channel:{}:{message_id}", root_id.as_deref().unwrap_or("-")), |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | fn unsupported<T>() -> Result<T> { |
| 176 | Err(Error::Unsupported("not faked")) |
| 177 | } |
| 178 | |
| 179 | impl Fake { |
| 180 | fn record(&self, call: String) { |
| 181 | self.calls.lock().unwrap().push(call); |
| 182 | } |
| 183 | |
| 184 | fn calls(&self) -> Vec<String> { |
| 185 | self.calls.lock().unwrap().clone() |
| 186 | } |
| 187 | |
| 188 | fn sorted_chats(&self) -> Vec<Chat> { |
| 189 | let mut chats = self.chats.lock().unwrap().clone(); |
| 190 | chats.sort_by_key(|chat| std::cmp::Reverse(chat.last_message_time())); |
| 191 | chats |
| 192 | } |
| 193 | |
| 194 | fn chats_from(&self, offset: usize, top: usize) -> ChatsPage { |
| 195 | *self.chat_page_calls.lock().unwrap() += 1; |
| 196 | let chats = self.sorted_chats(); |
| 197 | let items: Vec<Chat> = chats.iter().skip(offset).take(top).cloned().collect(); |
| 198 | let next_link = |
| 199 | (offset + top < chats.len()).then(|| format!("chats:{}:{top}", offset + top)); |
| 200 | ChatsPage { items, next_link } |
| 201 | } |
| 202 | } |
| 203 | |
| 204 | impl Remote for Handle { |
| 205 | async fn server_suggestions( |
| 206 | &self, |
| 207 | identity: &substrate_search::SearchIdentity, |
| 208 | _search_session: &substrate_search::SearchSession, |
| 209 | text: &str, |
| 210 | ) -> Result<substrate_search::Suggestions> { |
| 211 | self.search_identities |
| 212 | .lock() |
| 213 | .unwrap() |
| 214 | .push(identity.clone()); |
| 215 | self.record(format!("server_suggestions:{text}")); |
| 216 | Ok(substrate_search::Suggestions::default()) |
| 217 | } |
| 218 | |
| 219 | async fn me(&self) -> Result<User> { |
| 220 | Ok(serde_json::from_value(json!({"id": ME, "displayName": "Me Myself"})).unwrap()) |
| 221 | } |
| 222 | |
| 223 | async fn chats_page(&self, top: usize) -> Result<ChatsPage> { |
| 224 | Ok(self.chats_from(0, top)) |
| 225 | } |
| 226 | |
| 227 | async fn chats_at(&self, next_link: &str) -> Result<ChatsPage> { |
| 228 | if *self.chats_fail.lock().unwrap() { |
| 229 | return Err(Error::Unsupported("forced failure")); |
| 230 | } |
| 231 | let mut parts = next_link.trim_start_matches("chats:").split(':'); |
| 232 | let offset = parts.next().unwrap().parse().unwrap(); |
| 233 | let top = parts.next().unwrap().parse().unwrap(); |
| 234 | Ok(self.chats_from(offset, top)) |
| 235 | } |
| 236 | |
| 237 | async fn chat(&self, chat_id: &str) -> Result<Chat> { |
| 238 | *self.single_chat_calls.lock().unwrap() += 1; |
| 239 | if chat_id == NOTES_CHAT_ID { |
| 240 | return Err(Error::Graph(graph::Error::Session(session::Error::api( |
| 241 | 400, |
| 242 | chat_id, |
| 243 | json!({"error": {"code": "BadRequest", "message": "Resource is not a ChatThread"}}), |
| 244 | )))); |
| 245 | } |
| 246 | let found = self |
| 247 | .fetchable_chats |
| 248 | .lock() |
| 249 | .unwrap() |
| 250 | .iter() |
| 251 | .find(|candidate| candidate.id == chat_id) |
| 252 | .cloned(); |
| 253 | found.ok_or_else(|| { |
| 254 | Error::Graph(graph::Error::Session(session::Error::api( |
| 255 | 404, |
| 256 | chat_id, |
| 257 | json!({}), |
| 258 | ))) |
| 259 | }) |
| 260 | } |
| 261 | |
| 262 | async fn chat_members(&self, chat_id: &str) -> Result<Vec<Member>> { |
| 263 | self.member_requests |
| 264 | .lock() |
| 265 | .unwrap() |
| 266 | .push(chat_id.to_owned()); |
| 267 | Ok(vec![ |
| 268 | serde_json::from_value( |
| 269 | json!({"userId": ME, "tenantId": "tenant-1", "displayName": "Me Myself"}), |
| 270 | ) |
| 271 | .unwrap(), |
| 272 | ]) |
| 273 | } |
| 274 | |
| 275 | async fn joined_teams(&self) -> Result<Vec<Team>> { |
| 276 | *self.team_calls.lock().unwrap() += 1; |
| 277 | Ok(self.teams.lock().unwrap().clone()) |
| 278 | } |
| 279 | |
| 280 | async fn channels_for_teams(&self, team_ids: &[String]) -> Result<Vec<Result<Vec<Channel>>>> { |
| 281 | let failing = self.failing_team.lock().unwrap().clone(); |
| 282 | Ok(team_ids |
| 283 | .iter() |
| 284 | .map(|team_id| { |
| 285 | if failing.as_deref() == Some(team_id.as_str()) { |
| 286 | return Err(Error::Unsupported("forced failure")); |
| 287 | } |
| 288 | Ok(vec![serde_json::from_value(json!({"id": CHANNEL, "displayName": "General", "membershipType": "standard"})).unwrap()]) |
| 289 | }) |
| 290 | .collect()) |
| 291 | } |
| 292 | |
| 293 | async fn chat_messages( |
| 294 | &self, |
| 295 | _chat_id: &str, |
| 296 | before: Option<DateTime<Utc>>, |
| 297 | top: usize, |
| 298 | ) -> Result<RemotePage> { |
| 299 | let calls = { |
| 300 | let mut calls = self.chat_calls.lock().unwrap(); |
| 301 | *calls += 1; |
| 302 | *calls |
| 303 | }; |
| 304 | let mut lagging = self.lagging_message.lock().unwrap(); |
| 305 | if lagging |
| 306 | .as_ref() |
| 307 | .is_some_and(|(visible_from, _)| calls >= *visible_from) |
| 308 | && let Some((_, message)) = lagging.take() |
| 309 | { |
| 310 | self.chat_messages.lock().unwrap().push(message); |
| 311 | } |
| 312 | drop(lagging); |
| 313 | let mut matching: Vec<Message> = self |
| 314 | .chat_messages |
| 315 | .lock() |
| 316 | .unwrap() |
| 317 | .iter() |
| 318 | .filter(|message| { |
| 319 | before.is_none_or(|before| message.created_date_time.unwrap() < before) |
| 320 | }) |
| 321 | .cloned() |
| 322 | .collect(); |
| 323 | matching.sort_by_key(|message| std::cmp::Reverse(message.created_date_time)); |
| 324 | let has_more = matching.len() > top; |
| 325 | matching.truncate(top); |
| 326 | page_of( |
| 327 | matching, |
| 328 | has_more.then(|| "https://graph.microsoft.com/v1.0/next".to_owned()), |
| 329 | ) |
| 330 | } |
| 331 | |
| 332 | async fn chat_message_window( |
| 333 | &self, |
| 334 | _chat_id: &str, |
| 335 | anchor_id: &str, |
| 336 | direction: chatsvc::WindowDirection, |
| 337 | _page_size: usize, |
| 338 | ) -> Result<chatsvc::MessageWindow> { |
| 339 | self.window_requests |
| 340 | .lock() |
| 341 | .unwrap() |
| 342 | .push((anchor_id.to_owned(), direction)); |
| 343 | self.window_answer |
| 344 | .lock() |
| 345 | .unwrap() |
| 346 | .clone() |
| 347 | .ok_or(Error::Unsupported("no window")) |
| 348 | } |
| 349 | |
| 350 | async fn chat_messages_by_id( |
| 351 | &self, |
| 352 | chat_id: &str, |
| 353 | message_ids: &[String], |
| 354 | ) -> Result<Vec<Result<Message>>> { |
| 355 | let mut messages = Vec::new(); |
| 356 | for message_id in message_ids { |
| 357 | messages.push(self.chat_message(chat_id, message_id).await); |
| 358 | } |
| 359 | Ok(messages) |
| 360 | } |
| 361 | |
| 362 | async fn chat_message(&self, _chat_id: &str, message_id: &str) -> Result<Message> { |
| 363 | self.record(format!("chat_message {message_id}")); |
| 364 | self.chat_messages |
| 365 | .lock() |
| 366 | .unwrap() |
| 367 | .iter() |
| 368 | .find(|message| message.id == message_id) |
| 369 | .cloned() |
| 370 | .ok_or(Error::Unsupported("missing message")) |
| 371 | } |
| 372 | |
| 373 | async fn channel_messages( |
| 374 | &self, |
| 375 | _team_id: &str, |
| 376 | _channel_id: &str, |
| 377 | _top: usize, |
| 378 | ) -> Result<RemotePage> { |
| 379 | let pages = self.channel_pages.lock().unwrap(); |
| 380 | page_of( |
| 381 | pages[0].clone(), |
| 382 | (pages.len() > 1).then(|| "page:1".to_owned()), |
| 383 | ) |
| 384 | } |
| 385 | |
| 386 | async fn channel_messages_at(&self, next_link: &str) -> Result<RemotePage> { |
| 387 | let index: usize = next_link.trim_start_matches("page:").parse().unwrap(); |
| 388 | let pages = self.channel_pages.lock().unwrap(); |
| 389 | page_of( |
| 390 | pages[index].clone(), |
| 391 | (pages.len() > index + 1).then(|| format!("page:{}", index + 1)), |
| 392 | ) |
| 393 | } |
| 394 | |
| 395 | async fn channel_message( |
| 396 | &self, |
| 397 | _team_id: &str, |
| 398 | _channel_id: &str, |
| 399 | message_id: &str, |
| 400 | ) -> Result<Message> { |
| 401 | self.record(format!("channel_message {message_id}")); |
| 402 | self.channel_pages |
| 403 | .lock() |
| 404 | .unwrap() |
| 405 | .iter() |
| 406 | .flatten() |
| 407 | .find(|message| message.id == message_id) |
| 408 | .cloned() |
| 409 | .ok_or(Error::Unsupported("missing message")) |
| 410 | } |
| 411 | |
| 412 | async fn channel_reply( |
| 413 | &self, |
| 414 | _team_id: &str, |
| 415 | _channel_id: &str, |
| 416 | message_id: &str, |
| 417 | reply_id: &str, |
| 418 | ) -> Result<Message> { |
| 419 | self.record(format!("channel_reply {message_id} {reply_id}")); |
| 420 | self.channel_pages |
| 421 | .lock() |
| 422 | .unwrap() |
| 423 | .iter() |
| 424 | .flatten() |
| 425 | .filter(|root| root.id == message_id) |
| 426 | .flat_map(|root| root.replies.iter()) |
| 427 | .find(|reply| reply.id == reply_id) |
| 428 | .cloned() |
| 429 | .ok_or(Error::Unsupported("missing reply")) |
| 430 | } |
| 431 | |
| 432 | async fn channel_delta( |
| 433 | &self, |
| 434 | _team_id: &str, |
| 435 | _channel_id: &str, |
| 436 | modified_after: Option<DateTime<Utc>>, |
| 437 | ) -> Result<DeltaPage> { |
| 438 | self.record(format!("channel_delta since={}", modified_after.is_some())); |
| 439 | if *self.delta_fails.lock().unwrap() { |
| 440 | return unsupported(); |
| 441 | } |
| 442 | Ok(DeltaPage { |
| 443 | items: self.delta_items.lock().unwrap().clone(), |
| 444 | next_link: None, |
| 445 | delta_link: Some("delta:1".to_owned()), |
| 446 | }) |
| 447 | } |
| 448 | |
| 449 | async fn channel_delta_at(&self, link: &str) -> Result<DeltaPage> { |
| 450 | self.record(format!("channel_delta_at {link}")); |
| 451 | if *self.delta_fails.lock().unwrap() { |
| 452 | return unsupported(); |
| 453 | } |
| 454 | Ok(DeltaPage { |
| 455 | items: std::mem::take(&mut *self.delta_items.lock().unwrap()), |
| 456 | next_link: None, |
| 457 | delta_link: Some("delta:2".to_owned()), |
| 458 | }) |
| 459 | } |
| 460 | |
| 461 | async fn channel_replies( |
| 462 | &self, |
| 463 | _team_id: &str, |
| 464 | _channel_id: &str, |
| 465 | root_ids: &[String], |
| 466 | ) -> Result<Vec<Result<Vec<Message>>>> { |
| 467 | let replies = self.thread_replies.lock().unwrap().clone(); |
| 468 | Ok(root_ids |
| 469 | .iter() |
| 470 | .map(|root_id| { |
| 471 | Ok(replies |
| 472 | .iter() |
| 473 | .filter(|reply| reply.reply_to_id.as_deref() == Some(root_id.as_str())) |
| 474 | .cloned() |
| 475 | .collect()) |
| 476 | }) |
| 477 | .collect()) |
| 478 | } |
| 479 | |
| 480 | async fn send_chat_message( |
| 481 | &self, |
| 482 | _chat_id: &str, |
| 483 | html: &str, |
| 484 | mentions: &[OutgoingMention], |
| 485 | extras: &MessageExtras, |
| 486 | ) -> Result<Message> { |
| 487 | self.sent.lock().unwrap().push(html.to_owned()); |
| 488 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 489 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 490 | let body = self |
| 491 | .send_answer_body |
| 492 | .lock() |
| 493 | .unwrap() |
| 494 | .clone() |
| 495 | .unwrap_or_else(|| html.to_owned()); |
| 496 | Ok(message(9000, 500, &body)) |
| 497 | } |
| 498 | |
| 499 | async fn send_channel_message( |
| 500 | &self, |
| 501 | _team_id: &str, |
| 502 | _channel_id: &str, |
| 503 | html: &str, |
| 504 | subject: Option<&str>, |
| 505 | mentions: &[OutgoingMention], |
| 506 | extras: &MessageExtras, |
| 507 | ) -> Result<Message> { |
| 508 | self.record(format!("post subject={subject:?}")); |
| 509 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 510 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 511 | Ok(message(9001, 501, html)) |
| 512 | } |
| 513 | |
| 514 | async fn reply_to_channel_message( |
| 515 | &self, |
| 516 | _team_id: &str, |
| 517 | _channel_id: &str, |
| 518 | message_id: &str, |
| 519 | html: &str, |
| 520 | mentions: &[OutgoingMention], |
| 521 | extras: &MessageExtras, |
| 522 | ) -> Result<Message> { |
| 523 | self.record(format!("reply to {message_id}")); |
| 524 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 525 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 526 | Ok(message(9002, 502, html)) |
| 527 | } |
| 528 | |
| 529 | async fn post_chatsvc_message( |
| 530 | &self, |
| 531 | conversation: &chatsvc::ConversationRef, |
| 532 | html: &str, |
| 533 | display_name: &str, |
| 534 | properties: &serde_json::Value, |
| 535 | ) -> Result<String> { |
| 536 | let conversation_id = conversation.conversation_id(); |
| 537 | self.record(format!("chatsvc post {conversation_id}")); |
| 538 | self.chatsvc_posts.lock().unwrap().push(( |
| 539 | conversation_id, |
| 540 | html.to_owned(), |
| 541 | display_name.to_owned(), |
| 542 | properties.clone(), |
| 543 | )); |
| 544 | Ok("1727203440000".to_owned()) |
| 545 | } |
| 546 | |
| 547 | async fn mark_chat_read(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> { |
| 548 | self.record(format!("mark_read {chat_id} {user_id} {tenant_id}")); |
| 549 | Ok(()) |
| 550 | } |
| 551 | |
| 552 | async fn mark_chat_unread( |
| 553 | &self, |
| 554 | chat_id: &str, |
| 555 | user_id: &str, |
| 556 | tenant_id: &str, |
| 557 | last_read_at: DateTime<Utc>, |
| 558 | ) -> Result<()> { |
| 559 | self.record(format!( |
| 560 | "mark_unread {chat_id} {user_id} {tenant_id} {}", |
| 561 | last_read_at.timestamp_millis() |
| 562 | )); |
| 563 | Ok(()) |
| 564 | } |
| 565 | |
| 566 | async fn hide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> { |
| 567 | self.record(format!("hide {chat_id} {user_id} {tenant_id}")); |
| 568 | Ok(()) |
| 569 | } |
| 570 | |
| 571 | async fn unhide_chat(&self, chat_id: &str, user_id: &str, tenant_id: &str) -> Result<()> { |
| 572 | self.record(format!("unhide {chat_id} {user_id} {tenant_id}")); |
| 573 | Ok(()) |
| 574 | } |
| 575 | |
| 576 | async fn remove_chat_member(&self, chat_id: &str, user_id: &str) -> Result<()> { |
| 577 | self.record(format!("remove member {chat_id} {user_id}")); |
| 578 | Ok(()) |
| 579 | } |
| 580 | |
| 581 | async fn add_chat_members( |
| 582 | &self, |
| 583 | chat_id: &str, |
| 584 | user_ids: &[String], |
| 585 | share: chatsvc::HistoryShare, |
| 586 | ) -> Result<()> { |
| 587 | self.record(format!( |
| 588 | "add members {chat_id} {} {share:?}", |
| 589 | user_ids.join(",") |
| 590 | )); |
| 591 | Ok(()) |
| 592 | } |
| 593 | |
| 594 | async fn chat_states(&self) -> Result<Vec<chatsvc::ConversationState>> { |
| 595 | if *self.muted_fails.lock().unwrap() { |
| 596 | return Err(Error::Unsupported("forced failure")); |
| 597 | } |
| 598 | let muted = self.muted_states.lock().unwrap().clone(); |
| 599 | let hidden = self.hidden_states.lock().unwrap().clone(); |
| 600 | let mut states: Vec<chatsvc::ConversationState> = muted |
| 601 | .into_iter() |
| 602 | .map(|(id, muted)| chatsvc::ConversationState { |
| 603 | id, |
| 604 | muted, |
| 605 | hidden: None, |
| 606 | read: chatsvc::ReadHorizon::default(), |
| 607 | notification_settings: None, |
| 608 | history_cleared_ms: None, |
| 609 | hidden_at_ms: None, |
| 610 | }) |
| 611 | .collect(); |
| 612 | states.extend( |
| 613 | hidden |
| 614 | .into_iter() |
| 615 | .map(|(id, hidden)| chatsvc::ConversationState { |
| 616 | id, |
| 617 | muted: false, |
| 618 | hidden: Some(hidden), |
| 619 | read: chatsvc::ReadHorizon::default(), |
| 620 | notification_settings: None, |
| 621 | history_cleared_ms: None, |
| 622 | hidden_at_ms: None, |
| 623 | }), |
| 624 | ); |
| 625 | let read = self.read_states.lock().unwrap().clone(); |
| 626 | states.extend( |
| 627 | read.into_iter() |
| 628 | .map(|(id, read)| chatsvc::ConversationState { |
| 629 | id, |
| 630 | muted: false, |
| 631 | hidden: None, |
| 632 | read, |
| 633 | notification_settings: None, |
| 634 | history_cleared_ms: None, |
| 635 | hidden_at_ms: None, |
| 636 | }), |
| 637 | ); |
| 638 | if !*self.notes_placeholder.lock().unwrap() |
| 639 | && !states.iter().any(|state| state.id == NOTES_CHAT_ID) |
| 640 | { |
| 641 | states.push(chatsvc::ConversationState { |
| 642 | id: NOTES_CHAT_ID.to_owned(), |
| 643 | hidden: Some(true), |
| 644 | ..chatsvc::ConversationState::default() |
| 645 | }); |
| 646 | } |
| 647 | Ok(states) |
| 648 | } |
| 649 | |
| 650 | async fn set_chat_muted(&self, chat_id: &str, muted: bool) -> Result<()> { |
| 651 | self.record(format!("mute {chat_id} {muted}")); |
| 652 | Ok(()) |
| 653 | } |
| 654 | |
| 655 | async fn set_read_horizon(&self, conversation_id: &str, horizon: &str) -> Result<()> { |
| 656 | self.record(format!("read horizon {conversation_id} {horizon}")); |
| 657 | Ok(()) |
| 658 | } |
| 659 | |
| 660 | async fn set_read_bookmark(&self, conversation_id: &str, bookmark: &str) -> Result<()> { |
| 661 | self.record(format!("read bookmark {conversation_id} {bookmark}")); |
| 662 | Ok(()) |
| 663 | } |
| 664 | |
| 665 | async fn set_chat_hidden_at(&self, chat_id: &str, hidden_at_ms: Option<i64>) -> Result<()> { |
| 666 | let hidden = hidden_at_ms.map_or("none".to_owned(), |_| "now".to_owned()); |
| 667 | self.record(format!("hidden at {chat_id} {hidden}")); |
| 668 | Ok(()) |
| 669 | } |
| 670 | |
| 671 | async fn set_channel_notifications( |
| 672 | &self, |
| 673 | channel_id: &str, |
| 674 | notifications: store::ChannelNotifications, |
| 675 | ) -> Result<()> { |
| 676 | self.record(format!( |
| 677 | "channel notifications {channel_id} {} {}", |
| 678 | notifications.level.key(), |
| 679 | notifications.include_replies |
| 680 | )); |
| 681 | Ok(()) |
| 682 | } |
| 683 | |
| 684 | async fn send_typing(&self, conversation: &ConversationRef, active: bool) -> Result<()> { |
| 685 | self.record(format!( |
| 686 | "typing {} {active}", |
| 687 | conversation.conversation_id() |
| 688 | )); |
| 689 | Ok(()) |
| 690 | } |
| 691 | |
| 692 | async fn set_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> { |
| 693 | self.record(format!("set_reaction {} {reaction_type}", describe(target))); |
| 694 | Ok(()) |
| 695 | } |
| 696 | |
| 697 | async fn unset_reaction(&self, target: &MessageTarget, reaction_type: &str) -> Result<()> { |
| 698 | self.record(format!( |
| 699 | "unset_reaction {} {reaction_type}", |
| 700 | describe(target) |
| 701 | )); |
| 702 | Ok(()) |
| 703 | } |
| 704 | |
| 705 | async fn edit_message( |
| 706 | &self, |
| 707 | target: &MessageTarget, |
| 708 | html: &str, |
| 709 | mentions: &[OutgoingMention], |
| 710 | extras: &MessageExtras, |
| 711 | ) -> Result<()> { |
| 712 | self.record(format!("edit {} {html}", describe(target))); |
| 713 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 714 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 715 | Ok(()) |
| 716 | } |
| 717 | |
| 718 | async fn delete_file(&self, file: &UploadedFile) -> Result<()> { |
| 719 | self.record(format!("delete_file {}", file.item_id)); |
| 720 | Ok(()) |
| 721 | } |
| 722 | |
| 723 | async fn soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> { |
| 724 | self.record(format!("soft_delete {user_id} {}", describe(target))); |
| 725 | Ok(()) |
| 726 | } |
| 727 | |
| 728 | async fn undo_soft_delete_message(&self, user_id: &str, target: &MessageTarget) -> Result<()> { |
| 729 | self.record(format!("undo_soft_delete {user_id} {}", describe(target))); |
| 730 | Ok(()) |
| 731 | } |
| 732 | |
| 733 | async fn create_one_on_one(&self, my_user_id: &str, user_id: &str) -> Result<Chat> { |
| 734 | self.record(format!("one_on_one {my_user_id} {user_id}")); |
| 735 | Ok(chat("19:new@thread.v2", None, 40, 40, ME, false)) |
| 736 | } |
| 737 | |
| 738 | async fn create_group( |
| 739 | &self, |
| 740 | my_user_id: &str, |
| 741 | user_ids: &[String], |
| 742 | topic: Option<&str>, |
| 743 | ) -> Result<Chat> { |
| 744 | self.record(format!( |
| 745 | "group {my_user_id} {} {topic:?}", |
| 746 | user_ids.join(",") |
| 747 | )); |
| 748 | Ok(chat("19:group@thread.v2", topic, 41, 41, ME, false)) |
| 749 | } |
| 750 | |
| 751 | async fn reply_with_quote( |
| 752 | &self, |
| 753 | chat_id: &str, |
| 754 | quoted_message_id: &str, |
| 755 | html: &str, |
| 756 | mentions: &[OutgoingMention], |
| 757 | extras: &MessageExtras, |
| 758 | ) -> Result<Message> { |
| 759 | self.record(format!("quote_reply {chat_id} {quoted_message_id} {html}")); |
| 760 | self.mentions_sent.lock().unwrap().push(mentions.to_vec()); |
| 761 | self.extras_sent.lock().unwrap().push(extras.clone()); |
| 762 | Ok(message(9003, 503, html)) |
| 763 | } |
| 764 | |
| 765 | async fn channel_files_folder(&self, team_id: &str, channel_id: &str) -> Result<DriveFolder> { |
| 766 | *self.folder_requests.lock().unwrap() += 1; |
| 767 | self.record(format!("files_folder {team_id} {channel_id}")); |
| 768 | Ok(DriveFolder { |
| 769 | drive_id: "drive-1".into(), |
| 770 | item_id: "folder-1".into(), |
| 771 | }) |
| 772 | } |
| 773 | |
| 774 | async fn upload_file( |
| 775 | &self, |
| 776 | destination: &UploadDestination, |
| 777 | file_name: &str, |
| 778 | bytes: &[u8], |
| 779 | progress: &(dyn Fn(u8) + Send + Sync), |
| 780 | ) -> Result<UploadedFile> { |
| 781 | let target = match destination { |
| 782 | UploadDestination::ChatFiles => "chat-files".to_owned(), |
| 783 | UploadDestination::Folder(folder) => format!("{}/{}", folder.drive_id, folder.item_id), |
| 784 | }; |
| 785 | self.record(format!("upload {target} {file_name} {}", bytes.len())); |
| 786 | progress(50); |
| 787 | progress(100); |
| 788 | Ok(UploadedFile { |
| 789 | drive_id: "drive-1".into(), |
| 790 | item_id: "item-1".into(), |
| 791 | name: file_name.to_owned(), |
| 792 | web_url: "https://files.example/web".into(), |
| 793 | web_dav_url: Some("https://files.example/dav".into()), |
| 794 | etag: "\"{GUID-1},2\"".into(), |
| 795 | }) |
| 796 | } |
| 797 | |
| 798 | async fn resolve_share(&self, open_url: &str) -> Result<SharedFile> { |
| 799 | self.record(format!("resolve {open_url}")); |
| 800 | Ok(SharedFile { |
| 801 | name: "big.bin".into(), |
| 802 | size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3, |
| 803 | download_url: if open_url.contains("short") { |
| 804 | "https://dl.example/short".into() |
| 805 | } else if open_url.contains("grown") { |
| 806 | "https://dl.example/grown".into() |
| 807 | } else { |
| 808 | "https://dl.example/big".into() |
| 809 | }, |
| 810 | }) |
| 811 | } |
| 812 | |
| 813 | async fn resolve_drive_item(&self, drive_id: &str, item_id: &str) -> Result<SharedFile> { |
| 814 | self.record(format!("resolve item {drive_id}/{item_id}")); |
| 815 | Ok(SharedFile { |
| 816 | name: "big.bin".into(), |
| 817 | size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3, |
| 818 | download_url: "https://dl.example/fresh".into(), |
| 819 | }) |
| 820 | } |
| 821 | |
| 822 | async fn download_range( |
| 823 | &self, |
| 824 | download_url: &str, |
| 825 | start: u64, |
| 826 | end: Option<u64>, |
| 827 | ) -> Result<Vec<u8>> { |
| 828 | let total = 2 * graph::DOWNLOAD_CHUNK_BYTES + 3; |
| 829 | let shown_end = end.map_or(String::new(), |end| end.to_string()); |
| 830 | self.record(format!("range {download_url} {start}-{shown_end}")); |
| 831 | let length = match end { |
| 832 | _ if download_url.contains("short") => 1, |
| 833 | Some(end) => end - start + 1, |
| 834 | None if download_url.contains("grown") => total - start + 10, |
| 835 | None => total - start, |
| 836 | }; |
| 837 | Ok(vec![7; length as usize]) |
| 838 | } |
| 839 | |
| 840 | async fn share_file(&self, file: &UploadedFile, user_ids: &[String]) -> Result<()> { |
| 841 | self.record(format!("share {} {}", file.item_id, user_ids.join(","))); |
| 842 | Ok(()) |
| 843 | } |
| 844 | |
| 845 | async fn external_image(&self, url: &str) -> Result<Photo> { |
| 846 | self.external_requests.lock().unwrap().push(url.to_owned()); |
| 847 | self.hosted_content(url).await |
| 848 | } |
| 849 | |
| 850 | async fn hosted_content(&self, url: &str) -> Result<Photo> { |
| 851 | self.hosted_requests.lock().unwrap().push(url.to_owned()); |
| 852 | if url.contains("broken") { |
| 853 | return unsupported(); |
| 854 | } |
| 855 | let mut bytes = b"\x89PNG\r\n\x1a\n".to_vec(); |
| 856 | bytes.extend([ |
| 857 | 0, 0, 0, 13, b'I', b'H', b'D', b'R', 0, 0, 0, 40, 0, 0, 0, 20, |
| 858 | ]); |
| 859 | Ok(Photo { |
| 860 | bytes, |
| 861 | content_type: String::new(), |
| 862 | }) |
| 863 | } |
| 864 | |
| 865 | async fn user_photos(&self, user_ids: &[String]) -> Result<Vec<Result<Option<Photo>>>> { |
| 866 | self.photo_requests.lock().unwrap().push(user_ids.to_vec()); |
| 867 | let photos = self.photos.lock().unwrap(); |
| 868 | Ok(user_ids |
| 869 | .iter() |
| 870 | .map(|user_id| { |
| 871 | Ok(photos.get(user_id).map(|bytes| Photo { |
| 872 | bytes: bytes.clone(), |
| 873 | content_type: "image/jpeg".to_owned(), |
| 874 | })) |
| 875 | }) |
| 876 | .collect()) |
| 877 | } |
| 878 | |
| 879 | async fn consumption_horizons( |
| 880 | &self, |
| 881 | _conversation_id: &str, |
| 882 | ) -> Result<Vec<chatsvc::MemberHorizon>> { |
| 883 | *self.horizon_calls.lock().unwrap() += 1; |
| 884 | Ok(self.horizons.lock().unwrap().clone()) |
| 885 | } |
| 886 | |
| 887 | async fn forward_messages( |
| 888 | &self, |
| 889 | source_conversation_id: &str, |
| 890 | target_conversation_id: &str, |
| 891 | message_ids: &[String], |
| 892 | comment_html: &str, |
| 893 | ) -> Result<chatsvc::ForwardResult> { |
| 894 | self.record(format!( |
| 895 | "forward {source_conversation_id} {target_conversation_id} {} {comment_html}", |
| 896 | message_ids.join(",") |
| 897 | )); |
| 898 | Ok(chatsvc::ForwardResult { |
| 899 | thread_id: target_conversation_id.to_owned(), |
| 900 | message_id: "99".to_owned(), |
| 901 | }) |
| 902 | } |
| 903 | |
| 904 | async fn set_saved( |
| 905 | &self, |
| 906 | conversation_id: &str, |
| 907 | root_id: &str, |
| 908 | message_id: &str, |
| 909 | saved: bool, |
| 910 | ) -> Result<()> { |
| 911 | self.record(format!( |
| 912 | "save {conversation_id} {root_id} {message_id} {saved}" |
| 913 | )); |
| 914 | Ok(()) |
| 915 | } |
| 916 | |
| 917 | async fn set_post_followed( |
| 918 | &self, |
| 919 | user_id: &str, |
| 920 | channel_id: &str, |
| 921 | root_id: &str, |
| 922 | followed: bool, |
| 923 | ) -> Result<Option<String>> { |
| 924 | self.record(format!("follow {user_id} {channel_id} {root_id} {followed}")); |
| 925 | Ok(None) |
| 926 | } |
| 927 | |
| 928 | async fn pin_message(&self, chat_id: &str, message_id: &str) -> Result<()> { |
| 929 | self.record(format!("pin {chat_id} {message_id}")); |
| 930 | Ok(()) |
| 931 | } |
| 932 | |
| 933 | async fn unpin_message( |
| 934 | &self, |
| 935 | chat_id: &str, |
| 936 | message_id: &str, |
| 937 | parent_id: Option<&str>, |
| 938 | ) -> Result<()> { |
| 939 | self.record(format!("unpin {chat_id} {message_id} {parent_id:?}")); |
| 940 | Ok(()) |
| 941 | } |
| 942 | |
| 943 | async fn channel_pinned_posts( |
| 944 | &self, |
| 945 | team_thread_id: &str, |
| 946 | channel_id: &str, |
| 947 | ) -> Result<Vec<chatsvc::PinnedMessage>> { |
| 948 | self.record(format!("channel pins {team_thread_id} {channel_id}")); |
| 949 | Ok(vec![chatsvc::PinnedMessage { |
| 950 | message_id: "30".to_owned(), |
| 951 | pinned_at: None, |
| 952 | parent_id: None, |
| 953 | }]) |
| 954 | } |
| 955 | |
| 956 | async fn set_post_pinned( |
| 957 | &self, |
| 958 | team_thread_id: &str, |
| 959 | channel_id: &str, |
| 960 | post_id: &str, |
| 961 | pinned: bool, |
| 962 | ) -> Result<()> { |
| 963 | self.record(format!( |
| 964 | "post pin {team_thread_id} {channel_id} {post_id} {pinned}" |
| 965 | )); |
| 966 | Ok(()) |
| 967 | } |
| 968 | |
| 969 | async fn activity_feed(&self) -> Result<chatsvc::ActivitySnapshot> { |
| 970 | Ok(self.activity_feed.lock().unwrap().clone()) |
| 971 | } |
| 972 | |
| 973 | async fn mark_activity_read(&self, message_id: &str) -> Result<()> { |
| 974 | self.record(format!("activity read {message_id}")); |
| 975 | Ok(()) |
| 976 | } |
| 977 | |
| 978 | async fn mark_all_activity_read(&self, _now_ms: i64) -> Result<()> { |
| 979 | self.record("activity all read".to_owned()); |
| 980 | Ok(()) |
| 981 | } |
| 982 | |
| 983 | async fn app_consumption_horizon(&self) -> Result<chatsvc::AppConsumptionHorizon> { |
| 984 | Ok(chatsvc::AppConsumptionHorizon { |
| 985 | channel_ms: *self.app_channel_horizon_ms.lock().unwrap(), |
| 986 | ..chatsvc::AppConsumptionHorizon::default() |
| 987 | }) |
| 988 | } |
| 989 | |
| 990 | async fn mark_all_channels_read(&self, now_ms: i64) -> Result<chatsvc::AppConsumptionHorizon> { |
| 991 | self.record("mark all channels read".to_owned()); |
| 992 | *self.app_channel_horizon_ms.lock().unwrap() = now_ms; |
| 993 | self.app_consumption_horizon().await |
| 994 | } |
| 995 | |
| 996 | async fn chat_apps(&self, _chat_id: &str) -> Result<Vec<chatsvc::ChatApp>> { |
| 997 | *self.app_calls.lock().unwrap() += 1; |
| 998 | Ok(self.apps.lock().unwrap().clone()) |
| 999 | } |
| 1000 | |
| 1001 | async fn create_scheduled( |
| 1002 | &self, |
| 1003 | inner_thread_id: &str, |
| 1004 | html: &str, |
| 1005 | send_at: DateTime<Utc>, |
| 1006 | display_name: &str, |
| 1007 | ) -> Result<chatsvc::ScheduledDraft> { |
| 1008 | self.scheduled.lock().unwrap().push(( |
| 1009 | inner_thread_id.to_owned(), |
| 1010 | html.to_owned(), |
| 1011 | send_at, |
| 1012 | display_name.to_owned(), |
| 1013 | )); |
| 1014 | Ok(chatsvc::ScheduledDraft { |
| 1015 | id: "d1".to_owned(), |
| 1016 | client_message_id: "1".to_owned(), |
| 1017 | inner_thread_id: inner_thread_id.to_owned(), |
| 1018 | send_at, |
| 1019 | html: html.to_owned(), |
| 1020 | delivery_state: None, |
| 1021 | }) |
| 1022 | } |
| 1023 | |
| 1024 | async fn invoke_card(&self, invoke: chatsvc::InvokeRequest) -> Result<chatsvc::InvokeResponse> { |
| 1025 | self.invokes.lock().unwrap().push(invoke); |
| 1026 | Ok(self |
| 1027 | .invoke_answer |
| 1028 | .lock() |
| 1029 | .unwrap() |
| 1030 | .clone() |
| 1031 | .unwrap_or(chatsvc::InvokeResponse::Empty)) |
| 1032 | } |
| 1033 | |
| 1034 | async fn message_links( |
| 1035 | &self, |
| 1036 | conversation: &chatsvc::ConversationRef, |
| 1037 | _page_size: usize, |
| 1038 | ) -> Result<Vec<chatsvc::MessageLinks>> { |
| 1039 | self.link_page_calls |
| 1040 | .lock() |
| 1041 | .unwrap() |
| 1042 | .push(conversation.conversation_id()); |
| 1043 | Ok(self.link_pages.lock().unwrap().clone()) |
| 1044 | } |
| 1045 | |
| 1046 | async fn set_message_links(&self, target: &MessageTarget, links_json: &str) -> Result<()> { |
| 1047 | self.links_put |
| 1048 | .lock() |
| 1049 | .unwrap() |
| 1050 | .push((describe(target), links_json.to_owned())); |
| 1051 | Ok(()) |
| 1052 | } |
| 1053 | |
| 1054 | async fn translate_chat_messages( |
| 1055 | &self, |
| 1056 | chat_id: &str, |
| 1057 | to_language: &str, |
| 1058 | messages: &[chatsvc::TranslateRequest], |
| 1059 | _trigger: &chatsvc::TranslationTrigger, |
| 1060 | ) -> Result<Vec<chatsvc::Translation>> { |
| 1061 | self.translate_calls |
| 1062 | .lock() |
| 1063 | .unwrap() |
| 1064 | .push(format!("chat {chat_id} {to_language} {}", messages.len())); |
| 1065 | Ok(translated(messages)) |
| 1066 | } |
| 1067 | |
| 1068 | async fn translate_channel_messages( |
| 1069 | &self, |
| 1070 | team_id: &str, |
| 1071 | channel_id: &str, |
| 1072 | root_id: &str, |
| 1073 | to_language: &str, |
| 1074 | messages: &[chatsvc::TranslateRequest], |
| 1075 | _trigger: &chatsvc::TranslationTrigger, |
| 1076 | ) -> Result<Vec<chatsvc::Translation>> { |
| 1077 | self.translate_calls.lock().unwrap().push(format!( |
| 1078 | "channel {team_id} {channel_id} {root_id} {to_language} {}", |
| 1079 | messages.len() |
| 1080 | )); |
| 1081 | Ok(translated(messages)) |
| 1082 | } |
| 1083 | |
| 1084 | async fn link_info(&self, url: &str) -> Result<chatsvc::LinkInfo> { |
| 1085 | *self.link_info_calls.lock().unwrap() += 1; |
| 1086 | Ok(chatsvc::LinkInfo { |
| 1087 | url: url.to_owned(), |
| 1088 | title: Some("Example".into()), |
| 1089 | description: Some("Example page".into()), |
| 1090 | ..chatsvc::LinkInfo::default() |
| 1091 | }) |
| 1092 | } |
| 1093 | |
| 1094 | async fn presences(&self, user_ids: &[String]) -> Result<Vec<Presence>> { |
| 1095 | let answers = self.presence_answers.lock().unwrap(); |
| 1096 | Ok(answers |
| 1097 | .iter() |
| 1098 | .filter(|presence| user_ids.contains(&presence.user_id)) |
| 1099 | .cloned() |
| 1100 | .collect()) |
| 1101 | } |
| 1102 | |
| 1103 | async fn subscribe_presence( |
| 1104 | &self, |
| 1105 | endpoint_id: &str, |
| 1106 | _trouter_uri: &str, |
| 1107 | user_ids: &[String], |
| 1108 | purge: bool, |
| 1109 | ) -> Result<()> { |
| 1110 | self.presence_subscriptions.lock().unwrap().push(( |
| 1111 | endpoint_id.to_owned(), |
| 1112 | user_ids.to_vec(), |
| 1113 | purge, |
| 1114 | )); |
| 1115 | Ok(()) |
| 1116 | } |
| 1117 | |
| 1118 | async fn own_status(&self, _user_id: &str) -> Result<chatsvc::PresenceStatus> { |
| 1119 | Ok(self.own_status_answer.lock().unwrap().clone()) |
| 1120 | } |
| 1121 | |
| 1122 | async fn set_availability(&self, forced: Option<&chatsvc::ForcedAvailability>) -> Result<()> { |
| 1123 | self.availability_puts.lock().unwrap().push(forced.copied()); |
| 1124 | Ok(()) |
| 1125 | } |
| 1126 | |
| 1127 | async fn set_status_note(&self, note: Option<&chatsvc::StatusNote>) -> Result<()> { |
| 1128 | self.note_puts.lock().unwrap().push(note.cloned()); |
| 1129 | Ok(()) |
| 1130 | } |
| 1131 | |
| 1132 | async fn team_tags(&self, team_id: &str) -> Result<Vec<graph::Tag>> { |
| 1133 | self.record(format!("tags {team_id}")); |
| 1134 | Ok(vec![ |
| 1135 | serde_json::from_value( |
| 1136 | json!({"id": "tag-design", "displayName": "Designers", "memberCount": 4}), |
| 1137 | ) |
| 1138 | .unwrap(), |
| 1139 | ]) |
| 1140 | } |
| 1141 | |
| 1142 | async fn search_people(&self, query: &str) -> Result<Vec<User>> { |
| 1143 | self.record(format!("search {query}")); |
| 1144 | let configured = self.directory_users.lock().unwrap().clone(); |
| 1145 | if !configured.is_empty() { |
| 1146 | return Ok(configured); |
| 1147 | } |
| 1148 | Ok(vec![ |
| 1149 | serde_json::from_value(json!({"id": "user-ada", "displayName": "Ada Example"})) |
| 1150 | .unwrap(), |
| 1151 | ]) |
| 1152 | } |
| 1153 | } |
| 1154 | |
| 1155 | fn engine_with(fake: &Arc<Fake>, config: SyncConfig) -> SyncEngine<Handle> { |
| 1156 | SyncEngine::with_config( |
| 1157 | Handle(fake.clone()), |
| 1158 | Arc::new(Store::open_in_memory().unwrap()), |
| 1159 | config, |
| 1160 | ) |
| 1161 | } |
| 1162 | |
| 1163 | fn small_pages() -> SyncConfig { |
| 1164 | SyncConfig { |
| 1165 | page_size: 10, |
| 1166 | open_limit: 10, |
| 1167 | ..SyncConfig::default() |
| 1168 | } |
| 1169 | } |
| 1170 | |
| 1171 | async fn chat_engine(fake: &Arc<Fake>, config: SyncConfig) -> SyncEngine<Handle> { |
| 1172 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 1173 | let engine = engine_with(fake, config); |
| 1174 | engine.refresh_sidebar().await.unwrap(); |
| 1175 | engine |
| 1176 | } |
| 1177 | |
| 1178 | #[tokio::test] |
| 1179 | async fn refresh_sidebar_fills_chats_teams_and_channels() { |
| 1180 | let fake = Arc::new(Fake::default()); |
| 1181 | *fake.chats.lock().unwrap() = vec![ |
| 1182 | chat("19:read@thread.v2", Some("Read"), 10, 10, "user-ada", false), |
| 1183 | chat("19:unread@thread.v2", None, 30, 10, "user-ada", false), |
| 1184 | chat("19:mine@thread.v2", Some("Mine"), 20, 5, ME, false), |
| 1185 | chat( |
| 1186 | "19:hidden@thread.v2", |
| 1187 | Some("Hidden"), |
| 1188 | 40, |
| 1189 | 1, |
| 1190 | "user-ada", |
| 1191 | true, |
| 1192 | ), |
| 1193 | ]; |
| 1194 | *fake.teams.lock().unwrap() = |
| 1195 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 1196 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1197 | let mut events = engine.subscribe(); |
| 1198 | |
| 1199 | let summary = engine.refresh_sidebar().await.unwrap(); |
| 1200 | assert_eq!( |
| 1201 | ( |
| 1202 | summary.chats, |
| 1203 | summary.teams, |
| 1204 | summary.channels, |
| 1205 | summary.failed_teams |
| 1206 | ), |
| 1207 | (4, 1, 1, 0) |
| 1208 | ); |
| 1209 | let sent: Vec<CoreEvent> = std::iter::from_fn(|| events.try_recv().ok()).collect(); |
| 1210 | assert!(sent.contains(&CoreEvent::SidebarChanged), "{sent:?}"); |
| 1211 | |
| 1212 | let sidebar = engine.sidebar().unwrap(); |
| 1213 | let order: Vec<(&str, bool)> = sidebar |
| 1214 | .chats |
| 1215 | .iter() |
| 1216 | .map(|chat| (chat.title.as_str(), chat.unread)) |
| 1217 | .collect(); |
| 1218 | assert_eq!( |
| 1219 | order, |
| 1220 | [("Ada Example", true), ("Mine", false), ("Read", false)] |
| 1221 | ); |
| 1222 | assert_eq!(sidebar.chats[0].kind, "oneOnOne"); |
| 1223 | assert_eq!(sidebar.chats[1].member_summary, "Ada Example"); |
| 1224 | assert_eq!(sidebar.teams[0].channels[0].name, "General"); |
| 1225 | } |
| 1226 | |
| 1227 | #[tokio::test] |
| 1228 | async fn channel_unread_comes_from_the_read_horizon_and_opening_marks_it_read() { |
| 1229 | let fake = Arc::new(Fake::default()); |
| 1230 | *fake.teams.lock().unwrap() = |
| 1231 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 1232 | fake.read_states.lock().unwrap().push(( |
| 1233 | CHANNEL.to_owned(), |
| 1234 | chatsvc::ReadHorizon { |
| 1235 | consumed_until_ms: 5, |
| 1236 | last_message_ms: 9, |
| 1237 | last_message_from: Some("8:orgid:user-ada".to_owned()), |
| 1238 | ..chatsvc::ReadHorizon::default() |
| 1239 | }, |
| 1240 | )); |
| 1241 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1242 | engine.refresh_sidebar().await.unwrap(); |
| 1243 | engine.refresh_sidebar().await.unwrap(); |
| 1244 | let channel = engine.store().channel(CHANNEL).unwrap().unwrap(); |
| 1245 | assert!(channel.unread); |
| 1246 | assert_eq!(channel.last_message_at, DateTime::from_timestamp_millis(9)); |
| 1247 | |
| 1248 | engine.mark_read(CHANNEL).await.unwrap(); |
| 1249 | |
| 1250 | assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread); |
| 1251 | let call = fake.calls().last().unwrap().clone(); |
| 1252 | assert!( |
| 1253 | call.starts_with(&format!("read horizon {CHANNEL} 9;")), |
| 1254 | "{call}" |
| 1255 | ); |
| 1256 | assert!(call.ends_with(";0"), "{call}"); |
| 1257 | } |
| 1258 | |
| 1259 | #[tokio::test] |
| 1260 | async fn refresh_sidebar_marks_muted_chats_and_keeps_flags_when_the_lookup_fails() { |
| 1261 | let fake = Arc::new(Fake::default()); |
| 1262 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 1263 | fake.muted_states |
| 1264 | .lock() |
| 1265 | .unwrap() |
| 1266 | .push((CHAT.to_owned(), true)); |
| 1267 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1268 | engine.refresh_sidebar().await.unwrap(); |
| 1269 | assert!(engine.sidebar().unwrap().chats[0].muted); |
| 1270 | |
| 1271 | *fake.muted_fails.lock().unwrap() = true; |
| 1272 | fake.muted_states.lock().unwrap().clear(); |
| 1273 | let mut events = engine.subscribe(); |
| 1274 | engine.refresh_sidebar().await.unwrap(); |
| 1275 | assert!(engine.sidebar().unwrap().chats[0].muted); |
| 1276 | let mut reported = false; |
| 1277 | while let Ok(event) = events.try_recv() { |
| 1278 | reported |= matches!(event, CoreEvent::Error { .. }); |
| 1279 | } |
| 1280 | assert!(reported); |
| 1281 | |
| 1282 | *fake.muted_fails.lock().unwrap() = false; |
| 1283 | engine.refresh_sidebar().await.unwrap(); |
| 1284 | assert!(engine.sidebar().unwrap().chats[0].muted); |
| 1285 | |
| 1286 | fake.muted_states |
| 1287 | .lock() |
| 1288 | .unwrap() |
| 1289 | .push((CHAT.to_owned(), false)); |
| 1290 | engine.refresh_sidebar().await.unwrap(); |
| 1291 | assert!(!engine.sidebar().unwrap().chats[0].muted); |
| 1292 | } |
| 1293 | |
| 1294 | #[tokio::test] |
| 1295 | async fn chatsvc_visibility_beats_the_graph_hidden_flag_and_graph_is_the_fallback() { |
| 1296 | let fake = Arc::new(Fake::default()); |
| 1297 | *fake.chats.lock().unwrap() = vec![ |
| 1298 | chat("19:graph-hidden@thread.v2", Some("Kept"), 30, 30, ME, true), |
| 1299 | chat( |
| 1300 | "19:chatsvc-hidden@thread.v2", |
| 1301 | Some("Dropped"), |
| 1302 | 20, |
| 1303 | 20, |
| 1304 | ME, |
| 1305 | false, |
| 1306 | ), |
| 1307 | chat( |
| 1308 | "19:unknown-hidden@thread.v2", |
| 1309 | Some("Unknown"), |
| 1310 | 10, |
| 1311 | 10, |
| 1312 | ME, |
| 1313 | true, |
| 1314 | ), |
| 1315 | chat("19:plain@thread.v2", Some("Plain"), 5, 5, ME, false), |
| 1316 | ]; |
| 1317 | fake.hidden_states.lock().unwrap().extend([ |
| 1318 | ("19:graph-hidden@thread.v2".to_owned(), false), |
| 1319 | ("19:chatsvc-hidden@thread.v2".to_owned(), true), |
| 1320 | ]); |
| 1321 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1322 | engine.refresh_sidebar().await.unwrap(); |
| 1323 | let titles: Vec<String> = engine |
| 1324 | .sidebar() |
| 1325 | .unwrap() |
| 1326 | .chats |
| 1327 | .iter() |
| 1328 | .map(|chat| chat.title.clone()) |
| 1329 | .collect(); |
| 1330 | assert_eq!(titles, ["Kept", "Plain"]); |
| 1331 | } |
| 1332 | |
| 1333 | fn numbered_chats(count: usize) -> Vec<Chat> { |
| 1334 | (0..count) |
| 1335 | .map(|index| { |
| 1336 | chat( |
| 1337 | &format!("19:c{index:03}@thread.v2"), |
| 1338 | Some(&format!("Chat {index:03}")), |
| 1339 | (count - index) as i64, |
| 1340 | 0, |
| 1341 | ME, |
| 1342 | false, |
| 1343 | ) |
| 1344 | }) |
| 1345 | .collect() |
| 1346 | } |
| 1347 | |
| 1348 | #[tokio::test] |
| 1349 | async fn older_chats_load_page_by_page_until_the_list_ends() { |
| 1350 | let fake = Arc::new(Fake::default()); |
| 1351 | *fake.chats.lock().unwrap() = numbered_chats(25); |
| 1352 | let engine = engine_with( |
| 1353 | &fake, |
| 1354 | SyncConfig { |
| 1355 | chat_limit: 10, |
| 1356 | chat_page_size: 5, |
| 1357 | ..SyncConfig::default() |
| 1358 | }, |
| 1359 | ); |
| 1360 | engine.refresh_sidebar().await.unwrap(); |
| 1361 | assert_eq!(engine.sidebar().unwrap().chats.len(), 10); |
| 1362 | assert!(engine.has_older_chats()); |
| 1363 | assert!(!engine.is_loading_older_chats()); |
| 1364 | |
| 1365 | let mut loaded = Vec::new(); |
| 1366 | while engine.has_older_chats() { |
| 1367 | loaded.push(engine.load_older_chats().await.unwrap()); |
| 1368 | } |
| 1369 | assert_eq!(loaded, [5, 5, 5]); |
| 1370 | assert_eq!(engine.sidebar().unwrap().chats.len(), 25); |
| 1371 | assert_eq!(engine.load_older_chats().await.unwrap(), 0); |
| 1372 | } |
| 1373 | |
| 1374 | #[tokio::test] |
| 1375 | async fn the_older_chat_continuation_survives_a_restart() { |
| 1376 | let fake = Arc::new(Fake::default()); |
| 1377 | *fake.chats.lock().unwrap() = numbered_chats(12); |
| 1378 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1379 | let config = SyncConfig { |
| 1380 | chat_limit: 4, |
| 1381 | chat_page_size: 4, |
| 1382 | ..SyncConfig::default() |
| 1383 | }; |
| 1384 | let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), config.clone()); |
| 1385 | engine.refresh_sidebar().await.unwrap(); |
| 1386 | engine.load_older_chats().await.unwrap(); |
| 1387 | assert_eq!(store.chat_count().unwrap(), 8); |
| 1388 | |
| 1389 | let restarted = SyncEngine::with_config(Handle(fake.clone()), store.clone(), config); |
| 1390 | assert!(restarted.has_older_chats()); |
| 1391 | assert_eq!(restarted.load_older_chats().await.unwrap(), 4); |
| 1392 | assert!(!restarted.has_older_chats()); |
| 1393 | assert_eq!(store.chat_count().unwrap(), 12); |
| 1394 | } |
| 1395 | |
| 1396 | #[tokio::test] |
| 1397 | async fn a_failed_older_page_drops_the_link_and_the_next_refresh_records_a_fresh_one() { |
| 1398 | let fake = Arc::new(Fake::default()); |
| 1399 | *fake.chats.lock().unwrap() = numbered_chats(8); |
| 1400 | let engine = engine_with( |
| 1401 | &fake, |
| 1402 | SyncConfig { |
| 1403 | chat_limit: 4, |
| 1404 | chat_page_size: 4, |
| 1405 | ..SyncConfig::default() |
| 1406 | }, |
| 1407 | ); |
| 1408 | engine.refresh_sidebar().await.unwrap(); |
| 1409 | *fake.chats_fail.lock().unwrap() = true; |
| 1410 | assert!(engine.load_older_chats().await.is_err()); |
| 1411 | assert!(!engine.is_loading_older_chats()); |
| 1412 | assert!(!engine.has_older_chats()); |
| 1413 | assert_eq!(engine.load_older_chats().await.unwrap(), 0); |
| 1414 | |
| 1415 | *fake.chats_fail.lock().unwrap() = false; |
| 1416 | engine.refresh_sidebar().await.unwrap(); |
| 1417 | assert!(engine.has_older_chats()); |
| 1418 | assert_eq!(engine.load_older_chats().await.unwrap(), 4); |
| 1419 | } |
| 1420 | |
| 1421 | #[tokio::test] |
| 1422 | async fn a_chat_hidden_in_the_app_stays_hidden_until_a_newer_message_arrives() { |
| 1423 | let fake = Arc::new(Fake::default()); |
| 1424 | let engine = chat_engine(&fake, small_pages()).await; |
| 1425 | engine.hide_chat(CHAT).await.unwrap(); |
| 1426 | |
| 1427 | engine.refresh_sidebar().await.unwrap(); |
| 1428 | assert!(engine.sidebar().unwrap().chats.is_empty()); |
| 1429 | engine.refresh_sidebar_full().await.unwrap(); |
| 1430 | assert!(engine.sidebar().unwrap().chats.is_empty()); |
| 1431 | |
| 1432 | *fake.chats.lock().unwrap() = vec![chat( |
| 1433 | CHAT, |
| 1434 | Some("Planning"), |
| 1435 | 10_000_000, |
| 1436 | 5, |
| 1437 | "user-ada", |
| 1438 | false, |
| 1439 | )]; |
| 1440 | engine.refresh_sidebar().await.unwrap(); |
| 1441 | assert_eq!(engine.sidebar().unwrap().chats.len(), 1); |
| 1442 | |
| 1443 | *fake.chats.lock().unwrap() = vec![chat( |
| 1444 | CHAT, |
| 1445 | Some("Planning"), |
| 1446 | 10_000_000, |
| 1447 | 5, |
| 1448 | "user-ada", |
| 1449 | false, |
| 1450 | )]; |
| 1451 | engine.refresh_sidebar_full().await.unwrap(); |
| 1452 | assert_eq!(engine.sidebar().unwrap().chats.len(), 1); |
| 1453 | } |
| 1454 | |
| 1455 | #[tokio::test] |
| 1456 | async fn undo_after_chatsvc_reported_the_hide_keeps_the_chat_visible() { |
| 1457 | let fake = Arc::new(Fake::default()); |
| 1458 | let engine = chat_engine(&fake, small_pages()).await; |
| 1459 | engine.hide_chat(CHAT).await.unwrap(); |
| 1460 | fake.hidden_states |
| 1461 | .lock() |
| 1462 | .unwrap() |
| 1463 | .push((CHAT.to_owned(), true)); |
| 1464 | engine.refresh_sidebar().await.unwrap(); |
| 1465 | assert!(engine.sidebar().unwrap().chats.is_empty()); |
| 1466 | |
| 1467 | engine.unhide_chat(CHAT).await.unwrap(); |
| 1468 | assert_eq!(engine.sidebar().unwrap().chats.len(), 1); |
| 1469 | engine.refresh_sidebar().await.unwrap(); |
| 1470 | assert_eq!(engine.sidebar().unwrap().chats.len(), 1); |
| 1471 | } |
| 1472 | |
| 1473 | #[tokio::test] |
| 1474 | async fn deep_chats_that_chatsvc_reports_hidden_are_removed_on_refresh() { |
| 1475 | let fake = Arc::new(Fake::default()); |
| 1476 | *fake.chats.lock().unwrap() = numbered_chats(8); |
| 1477 | let engine = engine_with( |
| 1478 | &fake, |
| 1479 | SyncConfig { |
| 1480 | chat_limit: 4, |
| 1481 | chat_page_size: 4, |
| 1482 | ..SyncConfig::default() |
| 1483 | }, |
| 1484 | ); |
| 1485 | engine.refresh_sidebar().await.unwrap(); |
| 1486 | engine.load_older_chats().await.unwrap(); |
| 1487 | assert_eq!(engine.store().chat_count().unwrap(), 8); |
| 1488 | |
| 1489 | fake.hidden_states |
| 1490 | .lock() |
| 1491 | .unwrap() |
| 1492 | .push(("19:c007@thread.v2".to_owned(), true)); |
| 1493 | engine.refresh_sidebar().await.unwrap(); |
| 1494 | assert_eq!(engine.store().chat_count().unwrap(), 7); |
| 1495 | } |
| 1496 | |
| 1497 | #[tokio::test] |
| 1498 | async fn older_pages_use_fresh_chat_states_when_none_were_loaded_yet() { |
| 1499 | let fake = Arc::new(Fake::default()); |
| 1500 | *fake.chats.lock().unwrap() = numbered_chats(8); |
| 1501 | fake.hidden_states |
| 1502 | .lock() |
| 1503 | .unwrap() |
| 1504 | .push(("19:c005@thread.v2".to_owned(), true)); |
| 1505 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 1506 | store.set_meta("chats_next_link", "chats:4:4").unwrap(); |
| 1507 | let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages()); |
| 1508 | |
| 1509 | assert_eq!(engine.load_older_chats().await.unwrap(), 4); |
| 1510 | assert_eq!(store.chat_count().unwrap(), 3); |
| 1511 | } |
| 1512 | |
| 1513 | #[tokio::test] |
| 1514 | async fn chat_state_actions_call_remote_and_update_the_store() { |
| 1515 | let fake = Arc::new(Fake::default()); |
| 1516 | let engine = chat_engine(&fake, small_pages()).await; |
| 1517 | let mut events = engine.subscribe(); |
| 1518 | |
| 1519 | engine.mark_unread(CHAT).await.unwrap(); |
| 1520 | let last_message_millis = (base() + Duration::minutes(5)).timestamp_millis(); |
| 1521 | assert_eq!( |
| 1522 | fake.calls().last().unwrap(), |
| 1523 | &format!( |
| 1524 | "mark_unread {CHAT} {ME} tenant-1 {}", |
| 1525 | last_message_millis - 1 |
| 1526 | ) |
| 1527 | ); |
| 1528 | let unread = engine.sidebar().unwrap().chats[0].clone(); |
| 1529 | assert!(unread.unread); |
| 1530 | assert_eq!( |
| 1531 | unread.last_read_at.unwrap().timestamp_millis(), |
| 1532 | last_message_millis - 1 |
| 1533 | ); |
| 1534 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 1535 | |
| 1536 | engine.set_chat_muted(CHAT, true).await.unwrap(); |
| 1537 | assert_eq!(fake.calls().last().unwrap(), &format!("mute {CHAT} true")); |
| 1538 | assert!(engine.sidebar().unwrap().chats[0].muted); |
| 1539 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 1540 | engine.set_chat_muted(CHAT, false).await.unwrap(); |
| 1541 | assert!(!engine.sidebar().unwrap().chats[0].muted); |
| 1542 | } |
| 1543 | |
| 1544 | #[tokio::test] |
| 1545 | async fn hide_removes_the_chat_and_unhide_brings_it_back() { |
| 1546 | let fake = Arc::new(Fake::default()); |
| 1547 | let engine = chat_engine(&fake, small_pages()).await; |
| 1548 | let mut events = engine.subscribe(); |
| 1549 | |
| 1550 | engine.hide_chat(CHAT).await.unwrap(); |
| 1551 | assert_eq!( |
| 1552 | fake.calls().last().unwrap(), |
| 1553 | &format!("hide {CHAT} {ME} tenant-1") |
| 1554 | ); |
| 1555 | assert!(engine.sidebar().unwrap().chats.is_empty()); |
| 1556 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 1557 | |
| 1558 | engine.unhide_chat(CHAT).await.unwrap(); |
| 1559 | assert_eq!( |
| 1560 | fake.calls().last().unwrap(), |
| 1561 | &format!("unhide {CHAT} {ME} tenant-1") |
| 1562 | ); |
| 1563 | assert_eq!(engine.sidebar().unwrap().chats.len(), 1); |
| 1564 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 1565 | } |
| 1566 | |
| 1567 | #[tokio::test] |
| 1568 | async fn leave_removes_the_chat() { |
| 1569 | let fake = Arc::new(Fake::default()); |
| 1570 | let engine = chat_engine(&fake, small_pages()).await; |
| 1571 | let mut events = engine.subscribe(); |
| 1572 | |
| 1573 | engine.leave_chat(CHAT).await.unwrap(); |
| 1574 | assert_eq!( |
| 1575 | fake.calls().last().unwrap(), |
| 1576 | &format!("remove member {CHAT} {ME}") |
| 1577 | ); |
| 1578 | assert!(engine.sidebar().unwrap().chats.is_empty()); |
| 1579 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 1580 | } |
| 1581 | |
| 1582 | #[tokio::test] |
| 1583 | async fn removing_a_member_drops_them_from_the_cached_chat() { |
| 1584 | let fake = Arc::new(Fake::default()); |
| 1585 | let engine = chat_engine(&fake, small_pages()).await; |
| 1586 | let mut events = engine.subscribe(); |
| 1587 | |
| 1588 | engine.remove_chat_member(CHAT, "user-ada").await.unwrap(); |
| 1589 | assert_eq!( |
| 1590 | fake.calls().last().unwrap(), |
| 1591 | &format!("remove member {CHAT} user-ada") |
| 1592 | ); |
| 1593 | let chats = engine.sidebar().unwrap().chats; |
| 1594 | let member_ids: Vec<Option<&str>> = chats[0] |
| 1595 | .members |
| 1596 | .iter() |
| 1597 | .map(|member| member.user_id.as_deref()) |
| 1598 | .collect(); |
| 1599 | assert_eq!(member_ids, [Some(ME)]); |
| 1600 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 1601 | } |
| 1602 | |
| 1603 | #[tokio::test] |
| 1604 | async fn adding_members_writes_them_and_extends_the_cached_chat() { |
| 1605 | let fake = Arc::new(Fake::default()); |
| 1606 | let engine = chat_engine(&fake, small_pages()).await; |
| 1607 | let mut events = engine.subscribe(); |
| 1608 | let people = [store::MemberRecord { |
| 1609 | user_id: Some("user-bob".to_owned()), |
| 1610 | display_name: "Bob".to_owned(), |
| 1611 | }]; |
| 1612 | |
| 1613 | engine |
| 1614 | .add_chat_members(CHAT, &people, chatsvc::HistoryShare::Days(7)) |
| 1615 | .await |
| 1616 | .unwrap(); |
| 1617 | assert_eq!( |
| 1618 | fake.calls().last().unwrap(), |
| 1619 | &format!("add members {CHAT} user-bob Days(7)") |
| 1620 | ); |
| 1621 | let chats = engine.sidebar().unwrap().chats; |
| 1622 | assert!( |
| 1623 | chats[0] |
| 1624 | .members |
| 1625 | .iter() |
| 1626 | .any(|member| member.user_id.as_deref() == Some("user-bob")) |
| 1627 | ); |
| 1628 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 1629 | } |
| 1630 | |
| 1631 | #[tokio::test] |
| 1632 | async fn failing_channel_listing_is_reported_not_fatal() { |
| 1633 | let fake = Arc::new(Fake::default()); |
| 1634 | *fake.teams.lock().unwrap() = vec![ |
| 1635 | serde_json::from_value(json!({"id": "team-ok", "displayName": "Fine"})).unwrap(), |
| 1636 | serde_json::from_value(json!({"id": "team-bad", "displayName": "Broken"})).unwrap(), |
| 1637 | ]; |
| 1638 | *fake.failing_team.lock().unwrap() = Some("team-bad".to_owned()); |
| 1639 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1640 | let mut events = engine.subscribe(); |
| 1641 | let summary = engine.refresh_sidebar().await.unwrap(); |
| 1642 | assert_eq!( |
| 1643 | (summary.teams, summary.channels, summary.failed_teams), |
| 1644 | (2, 1, 1) |
| 1645 | ); |
| 1646 | let sent: Vec<CoreEvent> = std::iter::from_fn(|| events.try_recv().ok()).collect(); |
| 1647 | assert!( |
| 1648 | sent.iter().any(|event| matches!(event, CoreEvent::Error { .. })), |
| 1649 | "{sent:?}" |
| 1650 | ); |
| 1651 | assert!(sent.contains(&CoreEvent::SidebarChanged), "{sent:?}"); |
| 1652 | } |
| 1653 | |
| 1654 | #[tokio::test] |
| 1655 | async fn cold_open_then_delta() { |
| 1656 | let fake = Arc::new(Fake::default()); |
| 1657 | fake.set_chat_messages(numbered(25)); |
| 1658 | let engine = chat_engine(&fake, small_pages()).await; |
| 1659 | let mut events = engine.subscribe(); |
| 1660 | |
| 1661 | assert!(engine.open_conversation(CHAT).unwrap().is_empty()); |
| 1662 | let first = engine.fetch_newer(CHAT).await.unwrap(); |
| 1663 | assert_eq!(first.added.len(), 10); |
| 1664 | assert!(first.updated.is_empty()); |
| 1665 | assert_eq!( |
| 1666 | events.try_recv().unwrap(), |
| 1667 | CoreEvent::MessagesChanged { |
| 1668 | conversation_id: CHAT.to_owned() |
| 1669 | } |
| 1670 | ); |
| 1671 | |
| 1672 | let cached = engine.open_conversation(CHAT).unwrap(); |
| 1673 | assert_eq!(cached.len(), 10); |
| 1674 | assert_eq!(cached.first().unwrap().message_id, "m0016"); |
| 1675 | assert_eq!(cached.last().unwrap().message_id, "m0025"); |
| 1676 | *fake.chat_calls.lock().unwrap() = 0; |
| 1677 | |
| 1678 | let mut all = numbered(25); |
| 1679 | all.extend((26..=28).map(|index| message(index, i64::from(index), "<p>fresh</p>"))); |
| 1680 | all[24] = message(25, 25, "<p>edited</p>"); |
| 1681 | fake.set_chat_messages(all); |
| 1682 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 1683 | let added: Vec<&str> = delta |
| 1684 | .added |
| 1685 | .iter() |
| 1686 | .map(|record| record.message_id.as_str()) |
| 1687 | .collect(); |
| 1688 | assert_eq!(added, ["m0026", "m0027", "m0028"]); |
| 1689 | assert_eq!(delta.updated.len(), 1); |
| 1690 | assert_eq!(delta.updated[0].body_html, "<p>edited</p>"); |
| 1691 | assert_eq!(*fake.chat_calls.lock().unwrap(), 1); |
| 1692 | |
| 1693 | while events.try_recv().is_ok() {} |
| 1694 | let unchanged = engine.fetch_newer(CHAT).await.unwrap(); |
| 1695 | assert!(unchanged.is_empty()); |
| 1696 | assert!(events.try_recv().is_err()); |
| 1697 | } |
| 1698 | |
| 1699 | #[tokio::test] |
| 1700 | async fn catch_up_walks_several_pages_until_the_known_message() { |
| 1701 | let fake = Arc::new(Fake::default()); |
| 1702 | fake.set_chat_messages(numbered(5)); |
| 1703 | let engine = chat_engine(&fake, small_pages()).await; |
| 1704 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1705 | |
| 1706 | fake.set_chat_messages(numbered(35)); |
| 1707 | *fake.chat_calls.lock().unwrap() = 0; |
| 1708 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 1709 | assert_eq!(delta.added.len(), 30); |
| 1710 | assert_eq!(*fake.chat_calls.lock().unwrap(), 4); |
| 1711 | assert_eq!(engine.store().message_count(CHAT).unwrap(), 35); |
| 1712 | } |
| 1713 | |
| 1714 | #[tokio::test] |
| 1715 | async fn load_older_pages_back_to_the_start() { |
| 1716 | let fake = Arc::new(Fake::default()); |
| 1717 | fake.set_chat_messages(numbered(25)); |
| 1718 | let engine = chat_engine(&fake, small_pages()).await; |
| 1719 | |
| 1720 | let older = engine.load_older(CHAT).await.unwrap(); |
| 1721 | assert_eq!(older.len(), 10); |
| 1722 | assert_eq!(older[0].message_id, "m0006"); |
| 1723 | |
| 1724 | let older = engine.load_older(CHAT).await.unwrap(); |
| 1725 | assert_eq!(older.first().unwrap().message_id, "m0001"); |
| 1726 | assert_eq!(older.len(), 5); |
| 1727 | assert!(!engine.store().sync_state(CHAT).unwrap().unwrap().has_more); |
| 1728 | assert_eq!(engine.store().message_count(CHAT).unwrap(), 25); |
| 1729 | |
| 1730 | *fake.chat_calls.lock().unwrap() = 0; |
| 1731 | assert!(engine.load_older(CHAT).await.unwrap().is_empty()); |
| 1732 | assert_eq!(*fake.chat_calls.lock().unwrap(), 0); |
| 1733 | } |
| 1734 | |
| 1735 | #[tokio::test] |
| 1736 | async fn system_messages_are_not_cached() { |
| 1737 | let fake = Arc::new(Fake::default()); |
| 1738 | let system: Message = serde_json::from_value(json!({ |
| 1739 | "id": "sys", "messageType": "systemEventMessage", |
| 1740 | "createdDateTime": (base() + Duration::minutes(50)).to_rfc3339(), |
| 1741 | "body": {"contentType": "html", "content": "<systemEventMessage/>"} |
| 1742 | })) |
| 1743 | .unwrap(); |
| 1744 | fake.set_chat_messages(vec![message(1, 1, "<p>a</p>"), system]); |
| 1745 | let engine = chat_engine(&fake, small_pages()).await; |
| 1746 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 1747 | assert_eq!(delta.added.len(), 1); |
| 1748 | } |
| 1749 | |
| 1750 | #[tokio::test] |
| 1751 | async fn deleted_and_text_messages_are_normalised() { |
| 1752 | let fake = Arc::new(Fake::default()); |
| 1753 | let deleted: Message = serde_json::from_value(json!({ |
| 1754 | "id": "gone", "messageType": "message", |
| 1755 | "createdDateTime": (base() + Duration::minutes(1)).to_rfc3339(), |
| 1756 | "deletedDateTime": (base() + Duration::minutes(2)).to_rfc3339(), |
| 1757 | "body": {"contentType": "html", "content": "<p>secret</p>"} |
| 1758 | })) |
| 1759 | .unwrap(); |
| 1760 | let text: Message = serde_json::from_value(json!({ |
| 1761 | "id": "plain", "messageType": "message", |
| 1762 | "createdDateTime": (base() + Duration::minutes(3)).to_rfc3339(), |
| 1763 | "from": {"application": {"id": "bot", "displayName": "Build Bot"}}, |
| 1764 | "body": {"contentType": "text", "content": " a < b\nnext "} |
| 1765 | })) |
| 1766 | .unwrap(); |
| 1767 | fake.set_chat_messages(vec![deleted, text]); |
| 1768 | let engine = chat_engine(&fake, small_pages()).await; |
| 1769 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1770 | let cached = engine.open_conversation(CHAT).unwrap(); |
| 1771 | assert!(cached[0].deleted); |
| 1772 | assert_eq!(cached[0].body_html, ""); |
| 1773 | assert_eq!(cached[1].body_html, "a < b<br>next"); |
| 1774 | assert_eq!(cached[1].sender_name.as_deref(), Some("Build Bot")); |
| 1775 | assert_eq!(cached[1].sender_id, None); |
| 1776 | } |
| 1777 | |
| 1778 | #[tokio::test] |
| 1779 | async fn send_message_converts_markdown_and_caches_the_answer() { |
| 1780 | let fake = Arc::new(Fake::default()); |
| 1781 | fake.set_chat_messages(numbered(3)); |
| 1782 | let engine = chat_engine(&fake, small_pages()).await; |
| 1783 | engine.fetch_newer(CHAT).await.unwrap(); |
| 1784 | let mut events = engine.subscribe(); |
| 1785 | |
| 1786 | let record = engine |
| 1787 | .send_message(CHAT, "hi **there** <x>", None) |
| 1788 | .await |
| 1789 | .unwrap(); |
| 1790 | assert_eq!( |
| 1791 | fake.sent.lock().unwrap().as_slice(), |
| 1792 | ["hi <b>there</b> <x>"] |
| 1793 | ); |
| 1794 | assert_eq!(record.message_id, "m9000"); |
| 1795 | assert_eq!(engine.store().message_count(CHAT).unwrap(), 4); |
| 1796 | assert_eq!( |
| 1797 | events.try_recv().unwrap(), |
| 1798 | CoreEvent::MessagesChanged { |
| 1799 | conversation_id: CHAT.to_owned() |
| 1800 | } |
| 1801 | ); |
| 1802 | assert!( |
| 1803 | engine |
| 1804 | .store() |
| 1805 | .sync_state(CHAT) |
| 1806 | .unwrap() |
| 1807 | .unwrap() |
| 1808 | .newest_seen |
| 1809 | .unwrap() |
| 1810 | >= record.created_at |
| 1811 | ); |
| 1812 | } |
| 1813 | |
| 1814 | #[tokio::test] |
| 1815 | async fn unknown_chat_is_fetched_stored_and_resolves() { |
| 1816 | let fake = Arc::new(Fake::default()); |
| 1817 | let meeting_chat = "19:meeting_abc@thread.v2"; |
| 1818 | *fake.fetchable_chats.lock().unwrap() = |
| 1819 | vec![chat(meeting_chat, Some("Standup"), 5, 5, ME, false)]; |
| 1820 | fake.set_chat_messages(vec![message(1, 1, "<p>hello</p>")]); |
| 1821 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1822 | let delta = engine.fetch_newer(meeting_chat).await.unwrap(); |
| 1823 | assert_eq!(delta.added.len(), 1); |
| 1824 | engine.fetch_newer(meeting_chat).await.unwrap(); |
| 1825 | assert_eq!(*fake.single_chat_calls.lock().unwrap(), 1); |
| 1826 | engine.send_message(meeting_chat, "hi", None).await.unwrap(); |
| 1827 | } |
| 1828 | |
| 1829 | #[tokio::test] |
| 1830 | async fn unknown_chat_missing_remotely_stays_an_error() { |
| 1831 | let fake = Arc::new(Fake::default()); |
| 1832 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1833 | assert!(matches!( |
| 1834 | engine.fetch_newer("19:meeting_gone@thread.v2").await, |
| 1835 | Err(Error::UnknownConversation(_)) |
| 1836 | )); |
| 1837 | assert!(matches!( |
| 1838 | engine |
| 1839 | .send_message("19:meeting_gone@thread.v2", "hi", None) |
| 1840 | .await, |
| 1841 | Err(Error::UnknownConversation(_)) |
| 1842 | )); |
| 1843 | } |
| 1844 | |
| 1845 | #[tokio::test] |
| 1846 | async fn unknown_conversation_is_an_error() { |
| 1847 | let fake = Arc::new(Fake::default()); |
| 1848 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1849 | assert!(matches!( |
| 1850 | engine.fetch_newer("nope").await, |
| 1851 | Err(Error::UnknownConversation(_)) |
| 1852 | )); |
| 1853 | } |
| 1854 | |
| 1855 | fn thread(id: u32, minute: i64, reply_count: u32) -> Message { |
| 1856 | let mut value = json!({ |
| 1857 | "id": format!("m{id:04}"), |
| 1858 | "messageType": "message", |
| 1859 | "createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(), |
| 1860 | "body": {"contentType": "html", "content": "<p>root</p>"}, |
| 1861 | "replies": (0..reply_count).map(|reply| json!({ |
| 1862 | "id": format!("r{id:04}-{reply}"), |
| 1863 | "messageType": "message", |
| 1864 | "replyToId": format!("m{id:04}"), |
| 1865 | "createdDateTime": (base() + Duration::minutes(minute + 1 + i64::from(reply))).to_rfc3339(), |
| 1866 | "body": {"contentType": "html", "content": "<p>reply</p>"} |
| 1867 | })).collect::<Vec<_>>() |
| 1868 | }); |
| 1869 | value["from"] = json!({"user": {"id": "user-ada", "displayName": "Ada Example"}}); |
| 1870 | serde_json::from_value(value).unwrap() |
| 1871 | } |
| 1872 | |
| 1873 | #[tokio::test] |
| 1874 | async fn channel_threads_are_flattened_and_paged_by_cursor() { |
| 1875 | let fake = Arc::new(Fake::default()); |
| 1876 | *fake.teams.lock().unwrap() = |
| 1877 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 1878 | *fake.channel_pages.lock().unwrap() = vec![ |
| 1879 | vec![thread(30, 30, 2), thread(20, 20, 0)], |
| 1880 | vec![thread(10, 10, 1)], |
| 1881 | ]; |
| 1882 | let engine = engine_with(&fake, small_pages()); |
| 1883 | engine.refresh_sidebar().await.unwrap(); |
| 1884 | |
| 1885 | let delta = engine.fetch_newer(CHANNEL).await.unwrap(); |
| 1886 | assert_eq!(delta.added.len(), 4); |
| 1887 | let reply = delta |
| 1888 | .added |
| 1889 | .iter() |
| 1890 | .find(|record| record.message_id == "r0030-1") |
| 1891 | .unwrap(); |
| 1892 | assert_eq!(reply.reply_to_id.as_deref(), Some("m0030")); |
| 1893 | let state = engine.store().sync_state(CHANNEL).unwrap().unwrap(); |
| 1894 | assert_eq!(state.older_cursor.as_deref(), Some("page:1")); |
| 1895 | assert!(state.has_more); |
| 1896 | |
| 1897 | let older = engine.load_older(CHANNEL).await.unwrap(); |
| 1898 | assert_eq!(older.len(), 2); |
| 1899 | assert!( |
| 1900 | !engine |
| 1901 | .store() |
| 1902 | .sync_state(CHANNEL) |
| 1903 | .unwrap() |
| 1904 | .unwrap() |
| 1905 | .has_more |
| 1906 | ); |
| 1907 | assert!(engine.load_older(CHANNEL).await.unwrap().is_empty()); |
| 1908 | assert_eq!(engine.store().message_count(CHANNEL).unwrap(), 6); |
| 1909 | |
| 1910 | assert!(matches!( |
| 1911 | engine.send_message(CHANNEL, "x", None).await, |
| 1912 | Err(Error::Unsupported(_)) |
| 1913 | )); |
| 1914 | } |
| 1915 | |
| 1916 | fn many_chats(count: i64) -> Vec<Chat> { |
| 1917 | (1..=count) |
| 1918 | .map(|index| { |
| 1919 | chat( |
| 1920 | &format!("19:c{index:03}@thread.v2"), |
| 1921 | Some("Topic"), |
| 1922 | index, |
| 1923 | index, |
| 1924 | "user-ada", |
| 1925 | false, |
| 1926 | ) |
| 1927 | }) |
| 1928 | .collect() |
| 1929 | } |
| 1930 | |
| 1931 | #[tokio::test] |
| 1932 | async fn warm_refresh_stops_after_the_first_unchanged_page() { |
| 1933 | let fake = Arc::new(Fake::default()); |
| 1934 | *fake.chats.lock().unwrap() = many_chats(120); |
| 1935 | let engine = engine_with( |
| 1936 | &fake, |
| 1937 | SyncConfig { |
| 1938 | chat_page_size: 25, |
| 1939 | ..SyncConfig::default() |
| 1940 | }, |
| 1941 | ); |
| 1942 | let cold = engine.refresh_sidebar().await.unwrap(); |
| 1943 | assert!(cold.full_chat_refresh); |
| 1944 | assert_eq!(cold.chat_pages, 5); |
| 1945 | assert_eq!(engine.store().chat_count().unwrap(), 120); |
| 1946 | |
| 1947 | *fake.chat_page_calls.lock().unwrap() = 0; |
| 1948 | *fake.team_calls.lock().unwrap() = 0; |
| 1949 | let warm = engine.refresh_sidebar().await.unwrap(); |
| 1950 | assert!(!warm.full_chat_refresh); |
| 1951 | assert_eq!(warm.chat_pages, 1); |
| 1952 | assert_eq!(*fake.chat_page_calls.lock().unwrap(), 1); |
| 1953 | assert_eq!(*fake.team_calls.lock().unwrap(), 0); |
| 1954 | assert!(!warm.teams_refreshed); |
| 1955 | } |
| 1956 | |
| 1957 | #[tokio::test] |
| 1958 | async fn warm_refresh_walks_on_while_pages_hold_new_activity() { |
| 1959 | let fake = Arc::new(Fake::default()); |
| 1960 | *fake.chats.lock().unwrap() = many_chats(120); |
| 1961 | let engine = engine_with( |
| 1962 | &fake, |
| 1963 | SyncConfig { |
| 1964 | chat_page_size: 25, |
| 1965 | ..SyncConfig::default() |
| 1966 | }, |
| 1967 | ); |
| 1968 | engine.refresh_sidebar().await.unwrap(); |
| 1969 | |
| 1970 | let mut chats = many_chats(120); |
| 1971 | for chat in chats.iter_mut().take(30) { |
| 1972 | *chat = self::chat(&chat.id.clone(), Some("Topic"), 500, 1, "user-ada", false); |
| 1973 | } |
| 1974 | *fake.chats.lock().unwrap() = chats; |
| 1975 | *fake.chat_page_calls.lock().unwrap() = 0; |
| 1976 | let warm = engine.refresh_sidebar().await.unwrap(); |
| 1977 | assert_eq!(warm.chat_pages, 3); |
| 1978 | } |
| 1979 | |
| 1980 | #[tokio::test] |
| 1981 | async fn full_refresh_prunes_chats_the_user_left() { |
| 1982 | let fake = Arc::new(Fake::default()); |
| 1983 | *fake.chats.lock().unwrap() = many_chats(5); |
| 1984 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1985 | engine.refresh_sidebar().await.unwrap(); |
| 1986 | assert_eq!(engine.store().chat_count().unwrap(), 5); |
| 1987 | |
| 1988 | *fake.chats.lock().unwrap() = many_chats(3); |
| 1989 | engine.refresh_sidebar_full().await.unwrap(); |
| 1990 | assert_eq!(engine.store().chat_count().unwrap(), 3); |
| 1991 | } |
| 1992 | |
| 1993 | #[tokio::test] |
| 1994 | async fn teams_refresh_is_skipped_inside_the_interval() { |
| 1995 | let fake = Arc::new(Fake::default()); |
| 1996 | *fake.teams.lock().unwrap() = |
| 1997 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 1998 | let engine = engine_with(&fake, SyncConfig::default()); |
| 1999 | assert!(engine.refresh_sidebar().await.unwrap().teams_refreshed); |
| 2000 | assert!(!engine.refresh_sidebar().await.unwrap().teams_refreshed); |
| 2001 | assert!(engine.refresh_sidebar_full().await.unwrap().teams_refreshed); |
| 2002 | assert_eq!(*fake.team_calls.lock().unwrap(), 2); |
| 2003 | } |
| 2004 | |
| 2005 | async fn channel_engine(fake: &Arc<Fake>) -> SyncEngine<Handle> { |
| 2006 | *fake.teams.lock().unwrap() = |
| 2007 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 2008 | *fake.channel_pages.lock().unwrap() = vec![vec![thread(30, 30, 1)]]; |
| 2009 | let engine = engine_with(fake, small_pages()); |
| 2010 | engine.refresh_sidebar().await.unwrap(); |
| 2011 | engine |
| 2012 | } |
| 2013 | |
| 2014 | #[tokio::test] |
| 2015 | async fn refreshing_a_thread_stores_every_reply_of_that_root() { |
| 2016 | let fake = Arc::new(Fake::default()); |
| 2017 | let engine = channel_engine(&fake).await; |
| 2018 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2019 | let root_id = engine.open_conversation(CHANNEL).unwrap()[0] |
| 2020 | .message_id |
| 2021 | .clone(); |
| 2022 | let reply = |id: u32, minute: i64, root: &str| -> Message { |
| 2023 | let mut reply = message(id, minute, &format!("<p>reply {id}</p>")); |
| 2024 | reply.reply_to_id = Some(root.to_owned()); |
| 2025 | reply |
| 2026 | }; |
| 2027 | *fake.thread_replies.lock().unwrap() = vec![ |
| 2028 | reply(7001, 90, &root_id), |
| 2029 | reply(7002, 91, &root_id), |
| 2030 | reply(7003, 92, "other-root"), |
| 2031 | ]; |
| 2032 | let delta = engine.refresh_thread(CHANNEL, &root_id).await.unwrap(); |
| 2033 | assert_eq!(delta.added.len(), 2); |
| 2034 | let thread = engine.store().thread_messages(CHANNEL, &root_id).unwrap(); |
| 2035 | assert_eq!(thread.len(), 4); |
| 2036 | } |
| 2037 | |
| 2038 | #[tokio::test] |
| 2039 | async fn channel_delta_picks_up_new_and_edited_posts_and_stores_the_link() { |
| 2040 | let fake = Arc::new(Fake::default()); |
| 2041 | let engine = channel_engine(&fake).await; |
| 2042 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2043 | let state = engine.store().sync_state(CHANNEL).unwrap().unwrap(); |
| 2044 | assert_eq!(state.delta_link.as_deref(), Some("delta:1")); |
| 2045 | |
| 2046 | let mut edited = thread(30, 30, 0); |
| 2047 | edited.body = |
| 2048 | serde_json::from_value(json!({"contentType": "html", "content": "<p>edited root</p>"})) |
| 2049 | .unwrap(); |
| 2050 | *fake.delta_items.lock().unwrap() = vec![edited, thread(40, 40, 0)]; |
| 2051 | let delta = engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2052 | assert_eq!( |
| 2053 | delta |
| 2054 | .added |
| 2055 | .iter() |
| 2056 | .map(|record| record.message_id.as_str()) |
| 2057 | .collect::<Vec<_>>(), |
| 2058 | ["m0040"] |
| 2059 | ); |
| 2060 | assert_eq!(delta.updated.len(), 1); |
| 2061 | assert_eq!(delta.updated[0].body_html, "<p>edited root</p>"); |
| 2062 | assert!( |
| 2063 | fake.calls() |
| 2064 | .iter() |
| 2065 | .any(|call| call == "channel_delta_at delta:1") |
| 2066 | ); |
| 2067 | assert_eq!( |
| 2068 | engine |
| 2069 | .store() |
| 2070 | .sync_state(CHANNEL) |
| 2071 | .unwrap() |
| 2072 | .unwrap() |
| 2073 | .delta_link |
| 2074 | .as_deref(), |
| 2075 | Some("delta:2") |
| 2076 | ); |
| 2077 | } |
| 2078 | |
| 2079 | #[tokio::test] |
| 2080 | async fn channel_delta_failure_falls_back_to_the_first_page() { |
| 2081 | let fake = Arc::new(Fake::default()); |
| 2082 | let engine = channel_engine(&fake).await; |
| 2083 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2084 | |
| 2085 | *fake.delta_fails.lock().unwrap() = true; |
| 2086 | *fake.channel_pages.lock().unwrap() = vec![vec![thread(50, 50, 0), thread(30, 30, 1)]]; |
| 2087 | let delta = engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2088 | assert_eq!( |
| 2089 | delta |
| 2090 | .added |
| 2091 | .iter() |
| 2092 | .map(|record| record.message_id.as_str()) |
| 2093 | .collect::<Vec<_>>(), |
| 2094 | ["m0050"] |
| 2095 | ); |
| 2096 | assert_eq!( |
| 2097 | engine |
| 2098 | .store() |
| 2099 | .sync_state(CHANNEL) |
| 2100 | .unwrap() |
| 2101 | .unwrap() |
| 2102 | .delta_link, |
| 2103 | None |
| 2104 | ); |
| 2105 | } |
| 2106 | |
| 2107 | #[tokio::test] |
| 2108 | async fn channel_sends_post_and_reply_through_graph() { |
| 2109 | let fake = Arc::new(Fake::default()); |
| 2110 | let engine = channel_engine(&fake).await; |
| 2111 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 2112 | |
| 2113 | engine |
| 2114 | .post_to_channel(CHANNEL, "hello", Some("Topic")) |
| 2115 | .await |
| 2116 | .unwrap(); |
| 2117 | let reply = engine |
| 2118 | .send_message(CHANNEL, "answer", Some("m0030")) |
| 2119 | .await |
| 2120 | .unwrap(); |
| 2121 | assert_eq!(reply.message_id, "m9002"); |
| 2122 | let sends: Vec<String> = fake |
| 2123 | .calls() |
| 2124 | .into_iter() |
| 2125 | .filter(|call| !call.starts_with("channel_delta")) |
| 2126 | .collect(); |
| 2127 | assert_eq!(sends, ["post subject=Some(\"Topic\")", "reply to m0030"]); |
| 2128 | assert!(engine.post_to_channel(CHAT, "x", None).await.is_err()); |
| 2129 | } |
| 2130 | |
| 2131 | #[tokio::test] |
| 2132 | async fn chat_upload_goes_to_chat_files_and_is_shared_with_the_other_members() { |
| 2133 | let fake = Arc::new(Fake::default()); |
| 2134 | let engine = chat_engine(&fake, small_pages()).await; |
| 2135 | let steps = Arc::new(Mutex::new(Vec::new())); |
| 2136 | let seen = steps.clone(); |
| 2137 | |
| 2138 | let reference = engine |
| 2139 | .upload_attachment(CHAT, "plan.pdf", &[1, 2, 3], move |percent| { |
| 2140 | seen.lock().unwrap().push(percent) |
| 2141 | }) |
| 2142 | .await |
| 2143 | .unwrap(); |
| 2144 | |
| 2145 | assert_eq!( |
| 2146 | fake.calls(), |
| 2147 | ["upload chat-files plan.pdf 3", "share item-1 user-ada"] |
| 2148 | ); |
| 2149 | assert_eq!(*steps.lock().unwrap(), [50, 100]); |
| 2150 | assert_eq!(reference.attachment_id, "GUID-1"); |
| 2151 | assert_eq!(reference.content_url, "https://files.example/dav"); |
| 2152 | assert_eq!(reference.name, "plan.pdf"); |
| 2153 | } |
| 2154 | |
| 2155 | #[tokio::test] |
| 2156 | async fn channel_upload_uses_the_cached_files_folder_and_shares_nothing() { |
| 2157 | let fake = Arc::new(Fake::default()); |
| 2158 | let engine = channel_engine(&fake).await; |
| 2159 | |
| 2160 | engine |
| 2161 | .upload_attachment(CHANNEL, "a.pdf", &[1], |_| {}) |
| 2162 | .await |
| 2163 | .unwrap(); |
| 2164 | engine |
| 2165 | .upload_attachment(CHANNEL, "b.pdf", &[1, 2], |_| {}) |
| 2166 | .await |
| 2167 | .unwrap(); |
| 2168 | |
| 2169 | assert_eq!(*fake.folder_requests.lock().unwrap(), 1); |
| 2170 | let uploads: Vec<String> = fake |
| 2171 | .calls() |
| 2172 | .into_iter() |
| 2173 | .filter(|call| call.starts_with("upload") || call.starts_with("share")) |
| 2174 | .collect(); |
| 2175 | assert_eq!( |
| 2176 | uploads, |
| 2177 | [ |
| 2178 | "upload drive-1/folder-1 a.pdf 1", |
| 2179 | "upload drive-1/folder-1 b.pdf 2" |
| 2180 | ] |
| 2181 | ); |
| 2182 | } |
| 2183 | |
| 2184 | fn uploaded() -> UploadedFile { |
| 2185 | UploadedFile { |
| 2186 | drive_id: "drive-1".into(), |
| 2187 | item_id: "item-1".into(), |
| 2188 | name: "a.pdf".into(), |
| 2189 | web_url: "https://files.example/web".into(), |
| 2190 | web_dav_url: None, |
| 2191 | etag: "\"{GUID-1},2\"".into(), |
| 2192 | } |
| 2193 | } |
| 2194 | |
| 2195 | #[tokio::test] |
| 2196 | async fn sharing_fails_loudly_when_the_chat_members_are_unknown() { |
| 2197 | let fake = Arc::new(Fake::default()); |
| 2198 | let engine = chat_engine(&fake, small_pages()).await; |
| 2199 | engine |
| 2200 | .store() |
| 2201 | .upsert_chats(&[store::ChatRecord { |
| 2202 | id: "19:bare@thread.v2".into(), |
| 2203 | ..Default::default() |
| 2204 | }]) |
| 2205 | .unwrap(); |
| 2206 | |
| 2207 | let error = engine |
| 2208 | .share_attachment("19:bare@thread.v2", &uploaded()) |
| 2209 | .await |
| 2210 | .unwrap_err(); |
| 2211 | assert!(error.to_string().contains("Chat members not loaded yet.")); |
| 2212 | engine.share_attachment(CHAT, &uploaded()).await.unwrap(); |
| 2213 | assert!(fake.calls().contains(&"share item-1 user-ada".to_owned())); |
| 2214 | } |
| 2215 | |
| 2216 | #[tokio::test] |
| 2217 | async fn discarding_an_upload_deletes_the_drive_item() { |
| 2218 | let fake = Arc::new(Fake::default()); |
| 2219 | let engine = chat_engine(&fake, small_pages()).await; |
| 2220 | engine.discard_attachment(&uploaded()).await.unwrap(); |
| 2221 | assert_eq!(fake.calls(), ["delete_file item-1"]); |
| 2222 | } |
| 2223 | |
| 2224 | #[tokio::test] |
| 2225 | async fn an_edit_keeps_the_images_and_files_of_the_original() { |
| 2226 | let fake = Arc::new(Fake::default()); |
| 2227 | let engine = chat_engine(&fake, small_pages()).await; |
| 2228 | engine |
| 2229 | .store() |
| 2230 | .upsert_messages(&[store::MessageRecord { |
| 2231 | conversation_id: CHAT.into(), |
| 2232 | message_id: "m-edit".into(), |
| 2233 | created_at: base(), |
| 2234 | 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(), |
| 2235 | attachments_json: r#"[{"content_type":"reference","name":"a.pdf","url":"https://x/a.pdf","text":null}]"#.into(), |
| 2236 | reactions_json: "[]".into(), |
| 2237 | mentions_json: "[]".into(), |
| 2238 | ..Default::default() |
| 2239 | }]) |
| 2240 | .unwrap(); |
| 2241 | |
| 2242 | let _ = engine.edit_message(CHAT, "m-edit", "new").await; |
| 2243 | |
| 2244 | let call = fake |
| 2245 | .calls() |
| 2246 | .into_iter() |
| 2247 | .find(|call| call.starts_with("edit")) |
| 2248 | .unwrap(); |
| 2249 | assert!(call.contains("new<p><img src=\"https://graph.microsoft.com/")); |
| 2250 | let extras = fake.extras_sent.lock().unwrap(); |
| 2251 | assert_eq!(extras[0].files[0].attachment_id, "G1"); |
| 2252 | assert_eq!(extras[0].files[0].content_url, "https://x/a.pdf"); |
| 2253 | } |
| 2254 | |
| 2255 | #[tokio::test] |
| 2256 | async fn download_streams_every_chunk_and_reports_progress() { |
| 2257 | let fake = Arc::new(Fake::default()); |
| 2258 | let engine = chat_engine(&fake, small_pages()).await; |
| 2259 | let written = Mutex::new(0usize); |
| 2260 | let percents = Mutex::new(Vec::new()); |
| 2261 | let shared = engine |
| 2262 | .download_file( |
| 2263 | "https://files.example/doc", |
| 2264 | |bytes| { |
| 2265 | *written.lock().unwrap() += bytes.len(); |
| 2266 | Ok(()) |
| 2267 | }, |
| 2268 | |percent| percents.lock().unwrap().push(percent), |
| 2269 | ) |
| 2270 | .await |
| 2271 | .unwrap(); |
| 2272 | assert_eq!(*written.lock().unwrap() as u64, shared.size); |
| 2273 | let chunk = graph::DOWNLOAD_CHUNK_BYTES; |
| 2274 | let ranges: Vec<String> = fake |
| 2275 | .calls() |
| 2276 | .into_iter() |
| 2277 | .filter(|call| call.starts_with("range")) |
| 2278 | .collect(); |
| 2279 | assert_eq!( |
| 2280 | ranges, |
| 2281 | vec![ |
| 2282 | format!("range https://dl.example/big 0-{}", chunk - 1), |
| 2283 | format!("range https://dl.example/big {chunk}-{}", 2 * chunk - 1), |
| 2284 | format!("range https://dl.example/big {}-", 2 * chunk), |
| 2285 | ] |
| 2286 | ); |
| 2287 | let percents = percents.lock().unwrap(); |
| 2288 | assert_eq!(percents.first(), Some(&0)); |
| 2289 | assert_eq!(percents.last(), Some(&100)); |
| 2290 | assert!(percents.windows(2).all(|pair| pair[0] <= pair[1])); |
| 2291 | } |
| 2292 | |
| 2293 | #[tokio::test] |
| 2294 | async fn library_download_uses_the_listing_url_and_refetches_the_item_without_one() { |
| 2295 | let library_file = |cached_url: Option<&str>| teams_core::LibraryFile { |
| 2296 | drive_id: "drive".into(), |
| 2297 | item_id: "item".into(), |
| 2298 | name: "big.bin".into(), |
| 2299 | size: 2 * graph::DOWNLOAD_CHUNK_BYTES + 3, |
| 2300 | cached_url: cached_url.map(str::to_owned), |
| 2301 | }; |
| 2302 | let fake = Arc::new(Fake::default()); |
| 2303 | let engine = chat_engine(&fake, small_pages()).await; |
| 2304 | engine |
| 2305 | .download_library_file( |
| 2306 | &library_file(Some("https://dl.example/listed")), |
| 2307 | |_| Ok(()), |
| 2308 | |_| {}, |
| 2309 | ) |
| 2310 | .await |
| 2311 | .unwrap(); |
| 2312 | let calls = fake.calls(); |
| 2313 | assert!(!calls.iter().any(|call| call.starts_with("resolve"))); |
| 2314 | assert!( |
| 2315 | calls |
| 2316 | .iter() |
| 2317 | .any(|call| call.starts_with("range https://dl.example/listed ")) |
| 2318 | ); |
| 2319 | engine |
| 2320 | .download_library_file(&library_file(None), |_| Ok(()), |_| {}) |
| 2321 | .await |
| 2322 | .unwrap(); |
| 2323 | let calls = fake.calls(); |
| 2324 | assert!(calls.contains(&"resolve item drive/item".to_owned())); |
| 2325 | assert!( |
| 2326 | calls |
| 2327 | .iter() |
| 2328 | .any(|call| call.starts_with("range https://dl.example/fresh ")) |
| 2329 | ); |
| 2330 | } |
| 2331 | |
| 2332 | #[tokio::test] |
| 2333 | async fn download_keeps_a_file_that_grew_past_the_reported_size() { |
| 2334 | let fake = Arc::new(Fake::default()); |
| 2335 | let engine = chat_engine(&fake, small_pages()).await; |
| 2336 | let written = Mutex::new(0usize); |
| 2337 | let percents = Mutex::new(Vec::new()); |
| 2338 | let shared = engine |
| 2339 | .download_file( |
| 2340 | "https://files.example/grown", |
| 2341 | |bytes| { |
| 2342 | *written.lock().unwrap() += bytes.len(); |
| 2343 | Ok(()) |
| 2344 | }, |
| 2345 | |percent| percents.lock().unwrap().push(percent), |
| 2346 | ) |
| 2347 | .await |
| 2348 | .unwrap(); |
| 2349 | assert_eq!(*written.lock().unwrap() as u64, shared.size + 10); |
| 2350 | assert!( |
| 2351 | percents |
| 2352 | .lock() |
| 2353 | .unwrap() |
| 2354 | .iter() |
| 2355 | .all(|percent| *percent <= 100) |
| 2356 | ); |
| 2357 | } |
| 2358 | |
| 2359 | #[tokio::test] |
| 2360 | async fn download_rejects_a_short_chunk() { |
| 2361 | let fake = Arc::new(Fake::default()); |
| 2362 | let engine = chat_engine(&fake, small_pages()).await; |
| 2363 | let result = engine |
| 2364 | .download_file("https://files.example/short", |_| Ok(()), |_| {}) |
| 2365 | .await; |
| 2366 | assert!(result.is_err()); |
| 2367 | } |
| 2368 | |
| 2369 | #[tokio::test] |
| 2370 | async fn download_stops_when_the_writer_fails() { |
| 2371 | let fake = Arc::new(Fake::default()); |
| 2372 | let engine = chat_engine(&fake, small_pages()).await; |
| 2373 | let result = engine |
| 2374 | .download_file( |
| 2375 | "https://files.example/doc", |
| 2376 | |_| Err(std::io::Error::other("disk full")), |
| 2377 | |_| {}, |
| 2378 | ) |
| 2379 | .await; |
| 2380 | assert!(matches!(result, Err(Error::Io(_)))); |
| 2381 | let ranges = fake |
| 2382 | .calls() |
| 2383 | .into_iter() |
| 2384 | .filter(|call| call.starts_with("range")) |
| 2385 | .count(); |
| 2386 | assert_eq!(ranges, 1); |
| 2387 | } |
| 2388 | |
| 2389 | #[tokio::test] |
| 2390 | async fn upload_to_an_unknown_conversation_fails() { |
| 2391 | let fake = Arc::new(Fake::default()); |
| 2392 | let engine = chat_engine(&fake, small_pages()).await; |
| 2393 | assert!( |
| 2394 | engine |
| 2395 | .upload_attachment("unknown", "a.pdf", &[1], |_| {}) |
| 2396 | .await |
| 2397 | .is_err() |
| 2398 | ); |
| 2399 | } |
| 2400 | |
| 2401 | #[tokio::test] |
| 2402 | async fn the_notes_chat_takes_every_write_without_a_graph_chat_lookup() { |
| 2403 | let fake = Arc::new(Fake::default()); |
| 2404 | let engine = chat_engine(&fake, small_pages()).await; |
| 2405 | let extras = MessageExtras { |
| 2406 | kept: Vec::new(), |
| 2407 | images: vec![HostedImage { |
| 2408 | content_type: "image/png".into(), |
| 2409 | bytes: Arc::new(vec![9]), |
| 2410 | }], |
| 2411 | files: Vec::new(), |
| 2412 | importance: None, |
| 2413 | }; |
| 2414 | |
| 2415 | let sent = engine |
| 2416 | .send_message_with_extras(NOTES_CHAT_ID, "note to self", None, &[], &extras) |
| 2417 | .await |
| 2418 | .unwrap(); |
| 2419 | fake.set_chat_messages(vec![message(9000, 500, "<p>note to self</p>")]); |
| 2420 | engine |
| 2421 | .reply_to_with_extras( |
| 2422 | NOTES_CHAT_ID, |
| 2423 | &sent.message_id, |
| 2424 | "again", |
| 2425 | &[], |
| 2426 | &MessageExtras::default(), |
| 2427 | ) |
| 2428 | .await |
| 2429 | .unwrap(); |
| 2430 | engine |
| 2431 | .edit_message_html(NOTES_CHAT_ID, &sent.message_id, "edited", &[]) |
| 2432 | .await |
| 2433 | .unwrap(); |
| 2434 | engine |
| 2435 | .set_reaction(NOTES_CHAT_ID, &sent.message_id, "\u{1f44d}") |
| 2436 | .await |
| 2437 | .unwrap(); |
| 2438 | engine |
| 2439 | .unset_reaction(NOTES_CHAT_ID, &sent.message_id, "\u{1f44d}") |
| 2440 | .await |
| 2441 | .unwrap(); |
| 2442 | engine |
| 2443 | .upload_attachment(NOTES_CHAT_ID, "plan.txt", b"plan", |_| {}) |
| 2444 | .await |
| 2445 | .unwrap(); |
| 2446 | engine |
| 2447 | .soft_delete_message(NOTES_CHAT_ID, &sent.message_id) |
| 2448 | .await |
| 2449 | .unwrap(); |
| 2450 | |
| 2451 | assert_eq!(*fake.single_chat_calls.lock().unwrap(), 0); |
| 2452 | assert_eq!(fake.sent.lock().unwrap().as_slice(), ["note to self"]); |
| 2453 | let calls = fake.calls(); |
| 2454 | for expected in [ |
| 2455 | "chatsvc post 48:notes", |
| 2456 | "edit m9000 edited", |
| 2457 | "set_reaction m9000 \u{1f44d}", |
| 2458 | "unset_reaction m9000 \u{1f44d}", |
| 2459 | "upload chat-files plan.txt 4", |
| 2460 | "soft_delete user-me m9000", |
| 2461 | ] { |
| 2462 | assert!( |
| 2463 | calls.iter().any(|call| call == expected), |
| 2464 | "{expected} in {calls:?}" |
| 2465 | ); |
| 2466 | } |
| 2467 | assert!( |
| 2468 | calls |
| 2469 | .iter() |
| 2470 | .any(|call| call.starts_with("share ") && call.ends_with(' ')), |
| 2471 | "{calls:?}" |
| 2472 | ); |
| 2473 | } |
| 2474 | |
| 2475 | #[tokio::test] |
| 2476 | async fn send_with_extras_hands_images_and_files_to_the_remote() { |
| 2477 | let fake = Arc::new(Fake::default()); |
| 2478 | let engine = chat_engine(&fake, small_pages()).await; |
| 2479 | let extras = MessageExtras { |
| 2480 | kept: Vec::new(), |
| 2481 | images: vec![HostedImage { |
| 2482 | content_type: "image/png".into(), |
| 2483 | bytes: Arc::new(vec![9]), |
| 2484 | }], |
| 2485 | files: Vec::new(), |
| 2486 | importance: None, |
| 2487 | }; |
| 2488 | |
| 2489 | engine |
| 2490 | .send_message_with_extras(CHAT, "look", None, &[], &extras) |
| 2491 | .await |
| 2492 | .unwrap(); |
| 2493 | engine.send_message(CHAT, "plain", None).await.unwrap(); |
| 2494 | |
| 2495 | let sent = fake.extras_sent.lock().unwrap(); |
| 2496 | assert_eq!(sent[0], extras); |
| 2497 | assert!(sent[1].is_empty()); |
| 2498 | } |
| 2499 | |
| 2500 | #[tokio::test] |
| 2501 | async fn a_sent_image_is_cached_under_the_server_url_without_a_download() { |
| 2502 | let directory = tempfile::tempdir().unwrap(); |
| 2503 | let fake = Arc::new(Fake::default()); |
| 2504 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 2505 | *fake.send_answer_body.lock().unwrap() = Some(format!("<p>look</p><img src=\"{HOSTED}\">")); |
| 2506 | let engine = engine_with(&fake, small_pages()) |
| 2507 | .with_image_dir(directory.path(), 1024 * 1024) |
| 2508 | .unwrap(); |
| 2509 | engine.refresh_sidebar().await.unwrap(); |
| 2510 | let extras = MessageExtras { |
| 2511 | kept: Vec::new(), |
| 2512 | images: vec![HostedImage { |
| 2513 | content_type: "image/png".into(), |
| 2514 | bytes: Arc::new(vec![9, 8, 7]), |
| 2515 | }], |
| 2516 | files: Vec::new(), |
| 2517 | importance: None, |
| 2518 | }; |
| 2519 | let mut events = engine.subscribe(); |
| 2520 | |
| 2521 | engine |
| 2522 | .send_message_with_extras(CHAT, "look", None, &[], &extras) |
| 2523 | .await |
| 2524 | .unwrap(); |
| 2525 | |
| 2526 | assert_eq!(engine.image(HOSTED).unwrap().bytes, vec![9, 8, 7]); |
| 2527 | assert!(fake.hosted_requests.lock().unwrap().is_empty()); |
| 2528 | let mut seeded = false; |
| 2529 | while let Ok(event) = events.try_recv() { |
| 2530 | seeded |= |
| 2531 | matches!(event, CoreEvent::ImagesChanged { keys } if keys == vec![HOSTED.to_owned()]); |
| 2532 | } |
| 2533 | assert!(seeded); |
| 2534 | } |
| 2535 | |
| 2536 | #[tokio::test] |
| 2537 | async fn refresh_message_upserts_an_edit_older_than_the_newest_cached() { |
| 2538 | let fake = Arc::new(Fake::default()); |
| 2539 | fake.set_chat_messages(numbered(5)); |
| 2540 | let engine = chat_engine(&fake, small_pages()).await; |
| 2541 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2542 | let mut events = engine.subscribe(); |
| 2543 | |
| 2544 | let mut changed = numbered(5); |
| 2545 | changed[1] = message(2, 2, "<p>old but edited</p>"); |
| 2546 | fake.set_chat_messages(changed); |
| 2547 | let record = engine |
| 2548 | .refresh_message(CHAT, "m0002") |
| 2549 | .await |
| 2550 | .unwrap() |
| 2551 | .unwrap(); |
| 2552 | assert_eq!(record.body_html, "<p>old but edited</p>"); |
| 2553 | assert_eq!( |
| 2554 | engine.open_conversation(CHAT).unwrap()[1].body_html, |
| 2555 | "<p>old but edited</p>" |
| 2556 | ); |
| 2557 | assert_eq!( |
| 2558 | events.try_recv().unwrap(), |
| 2559 | CoreEvent::MessagesChanged { |
| 2560 | conversation_id: CHAT.to_owned() |
| 2561 | } |
| 2562 | ); |
| 2563 | |
| 2564 | assert!(engine.refresh_message(CHAT, "m0999").await.is_err()); |
| 2565 | } |
| 2566 | |
| 2567 | #[tokio::test] |
| 2568 | async fn refresh_message_marks_a_message_it_stores_first_as_late() { |
| 2569 | let fake = Arc::new(Fake::default()); |
| 2570 | fake.set_chat_messages(numbered(3)); |
| 2571 | let engine = chat_engine(&fake, small_pages()).await; |
| 2572 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2573 | let mut reacted = message(4, 4, "<p>PR link</p>"); |
| 2574 | reacted.reactions = serde_json::from_value(json!([ |
| 2575 | {"reactionType": "like", "user": {"user": {"id": ME}}} |
| 2576 | ])) |
| 2577 | .unwrap(); |
| 2578 | fake.chat_messages.lock().unwrap().push(reacted); |
| 2579 | let mut events = engine.subscribe(); |
| 2580 | |
| 2581 | engine.refresh_message(CHAT, "m0004").await.unwrap(); |
| 2582 | assert_eq!( |
| 2583 | events.try_recv().unwrap(), |
| 2584 | CoreEvent::MessagesStoredLate { |
| 2585 | conversation_id: CHAT.to_owned(), |
| 2586 | message_ids: vec!["m0004".to_owned()], |
| 2587 | } |
| 2588 | ); |
| 2589 | assert_eq!( |
| 2590 | events.try_recv().unwrap(), |
| 2591 | CoreEvent::MessagesChanged { |
| 2592 | conversation_id: CHAT.to_owned() |
| 2593 | } |
| 2594 | ); |
| 2595 | |
| 2596 | engine.refresh_message(CHAT, "m0004").await.unwrap(); |
| 2597 | while let Ok(event) = events.try_recv() { |
| 2598 | assert!(!matches!(event, CoreEvent::MessagesStoredLate { .. })); |
| 2599 | } |
| 2600 | } |
| 2601 | |
| 2602 | #[tokio::test] |
| 2603 | async fn fetch_until_cached_retries_while_graph_lags_behind_the_push() { |
| 2604 | let fake = Arc::new(Fake::default()); |
| 2605 | fake.set_chat_messages(numbered(3)); |
| 2606 | let engine = chat_engine(&fake, small_pages()).await; |
| 2607 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2608 | let calls_before = *fake.chat_calls.lock().unwrap(); |
| 2609 | *fake.lagging_message.lock().unwrap() = Some((calls_before + 2, message(4, 4, "<p>neu</p>"))); |
| 2610 | let delays = [std::time::Duration::ZERO; 3]; |
| 2611 | |
| 2612 | assert!(engine.fetch_newer(CHAT).await.unwrap().added.is_empty()); |
| 2613 | let delta = engine |
| 2614 | .fetch_until_cached(CHAT, "m0004", &delays) |
| 2615 | .await |
| 2616 | .unwrap(); |
| 2617 | assert_eq!(delta.added.len(), 1); |
| 2618 | assert_eq!(delta.added[0].message_id, "m0004"); |
| 2619 | assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2); |
| 2620 | |
| 2621 | let delta = engine |
| 2622 | .fetch_until_cached(CHAT, "m0004", &delays) |
| 2623 | .await |
| 2624 | .unwrap(); |
| 2625 | assert!(delta.is_empty()); |
| 2626 | assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 2); |
| 2627 | } |
| 2628 | |
| 2629 | #[tokio::test] |
| 2630 | async fn fetch_until_cached_gives_up_after_the_last_delay() { |
| 2631 | let fake = Arc::new(Fake::default()); |
| 2632 | fake.set_chat_messages(numbered(3)); |
| 2633 | let engine = chat_engine(&fake, small_pages()).await; |
| 2634 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2635 | let calls_before = *fake.chat_calls.lock().unwrap(); |
| 2636 | |
| 2637 | let delta = engine |
| 2638 | .fetch_until_cached(CHAT, "m0099", &[std::time::Duration::ZERO; 3]) |
| 2639 | .await |
| 2640 | .unwrap(); |
| 2641 | assert!(delta.is_empty()); |
| 2642 | assert_eq!(*fake.chat_calls.lock().unwrap(), calls_before + 3); |
| 2643 | } |
| 2644 | |
| 2645 | #[tokio::test] |
| 2646 | async fn send_typing_addresses_chats_channels_and_threads() { |
| 2647 | let chat_fake = Arc::new(Fake::default()); |
| 2648 | let chat_engine = chat_engine(&chat_fake, small_pages()).await; |
| 2649 | chat_engine.send_typing(CHAT, None, true).await.unwrap(); |
| 2650 | chat_engine.send_typing(CHAT, None, false).await.unwrap(); |
| 2651 | assert!( |
| 2652 | chat_engine |
| 2653 | .send_typing("19:unknown@thread.v2", None, true) |
| 2654 | .await |
| 2655 | .is_err() |
| 2656 | ); |
| 2657 | assert_eq!( |
| 2658 | chat_fake.calls(), |
| 2659 | [ |
| 2660 | format!("typing {CHAT} true"), |
| 2661 | format!("typing {CHAT} false") |
| 2662 | ] |
| 2663 | ); |
| 2664 | |
| 2665 | let channel_fake = Arc::new(Fake::default()); |
| 2666 | let channel_engine = channel_engine(&channel_fake).await; |
| 2667 | channel_engine |
| 2668 | .send_typing(CHANNEL, None, true) |
| 2669 | .await |
| 2670 | .unwrap(); |
| 2671 | channel_engine |
| 2672 | .send_typing(CHANNEL, Some("m0042"), true) |
| 2673 | .await |
| 2674 | .unwrap(); |
| 2675 | assert_eq!( |
| 2676 | channel_fake.calls(), |
| 2677 | [ |
| 2678 | format!("typing {CHANNEL} true"), |
| 2679 | format!("typing {CHANNEL};messageid=m0042 true"), |
| 2680 | ] |
| 2681 | ); |
| 2682 | } |
| 2683 | |
| 2684 | #[tokio::test] |
| 2685 | async fn chat_actions_call_graph_with_the_right_ids() { |
| 2686 | let fake = Arc::new(Fake::default()); |
| 2687 | fake.set_chat_messages(numbered(3)); |
| 2688 | let engine = chat_engine(&fake, small_pages()).await; |
| 2689 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2690 | |
| 2691 | engine.mark_read(CHAT).await.unwrap(); |
| 2692 | engine.set_reaction(CHAT, "m0001", "like").await.unwrap(); |
| 2693 | engine.unset_reaction(CHAT, "m0001", "like").await.unwrap(); |
| 2694 | engine |
| 2695 | .edit_message(CHAT, "m0002", "new **text**") |
| 2696 | .await |
| 2697 | .unwrap(); |
| 2698 | engine.soft_delete_message(CHAT, "m0003").await.unwrap(); |
| 2699 | engine |
| 2700 | .undo_soft_delete_message(CHAT, "m0003") |
| 2701 | .await |
| 2702 | .unwrap(); |
| 2703 | let calls = fake.calls(); |
| 2704 | assert_eq!(calls[0], format!("mark_read {CHAT} {ME} tenant-1")); |
| 2705 | assert!(calls.contains(&"set_reaction m0001 like".to_owned())); |
| 2706 | assert!(calls.contains(&"unset_reaction m0001 like".to_owned())); |
| 2707 | assert!(calls.contains(&"edit m0002 new <b>text</b>".to_owned())); |
| 2708 | assert!(calls.contains(&format!("soft_delete {ME} m0003"))); |
| 2709 | assert!(calls.contains(&format!("undo_soft_delete {ME} m0003"))); |
| 2710 | assert!(!engine.sidebar().unwrap().chats[0].unread); |
| 2711 | } |
| 2712 | |
| 2713 | #[tokio::test] |
| 2714 | async fn new_chats_are_cached_and_people_are_searched() { |
| 2715 | let fake = Arc::new(Fake::default()); |
| 2716 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2717 | let one_on_one = engine.create_one_on_one("user-ada").await.unwrap(); |
| 2718 | let group = engine |
| 2719 | .create_group( |
| 2720 | &["user-ada".to_owned(), "user-bob".to_owned()], |
| 2721 | Some("Crew"), |
| 2722 | ) |
| 2723 | .await |
| 2724 | .unwrap(); |
| 2725 | assert_eq!( |
| 2726 | (one_on_one.as_str(), group.as_str()), |
| 2727 | ("19:new@thread.v2", "19:group@thread.v2") |
| 2728 | ); |
| 2729 | assert_eq!(engine.store().chat_count().unwrap(), 2); |
| 2730 | assert_eq!( |
| 2731 | fake.calls()[1], |
| 2732 | format!("group {ME} user-ada,user-bob Some(\"Crew\")") |
| 2733 | ); |
| 2734 | assert_eq!(engine.search_people("ada").await.unwrap().len(), 1); |
| 2735 | } |
| 2736 | |
| 2737 | fn chat_with_preview( |
| 2738 | id: &str, |
| 2739 | minute: i64, |
| 2740 | content_type: &str, |
| 2741 | content: &str, |
| 2742 | deleted: bool, |
| 2743 | ) -> Chat { |
| 2744 | let mut chat = chat(id, Some("Planning"), minute, 0, "user-ada", false); |
| 2745 | let preview = chat.last_message_preview.as_mut().unwrap(); |
| 2746 | preview.body = Some(graph::Body { |
| 2747 | content_type: content_type.to_owned(), |
| 2748 | content: Some(content.to_owned()), |
| 2749 | }); |
| 2750 | preview.from = |
| 2751 | serde_json::from_value(json!({"user": {"id": "user-ada", "displayName": "Ada Example"}})) |
| 2752 | .unwrap(); |
| 2753 | preview.message_type = Some("message".to_owned()); |
| 2754 | if deleted { |
| 2755 | preview.deleted_date_time = Some(base()); |
| 2756 | } |
| 2757 | chat |
| 2758 | } |
| 2759 | |
| 2760 | #[tokio::test] |
| 2761 | async fn sidebar_sync_fills_the_last_message_preview() { |
| 2762 | let fake = Arc::new(Fake::default()); |
| 2763 | *fake.chats.lock().unwrap() = vec![ |
| 2764 | chat_with_preview( |
| 2765 | "c-html", |
| 2766 | 5, |
| 2767 | "html", |
| 2768 | "<p>Hello <b>team</b></p><p>second</p>", |
| 2769 | false, |
| 2770 | ), |
| 2771 | chat_with_preview("c-gone", 4, "html", "<p>secret</p>", true), |
| 2772 | chat_with_preview("c-image", 3, "html", "<p><img src=\"x\"></p>", false), |
| 2773 | chat_with_preview("c-text", 2, "text", &"x".repeat(500), false), |
| 2774 | ]; |
| 2775 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2776 | engine.refresh_sidebar().await.unwrap(); |
| 2777 | let chats = engine.sidebar().unwrap().chats; |
| 2778 | let by_id = |id: &str| chats.iter().find(|chat| chat.id == id).unwrap().clone(); |
| 2779 | let html = by_id("c-html"); |
| 2780 | assert_eq!( |
| 2781 | html.last_message_preview.as_deref(), |
| 2782 | Some("Hello team second") |
| 2783 | ); |
| 2784 | assert_eq!( |
| 2785 | html.last_message_sender_name.as_deref(), |
| 2786 | Some("Ada Example") |
| 2787 | ); |
| 2788 | assert_eq!(html.last_message_sender_id.as_deref(), Some("user-ada")); |
| 2789 | assert!(!html.last_message_deleted); |
| 2790 | let gone = by_id("c-gone"); |
| 2791 | assert!(gone.last_message_deleted); |
| 2792 | assert_eq!(gone.last_message_preview, None); |
| 2793 | assert_eq!( |
| 2794 | by_id("c-image").last_message_preview.as_deref(), |
| 2795 | Some("Sent an image") |
| 2796 | ); |
| 2797 | assert_eq!( |
| 2798 | by_id("c-text") |
| 2799 | .last_message_preview |
| 2800 | .unwrap() |
| 2801 | .chars() |
| 2802 | .count(), |
| 2803 | 200 |
| 2804 | ); |
| 2805 | assert!( |
| 2806 | html.members |
| 2807 | .iter() |
| 2808 | .all(|member| member.user_id.is_some() && !member.display_name.is_empty()) |
| 2809 | ); |
| 2810 | } |
| 2811 | |
| 2812 | #[tokio::test] |
| 2813 | async fn a_newer_message_updates_the_preview_and_announces_the_sidebar() { |
| 2814 | let fake = Arc::new(Fake::default()); |
| 2815 | fake.set_chat_messages(numbered(3)); |
| 2816 | let engine = chat_engine(&fake, SyncConfig::default()).await; |
| 2817 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2818 | let mut events = engine.subscribe(); |
| 2819 | let mut all = numbered(3); |
| 2820 | all.push(message(4, 40, "<p>brand <i>new</i></p>")); |
| 2821 | fake.set_chat_messages(all); |
| 2822 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2823 | let record = engine.sidebar().unwrap().chats.remove(0); |
| 2824 | assert_eq!(record.last_message_preview.as_deref(), Some("brand new")); |
| 2825 | assert_eq!( |
| 2826 | record.last_message_sender_name.as_deref(), |
| 2827 | Some("Ada Example") |
| 2828 | ); |
| 2829 | assert_eq!(record.last_message_at, Some(base() + Duration::minutes(40))); |
| 2830 | let mut seen = Vec::new(); |
| 2831 | while let Ok(event) = events.try_recv() { |
| 2832 | seen.push(event); |
| 2833 | } |
| 2834 | assert!(seen.contains(&CoreEvent::SidebarChanged)); |
| 2835 | } |
| 2836 | |
| 2837 | #[tokio::test] |
| 2838 | async fn a_card_line_survives_the_graph_chat_refresh() { |
| 2839 | let fake = Arc::new(Fake::default()); |
| 2840 | let engine = chat_engine(&fake, SyncConfig::default()).await; |
| 2841 | let body = r#"<attachment id="a1"></attachment>"#; |
| 2842 | let card: Message = serde_json::from_value(json!({ |
| 2843 | "id": "card", "messageType": "message", |
| 2844 | "createdDateTime": (base() + Duration::minutes(5)).to_rfc3339(), |
| 2845 | "from": {"user": {"id": "user-ada", "displayName": "Ada Example"}}, |
| 2846 | "body": {"contentType": "html", "content": body}, |
| 2847 | "attachments": [{ |
| 2848 | "id": "a1", "contentType": "application/vnd.microsoft.card.adaptive", |
| 2849 | "content": json!({"type": "AdaptiveCard", "body": [ |
| 2850 | {"type": "TextBlock", "text": "Ada edited Engine Notes"}, |
| 2851 | ]}).to_string(), |
| 2852 | }], |
| 2853 | })) |
| 2854 | .unwrap(); |
| 2855 | fake.set_chat_messages(vec![card]); |
| 2856 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2857 | let line = |engine: &SyncEngine<Handle>| { |
| 2858 | engine.sidebar().unwrap().chats.remove(0).last_message_preview |
| 2859 | }; |
| 2860 | assert_eq!(line(&engine).as_deref(), Some("Ada edited Engine Notes")); |
| 2861 | *fake.chats.lock().unwrap() = vec![chat_with_preview(CHAT, 5, "html", body, false)]; |
| 2862 | engine.refresh_sidebar().await.unwrap(); |
| 2863 | assert_eq!(line(&engine).as_deref(), Some("Ada edited Engine Notes")); |
| 2864 | } |
| 2865 | |
| 2866 | #[tokio::test] |
| 2867 | async fn a_newer_call_event_keeps_the_line_and_moves_the_time() { |
| 2868 | let fake = Arc::new(Fake::default()); |
| 2869 | let mut before = numbered(3); |
| 2870 | before.push(message(4, 30, "<p>before the call</p>")); |
| 2871 | fake.set_chat_messages(before.clone()); |
| 2872 | let engine = chat_engine(&fake, SyncConfig::default()).await; |
| 2873 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2874 | let call: Message = serde_json::from_value(json!({ |
| 2875 | "id": "call", "messageType": "systemEventMessage", |
| 2876 | "createdDateTime": (base() + Duration::minutes(40)).to_rfc3339(), |
| 2877 | "body": {"contentType": "html", "content": "<systemEventMessage/>"}, |
| 2878 | "eventDetail": { |
| 2879 | "@odata.type": "#microsoft.graph.callEndedEventMessageDetail", |
| 2880 | "callId": "c1", "callDuration": "PT1M2S", "callEventType": "call", |
| 2881 | "callParticipants": [], |
| 2882 | }, |
| 2883 | })) |
| 2884 | .unwrap(); |
| 2885 | before.push(call); |
| 2886 | fake.set_chat_messages(before); |
| 2887 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2888 | let record = engine.sidebar().unwrap().chats.remove(0); |
| 2889 | assert_eq!( |
| 2890 | record.last_message_preview.as_deref(), |
| 2891 | Some("before the call") |
| 2892 | ); |
| 2893 | assert_eq!(record.last_message_at, Some(base() + Duration::minutes(40))); |
| 2894 | } |
| 2895 | |
| 2896 | #[tokio::test] |
| 2897 | async fn a_departed_partner_keeps_their_name_from_the_chat_history() { |
| 2898 | let fake = Arc::new(Fake::default()); |
| 2899 | let departed = "19:user-ada_user-me@unq.gbl.spaces"; |
| 2900 | let mut alone = chat(departed, None, 5, 5, ME, false); |
| 2901 | alone |
| 2902 | .members |
| 2903 | .retain(|member| member.user_id.as_deref() == Some(ME)); |
| 2904 | *fake.chats.lock().unwrap() = vec![alone]; |
| 2905 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2906 | engine.refresh_sidebar().await.unwrap(); |
| 2907 | assert_eq!(engine.sidebar().unwrap().chats[0].title, "Unknown User"); |
| 2908 | fake.set_chat_messages(numbered(1)); |
| 2909 | engine.fetch_newer(departed).await.unwrap(); |
| 2910 | engine.refresh_sidebar().await.unwrap(); |
| 2911 | assert_eq!(engine.sidebar().unwrap().chats[0].title, "Ada Example"); |
| 2912 | } |
| 2913 | |
| 2914 | #[tokio::test] |
| 2915 | async fn an_edited_old_message_leaves_the_preview_alone() { |
| 2916 | let fake = Arc::new(Fake::default()); |
| 2917 | fake.set_chat_messages(numbered(3)); |
| 2918 | let engine = chat_engine(&fake, SyncConfig::default()).await; |
| 2919 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2920 | let before = engine.sidebar().unwrap().chats.remove(0); |
| 2921 | let mut all = numbered(3); |
| 2922 | all[0] = message(1, 1, "<p>edited early</p>"); |
| 2923 | fake.set_chat_messages(all); |
| 2924 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2925 | assert_eq!(engine.sidebar().unwrap().chats.remove(0), before); |
| 2926 | } |
| 2927 | |
| 2928 | #[tokio::test] |
| 2929 | async fn me_is_known_after_the_first_sync() { |
| 2930 | let fake = Arc::new(Fake::default()); |
| 2931 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2932 | assert_eq!(engine.me(), None); |
| 2933 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 2934 | engine.refresh_sidebar().await.unwrap(); |
| 2935 | let me = engine.me().unwrap(); |
| 2936 | assert_eq!(me.user_id, ME); |
| 2937 | assert_eq!(me.display_name, "Me Myself"); |
| 2938 | } |
| 2939 | |
| 2940 | #[tokio::test] |
| 2941 | async fn unread_count_uses_cached_messages_after_the_read_time() { |
| 2942 | let fake = Arc::new(Fake::default()); |
| 2943 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 10, 2, "user-ada", false)]; |
| 2944 | fake.set_chat_messages(numbered(5)); |
| 2945 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2946 | engine.refresh_sidebar().await.unwrap(); |
| 2947 | assert_eq!(engine.unread_count(CHAT), 1); |
| 2948 | engine.fetch_newer(CHAT).await.unwrap(); |
| 2949 | assert_eq!(engine.unread_count(CHAT), 3); |
| 2950 | assert_eq!(engine.unread_count("unknown"), 0); |
| 2951 | engine.mark_read(CHAT).await.unwrap(); |
| 2952 | assert_eq!(engine.unread_count(CHAT), 0); |
| 2953 | } |
| 2954 | |
| 2955 | fn ids(values: &[&str]) -> Vec<String> { |
| 2956 | values.iter().map(|value| value.to_string()).collect() |
| 2957 | } |
| 2958 | |
| 2959 | #[tokio::test] |
| 2960 | async fn avatars_are_fetched_cached_and_not_refetched_inside_seven_days() { |
| 2961 | let fake = Arc::new(Fake::default()); |
| 2962 | fake.photos |
| 2963 | .lock() |
| 2964 | .unwrap() |
| 2965 | .insert("ada".into(), vec![1, 2, 3]); |
| 2966 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2967 | let mut events = engine.subscribe(); |
| 2968 | engine |
| 2969 | .fetch_avatars(&ids(&["ada", "nobody", "ada"])) |
| 2970 | .await |
| 2971 | .unwrap(); |
| 2972 | assert_eq!( |
| 2973 | *fake.photo_requests.lock().unwrap(), |
| 2974 | vec![ids(&["ada", "nobody"])] |
| 2975 | ); |
| 2976 | let avatar = engine.avatar("ada").unwrap(); |
| 2977 | assert_eq!(avatar.bytes, [1, 2, 3]); |
| 2978 | assert_eq!(avatar.content_type, "image/jpeg"); |
| 2979 | assert!(engine.avatar("nobody").is_none()); |
| 2980 | assert_eq!( |
| 2981 | events.try_recv().unwrap(), |
| 2982 | CoreEvent::AvatarsChanged { |
| 2983 | user_ids: ids(&["ada"]) |
| 2984 | } |
| 2985 | ); |
| 2986 | engine |
| 2987 | .fetch_avatars(&ids(&["ada", "nobody"])) |
| 2988 | .await |
| 2989 | .unwrap(); |
| 2990 | assert_eq!(fake.photo_requests.lock().unwrap().len(), 1); |
| 2991 | assert!(events.try_recv().is_err()); |
| 2992 | } |
| 2993 | |
| 2994 | #[tokio::test] |
| 2995 | async fn stale_avatars_are_fetched_again() { |
| 2996 | let fake = Arc::new(Fake::default()); |
| 2997 | fake.photos.lock().unwrap().insert("ada".into(), vec![9]); |
| 2998 | let engine = engine_with(&fake, SyncConfig::default()); |
| 2999 | engine |
| 3000 | .store() |
| 3001 | .upsert_avatar(&store::AvatarRecord { |
| 3002 | user_id: "ada".into(), |
| 3003 | bytes: None, |
| 3004 | content_type: String::new(), |
| 3005 | fetched_at: chrono::Utc::now() - Duration::days(8), |
| 3006 | }) |
| 3007 | .unwrap(); |
| 3008 | engine.fetch_avatars(&ids(&["ada"])).await.unwrap(); |
| 3009 | assert_eq!(engine.avatar("ada").unwrap().bytes, [9]); |
| 3010 | } |
| 3011 | |
| 3012 | #[tokio::test] |
| 3013 | async fn presence_maps_availability_and_announces_changes_once() { |
| 3014 | let fake = Arc::new(Fake::default()); |
| 3015 | let entry = |user_id: &str, availability: &str| Presence { |
| 3016 | user_id: user_id.to_owned(), |
| 3017 | availability: availability.to_owned(), |
| 3018 | activity: None, |
| 3019 | }; |
| 3020 | *fake.presence_answers.lock().unwrap() = vec![ |
| 3021 | entry("ada", "BusyIdle"), |
| 3022 | entry("bob", "BeRightBack"), |
| 3023 | entry("cy", "PresenceUnknown"), |
| 3024 | entry("di", "DoNotDisturb"), |
| 3025 | ]; |
| 3026 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3027 | let mut events = engine.subscribe(); |
| 3028 | assert!(engine.presence("ada").is_none()); |
| 3029 | let wanted = ids(&["ada", "bob", "cy", "di"]); |
| 3030 | engine.refresh_presence(&wanted).await.unwrap(); |
| 3031 | assert_eq!( |
| 3032 | engine.presence("ada").unwrap().availability, |
| 3033 | Availability::Busy |
| 3034 | ); |
| 3035 | assert_eq!( |
| 3036 | engine.presence("bob").unwrap().availability, |
| 3037 | Availability::Away |
| 3038 | ); |
| 3039 | assert_eq!( |
| 3040 | engine.presence("cy").unwrap().availability, |
| 3041 | Availability::Unknown |
| 3042 | ); |
| 3043 | assert_eq!( |
| 3044 | engine.presence("di").unwrap().availability, |
| 3045 | Availability::DoNotDisturb |
| 3046 | ); |
| 3047 | assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged); |
| 3048 | engine.refresh_presence(&wanted).await.unwrap(); |
| 3049 | assert!(events.try_recv().is_err()); |
| 3050 | } |
| 3051 | |
| 3052 | #[tokio::test] |
| 3053 | async fn setting_own_availability_writes_then_reads_back_and_announces() { |
| 3054 | let fake = Arc::new(Fake::default()); |
| 3055 | *fake.own_status_answer.lock().unwrap() = chatsvc::PresenceStatus { |
| 3056 | availability: "Busy".into(), |
| 3057 | ..chatsvc::PresenceStatus::default() |
| 3058 | }; |
| 3059 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3060 | let mut events = engine.subscribe(); |
| 3061 | let forced = chatsvc::ForcedAvailability { |
| 3062 | kind: chatsvc::ForcedKind::Busy, |
| 3063 | expires_at: None, |
| 3064 | }; |
| 3065 | engine.set_own_availability(Some(forced)).await.unwrap(); |
| 3066 | assert_eq!(*fake.availability_puts.lock().unwrap(), vec![Some(forced)]); |
| 3067 | assert_eq!( |
| 3068 | engine.presence(ME).unwrap().availability, |
| 3069 | Availability::Busy |
| 3070 | ); |
| 3071 | assert!(matches!( |
| 3072 | events.try_recv().unwrap(), |
| 3073 | CoreEvent::PresenceStatusChanged(status) if status.availability == "Busy" |
| 3074 | )); |
| 3075 | assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged); |
| 3076 | } |
| 3077 | |
| 3078 | #[tokio::test] |
| 3079 | async fn setting_the_own_note_forwards_the_note() { |
| 3080 | let fake = Arc::new(Fake::default()); |
| 3081 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3082 | engine.set_own_status_note(None).await.unwrap(); |
| 3083 | assert_eq!(*fake.note_puts.lock().unwrap(), vec![None]); |
| 3084 | } |
| 3085 | |
| 3086 | fn trouter_endpoint(endpoint_id: &str) -> chatsvc::TrouterEndpoint { |
| 3087 | chatsvc::TrouterEndpoint { |
| 3088 | endpoint_id: endpoint_id.to_owned(), |
| 3089 | trouter_uri: "https://go-eu.trouter.teams.microsoft.com/v4/f/x/unifiedPresenceService" |
| 3090 | .to_owned(), |
| 3091 | } |
| 3092 | } |
| 3093 | |
| 3094 | #[tokio::test] |
| 3095 | async fn presence_subscribes_watched_users_once_the_endpoint_is_known() { |
| 3096 | let fake = Arc::new(Fake::default()); |
| 3097 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3098 | engine.watch_presence(&ids(&["ada", "bob"])).await.unwrap(); |
| 3099 | assert!(fake.presence_subscriptions.lock().unwrap().is_empty()); |
| 3100 | engine |
| 3101 | .presence_endpoint(trouter_endpoint("e1")) |
| 3102 | .await |
| 3103 | .unwrap(); |
| 3104 | engine.watch_presence(&ids(&["bob", "cy"])).await.unwrap(); |
| 3105 | engine.watch_presence(&ids(&["cy"])).await.unwrap(); |
| 3106 | assert_eq!( |
| 3107 | *fake.presence_subscriptions.lock().unwrap(), |
| 3108 | vec![ |
| 3109 | ("e1".to_owned(), ids(&["ada", "bob"]), true), |
| 3110 | ("e1".to_owned(), ids(&["cy"]), false), |
| 3111 | ] |
| 3112 | ); |
| 3113 | engine |
| 3114 | .presence_endpoint(trouter_endpoint("e1")) |
| 3115 | .await |
| 3116 | .unwrap(); |
| 3117 | assert_eq!(fake.presence_subscriptions.lock().unwrap().len(), 2); |
| 3118 | engine.resubscribe_presence().await.unwrap(); |
| 3119 | engine |
| 3120 | .presence_endpoint(trouter_endpoint("e2")) |
| 3121 | .await |
| 3122 | .unwrap(); |
| 3123 | assert_eq!( |
| 3124 | fake.presence_subscriptions.lock().unwrap()[2..], |
| 3125 | [ |
| 3126 | ("e1".to_owned(), ids(&["ada", "bob", "cy"]), true), |
| 3127 | ("e2".to_owned(), ids(&["ada", "bob", "cy"]), true), |
| 3128 | ] |
| 3129 | ); |
| 3130 | } |
| 3131 | |
| 3132 | #[tokio::test] |
| 3133 | async fn pushed_presence_announces_changes_once() { |
| 3134 | let fake = Arc::new(Fake::default()); |
| 3135 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3136 | let mut events = engine.subscribe(); |
| 3137 | let update = |user_id: &str, availability: &str| chatsvc::PresenceUpdate { |
| 3138 | user_id: user_id.to_owned(), |
| 3139 | availability: availability.to_owned(), |
| 3140 | activity: None, |
| 3141 | }; |
| 3142 | let updates = vec![update("ada", "Busy"), update("bob", "Away")]; |
| 3143 | engine.apply_presence(&updates); |
| 3144 | assert_eq!( |
| 3145 | engine.presence("ada").unwrap().availability, |
| 3146 | Availability::Busy |
| 3147 | ); |
| 3148 | assert_eq!(events.try_recv().unwrap(), CoreEvent::PresenceChanged); |
| 3149 | assert!(events.try_recv().is_err()); |
| 3150 | engine.apply_presence(&updates); |
| 3151 | assert!(events.try_recv().is_err()); |
| 3152 | } |
| 3153 | |
| 3154 | struct FakeFolders { |
| 3155 | state: Mutex<Vec<ChatFolder>>, |
| 3156 | channels: Vec<String>, |
| 3157 | layout: Vec<TeamLayoutRecord>, |
| 3158 | settings: ChatSectionSettings, |
| 3159 | folders_fail: bool, |
| 3160 | layout_fail: bool, |
| 3161 | team_order: Mutex<Option<Vec<(String, i64)>>>, |
| 3162 | calls: Mutex<Vec<String>>, |
| 3163 | } |
| 3164 | |
| 3165 | impl FakeFolders { |
| 3166 | fn new() -> Arc<Self> { |
| 3167 | let folder = |id: &str, kind, items: &[&str]| ChatFolder { |
| 3168 | id: id.to_owned(), |
| 3169 | name: id.to_owned(), |
| 3170 | kind, |
| 3171 | expanded: true, |
| 3172 | conversation_ids: ids(items), |
| 3173 | }; |
| 3174 | Arc::new(FakeFolders { |
| 3175 | state: Mutex::new(vec![ |
| 3176 | folder("fav", FolderKind::Favorites, &["a", "b"]), |
| 3177 | folder("work", FolderKind::UserCreated, &["c"]), |
| 3178 | ]), |
| 3179 | channels: ids(&["ch1", "ch2"]), |
| 3180 | layout: Vec::new(), |
| 3181 | settings: ChatSectionSettings::default(), |
| 3182 | folders_fail: false, |
| 3183 | layout_fail: false, |
| 3184 | team_order: Mutex::new(Some(Vec::new())), |
| 3185 | calls: Mutex::new(Vec::new()), |
| 3186 | }) |
| 3187 | } |
| 3188 | } |
| 3189 | |
| 3190 | impl FolderSource for FakeFolders { |
| 3191 | fn folders(&self) -> BoxFuture<'_, Result<Vec<ChatFolder>>> { |
| 3192 | Box::pin(async { |
| 3193 | if self.folders_fail { |
| 3194 | return Err(Error::Folders("folders down".to_owned())); |
| 3195 | } |
| 3196 | Ok(self.state.lock().unwrap().clone()) |
| 3197 | }) |
| 3198 | } |
| 3199 | |
| 3200 | fn pinned_channels(&self) -> BoxFuture<'_, Result<Vec<String>>> { |
| 3201 | Box::pin(async { Ok(self.channels.clone()) }) |
| 3202 | } |
| 3203 | |
| 3204 | fn team_layout(&self) -> BoxFuture<'_, Result<Vec<TeamLayoutRecord>>> { |
| 3205 | Box::pin(async { |
| 3206 | if self.layout_fail { |
| 3207 | return Err(Error::Folders("layout down".to_owned())); |
| 3208 | } |
| 3209 | Ok(self.layout.clone()) |
| 3210 | }) |
| 3211 | } |
| 3212 | |
| 3213 | fn section_settings(&self) -> BoxFuture<'_, Result<ChatSectionSettings>> { |
| 3214 | Box::pin(async { Ok(self.settings) }) |
| 3215 | } |
| 3216 | |
| 3217 | fn teams_order(&self) -> BoxFuture<'_, Result<Vec<(String, i64)>>> { |
| 3218 | Box::pin(async { |
| 3219 | self.team_order |
| 3220 | .lock() |
| 3221 | .unwrap() |
| 3222 | .clone() |
| 3223 | .ok_or_else(|| Error::Folders("order down".to_owned())) |
| 3224 | }) |
| 3225 | } |
| 3226 | |
| 3227 | fn set_section_enabled( |
| 3228 | &self, |
| 3229 | section: ChatSection, |
| 3230 | enabled: bool, |
| 3231 | ) -> BoxFuture<'_, Result<()>> { |
| 3232 | Box::pin(async move { |
| 3233 | self.calls |
| 3234 | .lock() |
| 3235 | .unwrap() |
| 3236 | .push(format!("section {section:?} {enabled}")); |
| 3237 | Ok(()) |
| 3238 | }) |
| 3239 | } |
| 3240 | |
| 3241 | fn set_folder_expanded<'a>( |
| 3242 | &'a self, |
| 3243 | folder_id: &'a str, |
| 3244 | expanded: bool, |
| 3245 | ) -> BoxFuture<'a, Result<()>> { |
| 3246 | Box::pin(async move { |
| 3247 | self.calls |
| 3248 | .lock() |
| 3249 | .unwrap() |
| 3250 | .push(format!("expanded {folder_id} {expanded}")); |
| 3251 | Ok(()) |
| 3252 | }) |
| 3253 | } |
| 3254 | |
| 3255 | fn move_to_folder<'a>( |
| 3256 | &'a self, |
| 3257 | conversation_id: &'a str, |
| 3258 | target_folder_id: &'a str, |
| 3259 | _index: Option<usize>, |
| 3260 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> { |
| 3261 | Box::pin(async move { |
| 3262 | self.calls |
| 3263 | .lock() |
| 3264 | .unwrap() |
| 3265 | .push(format!("move {conversation_id} {target_folder_id}")); |
| 3266 | let mut state = self.state.lock().unwrap(); |
| 3267 | for folder in state |
| 3268 | .iter_mut() |
| 3269 | .filter(|folder| folder.kind == FolderKind::UserCreated) |
| 3270 | { |
| 3271 | folder.conversation_ids.retain(|id| id != conversation_id); |
| 3272 | } |
| 3273 | state |
| 3274 | .iter_mut() |
| 3275 | .find(|folder| folder.id == target_folder_id) |
| 3276 | .unwrap() |
| 3277 | .conversation_ids |
| 3278 | .push(conversation_id.to_owned()); |
| 3279 | Ok(state.clone()) |
| 3280 | }) |
| 3281 | } |
| 3282 | |
| 3283 | fn remove_from_folder<'a>( |
| 3284 | &'a self, |
| 3285 | conversation_id: &'a str, |
| 3286 | folder_id: &'a str, |
| 3287 | ) -> BoxFuture<'a, Result<Vec<ChatFolder>>> { |
| 3288 | Box::pin(async move { |
| 3289 | self.calls |
| 3290 | .lock() |
| 3291 | .unwrap() |
| 3292 | .push(format!("remove {conversation_id} {folder_id}")); |
| 3293 | let mut state = self.state.lock().unwrap(); |
| 3294 | state |
| 3295 | .iter_mut() |
| 3296 | .find(|folder| folder.id == folder_id) |
| 3297 | .unwrap() |
| 3298 | .conversation_ids |
| 3299 | .retain(|id| id != conversation_id); |
| 3300 | Ok(state.clone()) |
| 3301 | }) |
| 3302 | } |
| 3303 | |
| 3304 | fn change_folders(&self, change: FolderChange) -> BoxFuture<'_, Result<Vec<ChatFolder>>> { |
| 3305 | Box::pin(async move { |
| 3306 | self.calls.lock().unwrap().push(format!("{change:?}")); |
| 3307 | let mut state = self.state.lock().unwrap(); |
| 3308 | match change { |
| 3309 | FolderChange::Create { name } => state.push(ChatFolder { |
| 3310 | id: name.clone(), |
| 3311 | name, |
| 3312 | kind: FolderKind::UserCreated, |
| 3313 | expanded: true, |
| 3314 | conversation_ids: Vec::new(), |
| 3315 | }), |
| 3316 | FolderChange::Rename { folder_id, name } => { |
| 3317 | state |
| 3318 | .iter_mut() |
| 3319 | .find(|folder| folder.id == folder_id) |
| 3320 | .unwrap() |
| 3321 | .name = name; |
| 3322 | } |
| 3323 | FolderChange::Delete { folder_id } => state.retain(|folder| folder.id != folder_id), |
| 3324 | FolderChange::Move { |
| 3325 | folder_id, |
| 3326 | target_folder_id, |
| 3327 | } => { |
| 3328 | let source = state |
| 3329 | .iter() |
| 3330 | .position(|folder| folder.id == folder_id) |
| 3331 | .unwrap(); |
| 3332 | let target = state |
| 3333 | .iter() |
| 3334 | .position(|folder| folder.id == target_folder_id) |
| 3335 | .unwrap(); |
| 3336 | state.swap(source, target); |
| 3337 | } |
| 3338 | } |
| 3339 | Ok(state.clone()) |
| 3340 | }) |
| 3341 | } |
| 3342 | |
| 3343 | fn set_channel_pinned<'a>( |
| 3344 | &'a self, |
| 3345 | channel_id: &'a str, |
| 3346 | pinned: bool, |
| 3347 | ) -> BoxFuture<'a, Result<Vec<String>>> { |
| 3348 | Box::pin(async move { |
| 3349 | self.calls |
| 3350 | .lock() |
| 3351 | .unwrap() |
| 3352 | .push(format!("pin channel {channel_id} {pinned}")); |
| 3353 | let mut channel_ids = self.channels.clone(); |
| 3354 | channel_ids.retain(|id| id != channel_id); |
| 3355 | if pinned { |
| 3356 | channel_ids.push(channel_id.to_owned()); |
| 3357 | } |
| 3358 | Ok(channel_ids) |
| 3359 | }) |
| 3360 | } |
| 3361 | |
| 3362 | fn set_channel_shown<'a>( |
| 3363 | &'a self, |
| 3364 | target: chatsvc::ChannelTarget<'a>, |
| 3365 | own_user_id: &'a str, |
| 3366 | shown: bool, |
| 3367 | _now_ms: i64, |
| 3368 | ) -> BoxFuture<'a, Result<()>> { |
| 3369 | Box::pin(async move { |
| 3370 | self.calls.lock().unwrap().push(format!( |
| 3371 | "show channel {} general={} {:?} {own_user_id} {shown}", |
| 3372 | target.channel_id, target.general, target.kind |
| 3373 | )); |
| 3374 | Ok(()) |
| 3375 | }) |
| 3376 | } |
| 3377 | |
| 3378 | fn set_team_shown<'a>( |
| 3379 | &'a self, |
| 3380 | team_thread_id: &'a str, |
| 3381 | shown: bool, |
| 3382 | ) -> BoxFuture<'a, Result<()>> { |
| 3383 | Box::pin(async move { |
| 3384 | self.calls |
| 3385 | .lock() |
| 3386 | .unwrap() |
| 3387 | .push(format!("show team {team_thread_id} {shown}")); |
| 3388 | Ok(()) |
| 3389 | }) |
| 3390 | } |
| 3391 | } |
| 3392 | |
| 3393 | fn store_alpha_team(engine: &SyncEngine<Handle>) { |
| 3394 | engine |
| 3395 | .store() |
| 3396 | .upsert_teams(&[TeamRecord { |
| 3397 | id: "alpha".into(), |
| 3398 | name: "Alpha".into(), |
| 3399 | }]) |
| 3400 | .unwrap(); |
| 3401 | let channel = |id: &str, name: &str, membership_type: Option<&str>| ChannelRecord { |
| 3402 | id: id.into(), |
| 3403 | team_id: "alpha".into(), |
| 3404 | name: name.into(), |
| 3405 | membership_type: membership_type.map(str::to_owned), |
| 3406 | last_message_at: None, |
| 3407 | unread: false, |
| 3408 | }; |
| 3409 | engine |
| 3410 | .store() |
| 3411 | .upsert_channels(&[ |
| 3412 | channel("19:general@thread.tacv2", "General", Some("standard")), |
| 3413 | channel("19:secret@thread.tacv2", "Secret", Some("private")), |
| 3414 | ]) |
| 3415 | .unwrap(); |
| 3416 | } |
| 3417 | |
| 3418 | #[tokio::test] |
| 3419 | async fn channel_pin_and_show_hide_go_through_the_source_and_cache() { |
| 3420 | let fake = Arc::new(Fake::default()); |
| 3421 | let source = FakeFolders::new(); |
| 3422 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 3423 | store_alpha_team(&engine); |
| 3424 | let mut events = engine.subscribe(); |
| 3425 | |
| 3426 | engine.set_channel_pinned("ch3", true).await.unwrap(); |
| 3427 | assert_eq!( |
| 3428 | engine.pinned_channels().unwrap(), |
| 3429 | ids(&["ch1", "ch2", "ch3"]) |
| 3430 | ); |
| 3431 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 3432 | engine.set_channel_pinned("ch1", false).await.unwrap(); |
| 3433 | assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch2"])); |
| 3434 | |
| 3435 | engine |
| 3436 | .set_channel_shown("19:secret@thread.tacv2", false) |
| 3437 | .await |
| 3438 | .unwrap(); |
| 3439 | engine |
| 3440 | .set_channel_shown("19:general@thread.tacv2", false) |
| 3441 | .await |
| 3442 | .unwrap(); |
| 3443 | engine.set_team_shown("alpha", false).await.unwrap(); |
| 3444 | let team = engine.store().sidebar().unwrap().teams.remove(0); |
| 3445 | assert!(team.hidden); |
| 3446 | assert_eq!(team.hidden_channel_ids.len(), 2); |
| 3447 | let calls = source.calls.lock().unwrap().clone(); |
| 3448 | assert_eq!( |
| 3449 | calls[2..], |
| 3450 | [ |
| 3451 | format!("show channel 19:secret@thread.tacv2 general=false Private {ME} false"), |
| 3452 | format!("show channel 19:general@thread.tacv2 general=true Standard {ME} false"), |
| 3453 | "show team 19:general@thread.tacv2 false".to_owned(), |
| 3454 | ] |
| 3455 | ); |
| 3456 | } |
| 3457 | |
| 3458 | #[tokio::test] |
| 3459 | async fn channel_and_team_links_use_the_cached_tenant() { |
| 3460 | let fake = Arc::new(Fake::default()); |
| 3461 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3462 | store_alpha_team(&engine); |
| 3463 | engine.store().set_meta("me_tenant_id", "tenant-1").unwrap(); |
| 3464 | |
| 3465 | assert_eq!( |
| 3466 | engine.channel_link("19:secret@thread.tacv2").await.unwrap(), |
| 3467 | "https://teams.cloud.microsoft/l/channel/19%3Asecret%40thread.tacv2/Secret?groupId=alpha&tenantId=tenant-1&ngc=true" |
| 3468 | ); |
| 3469 | assert_eq!( |
| 3470 | engine.team_link("alpha").await.unwrap(), |
| 3471 | "https://teams.cloud.microsoft/l/team/19%3Ageneral%40thread.tacv2/conversations?groupId=alpha&tenantId=tenant-1" |
| 3472 | ); |
| 3473 | } |
| 3474 | |
| 3475 | #[tokio::test] |
| 3476 | async fn folder_create_rename_move_and_delete_update_the_cache() { |
| 3477 | let fake = Arc::new(Fake::default()); |
| 3478 | let source = FakeFolders::new(); |
| 3479 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 3480 | engine.refresh_folders().await.unwrap(); |
| 3481 | let mut events = engine.subscribe(); |
| 3482 | let names = |engine: &SyncEngine<_>| -> Vec<String> { |
| 3483 | engine |
| 3484 | .chat_folders() |
| 3485 | .unwrap() |
| 3486 | .into_iter() |
| 3487 | .map(|folder| folder.name) |
| 3488 | .collect() |
| 3489 | }; |
| 3490 | |
| 3491 | engine |
| 3492 | .change_folders(FolderChange::Create { |
| 3493 | name: "todo".into(), |
| 3494 | }) |
| 3495 | .await |
| 3496 | .unwrap(); |
| 3497 | assert_eq!(names(&engine), ["fav", "work", "todo"]); |
| 3498 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 3499 | |
| 3500 | engine |
| 3501 | .change_folders(FolderChange::Rename { |
| 3502 | folder_id: "todo".into(), |
| 3503 | name: "later".into(), |
| 3504 | }) |
| 3505 | .await |
| 3506 | .unwrap(); |
| 3507 | engine |
| 3508 | .change_folders(FolderChange::Move { |
| 3509 | folder_id: "todo".into(), |
| 3510 | target_folder_id: "work".into(), |
| 3511 | }) |
| 3512 | .await |
| 3513 | .unwrap(); |
| 3514 | assert_eq!(names(&engine), ["fav", "later", "work"]); |
| 3515 | |
| 3516 | engine |
| 3517 | .change_folders(FolderChange::Delete { |
| 3518 | folder_id: "work".into(), |
| 3519 | }) |
| 3520 | .await |
| 3521 | .unwrap(); |
| 3522 | assert_eq!(names(&engine), ["fav", "later"]); |
| 3523 | assert_eq!(source.calls.lock().unwrap().len(), 4); |
| 3524 | } |
| 3525 | |
| 3526 | #[tokio::test] |
| 3527 | async fn folders_refresh_move_and_remove_go_through_the_source_and_cache() { |
| 3528 | let fake = Arc::new(Fake::default()); |
| 3529 | let source = FakeFolders::new(); |
| 3530 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 3531 | assert!(engine.chat_folders().unwrap().is_empty()); |
| 3532 | let mut events = engine.subscribe(); |
| 3533 | |
| 3534 | engine.refresh_folders().await.unwrap(); |
| 3535 | let folders = engine.chat_folders().unwrap(); |
| 3536 | assert_eq!(folders.len(), 2); |
| 3537 | assert_eq!(folders[0].kind, FolderKind::Favorites); |
| 3538 | assert_eq!(folders[0].conversation_ids, ids(&["a", "b"])); |
| 3539 | assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch1", "ch2"])); |
| 3540 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 3541 | |
| 3542 | engine.refresh_folders().await.unwrap(); |
| 3543 | assert!(events.try_recv().is_err()); |
| 3544 | |
| 3545 | engine.move_to_folder("a", "work", None).await.unwrap(); |
| 3546 | assert_eq!( |
| 3547 | engine.chat_folders().unwrap()[1].conversation_ids, |
| 3548 | ids(&["c", "a"]) |
| 3549 | ); |
| 3550 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 3551 | assert_eq!(engine.pinned_channels().unwrap(), ids(&["ch1", "ch2"])); |
| 3552 | |
| 3553 | engine.remove_from_folder("a", "work").await.unwrap(); |
| 3554 | assert_eq!( |
| 3555 | engine.chat_folders().unwrap()[1].conversation_ids, |
| 3556 | ids(&["c"]) |
| 3557 | ); |
| 3558 | assert_eq!( |
| 3559 | *source.calls.lock().unwrap(), |
| 3560 | ["move a work", "remove a work"] |
| 3561 | ); |
| 3562 | } |
| 3563 | |
| 3564 | #[tokio::test] |
| 3565 | async fn collapse_and_section_settings_go_through_the_source() { |
| 3566 | let fake = Arc::new(Fake::default()); |
| 3567 | let mut source = FakeFolders::new(); |
| 3568 | Arc::get_mut(&mut source).unwrap().settings = ChatSectionSettings { |
| 3569 | muted: Some(false), |
| 3570 | meeting: Some(true), |
| 3571 | adaptive_rail: Some(true), |
| 3572 | }; |
| 3573 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 3574 | let mut events = engine.subscribe(); |
| 3575 | engine.refresh_folders().await.unwrap(); |
| 3576 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 3577 | assert_eq!(events.try_recv().unwrap(), CoreEvent::FoldersChanged); |
| 3578 | assert_eq!( |
| 3579 | teams_core::stored_section_settings(engine.store()), |
| 3580 | ChatSectionSettings { |
| 3581 | muted: Some(false), |
| 3582 | meeting: Some(true), |
| 3583 | adaptive_rail: Some(true), |
| 3584 | } |
| 3585 | ); |
| 3586 | |
| 3587 | engine.set_folder_expanded("work", false).await.unwrap(); |
| 3588 | engine |
| 3589 | .set_section_enabled(ChatSection::Meeting, false) |
| 3590 | .await |
| 3591 | .unwrap(); |
| 3592 | assert_eq!( |
| 3593 | *source.calls.lock().unwrap(), |
| 3594 | ["expanded work false", "section Meeting false"] |
| 3595 | ); |
| 3596 | } |
| 3597 | |
| 3598 | #[tokio::test] |
| 3599 | async fn a_failing_folder_list_still_stores_the_team_layout_and_tabs() { |
| 3600 | let fake = Arc::new(Fake::default()); |
| 3601 | let mut source = FakeFolders::new(); |
| 3602 | let source_mut = Arc::get_mut(&mut source).unwrap(); |
| 3603 | source_mut.folders_fail = true; |
| 3604 | source_mut.layout = vec![TeamLayoutRecord { |
| 3605 | team_id: "alpha".into(), |
| 3606 | hidden: false, |
| 3607 | channels: vec![ChannelLayoutRecord { |
| 3608 | channel_id: "alpha-general".into(), |
| 3609 | general: true, |
| 3610 | hidden: false, |
| 3611 | tabs: vec![ChannelTabRecord { |
| 3612 | tab_id: "tab-1".into(), |
| 3613 | name: "Wiki".into(), |
| 3614 | definition_id: "com.microsoft.teamspace.tab.wiki".into(), |
| 3615 | open_url: None, |
| 3616 | }], |
| 3617 | notifications: Default::default(), |
| 3618 | }], |
| 3619 | }]; |
| 3620 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 3621 | |
| 3622 | let error = engine.refresh_folders().await.unwrap_err(); |
| 3623 | |
| 3624 | assert!(error.to_string().contains("folders down")); |
| 3625 | assert_eq!( |
| 3626 | engine.store().channel_tabs("alpha-general").unwrap().len(), |
| 3627 | 1 |
| 3628 | ); |
| 3629 | assert!( |
| 3630 | engine |
| 3631 | .store() |
| 3632 | .meta_time("team_layout_refreshed_at") |
| 3633 | .unwrap() |
| 3634 | .is_some() |
| 3635 | ); |
| 3636 | } |
| 3637 | |
| 3638 | #[tokio::test] |
| 3639 | async fn both_refresh_errors_are_reported_together() { |
| 3640 | let fake = Arc::new(Fake::default()); |
| 3641 | let mut source = FakeFolders::new(); |
| 3642 | let source_mut = Arc::get_mut(&mut source).unwrap(); |
| 3643 | source_mut.folders_fail = true; |
| 3644 | source_mut.layout_fail = true; |
| 3645 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 3646 | |
| 3647 | let message = engine.refresh_folders().await.unwrap_err().to_string(); |
| 3648 | |
| 3649 | assert!(message.contains("folders down") && message.contains("layout down")); |
| 3650 | } |
| 3651 | |
| 3652 | #[tokio::test] |
| 3653 | async fn team_order_follows_teams_order_and_survives_a_failing_order_lookup() { |
| 3654 | let fake = Arc::new(Fake::default()); |
| 3655 | let mut source = FakeFolders::new(); |
| 3656 | let team = |id: &str| TeamLayoutRecord { |
| 3657 | team_id: id.into(), |
| 3658 | hidden: false, |
| 3659 | channels: Vec::new(), |
| 3660 | }; |
| 3661 | Arc::get_mut(&mut source).unwrap().layout = vec![team("a"), team("b"), team("c")]; |
| 3662 | *source.team_order.lock().unwrap() = Some(vec![("c".to_owned(), 0), ("b".to_owned(), 1)]); |
| 3663 | let engine = engine_with( |
| 3664 | &fake, |
| 3665 | SyncConfig { |
| 3666 | team_layout_refresh_interval: Duration::zero(), |
| 3667 | ..SyncConfig::default() |
| 3668 | }, |
| 3669 | ) |
| 3670 | .with_folder_source(source.clone()); |
| 3671 | let record = |id: &str| TeamRecord { |
| 3672 | id: id.into(), |
| 3673 | name: id.into(), |
| 3674 | }; |
| 3675 | engine |
| 3676 | .store() |
| 3677 | .upsert_teams(&[record("a"), record("b"), record("c")]) |
| 3678 | .unwrap(); |
| 3679 | let order = |engine: &SyncEngine<Handle>| -> Vec<String> { |
| 3680 | let teams = engine.store().sidebar().unwrap().teams; |
| 3681 | teams.into_iter().map(|entry| entry.team.id).collect() |
| 3682 | }; |
| 3683 | |
| 3684 | engine.refresh_folders().await.unwrap(); |
| 3685 | assert_eq!(order(&engine), ["c", "b", "a"]); |
| 3686 | |
| 3687 | *source.team_order.lock().unwrap() = None; |
| 3688 | let mut events = engine.subscribe(); |
| 3689 | engine.refresh_folders().await.unwrap(); |
| 3690 | assert_eq!(order(&engine), ["c", "b", "a"]); |
| 3691 | let mut reported = false; |
| 3692 | while let Ok(event) = events.try_recv() { |
| 3693 | reported |= matches!(event, CoreEvent::Error { .. }); |
| 3694 | } |
| 3695 | assert!(reported); |
| 3696 | } |
| 3697 | |
| 3698 | #[tokio::test] |
| 3699 | async fn team_layout_from_teams_orders_and_hides_the_sidebar() { |
| 3700 | let fake = Arc::new(Fake::default()); |
| 3701 | let mut source = FakeFolders::new(); |
| 3702 | Arc::get_mut(&mut source).unwrap().layout = vec![ |
| 3703 | TeamLayoutRecord { |
| 3704 | team_id: "zeta".into(), |
| 3705 | hidden: false, |
| 3706 | channels: vec![ChannelLayoutRecord { |
| 3707 | channel_id: "zeta-old".into(), |
| 3708 | general: false, |
| 3709 | hidden: true, |
| 3710 | tabs: Vec::new(), |
| 3711 | notifications: Default::default(), |
| 3712 | }], |
| 3713 | }, |
| 3714 | TeamLayoutRecord { |
| 3715 | team_id: "alpha".into(), |
| 3716 | hidden: true, |
| 3717 | channels: Vec::new(), |
| 3718 | }, |
| 3719 | ]; |
| 3720 | let engine = engine_with(&fake, SyncConfig::default()).with_folder_source(source.clone()); |
| 3721 | let team = |id: &str| TeamRecord { |
| 3722 | id: id.into(), |
| 3723 | name: id.into(), |
| 3724 | }; |
| 3725 | engine |
| 3726 | .store() |
| 3727 | .upsert_teams(&[team("alpha"), team("zeta")]) |
| 3728 | .unwrap(); |
| 3729 | let channel = |id: &str, name: &str| ChannelRecord { |
| 3730 | id: id.into(), |
| 3731 | team_id: "zeta".into(), |
| 3732 | name: name.into(), |
| 3733 | membership_type: None, |
| 3734 | last_message_at: None, |
| 3735 | unread: false, |
| 3736 | }; |
| 3737 | engine |
| 3738 | .store() |
| 3739 | .upsert_channels(&[ |
| 3740 | channel("zeta-old", "Archiv"), |
| 3741 | channel("zeta-general", "General"), |
| 3742 | ]) |
| 3743 | .unwrap(); |
| 3744 | let mut events = engine.subscribe(); |
| 3745 | |
| 3746 | engine.refresh_folders().await.unwrap(); |
| 3747 | |
| 3748 | let teams = engine.store().sidebar().unwrap().teams; |
| 3749 | let order: Vec<&str> = teams.iter().map(|entry| entry.team.id.as_str()).collect(); |
| 3750 | assert_eq!(order, ["zeta", "alpha"]); |
| 3751 | assert!(teams[1].hidden); |
| 3752 | assert_eq!(teams[0].channels[0].id, "zeta-general"); |
| 3753 | assert_eq!(teams[0].hidden_channel_ids, ids(&["zeta-old"])); |
| 3754 | let received: Vec<CoreEvent> = std::iter::from_fn(|| events.try_recv().ok()).collect(); |
| 3755 | assert!(received.contains(&CoreEvent::SidebarChanged)); |
| 3756 | } |
| 3757 | |
| 3758 | #[tokio::test] |
| 3759 | async fn channel_notifications_go_to_the_service_then_the_store() { |
| 3760 | let fake = Arc::new(Fake::default()); |
| 3761 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3762 | engine |
| 3763 | .store() |
| 3764 | .upsert_teams(&[TeamRecord { |
| 3765 | id: "alpha".into(), |
| 3766 | name: "alpha".into(), |
| 3767 | }]) |
| 3768 | .unwrap(); |
| 3769 | engine |
| 3770 | .store() |
| 3771 | .upsert_channels(&[ChannelRecord { |
| 3772 | id: "alpha-news".into(), |
| 3773 | team_id: "alpha".into(), |
| 3774 | name: "News".into(), |
| 3775 | membership_type: None, |
| 3776 | last_message_at: None, |
| 3777 | unread: false, |
| 3778 | }]) |
| 3779 | .unwrap(); |
| 3780 | let mut events = engine.subscribe(); |
| 3781 | let banner = store::ChannelNotifications { |
| 3782 | level: store::ChannelNotificationLevel::BannerAndFeed, |
| 3783 | include_replies: true, |
| 3784 | }; |
| 3785 | |
| 3786 | engine |
| 3787 | .set_channel_notifications("alpha-news", banner) |
| 3788 | .await |
| 3789 | .unwrap(); |
| 3790 | |
| 3791 | assert_eq!( |
| 3792 | fake.calls().last().unwrap(), |
| 3793 | "channel notifications alpha-news banner true" |
| 3794 | ); |
| 3795 | let teams = engine.store().sidebar().unwrap().teams; |
| 3796 | assert_eq!(teams[0].channel_notifications("alpha-news"), banner); |
| 3797 | assert_eq!(events.try_recv().unwrap(), CoreEvent::SidebarChanged); |
| 3798 | } |
| 3799 | |
| 3800 | #[tokio::test] |
| 3801 | async fn folders_without_a_source_are_unsupported() { |
| 3802 | let fake = Arc::new(Fake::default()); |
| 3803 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3804 | assert!(matches!( |
| 3805 | engine.refresh_folders().await, |
| 3806 | Err(Error::Unsupported(_)) |
| 3807 | )); |
| 3808 | assert!(matches!( |
| 3809 | engine.move_to_folder("a", "b", None).await, |
| 3810 | Err(Error::Unsupported(_)) |
| 3811 | )); |
| 3812 | } |
| 3813 | |
| 3814 | const HOSTED: &str = |
| 3815 | "https://graph.microsoft.com/v1.0/chats/c/messages/m0001/hostedContents/h1/$value"; |
| 3816 | |
| 3817 | fn message_with_image(id: u32, minute: i64, url: &str) -> Message { |
| 3818 | message( |
| 3819 | id, |
| 3820 | minute, |
| 3821 | &format!("<p>look</p><img src=\"{url}\" width=\"300\" height=\"150\">"), |
| 3822 | ) |
| 3823 | } |
| 3824 | |
| 3825 | #[tokio::test] |
| 3826 | async fn images_are_fetched_once_cached_and_announced() { |
| 3827 | let fake = Arc::new(Fake::default()); |
| 3828 | fake.set_chat_messages(vec![message_with_image(1, 1, HOSTED)]); |
| 3829 | let engine = chat_engine(&fake, small_pages()).await; |
| 3830 | engine.fetch_newer(CHAT).await.unwrap(); |
| 3831 | let record = engine.open_conversation(CHAT).unwrap().remove(0); |
| 3832 | let found = teams_core::images(&record); |
| 3833 | assert_eq!(found.len(), 1); |
| 3834 | assert_eq!((found[0].width, found[0].height), (Some(300), Some(150))); |
| 3835 | assert!(found[0].id.starts_with("0-")); |
| 3836 | assert!(engine.image(found[0].key()).is_none()); |
| 3837 | |
| 3838 | let mut events = engine.subscribe(); |
| 3839 | engine.fetch_image(&found[0]).await.unwrap(); |
| 3840 | engine.fetch_image(&found[0]).await.unwrap(); |
| 3841 | assert_eq!(fake.hosted_requests.lock().unwrap().len(), 1); |
| 3842 | assert_eq!( |
| 3843 | events.try_recv().unwrap(), |
| 3844 | CoreEvent::ImagesChanged { |
| 3845 | keys: vec![HOSTED.to_owned()] |
| 3846 | } |
| 3847 | ); |
| 3848 | let stored = engine.image(found[0].key()).unwrap(); |
| 3849 | assert_eq!(stored.content_type, "image/png"); |
| 3850 | assert_eq!((stored.width, stored.height), (Some(40), Some(20))); |
| 3851 | } |
| 3852 | |
| 3853 | #[tokio::test] |
| 3854 | async fn gif_and_sticker_images_load_without_graph_and_keep_their_cache_key() { |
| 3855 | let fake = Arc::new(Fake::default()); |
| 3856 | let engine = chat_engine(&fake, small_pages()).await; |
| 3857 | 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"; |
| 3858 | let image = teams_core::ImageRef { |
| 3859 | id: "x".to_owned(), |
| 3860 | url: proxied.to_owned(), |
| 3861 | width: None, |
| 3862 | height: None, |
| 3863 | alt: None, |
| 3864 | }; |
| 3865 | engine.fetch_image(&image).await.unwrap(); |
| 3866 | assert_eq!( |
| 3867 | *fake.external_requests.lock().unwrap(), |
| 3868 | ["https://statics.teams.cdn.office.net/x/a.png"] |
| 3869 | ); |
| 3870 | assert!(engine.image(proxied).is_some()); |
| 3871 | } |
| 3872 | |
| 3873 | #[tokio::test] |
| 3874 | async fn a_failed_image_fetch_is_an_error_and_can_be_retried() { |
| 3875 | let fake = Arc::new(Fake::default()); |
| 3876 | let engine = chat_engine(&fake, small_pages()).await; |
| 3877 | let image = teams_core::ImageRef { |
| 3878 | id: "x".to_owned(), |
| 3879 | url: "https://graph.microsoft.com/v1.0/chats/broken".to_owned(), |
| 3880 | width: None, |
| 3881 | height: None, |
| 3882 | alt: None, |
| 3883 | }; |
| 3884 | assert!(engine.fetch_image(&image).await.is_err()); |
| 3885 | assert!(engine.fetch_image(&image).await.is_err()); |
| 3886 | assert_eq!(fake.hosted_requests.lock().unwrap().len(), 2); |
| 3887 | } |
| 3888 | |
| 3889 | #[tokio::test] |
| 3890 | async fn local_search_finds_cached_messages_and_titles() { |
| 3891 | let fake = Arc::new(Fake::default()); |
| 3892 | fake.set_chat_messages(vec![ |
| 3893 | message(1, 1, "<p>quarterly <b>budget</b> review</p>"), |
| 3894 | message(2, 2, "<p>lunch?</p>"), |
| 3895 | ]); |
| 3896 | let engine = chat_engine(&fake, small_pages()).await; |
| 3897 | engine.fetch_newer(CHAT).await.unwrap(); |
| 3898 | let hits = engine.search_messages("budg", 10).unwrap(); |
| 3899 | assert_eq!(hits.len(), 1); |
| 3900 | assert_eq!( |
| 3901 | ( |
| 3902 | hits[0].conversation_id.as_str(), |
| 3903 | hits[0].message_id.as_str() |
| 3904 | ), |
| 3905 | (CHAT, "m0001") |
| 3906 | ); |
| 3907 | assert!(hits[0].snippet.contains("\u{1}budget\u{2}")); |
| 3908 | assert_eq!( |
| 3909 | engine.search_messages_in(CHAT, "lunch", 10).unwrap().len(), |
| 3910 | 1 |
| 3911 | ); |
| 3912 | assert!( |
| 3913 | engine |
| 3914 | .search_messages_in("other", "lunch", 10) |
| 3915 | .unwrap() |
| 3916 | .is_empty() |
| 3917 | ); |
| 3918 | assert_eq!( |
| 3919 | engine.search_conversations("plann", 10).unwrap()[0].conversation_id, |
| 3920 | CHAT |
| 3921 | ); |
| 3922 | } |
| 3923 | |
| 3924 | #[tokio::test] |
| 3925 | async fn first_unread_is_the_first_message_from_others_after_the_read_time() { |
| 3926 | let fake = Arc::new(Fake::default()); |
| 3927 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 10, 2, "user-ada", false)]; |
| 3928 | fake.set_chat_messages(numbered(5)); |
| 3929 | let engine = engine_with(&fake, SyncConfig::default()); |
| 3930 | engine.refresh_sidebar().await.unwrap(); |
| 3931 | engine.fetch_newer(CHAT).await.unwrap(); |
| 3932 | assert_eq!( |
| 3933 | engine.first_unread_message_id(CHAT).as_deref(), |
| 3934 | Some("m0003") |
| 3935 | ); |
| 3936 | assert!(engine.first_unread_message_id("unknown").is_none()); |
| 3937 | engine.mark_read(CHAT).await.unwrap(); |
| 3938 | assert!(engine.first_unread_message_id(CHAT).is_none()); |
| 3939 | } |
| 3940 | |
| 3941 | #[tokio::test] |
| 3942 | async fn chat_reply_quotes_and_channel_reply_uses_the_thread_root() { |
| 3943 | let fake = Arc::new(Fake::default()); |
| 3944 | fake.set_chat_messages(numbered(2)); |
| 3945 | let engine = chat_engine(&fake, small_pages()).await; |
| 3946 | engine.fetch_newer(CHAT).await.unwrap(); |
| 3947 | let sent = engine |
| 3948 | .reply_to(CHAT, "m0001", "answer **bold**") |
| 3949 | .await |
| 3950 | .unwrap(); |
| 3951 | assert_eq!(sent.message_id, "1727203440000"); |
| 3952 | assert!(fake.calls().contains(&format!("chatsvc post {CHAT}"))); |
| 3953 | assert!( |
| 3954 | !fake |
| 3955 | .calls() |
| 3956 | .iter() |
| 3957 | .any(|call| call.starts_with("quote_reply")) |
| 3958 | ); |
| 3959 | |
| 3960 | let channel_fake = Arc::new(Fake::default()); |
| 3961 | let channel = channel_engine(&channel_fake).await; |
| 3962 | channel.fetch_newer(CHANNEL).await.unwrap(); |
| 3963 | channel.reply_to(CHANNEL, "m0030", "hi").await.unwrap(); |
| 3964 | assert!( |
| 3965 | channel_fake |
| 3966 | .calls() |
| 3967 | .contains(&format!("chatsvc post {CHANNEL};messageid=m0030")) |
| 3968 | ); |
| 3969 | assert!(engine.reply_to("unknown", "m1", "x").await.is_err()); |
| 3970 | } |
| 3971 | |
| 3972 | #[tokio::test] |
| 3973 | async fn can_edit_and_delete_need_an_own_live_chat_message() { |
| 3974 | let fake = Arc::new(Fake::default()); |
| 3975 | let mut own = message(1, 1, "<p>mine</p>"); |
| 3976 | own.from = |
| 3977 | serde_json::from_value(json!({"user": {"id": ME, "displayName": "Me Myself"}})).unwrap(); |
| 3978 | fake.set_chat_messages(vec![own, message(2, 2, "<p>theirs</p>")]); |
| 3979 | let engine = chat_engine(&fake, small_pages()).await; |
| 3980 | engine.fetch_newer(CHAT).await.unwrap(); |
| 3981 | let records = engine.open_conversation(CHAT).unwrap(); |
| 3982 | assert!(engine.can_edit(&records[0]) && engine.can_delete(&records[0])); |
| 3983 | assert!(!engine.can_edit(&records[1]) && !engine.can_delete(&records[1])); |
| 3984 | let mut deleted = records[0].clone(); |
| 3985 | deleted.deleted = true; |
| 3986 | assert!(!engine.can_edit(&deleted)); |
| 3987 | assert!(teams_core::can_edit(&records[0], ME)); |
| 3988 | assert!(!teams_core::can_delete(&deleted, ME)); |
| 3989 | } |
| 3990 | |
| 3991 | #[tokio::test] |
| 3992 | async fn channel_posts_and_replies_can_be_reacted_edited_and_deleted() { |
| 3993 | let fake = Arc::new(Fake::default()); |
| 3994 | let engine = channel_engine(&fake).await; |
| 3995 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 3996 | let reply_id = engine |
| 3997 | .open_conversation(CHANNEL) |
| 3998 | .unwrap() |
| 3999 | .into_iter() |
| 4000 | .find(|record| record.reply_to_id.is_some()) |
| 4001 | .unwrap() |
| 4002 | .message_id; |
| 4003 | |
| 4004 | engine.set_reaction(CHANNEL, "m0030", "like").await.unwrap(); |
| 4005 | engine |
| 4006 | .unset_reaction(CHANNEL, &reply_id, "like") |
| 4007 | .await |
| 4008 | .unwrap(); |
| 4009 | engine |
| 4010 | .edit_message(CHANNEL, &reply_id, "new **text**") |
| 4011 | .await |
| 4012 | .unwrap(); |
| 4013 | engine.edit_message(CHANNEL, "m0030", "root").await.unwrap(); |
| 4014 | engine |
| 4015 | .soft_delete_message(CHANNEL, &reply_id) |
| 4016 | .await |
| 4017 | .unwrap(); |
| 4018 | engine.soft_delete_message(CHANNEL, "m0030").await.unwrap(); |
| 4019 | |
| 4020 | let calls = fake.calls(); |
| 4021 | assert!(calls.contains(&"set_reaction channel:-:m0030 like".to_owned())); |
| 4022 | assert!(calls.contains(&format!("unset_reaction channel:m0030:{reply_id} like"))); |
| 4023 | assert!(calls.contains(&format!("edit channel:m0030:{reply_id} new <b>text</b>"))); |
| 4024 | assert!(calls.contains(&"edit channel:-:m0030 root".to_owned())); |
| 4025 | assert!(calls.contains(&format!("soft_delete {ME} channel:m0030:{reply_id}"))); |
| 4026 | assert!(calls.contains(&format!("soft_delete {ME} channel:-:m0030"))); |
| 4027 | assert!(engine.set_reaction("unknown", "m1", "like").await.is_err()); |
| 4028 | } |
| 4029 | |
| 4030 | #[tokio::test] |
| 4031 | async fn channel_messages_of_mine_are_editable_and_deletable() { |
| 4032 | let fake = Arc::new(Fake::default()); |
| 4033 | let engine = channel_engine(&fake).await; |
| 4034 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 4035 | let mut record = engine.open_conversation(CHANNEL).unwrap().remove(0); |
| 4036 | assert!(!engine.can_edit(&record)); |
| 4037 | record.sender_id = Some(ME.to_owned()); |
| 4038 | assert!(engine.can_edit(&record) && engine.can_delete(&record)); |
| 4039 | } |
| 4040 | |
| 4041 | #[tokio::test] |
| 4042 | async fn chat_mentions_become_at_tags_and_a_mentions_array() { |
| 4043 | let fake = Arc::new(Fake::default()); |
| 4044 | let engine = chat_engine(&fake, small_pages()).await; |
| 4045 | engine |
| 4046 | .send_message_with_mentions( |
| 4047 | CHAT, |
| 4048 | "hi @Ada Example & co", |
| 4049 | None, |
| 4050 | &[MentionInput::user("user-ada", "Ada Example")], |
| 4051 | ) |
| 4052 | .await |
| 4053 | .unwrap(); |
| 4054 | assert_eq!( |
| 4055 | fake.sent.lock().unwrap()[0], |
| 4056 | "hi <at id=\"0\">Ada Example</at> & co" |
| 4057 | ); |
| 4058 | let mentions = fake.mentions_sent.lock().unwrap()[0].clone(); |
| 4059 | assert_eq!(mentions.len(), 1); |
| 4060 | assert_eq!(mentions[0].id, 0); |
| 4061 | assert_eq!( |
| 4062 | mentions[0].target, |
| 4063 | MentionTarget::User { |
| 4064 | user_id: "user-ada".to_owned() |
| 4065 | } |
| 4066 | ); |
| 4067 | assert!( |
| 4068 | engine |
| 4069 | .send_message_with_mentions(CHAT, "@Squad", None, &[MentionInput::team("t", "Squad")]) |
| 4070 | .await |
| 4071 | .is_err() |
| 4072 | ); |
| 4073 | } |
| 4074 | |
| 4075 | #[tokio::test] |
| 4076 | async fn channel_mentions_cover_users_channel_and_team_on_post_reply_and_edit() { |
| 4077 | let fake = Arc::new(Fake::default()); |
| 4078 | let engine = channel_engine(&fake).await; |
| 4079 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 4080 | let everyone = [ |
| 4081 | MentionInput::user("user-ada", "Ada Example"), |
| 4082 | MentionInput::channel(CHANNEL, "General"), |
| 4083 | MentionInput::team("team-1", "Squad"), |
| 4084 | ]; |
| 4085 | let text = "@Ada Example @General @Squad"; |
| 4086 | engine |
| 4087 | .post_to_channel_with_mentions(CHANNEL, text, None, &everyone) |
| 4088 | .await |
| 4089 | .unwrap(); |
| 4090 | engine |
| 4091 | .reply_to_with_mentions(CHANNEL, "m0030", text, &everyone) |
| 4092 | .await |
| 4093 | .unwrap(); |
| 4094 | engine |
| 4095 | .edit_message_with_mentions(CHANNEL, "m0030", text, &everyone) |
| 4096 | .await |
| 4097 | .unwrap(); |
| 4098 | for mentions in fake.mentions_sent.lock().unwrap().iter() { |
| 4099 | assert_eq!(mentions.len(), 3); |
| 4100 | assert_eq!( |
| 4101 | mentions |
| 4102 | .iter() |
| 4103 | .map(|mention| mention.id) |
| 4104 | .collect::<Vec<_>>(), |
| 4105 | [0, 1, 2] |
| 4106 | ); |
| 4107 | assert!(matches!(mentions[1].target, MentionTarget::Channel { .. })); |
| 4108 | assert!(matches!(mentions[2].target, MentionTarget::Team { .. })); |
| 4109 | } |
| 4110 | assert_eq!(fake.mentions_sent.lock().unwrap().len(), 3); |
| 4111 | } |
| 4112 | |
| 4113 | fn directory_user(id: &str, name: &str) -> User { |
| 4114 | serde_json::from_value( |
| 4115 | json!({"id": id, "displayName": name, "mail": format!("{id}@example.test")}), |
| 4116 | ) |
| 4117 | .unwrap() |
| 4118 | } |
| 4119 | |
| 4120 | #[tokio::test] |
| 4121 | async fn people_candidates_list_members_first_then_the_directory_without_duplicates() { |
| 4122 | let fake = Arc::new(Fake::default()); |
| 4123 | *fake.directory_users.lock().unwrap() = vec![ |
| 4124 | directory_user("user-me", "Me Myself"), |
| 4125 | directory_user("user-ada", "Ada Example"), |
| 4126 | directory_user("user-adam", "Adam Directory"), |
| 4127 | ]; |
| 4128 | let engine = chat_engine(&fake, small_pages()).await; |
| 4129 | |
| 4130 | let all = engine.mention_candidates(CHAT, "", 10).await.unwrap(); |
| 4131 | assert_eq!(all.len(), 2); |
| 4132 | assert!(matches!(&all[0], MentionCandidate::Everyone { chat_id } if chat_id == CHAT)); |
| 4133 | assert_eq!( |
| 4134 | all[0].to_mention(), |
| 4135 | MentionInput::everyone(CHAT, "Everyone") |
| 4136 | ); |
| 4137 | assert_eq!(all[1].display_name(), "Ada Example"); |
| 4138 | assert!(!fake.calls().iter().any(|call| call.starts_with("search"))); |
| 4139 | |
| 4140 | let found = engine.mention_candidates(CHAT, "@ada", 10).await.unwrap(); |
| 4141 | let names: Vec<&str> = found |
| 4142 | .iter() |
| 4143 | .map(|candidate| candidate.display_name()) |
| 4144 | .collect(); |
| 4145 | assert_eq!(names, ["Ada Example", "Adam Directory"]); |
| 4146 | assert!( |
| 4147 | matches!(&found[0], MentionCandidate::Person(person) if person.source == PersonSource::Member) |
| 4148 | ); |
| 4149 | assert!( |
| 4150 | matches!(&found[1], MentionCandidate::Person(person) if person.source == PersonSource::Directory) |
| 4151 | ); |
| 4152 | |
| 4153 | engine.mention_candidates(CHAT, "ada", 10).await.unwrap(); |
| 4154 | engine.search_people("ADA").await.unwrap(); |
| 4155 | let searches = fake |
| 4156 | .calls() |
| 4157 | .into_iter() |
| 4158 | .filter(|call| call.starts_with("search")) |
| 4159 | .count(); |
| 4160 | assert_eq!(searches, 1); |
| 4161 | |
| 4162 | assert_eq!( |
| 4163 | engine |
| 4164 | .mention_candidates(CHAT, "ada", 1) |
| 4165 | .await |
| 4166 | .unwrap() |
| 4167 | .len(), |
| 4168 | 1 |
| 4169 | ); |
| 4170 | assert!(engine.mention_candidates("unknown", "a", 5).await.is_err()); |
| 4171 | } |
| 4172 | |
| 4173 | #[tokio::test] |
| 4174 | async fn channel_candidates_offer_recent_senders_the_channel_and_its_team() { |
| 4175 | let fake = Arc::new(Fake::default()); |
| 4176 | let engine = channel_engine(&fake).await; |
| 4177 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 4178 | let all = engine.mention_candidates(CHANNEL, "", 10).await.unwrap(); |
| 4179 | assert_eq!(all.len(), 4); |
| 4180 | assert!(matches!(&all[0], MentionCandidate::Person(person) if person.user_id == "user-ada")); |
| 4181 | assert!( |
| 4182 | matches!(&all[1], MentionCandidate::Channel { channel_id, .. } if channel_id == CHANNEL) |
| 4183 | ); |
| 4184 | assert!(matches!(&all[2], MentionCandidate::Team { team_id, .. } if team_id == "team-1")); |
| 4185 | assert!( |
| 4186 | matches!(&all[3], MentionCandidate::Tag { tag_id, member_count: Some(4), .. } if tag_id == "tag-design") |
| 4187 | ); |
| 4188 | let design = engine |
| 4189 | .mention_candidates(CHANNEL, "desi", 10) |
| 4190 | .await |
| 4191 | .unwrap(); |
| 4192 | assert_eq!( |
| 4193 | design[0].to_mention(), |
| 4194 | MentionInput::tag("tag-design", "Designers") |
| 4195 | ); |
| 4196 | engine.mention_candidates(CHANNEL, "", 10).await.unwrap(); |
| 4197 | let tag_loads = fake |
| 4198 | .calls() |
| 4199 | .into_iter() |
| 4200 | .filter(|call| call.starts_with("tags")) |
| 4201 | .count(); |
| 4202 | assert_eq!(tag_loads, 1); |
| 4203 | let squad = engine.mention_candidates(CHANNEL, "squ", 10).await.unwrap(); |
| 4204 | assert_eq!(squad[0].to_mention(), MentionInput::team("team-1", "Squad")); |
| 4205 | } |
| 4206 | |
| 4207 | #[tokio::test] |
| 4208 | async fn images_land_as_lru_files_and_are_served_by_path() { |
| 4209 | let directory = tempfile::tempdir().unwrap(); |
| 4210 | let fake = Arc::new(Fake::default()); |
| 4211 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 4212 | let engine = engine_with(&fake, small_pages()) |
| 4213 | .with_image_dir(directory.path(), 1024 * 1024) |
| 4214 | .unwrap(); |
| 4215 | engine.refresh_sidebar().await.unwrap(); |
| 4216 | let image = teams_core::ImageRef { |
| 4217 | id: "h1".to_owned(), |
| 4218 | url: HOSTED.to_owned(), |
| 4219 | width: None, |
| 4220 | height: None, |
| 4221 | alt: None, |
| 4222 | }; |
| 4223 | assert!(engine.image_path(&image).is_none()); |
| 4224 | let mut events = engine.subscribe(); |
| 4225 | let path = engine.fetch_image(&image).await.unwrap().unwrap(); |
| 4226 | assert_eq!(path.extension().unwrap(), "png"); |
| 4227 | assert!(path.starts_with(directory.path())); |
| 4228 | assert_eq!(engine.image_path(&image), Some(path.clone())); |
| 4229 | assert_eq!(engine.fetch_image(&image).await.unwrap(), Some(path)); |
| 4230 | assert_eq!(fake.hosted_requests.lock().unwrap().len(), 1); |
| 4231 | assert!(matches!( |
| 4232 | events.try_recv().unwrap(), |
| 4233 | CoreEvent::ImagesChanged { .. } |
| 4234 | )); |
| 4235 | let stored = engine.image(HOSTED).unwrap(); |
| 4236 | assert_eq!((stored.width, stored.height), (Some(40), Some(20))); |
| 4237 | assert!(engine.store().image(HOSTED).unwrap().is_none()); |
| 4238 | } |
| 4239 | |
| 4240 | #[tokio::test] |
| 4241 | async fn a_read_chat_has_no_first_unread_message() { |
| 4242 | let fake = Arc::new(Fake::default()); |
| 4243 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 10, 10, "user-ada", false)]; |
| 4244 | fake.set_chat_messages(numbered(5)); |
| 4245 | let engine = engine_with(&fake, SyncConfig::default()); |
| 4246 | engine.refresh_sidebar().await.unwrap(); |
| 4247 | engine.fetch_newer(CHAT).await.unwrap(); |
| 4248 | assert!(engine.first_unread_message_id(CHAT).is_none()); |
| 4249 | } |
| 4250 | |
| 4251 | fn millis(minute: i64) -> i64 { |
| 4252 | (base() + Duration::minutes(minute)).timestamp_millis() |
| 4253 | } |
| 4254 | |
| 4255 | fn horizon_of(user: &str, read_minute: i64, at_minute: i64) -> chatsvc::MemberHorizon { |
| 4256 | chatsvc::receipts::parse_horizon( |
| 4257 | &format!("8:orgid:{user}"), |
| 4258 | &format!( |
| 4259 | "{};{};6638000000000000001", |
| 4260 | millis(read_minute), |
| 4261 | millis(at_minute) |
| 4262 | ), |
| 4263 | ) |
| 4264 | .unwrap() |
| 4265 | } |
| 4266 | |
| 4267 | fn own_message(id: u32, minute: i64) -> Message { |
| 4268 | serde_json::from_value(json!({ |
| 4269 | "id": format!("m{id:04}"), |
| 4270 | "messageType": "message", |
| 4271 | "createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(), |
| 4272 | "from": {"user": {"id": ME, "displayName": "Me Myself"}}, |
| 4273 | "body": {"contentType": "html", "content": "<p>mine</p>"}, |
| 4274 | })) |
| 4275 | .unwrap() |
| 4276 | } |
| 4277 | |
| 4278 | fn group_chat(id: &str) -> Chat { |
| 4279 | serde_json::from_value(json!({ |
| 4280 | "id": id, |
| 4281 | "topic": "Planning", |
| 4282 | "chatType": "group", |
| 4283 | "lastUpdatedDateTime": base().to_rfc3339(), |
| 4284 | "members": [ |
| 4285 | {"userId": ME, "displayName": "Me Myself"}, |
| 4286 | {"userId": "user-ada", "displayName": "Ada Example"}, |
| 4287 | {"userId": "user-bob", "displayName": "Bob Example"}, |
| 4288 | {"userId": "user-cy", "displayName": "Cy Example"} |
| 4289 | ], |
| 4290 | "viewpoint": {"lastMessageReadDateTime": base().to_rfc3339(), "isHidden": false}, |
| 4291 | })) |
| 4292 | .unwrap() |
| 4293 | } |
| 4294 | |
| 4295 | async fn receipt_engine(fake: &Arc<Fake>, chats: Vec<Chat>) -> SyncEngine<Handle> { |
| 4296 | *fake.chats.lock().unwrap() = chats; |
| 4297 | fake.set_chat_messages(vec![ |
| 4298 | own_message(1, 1), |
| 4299 | message(2, 2, "<p>theirs</p>"), |
| 4300 | own_message(3, 3), |
| 4301 | ]); |
| 4302 | let engine = engine_with(fake, small_pages()) |
| 4303 | .with_receipt_debounce(std::time::Duration::from_millis(60)); |
| 4304 | engine.refresh_sidebar().await.unwrap(); |
| 4305 | engine.fetch_newer(CHAT).await.unwrap(); |
| 4306 | engine |
| 4307 | } |
| 4308 | |
| 4309 | fn one_on_one() -> Chat { |
| 4310 | chat(CHAT, None, 5, 5, ME, false) |
| 4311 | } |
| 4312 | |
| 4313 | #[tokio::test] |
| 4314 | async fn one_on_one_read_up_to_horizon() { |
| 4315 | let fake = Arc::new(Fake::default()); |
| 4316 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4317 | *fake.horizons.lock().unwrap() = |
| 4318 | vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 2, 9)]; |
| 4319 | let mut events = engine.subscribe(); |
| 4320 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4321 | assert_eq!( |
| 4322 | events.try_recv().unwrap(), |
| 4323 | CoreEvent::ReceiptsChanged { |
| 4324 | conversation_id: CHAT.into() |
| 4325 | } |
| 4326 | ); |
| 4327 | assert_eq!( |
| 4328 | engine.receipt_state(CHAT, "m0001"), |
| 4329 | teams_core::ReceiptState::Read { |
| 4330 | readers: vec![teams_core::ReceiptReader { |
| 4331 | name: "Ada Example".into(), |
| 4332 | at: base() + Duration::minutes(9), |
| 4333 | }], |
| 4334 | total_others: 1, |
| 4335 | } |
| 4336 | ); |
| 4337 | assert_eq!( |
| 4338 | engine.receipt_state(CHAT, "m0003"), |
| 4339 | teams_core::ReceiptState::Sent |
| 4340 | ); |
| 4341 | assert_eq!( |
| 4342 | engine.receipt_state(CHAT, "m0002"), |
| 4343 | teams_core::ReceiptState::Unknown |
| 4344 | ); |
| 4345 | assert_eq!( |
| 4346 | engine.receipt_state(CHAT, "missing"), |
| 4347 | teams_core::ReceiptState::Unknown |
| 4348 | ); |
| 4349 | } |
| 4350 | |
| 4351 | #[tokio::test] |
| 4352 | async fn stored_horizons_show_receipts_after_a_restart_before_any_refresh() { |
| 4353 | let fake = Arc::new(Fake::default()); |
| 4354 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4355 | *fake.horizons.lock().unwrap() = |
| 4356 | vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 2, 9)]; |
| 4357 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4358 | let restarted = |
| 4359 | SyncEngine::with_config(Handle(fake.clone()), engine.store().clone(), small_pages()); |
| 4360 | fake.horizons.lock().unwrap().clear(); |
| 4361 | |
| 4362 | assert!(matches!( |
| 4363 | restarted.receipt_state(CHAT, "m0001"), |
| 4364 | teams_core::ReceiptState::Read { .. } |
| 4365 | )); |
| 4366 | assert_eq!( |
| 4367 | restarted.receipt_state(CHAT, "m0003"), |
| 4368 | teams_core::ReceiptState::Sent |
| 4369 | ); |
| 4370 | } |
| 4371 | |
| 4372 | #[tokio::test] |
| 4373 | async fn horizon_equal_to_creation_time_counts_as_read() { |
| 4374 | let fake = Arc::new(Fake::default()); |
| 4375 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4376 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 3)]; |
| 4377 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4378 | assert!(matches!( |
| 4379 | engine.receipt_state(CHAT, "m0003"), |
| 4380 | teams_core::ReceiptState::Read { .. } |
| 4381 | )); |
| 4382 | } |
| 4383 | |
| 4384 | #[tokio::test] |
| 4385 | async fn nobody_read_means_sent() { |
| 4386 | let fake = Arc::new(Fake::default()); |
| 4387 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4388 | *fake.horizons.lock().unwrap() = |
| 4389 | vec![horizon_of("user-me", 3, 3), horizon_of("user-ada", 0, 0)]; |
| 4390 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4391 | assert_eq!( |
| 4392 | engine.receipt_state(CHAT, "m0001"), |
| 4393 | teams_core::ReceiptState::Sent |
| 4394 | ); |
| 4395 | assert_eq!( |
| 4396 | engine.receipt_state(CHAT, "m0003"), |
| 4397 | teams_core::ReceiptState::Sent |
| 4398 | ); |
| 4399 | } |
| 4400 | |
| 4401 | #[tokio::test] |
| 4402 | async fn group_partial_read_lists_who_and_total() { |
| 4403 | let fake = Arc::new(Fake::default()); |
| 4404 | let engine = receipt_engine(&fake, vec![group_chat(CHAT)]).await; |
| 4405 | *fake.horizons.lock().unwrap() = vec![ |
| 4406 | horizon_of("user-me", 3, 3), |
| 4407 | horizon_of("user-cy", 3, 8), |
| 4408 | horizon_of("user-ada", 1, 6), |
| 4409 | horizon_of("user-bob", 0, 0), |
| 4410 | ]; |
| 4411 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4412 | let names = |state: teams_core::ReceiptState| match state { |
| 4413 | teams_core::ReceiptState::Read { |
| 4414 | readers, |
| 4415 | total_others, |
| 4416 | } => ( |
| 4417 | readers |
| 4418 | .into_iter() |
| 4419 | .map(|reader| reader.name) |
| 4420 | .collect::<Vec<_>>(), |
| 4421 | total_others, |
| 4422 | ), |
| 4423 | other => panic!("expected read, got {other:?}"), |
| 4424 | }; |
| 4425 | assert_eq!( |
| 4426 | names(engine.receipt_state(CHAT, "m0001")), |
| 4427 | (vec!["Ada Example".to_owned(), "Cy Example".to_owned()], 3) |
| 4428 | ); |
| 4429 | assert_eq!( |
| 4430 | names(engine.receipt_state(CHAT, "m0003")), |
| 4431 | (vec!["Cy Example".to_owned()], 3) |
| 4432 | ); |
| 4433 | } |
| 4434 | |
| 4435 | #[tokio::test] |
| 4436 | async fn disabled_receipts_are_unknown() { |
| 4437 | let fake = Arc::new(Fake::default()); |
| 4438 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4439 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4440 | assert_eq!( |
| 4441 | engine.receipt_state(CHAT, "m0001"), |
| 4442 | teams_core::ReceiptState::Unknown |
| 4443 | ); |
| 4444 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-me", 3, 3)]; |
| 4445 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4446 | assert_eq!( |
| 4447 | engine.receipt_state(CHAT, "m0001"), |
| 4448 | teams_core::ReceiptState::Unknown |
| 4449 | ); |
| 4450 | } |
| 4451 | |
| 4452 | #[tokio::test] |
| 4453 | async fn disabling_after_reading_clears_the_state_and_announces() { |
| 4454 | let fake = Arc::new(Fake::default()); |
| 4455 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4456 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 3)]; |
| 4457 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4458 | let mut events = engine.subscribe(); |
| 4459 | fake.horizons.lock().unwrap().clear(); |
| 4460 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4461 | assert_eq!( |
| 4462 | events.try_recv().unwrap(), |
| 4463 | CoreEvent::ReceiptsChanged { |
| 4464 | conversation_id: CHAT.into() |
| 4465 | } |
| 4466 | ); |
| 4467 | assert_eq!( |
| 4468 | engine.receipt_state(CHAT, "m0001"), |
| 4469 | teams_core::ReceiptState::Unknown |
| 4470 | ); |
| 4471 | } |
| 4472 | |
| 4473 | #[tokio::test] |
| 4474 | async fn unchanged_horizons_announce_nothing() { |
| 4475 | let fake = Arc::new(Fake::default()); |
| 4476 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4477 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 3)]; |
| 4478 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4479 | let mut events = engine.subscribe(); |
| 4480 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4481 | assert!(events.try_recv().is_err()); |
| 4482 | } |
| 4483 | |
| 4484 | #[tokio::test] |
| 4485 | async fn channels_and_deleted_messages_have_no_state() { |
| 4486 | let fake = Arc::new(Fake::default()); |
| 4487 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4488 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 3)]; |
| 4489 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4490 | let mut deleted = engine.open_conversation(CHAT).unwrap().remove(0); |
| 4491 | deleted.deleted = true; |
| 4492 | assert_eq!( |
| 4493 | engine.receipt_state_for(&deleted), |
| 4494 | teams_core::ReceiptState::Unknown |
| 4495 | ); |
| 4496 | engine.refresh_receipts(CHANNEL).await.unwrap_err(); |
| 4497 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 1); |
| 4498 | } |
| 4499 | |
| 4500 | #[tokio::test] |
| 4501 | async fn read_event_burst_triggers_one_fetch() { |
| 4502 | let fake = Arc::new(Fake::default()); |
| 4503 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4504 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 1, 4)]; |
| 4505 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4506 | let before = *fake.horizon_calls.lock().unwrap(); |
| 4507 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 7)]; |
| 4508 | let event = read_event(Some(CHAT)); |
| 4509 | let started = std::time::Instant::now(); |
| 4510 | tokio::join!( |
| 4511 | engine.handle_receipt_event(&event), |
| 4512 | engine.handle_receipt_event(&event), |
| 4513 | engine.handle_receipt_event(&event), |
| 4514 | ); |
| 4515 | assert!(started.elapsed() >= std::time::Duration::from_millis(60)); |
| 4516 | assert_eq!(*fake.horizon_calls.lock().unwrap(), before + 1); |
| 4517 | assert!(matches!( |
| 4518 | engine.receipt_state(CHAT, "m0003"), |
| 4519 | teams_core::ReceiptState::Read { .. } |
| 4520 | )); |
| 4521 | } |
| 4522 | |
| 4523 | fn read_event(conversation_id: Option<&str>) -> chatsvc::MessageEvent { |
| 4524 | chatsvc::MessageEvent { |
| 4525 | resource_type: "NewMessage".into(), |
| 4526 | kind: chatsvc::EventKind::ReadReceipt, |
| 4527 | conversation_id: conversation_id.map(str::to_owned), |
| 4528 | message_id: None, |
| 4529 | received_at: base(), |
| 4530 | } |
| 4531 | } |
| 4532 | |
| 4533 | #[tokio::test] |
| 4534 | async fn events_for_other_kinds_or_unopened_chats_do_nothing() { |
| 4535 | let fake = Arc::new(Fake::default()); |
| 4536 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4537 | let mut typing = read_event(Some(CHAT)); |
| 4538 | typing.kind = chatsvc::EventKind::Typing; |
| 4539 | engine.handle_receipt_event(&typing).await; |
| 4540 | engine.handle_receipt_event(&read_event(Some(CHAT))).await; |
| 4541 | engine.handle_receipt_event(&read_event(None)).await; |
| 4542 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 0); |
| 4543 | } |
| 4544 | |
| 4545 | #[tokio::test] |
| 4546 | async fn reconnect_refetches_known_chats_only() { |
| 4547 | let fake = Arc::new(Fake::default()); |
| 4548 | let engine = receipt_engine(&fake, vec![one_on_one()]).await; |
| 4549 | let status = |kind| chatsvc::StatusEvent { |
| 4550 | kind, |
| 4551 | detail: String::new(), |
| 4552 | }; |
| 4553 | engine |
| 4554 | .handle_receipt_status(&status(chatsvc::StatusKind::Connected)) |
| 4555 | .await; |
| 4556 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 0); |
| 4557 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 1, 4)]; |
| 4558 | engine.refresh_receipts(CHAT).await.unwrap(); |
| 4559 | engine |
| 4560 | .handle_receipt_status(&status(chatsvc::StatusKind::Disconnected)) |
| 4561 | .await; |
| 4562 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 1); |
| 4563 | *fake.horizons.lock().unwrap() = vec![horizon_of("user-ada", 3, 7)]; |
| 4564 | let mut events = engine.subscribe(); |
| 4565 | engine |
| 4566 | .handle_receipt_status(&status(chatsvc::StatusKind::MessageLoss)) |
| 4567 | .await; |
| 4568 | assert_eq!(*fake.horizon_calls.lock().unwrap(), 2); |
| 4569 | assert!(matches!( |
| 4570 | events.try_recv().unwrap(), |
| 4571 | CoreEvent::ReceiptsChanged { .. } |
| 4572 | )); |
| 4573 | } |
| 4574 | |
| 4575 | const BOT_GUID: &str = "0000aaaa-0000-0000-0000-000000000001"; |
| 4576 | |
| 4577 | fn chat_app(app_id: &str, name: &str, bot_ids: &[&str]) -> chatsvc::ChatApp { |
| 4578 | chatsvc::ChatApp { |
| 4579 | app_id: app_id.to_owned(), |
| 4580 | name: name.to_owned(), |
| 4581 | bot_ids: bot_ids.iter().map(|bot| (*bot).to_owned()).collect(), |
| 4582 | small_image_url: None, |
| 4583 | accent_color: None, |
| 4584 | web_application_resource: None, |
| 4585 | } |
| 4586 | } |
| 4587 | |
| 4588 | fn bot_message(application_id: &str) -> Message { |
| 4589 | serde_json::from_value(json!({ |
| 4590 | "id": "m0001", |
| 4591 | "messageType": "message", |
| 4592 | "createdDateTime": base().to_rfc3339(), |
| 4593 | "from": {"application": {"id": application_id, "displayName": "Wiki Bot"}}, |
| 4594 | "body": {"contentType": "html", "content": "<attachment id=\"a1\"></attachment>"}, |
| 4595 | })) |
| 4596 | .unwrap() |
| 4597 | } |
| 4598 | |
| 4599 | async fn card_engine(fake: &Arc<Fake>, application_id: &str) -> SyncEngine<Handle> { |
| 4600 | let engine = chat_engine(fake, small_pages()).await; |
| 4601 | fake.set_chat_messages(vec![bot_message(application_id)]); |
| 4602 | engine.fetch_newer(CHAT).await.unwrap(); |
| 4603 | engine |
| 4604 | } |
| 4605 | |
| 4606 | fn submit_action(data: serde_json::Value) -> teams_core::CardAction { |
| 4607 | let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [ |
| 4608 | {"type": "Action.Submit", "title": "Go", "data": data} |
| 4609 | ]}); |
| 4610 | teams_core::AdaptiveCard::parse(&card.to_string()) |
| 4611 | .unwrap() |
| 4612 | .actions |
| 4613 | .remove(0) |
| 4614 | } |
| 4615 | |
| 4616 | #[tokio::test] |
| 4617 | async fn card_submit_invokes_the_matching_bot_and_caches_the_apps() { |
| 4618 | let fake = Arc::new(Fake::default()); |
| 4619 | *fake.apps.lock().unwrap() = vec![ |
| 4620 | chat_app( |
| 4621 | "app-other", |
| 4622 | "Other", |
| 4623 | &["0000bbbb-0000-0000-0000-000000000002"], |
| 4624 | ), |
| 4625 | chat_app("app-wiki", "Wiki", &[BOT_GUID]), |
| 4626 | ]; |
| 4627 | let engine = card_engine(&fake, BOT_GUID).await; |
| 4628 | let action = submit_action(json!({"type": "unwatch"})); |
| 4629 | |
| 4630 | let first = engine.card_action(CHAT, "m0001", &action).await.unwrap(); |
| 4631 | let second = engine.card_action(CHAT, "m0001", &action).await.unwrap(); |
| 4632 | |
| 4633 | assert_eq!(first, teams_core::CardActionOutcome::Sent); |
| 4634 | assert_eq!(second, first); |
| 4635 | assert_eq!(*fake.app_calls.lock().unwrap(), 1); |
| 4636 | let invokes = fake.invokes.lock().unwrap(); |
| 4637 | assert_eq!(invokes[0].app_id, "app-wiki"); |
| 4638 | assert_eq!(invokes[0].bot_id, BOT_GUID); |
| 4639 | assert_eq!(invokes[0].name, "messageback"); |
| 4640 | assert_eq!(invokes[0].value, json!({"type": "unwatch"})); |
| 4641 | assert_eq!(invokes[0].server_message_id, "m0001"); |
| 4642 | assert_eq!(invokes[0].conversation_id, CHAT); |
| 4643 | assert_eq!(invokes[0].display_name, "Me Myself"); |
| 4644 | } |
| 4645 | |
| 4646 | #[tokio::test] |
| 4647 | async fn card_action_falls_back_to_the_only_bot_app() { |
| 4648 | let fake = Arc::new(Fake::default()); |
| 4649 | *fake.apps.lock().unwrap() = vec![ |
| 4650 | chat_app("app-tabs", "Tabs", &[]), |
| 4651 | chat_app("app-wiki", "Wiki", &[BOT_GUID]), |
| 4652 | ]; |
| 4653 | let engine = card_engine(&fake, "unrelated-id").await; |
| 4654 | engine |
| 4655 | .card_action(CHAT, "m0001", &submit_action(json!({}))) |
| 4656 | .await |
| 4657 | .unwrap(); |
| 4658 | let invokes = fake.invokes.lock().unwrap(); |
| 4659 | assert_eq!(invokes[0].app_id, "app-wiki"); |
| 4660 | assert_eq!(invokes[0].bot_id, BOT_GUID); |
| 4661 | } |
| 4662 | |
| 4663 | #[tokio::test] |
| 4664 | async fn card_action_with_several_unmatched_bot_apps_is_an_error() { |
| 4665 | let fake = Arc::new(Fake::default()); |
| 4666 | *fake.apps.lock().unwrap() = vec![ |
| 4667 | chat_app("app-one", "One", &["bot-1"]), |
| 4668 | chat_app("app-two", "Two", &["bot-2"]), |
| 4669 | ]; |
| 4670 | let engine = card_engine(&fake, "unrelated-id").await; |
| 4671 | let outcome = engine |
| 4672 | .card_action(CHAT, "m0001", &submit_action(json!({}))) |
| 4673 | .await; |
| 4674 | assert!(outcome.is_err()); |
| 4675 | assert!(fake.invokes.lock().unwrap().is_empty()); |
| 4676 | } |
| 4677 | |
| 4678 | #[tokio::test] |
| 4679 | async fn card_answers_map_to_outcomes() { |
| 4680 | use chatsvc::{InvokeResponse, TaskContent, TaskContinue, TaskResponse}; |
| 4681 | use teams_core::{CardActionOutcome, TaskDialog, TaskDialogKind}; |
| 4682 | |
| 4683 | let fake = Arc::new(Fake::default()); |
| 4684 | *fake.apps.lock().unwrap() = vec![chat_app("app-wiki", "Wiki", &[BOT_GUID])]; |
| 4685 | let engine = card_engine(&fake, BOT_GUID).await; |
| 4686 | let action = submit_action(json!({"msteams": {"type": "task/fetch"}})); |
| 4687 | let answers = [ |
| 4688 | ( |
| 4689 | InvokeResponse::Card(json!({"type": "AdaptiveCard"})), |
| 4690 | CardActionOutcome::ReplaceCard(json!({"type": "AdaptiveCard"}).to_string()), |
| 4691 | ), |
| 4692 | ( |
| 4693 | InvokeResponse::Message("Saved".into()), |
| 4694 | CardActionOutcome::Message("Saved".into()), |
| 4695 | ), |
| 4696 | ( |
| 4697 | InvokeResponse::Task(TaskResponse::Message("Done".into())), |
| 4698 | CardActionOutcome::Message("Done".into()), |
| 4699 | ), |
| 4700 | ( |
| 4701 | InvokeResponse::Failed { |
| 4702 | status_code: 500, |
| 4703 | message: "Broken".into(), |
| 4704 | }, |
| 4705 | CardActionOutcome::Failed("The app answered 500: Broken".into()), |
| 4706 | ), |
| 4707 | ( |
| 4708 | InvokeResponse::Task(TaskResponse::Continue(TaskContinue { |
| 4709 | title: Some("Settings".into()), |
| 4710 | width: None, |
| 4711 | height: Some(300), |
| 4712 | content: TaskContent::Url { |
| 4713 | url: "https://bot.example/task".into(), |
| 4714 | fallback_url: None, |
| 4715 | }, |
| 4716 | })), |
| 4717 | CardActionOutcome::Dialog(TaskDialog { |
| 4718 | title: Some("Settings".into()), |
| 4719 | width: 520, |
| 4720 | height: 300, |
| 4721 | kind: TaskDialogKind::Url { |
| 4722 | url: "https://bot.example/task".into(), |
| 4723 | fallback_url: "https://bot.example/task".into(), |
| 4724 | }, |
| 4725 | }), |
| 4726 | ), |
| 4727 | ( |
| 4728 | InvokeResponse::Task(TaskResponse::Continue(TaskContinue { |
| 4729 | title: None, |
| 4730 | width: Some(600), |
| 4731 | height: Some(400), |
| 4732 | content: TaskContent::Card(json!({"type": "AdaptiveCard"})), |
| 4733 | })), |
| 4734 | CardActionOutcome::Dialog(TaskDialog { |
| 4735 | title: None, |
| 4736 | width: 600, |
| 4737 | height: 400, |
| 4738 | kind: TaskDialogKind::Card(json!({"type": "AdaptiveCard"}).to_string()), |
| 4739 | }), |
| 4740 | ), |
| 4741 | ]; |
| 4742 | for (answer, expected) in answers { |
| 4743 | *fake.invoke_answer.lock().unwrap() = Some(answer); |
| 4744 | assert_eq!( |
| 4745 | engine.card_action(CHAT, "m0001", &action).await.unwrap(), |
| 4746 | expected |
| 4747 | ); |
| 4748 | } |
| 4749 | assert_eq!(fake.invokes.lock().unwrap()[0].name, "task/fetch"); |
| 4750 | } |
| 4751 | |
| 4752 | #[tokio::test] |
| 4753 | async fn task_submit_wraps_the_data_for_the_dialog() { |
| 4754 | let fake = Arc::new(Fake::default()); |
| 4755 | *fake.apps.lock().unwrap() = vec![chat_app("app-wiki", "Wiki", &[BOT_GUID])]; |
| 4756 | let engine = card_engine(&fake, BOT_GUID).await; |
| 4757 | engine |
| 4758 | .task_submit(CHAT, "m0001", json!({"choice": "a"})) |
| 4759 | .await |
| 4760 | .unwrap(); |
| 4761 | let invokes = fake.invokes.lock().unwrap(); |
| 4762 | assert_eq!(invokes[0].name, "task/submit"); |
| 4763 | assert_eq!( |
| 4764 | invokes[0].value, |
| 4765 | json!({"data": {"choice": "a"}, "context": {"theme": "dark"}}) |
| 4766 | ); |
| 4767 | } |
| 4768 | |
| 4769 | #[tokio::test] |
| 4770 | async fn dialog_identity_names_the_user_and_the_tenant() { |
| 4771 | let fake = Arc::new(Fake::default()); |
| 4772 | let engine = card_engine(&fake, BOT_GUID).await; |
| 4773 | let identity = engine.dialog_identity(CHAT).await.unwrap(); |
| 4774 | assert_eq!(identity.user_id, ME); |
| 4775 | assert_eq!(identity.display_name, "Me Myself"); |
| 4776 | assert_eq!(identity.tenant_id, "tenant-1"); |
| 4777 | } |
| 4778 | |
| 4779 | #[tokio::test] |
| 4780 | async fn card_actions_without_a_payload_are_rejected() { |
| 4781 | let fake = Arc::new(Fake::default()); |
| 4782 | let engine = card_engine(&fake, BOT_GUID).await; |
| 4783 | let card = json!({"body": [{"type": "TextBlock", "text": "x"}], "actions": [ |
| 4784 | {"type": "Action.OpenUrl", "title": "Open", "url": "https://example.com"} |
| 4785 | ]}); |
| 4786 | let action = teams_core::AdaptiveCard::parse(&card.to_string()) |
| 4787 | .unwrap() |
| 4788 | .actions |
| 4789 | .remove(0); |
| 4790 | assert!(engine.card_action(CHAT, "m0001", &action).await.is_err()); |
| 4791 | } |
| 4792 | |
| 4793 | #[tokio::test] |
| 4794 | async fn bot_messages_remember_their_application() { |
| 4795 | let fake = Arc::new(Fake::default()); |
| 4796 | let engine = card_engine(&fake, BOT_GUID).await; |
| 4797 | let record = engine.open_conversation(CHAT).unwrap().remove(0); |
| 4798 | assert_eq!(record.sender_application_id.as_deref(), Some(BOT_GUID)); |
| 4799 | assert_eq!(record.sender_id, None); |
| 4800 | } |
| 4801 | |
| 4802 | const PREVIEW_LINKS: &str = |
| 4803 | r#"[{"url":"https://a.example/x","preview":{"title":"Example"},"previewenabled":true}]"#; |
| 4804 | |
| 4805 | #[tokio::test] |
| 4806 | async fn links_from_the_chat_service_survive_the_next_graph_sync() { |
| 4807 | let fake = Arc::new(Fake::default()); |
| 4808 | let engine = chat_engine(&fake, small_pages()).await; |
| 4809 | fake.set_chat_messages(vec![message( |
| 4810 | 1, |
| 4811 | 1, |
| 4812 | "<p><a href=\"https://a.example/x\">link</a></p>", |
| 4813 | )]); |
| 4814 | *fake.link_pages.lock().unwrap() = vec![chatsvc::MessageLinks { |
| 4815 | message_id: "m0001".into(), |
| 4816 | links_json: PREVIEW_LINKS.into(), |
| 4817 | }]; |
| 4818 | |
| 4819 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 4820 | assert_eq!(delta.added[0].links_json, PREVIEW_LINKS); |
| 4821 | assert_eq!( |
| 4822 | engine.open_conversation(CHAT).unwrap()[0].links_json, |
| 4823 | PREVIEW_LINKS |
| 4824 | ); |
| 4825 | assert_eq!(*fake.link_page_calls.lock().unwrap(), [CHAT]); |
| 4826 | |
| 4827 | let again = engine.fetch_newer(CHAT).await.unwrap(); |
| 4828 | assert!(again.is_empty()); |
| 4829 | assert_eq!( |
| 4830 | engine.open_conversation(CHAT).unwrap()[0].links_json, |
| 4831 | PREVIEW_LINKS |
| 4832 | ); |
| 4833 | } |
| 4834 | |
| 4835 | #[tokio::test] |
| 4836 | async fn messages_without_anchors_do_not_ask_the_chat_service() { |
| 4837 | let fake = Arc::new(Fake::default()); |
| 4838 | let engine = chat_engine(&fake, small_pages()).await; |
| 4839 | fake.set_chat_messages(vec![message(1, 1, "<p>plain</p>")]); |
| 4840 | engine.fetch_newer(CHAT).await.unwrap(); |
| 4841 | assert!(fake.link_page_calls.lock().unwrap().is_empty()); |
| 4842 | } |
| 4843 | |
| 4844 | #[tokio::test] |
| 4845 | async fn a_failing_chat_service_leaves_no_preview() { |
| 4846 | let fake = Arc::new(Fake::default()); |
| 4847 | let engine = chat_engine(&fake, small_pages()).await; |
| 4848 | fake.set_chat_messages(vec![message(1, 1, "<a href=\"https://a.example\">x</a>")]); |
| 4849 | let delta = engine.fetch_newer(CHAT).await.unwrap(); |
| 4850 | assert_eq!(delta.added[0].links_json, "[]"); |
| 4851 | } |
| 4852 | |
| 4853 | #[tokio::test] |
| 4854 | async fn attaching_a_preview_puts_the_links_and_keeps_them_locally() { |
| 4855 | let fake = Arc::new(Fake::default()); |
| 4856 | let engine = chat_engine(&fake, small_pages()).await; |
| 4857 | let sent = engine |
| 4858 | .send_message_with_mentions(CHAT, "see https://a.example/x", None, &[]) |
| 4859 | .await |
| 4860 | .unwrap(); |
| 4861 | let preview = engine |
| 4862 | .link_preview_for("https://a.example/x") |
| 4863 | .await |
| 4864 | .unwrap() |
| 4865 | .unwrap(); |
| 4866 | |
| 4867 | engine |
| 4868 | .attach_link_preview(CHAT, &sent.message_id, &preview) |
| 4869 | .await |
| 4870 | .unwrap(); |
| 4871 | |
| 4872 | let put = fake.links_put.lock().unwrap().clone(); |
| 4873 | assert_eq!(put.len(), 1); |
| 4874 | assert_eq!(put[0].0, sent.message_id); |
| 4875 | assert!(put[0].1.contains("\"itemid\":\"0\"")); |
| 4876 | let stored = engine |
| 4877 | .store() |
| 4878 | .messages_by_id(CHAT, std::slice::from_ref(&sent.message_id)) |
| 4879 | .unwrap(); |
| 4880 | assert_eq!(stored[&sent.message_id].links_json, put[0].1); |
| 4881 | } |
| 4882 | |
| 4883 | #[tokio::test] |
| 4884 | async fn link_infos_are_fetched_once_per_url_and_internal_links_never() { |
| 4885 | let fake = Arc::new(Fake::default()); |
| 4886 | let engine = chat_engine(&fake, small_pages()).await; |
| 4887 | for _ in 0..2 { |
| 4888 | engine |
| 4889 | .link_preview_for("https://a.example/x") |
| 4890 | .await |
| 4891 | .unwrap(); |
| 4892 | } |
| 4893 | assert!( |
| 4894 | engine |
| 4895 | .link_preview_for("https://contoso.sharepoint.com/x") |
| 4896 | .await |
| 4897 | .unwrap() |
| 4898 | .is_none() |
| 4899 | ); |
| 4900 | assert_eq!(*fake.link_info_calls.lock().unwrap(), 1); |
| 4901 | } |
| 4902 | |
| 4903 | #[tokio::test] |
| 4904 | async fn schedule_message_resolves_the_inner_thread_id() { |
| 4905 | let fake = Arc::new(Fake::default()); |
| 4906 | *fake.teams.lock().unwrap() = |
| 4907 | vec![serde_json::from_value(json!({"id": "team-1", "displayName": "Squad"})).unwrap()]; |
| 4908 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 4909 | let engine = engine_with(&fake, small_pages()); |
| 4910 | engine.refresh_sidebar().await.unwrap(); |
| 4911 | let send_at = base() + Duration::days(1); |
| 4912 | |
| 4913 | let draft = engine |
| 4914 | .schedule_message(CHAT, None, "<p>a</p>", send_at) |
| 4915 | .await |
| 4916 | .unwrap(); |
| 4917 | assert_eq!(draft.id, "d1"); |
| 4918 | engine |
| 4919 | .schedule_message(CHANNEL, None, "<p>b</p>", send_at) |
| 4920 | .await |
| 4921 | .unwrap(); |
| 4922 | engine |
| 4923 | .schedule_message(CHANNEL, Some("m0030"), "<p>c</p>", send_at) |
| 4924 | .await |
| 4925 | .unwrap(); |
| 4926 | |
| 4927 | let created = fake.scheduled.lock().unwrap().clone(); |
| 4928 | let thread_ids: Vec<&str> = created.iter().map(|entry| entry.0.as_str()).collect(); |
| 4929 | assert_eq!( |
| 4930 | thread_ids, |
| 4931 | [CHAT, CHANNEL, "19:channel@thread.tacv2;messageid=m0030"] |
| 4932 | ); |
| 4933 | assert_eq!(created[0].3, "Me Myself"); |
| 4934 | } |
| 4935 | |
| 4936 | #[tokio::test] |
| 4937 | async fn schedule_message_rejects_notes_and_chat_threads() { |
| 4938 | let fake = Arc::new(Fake::default()); |
| 4939 | let engine = chat_engine(&fake, small_pages()).await; |
| 4940 | let send_at = base(); |
| 4941 | assert!(matches!( |
| 4942 | engine |
| 4943 | .schedule_message(teams_core::NOTES_CHAT_ID, None, "<p>a</p>", send_at) |
| 4944 | .await, |
| 4945 | Err(Error::Unsupported(_)) |
| 4946 | )); |
| 4947 | assert!(matches!( |
| 4948 | engine |
| 4949 | .schedule_message(CHAT, Some("m1"), "<p>a</p>", send_at) |
| 4950 | .await, |
| 4951 | Err(Error::Unsupported(_)) |
| 4952 | )); |
| 4953 | assert!(fake.scheduled.lock().unwrap().is_empty()); |
| 4954 | } |
| 4955 | |
| 4956 | #[tokio::test] |
| 4957 | async fn mark_unread_from_a_message_backs_up_one_millisecond() { |
| 4958 | let fake = Arc::new(Fake::default()); |
| 4959 | let engine = chat_engine(&fake, small_pages()).await; |
| 4960 | let created_at = base() + Duration::minutes(2); |
| 4961 | engine.mark_unread_from(CHAT, created_at).await.unwrap(); |
| 4962 | assert_eq!( |
| 4963 | fake.calls().last().unwrap(), |
| 4964 | &format!( |
| 4965 | "mark_unread {CHAT} {ME} tenant-1 {}", |
| 4966 | created_at.timestamp_millis() - 1 |
| 4967 | ) |
| 4968 | ); |
| 4969 | } |
| 4970 | |
| 4971 | #[tokio::test] |
| 4972 | async fn forward_converts_the_comment_and_fetches_the_target() { |
| 4973 | let fake = Arc::new(Fake::default()); |
| 4974 | let engine = chat_engine(&fake, small_pages()).await; |
| 4975 | fake.set_chat_messages(vec![message(1, 1, "<p>one</p>")]); |
| 4976 | let ids = vec!["m0001".to_owned(), "m0002".to_owned()]; |
| 4977 | let result = engine |
| 4978 | .forward_messages("19:source@thread.v2", CHAT, &ids, "**fyi**") |
| 4979 | .await |
| 4980 | .unwrap(); |
| 4981 | assert_eq!(result.message_id, "99"); |
| 4982 | assert_eq!( |
| 4983 | fake.calls().last().unwrap(), |
| 4984 | &format!( |
| 4985 | "forward 19:source@thread.v2 {CHAT} m0001,m0002 {}", |
| 4986 | teams_core::markdown_to_html("**fyi**") |
| 4987 | ) |
| 4988 | ); |
| 4989 | assert_eq!(engine.open_conversation(CHAT).unwrap().len(), 1); |
| 4990 | engine |
| 4991 | .forward_messages("19:source@thread.v2", CHAT, &ids, "") |
| 4992 | .await |
| 4993 | .unwrap(); |
| 4994 | assert_eq!( |
| 4995 | fake.calls().last().unwrap(), |
| 4996 | &format!("forward 19:source@thread.v2 {CHAT} m0001,m0002 ") |
| 4997 | ); |
| 4998 | } |
| 4999 | |
| 5000 | #[tokio::test] |
| 5001 | async fn save_uses_the_message_id_as_root_in_chats() { |
| 5002 | let fake = Arc::new(Fake::default()); |
| 5003 | let engine = chat_engine(&fake, small_pages()).await; |
| 5004 | engine.set_saved(CHAT, "5", None, true).await.unwrap(); |
| 5005 | assert_eq!( |
| 5006 | fake.calls().last().unwrap(), |
| 5007 | &format!("save {CHAT} 5 5 true") |
| 5008 | ); |
| 5009 | engine |
| 5010 | .set_saved(CHANNEL, "7", Some("3"), false) |
| 5011 | .await |
| 5012 | .unwrap(); |
| 5013 | assert_eq!( |
| 5014 | fake.calls().last().unwrap(), |
| 5015 | &format!("save {CHANNEL} 3 7 false") |
| 5016 | ); |
| 5017 | } |
| 5018 | |
| 5019 | #[tokio::test] |
| 5020 | async fn post_follow_writes_as_the_signed_in_user() { |
| 5021 | let fake = Arc::new(Fake::default()); |
| 5022 | let engine = channel_engine(&fake).await; |
| 5023 | engine.set_post_followed(CHANNEL, "3", false).await.unwrap(); |
| 5024 | assert_eq!( |
| 5025 | fake.calls().last().unwrap(), |
| 5026 | &format!("follow {ME} {CHANNEL} 3 false") |
| 5027 | ); |
| 5028 | } |
| 5029 | |
| 5030 | #[tokio::test] |
| 5031 | async fn pinning_announces_in_chats() { |
| 5032 | let fake = Arc::new(Fake::default()); |
| 5033 | let engine = channel_engine(&fake).await; |
| 5034 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 5035 | engine.refresh_sidebar().await.unwrap(); |
| 5036 | let mut events = engine.subscribe(); |
| 5037 | engine.pin_message(CHAT, "5").await.unwrap(); |
| 5038 | assert_eq!( |
| 5039 | events.try_recv().unwrap(), |
| 5040 | CoreEvent::PinsChanged { |
| 5041 | conversation_id: CHAT.to_owned() |
| 5042 | } |
| 5043 | ); |
| 5044 | engine |
| 5045 | .unpin_message(CHAT, "5", Some("folder-1")) |
| 5046 | .await |
| 5047 | .unwrap(); |
| 5048 | assert_eq!( |
| 5049 | fake.calls().last().unwrap(), |
| 5050 | &format!("unpin {CHAT} 5 Some(\"folder-1\")") |
| 5051 | ); |
| 5052 | } |
| 5053 | |
| 5054 | #[tokio::test] |
| 5055 | async fn channel_pins_use_the_post_pin_routes_of_the_team_thread() { |
| 5056 | let fake = Arc::new(Fake::default()); |
| 5057 | let engine = channel_engine(&fake).await; |
| 5058 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 5059 | let pins = engine.chat_pins(CHANNEL).await.unwrap(); |
| 5060 | assert_eq!(pins[0].message_id, "30"); |
| 5061 | assert_eq!( |
| 5062 | fake.calls().last().unwrap(), |
| 5063 | &format!("channel pins {CHANNEL} {CHANNEL}") |
| 5064 | ); |
| 5065 | let mut events = engine.subscribe(); |
| 5066 | engine.pin_message(CHANNEL, "30").await.unwrap(); |
| 5067 | assert_eq!( |
| 5068 | fake.calls().last().unwrap(), |
| 5069 | &format!("post pin {CHANNEL} {CHANNEL} 30 true") |
| 5070 | ); |
| 5071 | assert_eq!( |
| 5072 | events.try_recv().unwrap(), |
| 5073 | CoreEvent::PinsChanged { |
| 5074 | conversation_id: CHANNEL.to_owned() |
| 5075 | } |
| 5076 | ); |
| 5077 | engine.unpin_message(CHANNEL, "30", None).await.unwrap(); |
| 5078 | assert_eq!( |
| 5079 | fake.calls().last().unwrap(), |
| 5080 | &format!("post pin {CHANNEL} {CHANNEL} 30 false") |
| 5081 | ); |
| 5082 | } |
| 5083 | |
| 5084 | #[tokio::test] |
| 5085 | async fn channel_mentions_follow_the_activity_feed_and_mark_all_as_read() { |
| 5086 | let fake = Arc::new(Fake::default()); |
| 5087 | fake.read_states.lock().unwrap().push(( |
| 5088 | CHANNEL.to_owned(), |
| 5089 | chatsvc::ReadHorizon { |
| 5090 | consumed_until_ms: 5, |
| 5091 | last_message_ms: 9, |
| 5092 | last_message_from: Some("8:orgid:user-ada".to_owned()), |
| 5093 | ..chatsvc::ReadHorizon::default() |
| 5094 | }, |
| 5095 | )); |
| 5096 | let mention = |activity_id: &str, subtype: &str| chatsvc::ActivityItem { |
| 5097 | message_id: activity_id.to_owned(), |
| 5098 | activity_id: activity_id.to_owned(), |
| 5099 | activity_type: "mention".to_owned(), |
| 5100 | activity_subtype: subtype.to_owned(), |
| 5101 | source_thread_id: CHANNEL.to_owned(), |
| 5102 | timestamp_ms: 8, |
| 5103 | version_ms: 8, |
| 5104 | ..chatsvc::ActivityItem::default() |
| 5105 | }; |
| 5106 | fake.activity_feed.lock().unwrap().items = vec![mention("1", "person"), mention("2", "team")]; |
| 5107 | let engine = channel_engine(&fake).await; |
| 5108 | engine.refresh_sidebar().await.unwrap(); |
| 5109 | let mentions = engine.store().sidebar().unwrap().teams[0].channel_mentions(CHANNEL); |
| 5110 | assert_eq!((mentions.personal, mentions.team), (1, 1)); |
| 5111 | |
| 5112 | engine.mark_all_channels_read().await.unwrap(); |
| 5113 | |
| 5114 | assert_eq!(fake.calls().last().unwrap(), "mark all channels read"); |
| 5115 | assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread); |
| 5116 | assert!( |
| 5117 | engine.store().sidebar().unwrap().teams[0] |
| 5118 | .mentions |
| 5119 | .is_empty() |
| 5120 | ); |
| 5121 | engine.refresh_sidebar().await.unwrap(); |
| 5122 | assert!(!engine.store().channel(CHANNEL).unwrap().unwrap().unread); |
| 5123 | assert!( |
| 5124 | engine.store().sidebar().unwrap().teams[0] |
| 5125 | .mentions |
| 5126 | .is_empty() |
| 5127 | ); |
| 5128 | } |
| 5129 | |
| 5130 | #[tokio::test] |
| 5131 | async fn activity_feed_is_stored_and_marked_read_like_teams() { |
| 5132 | let fake = Arc::new(Fake::default()); |
| 5133 | let engine = channel_engine(&fake).await; |
| 5134 | let mut events = engine.subscribe(); |
| 5135 | *fake.activity_feed.lock().unwrap() = chatsvc::ActivitySnapshot { |
| 5136 | items: vec![chatsvc::ActivityItem { |
| 5137 | message_id: "1791368000001".to_owned(), |
| 5138 | activity_type: "reactionInChat".to_owned(), |
| 5139 | source_thread_id: CHAT.to_owned(), |
| 5140 | timestamp_ms: 20, |
| 5141 | version_ms: 20, |
| 5142 | ..chatsvc::ActivityItem::default() |
| 5143 | }], |
| 5144 | horizons: chatsvc::ActivityHorizons { |
| 5145 | seen_ms: 10, |
| 5146 | bookmark_ms: 5, |
| 5147 | }, |
| 5148 | }; |
| 5149 | engine.refresh_sidebar().await.unwrap(); |
| 5150 | assert!(std::iter::from_fn(|| events.try_recv().ok()).any(|event| event == CoreEvent::ActivityChanged)); |
| 5151 | let stored = teams_core::stored_activity_feed(engine.store()).unwrap(); |
| 5152 | assert!(stored.counts_for_bell(&stored.items[0])); |
| 5153 | |
| 5154 | engine.mark_activity_read("1791368000001").await.unwrap(); |
| 5155 | assert_eq!(fake.calls().last().unwrap(), "activity read 1791368000001"); |
| 5156 | let stored = teams_core::stored_activity_feed(engine.store()).unwrap(); |
| 5157 | assert!(stored.is_read(&stored.items[0])); |
| 5158 | engine.refresh_sidebar().await.unwrap(); |
| 5159 | let stored = teams_core::stored_activity_feed(engine.store()).unwrap(); |
| 5160 | assert!(stored.is_read(&stored.items[0]), "a fetch from before the PUT keeps the local mark"); |
| 5161 | |
| 5162 | stored_feed_unread(&fake, &engine).await; |
| 5163 | engine.mark_all_activity_read().await.unwrap(); |
| 5164 | assert_eq!(fake.calls().last().unwrap(), "activity all read"); |
| 5165 | let stored = teams_core::stored_activity_feed(engine.store()).unwrap(); |
| 5166 | assert!(stored.is_read(&stored.items[0])); |
| 5167 | } |
| 5168 | |
| 5169 | async fn stored_feed_unread(fake: &Arc<Fake>, engine: &SyncEngine<Handle>) { |
| 5170 | fake.activity_feed.lock().unwrap().items[0].read_flag = true; |
| 5171 | engine.refresh_sidebar().await.unwrap(); |
| 5172 | fake.activity_feed.lock().unwrap().items[0].read_flag = false; |
| 5173 | engine.refresh_sidebar().await.unwrap(); |
| 5174 | let stored = teams_core::stored_activity_feed(engine.store()).unwrap(); |
| 5175 | assert!(!stored.is_read(&stored.items[0])); |
| 5176 | } |
| 5177 | |
| 5178 | #[tokio::test] |
| 5179 | async fn pin_events_become_core_events() { |
| 5180 | let fake = Arc::new(Fake::default()); |
| 5181 | let engine = chat_engine(&fake, small_pages()).await; |
| 5182 | let mut events = engine.subscribe(); |
| 5183 | let mut event = read_event(Some(CHAT)); |
| 5184 | engine.handle_pin_event(&event); |
| 5185 | assert!(events.try_recv().is_err()); |
| 5186 | event.kind = chatsvc::EventKind::PinsChanged; |
| 5187 | engine.handle_pin_event(&event); |
| 5188 | assert_eq!( |
| 5189 | events.try_recv().unwrap(), |
| 5190 | CoreEvent::PinsChanged { |
| 5191 | conversation_id: CHAT.to_owned() |
| 5192 | } |
| 5193 | ); |
| 5194 | } |
| 5195 | |
| 5196 | #[tokio::test] |
| 5197 | async fn message_links_resolve_chat_notes_and_channel() { |
| 5198 | let fake = Arc::new(Fake::default()); |
| 5199 | let engine = channel_engine(&fake).await; |
| 5200 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 5201 | engine.refresh_sidebar().await.unwrap(); |
| 5202 | assert_eq!( |
| 5203 | engine.message_link(CHAT, "5").await.unwrap(), |
| 5204 | teams_core::chat_message_link(CHAT, "5", None) |
| 5205 | ); |
| 5206 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 5207 | let root = engine.open_conversation(CHANNEL).unwrap()[0].clone(); |
| 5208 | assert_eq!( |
| 5209 | engine |
| 5210 | .message_link(CHANNEL, &root.message_id) |
| 5211 | .await |
| 5212 | .unwrap(), |
| 5213 | teams_core::channel_message_link(&teams_core::ChannelLinkInput { |
| 5214 | tenant_id: "tenant-1".into(), |
| 5215 | group_id: "team-1".into(), |
| 5216 | channel_id: CHANNEL.into(), |
| 5217 | team_name: "Squad".into(), |
| 5218 | channel_name: "General".into(), |
| 5219 | root_id: root.message_id.clone(), |
| 5220 | message_id: root.message_id.clone(), |
| 5221 | created_ms: root.created_at.timestamp_millis(), |
| 5222 | }) |
| 5223 | ); |
| 5224 | } |
| 5225 | |
| 5226 | #[tokio::test] |
| 5227 | async fn chat_translation_goes_out_in_batches_of_thirty() { |
| 5228 | let fake = Arc::new(Fake::default()); |
| 5229 | let engine = chat_engine(&fake, small_pages()).await; |
| 5230 | fake.set_chat_messages(vec![message(1, 1, "<p>eins</p>")]); |
| 5231 | engine.fetch_newer(CHAT).await.unwrap(); |
| 5232 | let ids: Vec<String> = (0..31).map(|index| format!("m{index:04}")).collect(); |
| 5233 | let translations = engine |
| 5234 | .translate_messages(CHAT, &ids, "en", &teams_core::TranslationTrigger::OnDemand) |
| 5235 | .await |
| 5236 | .unwrap(); |
| 5237 | assert_eq!(translations.len(), 31); |
| 5238 | assert_eq!( |
| 5239 | *fake.translate_calls.lock().unwrap(), |
| 5240 | [format!("chat {CHAT} en 30"), format!("chat {CHAT} en 1")] |
| 5241 | ); |
| 5242 | } |
| 5243 | |
| 5244 | #[tokio::test] |
| 5245 | async fn channel_translation_groups_messages_by_thread_root() { |
| 5246 | let fake = Arc::new(Fake::default()); |
| 5247 | let engine = channel_engine(&fake).await; |
| 5248 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 5249 | let root_id = engine.open_conversation(CHANNEL).unwrap()[0] |
| 5250 | .message_id |
| 5251 | .clone(); |
| 5252 | let translations = engine |
| 5253 | .translate_messages( |
| 5254 | CHANNEL, |
| 5255 | std::slice::from_ref(&root_id), |
| 5256 | "fr", |
| 5257 | &teams_core::TranslationTrigger::OnDemand, |
| 5258 | ) |
| 5259 | .await |
| 5260 | .unwrap(); |
| 5261 | assert_eq!(translations.len(), 1); |
| 5262 | assert_eq!( |
| 5263 | *fake.translate_calls.lock().unwrap(), |
| 5264 | [format!("channel team-1 {CHANNEL} {root_id} fr 1")] |
| 5265 | ); |
| 5266 | } |
| 5267 | |
| 5268 | #[tokio::test] |
| 5269 | async fn translating_in_an_unknown_conversation_fails() { |
| 5270 | let fake = Arc::new(Fake::default()); |
| 5271 | let engine = chat_engine(&fake, small_pages()).await; |
| 5272 | let outcome = engine |
| 5273 | .translate_messages( |
| 5274 | "19:nope@thread.v2", |
| 5275 | &["m1".to_owned()], |
| 5276 | "en", |
| 5277 | &teams_core::TranslationTrigger::OnDemand, |
| 5278 | ) |
| 5279 | .await; |
| 5280 | assert!(matches!( |
| 5281 | outcome, |
| 5282 | Err(teams_core::Error::UnknownConversation(_)) |
| 5283 | )); |
| 5284 | } |
| 5285 | |
| 5286 | #[tokio::test] |
| 5287 | async fn load_window_ingests_found_messages_oldest_first_and_keeps_cursors() { |
| 5288 | let fake = Arc::new(Fake::default()); |
| 5289 | let engine = chat_engine(&fake, small_pages()).await; |
| 5290 | fake.set_chat_messages(vec![message(3, 3, "<p>c</p>"), message(1, 1, "<p>a</p>")]); |
| 5291 | *fake.window_answer.lock().unwrap() = Some(chatsvc::MessageWindow { |
| 5292 | message_ids: vec!["m0003".into(), "m0002".into(), "m0001".into()], |
| 5293 | older_cursor: Some("100".into()), |
| 5294 | newer_cursor: None, |
| 5295 | }); |
| 5296 | |
| 5297 | let page = engine.load_window(CHAT, "m0003").await.unwrap(); |
| 5298 | |
| 5299 | let ids: Vec<&str> = page |
| 5300 | .records |
| 5301 | .iter() |
| 5302 | .map(|record| record.message_id.as_str()) |
| 5303 | .collect(); |
| 5304 | assert_eq!(ids, ["m0001", "m0003"]); |
| 5305 | assert_eq!(page.oldest, Some(base() + Duration::minutes(1))); |
| 5306 | assert_eq!(page.newest, Some(base() + Duration::minutes(3))); |
| 5307 | assert_eq!(page.older_cursor.as_deref(), Some("100")); |
| 5308 | assert_eq!(page.newer_cursor, None); |
| 5309 | assert_eq!(engine.store().message_count(CHAT).unwrap(), 2); |
| 5310 | assert_eq!( |
| 5311 | *fake.window_requests.lock().unwrap(), |
| 5312 | [("m0003".to_owned(), chatsvc::WindowDirection::Bidirectional)] |
| 5313 | ); |
| 5314 | } |
| 5315 | |
| 5316 | #[tokio::test] |
| 5317 | async fn fetch_chat_message_does_not_store_the_message() { |
| 5318 | let fake = Arc::new(Fake::default()); |
| 5319 | let engine = chat_engine(&fake, small_pages()).await; |
| 5320 | fake.set_chat_messages(vec![message(7, 7, "<p>pinned</p>")]); |
| 5321 | |
| 5322 | let record = engine |
| 5323 | .fetch_chat_message(CHAT, "m0007") |
| 5324 | .await |
| 5325 | .unwrap() |
| 5326 | .unwrap(); |
| 5327 | |
| 5328 | assert_eq!(record.message_id, "m0007"); |
| 5329 | assert_eq!(engine.store().message_count(CHAT).unwrap(), 0); |
| 5330 | } |
| 5331 | |
| 5332 | fn forwarded_message(id: &str, minute: i64) -> Message { |
| 5333 | let content = json!({ |
| 5334 | "originalMessageId": "orig-1", |
| 5335 | "originalMessageContent": "<p>original words</p>", |
| 5336 | "originalConversationId": "19:origin@thread.v2", |
| 5337 | "originalSentDateTime": base().to_rfc3339(), |
| 5338 | "originalMessageSender": {"user": {"id": "user-cleo", "displayName": null}}, |
| 5339 | }); |
| 5340 | serde_json::from_value(json!({ |
| 5341 | "id": id, |
| 5342 | "messageType": "message", |
| 5343 | "createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(), |
| 5344 | "from": {"user": {"id": ME, "displayName": null}}, |
| 5345 | "body": {"contentType": "html", "content": "<attachment id=\"orig-1\"></attachment>"}, |
| 5346 | "attachments": [{ |
| 5347 | "id": "orig-1", |
| 5348 | "contentType": "forwardedMessageReference", |
| 5349 | "content": content.to_string(), |
| 5350 | }], |
| 5351 | })) |
| 5352 | .unwrap() |
| 5353 | } |
| 5354 | |
| 5355 | #[tokio::test] |
| 5356 | async fn a_forward_cached_without_its_content_is_read_again_once() { |
| 5357 | let fake = Arc::new(Fake::default()); |
| 5358 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 5359 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 5360 | let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages()); |
| 5361 | engine.refresh_sidebar().await.unwrap(); |
| 5362 | let mut messages = numbered(11); |
| 5363 | messages.push(forwarded_message("m0000", 0)); |
| 5364 | fake.set_chat_messages(messages); |
| 5365 | let mut stale = teams_core::message_record(CHAT, &forwarded_message("m0000", 0)).unwrap(); |
| 5366 | stale.attachments_json = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"orig-1","content":null}]"#.to_owned(); |
| 5367 | store.upsert_messages(&[stale]).unwrap(); |
| 5368 | |
| 5369 | engine.fetch_newer(CHAT).await.unwrap(); |
| 5370 | |
| 5371 | let healed = store |
| 5372 | .messages_by_id(CHAT, &["m0000".to_owned()]) |
| 5373 | .unwrap() |
| 5374 | .remove("m0000") |
| 5375 | .unwrap(); |
| 5376 | assert_eq!(teams_core::forwarded_texts(&healed), ["original words"]); |
| 5377 | let reads = |fake: &Fake| { |
| 5378 | fake.calls() |
| 5379 | .iter() |
| 5380 | .filter(|call| *call == "chat_message m0000") |
| 5381 | .count() |
| 5382 | }; |
| 5383 | assert_eq!(reads(&fake), 1); |
| 5384 | engine.fetch_newer(CHAT).await.unwrap(); |
| 5385 | assert_eq!(reads(&fake), 1); |
| 5386 | } |
| 5387 | |
| 5388 | #[tokio::test] |
| 5389 | async fn server_search_is_anchored_to_my_user_and_tenant() { |
| 5390 | let fake = Arc::new(Fake::default()); |
| 5391 | let engine = chat_engine(&fake, SyncConfig::default()).await; |
| 5392 | let search_session = substrate_search::SearchSession::new(); |
| 5393 | engine |
| 5394 | .server_suggestions(&search_session, "ada") |
| 5395 | .await |
| 5396 | .unwrap(); |
| 5397 | engine |
| 5398 | .server_suggestions(&search_session, "adam") |
| 5399 | .await |
| 5400 | .unwrap(); |
| 5401 | let identities = fake.search_identities.lock().unwrap().clone(); |
| 5402 | let expected = substrate_search::SearchIdentity { |
| 5403 | user_id: ME.to_owned(), |
| 5404 | tenant_id: "tenant-1".to_owned(), |
| 5405 | }; |
| 5406 | assert_eq!(identities, [expected.clone(), expected]); |
| 5407 | } |
| 5408 | |
| 5409 | const STALE_FORWARD: &str = r#"[{"content_type":"forwardedMessageReference","name":null,"url":null,"text":null,"size":null,"quote":null,"id":"orig-1","content":null}]"#; |
| 5410 | |
| 5411 | fn stale_forward(conversation_id: &str, message_id: &str, minute: i64) -> store::MessageRecord { |
| 5412 | let mut stale = |
| 5413 | teams_core::message_record(conversation_id, &forwarded_message(message_id, minute)) |
| 5414 | .unwrap(); |
| 5415 | stale.attachments_json = STALE_FORWARD.to_owned(); |
| 5416 | stale |
| 5417 | } |
| 5418 | |
| 5419 | fn forwarded_message_without_original(id: &str, minute: i64) -> Message { |
| 5420 | let mut message = forwarded_message(id, minute); |
| 5421 | message.attachments[0].content = None; |
| 5422 | message |
| 5423 | } |
| 5424 | |
| 5425 | fn forward_state( |
| 5426 | store: &Store, |
| 5427 | conversation_id: &str, |
| 5428 | message_id: &str, |
| 5429 | ) -> teams_core::ForwardState { |
| 5430 | let record = store |
| 5431 | .messages_by_id(conversation_id, &[message_id.to_owned()]) |
| 5432 | .unwrap() |
| 5433 | .remove(message_id) |
| 5434 | .unwrap(); |
| 5435 | teams_core::forwards(&record)[0].state |
| 5436 | } |
| 5437 | |
| 5438 | #[tokio::test] |
| 5439 | async fn a_forward_graph_returns_without_its_original_is_not_read_again() { |
| 5440 | let fake = Arc::new(Fake::default()); |
| 5441 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 5442 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 5443 | let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages()); |
| 5444 | engine.refresh_sidebar().await.unwrap(); |
| 5445 | let mut messages = numbered(11); |
| 5446 | messages.push(forwarded_message_without_original("m0000", 0)); |
| 5447 | fake.set_chat_messages(messages); |
| 5448 | store |
| 5449 | .upsert_messages(&[stale_forward(CHAT, "m0000", 0)]) |
| 5450 | .unwrap(); |
| 5451 | assert_eq!( |
| 5452 | forward_state(&store, CHAT, "m0000"), |
| 5453 | teams_core::ForwardState::Loading |
| 5454 | ); |
| 5455 | |
| 5456 | engine.fetch_newer(CHAT).await.unwrap(); |
| 5457 | |
| 5458 | assert_eq!( |
| 5459 | forward_state(&store, CHAT, "m0000"), |
| 5460 | teams_core::ForwardState::Unavailable |
| 5461 | ); |
| 5462 | let next_session = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages()); |
| 5463 | next_session.fetch_newer(CHAT).await.unwrap(); |
| 5464 | let reads = fake |
| 5465 | .calls() |
| 5466 | .iter() |
| 5467 | .filter(|call| *call == "chat_message m0000") |
| 5468 | .count(); |
| 5469 | assert_eq!(reads, 1); |
| 5470 | } |
| 5471 | |
| 5472 | #[tokio::test] |
| 5473 | async fn the_background_heal_reads_the_newest_chat_first_and_skips_healthy_chats() { |
| 5474 | const OLDER: &str = "19:older@thread.v2"; |
| 5475 | const HEALTHY: &str = "19:healthy@thread.v2"; |
| 5476 | let fake = Arc::new(Fake::default()); |
| 5477 | *fake.chats.lock().unwrap() = vec![ |
| 5478 | chat(OLDER, Some("Older"), 2, 2, ME, false), |
| 5479 | chat(CHAT, Some("Newer"), 9, 9, ME, false), |
| 5480 | chat(HEALTHY, Some("Healthy"), 12, 12, ME, false), |
| 5481 | ]; |
| 5482 | let store = Arc::new(Store::open_in_memory().unwrap()); |
| 5483 | let engine = SyncEngine::with_config(Handle(fake.clone()), store.clone(), small_pages()); |
| 5484 | engine.refresh_sidebar().await.unwrap(); |
| 5485 | fake.set_chat_messages(vec![ |
| 5486 | forwarded_message("f-older", 1), |
| 5487 | forwarded_message("f-newer", 8), |
| 5488 | ]); |
| 5489 | let healthy = teams_core::message_record(HEALTHY, &forwarded_message("f-healthy", 11)).unwrap(); |
| 5490 | store |
| 5491 | .upsert_messages(&[ |
| 5492 | stale_forward(OLDER, "f-older", 1), |
| 5493 | stale_forward(CHAT, "f-newer", 8), |
| 5494 | healthy, |
| 5495 | ]) |
| 5496 | .unwrap(); |
| 5497 | let mut events = engine.subscribe(); |
| 5498 | |
| 5499 | engine.heal_all_forwards(std::time::Duration::ZERO).await; |
| 5500 | |
| 5501 | let reads: Vec<String> = fake |
| 5502 | .calls() |
| 5503 | .into_iter() |
| 5504 | .filter(|call| call.starts_with("chat_message ")) |
| 5505 | .collect(); |
| 5506 | assert_eq!(reads, ["chat_message f-newer", "chat_message f-older"]); |
| 5507 | assert_eq!( |
| 5508 | forward_state(&store, OLDER, "f-older"), |
| 5509 | teams_core::ForwardState::Ready |
| 5510 | ); |
| 5511 | let mut changed = Vec::new(); |
| 5512 | while let Ok(event) = events.try_recv() { |
| 5513 | if let CoreEvent::MessagesChanged { conversation_id } = event { |
| 5514 | changed.push(conversation_id); |
| 5515 | } |
| 5516 | } |
| 5517 | assert_eq!(changed, [CHAT, OLDER]); |
| 5518 | } |
| 5519 | |
| 5520 | fn own_note(id: u32, minute: i64, body: &str) -> Message { |
| 5521 | serde_json::from_value(json!({ |
| 5522 | "id": format!("m{id:04}"), |
| 5523 | "messageType": "message", |
| 5524 | "createdDateTime": (base() + Duration::minutes(minute)).to_rfc3339(), |
| 5525 | "from": {"user": {"id": ME, "displayName": "Me Myself"}}, |
| 5526 | "body": {"contentType": "html", "content": body}, |
| 5527 | })) |
| 5528 | .unwrap() |
| 5529 | } |
| 5530 | |
| 5531 | fn list_notes_chat(fake: &Fake, last_minute: i64) { |
| 5532 | let last_message_ms = (base() + Duration::minutes(last_minute)).timestamp_millis(); |
| 5533 | *fake.read_states.lock().unwrap() = vec![( |
| 5534 | NOTES_CHAT_ID.to_owned(), |
| 5535 | chatsvc::ReadHorizon { |
| 5536 | consumed_until_ms: last_message_ms, |
| 5537 | last_message_ms, |
| 5538 | last_message_from: Some(format!("8:orgid:{ME}")), |
| 5539 | ..chatsvc::ReadHorizon::default() |
| 5540 | }, |
| 5541 | )]; |
| 5542 | } |
| 5543 | |
| 5544 | #[tokio::test] |
| 5545 | async fn the_notes_chat_comes_from_chatsvc_with_its_newest_message_sorted_by_time() { |
| 5546 | let fake = Arc::new(Fake::default()); |
| 5547 | *fake.chats.lock().unwrap() = vec![ |
| 5548 | chat("19:old@thread.v2", Some("Old"), 5, 5, "user-ada", false), |
| 5549 | chat("19:new@thread.v2", Some("New"), 50, 50, "user-ada", false), |
| 5550 | ]; |
| 5551 | list_notes_chat(&fake, 20); |
| 5552 | fake.set_chat_messages(vec![ |
| 5553 | own_note(1, 10, "<p>first</p>"), |
| 5554 | own_note(2, 20, "<p>plan</p>"), |
| 5555 | ]); |
| 5556 | let engine = engine_with(&fake, small_pages()); |
| 5557 | |
| 5558 | engine.refresh_sidebar().await.unwrap(); |
| 5559 | |
| 5560 | let sidebar = engine.sidebar().unwrap(); |
| 5561 | let order: Vec<&str> = sidebar.chats.iter().map(|chat| chat.id.as_str()).collect(); |
| 5562 | assert_eq!( |
| 5563 | order, |
| 5564 | ["19:new@thread.v2", NOTES_CHAT_ID, "19:old@thread.v2"] |
| 5565 | ); |
| 5566 | let notes = &sidebar.chats[1]; |
| 5567 | assert_eq!(notes.title, "Me Myself (You)"); |
| 5568 | assert_eq!(notes.kind, "oneOnOne"); |
| 5569 | assert_eq!(notes.last_message_preview.as_deref(), Some("plan")); |
| 5570 | assert_eq!(notes.last_message_sender_id.as_deref(), Some(ME)); |
| 5571 | assert!(!notes.unread); |
| 5572 | assert_eq!(notes.members.len(), 1); |
| 5573 | assert_eq!(notes.members[0].user_id.as_deref(), Some(ME)); |
| 5574 | assert_eq!(engine.open_conversation(NOTES_CHAT_ID).unwrap().len(), 2); |
| 5575 | assert_eq!(*fake.single_chat_calls.lock().unwrap(), 0); |
| 5576 | |
| 5577 | let message_reads = *fake.chat_calls.lock().unwrap(); |
| 5578 | engine.refresh_sidebar_full().await.unwrap(); |
| 5579 | let notes = engine.store().chat(NOTES_CHAT_ID).unwrap().unwrap(); |
| 5580 | assert_eq!(notes.last_message_preview.as_deref(), Some("plan")); |
| 5581 | assert_eq!(*fake.chat_calls.lock().unwrap(), message_reads); |
| 5582 | } |
| 5583 | |
| 5584 | #[tokio::test] |
| 5585 | async fn a_new_note_refreshes_the_line_and_an_unlisted_notes_chat_leaves_the_sidebar() { |
| 5586 | let fake = Arc::new(Fake::default()); |
| 5587 | *fake.notes_placeholder.lock().unwrap() = true; |
| 5588 | list_notes_chat(&fake, 20); |
| 5589 | fake.set_chat_messages(vec![own_note(1, 20, "<p>plan</p>")]); |
| 5590 | let engine = engine_with(&fake, small_pages()); |
| 5591 | engine.refresh_sidebar().await.unwrap(); |
| 5592 | |
| 5593 | list_notes_chat(&fake, 30); |
| 5594 | fake.set_chat_messages(vec![ |
| 5595 | own_note(1, 20, "<p>plan</p>"), |
| 5596 | own_note(2, 30, "<p>later</p>"), |
| 5597 | ]); |
| 5598 | engine.refresh_sidebar().await.unwrap(); |
| 5599 | let notes = engine.store().chat(NOTES_CHAT_ID).unwrap().unwrap(); |
| 5600 | assert_eq!(notes.last_message_preview.as_deref(), Some("later")); |
| 5601 | |
| 5602 | fake.read_states.lock().unwrap().clear(); |
| 5603 | engine.refresh_sidebar().await.unwrap(); |
| 5604 | let placeholder = engine.store().chat(NOTES_CHAT_ID).unwrap().unwrap(); |
| 5605 | assert_eq!(placeholder.title, "Me Myself (You)"); |
| 5606 | assert_eq!(placeholder.last_message_at, None); |
| 5607 | assert_eq!(placeholder.last_message_preview, None); |
| 5608 | |
| 5609 | fake.hidden_states |
| 5610 | .lock() |
| 5611 | .unwrap() |
| 5612 | .push((NOTES_CHAT_ID.to_owned(), true)); |
| 5613 | engine.refresh_sidebar().await.unwrap(); |
| 5614 | assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_none()); |
| 5615 | } |
| 5616 | |
| 5617 | #[tokio::test] |
| 5618 | async fn marking_an_own_note_unread_sets_the_chatsvc_bookmark_and_reading_clears_it() { |
| 5619 | let fake = Arc::new(Fake::default()); |
| 5620 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 5621 | list_notes_chat(&fake, 20); |
| 5622 | fake.set_chat_messages(vec![own_note(1, 20, "<p>plan</p>")]); |
| 5623 | let engine = engine_with(&fake, small_pages()); |
| 5624 | engine.refresh_sidebar().await.unwrap(); |
| 5625 | |
| 5626 | engine.mark_unread(NOTES_CHAT_ID).await.unwrap(); |
| 5627 | engine.mark_read(NOTES_CHAT_ID).await.unwrap(); |
| 5628 | |
| 5629 | let arrived_ms = (base() + Duration::minutes(20)).timestamp_millis(); |
| 5630 | let calls = fake.calls(); |
| 5631 | let bookmarks: Vec<&String> = calls |
| 5632 | .iter() |
| 5633 | .filter(|call| call.starts_with("read bookmark ")) |
| 5634 | .collect(); |
| 5635 | assert_eq!(bookmarks.len(), 2, "{calls:?}"); |
| 5636 | let marked = bookmarks[0].strip_prefix("read bookmark 48:notes ").unwrap(); |
| 5637 | let fields: Vec<&str> = marked.split(';').collect(); |
| 5638 | assert_eq!(fields[0], (arrived_ms - 1).to_string()); |
| 5639 | assert_eq!(fields[2], "m0001"); |
| 5640 | let cleared = bookmarks[1].strip_prefix("read bookmark 48:notes ").unwrap(); |
| 5641 | assert!(cleared.starts_with("0;") && cleared.ends_with(";0"), "{cleared}"); |
| 5642 | assert!(!calls.iter().any(|call| call.starts_with("mark_unread")), "{calls:?}"); |
| 5643 | } |
| 5644 | |
| 5645 | #[tokio::test] |
| 5646 | async fn hiding_the_notes_chat_writes_the_chatsvc_hide_time_and_undo_clears_it() { |
| 5647 | let fake = Arc::new(Fake::default()); |
| 5648 | list_notes_chat(&fake, 20); |
| 5649 | fake.set_chat_messages(vec![own_note(1, 20, "<p>plan</p>")]); |
| 5650 | let engine = engine_with(&fake, small_pages()); |
| 5651 | engine.refresh_sidebar().await.unwrap(); |
| 5652 | |
| 5653 | engine.hide_chat(NOTES_CHAT_ID).await.unwrap(); |
| 5654 | assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_none()); |
| 5655 | engine.unhide_chat(NOTES_CHAT_ID).await.unwrap(); |
| 5656 | |
| 5657 | let calls = fake.calls(); |
| 5658 | let hides: Vec<&String> = calls |
| 5659 | .iter() |
| 5660 | .filter(|call| call.starts_with("hidden at ") || call.starts_with("hide")) |
| 5661 | .collect(); |
| 5662 | assert_eq!( |
| 5663 | hides, |
| 5664 | ["hidden at 48:notes now", "hidden at 48:notes none"], |
| 5665 | "{calls:?}" |
| 5666 | ); |
| 5667 | assert!(engine.store().chat(NOTES_CHAT_ID).unwrap().is_some()); |
| 5668 | } |
| 5669 | |
| 5670 | #[tokio::test] |
| 5671 | async fn marking_the_notes_chat_read_takes_the_tenant_from_another_chat() { |
| 5672 | let fake = Arc::new(Fake::default()); |
| 5673 | *fake.chats.lock().unwrap() = vec![chat(CHAT, Some("Planning"), 5, 5, ME, false)]; |
| 5674 | list_notes_chat(&fake, 20); |
| 5675 | fake.set_chat_messages(vec![own_note(1, 20, "<p>plan</p>")]); |
| 5676 | let engine = engine_with(&fake, small_pages()); |
| 5677 | engine.refresh_sidebar().await.unwrap(); |
| 5678 | |
| 5679 | engine.mark_read(NOTES_CHAT_ID).await.unwrap(); |
| 5680 | |
| 5681 | let calls = fake.calls(); |
| 5682 | assert!( |
| 5683 | calls.contains(&format!("mark_read {NOTES_CHAT_ID} {ME} tenant-1")), |
| 5684 | "{calls:?}" |
| 5685 | ); |
| 5686 | let member_requests = fake.member_requests.lock().unwrap(); |
| 5687 | assert!( |
| 5688 | !member_requests |
| 5689 | .iter() |
| 5690 | .any(|chat_id| chat_id == NOTES_CHAT_ID) |
| 5691 | ); |
| 5692 | } |
| 5693 | |
| 5694 | #[tokio::test] |
| 5695 | async fn a_quoted_chat_reply_is_written_through_chatsvc_in_the_teams_shape() { |
| 5696 | let fake = Arc::new(Fake::default()); |
| 5697 | fake.set_chat_messages(numbered(2)); |
| 5698 | let engine = chat_engine(&fake, small_pages()).await; |
| 5699 | engine.fetch_newer(CHAT).await.unwrap(); |
| 5700 | let extras = MessageExtras { |
| 5701 | importance: Some("high"), |
| 5702 | ..MessageExtras::default() |
| 5703 | }; |
| 5704 | let sent = engine |
| 5705 | .reply_to_with_extras( |
| 5706 | CHAT, |
| 5707 | "m0001", |
| 5708 | "<p>thanks @Ada Example</p>", |
| 5709 | &[MentionInput::user("user-ada", "Ada Example")], |
| 5710 | &extras, |
| 5711 | ) |
| 5712 | .await |
| 5713 | .unwrap(); |
| 5714 | let (conversation_id, html, display_name, properties) = |
| 5715 | fake.chatsvc_posts.lock().unwrap().last().cloned().unwrap(); |
| 5716 | assert_eq!(conversation_id, CHAT); |
| 5717 | assert_eq!(display_name, "Me Myself"); |
| 5718 | let time = (base() + Duration::minutes(1)).timestamp_millis(); |
| 5719 | let quote = format!( |
| 5720 | "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m0001\"><strong itemprop=\"mri\" itemid=\"8:orgid:user-ada\">Ada Example</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">n1</p></blockquote>" |
| 5721 | ); |
| 5722 | assert_eq!( |
| 5723 | html, |
| 5724 | format!( |
| 5725 | "{quote}<p>thanks <span itemscope=\"\" itemtype=\"http://schema.skype.com/Mention\" itemid=\"0\">Ada Example</span></p>" |
| 5726 | ) |
| 5727 | ); |
| 5728 | let mentions = json!([{ |
| 5729 | "@type": "http://schema.skype.com/Mention", |
| 5730 | "itemid": "0", |
| 5731 | "mri": "8:orgid:user-ada", |
| 5732 | "mentionType": "person", |
| 5733 | "displayName": "Ada Example", |
| 5734 | }]); |
| 5735 | let quoted = json!([{"messageId": "m0001", "sender": "8:orgid:user-ada", "time": time}]); |
| 5736 | assert_eq!( |
| 5737 | properties, |
| 5738 | json!({ |
| 5739 | "importance": "high", |
| 5740 | "links": "[]", |
| 5741 | "mentions": mentions.to_string(), |
| 5742 | "onbehalfof": null, |
| 5743 | "files": "[]", |
| 5744 | "qtdMsgs": quoted.to_string(), |
| 5745 | "formatVariant": "TEAMS", |
| 5746 | }) |
| 5747 | ); |
| 5748 | assert_eq!(sent.message_id, "1727203440000"); |
| 5749 | assert_eq!(sent.reply_to_id, None); |
| 5750 | assert_eq!(sent.importance, store::MessageImportance::High); |
| 5751 | assert!(sent.body_html.starts_with("e)); |
| 5752 | assert!( |
| 5753 | !fake |
| 5754 | .calls() |
| 5755 | .iter() |
| 5756 | .any(|call| call.starts_with("quote_reply")) |
| 5757 | ); |
| 5758 | } |
| 5759 | |
| 5760 | #[tokio::test] |
| 5761 | async fn a_quoted_chat_reply_with_an_image_stays_on_graph() { |
| 5762 | let fake = Arc::new(Fake::default()); |
| 5763 | fake.set_chat_messages(numbered(2)); |
| 5764 | let engine = chat_engine(&fake, small_pages()).await; |
| 5765 | engine.fetch_newer(CHAT).await.unwrap(); |
| 5766 | let extras = MessageExtras { |
| 5767 | images: vec![HostedImage { |
| 5768 | content_type: "image/png".into(), |
| 5769 | bytes: Arc::new(vec![9]), |
| 5770 | }], |
| 5771 | ..MessageExtras::default() |
| 5772 | }; |
| 5773 | engine |
| 5774 | .reply_to_with_extras(CHAT, "m0001", "look", &[], &extras) |
| 5775 | .await |
| 5776 | .unwrap(); |
| 5777 | assert!(fake.chatsvc_posts.lock().unwrap().is_empty()); |
| 5778 | assert!( |
| 5779 | fake.calls() |
| 5780 | .contains(&format!("quote_reply {CHAT} m0001 look")) |
| 5781 | ); |
| 5782 | } |
| 5783 | |
| 5784 | #[tokio::test] |
| 5785 | async fn a_quoted_reply_to_an_unknown_message_stays_on_graph() { |
| 5786 | let fake = Arc::new(Fake::default()); |
| 5787 | fake.set_chat_messages(numbered(2)); |
| 5788 | let engine = chat_engine(&fake, small_pages()).await; |
| 5789 | engine.fetch_newer(CHAT).await.unwrap(); |
| 5790 | engine.reply_to(CHAT, "m7777", "hi").await.unwrap(); |
| 5791 | assert!(fake.chatsvc_posts.lock().unwrap().is_empty()); |
| 5792 | assert!( |
| 5793 | fake.calls() |
| 5794 | .contains(&format!("quote_reply {CHAT} m7777 hi")) |
| 5795 | ); |
| 5796 | } |
| 5797 | |
| 5798 | #[tokio::test] |
| 5799 | async fn a_quoted_channel_reply_is_written_through_chatsvc_in_the_teams_quote_shape() { |
| 5800 | let fake = Arc::new(Fake::default()); |
| 5801 | let engine = channel_engine(&fake).await; |
| 5802 | engine.fetch_newer(CHANNEL).await.unwrap(); |
| 5803 | let sent = engine |
| 5804 | .reply_to_with_mentions(CHANNEL, "m0030", "answer", &[]) |
| 5805 | .await |
| 5806 | .unwrap(); |
| 5807 | assert!(!fake.calls().contains(&"reply to m0030".to_owned())); |
| 5808 | let (conversation_id, html, display_name, properties) = |
| 5809 | fake.chatsvc_posts.lock().unwrap().last().cloned().unwrap(); |
| 5810 | assert_eq!(conversation_id, format!("{CHANNEL};messageid=m0030")); |
| 5811 | assert_eq!(display_name, "Me Myself"); |
| 5812 | let time = (base() + Duration::minutes(30)).timestamp_millis(); |
| 5813 | let quote = format!( |
| 5814 | "<blockquote itemscope=\"\" itemtype=\"http://schema.skype.com/Reply\" itemid=\"m0030\"><strong itemprop=\"mri\" itemid=\"8:orgid:user-ada\">Ada Example</strong><span itemprop=\"time\" itemid=\"{time}\"></span><p itemprop=\"preview\">root</p></blockquote>" |
| 5815 | ); |
| 5816 | assert_eq!(html, format!("{quote}answer")); |
| 5817 | let quoted: serde_json::Value = |
| 5818 | serde_json::from_str(properties["qtdMsgs"].as_str().unwrap()).unwrap(); |
| 5819 | assert_eq!( |
| 5820 | quoted, |
| 5821 | json!([{"messageId": "m0030", "sender": "8:orgid:user-ada", "time": time}]) |
| 5822 | ); |
| 5823 | assert_eq!(sent.message_id, "1727203440000"); |
| 5824 | assert_eq!(sent.reply_to_id.as_deref(), Some("m0030")); |
| 5825 | assert!(sent.body_html.starts_with("e)); |
| 5826 | } |