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
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
use js_int::UInt;
use ruma_api::ruma_api;
use ruma_common::{
push::{PusherData, Tweak},
SecondsSinceUnixEpoch,
};
use ruma_events::EventType;
use ruma_identifiers::{EventId, RoomAliasId, RoomId, RoomName, UserId};
use ruma_serde::{Outgoing, StringEnum};
use serde::{Deserialize, Serialize};
use serde_json::value::RawValue as RawJsonValue;
ruma_api! {
metadata: {
description: "Notify a push gateway about an event or update the number of unread notifications a user has",
name: "send_event_notification",
method: POST,
path: "/_matrix/push/v1/notify",
rate_limited: false,
authentication: None,
}
request: {
pub notification: Notification<'a>,
}
#[derive(Default)]
response: {
pub rejected: Vec<String>,
}
}
impl<'a> Request<'a> {
pub fn new(notification: Notification<'a>) -> Self {
Self { notification }
}
}
impl Response {
pub fn new(rejected: Vec<String>) -> Self {
Self { rejected }
}
}
#[derive(Clone, Debug, Default, Outgoing, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Notification<'a> {
#[serde(skip_serializing_if = "Option::is_none")]
pub event_id: Option<&'a EventId>,
#[serde(skip_serializing_if = "Option::is_none")]
pub room_id: Option<&'a RoomId>,
#[serde(rename = "type", skip_serializing_if = "Option::is_none")]
pub event_type: Option<&'a EventType>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sender: Option<&'a UserId>,
#[serde(skip_serializing_if = "Option::is_none")]
pub sender_display_name: Option<&'a str>,
#[serde(skip_serializing_if = "Option::is_none")]
pub room_name: Option<&'a RoomName>,
#[serde(skip_serializing_if = "Option::is_none")]
pub room_alias: Option<&'a RoomAliasId>,
#[serde(default, skip_serializing_if = "ruma_serde::is_default")]
pub user_is_target: bool,
#[serde(default, skip_serializing_if = "ruma_serde::is_default")]
pub prio: NotificationPriority,
#[serde(skip_serializing_if = "Option::is_none")]
pub content: Option<&'a RawJsonValue>,
#[serde(default, skip_serializing_if = "ruma_serde::is_default")]
pub counts: NotificationCounts,
pub devices: &'a [Device],
}
impl<'a> Notification<'a> {
pub fn new(devices: &'a [Device]) -> Self {
Notification { devices, ..Default::default() }
}
}
#[derive(Clone, Debug, PartialEq, Eq, StringEnum)]
#[ruma_enum(rename_all = "snake_case")]
#[non_exhaustive]
pub enum NotificationPriority {
High,
Low,
#[doc(hidden)]
_Custom(String),
}
impl NotificationPriority {
pub fn as_str(&self) -> &str {
self.as_ref()
}
}
impl Default for NotificationPriority {
fn default() -> Self {
Self::High
}
}
#[derive(Clone, Debug, Default, Deserialize, Serialize, PartialEq)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct NotificationCounts {
#[serde(default, skip_serializing_if = "ruma_serde::is_default")]
pub unread: UInt,
#[serde(default, skip_serializing_if = "ruma_serde::is_default")]
pub missed_calls: UInt,
}
impl NotificationCounts {
pub fn new(unread: UInt, missed_calls: UInt) -> Self {
NotificationCounts { unread, missed_calls }
}
}
#[derive(Clone, Debug, Deserialize, Outgoing, Serialize)]
#[cfg_attr(not(feature = "unstable-exhaustive-types"), non_exhaustive)]
pub struct Device {
pub app_id: String,
pub pushkey: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub pushkey_ts: Option<SecondsSinceUnixEpoch>,
#[serde(skip_serializing_if = "Option::is_none")]
pub data: Option<PusherData>,
#[serde(with = "tweak_serde", skip_serializing_if = "Vec::is_empty")]
pub tweaks: Vec<Tweak>,
}
impl Device {
pub fn new(app_id: String, pushkey: String) -> Self {
Device { app_id, pushkey, pushkey_ts: None, data: None, tweaks: Vec::new() }
}
}
mod tweak_serde {
use std::fmt;
use ruma_common::push::Tweak;
use serde::{
de::{MapAccess, Visitor},
ser::SerializeMap,
Deserializer, Serializer,
};
pub fn serialize<S>(tweak: &[Tweak], serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut map = serializer.serialize_map(Some(tweak.len()))?;
for item in tweak {
#[allow(unreachable_patterns)]
match item {
Tweak::Highlight(b) => map.serialize_entry("highlight", b)?,
Tweak::Sound(value) => map.serialize_entry("sound", value)?,
Tweak::Custom { value, name } => map.serialize_entry(name, value)?,
_ => unreachable!("variant added to Tweak not covered by Custom"),
}
}
map.end()
}
struct TweaksVisitor;
impl<'de> Visitor<'de> for TweaksVisitor {
type Value = Vec<Tweak>;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("List of tweaks")
}
fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
where
M: MapAccess<'de>,
{
let mut tweaks = vec![];
while let Some(key) = access.next_key::<String>()? {
match &*key {
"sound" => tweaks.push(Tweak::Sound(access.next_value()?)),
"highlight" => {
let highlight =
if let Ok(highlight) = access.next_value() { highlight } else { true };
tweaks.push(Tweak::Highlight(highlight))
}
_ => tweaks.push(Tweak::Custom { name: key, value: access.next_value()? }),
};
}
if !tweaks.iter().any(|tw| matches!(tw, Tweak::Highlight(_))) {
tweaks.push(Tweak::Highlight(false));
}
Ok(tweaks)
}
}
pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<Tweak>, D::Error>
where
D: Deserializer<'de>,
{
deserializer.deserialize_map(TweaksVisitor)
}
}
#[cfg(test)]
mod tests {
use js_int::uint;
use ruma_common::SecondsSinceUnixEpoch;
use ruma_events::EventType;
use ruma_identifiers::{event_id, room_alias_id, room_id, user_id};
use serde_json::{
from_value as from_json_value, json, to_value as to_json_value, Value as JsonValue,
};
use super::{Device, Notification, NotificationCounts, NotificationPriority, Tweak};
#[test]
fn serialize_request() {
let expected = json!({
"event_id": "$3957tyerfgewrf384",
"room_id": "!slw48wfj34rtnrf:example.com",
"type": "m.room.message",
"sender": "@exampleuser:matrix.org",
"sender_display_name": "Major Tom",
"room_alias": "#exampleroom:matrix.org",
"prio": "low",
"content": {},
"counts": {
"unread": 2,
},
"devices": [
{
"app_id": "org.matrix.matrixConsole.ios",
"pushkey": "V2h5IG9uIGVhcnRoIGRpZCB5b3UgZGVjb2RlIHRoaXM/",
"pushkey_ts": 123,
"tweaks": {
"sound": "silence",
"highlight": true,
"custom": "go wild"
}
}
]
});
let eid = event_id!("$3957tyerfgewrf384");
let rid = room_id!("!slw48wfj34rtnrf:example.com");
let uid = user_id!("@exampleuser:matrix.org");
let alias = room_alias_id!("#exampleroom:matrix.org");
let count = NotificationCounts { unread: uint!(2), ..NotificationCounts::default() };
let device = Device {
pushkey_ts: Some(SecondsSinceUnixEpoch(uint!(123))),
tweaks: vec![
Tweak::Highlight(true),
Tweak::Sound("silence".into()),
Tweak::Custom {
name: "custom".into(),
value: from_json_value(JsonValue::String("go wild".into())).unwrap(),
},
],
..Device::new(
"org.matrix.matrixConsole.ios".into(),
"V2h5IG9uIGVhcnRoIGRpZCB5b3UgZGVjb2RlIHRoaXM/".into(),
)
};
let devices = &[device];
let notice = Notification {
event_id: Some(&eid),
room_id: Some(&rid),
event_type: Some(&EventType::RoomMessage),
sender: Some(&uid),
sender_display_name: Some("Major Tom"),
room_alias: Some(&alias),
content: Some(serde_json::from_str("{}").unwrap()),
counts: count,
prio: NotificationPriority::Low,
devices,
..Notification::default()
};
assert_eq!(expected, to_json_value(notice).unwrap())
}
}