Skip to main content

tuwunel_service/pusher/
send.rs

1use futures::{
2	FutureExt,
3	future::{join, join4},
4};
5use ruma::{
6	UInt, UserId,
7	api::{
8		client::push::{Pusher, PusherKind},
9		push_gateway::send_event_notification::v1::{
10			Device, Notification, NotificationCounts, NotificationPriority, Request,
11		},
12	},
13	events::TimelineEventType,
14	push::{Action, HighlightTweakValue, HttpPusherData, PushFormat, Ruleset, Tweak},
15};
16use serde_json::Value;
17use tuwunel_core::{Result, err, error, implement, trace, utils::BoolExt};
18use tuwunel_matrix::Event;
19use url::Url;
20
21use super::Evaluate;
22
23#[implement(super::Service)]
24#[tracing::instrument(level = "debug", skip_all)]
25pub async fn send_push_notice<E>(
26	&self,
27	user_id: &UserId,
28	pusher: &Pusher,
29	ruleset: &Ruleset,
30	event: &E,
31) -> Result
32where
33	E: Event,
34{
35	let power_levels = self
36		.services
37		.state_accessor
38		.get_power_levels(event.room_id())
39		.map(Result::ok);
40
41	let (power_levels, related_events) = join(power_levels, self.related_events(event)).await;
42
43	let serialized = event.to_format();
44	let actions = self
45		.get_actions(Evaluate {
46			user: user_id,
47			ruleset,
48			power_levels: power_levels.as_ref(),
49			pdu: &serialized,
50			room_id: event.room_id(),
51			related_events: related_events.as_ref(),
52		})
53		.await;
54
55	let notify = actions.iter().any(Action::should_notify);
56	let tweak_count = actions
57		.iter()
58		.filter(|action| matches!(action, Action::SetTweak(_)))
59		.count();
60
61	trace!(
62		%user_id,
63		event_id = %event.event_id(),
64		actions = %actions.len(),
65		notify,
66		tweaks = tweak_count,
67		"Push notice decision",
68	);
69
70	if notify || self.services.config.push.everything {
71		let tweaks: Vec<Tweak> = actions
72			.iter()
73			.filter_map(|action| match action {
74				| Action::SetTweak(tweak) => Some(tweak.clone()),
75				| _ => None,
76			})
77			.collect();
78
79		self.send_notice(user_id, pusher, tweaks, event)
80			.await?;
81	}
82
83	Ok(())
84}
85
86/// Send an account-wide counts-only notification to a push gateway.
87///
88/// Enabled HTTP pushers emit the request, including an explicit zero. The
89/// delivery is skipped only when the gateway is known to hold the current
90/// total already; an unknown gateway is always sent to.
91#[implement(super::Service)]
92#[tracing::instrument(level = "debug", skip_all)]
93pub async fn send_badge_notice(&self, user_id: &UserId, pusher: &Pusher) -> Result {
94	let PusherKind::Http(http) = &pusher.kind else {
95		return Ok(());
96	};
97
98	if badge_count_disabled(http) {
99		return Ok(());
100	}
101
102	let unread = UInt::new_saturating(self.global_notification_count(user_id).await);
103
104	if self.sent_badge(user_id, &pusher.ids.pushkey) == Some(unread) {
105		return Ok(());
106	}
107
108	let device = self.prepare_http_pusher(pusher, http)?;
109	let mut notify = Notification::new(vec![device]);
110	notify.counts = NotificationCounts::new_explicit(Some(unread), None);
111
112	self.send_http_notice(user_id, pusher, http, notify, Some(unread))
113		.await
114}
115
116#[implement(super::Service)]
117#[tracing::instrument(level = "debug", skip_all)]
118async fn send_notice<Pdu: Event>(
119	&self,
120	user_id: &UserId,
121	pusher: &Pusher,
122	tweaks: Vec<Tweak>,
123	event: &Pdu,
124) -> Result {
125	// TODO: email
126	match &pusher.kind {
127		| PusherKind::Http(http) =>
128			self.send_http_event_notice(user_id, pusher, http, tweaks, event)
129				.await,
130		// TODO: Handle email
131		//PusherKind::Email(_) => Ok(()),
132		| _ => Ok(()),
133	}
134}
135
136#[implement(super::Service)]
137async fn send_http_event_notice<Pdu: Event>(
138	&self,
139	user_id: &UserId,
140	pusher: &Pusher,
141	http: &HttpPusherData,
142	tweaks: Vec<Tweak>,
143	event: &Pdu,
144) -> Result {
145	let mut device = self.prepare_http_pusher(pusher, http)?;
146
147	// TODO (timo): can pusher/devices have conflicting formats
148	let event_id_only = http.format == Some(PushFormat::EventIdOnly);
149
150	if !event_id_only {
151		device.tweaks.clone_from(&tweaks);
152	}
153
154	let mut notify = Notification::new(vec![device]);
155
156	notify.event_id = Some(event.event_id().to_owned());
157	notify.room_id = Some(event.room_id().to_owned());
158
159	let unread = badge_count_disabled(http)
160		.is_false()
161		.then_async(async || UInt::new_saturating(self.global_notification_count(user_id).await));
162
163	let unread = if !event_id_only {
164		if *event.kind() == TimelineEventType::RoomEncrypted
165			|| tweaks.iter().any(|t| {
166				matches!(t, Tweak::Highlight(HighlightTweakValue::Yes) | Tweak::Sound(_))
167			}) {
168			notify.prio = NotificationPriority::High;
169		} else {
170			notify.prio = NotificationPriority::Low;
171		}
172		notify.sender = Some(event.sender().to_owned());
173		notify.event_type = Some(event.kind().to_owned());
174		notify.content = serde_json::value::to_raw_value(event.content()).ok();
175
176		if *event.kind() == TimelineEventType::RoomMember {
177			notify.user_is_target = event.state_key() == Some(user_id.as_str());
178		}
179
180		let (display_name, room_name, room_alias, unread) = join4(
181			self.services.profile.displayname(event.sender()),
182			self.services
183				.state_accessor
184				.get_name(event.room_id()),
185			self.services
186				.state_accessor
187				.get_canonical_alias(event.room_id()),
188			unread,
189		)
190		.await;
191
192		notify.sender_display_name = display_name.ok();
193		notify.room_name = room_name.ok();
194		notify.room_alias = room_alias.ok();
195
196		unread
197	} else {
198		unread.await
199	};
200
201	if let Some(unread) = unread {
202		notify.counts = NotificationCounts::new_explicit(Some(unread), None);
203	}
204
205	self.send_http_notice(user_id, pusher, http, notify, unread)
206		.await
207}
208
209#[implement(super::Service)]
210fn prepare_http_pusher(&self, pusher: &Pusher, http: &HttpPusherData) -> Result<Device> {
211	let address = &http.url;
212	let url = Url::parse(address).map_err(|e| {
213		err!(Request(InvalidParam(
214			warn!(url = %address, error = %e, "HTTP pusher URL is not a valid URL")
215		)))
216	})?;
217
218	self.check_http_pusher_url(&url)?;
219
220	let mut device = Device::new(pusher.ids.app_id.clone(), pusher.ids.pushkey.clone());
221	device.data.data.clone_from(&http.data);
222	device.data.format.clone_from(&http.format);
223
224	Ok(device)
225}
226
227/// Deliver one notification to the pusher's gateway and honor its verdict.
228///
229/// A pushkey the gateway names in `rejected` has its pusher removed. `unread`
230/// names the counts value on the wire; it is recorded as delivered only after
231/// the gateway accepts, so a failed or rejected send leaves the next refresh
232/// unconditional.
233#[implement(super::Service)]
234#[tracing::instrument(level = "debug", skip_all)]
235async fn send_http_notice(
236	&self,
237	user_id: &UserId,
238	pusher: &Pusher,
239	http: &HttpPusherData,
240	notify: Notification,
241	unread: Option<UInt>,
242) -> Result {
243	let response = self
244		.send_request(&http.url, Request::new(notify))
245		.await?;
246
247	let pushkey = &pusher.ids.pushkey;
248
249	if response.rejected.contains(pushkey) {
250		error!(
251			url = %http.url,
252			%pushkey,
253			"Push gateway rejected the pushkey; removing the pusher. Push notifications \
254			 for this device stop until the client registers a new pusher.",
255		);
256
257		self.delete_pusher(user_id, pushkey).await;
258
259		return Ok(());
260	}
261
262	if let Some(unread) = unread {
263		self.record_sent_badge(user_id, pushkey, unread);
264	}
265
266	Ok(())
267}
268
269fn badge_count_disabled(http: &HttpPusherData) -> bool {
270	["org.matrix.msc4076.disable_badge_count", "disable_badge_count"]
271		.iter()
272		.any(|key| http.data.get(*key).and_then(Value::as_bool) == Some(true))
273}