| 1 | use serde_json::Value; |
| 2 | use session::{Request, Session}; |
| 3 | |
| 4 | use crate::error::Result; |
| 5 | use crate::relay::ic3_scope; |
| 6 | use crate::signaling::{CHATSVC_REGION, MeetingTarget}; |
| 7 | |
| 8 | const LIVE_STATE_PREFIX: &str = "awareness_conversationLiveState"; |
| 9 | const MEETING_PROPERTY: &str = "meeting"; |
| 10 | const ACTIVE_STATUS: &str = "Active"; |
| 11 | const MILLISECOND_EPOCH_FLOOR: i64 = 1_000_000_000_000; |
| 12 | |
| 13 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 14 | pub struct LiveMeeting { |
| 15 | pub thread_id: String, |
| 16 | pub conversation_url: Option<String>, |
| 17 | pub expiration: Option<i64>, |
| 18 | pub organizer_id: Option<String>, |
| 19 | pub tenant_id: Option<String>, |
| 20 | pub meeting_code: Option<String>, |
| 21 | pub passcode: Option<String>, |
| 22 | } |
| 23 | |
| 24 | impl LiveMeeting { |
| 25 | pub fn is_running(&self, now_unix: i64) -> bool { |
| 26 | self.expiration.is_none_or(|expires| expires > now_unix) |
| 27 | } |
| 28 | |
| 29 | pub fn target(&self) -> Option<MeetingTarget> { |
| 30 | let meeting_data = self |
| 31 | .meeting_code |
| 32 | .as_ref() |
| 33 | .map(|code| serde_json::json!({"meetingCode": code, "passcode": self.passcode})); |
| 34 | Some(MeetingTarget { |
| 35 | thread_id: self.thread_id.clone(), |
| 36 | tenant_id: self.tenant_id.clone()?, |
| 37 | organizer_id: self.organizer_id.clone()?, |
| 38 | meeting_data, |
| 39 | }) |
| 40 | } |
| 41 | } |
| 42 | |
| 43 | fn as_object(value: &Value) -> Option<Value> { |
| 44 | match value { |
| 45 | Value::String(text) => serde_json::from_str(text).ok(), |
| 46 | Value::Object(_) => Some(value.clone()), |
| 47 | _ => None, |
| 48 | } |
| 49 | } |
| 50 | |
| 51 | fn expiration_seconds(value: &Value) -> Option<i64> { |
| 52 | let raw = value.as_i64().or_else(|| value.as_str()?.parse().ok())?; |
| 53 | Some(if raw >= MILLISECOND_EPOCH_FLOOR { |
| 54 | raw / 1000 |
| 55 | } else { |
| 56 | raw |
| 57 | }) |
| 58 | } |
| 59 | |
| 60 | fn property_text(value: &Value, key: &str) -> Option<String> { |
| 61 | value[key] |
| 62 | .as_str() |
| 63 | .filter(|text| !text.is_empty()) |
| 64 | .map(str::to_owned) |
| 65 | } |
| 66 | |
| 67 | fn thread_properties(body: &Value) -> Value { |
| 68 | let mut merged = serde_json::Map::new(); |
| 69 | for key in ["properties", "threadProperties"] { |
| 70 | if let Some(properties) = body.get(key).and_then(Value::as_object) { |
| 71 | merged.extend(properties.clone()); |
| 72 | } |
| 73 | } |
| 74 | Value::Object(merged) |
| 75 | } |
| 76 | |
| 77 | pub fn live_meeting(thread_id: &str, properties: &Value, now_unix: i64) -> Option<LiveMeeting> { |
| 78 | let meeting = properties.get(MEETING_PROPERTY).and_then(as_object); |
| 79 | let entries = properties.as_object()?; |
| 80 | entries |
| 81 | .iter() |
| 82 | .filter(|(key, _)| key.starts_with(LIVE_STATE_PREFIX)) |
| 83 | .filter_map(|(_, value)| as_object(value)) |
| 84 | .filter(|state| state["status"].as_str() == Some(ACTIVE_STATUS)) |
| 85 | .filter_map(|state| { |
| 86 | let expiration = expiration_seconds(&state["expiration"]); |
| 87 | if expiration.is_some_and(|expires| expires <= now_unix) { |
| 88 | return None; |
| 89 | } |
| 90 | let info = &state["meetingInfo"]; |
| 91 | let fallback = meeting.as_ref(); |
| 92 | Some(LiveMeeting { |
| 93 | thread_id: thread_id.to_owned(), |
| 94 | conversation_url: property_text(&state, "conversationUrl"), |
| 95 | expiration, |
| 96 | organizer_id: property_text(info, "organizerId") |
| 97 | .or_else(|| fallback.and_then(|meeting| property_text(meeting, "organizerId"))), |
| 98 | tenant_id: property_text(info, "tenantId") |
| 99 | .or_else(|| fallback.and_then(|meeting| property_text(meeting, "tenantId"))), |
| 100 | meeting_code: property_text(&state["meetingData"], "meetingCode"), |
| 101 | passcode: property_text(&state["meetingData"], "passcode"), |
| 102 | }) |
| 103 | }) |
| 104 | .next() |
| 105 | } |
| 106 | |
| 107 | pub async fn fetch_live_meeting(session: &Session, thread_id: &str) -> Result<Option<LiveMeeting>> { |
| 108 | let url = chatsvc::conversations::thread_url(CHATSVC_REGION, thread_id); |
| 109 | let response = session.send(Request::get(url), &ic3_scope()).await?; |
| 110 | let now = std::time::SystemTime::now() |
| 111 | .duration_since(std::time::UNIX_EPOCH) |
| 112 | .map_or(0, |elapsed| elapsed.as_secs() as i64); |
| 113 | Ok(live_meeting( |
| 114 | thread_id, |
| 115 | &thread_properties(&response.body), |
| 116 | now, |
| 117 | )) |
| 118 | } |
| 119 | |
| 120 | #[cfg(test)] |
| 121 | mod tests { |
| 122 | use serde_json::json; |
| 123 | |
| 124 | use super::*; |
| 125 | |
| 126 | const NOW: i64 = 1_791_600_000; |
| 127 | |
| 128 | fn live_state(status: &str, expiration: i64) -> String { |
| 129 | json!({ |
| 130 | "conversationUrl": "https://conv/1", |
| 131 | "conversationId": "1", |
| 132 | "status": status, |
| 133 | "expiration": expiration, |
| 134 | "conversationType": "scheduledMeeting", |
| 135 | "meetingInfo": {"organizerId": "org-1", "tenantId": "tenant-1"}, |
| 136 | "meetingData": {"meetingCode": "123", "passcode": "pw"}, |
| 137 | }) |
| 138 | .to_string() |
| 139 | } |
| 140 | |
| 141 | #[test] |
| 142 | fn an_active_unexpired_state_is_a_running_meeting() { |
| 143 | let properties = |
| 144 | json!({"awareness_conversationLiveState:0": live_state("Active", NOW + 600)}); |
| 145 | let meeting = live_meeting("19:m@thread.v2", &properties, NOW).unwrap(); |
| 146 | assert_eq!(meeting.organizer_id.as_deref(), Some("org-1")); |
| 147 | assert_eq!(meeting.conversation_url.as_deref(), Some("https://conv/1")); |
| 148 | let target = meeting.target().unwrap(); |
| 149 | assert_eq!(target.thread_id, "19:m@thread.v2"); |
| 150 | assert_eq!(target.tenant_id, "tenant-1"); |
| 151 | assert_eq!(target.meeting_data.unwrap()["meetingCode"], "123"); |
| 152 | } |
| 153 | |
| 154 | #[test] |
| 155 | fn no_state_expired_or_ended_means_no_join_button() { |
| 156 | assert!(live_meeting("t", &json!({}), NOW).is_none()); |
| 157 | assert!(live_meeting("t", &json!({"topic": "x"}), NOW).is_none()); |
| 158 | let expired = json!({"awareness_conversationLiveState:0": live_state("Active", NOW - 1)}); |
| 159 | assert!(live_meeting("t", &expired, NOW).is_none()); |
| 160 | let ended = json!({"awareness_conversationLiveState:0": live_state("Ended", NOW + 600)}); |
| 161 | assert!(live_meeting("t", &ended, NOW).is_none()); |
| 162 | } |
| 163 | |
| 164 | #[test] |
| 165 | fn a_known_meeting_stops_running_when_it_expires() { |
| 166 | let properties = |
| 167 | json!({"awareness_conversationLiveState:0": live_state("Active", NOW + 600)}); |
| 168 | let meeting = live_meeting("t", &properties, NOW).unwrap(); |
| 169 | assert!(meeting.is_running(NOW + 599)); |
| 170 | assert!(!meeting.is_running(NOW + 600)); |
| 171 | } |
| 172 | |
| 173 | #[test] |
| 174 | fn a_second_parallel_state_still_counts() { |
| 175 | let properties = json!({ |
| 176 | "awareness_conversationLiveState:0": live_state("Ended", NOW + 600), |
| 177 | "awareness_conversationLiveState:1": live_state("Active", NOW + 600), |
| 178 | }); |
| 179 | assert!(live_meeting("t", &properties, NOW).is_some()); |
| 180 | } |
| 181 | |
| 182 | #[test] |
| 183 | fn expiration_in_milliseconds_is_understood() { |
| 184 | let properties = |
| 185 | json!({"awareness_conversationLiveState": live_state("Active", (NOW + 600) * 1000)}); |
| 186 | assert!(live_meeting("t", &properties, NOW).is_some()); |
| 187 | let past = |
| 188 | json!({"awareness_conversationLiveState": live_state("Active", (NOW - 600) * 1000)}); |
| 189 | assert!(live_meeting("t", &past, NOW).is_none()); |
| 190 | } |
| 191 | |
| 192 | #[test] |
| 193 | fn meeting_info_falls_back_to_the_meeting_property() { |
| 194 | let mut state: Value = serde_json::from_str(&live_state("Active", NOW + 600)).unwrap(); |
| 195 | state.as_object_mut().unwrap().remove("meetingInfo"); |
| 196 | let properties = json!({ |
| 197 | "awareness_conversationLiveState:0": state.to_string(), |
| 198 | "meeting": json!({"organizerId": "org-2", "tenantId": "tenant-2"}).to_string(), |
| 199 | }); |
| 200 | let meeting = live_meeting("t", &properties, NOW).unwrap(); |
| 201 | assert_eq!(meeting.organizer_id.as_deref(), Some("org-2")); |
| 202 | assert_eq!(meeting.tenant_id.as_deref(), Some("tenant-2")); |
| 203 | } |
| 204 | |
| 205 | #[test] |
| 206 | fn without_organizer_or_tenant_there_is_no_join_target() { |
| 207 | let state = json!({"status": "Active", "expiration": NOW + 600}); |
| 208 | let properties = json!({"awareness_conversationLiveState:0": state.to_string()}); |
| 209 | let meeting = live_meeting("t", &properties, NOW).unwrap(); |
| 210 | assert!(meeting.target().is_none()); |
| 211 | } |
| 212 | |
| 213 | #[test] |
| 214 | fn thread_and_conversation_properties_merge() { |
| 215 | let body = json!({ |
| 216 | "properties": {"a": 1}, |
| 217 | "threadProperties": {"awareness_conversationLiveState:0": live_state("Active", NOW + 600)}, |
| 218 | }); |
| 219 | let merged = thread_properties(&body); |
| 220 | assert!(merged.get("a").is_some()); |
| 221 | assert!(live_meeting("t", &merged, NOW).is_some()); |
| 222 | } |
| 223 | } |