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

Commit 2ee17d7

Browse files
committed
Refactor jinja2 templating. Remove old XXX comment
1 parent 2253193 commit 2ee17d7

File tree

6 files changed

+90
-61
lines changed

6 files changed

+90
-61
lines changed

synapse/handlers/account_validity.py

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@
3838
class AccountValidityHandler(object):
3939
def __init__(self, hs):
4040
self.hs = hs
41+
self.config = hs.config
4142
self.store = self.hs.get_datastore()
4243
self.sendmail = self.hs.get_sendmail()
4344
self.clock = self.hs.get_clock()
@@ -62,9 +63,14 @@ def __init__(self, hs):
6263
self._raw_from = email.utils.parseaddr(self._from_string)[1]
6364

6465
self._template_html, self._template_text = load_jinja2_templates(
65-
config=self.hs.config,
66-
template_html_name=self.hs.config.email_expiry_template_html,
67-
template_text_name=self.hs.config.email_expiry_template_text,
66+
self.config.email_template_dir,
67+
[
68+
self.config.email_expiry_template_html,
69+
self.config.email_expiry_template_text,
70+
],
71+
apply_format_ts_filter=True,
72+
apply_mxc_to_http_filter=True,
73+
public_baseurl=self.config.public_baseurl,
6874
)
6975

7076
# Check the renewal emails to send and send them every 30min.

synapse/handlers/auth.py

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -363,8 +363,6 @@ def _check_auth_dict(self, authdict, clientip):
363363
login_type = authdict["type"]
364364
checker = self.checkers.get(login_type)
365365
if checker is not None:
366-
# XXX: Temporary workaround for having Synapse handle password resets
367-
# See AuthHandler.check_auth for further details
368366
res = yield checker(authdict, clientip=clientip)
369367
return res
370368

synapse/push/mailer.py

Lines changed: 30 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -629,46 +629,50 @@ def format_ts_filter(value, format):
629629
return time.strftime(format, time.localtime(value / 1000))
630630

631631

632-
# XXX: This method and the next could likely be combined in a smarter way
633-
@staticmethod
634-
def load_jinja2_template(template_dir, template_filename, template_vars):
632+
def load_jinja2_templates(
633+
template_dir,
634+
template_filenames,
635+
apply_format_ts_filter=False,
636+
apply_mxc_to_http_filter=False,
637+
public_baseurl=None,
638+
):
635639
"""Loads a jinja2 template with variables to insert
636640
637641
Args:
638642
template_dir (str): The directory where templates are stored
639-
template_filename (str): The name of the template in the template_dir
640-
template_vars (Dict): Dictionary of keys in the template
641-
alongside their values to insert
643+
template_filenames (list[str]): A list of template filenames
644+
apply_format_ts_filter (bool): Whether to apply a template filter that formats
645+
timestamps
646+
apply_mxc_to_http_filter (bool): Whether to apply a template filter that converts
647+
mxc urls to http urls
648+
public_baseurl (str|None): The public baseurl of the server. Required for
649+
apply_mxc_to_http_filter to be enabled
642650
643651
Returns:
644-
str containing the contents of the rendered template
652+
A list of jinja2 templates corresponding to the given list of filepaths,
653+
with order preserved
645654
"""
655+
logger.info(
656+
"loading email templates %s from '%s'", template_filenames, template_dir
657+
)
646658
loader = jinja2.FileSystemLoader(template_dir)
647659
env = jinja2.Environment(loader=loader)
648660

