Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit a948122

Browse files
Bubusquahtx
andauthored
Improved push typing (#11409)
Co-authored-by: Sean Quah <[email protected]>
1 parent 35b1900 commit a948122

File tree

7 files changed

+210
-36
lines changed

7 files changed

+210
-36
lines changed

changelog.d/11409.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve internal types in push code.

docs/templates.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,12 @@ Below are the templates Synapse will look for when generating the content of an
7171
* `sender_avatar_url`: the avatar URL (as a `mxc://` URL) for the event's
7272
sender
7373
* `sender_hash`: a hash of the user ID of the sender
74+
* `msgtype`: the type of the message
75+
* `body_text_html`: html representation of the message
76+
* `body_text_plain`: plaintext representation of the message
77+
* `image_url`: mxc url of an image, when "msgtype" is "m.image"
7478
* `link`: a `matrix.to` link to the room
79+
* `avator_url`: url to the room's avator
7580
* `reason`: information on the event that triggered the email to be sent. It's an
7681
object with the following attributes:
7782
* `room_id`: the ID of the room the event was sent in

synapse/push/emailpusher.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,8 @@
2121
from synapse.metrics.background_process_metrics import run_as_background_process
2222
from synapse.push import Pusher, PusherConfig, PusherConfigException, ThrottleParams
2323
from synapse.push.mailer import Mailer
24+
from synapse.push.push_types import EmailReason
25+
from synapse.storage.databases.main.event_push_actions import EmailPushAction
2426
from synapse.util.threepids import validate_email
2527

2628
if TYPE_CHECKING:
@@ -190,7 +192,7 @@ async def _unsafe_process(self) -> None:
190192
# we then consider all previously outstanding notifications
191193
# to be delivered.
192194

193-
reason = {
195+
reason: EmailReason = {
194196
"room_id": push_action["room_id"],
195197
"now": self.clock.time_msec(),
196198
"received_at": received_at,
@@ -275,7 +277,7 @@ def room_ready_to_notify_at(self, room_id: str) -> int:
275277
return may_send_at
276278

277279
async def sent_notif_update_throttle(
278-
self, room_id: str, notified_push_action: dict
280+
self, room_id: str, notified_push_action: EmailPushAction
279281
) -> None:
280282
# We have sent a notification, so update the throttle accordingly.
281283
# If the event that triggered the notif happened more than
@@ -315,7 +317,9 @@ async def sent_notif_update_throttle(
315317
self.pusher_id, room_id, self.throttle_params[room_id]
316318
)
317319

318-
async def send_notification(self, push_actions: List[dict], reason: dict) -> None:
320+
async def send_notification(
321+
self, push_actions: List[EmailPushAction], reason: EmailReason
322+
) -> None:
319323
logger.info("Sending notif email for user %r", self.user_id)
320324

321325
await self.mailer.send_notification_mail(

synapse/push/httppusher.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
from synapse.logging import opentracing
2727
from synapse.metrics.background_process_metrics import run_as_background_process
2828
from synapse.push import Pusher, PusherConfig, PusherConfigException
29+
from synapse.storage.databases.main.event_push_actions import HttpPushAction
2930

3031
from . import push_rule_evaluator, push_tools
3132

@@ -273,7 +274,7 @@ async def _unsafe_process(self) -> None:
273274
)
274275
break
275276

276-
async def _process_one(self, push_action: dict) -> bool:
277+
async def _process_one(self, push_action: HttpPushAction) -> bool:
277278
if "notify" not in push_action["actions"]:
278279
return True
279280

synapse/push/mailer.py

Lines changed: 42 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414

1515
import logging
1616
import urllib.parse
17-
from typing import TYPE_CHECKING, Any, Dict, Iterable, List, Optional, TypeVar
17+
from typing import TYPE_CHECKING, Dict, Iterable, List, Optional, TypeVar
1818

1919
import bleach
2020
import jinja2
@@ -28,6 +28,14 @@
2828
descriptor_from_member_events,
2929
name_from_member_event,
3030
)
31+
from synapse.push.push_types import (
32+
EmailReason,
33+
MessageVars,
34+
NotifVars,
35+
RoomVars,
36+
TemplateVars,
37+
)
38+
from synapse.storage.databases.main.event_push_actions import EmailPushAction
3139
from synapse.storage.state import StateFilter
3240
from synapse.types import StateMap, UserID
3341
from synapse.util.async_helpers import concurrently_execute
@@ -135,7 +143,7 @@ async def send_password_reset_mail(
135143
% urllib.parse.urlencode(params)
136144
)
137145

138-
template_vars = {"link": link}
146+
template_vars: TemplateVars = {"link": link}
139147

140148
await self.send_email(
141149
email_address,
@@ -165,7 +173,7 @@ async def send_registration_mail(
165173
% urllib.parse.urlencode(params)
166174
)
167175

168-
template_vars = {"link": link}
176+
template_vars: TemplateVars = {"link": link}
169177

170178
await self.send_email(
171179
email_address,
@@ -196,7 +204,7 @@ async def send_add_threepid_mail(
196204
% urllib.parse.urlencode(params)
197205
)
198206

199-
template_vars = {"link": link}
207+
template_vars: TemplateVars = {"link": link}
200208

201209
await self.send_email(
202210
email_address,
@@ -210,8 +218,8 @@ async def send_notification_mail(
210218
app_id: str,
211219
user_id: str,
212220
email_address: str,
213-
push_actions: Iterable[Dict[str, Any]],
214-
reason: Dict[str, Any],
221+
push_actions: Iterable[EmailPushAction],
222+
reason: EmailReason,
215223
) -> None:
216224
"""
217225
Send email regarding a user's room notifications
@@ -230,7 +238,7 @@ async def send_notification_mail(
230238
[pa["event_id"] for pa in push_actions]
231239
)
232240

233-
notifs_by_room: Dict[str, List[Dict[str, Any]]] = {}
241+
notifs_by_room: Dict[str, List[EmailPushAction]] = {}
234242
for pa in push_actions:
235243
notifs_by_room.setdefault(pa["room_id"], []).append(pa)
236244

@@ -258,7 +266,7 @@ async def _fetch_room_state(room_id: str) -> None:
258266
# actually sort our so-called rooms_in_order list, most recent room first
259267
rooms_in_order.sort(key=lambda r: -(notifs_by_room[r][-1]["received_ts"] or 0))
260268

261-
rooms: List[Dict[str, Any]] = []
269+
rooms: List[RoomVars] = []
262270

263271
for r in rooms_in_order:
264272
roomvars = await self._get_room_vars(
@@ -289,7 +297,7 @@ async def _fetch_room_state(room_id: str) -> None:
289297
notifs_by_room, state_by_room, notif_events, reason
290298
)
291299

292-
template_vars = {
300+
template_vars: TemplateVars = {
293301
"user_display_name": user_display_name,
294302
"unsubscribe_link": self._make_unsubscribe_link(
295303
user_id, app_id, email_address
@@ -302,10 +310,10 @@ async def _fetch_room_state(room_id: str) -> None:
302310
await self.send_email(email_address, summary_text, template_vars)
303311

304312
async def send_email(
305-
self, email_address: str, subject: str, extra_template_vars: Dict[str, Any]
313+
self, email_address: str, subject: str, extra_template_vars: TemplateVars
306314
) -> None:
307315
"""Send an email with the given information and template text"""
308-
template_vars = {
316+
template_vars: TemplateVars = {
309317
"app_name": self.app_name,
310318
"server_name": self.hs.config.server.server_name,
311319
}
@@ -327,10 +335,10 @@ async def _get_room_vars(
327335
self,
328336
room_id: str,
329337
user_id: str,
330-
notifs: Iterable[Dict[str, Any]],
338+
notifs: Iterable[EmailPushAction],
331339
notif_events: Dict[str, EventBase],
332340
room_state_ids: StateMap[str],
333-
) -> Dict[str, Any]:
341+
) -> RoomVars:
334342
"""
335343
Generate the variables for notifications on a per-room basis.
336344
@@ -356,7 +364,7 @@ async def _get_room_vars(
356364

357365
room_name = await calculate_room_name(self.store, room_state_ids, user_id)
358366

359-
room_vars: Dict[str, Any] = {
367+
room_vars: RoomVars = {
360368
"title": room_name,
361369
"hash": string_ordinal_total(room_id), # See sender avatar hash
362370
"notifs": [],
@@ -417,11 +425,11 @@ async def _get_room_avatar(
417425

418426
async def _get_notif_vars(
419427
self,
420-
notif: Dict[str, Any],
428+
notif: EmailPushAction,
421429
user_id: str,
422430
notif_event: EventBase,
423431
room_state_ids: StateMap[str],
424-
) -> Dict[str, Any]:
432+
) -> NotifVars:
425433
"""
426434
Generate the variables for a single notification.
427435
@@ -442,7 +450,7 @@ async def _get_notif_vars(
442450
after_limit=CONTEXT_AFTER,
443451
)
444452

445-
ret = {
453+
ret: NotifVars = {
446454
"link": self._make_notif_link(notif),
447455
"ts": notif["received_ts"],
448456
"messages": [],
@@ -461,8 +469,8 @@ async def _get_notif_vars(
461469
return ret
462470

463471
async def _get_message_vars(
464-
self, notif: Dict[str, Any], event: EventBase, room_state_ids: StateMap[str]
465-
) -> Optional[Dict[str, Any]]:
472+
self, notif: EmailPushAction, event: EventBase, room_state_ids: StateMap[str]
473+
) -> Optional[MessageVars]:
466474
"""
467475
Generate the variables for a single event, if possible.
468476
@@ -494,7 +502,9 @@ async def _get_message_vars(
494502

495503
if sender_state_event:
496504
sender_name = name_from_member_event(sender_state_event)
497-
sender_avatar_url = sender_state_event.content.get("avatar_url")
505+
sender_avatar_url: Optional[str] = sender_state_event.content.get(
506+
"avatar_url"
507+
)
498508
else:
499509
# No state could be found, fallback to the MXID.
500510
sender_name = event.sender
@@ -504,7 +514,7 @@ async def _get_message_vars(
504514
# sender_hash % the number of default images to choose from
505515
sender_hash = string_ordinal_total(event.sender)
506516

507-
ret = {
517+
ret: MessageVars = {
508518
"event_type": event.type,
509519
"is_historical": event.event_id != notif["event_id"],
510520
"id": event.event_id,
@@ -519,6 +529,8 @@ async def _get_message_vars(
519529
return ret
520530

521531
msgtype = event.content.get("msgtype")
532+
if not isinstance(msgtype, str):
533+
msgtype = None
522534

523535
ret["msgtype"] = msgtype
524536

@@ -533,7 +545,7 @@ async def _get_message_vars(
533545
return ret
534546

535547
def _add_text_message_vars(
536-
self, messagevars: Dict[str, Any], event: EventBase
548+
self, messagevars: MessageVars, event: EventBase
537549
) -> None:
538550
"""
539551
Potentially add a sanitised message body to the message variables.
@@ -543,8 +555,8 @@ def _add_text_message_vars(
543555
event: The event under consideration.
544556
"""
545557
msgformat = event.content.get("format")
546-
547-
messagevars["format"] = msgformat
558+
if not isinstance(msgformat, str):
559+
msgformat = None
548560

549561
formatted_body = event.content.get("formatted_body")
550562
body = event.content.get("body")
@@ -555,7 +567,7 @@ def _add_text_message_vars(
555567
messagevars["body_text_html"] = safe_text(body)
556568

557569
def _add_image_message_vars(
558-
self, messagevars: Dict[str, Any], event: EventBase
570+
self, messagevars: MessageVars, event: EventBase
559571
) -> None:
560572
"""
561573
Potentially add an image URL to the message variables.
@@ -570,7 +582,7 @@ def _add_image_message_vars(
570582
async def _make_summary_text_single_room(
571583
self,
572584
room_id: str,
573-
notifs: List[Dict[str, Any]],
585+
notifs: List[EmailPushAction],
574586
room_state_ids: StateMap[str],
575587
notif_events: Dict[str, EventBase],
576588
user_id: str,
@@ -685,10 +697,10 @@ async def _make_summary_text_single_room(
685697

686698
async def _make_summary_text(
687699
self,
688-
notifs_by_room: Dict[str, List[Dict[str, Any]]],
700+
notifs_by_room: Dict[str, List[EmailPushAction]],
689701
room_state_ids: Dict[str, StateMap[str]],
690702
notif_events: Dict[str, EventBase],
691-
reason: Dict[str, Any],
703+
reason: EmailReason,
692704
) -> str:
693705
"""
694706
Make a summary text for the email when multiple rooms have notifications.
@@ -718,7 +730,7 @@ async def _make_summary_text(
718730
async def _make_summary_text_from_member_events(
719731
self,
720732
room_id: str,
721-
notifs: List[Dict[str, Any]],
733+
notifs: List[EmailPushAction],
722734
room_state_ids: StateMap[str],
723735
notif_events: Dict[str, EventBase],
724736
) -> str:
@@ -805,7 +817,7 @@ def _make_room_link(self, room_id: str) -> str:
805817
base_url = "https://matrix.to/#"
806818
return "%s/%s" % (base_url, room_id)
807819

808-
def _make_notif_link(self, notif: Dict[str, str]) -> str:
820+
def _make_notif_link(self, notif: EmailPushAction) -> str:
809821
"""
810822
Generate a link to open an event in the web client.
811823

0 commit comments

Comments
 (0)