sendtodevice.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 logging
  16. from twisted.internet import defer
  17. from synapse.http import servlet
  18. from synapse.http.servlet import parse_json_object_from_request
  19. from synapse.rest.client.transactions import HttpTransactionCache
  20. from ._base import client_patterns
  21. logger = logging.getLogger(__name__)
  22. class SendToDeviceRestServlet(servlet.RestServlet):
  23. PATTERNS = client_patterns(
  24. "/sendToDevice/(?P<message_type>[^/]*)/(?P<txn_id>[^/]*)$"
  25. )
  26. def __init__(self, hs):
  27. """
  28. Args:
  29. hs (synapse.server.HomeServer): server
  30. """
  31. super(SendToDeviceRestServlet, self).__init__()
  32. self.hs = hs
  33. self.auth = hs.get_auth()
  34. self.txns = HttpTransactionCache(hs)
  35. self.device_message_handler = hs.get_device_message_handler()
  36. def on_PUT(self, request, message_type, txn_id):
  37. return self.txns.fetch_or_execute_request(
  38. request, self._put, request, message_type, txn_id
  39. )
  40. @defer.inlineCallbacks
  41. def _put(self, request, message_type, txn_id):
  42. requester = yield self.auth.get_user_by_req(request, allow_guest=True)
  43. content = parse_json_object_from_request(request)
  44. sender_user_id = requester.user.to_string()
  45. yield self.device_message_handler.send_device_message(
  46. sender_user_id, message_type, content["messages"]
  47. )
  48. response = (200, {})
  49. return response
  50. def register_servlets(hs, http_server):
  51. SendToDeviceRestServlet(hs).register(http_server)