pusher.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194
  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. from twisted.internet import defer
  16. from synapse.api.errors import SynapseError, Codes
  17. from synapse.push import PusherConfigException
  18. from synapse.http.servlet import (
  19. parse_json_object_from_request, parse_string, RestServlet
  20. )
  21. from synapse.http.server import finish_request
  22. from synapse.api.errors import StoreError
  23. from .base import ClientV1RestServlet, client_path_patterns
  24. import logging
  25. logger = logging.getLogger(__name__)
  26. class PushersRestServlet(ClientV1RestServlet):
  27. PATTERNS = client_path_patterns("/pushers$")
  28. def __init__(self, hs):
  29. super(PushersRestServlet, self).__init__(hs)
  30. @defer.inlineCallbacks
  31. def on_GET(self, request):
  32. requester = yield self.auth.get_user_by_req(request)
  33. user = requester.user
  34. pushers = yield self.hs.get_datastore().get_pushers_by_user_id(
  35. user.to_string()
  36. )
  37. allowed_keys = [
  38. "app_display_name",
  39. "app_id",
  40. "data",
  41. "device_display_name",
  42. "kind",
  43. "lang",
  44. "profile_tag",
  45. "pushkey",
  46. ]
  47. for p in pushers:
  48. for k, v in p.items():
  49. if k not in allowed_keys:
  50. del p[k]
  51. defer.returnValue((200, {"pushers": pushers}))
  52. def on_OPTIONS(self, _):
  53. return 200, {}
  54. class PushersSetRestServlet(ClientV1RestServlet):
  55. PATTERNS = client_path_patterns("/pushers/set$")
  56. def __init__(self, hs):
  57. super(PushersSetRestServlet, self).__init__(hs)
  58. self.notifier = hs.get_notifier()
  59. self.pusher_pool = self.hs.get_pusherpool()
  60. @defer.inlineCallbacks
  61. def on_POST(self, request):
  62. requester = yield self.auth.get_user_by_req(request)
  63. user = requester.user
  64. content = parse_json_object_from_request(request)
  65. if ('pushkey' in content and 'app_id' in content
  66. and 'kind' in content and
  67. content['kind'] is None):
  68. yield self.pusher_pool.remove_pusher(
  69. content['app_id'], content['pushkey'], user_id=user.to_string()
  70. )
  71. defer.returnValue((200, {}))
  72. reqd = ['kind', 'app_id', 'app_display_name',
  73. 'device_display_name', 'pushkey', 'lang', 'data']
  74. missing = []
  75. for i in reqd:
  76. if i not in content:
  77. missing.append(i)
  78. if len(missing):
  79. raise SynapseError(400, "Missing parameters: " + ','.join(missing),
  80. errcode=Codes.MISSING_PARAM)
  81. logger.debug("set pushkey %s to kind %s", content['pushkey'], content['kind'])
  82. logger.debug("Got pushers request with body: %r", content)
  83. append = False
  84. if 'append' in content:
  85. append = content['append']
  86. if not append:
  87. yield self.pusher_pool.remove_pushers_by_app_id_and_pushkey_not_user(
  88. app_id=content['app_id'],
  89. pushkey=content['pushkey'],
  90. not_user_id=user.to_string()
  91. )
  92. try:
  93. yield self.pusher_pool.add_pusher(
  94. user_id=user.to_string(),
  95. access_token=requester.access_token_id,
  96. kind=content['kind'],
  97. app_id=content['app_id'],
  98. app_display_name=content['app_display_name'],
  99. device_display_name=content['device_display_name'],
  100. pushkey=content['pushkey'],
  101. lang=content['lang'],
  102. data=content['data'],
  103. profile_tag=content.get('profile_tag', ""),
  104. )
  105. except PusherConfigException as pce:
  106. raise SynapseError(400, "Config Error: " + pce.message,
  107. errcode=Codes.MISSING_PARAM)
  108. self.notifier.on_new_replication_data()
  109. defer.returnValue((200, {}))
  110. def on_OPTIONS(self, _):
  111. return 200, {}
  112. class PushersRemoveRestServlet(RestServlet):
  113. """
  114. To allow pusher to be delete by clicking a link (ie. GET request)
  115. """
  116. PATTERNS = client_path_patterns("/pushers/remove$")
  117. SUCCESS_HTML = "<html><body>You have been unsubscribed</body><html>"
  118. def __init__(self, hs):
  119. super(RestServlet, self).__init__()
  120. self.hs = hs
  121. self.notifier = hs.get_notifier()
  122. self.auth = hs.get_v1auth()
  123. self.pusher_pool = self.hs.get_pusherpool()
  124. @defer.inlineCallbacks
  125. def on_GET(self, request):
  126. requester = yield self.auth.get_user_by_req(request, rights="delete_pusher")
  127. user = requester.user
  128. app_id = parse_string(request, "app_id", required=True)
  129. pushkey = parse_string(request, "pushkey", required=True)
  130. try:
  131. yield self.pusher_pool.remove_pusher(
  132. app_id=app_id,
  133. pushkey=pushkey,
  134. user_id=user.to_string(),
  135. )
  136. except StoreError as se:
  137. if se.code != 404:
  138. # This is fine: they're already unsubscribed
  139. raise
  140. self.notifier.on_new_replication_data()
  141. request.setResponseCode(200)
  142. request.setHeader(b"Content-Type", b"text/html; charset=utf-8")
  143. request.setHeader(b"Server", self.hs.version_string)
  144. request.setHeader(b"Content-Length", b"%d" % (
  145. len(PushersRemoveRestServlet.SUCCESS_HTML),
  146. ))
  147. request.write(PushersRemoveRestServlet.SUCCESS_HTML)
  148. finish_request(request)
  149. defer.returnValue(None)
  150. def on_OPTIONS(self, _):
  151. return 200, {}
  152. def register_servlets(hs, http_server):
  153. PushersRestServlet(hs).register(http_server)
  154. PushersSetRestServlet(hs).register(http_server)
  155. PushersRemoveRestServlet(hs).register(http_server)