summary refs log tree commit diff
path: root/synapse/types.py
diff options
context:
space:
mode:
Diffstat (limited to 'synapse/types.py')
-rw-r--r--synapse/types.py108
1 files changed, 58 insertions, 50 deletions
diff --git a/synapse/types.py b/synapse/types.py
index 3de94b6335..51eadb6ad4 100644
--- a/synapse/types.py
+++ b/synapse/types.py
@@ -21,9 +21,11 @@ import attr
 from synapse.api.errors import SynapseError
 
 
-class Requester(namedtuple("Requester", [
-    "user", "access_token_id", "is_guest", "device_id", "app_service",
-])):
+class Requester(
+    namedtuple(
+        "Requester", ["user", "access_token_id", "is_guest", "device_id", "app_service"]
+    )
+):
     """
     Represents the user making a request
 
@@ -76,8 +78,9 @@ class Requester(namedtuple("Requester", [
         )
 
 
-def create_requester(user_id, access_token_id=None, is_guest=False,
-                     device_id=None, app_service=None):
+def create_requester(
+    user_id, access_token_id=None, is_guest=False, device_id=None, app_service=None
+):
     """
     Create a new ``Requester`` object
 
@@ -101,7 +104,7 @@ def get_domain_from_id(string):
     idx = string.find(":")
     if idx == -1:
         raise SynapseError(400, "Invalid ID: %r" % (string,))
-    return string[idx + 1:]
+    return string[idx + 1 :]
 
 
 def get_localpart_from_id(string):
@@ -111,9 +114,7 @@ def get_localpart_from_id(string):
     return string[1:idx]
 
 
-class DomainSpecificString(
-        namedtuple("DomainSpecificString", ("localpart", "domain"))
-):
+class DomainSpecificString(namedtuple("DomainSpecificString", ("localpart", "domain"))):
     """Common base class among ID/name strings that have a local part and a
     domain name, prefixed with a sigil.
 
@@ -141,16 +142,16 @@ class DomainSpecificString(
     def from_string(cls, s):
         """Parse the string given by 's' into a structure object."""
         if len(s) < 1 or s[0:1] != cls.SIGIL:
-            raise SynapseError(400, "Expected %s string to start with '%s'" % (
-                cls.__name__, cls.SIGIL,
-            ))
+            raise SynapseError(
+                400, "Expected %s string to start with '%s'" % (cls.__name__, cls.SIGIL)
+            )
 
-        parts = s[1:].split(':', 1)
+        parts = s[1:].split(":", 1)
         if len(parts) != 2:
             raise SynapseError(
-                400, "Expected %s of the form '%slocalname:domain'" % (
-                    cls.__name__, cls.SIGIL,
-                )
+                400,
+                "Expected %s of the form '%slocalname:domain'"
+                % (cls.__name__, cls.SIGIL),
             )
 
         domain = parts[1]
@@ -176,47 +177,50 @@ class DomainSpecificString(
 
 class UserID(DomainSpecificString):
     """Structure representing a user ID."""
+
     SIGIL = "@"
 
 
 class RoomAlias(DomainSpecificString):
     """Structure representing a room name."""
+
     SIGIL = "#"
 
 
 class RoomID(DomainSpecificString):
     """Structure representing a room id. """
+
     SIGIL = "!"
 
 
 class EventID(DomainSpecificString):
     """Structure representing an event id. """
+
     SIGIL = "$"
 
 
 class GroupID(DomainSpecificString):
     """Structure representing a group ID."""
+
     SIGIL = "+"
 
     @classmethod
     def from_string(cls, s):
         group_id = super(GroupID, cls).from_string(s)
         if not group_id.localpart:
-            raise SynapseError(
-                400,
-                "Group ID cannot be empty",
-            )
+            raise SynapseError(400, "Group ID cannot be empty")
 
         if contains_invalid_mxid_characters(group_id.localpart):
             raise SynapseError(
-                400,
-                "Group ID can only contain characters a-z, 0-9, or '=_-./'",
+                400, "Group ID can only contain characters a-z, 0-9, or '=_-./'"
             )
 
         return group_id
 
 
-mxid_localpart_allowed_characters = set("_-./=" + string.ascii_lowercase + string.digits)
+mxid_localpart_allowed_characters = set(
+    "_-./=" + string.ascii_lowercase + string.digits
+)
 
 
 def contains_invalid_mxid_characters(localpart):
@@ -245,9 +249,9 @@ UPPER_CASE_PATTERN = re.compile(b"[A-Z_]")
 #    bytes rather than strings
 #
 NON_MXID_CHARACTER_PATTERN = re.compile(
-    ("[^%s]" % (
-        re.escape("".join(mxid_localpart_allowed_characters - {"="}),),
-    )).encode("ascii"),
+    ("[^%s]" % (re.escape("".join(mxid_localpart_allowed_characters - {"="})),)).encode(
+        "ascii"
+    )
 )
 
 
@@ -266,10 +270,11 @@ def map_username_to_mxid_localpart(username, case_sensitive=False):
         unicode: string suitable for a mxid localpart
     """
     if not isinstance(username, bytes):
