1mod focus;
8mod member_data;
9mod member_state_key;
10
11use std::time::Duration;
12
13pub use focus::*;
14pub use member_data::*;
15pub use member_state_key::*;
16use ruma_common::{MilliSecondsSinceUnixEpoch, OwnedDeviceId, room_version_rules::RedactionRules};
17use ruma_macros::{EventContent, StringEnum};
18use serde::{Deserialize, Serialize};
19
20use crate::{
21 PossiblyRedactedStateEventContent, PrivOwnedStr, RedactContent, RedactedStateEventContent,
22 StateEventType, StaticEventContent,
23};
24
25#[derive(Clone, Debug, Serialize, Deserialize, EventContent, PartialEq)]
36#[ruma_event(type = "org.matrix.msc3401.call.member", kind = State, state_key_type = CallMemberStateKey, custom_redacted, custom_possibly_redacted)]
37#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
38#[serde(untagged)]
39pub enum CallMemberEventContent {
40 LegacyContent(LegacyMembershipContent),
43 SessionContent(SessionMembershipData),
46 Empty(EmptyMembershipData),
48}
49
50impl CallMemberEventContent {
51 pub fn new_legacy(memberships: Vec<LegacyMembershipData>) -> Self {
53 Self::LegacyContent(LegacyMembershipContent {
54 memberships, })
56 }
57
58 pub fn new(
70 application: Application,
71 device_id: OwnedDeviceId,
72 focus_active: ActiveFocus,
73 foci_preferred: Vec<Focus>,
74 created_ts: Option<MilliSecondsSinceUnixEpoch>,
75 expires: Option<Duration>,
76 ) -> Self {
77 Self::SessionContent(SessionMembershipData {
78 application,
79 device_id,
80 focus_active,
81 foci_preferred,
82 created_ts,
83 expires: expires.unwrap_or(Duration::from_secs(14_400)), })
85 }
86
87 pub fn new_empty(leave_reason: Option<LeaveReason>) -> Self {
89 Self::Empty(EmptyMembershipData { leave_reason })
90 }
91
92 pub fn active_memberships(
104 &self,
105 origin_server_ts: Option<MilliSecondsSinceUnixEpoch>,
106 ) -> Vec<MembershipData<'_>> {
107 match self {
108 CallMemberEventContent::LegacyContent(content) => content
109 .memberships
110 .iter()
111 .map(MembershipData::Legacy)
112 .filter(|m| !m.is_expired(origin_server_ts))
113 .collect(),
114 CallMemberEventContent::SessionContent(content) => {
115 vec![MembershipData::Session(content)]
116 .into_iter()
117 .filter(|m| !m.is_expired(origin_server_ts))
118 .collect()
119 }
120
121 CallMemberEventContent::Empty(_) => Vec::new(),
122 }
123 }
124
125 pub fn memberships(&self) -> Vec<MembershipData<'_>> {
128 match self {
129 CallMemberEventContent::LegacyContent(content) => {
130 content.memberships.iter().map(MembershipData::Legacy).collect()
131 }
132 CallMemberEventContent::SessionContent(content) => {
133 [content].map(MembershipData::Session).to_vec()
134 }
135 CallMemberEventContent::Empty(_) => Vec::new(),
136 }
137 }
138
139 pub fn set_created_ts_if_none(&mut self, origin_server_ts: MilliSecondsSinceUnixEpoch) {
148 match self {
149 CallMemberEventContent::LegacyContent(content) => {
150 content.memberships.iter_mut().for_each(|m: &mut LegacyMembershipData| {
151 m.created_ts.get_or_insert(origin_server_ts);
152 });
153 }
154 CallMemberEventContent::SessionContent(m) => {
155 m.created_ts.get_or_insert(origin_server_ts);
156 }
157 _ => (),
158 }
159 }
160}
161
162#[derive(Clone, PartialEq, Serialize, Deserialize, Debug)]
164#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
165pub struct EmptyMembershipData {
166 #[serde(skip_serializing_if = "Option::is_none")]
169 pub leave_reason: Option<LeaveReason>,
170}
171
172#[derive(Clone, StringEnum)]
178#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
179#[ruma_enum(rename_all(prefix = "m.", rule = "snake_case"))]
180pub enum LeaveReason {
181 LostConnection,
184 #[doc(hidden)]
185 _Custom(PrivOwnedStr),
186}
187
188impl RedactContent for CallMemberEventContent {
189 type Redacted = RedactedCallMemberEventContent;
190
191 fn redact(self, _rules: &RedactionRules) -> Self::Redacted {
192 RedactedCallMemberEventContent {}
193 }
194}
195
196pub type PossiblyRedactedCallMemberEventContent = CallMemberEventContent;
201
202impl PossiblyRedactedStateEventContent for PossiblyRedactedCallMemberEventContent {
203 type StateKey = CallMemberStateKey;
204
205 fn event_type(&self) -> StateEventType {
206 StateEventType::CallMember
207 }
208}
209
210#[derive(Clone, Debug, Deserialize, Serialize)]
212#[allow(clippy::exhaustive_structs)]
213pub struct RedactedCallMemberEventContent {}
214
215impl RedactedStateEventContent for RedactedCallMemberEventContent {
216 type StateKey = CallMemberStateKey;
217
218 fn event_type(&self) -> StateEventType {
219 StateEventType::CallMember
220 }
221}
222
223impl StaticEventContent for RedactedCallMemberEventContent {
224 const TYPE: &'static str = CallMemberEventContent::TYPE;
225 type IsPrefix = <CallMemberEventContent as StaticEventContent>::IsPrefix;
226}
227
228impl From<RedactedCallMemberEventContent> for PossiblyRedactedCallMemberEventContent {
229 fn from(_value: RedactedCallMemberEventContent) -> Self {
230 Self::new_empty(None)
231 }
232}
233
234#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
236#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
237pub struct LegacyMembershipContent {
238 memberships: Vec<LegacyMembershipData>,
249}
250
251#[cfg(test)]
252#[allow(deprecated)]
253mod tests {
254 use std::time::Duration;
255
256 use assert_matches::assert_matches;
257 use js_int::{int, uint};
258 use ruma_common::{
259 MilliSecondsSinceUnixEpoch, OwnedEventId, OwnedRoomId, OwnedUserId,
260 canonical_json::assert_to_canonical_json_eq, device_id, owned_device_id, user_id,
261 };
262 use serde_json::{Value as JsonValue, from_value as from_json_value, json};
263 use strass::{assert_let, assert_variant_eq};
264
265 use super::{
266 CallMemberEventContent,
267 focus::{ActiveFocus, ActiveLivekitFocus, Focus, LivekitFocus},
268 member_data::{
269 Application, CallApplicationContent, CallScope, LegacyMembershipData, MembershipData,
270 },
271 };
272 use crate::{
273 AnyStateEvent, StateEvent,
274 call::member::{EmptyMembershipData, FocusSelection, SessionMembershipData},
275 rtc::notification::CallIntent,
276 };
277
278 fn create_call_member_legacy_event_content() -> CallMemberEventContent {
279 CallMemberEventContent::new_legacy(vec![LegacyMembershipData {
280 application: Application::Call(CallApplicationContent::new(
281 "123456".to_owned(),
282 CallScope::Room,
283 )),
284 device_id: owned_device_id!("ABCDE"),
285 expires: Duration::from_secs(3600),
286 foci_active: vec![Focus::LegacyLivekit(LivekitFocus {
287 alias: Some("1".to_owned()),
288 url: None,
289 server_name: None,
290 service_url: Some("https://livekit.com".to_owned()),
291 })],
292 membership_id: "0".to_owned(),
293 created_ts: None,
294 }])
295 }
296
297 fn create_call_member_event_content() -> CallMemberEventContent {
298 CallMemberEventContent::new(
299 Application::Call(CallApplicationContent::new("123456".to_owned(), CallScope::Room)),
300 owned_device_id!("ABCDE"),
301 ActiveFocus::Livekit(ActiveLivekitFocus {
302 focus_selection: FocusSelection::OldestMembership,
303 }),
304 vec![Focus::LegacyLivekit(LivekitFocus {
305 alias: Some("1".to_owned()),
306 url: None,
307 server_name: None,
308 service_url: Some("https://livekit.com".to_owned()),
309 })],
310 None,
311 Duration::from_secs(3600).into(), )
313 }
314
315 #[test]
316 fn serialize_call_member_event_content() {
317 let call_member_event = &json!({
318 "application": "m.call",
319 "call_id": "123456",
320 "scope": "m.room",
321 "device_id": "ABCDE",
322 "expires": 3_600_000, "foci_preferred": [
324 {
325 "livekit_alias": "1",
326 "livekit_service_url": "https://livekit.com",
327 "type": "livekit"
328 }
329 ],
330 "focus_active":{
331 "type":"livekit",
332 "focus_selection":"oldest_membership"
333 }
334 });
335 assert_eq!(
336 call_member_event,
337 &serde_json::to_value(create_call_member_event_content()).unwrap()
338 );
339
340 let empty_call_member_event = &json!({});
341 assert_eq!(
342 empty_call_member_event,
343 &serde_json::to_value(CallMemberEventContent::Empty(EmptyMembershipData {
344 leave_reason: None
345 }))
346 .unwrap()
347 );
348 }
349
350 #[test]
351 fn serialize_legacy_call_member_event_content() {
352 let call_member_event = &json!({
353 "memberships": [
354 {
355 "application": "m.call",
356 "call_id": "123456",
357 "scope": "m.room",
358 "device_id": "ABCDE",
359 "expires": 3_600_000,
360 "foci_active": [
361 {
362 "livekit_alias": "1",
363 "livekit_service_url": "https://livekit.com",
364 "type": "livekit"
365 }
366 ],
367 "membershipID": "0"
368 }
369 ]
370 });
371
372 assert_eq!(
373 call_member_event,
374 &serde_json::to_value(create_call_member_legacy_event_content()).unwrap()
375 );
376 }
377 #[test]
378 fn deserialize_call_member_event_content() {
379 let call_member_ev = CallMemberEventContent::new(
380 Application::Call(CallApplicationContent::new("123456".to_owned(), CallScope::Room)),
381 owned_device_id!("THIS_DEVICE"),
382 ActiveFocus::Livekit(ActiveLivekitFocus {
383 focus_selection: FocusSelection::OldestMembership,
384 }),
385 vec![Focus::LegacyLivekit(LivekitFocus {
386 alias: Some("room1".to_owned()),
387 url: None,
388 server_name: None,
389 service_url: Some("https://livekit1.com".to_owned()),
390 })],
391 None,
392 None,
393 );
394
395 let call_member_ev_json = json!({
396 "application": "m.call",
397 "call_id": "123456",
398 "scope": "m.room",
399 "expires": 14_400_000, "device_id": "THIS_DEVICE",
401 "focus_active":{
402 "type": "livekit",
403 "focus_selection": "oldest_membership"
404 },
405 "foci_preferred": [
406 {
407 "livekit_alias": "room1",
408 "livekit_service_url": "https://livekit1.com",
409 "type": "livekit"
410 }
411 ],
412 });
413
414 let ev_content: CallMemberEventContent =
415 serde_json::from_value(call_member_ev_json).unwrap();
416 assert_eq!(
417 serde_json::to_string(&ev_content).unwrap(),
418 serde_json::to_string(&call_member_ev).unwrap()
419 );
420 let empty = CallMemberEventContent::Empty(EmptyMembershipData { leave_reason: None });
421 assert_eq!(
422 serde_json::to_string(&json!({})).unwrap(),
423 serde_json::to_string(&empty).unwrap()
424 );
425 }
426
427 #[test]
428 fn deserialize_call_member_event_content_without_livekit_alias() {
429 let call_member_ev = CallMemberEventContent::new(
430 Application::Call(CallApplicationContent::new("123456".to_owned(), CallScope::Room)),
431 owned_device_id!("THIS_DEVICE"),
432 ActiveFocus::Livekit(ActiveLivekitFocus {
433 focus_selection: FocusSelection::OldestMembership,
434 }),
435 vec![Focus::LegacyLivekit(LivekitFocus {
436 alias: None,
437 url: None,
438 server_name: None,
439 service_url: Some("https://livekit1.com".to_owned()),
440 })],
441 None,
442 None,
443 );
444
445 let call_member_ev_json = json!({
446 "application": "m.call",
447 "call_id": "123456",
448 "scope": "m.room",
449 "expires": 14_400_000, "device_id": "THIS_DEVICE",
451 "focus_active":{
452 "type": "livekit",
453 "focus_selection": "oldest_membership"
454 },
455 "foci_preferred": [
456 {
457 "livekit_service_url": "https://livekit1.com",
458 "type": "livekit"
459 }
460 ],
461 });
462
463 let ev_content: CallMemberEventContent =
464 serde_json::from_value(call_member_ev_json).unwrap();
465 assert_eq!(
466 serde_json::to_string(&ev_content).unwrap(),
467 serde_json::to_string(&call_member_ev).unwrap()
468 );
469 let empty = CallMemberEventContent::Empty(EmptyMembershipData { leave_reason: None });
470 assert_eq!(
471 serde_json::to_string(&json!({})).unwrap(),
472 serde_json::to_string(&empty).unwrap()
473 );
474 }
475
476 #[test]
477 fn serde_legacy_livekit_focus_service_url_only() {
478 let json = json!({
479 "type": "livekit",
480 "livekit_service_url": "https://livekit-jwt.example.com",
481 });
482
483 let focus = from_json_value::<Focus>(json.clone()).unwrap();
484 assert_let!(Focus::LegacyLivekit(livekit) = &focus);
485 assert_eq!(livekit.alias, None);
486 assert_eq!(livekit.url, None);
487 assert_eq!(livekit.server_name, None);
488 assert_variant_eq!(livekit.service_url, Some("https://livekit-jwt.example.com"));
489
490 assert_to_canonical_json_eq!(focus, json);
491 }
492
493 #[test]
494 fn serde_legacy_livekit_focus_url_only() {
495 let json = json!({
496 "type": "livekit",
497 "url": "wss://livekit.example.com",
498 });
499
500 let focus = from_json_value::<Focus>(json.clone()).unwrap();
501 assert_let!(Focus::LegacyLivekit(livekit) = &focus);
502 assert_eq!(livekit.alias, None);
503 assert_variant_eq!(livekit.url, Some("wss://livekit.example.com"));
504 assert_eq!(livekit.server_name, None);
505 assert_eq!(livekit.service_url, None);
506
507 assert_to_canonical_json_eq!(focus, json);
508 }
509
510 #[test]
511 fn serde_legacy_livekit_focus_all_fields() {
512 let json = json!({
513 "type": "livekit",
514 "url": "wss://livekit.bob.com",
515 "server_name": "bob.com",
516 "livekit_service_url": "https://livekit-jwt.bob.com",
517 "livekit_alias": "room1",
518 });
519
520 let focus = from_json_value::<Focus>(json.clone()).unwrap();
521 assert_let!(Focus::LegacyLivekit(livekit) = &focus);
522 assert_variant_eq!(livekit.alias, Some("room1"));
523 assert_variant_eq!(livekit.url, Some("wss://livekit.bob.com"));
524 assert_variant_eq!(livekit.server_name, Some("bob.com"));
525 assert_variant_eq!(livekit.service_url, Some("https://livekit-jwt.bob.com"));
526
527 assert_to_canonical_json_eq!(focus, json);
528 }
529
530 #[test]
531 fn livekit_focus_new() {
532 let url = "wss://livekit.local/".to_owned();
533 let focus = Focus::livekit(url.clone());
534 assert_eq!(focus.focus_type(), "m.livekit");
535 assert_eq!(focus, Focus::Livekit(LivekitFocus::new(url)));
536 }
537
538 #[test]
539 fn serde_livekit_focus() {
540 let json = json!({
541 "type": "m.livekit",
542 "url": "wss://livekit.example.com",
543 });
544
545 let focus = from_json_value::<Focus>(json.clone()).unwrap();
546 assert_eq!(focus, Focus::livekit("wss://livekit.example.com".to_owned()));
547 assert_let!(Focus::Livekit(livekit) = &focus);
548 assert_variant_eq!(livekit.url, Some("wss://livekit.example.com"));
549 assert_eq!(livekit.server_name, None);
550
551 assert_to_canonical_json_eq!(focus, json);
552 }
553
554 #[test]
555 fn serde_livekit_focus_with_server_name() {
556 let json = json!({
557 "type": "m.livekit",
558 "url": "wss://livekit.bob.com",
559 "server_name": "bob.com",
560 });
561
562 let focus = from_json_value::<Focus>(json.clone()).unwrap();
563 assert_let!(Focus::Livekit(livekit) = &focus);
564 assert_variant_eq!(livekit.url, Some("wss://livekit.bob.com"));
565 assert_variant_eq!(livekit.server_name, Some("bob.com"));
566
567 assert_to_canonical_json_eq!(focus, json);
568 }
569
570 #[test]
571 fn serde_livekit_focus_service_url_only() {
572 let json = json!({
573 "type": "m.livekit",
574 "livekit_service_url": "https://livekit-jwt.example.com",
575 });
576
577 let focus = from_json_value::<Focus>(json.clone()).unwrap();
578 assert_let!(Focus::Livekit(livekit) = &focus);
579 assert_eq!(livekit.url, None);
580 assert_variant_eq!(livekit.service_url, Some("https://livekit-jwt.example.com"));
581 assert_eq!(
582 *livekit,
583 LivekitFocus::with_service_url("https://livekit-jwt.example.com".to_owned())
584 );
585
586 assert_to_canonical_json_eq!(focus, json);
587 }
588
589 #[test]
590 fn serde_livekit_focus_all_fields() {
591 let json = json!({
592 "type": "m.livekit",
593 "url": "wss://livekit.bob.com",
594 "server_name": "bob.com",
595 "livekit_service_url": "https://livekit-jwt.bob.com",
596 "livekit_alias": "room1",
597 });
598
599 let focus = from_json_value::<Focus>(json.clone()).unwrap();
600 assert_let!(Focus::Livekit(livekit) = &focus);
601 assert_variant_eq!(livekit.alias, Some("room1"));
602 assert_variant_eq!(livekit.url, Some("wss://livekit.bob.com"));
603 assert_variant_eq!(livekit.server_name, Some("bob.com"));
604 assert_variant_eq!(livekit.service_url, Some("https://livekit-jwt.bob.com"));
605
606 assert_to_canonical_json_eq!(focus, json);
607 }
608
609 #[test]
610 fn new_livekit_focus_service_url_only() {
611 assert_let!(
612 JsonValue::Object(data) = json!({
613 "livekit_service_url": "https://livekit-jwt.example.com",
614 })
615 );
616
617 let focus = Focus::new("m.livekit", data.clone()).unwrap();
618 assert_let!(Focus::Livekit(livekit) = &focus);
619 assert_variant_eq!(livekit.service_url, Some("https://livekit-jwt.example.com"));
620 assert_eq!(*focus.data(), data);
621 }
622
623 #[test]
624 fn serde_custom_focus() {
625 let focus_type = "local.custom.focus";
626 assert_let!(
627 JsonValue::Object(focus_data) = json!({
628 "foo": "bar",
629 "baz": true,
630 })
631 );
632 let focus = Focus::new(focus_type, focus_data.clone()).unwrap();
633 let json = json!({
634 "type": focus_type,
635 "foo": "bar",
636 "baz": true,
637 });
638
639 assert_eq!(focus.focus_type(), focus_type);
640 assert_eq!(*focus.data().as_ref(), focus_data);
641 assert_to_canonical_json_eq!(focus, json.clone());
642 assert_eq!(from_json_value::<Focus>(json).unwrap(), focus);
643 }
644
645 #[test]
646 fn deserialize_call_member_event_content_with_custom_foci_preferred() {
647 let json = json!({
648 "application": "m.call",
649 "call_id": "123456",
650 "scope": "m.room",
651 "expires": 3_600_000,
652 "device_id": "THIS_DEVICE",
653 "focus_active": {
654 "type": "livekit",
655 "focus_selection": "oldest_membership",
656 },
657 "foci_preferred": [
658 {
659 "type": "local.custom.focus",
660 "url": "https://custom.example.com",
661 }
662 ],
663 });
664
665 assert_let!(
666 Ok(CallMemberEventContent::SessionContent(content)) =
667 from_json_value::<CallMemberEventContent>(json)
668 );
669 assert_eq!(content.foci_preferred.len(), 1);
670 assert_eq!(content.foci_preferred[0].focus_type(), "local.custom.focus");
671 }
672
673 #[test]
674 fn deserialize_call_member_event_content_without_foci_preferred() {
675 let json = json!({
676 "application": "m.call",
677 "call_id": "123456",
678 "scope": "m.room",
679 "expires": 3_600_000,
680 "device_id": "THIS_DEVICE",
681 "focus_active": {
682 "type": "livekit",
683 "focus_selection": "multi_sfu",
684 },
685 });
686
687 assert_let!(
688 Ok(CallMemberEventContent::SessionContent(content)) =
689 from_json_value::<CallMemberEventContent>(json)
690 );
691 assert_eq!(content.foci_preferred, []);
692 }
693
694 #[test]
695 fn serde_livekit_legacy_livekit_and_custom_foci() {
696 let json = json!([
697 { "type": "livekit", "livekit_service_url": "https://livekit-jwt.example.com" },
698 { "type": "m.livekit", "livekit_service_url": "https://livekit-jwt.example.com" },
699 { "type": "livekit", "url": "wss://livekit.example.com" },
700 { "type": "m.livekit", "url": "wss://livekit.example.com" },
701 { "type": "local.custom.focus", "foo": "bar" },
702 ]);
703
704 let service_url_focus =
705 LivekitFocus::with_service_url("https://livekit-jwt.example.com".to_owned());
706 let foci = from_json_value::<Vec<Focus>>(json.clone()).unwrap();
707 assert_eq!(foci.len(), 5);
708 assert_eq!(foci[0], Focus::LegacyLivekit(service_url_focus.clone()));
709 assert_eq!(foci[1], Focus::Livekit(service_url_focus));
710 assert_eq!(
711 foci[2],
712 Focus::LegacyLivekit(LivekitFocus::new("wss://livekit.example.com".to_owned()))
713 );
714 assert_eq!(foci[3], Focus::livekit("wss://livekit.example.com".to_owned()));
715 assert_eq!(foci[4].focus_type(), "local.custom.focus");
716 assert_to_canonical_json_eq!(foci, json);
717 }
718
719 #[test]
720 #[cfg(feature = "unstable-msc4075")]
721 fn deserialize_event_with_call_intent() {
722 let call_member_ev = CallMemberEventContent::new(
723 Application::Call(CallApplicationContent {
724 call_id: "".to_owned(),
725 scope: CallScope::Room,
726 call_intent: Some(CallIntent::Audio),
727 }),
728 owned_device_id!("THIS_DEVICE"),
729 ActiveFocus::Livekit(ActiveLivekitFocus {
730 focus_selection: FocusSelection::OldestMembership,
731 }),
732 vec![Focus::LegacyLivekit(LivekitFocus {
733 alias: Some("room1".to_owned()),
734 url: None,
735 server_name: None,
736 service_url: Some("https://livekit1.com".to_owned()),
737 })],
738 None,
739 None,
740 );
741
742 let json = json!({
743 "application": "m.call",
744 "call_id": "",
745 "scope": "m.room",
746 "m.call.intent": "audio",
747 "device_id": "THIS_DEVICE",
748 "foci_preferred": [
749 {
750 "type": "livekit",
751 "livekit_alias": "room1",
752 "livekit_service_url": "https://livekit1.com"
753 }
754 ],
755 "focus_active": {
756 "type": "livekit",
757 "focus_selection": "oldest_membership"
758 },
759 "expires": 14_400_000
760 });
761
762 let ev_content: CallMemberEventContent = serde_json::from_value(json).unwrap();
763 assert_eq!(
764 serde_json::to_string(&ev_content).unwrap(),
765 serde_json::to_string(&call_member_ev).unwrap()
766 );
767 }
768
769 #[test]
770 #[cfg(feature = "unstable-msc4075")]
771 fn deserialize_application() {
772 let test_cases = vec![
773 (
774 Application::Call(CallApplicationContent {
775 call_id: "".to_owned(),
776 scope: CallScope::Room,
777 call_intent: None,
778 }),
779 json!({
780 "application": "m.call",
781 "call_id": "",
782 "scope": "m.room",
783 }),
784 ),
785 (
786 Application::Call(CallApplicationContent {
787 call_id: "".to_owned(),
788 scope: CallScope::Room,
789 call_intent: Some(CallIntent::Audio),
790 }),
791 json!({
792 "application": "m.call",
793 "call_id": "",
794 "scope": "m.room",
795 "m.call.intent": "audio"
796 }),
797 ),
798 (
799 Application::Call(CallApplicationContent {
800 call_id: "xxxx".to_owned(),
801 scope: CallScope::User,
802 call_intent: Some(CallIntent::Video),
803 }),
804 json!({
805 "application": "m.call",
806 "call_id": "xxxx",
807 "scope": "m.user",
808 "m.call.intent": "video"
809 }),
810 ),
811 ];
812
813 for (model, jon) in test_cases {
814 let app: Application = serde_json::from_value(jon).unwrap();
815 assert_eq!(
816 serde_json::to_string(&app).unwrap(),
817 serde_json::to_string(&model).unwrap()
818 );
819 }
820 }
821
822 #[test]
823 fn deserialize_legacy_call_member_event_content() {
824 let call_member_ev = CallMemberEventContent::new_legacy(vec![
825 LegacyMembershipData {
826 application: Application::Call(CallApplicationContent::new(
827 "123456".to_owned(),
828 CallScope::Room,
829 )),
830 device_id: owned_device_id!("THIS_DEVICE"),
831 expires: Duration::from_secs(3600),
832 foci_active: vec![Focus::LegacyLivekit(LivekitFocus {
833 alias: Some("room1".to_owned()),
834 url: None,
835 server_name: None,
836 service_url: Some("https://livekit1.com".to_owned()),
837 })],
838 membership_id: "0".to_owned(),
839 created_ts: None,
840 },
841 LegacyMembershipData {
842 application: Application::Call(CallApplicationContent::new(
843 "".to_owned(),
844 CallScope::Room,
845 )),
846 device_id: owned_device_id!("OTHER_DEVICE"),
847 expires: Duration::from_secs(3600),
848 foci_active: vec![Focus::LegacyLivekit(LivekitFocus {
849 alias: Some("room2".to_owned()),
850 url: None,
851 server_name: None,
852 service_url: Some("https://livekit2.com".to_owned()),
853 })],
854 membership_id: "0".to_owned(),
855 created_ts: None,
856 },
857 ]);
858
859 let call_member_ev_json = json!({
860 "memberships": [
861 {
862 "application": "m.call",
863 "call_id": "123456",
864 "scope": "m.room",
865 "device_id": "THIS_DEVICE",
866 "expires": 3_600_000,
867 "foci_active": [
868 {
869 "livekit_alias": "room1",
870 "livekit_service_url": "https://livekit1.com",
871 "type": "livekit"
872 }
873 ],
874 "membershipID": "0",
875 },
876 {
877 "application": "m.call",
878 "call_id": "",
879 "scope": "m.room",
880 "device_id": "OTHER_DEVICE",
881 "expires": 3_600_000,
882 "foci_active": [
883 {
884 "livekit_alias": "room2",
885 "livekit_service_url": "https://livekit2.com",
886 "type": "livekit"
887 }
888 ],
889 "membershipID": "0"
890 }
891 ]
892 });
893
894 let ev_content: CallMemberEventContent =
895 serde_json::from_value(call_member_ev_json).unwrap();
896 assert_eq!(
897 serde_json::to_string(&ev_content).unwrap(),
898 serde_json::to_string(&call_member_ev).unwrap()
899 );
900 }
901
902 fn member_event_json(state_key: &str) -> JsonValue {
903 json!({
904 "content":{
905 "expires": 3_600_000, "application": "m.call",
907 "call_id": "",
908 "scope": "m.room",
909 "device_id": "THIS_DEVICE",
910 "focus_active":{
911 "type": "livekit",
912 "focus_selection": "oldest_membership"
913 },
914 "foci_preferred": [
915 {
916 "livekit_alias": "room1",
917 "livekit_service_url": "https://livekit1.com",
918 "type": "livekit"
919 }
920 ],
921 },
922 "type": "m.call.member",
923 "origin_server_ts": 111,
924 "event_id": "$3qfxjGYSu4sL25FtR0ep6vePOc",
925 "room_id": "!1234:example.org",
926 "sender": "@user:example.org",
927 "state_key": state_key,
928 "unsigned":{
929 "age":10,
930 "prev_content": {},
931 "prev_sender":"@user:example.org",
932 }
933 })
934 }
935
936 fn deserialize_member_event_helper(state_key: &str) {
937 let ev = member_event_json(state_key);
938
939 assert_let!(
940 Ok(AnyStateEvent::CallMember(StateEvent::Original(member_event))) = from_json_value(ev)
941 );
942
943 let event_id = OwnedEventId::try_from("$3qfxjGYSu4sL25FtR0ep6vePOc").unwrap();
944 let sender = OwnedUserId::try_from("@user:example.org").unwrap();
945 let room_id = OwnedRoomId::try_from("!1234:example.org").unwrap();
946 assert_eq!(member_event.state_key.as_ref(), state_key);
947 assert_eq!(member_event.event_id, event_id);
948 assert_eq!(member_event.sender, sender);
949 assert_eq!(member_event.room_id, room_id);
950 assert_eq!(member_event.origin_server_ts.0, uint!(111));
951 let membership = SessionMembershipData {
952 application: Application::Call(CallApplicationContent::new(
953 "".to_owned(),
954 CallScope::Room,
955 )),
956 device_id: owned_device_id!("THIS_DEVICE"),
957 foci_preferred: [Focus::LegacyLivekit(LivekitFocus {
958 alias: Some("room1".to_owned()),
959 url: None,
960 server_name: None,
961 service_url: Some("https://livekit1.com".to_owned()),
962 })]
963 .to_vec(),
964 focus_active: ActiveFocus::Livekit(ActiveLivekitFocus {
965 focus_selection: FocusSelection::OldestMembership,
966 }),
967 created_ts: None,
968 expires: Duration::from_secs(3600),
969 };
970 assert_eq!(
971 member_event.content,
972 CallMemberEventContent::SessionContent(membership.clone())
973 );
974
975 assert_eq!(
977 member_event.content.active_memberships(None)[0],
978 MembershipData::Session(&membership)
979 );
980 assert_eq!(member_event.unsigned.age, Some(int!(10)));
981 assert_eq!(
982 member_event.unsigned.prev_content.unwrap(),
983 CallMemberEventContent::Empty(EmptyMembershipData { leave_reason: None }),
984 );
985 }
986
987 #[test]
988 fn deserialize_member_event() {
989 deserialize_member_event_helper("@user:example.org");
990 }
991
992 #[test]
993 fn deserialize_member_event_with_scoped_state_key_prefixed() {
994 deserialize_member_event_helper("_@user:example.org_THIS_DEVICE_m.call");
995 }
996
997 #[test]
998 fn deserialize_member_event_with_scoped_state_key_unprefixed() {
999 deserialize_member_event_helper("@user:example.org_THIS_DEVICE_m.call");
1000 }
1001
1002 fn timestamps()
1003 -> (MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch, MilliSecondsSinceUnixEpoch) {
1004 let now = MilliSecondsSinceUnixEpoch::now();
1005 let one_second_ago =
1006 now.to_system_time().unwrap().checked_sub(Duration::from_secs(1)).unwrap();
1007 let two_hours_ago =
1008 now.to_system_time().unwrap().checked_sub(Duration::from_secs(60 * 60 * 2)).unwrap();
1009 (
1010 now,
1011 MilliSecondsSinceUnixEpoch::from_system_time(one_second_ago).unwrap(),
1012 MilliSecondsSinceUnixEpoch::from_system_time(two_hours_ago).unwrap(),
1013 )
1014 }
1015
1016 #[test]
1017 fn legacy_memberships_do_expire() {
1018 let content_legacy = create_call_member_legacy_event_content();
1019 let (now, one_second_ago, two_hours_ago) = timestamps();
1020
1021 assert_eq!(
1022 content_legacy.active_memberships(Some(one_second_ago)),
1023 content_legacy.memberships()
1024 );
1025 assert_eq!(content_legacy.active_memberships(Some(now)), content_legacy.memberships());
1026 assert_eq!(
1027 content_legacy.active_memberships(Some(two_hours_ago)),
1028 vec![] as Vec<MembershipData<'_>>
1029 );
1030 }
1031
1032 #[test]
1033 fn session_membership_does_expire() {
1034 let content = create_call_member_event_content();
1035 let (now, one_second_ago, two_hours_ago) = timestamps();
1036
1037 assert_eq!(content.active_memberships(Some(now)), content.memberships());
1038 assert_eq!(content.active_memberships(Some(one_second_ago)), content.memberships());
1039 assert_eq!(
1040 content.active_memberships(Some(two_hours_ago)),
1041 vec![] as Vec<MembershipData<'_>>
1042 );
1043 }
1044
1045 #[test]
1046 fn set_created_ts() {
1047 let mut content_now = create_call_member_legacy_event_content();
1048 let mut content_two_hours_ago = create_call_member_legacy_event_content();
1049 let mut content_one_second_ago = create_call_member_legacy_event_content();
1050 let (now, one_second_ago, two_hours_ago) = timestamps();
1051
1052 content_now.set_created_ts_if_none(now);
1053 content_one_second_ago.set_created_ts_if_none(one_second_ago);
1054 content_two_hours_ago.set_created_ts_if_none(two_hours_ago);
1055 assert_eq!(content_now.active_memberships(None), content_now.memberships());
1056
1057 assert_eq!(
1058 content_two_hours_ago.active_memberships(None),
1059 vec![] as Vec<MembershipData<'_>>
1060 );
1061 assert_eq!(
1062 content_one_second_ago.active_memberships(None),
1063 content_one_second_ago.memberships()
1064 );
1065
1066 content_two_hours_ago.set_created_ts_if_none(one_second_ago);
1068 assert_eq!(
1070 content_two_hours_ago.active_memberships(None),
1071 vec![] as Vec<MembershipData<'_>>
1072 );
1073 }
1074
1075 #[test]
1076 fn test_parse_rtc_member_event_key() {
1077 assert!(from_json_value::<AnyStateEvent>(member_event_json("abc")).is_err());
1078 assert!(from_json_value::<AnyStateEvent>(member_event_json("@nocolon")).is_err());
1079 assert!(from_json_value::<AnyStateEvent>(member_event_json("@noserverpart:")).is_err());
1080 assert!(
1081 from_json_value::<AnyStateEvent>(member_event_json("@noserverpart:_suffix")).is_err()
1082 );
1083
1084 let user_id = user_id!("@username:example.org").as_str();
1085 let device_id = device_id!("VALID_DEVICE_ID").as_str();
1086
1087 let parse_result = from_json_value::<AnyStateEvent>(member_event_json(user_id));
1088 assert_matches!(parse_result, Ok(_));
1089 assert_matches!(
1090 from_json_value::<AnyStateEvent>(member_event_json(&format!("{user_id}_{device_id}"))),
1091 Ok(_)
1092 );
1093
1094 assert_matches!(
1095 from_json_value::<AnyStateEvent>(member_event_json(&format!(
1096 "{user_id}:invalid_suffix"
1097 ))),
1098 Err(_)
1099 );
1100
1101 assert_matches!(
1102 from_json_value::<AnyStateEvent>(member_event_json(&format!("_{user_id}"))),
1103 Err(_)
1104 );
1105
1106 assert_matches!(
1107 from_json_value::<AnyStateEvent>(member_event_json(&format!("_{user_id}_{device_id}"))),
1108 Ok(_)
1109 );
1110
1111 assert_matches!(
1112 from_json_value::<AnyStateEvent>(member_event_json(&format!(
1113 "_{user_id}:invalid_suffix"
1114 ))),
1115 Err(_)
1116 );
1117 assert_matches!(
1118 from_json_value::<AnyStateEvent>(member_event_json(&format!("{user_id}_"))),
1119 Err(_)
1120 );
1121 }
1122}