| 1 | //! Keeps an org that is not open in the window live for notifications, like Teams does for other orgs: |
| 2 | //! its own realtime socket, and a toast for every new chat message from someone else. |
| 3 | use std::collections::HashMap; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use app_base::orgs::Org; |
| 7 | use chatsvc::{ChatListing, Conversations, EventKind, Realtime, RealtimeConfig, RealtimeEvent}; |
| 8 | use serde_json::Value; |
| 9 | use session::Session; |
| 10 | use tokio::sync::mpsc; |
| 11 | |
| 12 | use crate::backend::BackendEvent; |
| 13 | |
| 14 | const RETRY: Duration = Duration::from_secs(30); |
| 15 | const PREVIEW_CHARS: usize = 200; |
| 16 | /// Chats only, like the default Teams settings for other orgs; channel posts and system threads stay quiet. |
| 17 | const CHANNEL_SUFFIX: &str = "@thread.tacv2"; |
| 18 | const SYSTEM_PREFIX: &str = "48:"; |
| 19 | const MESSAGE_TYPES: [&str; 2] = ["RichText/Html", "Text"]; |
| 20 | |
| 21 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 22 | pub struct OrgMessage { |
| 23 | pub org: Org, |
| 24 | pub conversation_id: String, |
| 25 | pub message_id: String, |
| 26 | pub chat_title: String, |
| 27 | pub sender_name: String, |
| 28 | pub preview: String, |
| 29 | pub direct: bool, |
| 30 | } |
| 31 | |
| 32 | pub(crate) async fn watch( |
| 33 | session: Session, |
| 34 | org: Org, |
| 35 | me: Option<String>, |
| 36 | events: mpsc::UnboundedSender<BackendEvent>, |
| 37 | ) { |
| 38 | let me = match me { |
| 39 | Some(me) => Some(me), |
| 40 | None => own_object_id(&session).await, |
| 41 | }; |
| 42 | let listing = ChatListing::new(&session); |
| 43 | let conversations = Conversations::new(&session); |
| 44 | let mut muted: HashMap<String, bool> = HashMap::new(); |
| 45 | loop { |
| 46 | match Realtime::start_with(&session, RealtimeConfig::default()).await { |
| 47 | Ok(mut realtime) => { |
| 48 | while let Some(event) = realtime.recv().await { |
| 49 | let RealtimeEvent::Message(event) = event else { |
| 50 | continue; |
| 51 | }; |
| 52 | let (EventKind::NewMessage, Some(conversation_id), Some(message_id)) = |
| 53 | (event.kind, event.conversation_id, event.message_id) |
| 54 | else { |
| 55 | continue; |
| 56 | }; |
| 57 | if !is_chat(&conversation_id) { |
| 58 | continue; |
| 59 | } |
| 60 | if !muted.contains_key(&conversation_id) |
| 61 | && let Ok(states) = conversations.conversation_states().await |
| 62 | { |
| 63 | muted.extend(states.into_iter().map(|state| (state.id, state.muted))); |
| 64 | } |
| 65 | if muted.get(&conversation_id).copied().unwrap_or(false) { |
| 66 | continue; |
| 67 | } |
| 68 | let Ok(message) = listing.message(&conversation_id, &message_id).await else { |
| 69 | continue; |
| 70 | }; |
| 71 | let conversation = listing.conversation(&conversation_id).await.ok(); |
| 72 | let parsed = org_message( |
| 73 | &org, |
| 74 | me.as_deref(), |
| 75 | &conversation_id, |
| 76 | &message_id, |
| 77 | &message, |
| 78 | conversation.as_ref(), |
| 79 | ); |
| 80 | if let Some(parsed) = parsed |
| 81 | && events.send(BackendEvent::OrgMessage(parsed)).is_err() |
| 82 | { |
| 83 | return; |
| 84 | } |
| 85 | } |
| 86 | } |
| 87 | Err(error) => crate::diagnostics::record(format!( |
| 88 | "orgs: live updates for another org failed: {error}" |
| 89 | )), |
| 90 | } |
| 91 | tokio::time::sleep(RETRY).await; |
| 92 | } |
| 93 | } |
| 94 | |
| 95 | async fn own_object_id(session: &Session) -> Option<String> { |
| 96 | match graph::Graph::new(session.clone()).me().await { |
| 97 | Ok(user) => Some(user.id.to_ascii_lowercase()), |
| 98 | Err(error) => { |
| 99 | crate::diagnostics::record(format!("orgs: own id in another org not read: {error}")); |
| 100 | None |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | fn is_chat(conversation_id: &str) -> bool { |
| 106 | !conversation_id.starts_with(SYSTEM_PREFIX) && !conversation_id.ends_with(CHANNEL_SUFFIX) |
| 107 | } |
| 108 | |
| 109 | fn org_message( |
| 110 | org: &Org, |
| 111 | me: Option<&str>, |
| 112 | conversation_id: &str, |
| 113 | message_id: &str, |
| 114 | message: &Value, |
| 115 | conversation: Option<&Value>, |
| 116 | ) -> Option<OrgMessage> { |
| 117 | let message_type = message["messagetype"].as_str()?; |
| 118 | if !MESSAGE_TYPES.contains(&message_type) { |
| 119 | return None; |
| 120 | } |
| 121 | let from = message["from"] |
| 122 | .as_str() |
| 123 | .unwrap_or_default() |
| 124 | .to_ascii_lowercase(); |
| 125 | if me.is_some_and(|me| from.ends_with(me)) { |
| 126 | return None; |
| 127 | } |
| 128 | let sender_name = message["imdisplayname"] |
| 129 | .as_str() |
| 130 | .unwrap_or_default() |
| 131 | .to_owned(); |
| 132 | let text = store::plain_text(message["content"].as_str().unwrap_or_default()); |
| 133 | let preview: String = text.trim().chars().take(PREVIEW_CHARS).collect(); |
| 134 | if preview.is_empty() { |
| 135 | return None; |
| 136 | } |
| 137 | let properties = conversation.map(|conversation| &conversation["threadProperties"]); |
| 138 | let topic = properties |
| 139 | .and_then(|properties| properties["topic"].as_str()) |
| 140 | .map(str::trim) |
| 141 | .filter(|topic| !topic.is_empty()); |
| 142 | let direct = properties |
| 143 | .and_then(|properties| properties["uniquerosterthread"].as_str()) |
| 144 | .is_some_and(|flag| flag == "true") |
| 145 | || conversation_id.ends_with("@unq.gbl.spaces"); |
| 146 | Some(OrgMessage { |
| 147 | org: org.clone(), |
| 148 | conversation_id: conversation_id.to_owned(), |
| 149 | message_id: message_id.to_owned(), |
| 150 | chat_title: topic.unwrap_or(&sender_name).to_owned(), |
| 151 | sender_name, |
| 152 | preview, |
| 153 | direct, |
| 154 | }) |
| 155 | } |
| 156 | |
| 157 | #[cfg(test)] |
| 158 | mod tests { |
| 159 | use super::*; |
| 160 | use serde_json::json; |
| 161 | |
| 162 | fn org() -> Org { |
| 163 | Org { |
| 164 | id: "bbbb".into(), |
| 165 | name: "Guest Org".into(), |
| 166 | guest: true, |
| 167 | } |
| 168 | } |
| 169 | |
| 170 | fn message(from: &str, kind: &str, content: &str) -> Value { |
| 171 | json!({"messagetype": kind, "from": format!("https://x/v1/users/ME/contacts/8:orgid:{from}"), "imdisplayname": "Ann Example", "content": content}) |
| 172 | } |
| 173 | |
| 174 | #[test] |
| 175 | fn a_chat_message_from_someone_else_becomes_a_toast_with_the_topic() { |
| 176 | let parsed = org_message( |
| 177 | &org(), |
| 178 | Some("me-1"), |
| 179 | "19:abc@thread.v2", |
| 180 | "1", |
| 181 | &message("ann-2", "RichText/Html", "<p>Hello <b>there</b></p>"), |
| 182 | Some(&json!({"threadProperties": {"topic": "Release"}})), |
| 183 | ) |
| 184 | .unwrap(); |
| 185 | assert_eq!(parsed.chat_title, "Release"); |
| 186 | assert_eq!(parsed.sender_name, "Ann Example"); |
| 187 | assert!(parsed.preview.starts_with("Hello")); |
| 188 | assert!(!parsed.direct); |
| 189 | } |
| 190 | |
| 191 | #[test] |
| 192 | fn own_messages_control_messages_and_channels_stay_quiet() { |
| 193 | let own = message("ME-1", "RichText/Html", "hi"); |
| 194 | assert_eq!( |
| 195 | org_message(&org(), Some("me-1"), "19:a@thread.v2", "1", &own, None), |
| 196 | None |
| 197 | ); |
| 198 | let control = message("ann-2", "ThreadActivity/AddMember", "x"); |
| 199 | assert_eq!( |
| 200 | org_message(&org(), Some("me-1"), "19:a@thread.v2", "1", &control, None), |
| 201 | None |
| 202 | ); |
| 203 | assert!(!is_chat("19:general@thread.tacv2")); |
| 204 | assert!(!is_chat("48:notifications")); |
| 205 | assert!(is_chat("19:a_b@unq.gbl.spaces")); |
| 206 | } |
| 207 | } |