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