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