summary refs log tree commit diff
diff options
context:
space:
mode:
authorErik Johnston <erik@matrix.org>2021-05-05 13:42:58 +0100
committerErik Johnston <erik@matrix.org>2021-05-05 13:52:29 +0100
commitc856e29ccd63aa10d1c03434b1bc021753305348 (patch)
tree506412b623253d86b37b3a7fcb35c2abd5c4e04e
parentTime external cache response time (#9904) (diff)
downloadsynapse-c856e29ccd63aa10d1c03434b1bc021753305348.tar.xz
Remvoe dictionary based access form events
-rw-r--r--synapse/api/filtering.py8
-rw-r--r--synapse/crypto/event_signing.py2
-rw-r--r--synapse/event_auth.py4
-rw-r--r--synapse/events/__init__.py28
-rw-r--r--synapse/federation/federation_base.py4
-rw-r--r--synapse/handlers/message.py2
-rw-r--r--synapse/handlers/room.py2
-rw-r--r--synapse/notifier.py2
-rw-r--r--synapse/push/push_rule_evaluator.py4
9 files changed, 23 insertions, 33 deletions
diff --git a/synapse/api/filtering.py b/synapse/api/filtering.py
index ce49a0ad58..3e7eb47001 100644
--- a/synapse/api/filtering.py
+++ b/synapse/api/filtering.py
@@ -23,6 +23,7 @@ from jsonschema import FormatChecker
 from synapse.api.constants import EventContentFields
 from synapse.api.errors import SynapseError
 from synapse.api.presence import UserPresenceState
+from synapse.events import EventBase
 from synapse.types import RoomID, UserID
 
 FILTER_SCHEMA = {
@@ -290,6 +291,13 @@ class Filter:
             ev_type = "m.presence"
             contains_url = False
             labels = []  # type: List[str]
+        elif isinstance(event, EventBase):
+            sender = event.sender
+            room_id = event.room_id
+            ev_type = event.type
+            content = event.content
+            contains_url = isinstance(content.get("url"), str)
+            labels = content.get(EventContentFields.LABELS, [])
         else:
             sender = event.get("sender", None)
             if not sender:
diff --git a/synapse/crypto/event_signing.py b/synapse/crypto/event_signing.py
index 0f2b632e47..c2a67704d6 100644
--- a/synapse/crypto/event_signing.py
+++ b/synapse/crypto/event_signing.py
@@ -48,7 +48,7 @@ def check_event_content_hash(
 
     # some malformed events lack a 'hashes'. Protect against it being missing
     # or a weird type by basically treating it the same as an unhashed event.
-    hashes = event.get("hashes")
+    hashes = getattr(event, "hashes", None)
     # nb it might be a frozendict or a dict
     if not isinstance(hashes, collections.abc.Mapping):
         raise SynapseError(
diff --git a/synapse/event_auth.py b/synapse/event_auth.py
index 70c556566e..eb9cd2f5eb 100644
--- a/synapse/event_auth.py
+++ b/synapse/event_auth.py
@@ -418,7 +418,9 @@ def get_send_level(
 def _can_send_event(event: EventBase, auth_events: StateMap[EventBase]) -> bool:
     power_levels_event = _get_power_level_event(auth_events)
 
-    send_level = get_send_level(event.type, event.get("state_key"), power_levels_event)
+    send_level = get_send_level(
+        event.type, getattr(event, "state_key", None), power_levels_event
+    )
     user_level = get_user_power_level(event.user_id, auth_events)
 
     if user_level < send_level:
diff --git a/synapse/events/__init__.py b/synapse/events/__init__.py
index c8b52cbc7a..46d26e0af9 100644
--- a/synapse/events/__init__.py
+++ b/synapse/events/__init__.py
@@ -263,12 +263,6 @@ class EventBase(metaclass=abc.ABCMeta):
 
         return d
 
-    def get(self, key, default=None):
-        return self._dict.get(key, default)
-
-    def get_internal_metadata_dict(self):
-        return self.internal_metadata.get_dict()
-
     def get_pdu_json(self, time_now=None) -> JsonDict:
         pdu_json = self.get_dict()
 
@@ -285,18 +279,6 @@ class EventBase(metaclass=abc.ABCMeta):
     def __set__(self, instance, value):
         raise AttributeError("Unrecognized attribute %s" % (instance,))
 
-    def __getitem__(self, field):
-        return self._dict[field]
-
-    def __contains__(self, field):
-        return field in self._dict
-
-    def items(self):
-        return list(self._dict.items())
-
-    def keys(self):
-        return self._dict.keys()
-
     def prev_event_ids(self):
         """Returns the list of prev event IDs. The order matches the order
         specified in the event, though there is no meaning to it.
@@ -374,9 +356,9 @@ class FrozenEvent(EventBase):
 
     def __repr__(self):
         return "<FrozenEvent event_id=%r, type=%r, state_key=%r>" % (
-            self.get("event_id", None),
-            self.get("type", None),
-            self.get("state_key", None),
+            self.event_id,
+            self.type,
+            getattr(self, "state_key", None),
         )
 
 
@@ -461,8 +443,8 @@ class FrozenEventV2(EventBase):
         return "<%s event_id=%r, type=%r, state_key=%r>" % (
             self.__class__.__name__,
             self.event_id,
-            self.get("type", None),
-            self.get("state_key", None),
+            self.type,
+            self.state_key if self.is_state() else None,
         )
 
 
diff --git a/synapse/federation/federation_base.py b/synapse/federation/federation_base.py
index 949dcd4614..a6471ce6cc 100644
--- a/synapse/federation/federation_base.py
+++ b/synapse/federation/federation_base.py
@@ -90,9 +90,7 @@ class FederationBase:
                     # received event was probably a redacted copy (but we then use our
                     # *actual* redacted copy to be on the safe side.)
                     redacted_event = prune_event(pdu)
-                    if set(redacted_event.keys()) == set(pdu.keys()) and set(
-                        redacted_event.content.keys()
-                    ) == set(pdu.content.keys()):
+                    if set(redacted_event.content.keys()) == set(pdu.content.keys()):
                         logger.info(
                             "Event %s seems to have been redacted; using our redacted "
                             "copy",
diff --git a/synapse/handlers/message.py b/synapse/handlers/message.py
index 49f8aa25ea..a9364670a1 100644
--- a/synapse/handlers/message.py
+++ b/synapse/handlers/message.py
@@ -1401,7 +1401,7 @@ class EventCreationHandler:
         ]
 
         for k in immutable_fields:
-            if getattr(builder, k, None) != original_event.get(k):
+            if getattr(builder, k, None) != getattr(original_event, k, None):
                 raise Exception(
                     "Third party rules module created an invalid event: "
                     "cannot change field " + k
diff --git a/synapse/handlers/room.py b/synapse/handlers/room.py
index 5a888b7941..88e9d0e2fe 100644
--- a/synapse/handlers/room.py
+++ b/synapse/handlers/room.py
@@ -475,7 +475,7 @@ class RoomCreationHandler(BaseHandler):
             ):
                 await self.room_member_handler.update_membership(
                     requester,
-                    UserID.from_string(old_event["state_key"]),
+                    UserID.from_string(old_event.state_key),
                     new_room_id,
                     "ban",
                     ratelimit=False,
diff --git a/synapse/notifier.py b/synapse/notifier.py
index b9531007e2..4787ea438e 100644
--- a/synapse/notifier.py
+++ b/synapse/notifier.py
@@ -277,7 +277,7 @@ class Notifier:
             event_pos=event_pos,
             room_id=event.room_id,
             event_type=event.type,
-            state_key=event.get("state_key"),
+            state_key=getattr(event, "state_key", None),
             membership=event.content.get("membership"),
             max_room_stream_token=max_room_stream_token,
             extra_users=extra_users or [],
diff --git a/synapse/push/push_rule_evaluator.py b/synapse/push/push_rule_evaluator.py
index 49ecb38522..fa5985894c 100644
--- a/synapse/push/push_rule_evaluator.py
+++ b/synapse/push/push_rule_evaluator.py
@@ -125,7 +125,7 @@ class PushRuleEvaluatorForEvent:
         self._power_levels = power_levels
 
         # Maps strings of e.g. 'content.body' -> event["content"]["body"]
-        self._value_cache = _flatten_dict(event)
+        self._value_cache = _flatten_dict(event.get_dict())
 
     def matches(
         self, condition: Dict[str, Any], user_id: str, display_name: str
@@ -271,7 +271,7 @@ def _re_word_boundary(r: str) -> str:
 
 
 def _flatten_dict(
-    d: Union[EventBase, dict],
+    d: dict,
     prefix: Optional[List[str]] = None,
     result: Optional[Dict[str, str]] = None,
 ) -> Dict[str, str]: