room_list.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521
  1. # Copyright 2014 - 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Any, Optional, Tuple
  16. import attr
  17. import msgpack
  18. from unpaddedbase64 import decode_base64, encode_base64
  19. from synapse.api.constants import (
  20. EventContentFields,
  21. EventTypes,
  22. GuestAccess,
  23. HistoryVisibility,
  24. JoinRules,
  25. )
  26. from synapse.api.errors import (
  27. Codes,
  28. HttpResponseException,
  29. RequestSendFailed,
  30. SynapseError,
  31. )
  32. from synapse.types import JsonDict, ThirdPartyInstanceID
  33. from synapse.util.caches.descriptors import _CacheContext, cached
  34. from synapse.util.caches.response_cache import ResponseCache
  35. if TYPE_CHECKING:
  36. from synapse.server import HomeServer
  37. logger = logging.getLogger(__name__)
  38. REMOTE_ROOM_LIST_POLL_INTERVAL = 60 * 1000
  39. # This is used to indicate we should only return rooms published to the main list.
  40. EMPTY_THIRD_PARTY_ID = ThirdPartyInstanceID(None, None)
  41. class RoomListHandler:
  42. def __init__(self, hs: "HomeServer"):
  43. self.store = hs.get_datastores().main
  44. self.hs = hs
  45. self.enable_room_list_search = hs.config.roomdirectory.enable_room_list_search
  46. self.response_cache: ResponseCache[
  47. Tuple[Optional[int], Optional[str], Optional[ThirdPartyInstanceID]]
  48. ] = ResponseCache(hs.get_clock(), "room_list")
  49. self.remote_response_cache: ResponseCache[
  50. Tuple[str, Optional[int], Optional[str], bool, Optional[str]]
  51. ] = ResponseCache(hs.get_clock(), "remote_room_list", timeout_ms=30 * 1000)
  52. async def get_local_public_room_list(
  53. self,
  54. limit: Optional[int] = None,
  55. since_token: Optional[str] = None,
  56. search_filter: Optional[dict] = None,
  57. network_tuple: Optional[ThirdPartyInstanceID] = EMPTY_THIRD_PARTY_ID,
  58. from_federation: bool = False,
  59. ) -> JsonDict:
  60. """Generate a local public room list.
  61. There are multiple different lists: the main one plus one per third
  62. party network. A client can ask for a specific list or to return all.
  63. Args:
  64. limit
  65. since_token
  66. search_filter
  67. network_tuple: Which public list to use.
  68. This can be (None, None) to indicate the main list, or a particular
  69. appservice and network id to use an appservice specific one.
  70. Setting to None returns all public rooms across all lists.
  71. from_federation: true iff the request comes from the federation API
  72. """
  73. if not self.enable_room_list_search:
  74. return {"chunk": [], "total_room_count_estimate": 0}
  75. logger.info(
  76. "Getting public room list: limit=%r, since=%r, search=%r, network=%r",
  77. limit,
  78. since_token,
  79. bool(search_filter),
  80. network_tuple,
  81. )
  82. if search_filter:
  83. # We explicitly don't bother caching searches or requests for
  84. # appservice specific lists.
  85. logger.info("Bypassing cache as search request.")
  86. return await self._get_public_room_list(
  87. limit,
  88. since_token,
  89. search_filter,
  90. network_tuple=network_tuple,
  91. from_federation=from_federation,
  92. )
  93. key = (limit, since_token, network_tuple)
  94. return await self.response_cache.wrap(
  95. key,
  96. self._get_public_room_list,
  97. limit,
  98. since_token,
  99. network_tuple=network_tuple,
  100. from_federation=from_federation,
  101. )
  102. async def _get_public_room_list(
  103. self,
  104. limit: Optional[int] = None,
  105. since_token: Optional[str] = None,
  106. search_filter: Optional[dict] = None,
  107. network_tuple: Optional[ThirdPartyInstanceID] = EMPTY_THIRD_PARTY_ID,
  108. from_federation: bool = False,
  109. ) -> JsonDict:
  110. """Generate a public room list.
  111. Args:
  112. limit: Maximum amount of rooms to return.
  113. since_token:
  114. search_filter: Dictionary to filter rooms by.
  115. network_tuple: Which public list to use.
  116. This can be (None, None) to indicate the main list, or a particular
  117. appservice and network id to use an appservice specific one.
  118. Setting to None returns all public rooms across all lists.
  119. from_federation: Whether this request originated from a
  120. federating server or a client. Used for room filtering.
  121. """
  122. # Pagination tokens work by storing the room ID sent in the last batch,
  123. # plus the direction (forwards or backwards). Next batch tokens always
  124. # go forwards, prev batch tokens always go backwards.
  125. if since_token:
  126. batch_token = RoomListNextBatch.from_token(since_token)
  127. bounds: Optional[Tuple[int, str]] = (
  128. batch_token.last_joined_members,
  129. batch_token.last_room_id,
  130. )
  131. forwards = batch_token.direction_is_forward
  132. has_batch_token = True
  133. else:
  134. bounds = None
  135. forwards = True
  136. has_batch_token = False
  137. # we request one more than wanted to see if there are more pages to come
  138. probing_limit = limit + 1 if limit is not None else None
  139. results = await self.store.get_largest_public_rooms(
  140. network_tuple,
  141. search_filter,
  142. probing_limit,
  143. bounds=bounds,
  144. forwards=forwards,
  145. ignore_non_federatable=from_federation,
  146. )
  147. def build_room_entry(room: JsonDict) -> JsonDict:
  148. entry = {
  149. "room_id": room["room_id"],
  150. "name": room["name"],
  151. "topic": room["topic"],
  152. "canonical_alias": room["canonical_alias"],
  153. "num_joined_members": room["joined_members"],
  154. "avatar_url": room["avatar"],
  155. "world_readable": room["history_visibility"]
  156. == HistoryVisibility.WORLD_READABLE,
  157. "guest_can_join": room["guest_access"] == "can_join",
  158. "join_rule": room["join_rules"],
  159. }
  160. # Filter out Nones – rather omit the field altogether
  161. return {k: v for k, v in entry.items() if v is not None}
  162. results = [build_room_entry(r) for r in results]
  163. response: JsonDict = {}
  164. num_results = len(results)
  165. if limit is not None:
  166. more_to_come = num_results == probing_limit
  167. # Depending on direction we trim either the front or back.
  168. if forwards:
  169. results = results[:limit]
  170. else:
  171. results = results[-limit:]
  172. else:
  173. more_to_come = False
  174. if num_results > 0:
  175. final_entry = results[-1]
  176. initial_entry = results[0]
  177. if forwards:
  178. if has_batch_token:
  179. # If there was a token given then we assume that there
  180. # must be previous results.
  181. response["prev_batch"] = RoomListNextBatch(
  182. last_joined_members=initial_entry["num_joined_members"],
  183. last_room_id=initial_entry["room_id"],
  184. direction_is_forward=False,
  185. ).to_token()
  186. if more_to_come:
  187. response["next_batch"] = RoomListNextBatch(
  188. last_joined_members=final_entry["num_joined_members"],
  189. last_room_id=final_entry["room_id"],
  190. direction_is_forward=True,
  191. ).to_token()
  192. else:
  193. if has_batch_token:
  194. response["next_batch"] = RoomListNextBatch(
  195. last_joined_members=final_entry["num_joined_members"],
  196. last_room_id=final_entry["room_id"],
  197. direction_is_forward=True,
  198. ).to_token()
  199. if more_to_come:
  200. response["prev_batch"] = RoomListNextBatch(
  201. last_joined_members=initial_entry["num_joined_members"],
  202. last_room_id=initial_entry["room_id"],
  203. direction_is_forward=False,
  204. ).to_token()
  205. response["chunk"] = results
  206. response["total_room_count_estimate"] = await self.store.count_public_rooms(
  207. network_tuple, ignore_non_federatable=from_federation
  208. )
  209. return response
  210. @cached(num_args=1, cache_context=True)
  211. async def generate_room_entry(
  212. self,
  213. room_id: str,
  214. num_joined_users: int,
  215. cache_context: _CacheContext,
  216. with_alias: bool = True,
  217. allow_private: bool = False,
  218. ) -> Optional[JsonDict]:
  219. """Returns the entry for a room
  220. Args:
  221. room_id: The room's ID.
  222. num_joined_users: Number of users in the room.
  223. cache_context: Information for cached responses.
  224. with_alias: Whether to return the room's aliases in the result.
  225. allow_private: Whether invite-only rooms should be shown.
  226. Returns:
  227. Returns a room entry as a dictionary, or None if this
  228. room was determined not to be shown publicly.
  229. """
  230. result = {"room_id": room_id, "num_joined_members": num_joined_users}
  231. if with_alias:
  232. aliases = await self.store.get_aliases_for_room(
  233. room_id, on_invalidate=cache_context.invalidate
  234. )
  235. if aliases:
  236. result["aliases"] = aliases
  237. current_state_ids = await self.store.get_current_state_ids(
  238. room_id, on_invalidate=cache_context.invalidate
  239. )
  240. if not current_state_ids:
  241. # We're not in the room, so may as well bail out here.
  242. return result
  243. event_map = await self.store.get_events(
  244. [
  245. event_id
  246. for key, event_id in current_state_ids.items()
  247. if key[0]
  248. in (
  249. EventTypes.Create,
  250. EventTypes.JoinRules,
  251. EventTypes.Name,
  252. EventTypes.Topic,
  253. EventTypes.CanonicalAlias,
  254. EventTypes.RoomHistoryVisibility,
  255. EventTypes.GuestAccess,
  256. "m.room.avatar",
  257. )
  258. ]
  259. )
  260. current_state = {(ev.type, ev.state_key): ev for ev in event_map.values()}
  261. # Double check that this is actually a public room.
  262. join_rules_event = current_state.get((EventTypes.JoinRules, ""))
  263. if join_rules_event:
  264. join_rule = join_rules_event.content.get("join_rule", None)
  265. if not allow_private and join_rule and join_rule != JoinRules.PUBLIC:
  266. return None
  267. # Return whether this room is open to federation users or not
  268. create_event = current_state[EventTypes.Create, ""]
  269. result["m.federate"] = create_event.content.get(
  270. EventContentFields.FEDERATE, True
  271. )
  272. name_event = current_state.get((EventTypes.Name, ""))
  273. if name_event:
  274. name = name_event.content.get("name", None)
  275. if name:
  276. result["name"] = name
  277. topic_event = current_state.get((EventTypes.Topic, ""))
  278. if topic_event:
  279. topic = topic_event.content.get("topic", None)
  280. if topic:
  281. result["topic"] = topic
  282. canonical_event = current_state.get((EventTypes.CanonicalAlias, ""))
  283. if canonical_event:
  284. canonical_alias = canonical_event.content.get("alias", None)
  285. if canonical_alias:
  286. result["canonical_alias"] = canonical_alias
  287. visibility_event = current_state.get((EventTypes.RoomHistoryVisibility, ""))
  288. visibility = None
  289. if visibility_event:
  290. visibility = visibility_event.content.get("history_visibility", None)
  291. result["world_readable"] = visibility == HistoryVisibility.WORLD_READABLE
  292. guest_event = current_state.get((EventTypes.GuestAccess, ""))
  293. guest = None
  294. if guest_event:
  295. guest = guest_event.content.get(EventContentFields.GUEST_ACCESS)
  296. result["guest_can_join"] = guest == GuestAccess.CAN_JOIN
  297. avatar_event = current_state.get(("m.room.avatar", ""))
  298. if avatar_event:
  299. avatar_url = avatar_event.content.get("url", None)
  300. if avatar_url:
  301. result["avatar_url"] = avatar_url
  302. return result
  303. async def get_remote_public_room_list(
  304. self,
  305. server_name: str,
  306. limit: Optional[int] = None,
  307. since_token: Optional[str] = None,
  308. search_filter: Optional[dict] = None,
  309. include_all_networks: bool = False,
  310. third_party_instance_id: Optional[str] = None,
  311. ) -> JsonDict:
  312. """Get the public room list from remote server
  313. Raises:
  314. SynapseError
  315. """
  316. if not self.enable_room_list_search:
  317. return {"chunk": [], "total_room_count_estimate": 0}
  318. if search_filter:
  319. # Searching across federation is defined in MSC2197.
  320. # However, the remote homeserver may or may not actually support it.
  321. # So we first try an MSC2197 remote-filtered search, then fall back
  322. # to a locally-filtered search if we must.
  323. try:
  324. res = await self._get_remote_list_cached(
  325. server_name,
  326. limit=limit,
  327. since_token=since_token,
  328. include_all_networks=include_all_networks,
  329. third_party_instance_id=third_party_instance_id,
  330. search_filter=search_filter,
  331. )
  332. return res
  333. except HttpResponseException as hre:
  334. syn_err = hre.to_synapse_error()
  335. if hre.code in (404, 405) or syn_err.errcode in (
  336. Codes.UNRECOGNIZED,
  337. Codes.NOT_FOUND,
  338. ):
  339. logger.debug("Falling back to locally-filtered /publicRooms")
  340. else:
  341. # Not an error that should trigger a fallback.
  342. raise SynapseError(502, "Failed to fetch room list")
  343. except RequestSendFailed:
  344. # Not an error that should trigger a fallback.
  345. raise SynapseError(502, "Failed to fetch room list")
  346. # if we reach this point, then we fall back to the situation where
  347. # we currently don't support searching across federation, so we have
  348. # to do it manually without pagination
  349. limit = None
  350. since_token = None
  351. try:
  352. res = await self._get_remote_list_cached(
  353. server_name,
  354. limit=limit,
  355. since_token=since_token,
  356. include_all_networks=include_all_networks,
  357. third_party_instance_id=third_party_instance_id,
  358. )
  359. except (RequestSendFailed, HttpResponseException):
  360. raise SynapseError(502, "Failed to fetch room list")
  361. if search_filter:
  362. res = {
  363. "chunk": [
  364. entry
  365. for entry in list(res.get("chunk", []))
  366. if _matches_room_entry(entry, search_filter)
  367. ]
  368. }
  369. return res
  370. async def _get_remote_list_cached(
  371. self,
  372. server_name: str,
  373. limit: Optional[int] = None,
  374. since_token: Optional[str] = None,
  375. search_filter: Optional[dict] = None,
  376. include_all_networks: bool = False,
  377. third_party_instance_id: Optional[str] = None,
  378. ) -> JsonDict:
  379. """Wrapper around FederationClient.get_public_rooms that caches the
  380. result.
  381. """
  382. repl_layer = self.hs.get_federation_client()
  383. if search_filter:
  384. # We can't cache when asking for search
  385. return await repl_layer.get_public_rooms(
  386. server_name,
  387. limit=limit,
  388. since_token=since_token,
  389. search_filter=search_filter,
  390. include_all_networks=include_all_networks,
  391. third_party_instance_id=third_party_instance_id,
  392. )
  393. key = (
  394. server_name,
  395. limit,
  396. since_token,
  397. include_all_networks,
  398. third_party_instance_id,
  399. )
  400. return await self.remote_response_cache.wrap(
  401. key,
  402. repl_layer.get_public_rooms,
  403. server_name,
  404. limit=limit,
  405. since_token=since_token,
  406. search_filter=search_filter,
  407. include_all_networks=include_all_networks,
  408. third_party_instance_id=third_party_instance_id,
  409. )
  410. @attr.s(slots=True, frozen=True, auto_attribs=True)
  411. class RoomListNextBatch:
  412. last_joined_members: int # The count to get rooms after/before
  413. last_room_id: str # The room_id to get rooms after/before
  414. direction_is_forward: bool # True if this is a next_batch, false if prev_batch
  415. KEY_DICT = {
  416. "last_joined_members": "m",
  417. "last_room_id": "r",
  418. "direction_is_forward": "d",
  419. }
  420. REVERSE_KEY_DICT = {v: k for k, v in KEY_DICT.items()}
  421. @classmethod
  422. def from_token(cls, token: str) -> "RoomListNextBatch":
  423. decoded = msgpack.loads(decode_base64(token), raw=False)
  424. return RoomListNextBatch(
  425. **{cls.REVERSE_KEY_DICT[key]: val for key, val in decoded.items()}
  426. )
  427. def to_token(self) -> str:
  428. return encode_base64(
  429. msgpack.dumps(
  430. {self.KEY_DICT[key]: val for key, val in attr.asdict(self).items()}
  431. )
  432. )
  433. def copy_and_replace(self, **kwds: Any) -> "RoomListNextBatch":
  434. return attr.evolve(self, **kwds)
  435. def _matches_room_entry(room_entry: JsonDict, search_filter: dict) -> bool:
  436. if search_filter and search_filter.get("generic_search_term", None):
  437. generic_search_term = search_filter["generic_search_term"].upper()
  438. if generic_search_term in room_entry.get("name", "").upper():
  439. return True
  440. elif generic_search_term in room_entry.get("topic", "").upper():
  441. return True
  442. elif generic_search_term in room_entry.get("canonical_alias", "").upper():
  443. return True
  444. else:
  445. return True
  446. return False