event_injector.py 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 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.constants import EventTypes
  17. class EventInjector:
  18. def __init__(self, hs):
  19. self.hs = hs
  20. self.store = hs.get_datastore()
  21. self.message_handler = hs.get_handlers().message_handler
  22. self.event_builder_factory = hs.get_event_builder_factory()
  23. @defer.inlineCallbacks
  24. def create_room(self, room, user):
  25. builder = self.event_builder_factory.new({
  26. "type": EventTypes.Create,
  27. "sender": user.to_string(),
  28. "room_id": room.to_string(),
  29. "content": {},
  30. })
  31. event, context = yield self.message_handler._create_new_client_event(
  32. builder
  33. )
  34. yield self.store.persist_event(event, context)
  35. @defer.inlineCallbacks
  36. def inject_room_member(self, room, user, membership):
  37. builder = self.event_builder_factory.new({
  38. "type": EventTypes.Member,
  39. "sender": user.to_string(),
  40. "state_key": user.to_string(),
  41. "room_id": room.to_string(),
  42. "content": {"membership": membership},
  43. })
  44. event, context = yield self.message_handler._create_new_client_event(
  45. builder
  46. )
  47. yield self.store.persist_event(event, context)
  48. defer.returnValue(event)
  49. @defer.inlineCallbacks
  50. def inject_message(self, room, user, body):
  51. builder = self.event_builder_factory.new({
  52. "type": EventTypes.Message,
  53. "sender": user.to_string(),
  54. "state_key": user.to_string(),
  55. "room_id": room.to_string(),
  56. "content": {"body": body, "msgtype": u"message"},
  57. })
  58. event, context = yield self.message_handler._create_new_client_event(
  59. builder
  60. )
  61. yield self.store.persist_event(event, context)