-        username = username.encode('utf-8')
+        username = username.encode("utf-8")
 
     # first we sort out upper-case characters
     if case_sensitive:
+
         def f1(m):
             return b"_" + m.group().lower()
 
@@ -289,25 +294,28 @@ def map_username_to_mxid_localpart(username, case_sensitive=False):
     username = NON_MXID_CHARACTER_PATTERN.sub(f2, username)
 
     # we also do the =-escaping to mxids starting with an underscore.
-    username = re.sub(b'^_', b'=5f', username)
+    username = re.sub(b"^_", b"=5f", username)
 
     # we should now only have ascii bytes left, so can decode back to a
     # unicode.
-    return username.decode('ascii')
+    return username.decode("ascii")
 
 
 class StreamToken(
-    namedtuple("Token", (
-        "room_key",
-        "presence_key",
-        "typing_key",
-        "receipt_key",
-        "account_data_key",
-        "push_rules_key",
-        "to_device_key",
-        "device_list_key",
-        "groups_key",
-    ))
+    namedtuple(
+        "Token",
+        (
+            "room_key",
+            "presence_key",
+            "typing_key",
+            "receipt_key",
+            "account_data_key",
+            "push_rules_key",
+            "to_device_key",
+            "device_list_key",
+            "groups_key",
+        ),
+    )
 ):
     _SEPARATOR = "_"
 
@@ -368,9 +376,7 @@ class StreamToken(
         return self._replace(**{key: new_value})
 
 
-StreamToken.START = StreamToken(
-    *(["s0"] + ["0"] * (len(StreamToken._fields) - 1))
-)
+StreamToken.START = StreamToken(*(["s0"] + ["0"] * (len(StreamToken._fields) - 1)))
 
 
 class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
@@ -395,15 +401,16 @@ class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
     "topological_ordering" id of the event it comes after, followed by "-",
     followed by the "stream_ordering" id of the event it comes after.
     """
+
     __slots__ = []
 
     @classmethod
     def parse(cls, string):
         try:
-            if string[0] == 's':
+            if string[0] == "s":
                 return cls(topological=None, stream=int(string[1:]))
-            if string[0] == 't':
-                parts = string[1:].split('-', 1)
+            if string[0] == "t":
+                parts = string[1:].split("-", 1)
                 return cls(topological=int(parts[0]), stream=int(parts[1]))
         except Exception:
             pass
@@ -412,7 +419,7 @@ class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
     @classmethod
     def parse_stream_token(cls, string):
         try:
-            if string[0] == 's':
+            if string[0] == "s":
                 return cls(topological=None, stream=int(string[1:]))
         except Exception:
             pass
@@ -426,7 +433,7 @@ class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
 
 
 class ThirdPartyInstanceID(
-        namedtuple("ThirdPartyInstanceID", ("appservice_id", "network_id"))
+    namedtuple("ThirdPartyInstanceID", ("appservice_id", "network_id"))
 ):
     # Deny iteration because it will bite you if you try to create a singleton
     # set by:
@@ -450,18 +457,19 @@ class ThirdPartyInstanceID(
         return cls(appservice_id=bits[0], network_id=bits[1])
 
     def to_string(self):
-        return "%s|%s" % (self.appservice_id, self.network_id,)
+        return "%s|%s" % (self.appservice_id, self.network_id)
 
     __str__ = to_string
 
     @classmethod
-    def create(cls, appservice_id, network_id,):
+    def create(cls, appservice_id, network_id):
         return cls(appservice_id=appservice_id, network_id=network_id)
 
 
 @attr.s(slots=True)
 class ReadReceipt(object):
     """Information about a read-receipt"""
+
     room_id = attr.ib()
     receipt_type = attr.ib()
     user_id = attr.ib()