pusher.py 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014-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 logging
  16. from typing import TYPE_CHECKING, Callable, Dict, Optional
  17. from synapse.push import Pusher, PusherConfig
  18. from synapse.push.emailpusher import EmailPusher
  19. from synapse.push.httppusher import HttpPusher
  20. from synapse.push.mailer import Mailer
  21. if TYPE_CHECKING:
  22. from synapse.app.homeserver import HomeServer
  23. logger = logging.getLogger(__name__)
  24. class PusherFactory:
  25. def __init__(self, hs: "HomeServer"):
  26. self.hs = hs
  27. self.config = hs.config
  28. self.pusher_types = {
  29. "http": HttpPusher
  30. } # type: Dict[str, Callable[[HomeServer, PusherConfig], Pusher]]
  31. logger.info("email enable notifs: %r", hs.config.email_enable_notifs)
  32. if hs.config.email_enable_notifs:
  33. self.mailers = {} # type: Dict[str, Mailer]
  34. self._notif_template_html = hs.config.email_notif_template_html
  35. self._notif_template_text = hs.config.email_notif_template_text
  36. self.pusher_types["email"] = self._create_email_pusher
  37. logger.info("defined email pusher type")
  38. def create_pusher(self, pusher_config: PusherConfig) -> Optional[Pusher]:
  39. kind = pusher_config.kind
  40. f = self.pusher_types.get(kind, None)
  41. if not f:
  42. return None
  43. logger.debug("creating %s pusher for %r", kind, pusher_config)
  44. return f(self.hs, pusher_config)
  45. def _create_email_pusher(
  46. self, _hs: "HomeServer", pusher_config: PusherConfig
  47. ) -> EmailPusher:
  48. app_name = self._app_name_from_pusherdict(pusher_config)
  49. mailer = self.mailers.get(app_name)
  50. if not mailer:
  51. mailer = Mailer(
  52. hs=self.hs,
  53. app_name=app_name,
  54. template_html=self._notif_template_html,
  55. template_text=self._notif_template_text,
  56. )
  57. self.mailers[app_name] = mailer
  58. return EmailPusher(self.hs, pusher_config, mailer)
  59. def _app_name_from_pusherdict(self, pusher_config: PusherConfig) -> str:
  60. data = pusher_config.data
  61. if isinstance(data, dict):
  62. brand = data.get("brand")
  63. if isinstance(brand, str):
  64. return brand
  65. return self.config.email_app_name