pusher.py 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. # Copyright 2014-2016 OpenMarket Ltd
  2. # Copyright 2022 The Matrix.org Foundation C.I.C.
  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, Tuple
  17. from synapse.api.errors import Codes, SynapseError
  18. from synapse.http.server import HttpServer
  19. from synapse.http.servlet import (
  20. RestServlet,
  21. assert_params_in_dict,
  22. parse_json_object_from_request,
  23. )
  24. from synapse.http.site import SynapseRequest
  25. from synapse.push import PusherConfigException
  26. from synapse.rest.client._base import client_patterns
  27. from synapse.rest.synapse.client.unsubscribe import UnsubscribeResource
  28. from synapse.types import JsonDict
  29. if TYPE_CHECKING:
  30. from synapse.server import HomeServer
  31. logger = logging.getLogger(__name__)
  32. class PushersRestServlet(RestServlet):
  33. PATTERNS = client_patterns("/pushers$", v1=True)
  34. def __init__(self, hs: "HomeServer"):
  35. super().__init__()
  36. self.hs = hs
  37. self.auth = hs.get_auth()
  38. self._msc3881_enabled = self.hs.config.experimental.msc3881_enabled
  39. async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  40. requester = await self.auth.get_user_by_req(request)
  41. user = requester.user
  42. pushers = await self.hs.get_datastores().main.get_pushers_by_user_id(
  43. user.to_string()
  44. )
  45. pusher_dicts = [p.as_dict() for p in pushers]
  46. for pusher in pusher_dicts:
  47. if self._msc3881_enabled:
  48. pusher["org.matrix.msc3881.enabled"] = pusher["enabled"]
  49. pusher["org.matrix.msc3881.device_id"] = pusher["device_id"]
  50. del pusher["enabled"]
  51. del pusher["device_id"]
  52. return 200, {"pushers": pusher_dicts}
  53. class PushersSetRestServlet(RestServlet):
  54. PATTERNS = client_patterns("/pushers/set$", v1=True)
  55. def __init__(self, hs: "HomeServer"):
  56. super().__init__()
  57. self.hs = hs
  58. self.auth = hs.get_auth()
  59. self.notifier = hs.get_notifier()
  60. self.pusher_pool = self.hs.get_pusherpool()
  61. self._msc3881_enabled = self.hs.config.experimental.msc3881_enabled
  62. async def on_POST(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
  63. requester = await self.auth.get_user_by_req(request)
  64. user = requester.user
  65. content = parse_json_object_from_request(request)
  66. if (
  67. "pushkey" in content
  68. and "app_id" in content
  69. and "kind" in content
  70. and content["kind"] is None
  71. ):
  72. await self.pusher_pool.remove_pusher(
  73. content["app_id"], content["pushkey"], user_id=user.to_string()
  74. )
  75. return 200, {}
  76. assert_params_in_dict(
  77. content,
  78. [
  79. "kind",
  80. "app_id",
  81. "app_display_name",
  82. "device_display_name",
  83. "pushkey",
  84. "lang",
  85. "data",
  86. ],
  87. )
  88. logger.debug("set pushkey %s to kind %s", content["pushkey"], content["kind"])
  89. logger.debug("Got pushers request with body: %r", content)
  90. append = False
  91. if "append" in content:
  92. append = content["append"]
  93. enabled = True
  94. if self._msc3881_enabled and "org.matrix.msc3881.enabled" in content:
  95. enabled = content["org.matrix.msc3881.enabled"]
  96. if not append:
  97. await self.pusher_pool.remove_pushers_by_app_id_and_pushkey_not_user(
  98. app_id=content["app_id"],
  99. pushkey=content["pushkey"],
  100. not_user_id=user.to_string(),
  101. )
  102. try:
  103. await self.pusher_pool.add_or_update_pusher(
  104. user_id=user.to_string(),
  105. kind=content["kind"],
  106. app_id=content["app_id"],
  107. app_display_name=content["app_display_name"],
  108. device_display_name=content["device_display_name"],
  109. pushkey=content["pushkey"],
  110. lang=content["lang"],
  111. data=content["data"],
  112. profile_tag=content.get("profile_tag", ""),
  113. enabled=enabled,
  114. device_id=requester.device_id,
  115. )
  116. except PusherConfigException as pce:
  117. raise SynapseError(
  118. 400, "Config Error: " + str(pce), errcode=Codes.MISSING_PARAM
  119. )
  120. self.notifier.on_new_replication_data()
  121. return 200, {}
  122. class LegacyPushersRemoveRestServlet(UnsubscribeResource, RestServlet):
  123. """
  124. A servlet to handle legacy "email unsubscribe" links, forwarding requests to the ``UnsubscribeResource``
  125. This should be kept for some time, so unsubscribe links in past emails stay valid.
  126. """
  127. PATTERNS = client_patterns("/pushers/remove$", releases=[], v1=False, unstable=True)
  128. async def on_GET(self, request: SynapseRequest) -> None:
  129. # Forward the request to the UnsubscribeResource
  130. await self._async_render(request)
  131. def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
  132. PushersRestServlet(hs).register(http_server)
  133. PushersSetRestServlet(hs).register(http_server)
  134. LegacyPushersRemoveRestServlet(hs).register(http_server)