types.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  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. from synapse.api.errors import SynapseError
  16. from collections import namedtuple
  17. Requester = namedtuple("Requester", ["user", "access_token_id", "is_guest"])
  18. def get_domain_from_id(string):
  19. return string.split(":", 1)[1]
  20. class DomainSpecificString(
  21. namedtuple("DomainSpecificString", ("localpart", "domain"))
  22. ):
  23. """Common base class among ID/name strings that have a local part and a
  24. domain name, prefixed with a sigil.
  25. Has the fields:
  26. 'localpart' : The local part of the name (without the leading sigil)
  27. 'domain' : The domain part of the name
  28. """
  29. # Deny iteration because it will bite you if you try to create a singleton
  30. # set by:
  31. # users = set(user)
  32. def __iter__(self):
  33. raise ValueError("Attempted to iterate a %s" % (type(self).__name__,))
  34. # Because this class is a namedtuple of strings and booleans, it is deeply
  35. # immutable.
  36. def __copy__(self):
  37. return self
  38. def __deepcopy__(self, memo):
  39. return self
  40. @classmethod
  41. def from_string(cls, s):
  42. """Parse the string given by 's' into a structure object."""
  43. if len(s) < 1 or s[0] != cls.SIGIL:
  44. raise SynapseError(400, "Expected %s string to start with '%s'" % (
  45. cls.__name__, cls.SIGIL,
  46. ))
  47. parts = s[1:].split(':', 1)
  48. if len(parts) != 2:
  49. raise SynapseError(
  50. 400, "Expected %s of the form '%slocalname:domain'" % (
  51. cls.__name__, cls.SIGIL,
  52. )
  53. )
  54. domain = parts[1]
  55. # This code will need changing if we want to support multiple domain
  56. # names on one HS
  57. return cls(localpart=parts[0], domain=domain)
  58. def to_string(self):
  59. """Return a string encoding the fields of the structure object."""
  60. return "%s%s:%s" % (self.SIGIL, self.localpart, self.domain)
  61. @classmethod
  62. def is_valid(cls, s):
  63. try:
  64. cls.from_string(s)
  65. return True
  66. except:
  67. return False
  68. __str__ = to_string
  69. @classmethod
  70. def create(cls, localpart, domain,):
  71. return cls(localpart=localpart, domain=domain)
  72. class UserID(DomainSpecificString):
  73. """Structure representing a user ID."""
  74. SIGIL = "@"
  75. class RoomAlias(DomainSpecificString):
  76. """Structure representing a room name."""
  77. SIGIL = "#"
  78. class RoomID(DomainSpecificString):
  79. """Structure representing a room id. """
  80. SIGIL = "!"
  81. class EventID(DomainSpecificString):
  82. """Structure representing an event id. """
  83. SIGIL = "$"
  84. class StreamToken(
  85. namedtuple("Token", (
  86. "room_key",
  87. "presence_key",
  88. "typing_key",
  89. "receipt_key",
  90. "account_data_key",
  91. "push_rules_key",
  92. ))
  93. ):
  94. _SEPARATOR = "_"
  95. @classmethod
  96. def from_string(cls, string):
  97. try:
  98. keys = string.split(cls._SEPARATOR)
  99. while len(keys) < len(cls._fields):
  100. # i.e. old token from before receipt_key
  101. keys.append("0")
  102. return cls(*keys)
  103. except:
  104. raise SynapseError(400, "Invalid Token")
  105. def to_string(self):
  106. return self._SEPARATOR.join([str(k) for k in self])
  107. @property
  108. def room_stream_id(self):
  109. # TODO(markjh): Awful hack to work around hacks in the presence tests
  110. # which assume that the keys are integers.
  111. if type(self.room_key) is int:
  112. return self.room_key
  113. else:
  114. return int(self.room_key[1:].split("-")[-1])
  115. def is_after(self, other):
  116. """Does this token contain events that the other doesn't?"""
  117. return (
  118. (other.room_stream_id < self.room_stream_id)
  119. or (int(other.presence_key) < int(self.presence_key))
  120. or (int(other.typing_key) < int(self.typing_key))
  121. or (int(other.receipt_key) < int(self.receipt_key))
  122. or (int(other.account_data_key) < int(self.account_data_key))
  123. or (int(other.push_rules_key) < int(self.push_rules_key))
  124. )
  125. def copy_and_advance(self, key, new_value):
  126. """Advance the given key in the token to a new value if and only if the
  127. new value is after the old value.
  128. """
  129. new_token = self.copy_and_replace(key, new_value)
  130. if key == "room_key":
  131. new_id = new_token.room_stream_id
  132. old_id = self.room_stream_id
  133. else:
  134. new_id = int(getattr(new_token, key))
  135. old_id = int(getattr(self, key))
  136. if old_id < new_id:
  137. return new_token
  138. else:
  139. return self
  140. def copy_and_replace(self, key, new_value):
  141. d = self._asdict()
  142. d[key] = new_value
  143. return StreamToken(**d)
  144. StreamToken.START = StreamToken(
  145. *(["s0"] + ["0"] * (len(StreamToken._fields) - 1))
  146. )
  147. class RoomStreamToken(namedtuple("_StreamToken", "topological stream")):
  148. """Tokens are positions between events. The token "s1" comes after event 1.
  149. s0 s1
  150. | |
  151. [0] V [1] V [2]
  152. Tokens can either be a point in the live event stream or a cursor going
  153. through historic events.
  154. When traversing the live event stream events are ordered by when they
  155. arrived at the homeserver.
  156. When traversing historic events the events are ordered by their depth in
  157. the event graph "topological_ordering" and then by when they arrived at the
  158. homeserver "stream_ordering".
  159. Live tokens start with an "s" followed by the "stream_ordering" id of the
  160. event it comes after. Historic tokens start with a "t" followed by the
  161. "topological_ordering" id of the event it comes after, followed by "-",
  162. followed by the "stream_ordering" id of the event it comes after.
  163. """
  164. __slots__ = []
  165. @classmethod
  166. def parse(cls, string):
  167. try:
  168. if string[0] == 's':
  169. return cls(topological=None, stream=int(string[1:]))
  170. if string[0] == 't':
  171. parts = string[1:].split('-', 1)
  172. return cls(topological=int(parts[0]), stream=int(parts[1]))
  173. except:
  174. pass
  175. raise SynapseError(400, "Invalid token %r" % (string,))
  176. @classmethod
  177. def parse_stream_token(cls, string):
  178. try:
  179. if string[0] == 's':
  180. return cls(topological=None, stream=int(string[1:]))
  181. except:
  182. pass
  183. raise SynapseError(400, "Invalid token %r" % (string,))
  184. def __str__(self):
  185. if self.topological is not None:
  186. return "t%d-%d" % (self.topological, self.stream)
  187. else:
  188. return "s%d" % (self.stream,)