pusher.py 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  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 synapse.api.errors import Codes, StoreError, SynapseError
  17. from synapse.http.server import respond_with_html_bytes
  18. from synapse.http.servlet import (
  19. RestServlet,
  20. assert_params_in_dict,
  21. parse_json_object_from_request,
  22. parse_string,
  23. )
  24. from synapse.push import PusherConfigException
  25. from synapse.rest.client.v2_alpha._base import client_patterns
  26. logger = logging.getLogger(__name__)
  27. class PushersRestServlet(RestServlet):
  28. PATTERNS = client_patterns("/pushers$", v1=True)
  29. def __init__(self, hs):
  30. super().__init__()
  31. self.hs = hs
  32. self.auth = hs.get_auth()
  33. async def on_GET(self, request):
  34. requester = await self.auth.get_user_by_req(request)
  35. user = requester.user
  36. pushers = await self.hs.get_datastore().get_pushers_by_user_id(user.to_string())
  37. filtered_pushers = [p.as_dict() for p in pushers]
  38. return 200, {"pushers": filtered_pushers}
  39. class PushersSetRestServlet(RestServlet):
  40. PATTERNS = client_patterns("/pushers/set$", v1=True)
  41. def __init__(self, hs):
  42. super().__init__()
  43. self.hs = hs
  44. self.auth = hs.get_auth()
  45. self.notifier = hs.get_notifier()
  46. self.pusher_pool = self.hs.get_pusherpool()
  47. async def on_POST(self, request):
  48. requester = await self.auth.get_user_by_req(request)
  49. user = requester.user
  50. content = parse_json_object_from_request(request)
  51. if (
  52. "pushkey" in content
  53. and "app_id" in content
  54. and "kind" in content
  55. and content["kind"] is None
  56. ):
  57. await self.pusher_pool.remove_pusher(
  58. content["app_id"], content["pushkey"], user_id=user.to_string()
  59. )
  60. return 200, {}
  61. assert_params_in_dict(
  62. content,
  63. [
  64. "kind",
  65. "app_id",
  66. "app_display_name",
  67. "device_display_name",
  68. "pushkey",
  69. "lang",
  70. "data",
  71. ],
  72. )
  73. logger.debug("set pushkey %s to kind %s", content["pushkey"], content["kind"])
  74. logger.debug("Got pushers request with body: %r", content)
  75. append = False
  76. if "append" in content:
  77. append = content["append"]
  78. if not append:
  79. await self.pusher_pool.remove_pushers_by_app_id_and_pushkey_not_user(
  80. app_id=content["app_id"],
  81. pushkey=content["pushkey"],
  82. not_user_id=user.to_string(),
  83. )
  84. try:
  85. await self.pusher_pool.add_pusher(
  86. user_id=user.to_string(),
  87. access_token=requester.access_token_id,
  88. kind=content["kind"],
  89. app_id=content["app_id"],
  90. app_display_name=content["app_display_name"],
  91. device_display_name=content["device_display_name"],
  92. pushkey=content["pushkey"],
  93. lang=content["lang"],
  94. data=content["data"],
  95. profile_tag=content.get("profile_tag", ""),
  96. )
  97. except PusherConfigException as pce:
  98. raise SynapseError(
  99. 400, "Config Error: " + str(pce), errcode=Codes.MISSING_PARAM
  100. )
  101. self.notifier.on_new_replication_data()
  102. return 200, {}
  103. class PushersRemoveRestServlet(RestServlet):
  104. """
  105. To allow pusher to be delete by clicking a link (ie. GET request)
  106. """
  107. PATTERNS = client_patterns("/pushers/remove$", v1=True)
  108. SUCCESS_HTML = b"<html><body>You have been unsubscribed</body><html>"
  109. def __init__(self, hs):
  110. super().__init__()
  111. self.hs = hs
  112. self.notifier = hs.get_notifier()
  113. self.auth = hs.get_auth()
  114. self.pusher_pool = self.hs.get_pusherpool()
  115. async def on_GET(self, request):
  116. requester = await self.auth.get_user_by_req(request, rights="delete_pusher")
  117. user = requester.user
  118. app_id = parse_string(request, "app_id", required=True)
  119. pushkey = parse_string(request, "pushkey", required=True)
  120. try:
  121. await self.pusher_pool.remove_pusher(
  122. app_id=app_id, pushkey=pushkey, user_id=user.to_string()
  123. )
  124. except StoreError as se:
  125. if se.code != 404:
  126. # This is fine: they're already unsubscribed
  127. raise
  128. self.notifier.on_new_replication_data()
  129. respond_with_html_bytes(
  130. request, 200, PushersRemoveRestServlet.SUCCESS_HTML,
  131. )
  132. return None
  133. def register_servlets(hs, http_server):
  134. PushersRestServlet(hs).register(http_server)
  135. PushersSetRestServlet(hs).register(http_server)
  136. PushersRemoveRestServlet(hs).register(http_server)