ruma_events/
beacon_info.rs

1//! Types for the `org.matrix.msc3489.beacon_info` state event, the unstable version of
2//! `m.beacon_info` ([MSC3489]).
3//!
4//! [MSC3489]: https://github.com/matrix-org/matrix-spec-proposals/pull/3489
5
6use ruma_common::{MilliSecondsSinceUnixEpoch, OwnedUserId};
7use ruma_macros::EventContent;
8use serde::{Deserialize, Serialize};
9use web_time::{Duration, SystemTime};
10
11use crate::location::AssetContent;
12
13/// The content of a beacon_info state.
14#[derive(Clone, Debug, Deserialize, Serialize, EventContent)]
15#[cfg_attr(not(ruma_unstable_exhaustive_types), non_exhaustive)]
16#[ruma_event(
17    type = "org.matrix.msc3672.beacon_info", alias = "m.beacon_info", kind = State, state_key_type = OwnedUserId
18)]
19pub struct BeaconInfoEventContent {
20    /// The description of the location.
21    ///
22    /// It should be used to label the location on a map.
23    #[serde(skip_serializing_if = "Option::is_none")]
24    pub description: Option<String>,
25
26    /// Whether the user starts sharing their location.
27    pub live: bool,
28
29    /// The time when location sharing started.
30    #[serde(rename = "org.matrix.msc3488.ts")]
31    pub ts: MilliSecondsSinceUnixEpoch,
32
33    /// The duration that the location sharing will be live.
34    ///
35    /// Meaning that the location will stop being shared at `ts + timeout`.
36    #[serde(default, with = "ruma_common::serde::duration::ms")]
37    pub timeout: Duration,
38
39    /// The asset that this message refers to.
40    #[serde(default, rename = "org.matrix.msc3488.asset")]
41    pub asset: AssetContent,
42}
43
44impl BeaconInfoEventContent {
45    /// Creates a new `BeaconInfoEventContent` with the given description, live, timeout and
46    /// optional ts. If ts is None, the current time will be used.
47    pub fn new(
48        description: Option<String>,
49        timeout: Duration,
50        live: bool,
51        ts: Option<MilliSecondsSinceUnixEpoch>,
52    ) -> Self {
53        Self {
54            description,
55            live,
56            ts: ts.unwrap_or_else(MilliSecondsSinceUnixEpoch::now),
57            timeout,
58            asset: Default::default(),
59        }
60    }
61
62    /// Starts the beacon_info being live.
63    pub fn start(&mut self) {
64        self.live = true;
65    }
66
67    /// Stops the beacon_info from being live.
68    pub fn stop(&mut self) {
69        self.live = false;
70    }
71
72    /// Start time plus its timeout, it returns `false`, indicating that the beacon is not live.
73    /// Otherwise, it returns `true`.
74    pub fn is_live(&self) -> bool {
75        self.live
76            && self
77                .ts
78                .to_system_time()
79                .and_then(|t| t.checked_add(self.timeout))
80                .is_some_and(|t| t > SystemTime::now())
81    }
82}