1
0

event_injector.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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):
  25. builder = self.event_builder_factory.new({
  26. "type": EventTypes.Create,
  27. "room_id": room.to_string(),
  28. "content": {},
  29. })
  30. event, context = yield self.message_handler._create_new_client_event(
  31. builder
  32. )
  33. yield self.store.persist_event(event, context)
  34. @defer.inlineCallbacks
  35. def inject_room_member(self, room, user, membership):
  36. builder = self.event_builder_factory.new({
  37. "type": EventTypes.Member,
  38. "sender": user.to_string(),
  39. "state_key": user.to_string(),
  40. "room_id": room.to_string(),
  41. "content": {"membership": membership},
  42. })
  43. event, context = yield self.message_handler._create_new_client_event(
  44. builder
  45. )
  46. yield self.store.persist_event(event, context)
  47. defer.returnValue(event)
  48. @defer.inlineCallbacks
  49. def inject_message(self, room, user, body):
  50. builder = self.event_builder_factory.new({
  51. "type": EventTypes.Message,
  52. "sender": user.to_string(),
  53. "state_key": user.to_string(),
  54. "room_id": room.to_string(),
  55. "content": {"body": body, "msgtype": u"message"},
  56. })
  57. event, context = yield self.message_handler._create_new_client_event(
  58. builder
  59. )
  60. yield self.store.persist_event(event, context)