builder.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. import copy
  16. from synapse.types import EventID
  17. from synapse.util.stringutils import random_string
  18. from . import EventBase, FrozenEvent, _event_dict_property
  19. class EventBuilder(EventBase):
  20. def __init__(self, key_values={}, internal_metadata_dict={}):
  21. signatures = copy.deepcopy(key_values.pop("signatures", {}))
  22. unsigned = copy.deepcopy(key_values.pop("unsigned", {}))
  23. super(EventBuilder, self).__init__(
  24. key_values,
  25. signatures=signatures,
  26. unsigned=unsigned,
  27. internal_metadata_dict=internal_metadata_dict,
  28. )
  29. event_id = _event_dict_property("event_id")
  30. state_key = _event_dict_property("state_key")
  31. type = _event_dict_property("type")
  32. def build(self):
  33. return FrozenEvent.from_event(self)
  34. class EventBuilderFactory(object):
  35. def __init__(self, clock, hostname):
  36. self.clock = clock
  37. self.hostname = hostname
  38. self.event_id_count = 0
  39. def create_event_id(self):
  40. i = str(self.event_id_count)
  41. self.event_id_count += 1
  42. local_part = str(int(self.clock.time())) + i + random_string(5)
  43. e_id = EventID(local_part, self.hostname)
  44. return e_id.to_string()
  45. def new(self, key_values={}):
  46. key_values["event_id"] = self.create_event_id()
  47. time_now = int(self.clock.time_msec())
  48. key_values.setdefault("origin", self.hostname)
  49. key_values.setdefault("origin_server_ts", time_now)
  50. key_values.setdefault("unsigned", {})
  51. age = key_values["unsigned"].pop("age", 0)
  52. key_values["unsigned"].setdefault("age_ts", time_now - age)
  53. key_values["signatures"] = {}
  54. return EventBuilder(key_values=key_values,)