room.py 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014, 2015 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 twisted.internet import defer
  16. from synapse.api.errors import StoreError
  17. from ._base import SQLBaseStore
  18. from synapse.util.caches.descriptors import cachedInlineCallbacks
  19. from .engines import PostgresEngine, Sqlite3Engine
  20. import collections
  21. import logging
  22. logger = logging.getLogger(__name__)
  23. OpsLevel = collections.namedtuple(
  24. "OpsLevel",
  25. ("ban_level", "kick_level", "redact_level",)
  26. )
  27. class RoomStore(SQLBaseStore):
  28. @defer.inlineCallbacks
  29. def store_room(self, room_id, room_creator_user_id, is_public):
  30. """Stores a room.
  31. Args:
  32. room_id (str): The desired room ID, can be None.
  33. room_creator_user_id (str): The user ID of the room creator.
  34. is_public (bool): True to indicate that this room should appear in
  35. public room lists.
  36. Raises:
  37. StoreError if the room could not be stored.
  38. """
  39. try:
  40. yield self._simple_insert(
  41. RoomsTable.table_name,
  42. {
  43. "room_id": room_id,
  44. "creator": room_creator_user_id,
  45. "is_public": is_public,
  46. },
  47. desc="store_room",
  48. )
  49. except Exception as e:
  50. logger.error("store_room with room_id=%s failed: %s", room_id, e)
  51. raise StoreError(500, "Problem creating room.")
  52. def get_room(self, room_id):
  53. """Retrieve a room.
  54. Args:
  55. room_id (str): The ID of the room to retrieve.
  56. Returns:
  57. A namedtuple containing the room information, or an empty list.
  58. """
  59. return self._simple_select_one(
  60. table=RoomsTable.table_name,
  61. keyvalues={"room_id": room_id},
  62. retcols=RoomsTable.fields,
  63. desc="get_room",
  64. allow_none=True,
  65. )
  66. def get_public_room_ids(self):
  67. return self._simple_select_onecol(
  68. table="rooms",
  69. keyvalues={
  70. "is_public": True,
  71. },
  72. retcol="room_id",
  73. desc="get_public_room_ids",
  74. )
  75. @defer.inlineCallbacks
  76. def get_rooms(self, is_public):
  77. """Retrieve a list of all public rooms.
  78. Args:
  79. is_public (bool): True if the rooms returned should be public.
  80. Returns:
  81. A list of room dicts containing at least a "room_id" key, a
  82. "topic" key if one is set, and a "name" key if one is set
  83. """
  84. def f(txn):
  85. topic_subquery = (
  86. "SELECT topics.event_id as event_id, "
  87. "topics.room_id as room_id, topic "
  88. "FROM topics "
  89. "INNER JOIN current_state_events as c "
  90. "ON c.event_id = topics.event_id "
  91. )
  92. name_subquery = (
  93. "SELECT room_names.event_id as event_id, "
  94. "room_names.room_id as room_id, name "
  95. "FROM room_names "
  96. "INNER JOIN current_state_events as c "
  97. "ON c.event_id = room_names.event_id "
  98. )
  99. # We use non printing ascii character US (\x1F) as a separator
  100. sql = (
  101. "SELECT r.room_id, max(n.name), max(t.topic)"
  102. " FROM rooms AS r"
  103. " LEFT JOIN (%(topic)s) AS t ON t.room_id = r.room_id"
  104. " LEFT JOIN (%(name)s) AS n ON n.room_id = r.room_id"
  105. " WHERE r.is_public = ?"
  106. " GROUP BY r.room_id"
  107. ) % {
  108. "topic": topic_subquery,
  109. "name": name_subquery,
  110. }
  111. txn.execute(sql, (is_public,))
  112. rows = txn.fetchall()
  113. for i, row in enumerate(rows):
  114. room_id = row[0]
  115. aliases = self._simple_select_onecol_txn(
  116. txn,
  117. table="room_aliases",
  118. keyvalues={
  119. "room_id": room_id
  120. },
  121. retcol="room_alias",
  122. )
  123. rows[i] = list(row) + [aliases]
  124. return rows
  125. rows = yield self.runInteraction(
  126. "get_rooms", f
  127. )
  128. ret = [
  129. {
  130. "room_id": r[0],
  131. "name": r[1],
  132. "topic": r[2],
  133. "aliases": r[3],
  134. }
  135. for r in rows
  136. if r[3] # We only return rooms that have at least one alias.
  137. ]
  138. defer.returnValue(ret)
  139. def _store_room_topic_txn(self, txn, event):
  140. if hasattr(event, "content") and "topic" in event.content:
  141. self._simple_insert_txn(
  142. txn,
  143. "topics",
  144. {
  145. "event_id": event.event_id,
  146. "room_id": event.room_id,
  147. "topic": event.content["topic"],
  148. },
  149. )
  150. self._store_event_search_txn(
  151. txn, event, "content.topic", event.content["topic"]
  152. )
  153. def _store_room_name_txn(self, txn, event):
  154. if hasattr(event, "content") and "name" in event.content:
  155. self._simple_insert_txn(
  156. txn,
  157. "room_names",
  158. {
  159. "event_id": event.event_id,
  160. "room_id": event.room_id,
  161. "name": event.content["name"],
  162. }
  163. )
  164. self._store_event_search_txn(
  165. txn, event, "content.name", event.content["name"]
  166. )
  167. def _store_room_message_txn(self, txn, event):
  168. if hasattr(event, "content") and "body" in event.content:
  169. self._store_event_search_txn(
  170. txn, event, "content.body", event.content["body"]
  171. )
  172. def _store_event_search_txn(self, txn, event, key, value):
  173. if isinstance(self.database_engine, PostgresEngine):
  174. sql = (
  175. "INSERT INTO event_search (event_id, room_id, key, vector)"
  176. " VALUES (?,?,?,to_tsvector('english', ?))"
  177. )
  178. elif isinstance(self.database_engine, Sqlite3Engine):
  179. sql = (
  180. "INSERT INTO event_search (event_id, room_id, key, value)"
  181. " VALUES (?,?,?,?)"
  182. )
  183. else:
  184. # This should be unreachable.
  185. raise Exception("Unrecognized database engine")
  186. txn.execute(sql, (event.event_id, event.room_id, key, value,))
  187. @cachedInlineCallbacks()
  188. def get_room_name_and_aliases(self, room_id):
  189. def f(txn):
  190. sql = (
  191. "SELECT event_id FROM current_state_events "
  192. "WHERE room_id = ? "
  193. )
  194. sql += " AND ((type = 'm.room.name' AND state_key = '')"
  195. sql += " OR type = 'm.room.aliases')"
  196. txn.execute(sql, (room_id,))
  197. results = self.cursor_to_dict(txn)
  198. return self._parse_events_txn(txn, results)
  199. events = yield self.runInteraction("get_room_name_and_aliases", f)
  200. name = None
  201. aliases = []
  202. for e in events:
  203. if e.type == 'm.room.name':
  204. if 'name' in e.content:
  205. name = e.content['name']
  206. elif e.type == 'm.room.aliases':
  207. if 'aliases' in e.content:
  208. aliases.extend(e.content['aliases'])
  209. defer.returnValue((name, aliases))
  210. class RoomsTable(object):
  211. table_name = "rooms"
  212. fields = [
  213. "room_id",
  214. "is_public",
  215. "creator"
  216. ]