Skip to main content

ruma_client_api/delayed_events/
send_delayed_event.rs

1//! `PUT /_matrix/client/*/rooms/{roomId}/delayed_event/{eventType}/{txnId}`
2//!
3//! Send a delayed event (a scheduled message) to a room.
4
5pub mod msc4140 {
6    //! `/unstable/org.matrix.msc4140/` ([MSC])
7    //!
8    //! [MSC]: https://github.com/matrix-org/matrix-spec-proposals/pull/4140
9
10    use std::time::Duration;
11
12    use ruma_common::{
13        OwnedRoomId, OwnedTransactionId,
14        api::{auth_scheme::AccessToken, request, response},
15        metadata,
16        serde::Raw,
17    };
18    #[cfg(feature = "unstable-msc4354")]
19    use ruma_events::sticky::StickyDurationMs;
20    use ruma_events::{AnyTimelineEventContent, TimelineEventType};
21
22    metadata! {
23        method: PUT,
24        rate_limited: true,
25        authentication: AccessToken,
26        history: {
27            unstable("org.matrix.msc4140") => "/_matrix/client/unstable/org.matrix.msc4140/rooms/{room_id}/delayed_event/{event_type}/{txn_id}",
28        }
29    }
30
31    /// Request type for the `send_delayed_event` endpoint.
32    #[request]
33    pub struct Request {
34        /// The room to send the event to.
35        #[ruma_api(path)]
36        pub room_id: OwnedRoomId,
37
38        /// The type of event to send.
39        #[ruma_api(path)]
40        pub event_type: TimelineEventType,
41
42        /// The transaction ID for this event.
43        ///
44        /// Clients should generate a unique ID across requests within the
45        /// same session. A session is identified by an access token, and
46        /// persists when the [access token is refreshed].
47        ///
48        /// It will be used by the server to ensure idempotency of requests.
49        ///
50        /// [access token is refreshed]: https://spec.matrix.org/v1.19/client-server-api/#refreshing-access-tokens
51        #[ruma_api(path)]
52        pub txn_id: OwnedTransactionId,
53
54        /// The duration that the server should wait before sending this event
55        #[serde(with = "ruma_common::serde::duration::ms")]
56        pub delay_ms: Duration,
57
58        /// The duration to stick the delayed event.
59        ///
60        /// Caller must first check that the server supports sticky events (via `/versions`),
61        /// or it will be no-op.
62        ///
63        /// See [MSC4354 sticky events](https://github.com/matrix-org/matrix-spec-proposals/pull/4354).
64        #[cfg(feature = "unstable-msc4354")]
65        #[serde(
66            skip_serializing_if = "Option::is_none",
67            rename = "org.matrix.msc4354.sticky_duration_ms"
68        )]
69        pub sticky_duration_ms: Option<StickyDurationMs>,
70
71        /// The State Key if the event is a state event, nothing otherwise
72        #[serde(skip_serializing_if = "Option::is_none")]
73        pub state_key: Option<String>,
74
75        /// The event content to send.
76        pub content: Raw<AnyTimelineEventContent>,
77    }
78
79    /// Response type for the `send_delayed_event` endpoint.
80    #[response]
81    pub struct Response {
82        /// The `delay_id` generated for this delayed event. Used to interact with delayed events.
83        pub delay_id: String,
84    }
85
86    impl Request {
87        /// Creates a new `Request` with the given room id, transaction id, `delay_parameters` and
88        /// event content.
89        ///
90        /// # Errors
91        ///
92        /// Since `Request` stores the request body in serialized form, this function can fail if
93        /// `T`s [`serde::Serialize`] implementation can fail.
94        pub fn new(
95            room_id: OwnedRoomId,
96            txn_id: OwnedTransactionId,
97            delay_ms: Duration,
98            state_key: Option<String>,
99            content: &AnyTimelineEventContent,
100        ) -> serde_json::Result<Self> {
101            Ok(Self {
102                room_id,
103                txn_id,
104                event_type: content.event_type(),
105                state_key,
106                delay_ms,
107                #[cfg(feature = "unstable-msc4354")]
108                sticky_duration_ms: None,
109                content: Raw::new(content)?,
110            })
111        }
112
113        /// Creates a new `Request` with the given room id, transaction id, event type,
114        /// `delay_parameters` and raw event content.
115        pub fn new_raw(
116            event_type: TimelineEventType,
117            room_id: OwnedRoomId,
118            txn_id: OwnedTransactionId,
119            delay_ms: Duration,
120            state_key: Option<String>,
121            content: Raw<AnyTimelineEventContent>,
122        ) -> serde_json::Result<Self> {
123            Ok(Self {
124                room_id,
125                txn_id,
126                event_type,
127                state_key,
128                delay_ms,
129                #[cfg(feature = "unstable-msc4354")]
130                sticky_duration_ms: None,
131                content,
132            })
133        }
134    }
135
136    impl Response {
137        /// Creates a new `Response` with the token required to control the delayed event.
138        pub fn new(delay_id: String) -> Self {
139            Self { delay_id }
140        }
141    }
142
143    #[cfg(all(test, feature = "client"))]
144    mod client_tests {
145        use std::borrow::Cow;
146
147        use ruma_common::{
148            api::{
149                MatrixVersion, OutgoingRequestExt as _, SupportedVersions,
150                auth_scheme::SendAccessToken,
151            },
152            owned_room_id,
153        };
154        use ruma_events::{AnyMessageLikeEventContent, room::message::RoomMessageEventContent};
155        use serde_json::{Value as JsonValue, json};
156        use web_time::Duration;
157
158        use super::Request;
159
160        #[test]
161        fn serialize_send_delayed_event_request() {
162            let room_id = owned_room_id!("!roomid:example.org");
163            let supported = SupportedVersions {
164                versions: [MatrixVersion::V1_1].into(),
165                features: Default::default(),
166            };
167
168            let req = Request::new(
169                room_id,
170                "1234".into(),
171                Duration::from_millis(103),
172                None,
173                &AnyMessageLikeEventContent::from(RoomMessageEventContent::text_plain("test"))
174                    .into(),
175            )
176            .unwrap();
177            let request: http::Request<Vec<u8>> = req
178                .try_into_http_request(
179                    "https://homeserver.tld",
180                    SendAccessToken::IfRequired("auth_tok"),
181                    Cow::Owned(supported),
182                )
183                .unwrap();
184            let (parts, body) = request.into_parts();
185            assert_eq!(
186                "https://homeserver.tld/_matrix/client/unstable/org.matrix.msc4140/rooms/!roomid:example.org/delayed_event/m.room.message/1234",
187                parts.uri
188            );
189            assert_eq!("PUT", parts.method);
190            assert_eq!(
191                json!({"content":{"msgtype":"m.text","body":"test"}, "delay_ms": 103}),
192                serde_json::from_slice::<JsonValue>(&body).unwrap()
193            );
194        }
195
196        #[cfg(feature = "unstable-msc4354")]
197        #[test]
198        fn serialize_send_delayed_sticky_event_request() {
199            use ruma_events::sticky::StickyDurationMs;
200
201            let supported = SupportedVersions {
202                versions: [MatrixVersion::V1_1].into(),
203                features: Default::default(),
204            };
205
206            let mut req = Request::new(
207                owned_room_id!("!roomid:example.org"),
208                "1234".into(),
209                Duration::from_millis(30_000),
210                None,
211                &AnyMessageLikeEventContent::from(RoomMessageEventContent::text_plain("test"))
212                    .into(),
213            )
214            .unwrap();
215            req.sticky_duration_ms = Some(StickyDurationMs::new_clamped(300_000_u32));
216
217            let request: http::Request<Vec<u8>> = req
218                .try_into_http_request(
219                    "https://homeserver.tld",
220                    SendAccessToken::IfRequired("auth_tok"),
221                    Cow::Owned(supported),
222                )
223                .unwrap();
224            let (parts, body) = request.into_parts();
225            assert_eq!(
226                "https://homeserver.tld/_matrix/client/unstable/org.matrix.msc4140/rooms/!roomid:example.org/delayed_event/m.room.message/1234",
227                parts.uri
228            );
229            assert_eq!(
230                json!({
231                    "content": {"msgtype":"m.text","body":"test"},
232                    "delay_ms": 30000,
233                    "org.matrix.msc4354.sticky_duration_ms": 300_000,
234                }),
235                serde_json::from_slice::<JsonValue>(&body).unwrap()
236            );
237        }
238    }
239
240    #[cfg(all(test, feature = "server"))]
241    mod server_tests {
242
243        use std::time::Duration;
244
245        use ruma_common::api::IncomingRequestExt as _;
246        use serde_json::json;
247
248        use super::Request;
249
250        #[test]
251        fn deserialize_send_delayed_events_request() {
252            let uri = http::Uri::builder()
253                .scheme("https")
254                .authority("matrix.org")
255                .path_and_query(
256                    "/_matrix/client/unstable/org.matrix.msc4140/rooms/!roomid:example.org/delayed_event/m.room.message/5678",
257                )
258                .build()
259                .unwrap();
260
261            let body = json!({"content":{"msgtype":"m.text","body":"test"}, "delay_ms": 103});
262
263            let req = Request::try_from_http_request(
264                http::Request::builder()
265                    .method("PUT")
266                    .uri(uri)
267                    .body(body.to_string().as_bytes())
268                    .unwrap(),
269                &["!roomid:example.org", "m.room.message", "5678"],
270            )
271            .unwrap();
272
273            assert_eq!(req.room_id, "!roomid:example.org");
274            assert_eq!(req.event_type, "m.room.message".into());
275            assert_eq!(req.txn_id, "5678");
276            assert_eq!(req.delay_ms, Duration::from_millis(103));
277            assert_eq!(req.state_key, None);
278            assert_eq!(
279                serde_json::from_str::<serde_json::Value>(req.content.json().get()).unwrap(),
280                json!({"msgtype":"m.text","body":"test"}),
281            );
282        }
283
284        /// The sticky duration is read from the request body.
285        #[cfg(feature = "unstable-msc4354")]
286        #[test]
287        fn deserialize_send_delayed_sticky_event_request() {
288            use ruma_events::sticky::StickyDurationMs;
289
290            let uri = http::Uri::builder()
291                .scheme("https")
292                .authority("matrix.org")
293                .path_and_query(
294                    "/_matrix/client/unstable/org.matrix.msc4140/rooms/!roomid:example.org/delayed_event/m.room.message/5678",
295                )
296                .build()
297                .unwrap();
298
299            let body = json!({
300                "content": {"msgtype":"m.text","body":"test"},
301                "delay_ms": 103,
302                "org.matrix.msc4354.sticky_duration_ms": 300_000,
303            });
304
305            let req = Request::try_from_http_request(
306                http::Request::builder()
307                    .method("PUT")
308                    .uri(uri)
309                    .body(body.to_string().as_bytes())
310                    .unwrap(),
311                &["!roomid:example.org", "m.room.message", "5678"],
312            )
313            .unwrap();
314
315            assert_eq!(req.sticky_duration_ms, Some(StickyDurationMs::new_clamped(300_000_u32)));
316        }
317
318        /// Without the body field the delayed event is scheduled as a regular, non-sticky event.
319        #[cfg(feature = "unstable-msc4354")]
320        #[test]
321        fn deserialize_send_delayed_event_request_without_sticky() {
322            let uri = http::Uri::builder()
323                .scheme("https")
324                .authority("matrix.org")
325                .path_and_query(
326                    "/_matrix/client/unstable/org.matrix.msc4140/rooms/!roomid:example.org/delayed_event/m.room.message/5678",
327                )
328                .build()
329                .unwrap();
330
331            let body = json!({"content":{"msgtype":"m.text","body":"test"}, "delay_ms": 103});
332
333            let req = Request::try_from_http_request(
334                http::Request::builder()
335                    .method("PUT")
336                    .uri(uri)
337                    .body(body.to_string().as_bytes())
338                    .unwrap(),
339                &["!roomid:example.org", "m.room.message", "5678"],
340            )
341            .unwrap();
342
343            assert_eq!(req.sticky_duration_ms, None);
344        }
345    }
346}