649-
template = env.get_template(template_filename)
650-
return template.render(**template_vars)
651-
652-
653-
def load_jinja2_templates(config, template_html_name, template_text_name):
654-
"""Load the jinja2 email templates from disk
661+
if apply_format_ts_filter:
662+
env.filters["format_ts"] = format_ts_filter
655663

656-
Returns:
657-
(template_html, template_text)
658-
"""
659-
logger.info("loading email templates from '%s'", config.email_template_dir)
660-
loader = jinja2.FileSystemLoader(config.email_template_dir)
661-
env = jinja2.Environment(loader=loader)
662-
env.filters["format_ts"] = format_ts_filter
663-
env.filters["mxc_to_http"] = _create_mxc_to_http_filter(config)
664+
if apply_mxc_to_http_filter and public_baseurl:
665+
env.filters["mxc_to_http"] = _create_mxc_to_http_filter(public_baseurl)
664666

665-
template_html = env.get_template(template_html_name)
666-
template_text = env.get_template(template_text_name)
667+
templates = []
668+
for template_filename in template_filenames:
669+
template = env.get_template(template_filename)
670+
templates.append(template)
667671

668-
return template_html, template_text
672+
return templates
669673

670674

671-
def _create_mxc_to_http_filter(config):
675+
def _create_mxc_to_http_filter(public_baseurl):
672676
def mxc_to_http_filter(value, width, height, resize_method="crop"):
673677
if value[0:6] != "mxc://":
674678
return ""
@@ -681,7 +685,7 @@ def mxc_to_http_filter(value, width, height, resize_method="crop"):
681685

