sendtodevice.py 2.2 KB

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