types.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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 string
  16. from collections import namedtuple
  17. from synapse.api.errors import SynapseError
  18. class Requester(namedtuple("Requester", [
  19. "user", "access_token_id", "is_guest", "device_id", "app_service",
  20. ])):
  21. """
  22. Represents the user making a request
  23. Attributes:
  24. user (UserID): id of the user making the request
  25. access_token_id (int|None): *ID* of the access token used for this
  26. request, or None if it came via the appservice API or similar
  27. is_guest (bool): True if the user making this request is a guest user
  28. device_id (str|None): device_id which was set at authentication time
  29. app_service (ApplicationService|None): the AS requesting on behalf of the user
  30. """
  31. def serialize(self):
  32. """Converts self to a type that can be serialized as JSON, and then
  33. deserialized by `deserialize`
  34. Returns:
  35. dict
  36. """
  37. return {
  38. "user_id": self.user.to_string(),
  39. "access_token_id": self.access_token_id,
  40. "is_guest": self.is_guest,
  41. "device_id": self.device_id,
  42. "app_server_id": self.app_service.id if self.app_service else None,
  43. }
  44. @staticmethod
  45. def deserialize(store, input):
  46. """Converts a dict that was produced by `serialize` back into a
  47. Requester.
  48. Args:
  49. store (DataStore): Used to convert AS ID to AS object
  50. input (dict): A dict produced by `serialize`
  51. Returns:
  52. Requester
  53. """
  54. appservice = None
  55. if input["app_server_id"]:
  56. appservice = store.get_app_service_by_id(input["app_server_id"])
  57. return Requester(
  58. user=UserID.from_string(input["user_id"]),
  59. access_token_id=input["access_token_id"],
  60. is_guest=input["is_guest"],
  61. device_id=input["device_id"],
  62. app_service=appservice,
  63. )
  64. def create_requester(user_id, access_token_id=None, is_guest=False,
  65. device_id=None, app_service=None):
  66. """
  67. Create a new ``Requester`` object
  68. Args:
  69. user_id (str|UserID): id of the user making the request
  70. access_token_id (int|None): *ID* of the access token used for this
  71. request, or None if it came via the appservice API or similar
  72. is_guest (bool): True if the user making this request is a guest user
  73. device_id (str|None): device_id which was set at authentication time
  74. app_service (ApplicationService|None): the AS requesting on behalf of the user
  75. Returns:
  76. Requester
  77. """
  78. if not isinstance(user_id, UserID):
  79. user_id = UserID.from_string(user_id)
  80. return Requester(user_id, access_token_id, is_guest, device_id, app_service)
  81. def get_domain_from_id(string):
  82. idx = string.find(":")
  83. if idx == -1:
  84. raise SynapseError(400, "Invalid ID: %r" % (string,))
  85. return string[idx + 1:]
  86. def get_localpart_from_id(string):
  87. idx = string.find(":")
  88. if idx == -1:
  89. raise SynapseError(400, "Invalid ID: %r" % (string,))
  90. return string[1:idx]
  91. class DomainSpecificString(
  92. namedtuple("DomainSpecificString", ("localpart", "domain"))
  93. ):
  94. """Common base class among ID/name strings that have a local part and a
  95. domain name, prefixed with a sigil.
  96. Has the fields:
  97. 'localpart' : The local part of the name (without the leading sigil)
  98. 'domain' : The domain part of the name
  99. """
  100. # Deny iteration because it will bite you if you try to create a singleton
  101. # set by:
  102. # users = set(user)
  103. def __iter__(self):
  104. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  105. # Because this class is a namedtuple of strings and booleans, it is deeply
  106. # immutable.
  107. def __copy__(self):
  108. return self
  109. def __deepcopy__(self, memo):
  110. return self
  111. @classmethod
  112. def from_string(cls, s):
  113. """Parse the string given by 's' into a structure object."""
  114. if len(s) < 1 or s[0:1] != cls.SIGIL:
  115. raise SynapseError(400, "Expected %s string to start with '%s'" % (
  116. cls.__name__, cls.SIGIL,
  117. ))
  118. parts = s[1:].split(':', 1)
  119. if len(parts) != 2:
  120. raise SynapseError(
  121. 400, "Expected %s of the form '%slocalname:domain'" % (
  122. cls.__name__, cls.SIGIL,
  123. )
  124. )
  125. domain = parts[1]
  126. # This code will need changing if we want to support multiple domain
  127. # names on one HS
  128. return cls(localpart=parts[0], domain=domain)
  129. def to_string(self):
  130. """Return a string encoding the fields of the structure object."""
  131. return "%s%s:%s" % (self.SIGIL, self.localpart, self.domain)
  132. @classmethod
  133. def is_valid(cls, s):
  134. try:
  135. cls.from_string(s)
  136. return True
  137. except Exception:
  138. return False
  139. __repr__ = to_string
  140. class UserID(DomainSpecificString):
  141. """Structure representing a user ID."""
  142. SIGIL = "@"
  143. class RoomAlias(DomainSpecificString):
  144. """Structure representing a room name."""
  145. SIGIL = "#"
  146. class RoomID(DomainSpecificString):
  147. """Structure representing a room id. """
  148. SIGIL = "!"
  149. class EventID(DomainSpecificString):
  150. """Structure representing an event id. """
  151. SIGIL = "$"
  152. class GroupID(DomainSpecificString):
  153. """Structure representing a group ID."""
  154. SIGIL = "+"
  155. @classmethod
  156. def from_string(cls, s):
  157. group_id = super(GroupID, cls).from_string(s)
  158. if not group_id.localpart:
  159. raise SynapseError(
  160. 400,
  161. "Group ID cannot be empty",
  162. )
  163. if contains_invalid_mxid_characters(group_id.localpart):
  164. raise SynapseError(
  165. 400,
  166. "Group ID can only contain characters a-z, 0-9, or '=_-./'",
  167. )
  168. return group_id
  169. mxid_localpart_allowed_characters = set("_-./=" + string.ascii_lowercase + string.digits)
  170. def contains_invalid_mxid_characters(localpart):
  171. """Check for characters not allowed in an mxid or groupid localpart
  172. Args:
  173. localpart (basestring): the localpart to be checked
  174. Returns:
  175. bool: True if there are any naughty characters
  176. """
  177. return any(c not in mxid_localpart_allowed_characters for c in localpart)
  178. def strip_invalid_mxid_characters(localpart):
  179. """Removes any invalid characters from an mxid
  180. Args:
  181. localpart (basestring): the localpart to be stripped
  182. Returns:
  183. localpart (basestring): the localpart having been stripped
  184. """
  185. return filter(lambda c: c in mxid_localpart_allowed_characters, localpart)
  186. class StreamToken(
  187. namedtuple("Token", (
  188. "room_key",
  189. "presence_key",
  190. "typing_key",
  191. "receipt_key",
  192. "account_data_key",
  193. "push_rules_key",
  194. "to_device_key",
  195. "device_list_key",
  196. "groups_key",
  197. ))
  198. ):
  199. _SEPARATOR = "_"
  200. @classmethod
  201. def from_string(cls, string):
  202. try:
  203. keys = string.split(cls._SEPARATOR)
  204. while len(keys) < len(cls._fields):
  205. # i.e. old token from before receipt_key
  206. keys.append("0")
  207. return cls(*keys)
  208. except Exception:
  209. raise SynapseError(400, "Invalid Token")
  210. def to_string(self):
  211. return self._SEPARATOR.join([str(k) for k in self])
  212. @property
  213. def room_stream_id(self):
  214. # TODO(markjh): Awful hack to work around hacks in the presence tests
  215. # which assume that the keys are integers.
  216. if type(self.room_key) is int:
  217. return self.room_key
  218. else:
  219. return int(self.room_key[1:].split("-")[-1])
  220. def is_after(self, other):
  221. """Does this token contain events that the other doesn't?"""
  222. return (
  223. (other.room_stream_id < self.room_stream_id)
  224. or (int(other.presence_key) < int(self.presence_key))
  225. or (int(other.typing_key) < int(self.typing_key))
  226. or (int(other.receipt_key) < int(self.receipt_key))
  227. or (int(other.account_data_key) < int(self.account_data_key))
  228. or (int(other.push_rules_key) < int(self.push_rules_key))
  229. or (int(other.to_device_key) < int(self.to_device_key))
  230. or (int(other.device_list_key) < int(self.device_list_key))
  231. or (int(other.groups_key) < int(self.groups_key))
  232. )
  233. def copy_and_advance(self, key, new_value):
  234. """Advance the given key in the token to a new value if and only if the
  235. new value is after the old value.
  236. """
  237. new_token = self.copy_and_replace(key, new_value)
  238. if key == "room_key":
  239. new_id = new_token.room_stream_id
  240. old_id = self.room_stream_id
  241. else:
  242. new_id = int(getattr(new_token, key))
  243. old_id = int(getattr(self, key))
  244. if old_id < new_id:
  245. return new_token
  246. else:
  247. return self
  248. def copy_and_replace(self, key, new_value):
  249. return self._replace(**{key: new_value})
  250. StreamToken.START = StreamToken(
  251. *(["s0"] + ["0"] * (len(StreamToken._fields) - 1))
  252. )
  253. class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
  254. """Tokens are positions between events. The token "s1" comes after event 1.
  255. s0 s1
  256. | |
  257. [0] V [1] V [2]
  258. Tokens can either be a point in the live event stream or a cursor going
  259. through historic events.
  260. When traversing the live event stream events are ordered by when they
  261. arrived at the homeserver.
  262. When traversing historic events the events are ordered by their depth in
  263. the event graph "topological_ordering" and then by when they arrived at the
  264. homeserver "stream_ordering".
  265. Live tokens start with an "s" followed by the "stream_ordering" id of the
  266. event it comes after. Historic tokens start with a "t" followed by the
  267. "topological_ordering" id of the event it comes after, followed by "-",
  268. followed by the "stream_ordering" id of the event it comes after.
  269. """
  270. __slots__ = []
  271. @classmethod
  272. def parse(cls, string):
  273. try:
  274. if string[0] == 's':
  275. return cls(topological=None, stream=int(string[1:]))
  276. if string[0] == 't':
  277. parts = string[1:].split('-', 1)
  278. return cls(topological=int(parts[0]), stream=int(parts[1]))
  279. except Exception:
  280. pass
  281. raise SynapseError(400, "Invalid token %r" % (string,))
  282. @classmethod
  283. def parse_stream_token(cls, string):
  284. try:
  285. if string[0] == 's':
  286. return cls(topological=None, stream=int(string[1:]))
  287. except Exception:
  288. pass
  289. raise SynapseError(400, "Invalid token %r" % (string,))
  290. def __str__(self):
  291. if self.topological is not None:
  292. return "t%d-%d" % (self.topological, self.stream)
  293. else:
  294. return "s%d" % (self.stream,)
  295. class ThirdPartyInstanceID(
  296. namedtuple("ThirdPartyInstanceID", ("appservice_id", "network_id"))
  297. ):
  298. # Deny iteration because it will bite you if you try to create a singleton
  299. # set by:
  300. # users = set(user)
  301. def __iter__(self):
  302. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  303. # Because this class is a namedtuple of strings, it is deeply immutable.
  304. def __copy__(self):
  305. return self
  306. def __deepcopy__(self, memo):
  307. return self
  308. @classmethod
  309. def from_string(cls, s):
  310. bits = s.split("|", 2)
  311. if len(bits) != 2:
  312. raise SynapseError(400, "Invalid ID %r" % (s,))
  313. return cls(appservice_id=bits[0], network_id=bits[1])
  314. def to_string(self):
  315. return "%s|%s" % (self.appservice_id, self.network_id,)
  316. __str__ = to_string
  317. @classmethod
  318. def create(cls, appservice_id, network_id,):
  319. return cls(appservice_id=appservice_id, network_id=network_id)