search.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  1. # Copyright 2015, 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 itertools
  15. import logging
  16. from typing import TYPE_CHECKING, Collection, Dict, Iterable, List, Optional, Set, Tuple
  17. import attr
  18. from unpaddedbase64 import decode_base64, encode_base64
  19. from synapse.api.constants import EventTypes, Membership
  20. from synapse.api.errors import NotFoundError, SynapseError
  21. from synapse.api.filtering import Filter
  22. from synapse.events import EventBase
  23. from synapse.storage.state import StateFilter
  24. from synapse.types import JsonDict, StreamKeyType, UserID
  25. from synapse.visibility import filter_events_for_client
  26. if TYPE_CHECKING:
  27. from synapse.server import HomeServer
  28. logger = logging.getLogger(__name__)
  29. @attr.s(slots=True, frozen=True, auto_attribs=True)
  30. class _SearchResult:
  31. # The count of results.
  32. count: int
  33. # A mapping of event ID to the rank of that event.
  34. rank_map: Dict[str, int]
  35. # A list of the resulting events.
  36. allowed_events: List[EventBase]
  37. # A map of room ID to results.
  38. room_groups: Dict[str, JsonDict]
  39. # A set of event IDs to highlight.
  40. highlights: Set[str]
  41. class SearchHandler:
  42. def __init__(self, hs: "HomeServer"):
  43. self.store = hs.get_datastores().main
  44. self.state_handler = hs.get_state_handler()
  45. self.clock = hs.get_clock()
  46. self.hs = hs
  47. self._event_serializer = hs.get_event_client_serializer()
  48. self._relations_handler = hs.get_relations_handler()
  49. self.storage = hs.get_storage()
  50. self.state_store = self.storage.state
  51. self.auth = hs.get_auth()
  52. async def get_old_rooms_from_upgraded_room(self, room_id: str) -> Iterable[str]:
  53. """Retrieves room IDs of old rooms in the history of an upgraded room.
  54. We do so by checking the m.room.create event of the room for a
  55. `predecessor` key. If it exists, we add the room ID to our return
  56. list and then check that room for a m.room.create event and so on
  57. until we can no longer find any more previous rooms.
  58. The full list of all found rooms in then returned.
  59. Args:
  60. room_id: id of the room to search through.
  61. Returns:
  62. Predecessor room ids
  63. """
  64. historical_room_ids = []
  65. # The initial room must have been known for us to get this far
  66. predecessor = await self.store.get_room_predecessor(room_id)
  67. while True:
  68. if not predecessor:
  69. # We have reached the end of the chain of predecessors
  70. break
  71. if not isinstance(predecessor.get("room_id"), str):
  72. # This predecessor object is malformed. Exit here
  73. break
  74. predecessor_room_id = predecessor["room_id"]
  75. # Don't add it to the list until we have checked that we are in the room
  76. try:
  77. next_predecessor_room = await self.store.get_room_predecessor(
  78. predecessor_room_id
  79. )
  80. except NotFoundError:
  81. # The predecessor is not a known room, so we are done here
  82. break
  83. historical_room_ids.append(predecessor_room_id)
  84. # And repeat
  85. predecessor = next_predecessor_room
  86. return historical_room_ids
  87. async def search(
  88. self, user: UserID, content: JsonDict, batch: Optional[str] = None
  89. ) -> JsonDict:
  90. """Performs a full text search for a user.
  91. Args:
  92. user: The user performing the search.
  93. content: Search parameters
  94. batch: The next_batch parameter. Used for pagination.
  95. Returns:
  96. dict to be returned to the client with results of search
  97. """
  98. if not self.hs.config.server.enable_search:
  99. raise SynapseError(400, "Search is disabled on this homeserver")
  100. batch_group = None
  101. batch_group_key = None
  102. batch_token = None
  103. if batch:
  104. try:
  105. b = decode_base64(batch).decode("ascii")
  106. batch_group, batch_group_key, batch_token = b.split("\n")
  107. assert batch_group is not None
  108. assert batch_group_key is not None
  109. assert batch_token is not None
  110. except Exception:
  111. raise SynapseError(400, "Invalid batch")
  112. logger.info(
  113. "Search batch properties: %r, %r, %r",
  114. batch_group,
  115. batch_group_key,
  116. batch_token,
  117. )
  118. logger.info("Search content: %s", content)
  119. try:
  120. room_cat = content["search_categories"]["room_events"]
  121. # The actual thing to query in FTS
  122. search_term = room_cat["search_term"]
  123. # Which "keys" to search over in FTS query
  124. keys = room_cat.get(
  125. "keys", ["content.body", "content.name", "content.topic"]
  126. )
  127. # Filter to apply to results
  128. filter_dict = room_cat.get("filter", {})
  129. # What to order results by (impacts whether pagination can be done)
  130. order_by = room_cat.get("order_by", "rank")
  131. # Return the current state of the rooms?
  132. include_state = room_cat.get("include_state", False)
  133. # Include context around each event?
  134. event_context = room_cat.get("event_context", None)
  135. before_limit = after_limit = None
  136. include_profile = False
  137. # Group results together? May allow clients to paginate within a
  138. # group
  139. group_by = room_cat.get("groupings", {}).get("group_by", {})
  140. group_keys = [g["key"] for g in group_by]
  141. if event_context is not None:
  142. before_limit = int(event_context.get("before_limit", 5))
  143. after_limit = int(event_context.get("after_limit", 5))
  144. # Return the historic display name and avatar for the senders
  145. # of the events?
  146. include_profile = bool(event_context.get("include_profile", False))
  147. except KeyError:
  148. raise SynapseError(400, "Invalid search query")
  149. if order_by not in ("rank", "recent"):
  150. raise SynapseError(400, "Invalid order by: %r" % (order_by,))
  151. if set(group_keys) - {"room_id", "sender"}:
  152. raise SynapseError(
  153. 400,
  154. "Invalid group by keys: %r"
  155. % (set(group_keys) - {"room_id", "sender"},),
  156. )
  157. return await self._search(
  158. user,
  159. batch_group,
  160. batch_group_key,
  161. batch_token,
  162. search_term,
  163. keys,
  164. filter_dict,
  165. order_by,
  166. include_state,
  167. group_keys,
  168. event_context,
  169. before_limit,
  170. after_limit,
  171. include_profile,
  172. )
  173. async def _search(
  174. self,
  175. user: UserID,
  176. batch_group: Optional[str],
  177. batch_group_key: Optional[str],
  178. batch_token: Optional[str],
  179. search_term: str,
  180. keys: List[str],
  181. filter_dict: JsonDict,
  182. order_by: str,
  183. include_state: bool,
  184. group_keys: List[str],
  185. event_context: Optional[bool],
  186. before_limit: Optional[int],
  187. after_limit: Optional[int],
  188. include_profile: bool,
  189. ) -> JsonDict:
  190. """Performs a full text search for a user.
  191. Args:
  192. user: The user performing the search.
  193. batch_group: Pagination information.
  194. batch_group_key: Pagination information.
  195. batch_token: Pagination information.
  196. search_term: Search term to search for
  197. keys: List of keys to search in, currently supports
  198. "content.body", "content.name", "content.topic"
  199. filter_dict: The JSON to build a filter out of.
  200. order_by: How to order the results. Valid values ore "rank" and "recent".
  201. include_state: True if the state of the room at each result should
  202. be included.
  203. group_keys: A list of ways to group the results. Valid values are
  204. "room_id" and "sender".
  205. event_context: True to include contextual events around results.
  206. before_limit:
  207. The number of events before a result to include as context.
  208. Only used if event_context is True.
  209. after_limit:
  210. The number of events after a result to include as context.
  211. Only used if event_context is True.
  212. include_profile: True if historical profile information should be
  213. included in the event context.
  214. Only used if event_context is True.
  215. Returns:
  216. dict to be returned to the client with results of search
  217. """
  218. search_filter = Filter(self.hs, filter_dict)
  219. # TODO: Search through left rooms too
  220. rooms = await self.store.get_rooms_for_local_user_where_membership_is(
  221. user.to_string(),
  222. membership_list=[Membership.JOIN],
  223. # membership_list=[Membership.JOIN, Membership.LEAVE, Membership.Ban],
  224. )
  225. room_ids = {r.room_id for r in rooms}
  226. # If doing a subset of all rooms seearch, check if any of the rooms
  227. # are from an upgraded room, and search their contents as well
  228. if search_filter.rooms:
  229. historical_room_ids: List[str] = []
  230. for room_id in search_filter.rooms:
  231. # Add any previous rooms to the search if they exist
  232. ids = await self.get_old_rooms_from_upgraded_room(room_id)
  233. historical_room_ids += ids
  234. # Prevent any historical events from being filtered
  235. search_filter = search_filter.with_room_ids(historical_room_ids)
  236. room_ids = search_filter.filter_rooms(room_ids)
  237. if batch_group == "room_id":
  238. room_ids.intersection_update({batch_group_key})
  239. if not room_ids:
  240. return {
  241. "search_categories": {
  242. "room_events": {"results": [], "count": 0, "highlights": []}
  243. }
  244. }
  245. sender_group: Optional[Dict[str, JsonDict]]
  246. if order_by == "rank":
  247. search_result, sender_group = await self._search_by_rank(
  248. user, room_ids, search_term, keys, search_filter
  249. )
  250. # Unused return values for rank search.
  251. global_next_batch = None
  252. elif order_by == "recent":
  253. search_result, global_next_batch = await self._search_by_recent(
  254. user,
  255. room_ids,
  256. search_term,
  257. keys,
  258. search_filter,
  259. batch_group,
  260. batch_group_key,
  261. batch_token,
  262. )
  263. # Unused return values for recent search.
  264. sender_group = None
  265. else:
  266. # We should never get here due to the guard earlier.
  267. raise NotImplementedError()
  268. logger.info("Found %d events to return", len(search_result.allowed_events))
  269. # If client has asked for "context" for each event (i.e. some surrounding
  270. # events and state), fetch that
  271. if event_context is not None:
  272. # Note that before and after limit must be set in this case.
  273. assert before_limit is not None
  274. assert after_limit is not None
  275. contexts = await self._calculate_event_contexts(
  276. user,
  277. search_result.allowed_events,
  278. before_limit,
  279. after_limit,
  280. include_profile,
  281. )
  282. else:
  283. contexts = {}
  284. # TODO: Add a limit
  285. state_results = {}
  286. if include_state:
  287. for room_id in {e.room_id for e in search_result.allowed_events}:
  288. state = await self.state_handler.get_current_state(room_id)
  289. state_results[room_id] = list(state.values())
  290. aggregations = await self._relations_handler.get_bundled_aggregations(
  291. # Generate an iterable of EventBase for all the events that will be
  292. # returned, including contextual events.
  293. itertools.chain(
  294. # The events_before and events_after for each context.
  295. itertools.chain.from_iterable(
  296. itertools.chain(context["events_before"], context["events_after"])
  297. for context in contexts.values()
  298. ),
  299. # The returned events.
  300. search_result.allowed_events,
  301. ),
  302. user.to_string(),
  303. )
  304. # We're now about to serialize the events. We should not make any
  305. # blocking calls after this. Otherwise, the 'age' will be wrong.
  306. time_now = self.clock.time_msec()
  307. for context in contexts.values():
  308. context["events_before"] = self._event_serializer.serialize_events(
  309. context["events_before"], time_now, bundle_aggregations=aggregations
  310. )
  311. context["events_after"] = self._event_serializer.serialize_events(
  312. context["events_after"], time_now, bundle_aggregations=aggregations
  313. )
  314. results = [
  315. {
  316. "rank": search_result.rank_map[e.event_id],
  317. "result": self._event_serializer.serialize_event(
  318. e, time_now, bundle_aggregations=aggregations
  319. ),
  320. "context": contexts.get(e.event_id, {}),
  321. }
  322. for e in search_result.allowed_events
  323. ]
  324. rooms_cat_res: JsonDict = {
  325. "results": results,
  326. "count": search_result.count,
  327. "highlights": list(search_result.highlights),
  328. }
  329. if state_results:
  330. rooms_cat_res["state"] = {
  331. room_id: self._event_serializer.serialize_events(state_events, time_now)
  332. for room_id, state_events in state_results.items()
  333. }
  334. if search_result.room_groups and "room_id" in group_keys:
  335. rooms_cat_res.setdefault("groups", {})[
  336. "room_id"
  337. ] = search_result.room_groups
  338. if sender_group and "sender" in group_keys:
  339. rooms_cat_res.setdefault("groups", {})["sender"] = sender_group
  340. if global_next_batch:
  341. rooms_cat_res["next_batch"] = global_next_batch
  342. return {"search_categories": {"room_events": rooms_cat_res}}
  343. async def _search_by_rank(
  344. self,
  345. user: UserID,
  346. room_ids: Collection[str],
  347. search_term: str,
  348. keys: Iterable[str],
  349. search_filter: Filter,
  350. ) -> Tuple[_SearchResult, Dict[str, JsonDict]]:
  351. """
  352. Performs a full text search for a user ordering by rank.
  353. Args:
  354. user: The user performing the search.
  355. room_ids: List of room ids to search in
  356. search_term: Search term to search for
  357. keys: List of keys to search in, currently supports
  358. "content.body", "content.name", "content.topic"
  359. search_filter: The event filter to use.
  360. Returns:
  361. A tuple of:
  362. The search results.
  363. A map of sender ID to results.
  364. """
  365. rank_map = {} # event_id -> rank of event
  366. # Holds result of grouping by room, if applicable
  367. room_groups: Dict[str, JsonDict] = {}
  368. # Holds result of grouping by sender, if applicable
  369. sender_group: Dict[str, JsonDict] = {}
  370. search_result = await self.store.search_msgs(room_ids, search_term, keys)
  371. if search_result["highlights"]:
  372. highlights = search_result["highlights"]
  373. else:
  374. highlights = set()
  375. results = search_result["results"]
  376. # event_id -> rank of event
  377. rank_map = {r["event"].event_id: r["rank"] for r in results}
  378. filtered_events = await search_filter.filter([r["event"] for r in results])
  379. events = await filter_events_for_client(
  380. self.storage, user.to_string(), filtered_events
  381. )
  382. events.sort(key=lambda e: -rank_map[e.event_id])
  383. allowed_events = events[: search_filter.limit]
  384. for e in allowed_events:
  385. rm = room_groups.setdefault(
  386. e.room_id, {"results": [], "order": rank_map[e.event_id]}
  387. )
  388. rm["results"].append(e.event_id)
  389. s = sender_group.setdefault(
  390. e.sender, {"results": [], "order": rank_map[e.event_id]}
  391. )
  392. s["results"].append(e.event_id)
  393. return (
  394. _SearchResult(
  395. search_result["count"],
  396. rank_map,
  397. allowed_events,
  398. room_groups,
  399. highlights,
  400. ),
  401. sender_group,
  402. )
  403. async def _search_by_recent(
  404. self,
  405. user: UserID,
  406. room_ids: Collection[str],
  407. search_term: str,
  408. keys: Iterable[str],
  409. search_filter: Filter,
  410. batch_group: Optional[str],
  411. batch_group_key: Optional[str],
  412. batch_token: Optional[str],
  413. ) -> Tuple[_SearchResult, Optional[str]]:
  414. """
  415. Performs a full text search for a user ordering by recent.
  416. Args:
  417. user: The user performing the search.
  418. room_ids: List of room ids to search in
  419. search_term: Search term to search for
  420. keys: List of keys to search in, currently supports
  421. "content.body", "content.name", "content.topic"
  422. search_filter: The event filter to use.
  423. batch_group: Pagination information.
  424. batch_group_key: Pagination information.
  425. batch_token: Pagination information.
  426. Returns:
  427. A tuple of:
  428. The search results.
  429. Optionally, a pagination token.
  430. """
  431. rank_map = {} # event_id -> rank of event
  432. # Holds result of grouping by room, if applicable
  433. room_groups: Dict[str, JsonDict] = {}
  434. # Holds the next_batch for the entire result set if one of those exists
  435. global_next_batch = None
  436. highlights = set()
  437. room_events: List[EventBase] = []
  438. i = 0
  439. pagination_token = batch_token
  440. # We keep looping and we keep filtering until we reach the limit
  441. # or we run out of things.
  442. # But only go around 5 times since otherwise synapse will be sad.
  443. while len(room_events) < search_filter.limit and i < 5:
  444. i += 1
  445. search_result = await self.store.search_rooms(
  446. room_ids,
  447. search_term,
  448. keys,
  449. search_filter.limit * 2,
  450. pagination_token=pagination_token,
  451. )
  452. if search_result["highlights"]:
  453. highlights.update(search_result["highlights"])
  454. count = search_result["count"]
  455. results = search_result["results"]
  456. results_map = {r["event"].event_id: r for r in results}
  457. rank_map.update({r["event"].event_id: r["rank"] for r in results})
  458. filtered_events = await search_filter.filter([r["event"] for r in results])
  459. events = await filter_events_for_client(
  460. self.storage, user.to_string(), filtered_events
  461. )
  462. room_events.extend(events)
  463. room_events = room_events[: search_filter.limit]
  464. if len(results) < search_filter.limit * 2:
  465. break
  466. else:
  467. pagination_token = results[-1]["pagination_token"]
  468. for event in room_events:
  469. group = room_groups.setdefault(event.room_id, {"results": []})
  470. group["results"].append(event.event_id)
  471. if room_events and len(room_events) >= search_filter.limit:
  472. last_event_id = room_events[-1].event_id
  473. pagination_token = results_map[last_event_id]["pagination_token"]
  474. # We want to respect the given batch group and group keys so
  475. # that if people blindly use the top level `next_batch` token
  476. # it returns more from the same group (if applicable) rather
  477. # than reverting to searching all results again.
  478. if batch_group and batch_group_key:
  479. global_next_batch = encode_base64(
  480. (
  481. "%s\n%s\n%s" % (batch_group, batch_group_key, pagination_token)
  482. ).encode("ascii")
  483. )
  484. else:
  485. global_next_batch = encode_base64(
  486. ("%s\n%s\n%s" % ("all", "", pagination_token)).encode("ascii")
  487. )
  488. for room_id, group in room_groups.items():
  489. group["next_batch"] = encode_base64(
  490. ("%s\n%s\n%s" % ("room_id", room_id, pagination_token)).encode(
  491. "ascii"
  492. )
  493. )
  494. return (
  495. _SearchResult(count, rank_map, room_events, room_groups, highlights),
  496. global_next_batch,
  497. )
  498. async def _calculate_event_contexts(
  499. self,
  500. user: UserID,
  501. allowed_events: List[EventBase],
  502. before_limit: int,
  503. after_limit: int,
  504. include_profile: bool,
  505. ) -> Dict[str, JsonDict]:
  506. """
  507. Calculates the contextual events for any search results.
  508. Args:
  509. user: The user performing the search.
  510. allowed_events: The search results.
  511. before_limit:
  512. The number of events before a result to include as context.
  513. after_limit:
  514. The number of events after a result to include as context.
  515. include_profile: True if historical profile information should be
  516. included in the event context.
  517. Returns:
  518. A map of event ID to contextual information.
  519. """
  520. now_token = self.hs.get_event_sources().get_current_token()
  521. contexts = {}
  522. for event in allowed_events:
  523. res = await self.store.get_events_around(
  524. event.room_id, event.event_id, before_limit, after_limit
  525. )
  526. logger.info(
  527. "Context for search returned %d and %d events",
  528. len(res.events_before),
  529. len(res.events_after),
  530. )
  531. events_before = await filter_events_for_client(
  532. self.storage, user.to_string(), res.events_before
  533. )
  534. events_after = await filter_events_for_client(
  535. self.storage, user.to_string(), res.events_after
  536. )
  537. context: JsonDict = {
  538. "events_before": events_before,
  539. "events_after": events_after,
  540. "start": await now_token.copy_and_replace(
  541. StreamKeyType.ROOM, res.start
  542. ).to_string(self.store),
  543. "end": await now_token.copy_and_replace(
  544. StreamKeyType.ROOM, res.end
  545. ).to_string(self.store),
  546. }
  547. if include_profile:
  548. senders = {
  549. ev.sender
  550. for ev in itertools.chain(events_before, [event], events_after)
  551. }
  552. if events_after:
  553. last_event_id = events_after[-1].event_id
  554. else:
  555. last_event_id = event.event_id
  556. state_filter = StateFilter.from_types(
  557. [(EventTypes.Member, sender) for sender in senders]
  558. )
  559. state = await self.state_store.get_state_for_event(
  560. last_event_id, state_filter
  561. )
  562. context["profile_info"] = {
  563. s.state_key: {
  564. "displayname": s.content.get("displayname", None),
  565. "avatar_url": s.content.get("avatar_url", None),
  566. }
  567. for s in state.values()
  568. if s.type == EventTypes.Member and s.state_key in senders
  569. }
  570. contexts[event.event_id] = context
  571. return contexts