mailer.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. import email.mime.multipart
  16. import email.utils
  17. import logging
  18. import time
  19. import urllib
  20. from email.mime.multipart import MIMEMultipart
  21. from email.mime.text import MIMEText
  22. from typing import Iterable, List, TypeVar
  23. import bleach
  24. import jinja2
  25. from synapse.api.constants import EventTypes
  26. from synapse.api.errors import StoreError
  27. from synapse.logging.context import make_deferred_yieldable
  28. from synapse.push.presentable_names import (
  29. calculate_room_name,
  30. descriptor_from_member_events,
  31. name_from_member_event,
  32. )
  33. from synapse.types import UserID
  34. from synapse.util.async_helpers import concurrently_execute
  35. from synapse.visibility import filter_events_for_client
  36. logger = logging.getLogger(__name__)
  37. T = TypeVar("T")
  38. MESSAGE_FROM_PERSON_IN_ROOM = (
  39. "You have a message on %(app)s from %(person)s in the %(room)s room..."
  40. )
  41. MESSAGE_FROM_PERSON = "You have a message on %(app)s from %(person)s..."
  42. MESSAGES_FROM_PERSON = "You have messages on %(app)s from %(person)s..."
  43. MESSAGES_IN_ROOM = "You have messages on %(app)s in the %(room)s room..."
  44. MESSAGES_IN_ROOM_AND_OTHERS = (
  45. "You have messages on %(app)s in the %(room)s room and others..."
  46. )
  47. MESSAGES_FROM_PERSON_AND_OTHERS = (
  48. "You have messages on %(app)s from %(person)s and others..."
  49. )
  50. INVITE_FROM_PERSON_TO_ROOM = (
  51. "%(person)s has invited you to join the %(room)s room on %(app)s..."
  52. )
  53. INVITE_FROM_PERSON = "%(person)s has invited you to chat on %(app)s..."
  54. CONTEXT_BEFORE = 1
  55. CONTEXT_AFTER = 1
  56. # From https://github.com/matrix-org/matrix-react-sdk/blob/master/src/HtmlUtils.js
  57. ALLOWED_TAGS = [
  58. "font", # custom to matrix for IRC-style font coloring
  59. "del", # for markdown
  60. # deliberately no h1/h2 to stop people shouting.
  61. "h3",
  62. "h4",
  63. "h5",
  64. "h6",
  65. "blockquote",
  66. "p",
  67. "a",
  68. "ul",
  69. "ol",
  70. "nl",
  71. "li",
  72. "b",
  73. "i",
  74. "u",
  75. "strong",
  76. "em",
  77. "strike",
  78. "code",
  79. "hr",
  80. "br",
  81. "div",
  82. "table",
  83. "thead",
  84. "caption",
  85. "tbody",
  86. "tr",
  87. "th",
  88. "td",
  89. "pre",
  90. ]
  91. ALLOWED_ATTRS = {
  92. # custom ones first:
  93. "font": ["color"], # custom to matrix
  94. "a": ["href", "name", "target"], # remote target: custom to matrix
  95. # We don't currently allow img itself by default, but this
  96. # would make sense if we did
  97. "img": ["src"],
  98. }
  99. # When bleach release a version with this option, we can specify schemes
  100. # ALLOWED_SCHEMES = ["http", "https", "ftp", "mailto"]
  101. class Mailer(object):
  102. def __init__(self, hs, app_name, template_html, template_text):
  103. self.hs = hs
  104. self.template_html = template_html
  105. self.template_text = template_text
  106. self.sendmail = self.hs.get_sendmail()
  107. self.store = self.hs.get_datastore()
  108. self.macaroon_gen = self.hs.get_macaroon_generator()
  109. self.state_handler = self.hs.get_state_handler()
  110. self.storage = hs.get_storage()
  111. self.app_name = app_name
  112. logger.info("Created Mailer for app_name %s" % app_name)
  113. async def send_password_reset_mail(self, email_address, token, client_secret, sid):
  114. """Send an email with a password reset link to a user
  115. Args:
  116. email_address (str): Email address we're sending the password
  117. reset to
  118. token (str): Unique token generated by the server to verify
  119. the email was received
  120. client_secret (str): Unique token generated by the client to
  121. group together multiple email sending attempts
  122. sid (str): The generated session ID
  123. """
  124. params = {"token": token, "client_secret": client_secret, "sid": sid}
  125. link = (
  126. self.hs.config.public_baseurl
  127. + "_matrix/client/unstable/password_reset/email/submit_token?%s"
  128. % urllib.parse.urlencode(params)
  129. )
  130. template_vars = {"link": link}
  131. await self.send_email(
  132. email_address,
  133. "[%s] Password Reset" % self.hs.config.server_name,
  134. template_vars,
  135. )
  136. async def send_registration_mail(self, email_address, token, client_secret, sid):
  137. """Send an email with a registration confirmation link to a user
  138. Args:
  139. email_address (str): Email address we're sending the registration
  140. link to
  141. token (str): Unique token generated by the server to verify
  142. the email was received
  143. client_secret (str): Unique token generated by the client to
  144. group together multiple email sending attempts
  145. sid (str): The generated session ID
  146. """
  147. params = {"token": token, "client_secret": client_secret, "sid": sid}
  148. link = (
  149. self.hs.config.public_baseurl
  150. + "_matrix/client/unstable/registration/email/submit_token?%s"
  151. % urllib.parse.urlencode(params)
  152. )
  153. template_vars = {"link": link}
  154. await self.send_email(
  155. email_address,
  156. "[%s] Register your Email Address" % self.hs.config.server_name,
  157. template_vars,
  158. )
  159. async def send_add_threepid_mail(self, email_address, token, client_secret, sid):
  160. """Send an email with a validation link to a user for adding a 3pid to their account
  161. Args:
  162. email_address (str): Email address we're sending the validation link to
  163. token (str): Unique token generated by the server to verify the email was received
  164. client_secret (str): Unique token generated by the client to group together
  165. multiple email sending attempts
  166. sid (str): The generated session ID
  167. """
  168. params = {"token": token, "client_secret": client_secret, "sid": sid}
  169. link = (
  170. self.hs.config.public_baseurl
  171. + "_matrix/client/unstable/add_threepid/email/submit_token?%s"
  172. % urllib.parse.urlencode(params)
  173. )
  174. template_vars = {"link": link}
  175. await self.send_email(
  176. email_address,
  177. "[%s] Validate Your Email" % self.hs.config.server_name,
  178. template_vars,
  179. )
  180. async def send_notification_mail(
  181. self, app_id, user_id, email_address, push_actions, reason
  182. ):
  183. """Send email regarding a user's room notifications"""
  184. rooms_in_order = deduped_ordered_list([pa["room_id"] for pa in push_actions])
  185. notif_events = await self.store.get_events(
  186. [pa["event_id"] for pa in push_actions]
  187. )
  188. notifs_by_room = {}
  189. for pa in push_actions:
  190. notifs_by_room.setdefault(pa["room_id"], []).append(pa)
  191. # collect the current state for all the rooms in which we have
  192. # notifications
  193. state_by_room = {}
  194. try:
  195. user_display_name = await self.store.get_profile_displayname(
  196. UserID.from_string(user_id).localpart
  197. )
  198. if user_display_name is None:
  199. user_display_name = user_id
  200. except StoreError:
  201. user_display_name = user_id
  202. async def _fetch_room_state(room_id):
  203. room_state = await self.store.get_current_state_ids(room_id)
  204. state_by_room[room_id] = room_state
  205. # Run at most 3 of these at once: sync does 10 at a time but email
  206. # notifs are much less realtime than sync so we can afford to wait a bit.
  207. await concurrently_execute(_fetch_room_state, rooms_in_order, 3)
  208. # actually sort our so-called rooms_in_order list, most recent room first
  209. rooms_in_order.sort(key=lambda r: -(notifs_by_room[r][-1]["received_ts"] or 0))
  210. rooms = []
  211. for r in rooms_in_order:
  212. roomvars = await self.get_room_vars(
  213. r, user_id, notifs_by_room[r], notif_events, state_by_room[r]
  214. )
  215. rooms.append(roomvars)
  216. reason["room_name"] = await calculate_room_name(
  217. self.store,
  218. state_by_room[reason["room_id"]],
  219. user_id,
  220. fallback_to_members=True,
  221. )
  222. summary_text = await self.make_summary_text(
  223. notifs_by_room, state_by_room, notif_events, user_id, reason
  224. )
  225. template_vars = {
  226. "user_display_name": user_display_name,
  227. "unsubscribe_link": self.make_unsubscribe_link(
  228. user_id, app_id, email_address
  229. ),
  230. "summary_text": summary_text,
  231. "app_name": self.app_name,
  232. "rooms": rooms,
  233. "reason": reason,
  234. }
  235. await self.send_email(
  236. email_address, "[%s] %s" % (self.app_name, summary_text), template_vars
  237. )
  238. async def send_email(self, email_address, subject, template_vars):
  239. """Send an email with the given information and template text"""
  240. try:
  241. from_string = self.hs.config.email_notif_from % {"app": self.app_name}
  242. except TypeError:
  243. from_string = self.hs.config.email_notif_from
  244. raw_from = email.utils.parseaddr(from_string)[1]
  245. raw_to = email.utils.parseaddr(email_address)[1]
  246. if raw_to == "":
  247. raise RuntimeError("Invalid 'to' address")
  248. html_text = self.template_html.render(**template_vars)
  249. html_part = MIMEText(html_text, "html", "utf8")
  250. plain_text = self.template_text.render(**template_vars)
  251. text_part = MIMEText(plain_text, "plain", "utf8")
  252. multipart_msg = MIMEMultipart("alternative")
  253. multipart_msg["Subject"] = subject
  254. multipart_msg["From"] = from_string
  255. multipart_msg["To"] = email_address
  256. multipart_msg["Date"] = email.utils.formatdate()
  257. multipart_msg["Message-ID"] = email.utils.make_msgid()
  258. multipart_msg.attach(text_part)
  259. multipart_msg.attach(html_part)
  260. logger.info("Sending email to %s" % email_address)
  261. await make_deferred_yieldable(
  262. self.sendmail(
  263. self.hs.config.email_smtp_host,
  264. raw_from,
  265. raw_to,
  266. multipart_msg.as_string().encode("utf8"),
  267. reactor=self.hs.get_reactor(),
  268. port=self.hs.config.email_smtp_port,
  269. requireAuthentication=self.hs.config.email_smtp_user is not None,
  270. username=self.hs.config.email_smtp_user,
  271. password=self.hs.config.email_smtp_pass,
  272. requireTransportSecurity=self.hs.config.require_transport_security,
  273. )
  274. )
  275. async def get_room_vars(
  276. self, room_id, user_id, notifs, notif_events, room_state_ids
  277. ):
  278. my_member_event_id = room_state_ids[("m.room.member", user_id)]
  279. my_member_event = await self.store.get_event(my_member_event_id)
  280. is_invite = my_member_event.content["membership"] == "invite"
  281. room_name = await calculate_room_name(self.store, room_state_ids, user_id)
  282. room_vars = {
  283. "title": room_name,
  284. "hash": string_ordinal_total(room_id), # See sender avatar hash
  285. "notifs": [],
  286. "invite": is_invite,
  287. "link": self.make_room_link(room_id),
  288. }
  289. if not is_invite:
  290. for n in notifs:
  291. notifvars = await self.get_notif_vars(
  292. n, user_id, notif_events[n["event_id"]], room_state_ids
  293. )
  294. # merge overlapping notifs together.
  295. # relies on the notifs being in chronological order.
  296. merge = False
  297. if room_vars["notifs"] and "messages" in room_vars["notifs"][-1]:
  298. prev_messages = room_vars["notifs"][-1]["messages"]
  299. for message in notifvars["messages"]:
  300. pm = list(
  301. filter(lambda pm: pm["id"] == message["id"], prev_messages)
  302. )
  303. if pm:
  304. if not message["is_historical"]:
  305. pm[0]["is_historical"] = False
  306. merge = True
  307. elif merge:
  308. # we're merging, so append any remaining messages
  309. # in this notif to the previous one
  310. prev_messages.append(message)
  311. if not merge:
  312. room_vars["notifs"].append(notifvars)
  313. return room_vars
  314. async def get_notif_vars(self, notif, user_id, notif_event, room_state_ids):
  315. results = await self.store.get_events_around(
  316. notif["room_id"],
  317. notif["event_id"],
  318. before_limit=CONTEXT_BEFORE,
  319. after_limit=CONTEXT_AFTER,
  320. )
  321. ret = {
  322. "link": self.make_notif_link(notif),
  323. "ts": notif["received_ts"],
  324. "messages": [],
  325. }
  326. the_events = await filter_events_for_client(
  327. self.storage, user_id, results["events_before"]
  328. )
  329. the_events.append(notif_event)
  330. for event in the_events:
  331. messagevars = await self.get_message_vars(notif, event, room_state_ids)
  332. if messagevars is not None:
  333. ret["messages"].append(messagevars)
  334. return ret
  335. async def get_message_vars(self, notif, event, room_state_ids):
  336. if event.type != EventTypes.Message:
  337. return
  338. sender_state_event_id = room_state_ids[("m.room.member", event.sender)]
  339. sender_state_event = await self.store.get_event(sender_state_event_id)
  340. sender_name = name_from_member_event(sender_state_event)
  341. sender_avatar_url = sender_state_event.content.get("avatar_url")
  342. # 'hash' for deterministically picking default images: use
  343. # sender_hash % the number of default images to choose from
  344. sender_hash = string_ordinal_total(event.sender)
  345. msgtype = event.content.get("msgtype")
  346. ret = {
  347. "msgtype": msgtype,
  348. "is_historical": event.event_id != notif["event_id"],
  349. "id": event.event_id,
  350. "ts": event.origin_server_ts,
  351. "sender_name": sender_name,
  352. "sender_avatar_url": sender_avatar_url,
  353. "sender_hash": sender_hash,
  354. }
  355. if msgtype == "m.text":
  356. self.add_text_message_vars(ret, event)
  357. elif msgtype == "m.image":
  358. self.add_image_message_vars(ret, event)
  359. if "body" in event.content:
  360. ret["body_text_plain"] = event.content["body"]
  361. return ret
  362. def add_text_message_vars(self, messagevars, event):
  363. msgformat = event.content.get("format")
  364. messagevars["format"] = msgformat
  365. formatted_body = event.content.get("formatted_body")
  366. body = event.content.get("body")
  367. if msgformat == "org.matrix.custom.html" and formatted_body:
  368. messagevars["body_text_html"] = safe_markup(formatted_body)
  369. elif body:
  370. messagevars["body_text_html"] = safe_text(body)
  371. return messagevars
  372. def add_image_message_vars(self, messagevars, event):
  373. messagevars["image_url"] = event.content["url"]
  374. return messagevars
  375. async def make_summary_text(
  376. self, notifs_by_room, room_state_ids, notif_events, user_id, reason
  377. ):
  378. if len(notifs_by_room) == 1:
  379. # Only one room has new stuff
  380. room_id = list(notifs_by_room.keys())[0]
  381. # If the room has some kind of name, use it, but we don't
  382. # want the generated-from-names one here otherwise we'll
  383. # end up with, "new message from Bob in the Bob room"
  384. room_name = await calculate_room_name(
  385. self.store, room_state_ids[room_id], user_id, fallback_to_members=False
  386. )
  387. my_member_event_id = room_state_ids[room_id][("m.room.member", user_id)]
  388. my_member_event = await self.store.get_event(my_member_event_id)
  389. if my_member_event.content["membership"] == "invite":
  390. inviter_member_event_id = room_state_ids[room_id][
  391. ("m.room.member", my_member_event.sender)
  392. ]
  393. inviter_member_event = await self.store.get_event(
  394. inviter_member_event_id
  395. )
  396. inviter_name = name_from_member_event(inviter_member_event)
  397. if room_name is None:
  398. return INVITE_FROM_PERSON % {
  399. "person": inviter_name,
  400. "app": self.app_name,
  401. }
  402. else:
  403. return INVITE_FROM_PERSON_TO_ROOM % {
  404. "person": inviter_name,
  405. "room": room_name,
  406. "app": self.app_name,
  407. }
  408. sender_name = None
  409. if len(notifs_by_room[room_id]) == 1:
  410. # There is just the one notification, so give some detail
  411. event = notif_events[notifs_by_room[room_id][0]["event_id"]]
  412. if ("m.room.member", event.sender) in room_state_ids[room_id]:
  413. state_event_id = room_state_ids[room_id][
  414. ("m.room.member", event.sender)
  415. ]
  416. state_event = await self.store.get_event(state_event_id)
  417. sender_name = name_from_member_event(state_event)
  418. if sender_name is not None and room_name is not None:
  419. return MESSAGE_FROM_PERSON_IN_ROOM % {
  420. "person": sender_name,
  421. "room": room_name,
  422. "app": self.app_name,
  423. }
  424. elif sender_name is not None:
  425. return MESSAGE_FROM_PERSON % {
  426. "person": sender_name,
  427. "app": self.app_name,
  428. }
  429. else:
  430. # There's more than one notification for this room, so just
  431. # say there are several
  432. if room_name is not None:
  433. return MESSAGES_IN_ROOM % {"room": room_name, "app": self.app_name}
  434. else:
  435. # If the room doesn't have a name, say who the messages
  436. # are from explicitly to avoid, "messages in the Bob room"
  437. sender_ids = list(
  438. {
  439. notif_events[n["event_id"]].sender
  440. for n in notifs_by_room[room_id]
  441. }
  442. )
  443. member_events = await self.store.get_events(
  444. [
  445. room_state_ids[room_id][("m.room.member", s)]
  446. for s in sender_ids
  447. ]
  448. )
  449. return MESSAGES_FROM_PERSON % {
  450. "person": descriptor_from_member_events(member_events.values()),
  451. "app": self.app_name,
  452. }
  453. else:
  454. # Stuff's happened in multiple different rooms
  455. # ...but we still refer to the 'reason' room which triggered the mail
  456. if reason["room_name"] is not None:
  457. return MESSAGES_IN_ROOM_AND_OTHERS % {
  458. "room": reason["room_name"],
  459. "app": self.app_name,
  460. }
  461. else:
  462. # If the reason room doesn't have a name, say who the messages
  463. # are from explicitly to avoid, "messages in the Bob room"
  464. room_id = reason["room_id"]
  465. sender_ids = list(
  466. {
  467. notif_events[n["event_id"]].sender
  468. for n in notifs_by_room[room_id]
  469. }
  470. )
  471. member_events = await self.store.get_events(
  472. [room_state_ids[room_id][("m.room.member", s)] for s in sender_ids]
  473. )
  474. return MESSAGES_FROM_PERSON_AND_OTHERS % {
  475. "person": descriptor_from_member_events(member_events.values()),
  476. "app": self.app_name,
  477. }
  478. def make_room_link(self, room_id):
  479. if self.hs.config.email_riot_base_url:
  480. base_url = "%s/#/room" % (self.hs.config.email_riot_base_url)
  481. elif self.app_name == "Vector":
  482. # need /beta for Universal Links to work on iOS
  483. base_url = "https://vector.im/beta/#/room"
  484. else:
  485. base_url = "https://matrix.to/#"
  486. return "%s/%s" % (base_url, room_id)
  487. def make_notif_link(self, notif):
  488. if self.hs.config.email_riot_base_url:
  489. return "%s/#/room/%s/%s" % (
  490. self.hs.config.email_riot_base_url,
  491. notif["room_id"],
  492. notif["event_id"],
  493. )
  494. elif self.app_name == "Vector":
  495. # need /beta for Universal Links to work on iOS
  496. return "https://vector.im/beta/#/room/%s/%s" % (
  497. notif["room_id"],
  498. notif["event_id"],
  499. )
  500. else:
  501. return "https://matrix.to/#/%s/%s" % (notif["room_id"], notif["event_id"])
  502. def make_unsubscribe_link(self, user_id, app_id, email_address):
  503. params = {
  504. "access_token": self.macaroon_gen.generate_delete_pusher_token(user_id),
  505. "app_id": app_id,
  506. "pushkey": email_address,
  507. }
  508. # XXX: make r0 once API is stable
  509. return "%s_matrix/client/unstable/pushers/remove?%s" % (
  510. self.hs.config.public_baseurl,
  511. urllib.parse.urlencode(params),
  512. )
  513. def safe_markup(raw_html):
  514. return jinja2.Markup(
  515. bleach.linkify(
  516. bleach.clean(
  517. raw_html,
  518. tags=ALLOWED_TAGS,
  519. attributes=ALLOWED_ATTRS,
  520. # bleach master has this, but it isn't released yet
  521. # protocols=ALLOWED_SCHEMES,
  522. strip=True,
  523. )
  524. )
  525. )
  526. def safe_text(raw_text):
  527. """
  528. Process text: treat it as HTML but escape any tags (ie. just escape the
  529. HTML) then linkify it.
  530. """
  531. return jinja2.Markup(
  532. bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=False))
  533. )
  534. def deduped_ordered_list(it: Iterable[T]) -> List[T]:
  535. seen = set()
  536. ret = []
  537. for item in it:
  538. if item not in seen:
  539. seen.add(item)
  540. ret.append(item)
  541. return ret
  542. def string_ordinal_total(s):
  543. tot = 0
  544. for c in s:
  545. tot += ord(c)
  546. return tot
  547. def format_ts_filter(value, format):
  548. return time.strftime(format, time.localtime(value / 1000))
  549. def load_jinja2_templates(
  550. template_dir,
  551. template_filenames,
  552. apply_format_ts_filter=False,
  553. apply_mxc_to_http_filter=False,
  554. public_baseurl=None,
  555. ):
  556. """Loads and returns one or more jinja2 templates and applies optional filters
  557. Args:
  558. template_dir (str): The directory where templates are stored
  559. template_filenames (list[str]): A list of template filenames
  560. apply_format_ts_filter (bool): Whether to apply a template filter that formats
  561. timestamps
  562. apply_mxc_to_http_filter (bool): Whether to apply a template filter that converts
  563. mxc urls to http urls
  564. public_baseurl (str|None): The public baseurl of the server. Required for
  565. apply_mxc_to_http_filter to be enabled
  566. Returns:
  567. A list of jinja2 templates corresponding to the given list of filenames,
  568. with order preserved
  569. """
  570. logger.info(
  571. "loading email templates %s from '%s'", template_filenames, template_dir
  572. )
  573. loader = jinja2.FileSystemLoader(template_dir)
  574. env = jinja2.Environment(loader=loader)
  575. if apply_format_ts_filter:
  576. env.filters["format_ts"] = format_ts_filter
  577. if apply_mxc_to_http_filter and public_baseurl:
  578. env.filters["mxc_to_http"] = _create_mxc_to_http_filter(public_baseurl)
  579. templates = []
  580. for template_filename in template_filenames:
  581. template = env.get_template(template_filename)
  582. templates.append(template)
  583. return templates
  584. def _create_mxc_to_http_filter(public_baseurl):
  585. def mxc_to_http_filter(value, width, height, resize_method="crop"):
  586. if value[0:6] != "mxc://":
  587. return ""
  588. serverAndMediaId = value[6:]
  589. fragment = None
  590. if "#" in serverAndMediaId:
  591. (serverAndMediaId, fragment) = serverAndMediaId.split("#", 1)
  592. fragment = "#" + fragment
  593. params = {"width": width, "height": height, "method": resize_method}
  594. return "%s_matrix/media/v1/thumbnail/%s?%s%s" % (
  595. public_baseurl,
  596. serverAndMediaId,
  597. urllib.parse.urlencode(params),
  598. fragment or "",
  599. )
  600. return mxc_to_http_filter