state_deltas.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2018 New Vector 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. logger = logging.getLogger(__name__)
  18. class StateDeltasHandler(object):
  19. def __init__(self, hs):
  20. self.store = hs.get_datastore()
  21. @defer.inlineCallbacks
  22. def _get_key_change(self, prev_event_id, event_id, key_name, public_value):
  23. """Given two events check if the `key_name` field in content changed
  24. from not matching `public_value` to doing so.
  25. For example, check if `history_visibility` (`key_name`) changed from
  26. `shared` to `world_readable` (`public_value`).
  27. Returns:
  28. None if the field in the events either both match `public_value`
  29. or if neither do, i.e. there has been no change.
  30. True if it didnt match `public_value` but now does
  31. False if it did match `public_value` but now doesn't
  32. """
  33. prev_event = None
  34. event = None
  35. if prev_event_id:
  36. prev_event = yield self.store.get_event(prev_event_id, allow_none=True)
  37. if event_id:
  38. event = yield self.store.get_event(event_id, allow_none=True)
  39. if not event and not prev_event:
  40. logger.debug("Neither event exists: %r %r", prev_event_id, event_id)
  41. return None
  42. prev_value = None
  43. value = None
  44. if prev_event:
  45. prev_value = prev_event.content.get(key_name)
  46. if event:
  47. value = event.content.get(key_name)
  48. logger.debug("prev_value: %r -> value: %r", prev_value, value)
  49. if value == public_value and prev_value != public_value:
  50. return True
  51. elif value != public_value and prev_value == public_value:
  52. return False
  53. else:
  54. return None