682686
params = {"width": width, "height": height, "method": resize_method}
683687
return "%s_matrix/media/v1/thumbnail/%s?%s%s" % (
684-
config.public_baseurl,
688+
public_baseurl,
685689
serverAndMediaId,
686690
urllib.parse.urlencode(params),
687691
fragment or "",

synapse/push/pusher.py

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,24 @@
3535
class PusherFactory(object):
3636
def __init__(self, hs):
3737
self.hs = hs
38+
self.config = hs.config
3839

3940
self.pusher_types = {"http": HttpPusher}
4041

4142
logger.info("email enable notifs: %r", hs.config.email_enable_notifs)
4243
if hs.config.email_enable_notifs:
4344
self.mailers = {} # app_name -> Mailer
4445

45-
templates = load_jinja2_templates(
46-
config=hs.config,
47-
template_html_name=hs.config.email_notif_template_html,
48-
template_text_name=hs.config.email_notif_template_text,
46+
self.notif_template_html, self.notif_template_text = load_jinja2_templates(
47+
self.config.email_template_dir,
48+
[
49+
self.config.email_notif_template_html,
50+
self.config.email_notif_template_text,
51+
],
52+
apply_format_ts_filter=True,
53+
apply_mxc_to_http_filter=True,
54+
public_baseurl=self.config.public_baseurl,
4955
)
50-
self.notif_template_html, self.notif_template_text = templates
5156

5257
self.pusher_types["email"] = self._create_email_pusher
5358

@@ -78,6 +83,6 @@ def _app_name_from_pusherdict(self, pusherdict):
7883
if "data" in pusherdict and "brand" in pusherdict["data"]:
7984
app_name = pusherdict["data"]["brand"]
8085
else:
81-
app_name = self.hs.config.email_app_name
86+
app_name = self.config.email_app_name
8287

8388
return app_name

synapse/rest/client/v2_alpha/account.py

Lines changed: 19 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@
3030
parse_json_object_from_request,
3131
parse_string,
3232
)
33-
from synapse.push.mailer import load_jinja2_template
33+
from synapse.push.mailer import load_jinja2_templates
3434
from synapse.util.msisdn import phone_number_to_msisdn
3535
from synapse.util.threepids import check_3pid_allowed
3636

@@ -52,16 +52,21 @@ def __init__(self, hs):
5252
if self.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
5353
from synapse.push.mailer import Mailer, load_jinja2_templates
5454

55-
templates = load_jinja2_templates(
56-
config=hs.config,
57-
template_html_name=hs.config.email_password_reset_template_html,
58-
template_text_name=hs.config.email_password_reset_template_text,
55+
template_html, template_text = load_jinja2_templates(
56+
self.config.email_template_dir,
57+
[
58+
self.config.email_password_reset_template_html,
59+
self.config.email_password_reset_template_text,
60+
],
61+
apply_format_ts_filter=True,
62+
apply_mxc_to_http_filter=True,
63+
public_baseurl=self.config.public_baseurl,
5964
)
6065
self.mailer = Mailer(
6166
hs=self.hs,
6267
app_name=self.config.email_app_name,
63-
template_html=templates[0],
64-
template_text=templates[1],
68+
template_html=template_html,
69+
template_text=template_text,
6570
)
6671

6772
@defer.inlineCallbacks
@@ -255,13 +260,16 @@ def on_GET(self, request, medium):
255260
html = self.config.email_password_reset_template_success_html
256261
request.setResponseCode(200)
257262
except ThreepidValidationError as e:
263+
request.setResponseCode(e.code)
264+
258265
# Show a failure page with a reason
259-
html = load_jinja2_template(
266+
html_template = load_jinja2_templates(
260267
self.config.email_template_dir,
261-
self.config.email_password_reset_template_failure_html,
262-
template_vars={"failure_reason": e.msg},
268+
[self.config.email_password_reset_template_failure_html],
263269
)
264-
request.setResponseCode(e.code)
270+
271+
template_vars = {"failure_reason": e.msg}
272+
html = html_template.render(**template_vars)
265273

266274
request.write(html.encode("utf-8"))
267275
finish_request(request)

synapse/rest/client/v2_alpha/register.py

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@
4141
parse_json_object_from_request,
4242
parse_string,
4343
)
44-
from synapse.push.mailer import load_jinja2_template
44+
from synapse.push.mailer import load_jinja2_templates
4545
from synapse.util.msisdn import phone_number_to_msisdn
4646
from synapse.util.ratelimitutils import FederationRateLimiter
4747
from synapse.util.threepids import check_3pid_allowed
@@ -79,16 +79,21 @@ def __init__(self, hs):
7979
if self.hs.config.threepid_behaviour_email == ThreepidBehaviour.LOCAL:
8080
from synapse.push.mailer import Mailer, load_jinja2_templates
8181

82-
templates = load_jinja2_templates(
83-
config=hs.config,
84-
template_html_name=hs.config.email_registration_template_html,
85-
template_text_name=hs.config.email_registration_template_text,
82+
template_html, template_text = load_jinja2_templates(
83+
self.config.email_template_dir,
84+
[
85+
self.config.email_registration_template_html,
86+
self.config.email_registration_template_text,
87+
],
88+
apply_format_ts_filter=True,
89+
apply_mxc_to_http_filter=True,
90+
public_baseurl=self.config.public_baseurl,
8691
)
8792
self.mailer = Mailer(
8893
hs=self.hs,
89-
app_name=self.hs.config.email_app_name,
90-
template_html=templates[0],
91-
template_text=templates[1],
94+
app_name=self.config.email_app_name,
95+
template_html=template_html,
96+
template_text=template_text,
9297
)
9398

9499
@defer.inlineCallbacks
@@ -285,16 +290,19 @@ def on_GET(self, request, medium):
285290
request.setResponseCode(200)
286291
except ThreepidValidationError as e:
287292
# Show a failure page with a reason
288-
html = load_jinja2_template(
293+
request.setResponseCode(e.code)
294+
295+
# Show a failure page with a reason
296+
html_template = load_jinja2_templates(
289297
self.config.email_template_dir,
290-
self.config.email_registration_template_failure_html,
291-
template_vars={"failure_reason": e.msg},
298+
[self.config.email_registration_template_failure_html],
292299
)
293-
request.setResponseCode(e.code)
300+
301+
template_vars = {"failure_reason": e.msg}
302+
html = html_template.render(**template_vars)
294303

295304
request.write(html.encode("utf-8"))
296305
finish_request(request)
297-
return None
298306

299307

300308
class UsernameAvailabilityRestServlet(RestServlet):

0 commit comments

Comments
 (0)