pagination.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765
  1. # Copyright 2014 - 2016 OpenMarket Ltd
  2. # Copyright 2017 - 2018 New Vector 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 logging
  16. from typing import TYPE_CHECKING, Collection, Dict, List, Optional, Set
  17. import attr
  18. from twisted.python.failure import Failure
  19. from synapse.api.constants import EventTypes, Membership
  20. from synapse.api.errors import SynapseError
  21. from synapse.api.filtering import Filter
  22. from synapse.events.utils import SerializeEventConfig
  23. from synapse.handlers.room import ShutdownRoomResponse
  24. from synapse.metrics.background_process_metrics import run_as_background_process
  25. from synapse.storage.state import StateFilter
  26. from synapse.streams.config import PaginationConfig
  27. from synapse.types import JsonDict, Requester, StreamKeyType
  28. from synapse.util.async_helpers import ReadWriteLock
  29. from synapse.util.stringutils import random_string
  30. from synapse.visibility import filter_events_for_client
  31. if TYPE_CHECKING:
  32. from synapse.server import HomeServer
  33. logger = logging.getLogger(__name__)
  34. @attr.s(slots=True, auto_attribs=True)
  35. class PurgeStatus:
  36. """Object tracking the status of a purge request
  37. This class contains information on the progress of a purge request, for
  38. return by get_purge_status.
  39. """
  40. STATUS_ACTIVE = 0
  41. STATUS_COMPLETE = 1
  42. STATUS_FAILED = 2
  43. STATUS_TEXT = {
  44. STATUS_ACTIVE: "active",
  45. STATUS_COMPLETE: "complete",
  46. STATUS_FAILED: "failed",
  47. }
  48. # Save the error message if an error occurs
  49. error: str = ""
  50. # Tracks whether this request has completed. One of STATUS_{ACTIVE,COMPLETE,FAILED}.
  51. status: int = STATUS_ACTIVE
  52. def asdict(self) -> JsonDict:
  53. ret = {"status": PurgeStatus.STATUS_TEXT[self.status]}
  54. if self.error:
  55. ret["error"] = self.error
  56. return ret
  57. @attr.s(slots=True, auto_attribs=True)
  58. class DeleteStatus:
  59. """Object tracking the status of a delete room request
  60. This class contains information on the progress of a delete room request, for
  61. return by get_delete_status.
  62. """
  63. STATUS_PURGING = 0
  64. STATUS_COMPLETE = 1
  65. STATUS_FAILED = 2
  66. STATUS_SHUTTING_DOWN = 3
  67. STATUS_TEXT = {
  68. STATUS_PURGING: "purging",
  69. STATUS_COMPLETE: "complete",
  70. STATUS_FAILED: "failed",
  71. STATUS_SHUTTING_DOWN: "shutting_down",
  72. }
  73. # Tracks whether this request has completed.
  74. # One of STATUS_{PURGING,COMPLETE,FAILED,SHUTTING_DOWN}.
  75. status: int = STATUS_PURGING
  76. # Save the error message if an error occurs
  77. error: str = ""
  78. # Saves the result of an action to give it back to REST API
  79. shutdown_room: ShutdownRoomResponse = {
  80. "kicked_users": [],
  81. "failed_to_kick_users": [],
  82. "local_aliases": [],
  83. "new_room_id": None,
  84. }
  85. def asdict(self) -> JsonDict:
  86. ret = {
  87. "status": DeleteStatus.STATUS_TEXT[self.status],
  88. "shutdown_room": self.shutdown_room,
  89. }
  90. if self.error:
  91. ret["error"] = self.error
  92. return ret
  93. class PaginationHandler:
  94. """Handles pagination and purge history requests.
  95. These are in the same handler due to the fact we need to block clients
  96. paginating during a purge.
  97. """
  98. # when to remove a completed deletion/purge from the results map
  99. CLEAR_PURGE_AFTER_MS = 1000 * 3600 * 24 # 24 hours
  100. def __init__(self, hs: "HomeServer"):
  101. self.hs = hs
  102. self.auth = hs.get_auth()
  103. self.store = hs.get_datastores().main
  104. self.storage = hs.get_storage()
  105. self.state_store = self.storage.state
  106. self.clock = hs.get_clock()
  107. self._server_name = hs.hostname
  108. self._room_shutdown_handler = hs.get_room_shutdown_handler()
  109. self._relations_handler = hs.get_relations_handler()
  110. self.pagination_lock = ReadWriteLock()
  111. # IDs of rooms in which there currently an active purge *or delete* operation.
  112. self._purges_in_progress_by_room: Set[str] = set()
  113. # map from purge id to PurgeStatus
  114. self._purges_by_id: Dict[str, PurgeStatus] = {}
  115. # map from purge id to DeleteStatus
  116. self._delete_by_id: Dict[str, DeleteStatus] = {}
  117. # map from room id to delete ids
  118. # Dict[`room_id`, List[`delete_id`]]
  119. self._delete_by_room: Dict[str, List[str]] = {}
  120. self._event_serializer = hs.get_event_client_serializer()
  121. self._retention_default_max_lifetime = (
  122. hs.config.retention.retention_default_max_lifetime
  123. )
  124. self._retention_allowed_lifetime_min = (
  125. hs.config.retention.retention_allowed_lifetime_min
  126. )
  127. self._retention_allowed_lifetime_max = (
  128. hs.config.retention.retention_allowed_lifetime_max
  129. )
  130. if (
  131. hs.config.worker.run_background_tasks
  132. and hs.config.retention.retention_enabled
  133. ):
  134. # Run the purge jobs described in the configuration file.
  135. for job in hs.config.retention.retention_purge_jobs:
  136. logger.info("Setting up purge job with config: %s", job)
  137. self.clock.looping_call(
  138. run_as_background_process,
  139. job.interval,
  140. "purge_history_for_rooms_in_range",
  141. self.purge_history_for_rooms_in_range,
  142. job.shortest_max_lifetime,
  143. job.longest_max_lifetime,
  144. )
  145. async def purge_history_for_rooms_in_range(
  146. self, min_ms: Optional[int], max_ms: Optional[int]
  147. ) -> None:
  148. """Purge outdated events from rooms within the given retention range.
  149. If a default retention policy is defined in the server's configuration and its
  150. 'max_lifetime' is within this range, also targets rooms which don't have a
  151. retention policy.
  152. Args:
  153. min_ms: Duration in milliseconds that define the lower limit of
  154. the range to handle (exclusive). If None, it means that the range has no
  155. lower limit.
  156. max_ms: Duration in milliseconds that define the upper limit of
  157. the range to handle (inclusive). If None, it means that the range has no
  158. upper limit.
  159. """
  160. # We want the storage layer to include rooms with no retention policy in its
  161. # return value only if a default retention policy is defined in the server's
  162. # configuration and that policy's 'max_lifetime' is either lower (or equal) than
  163. # max_ms or higher than min_ms (or both).
  164. if self._retention_default_max_lifetime is not None:
  165. include_null = True
  166. if min_ms is not None and min_ms >= self._retention_default_max_lifetime:
  167. # The default max_lifetime is lower than (or equal to) min_ms.
  168. include_null = False
  169. if max_ms is not None and max_ms < self._retention_default_max_lifetime:
  170. # The default max_lifetime is higher than max_ms.
  171. include_null = False
  172. else:
  173. include_null = False
  174. logger.info(
  175. "[purge] Running purge job for %s < max_lifetime <= %s (include NULLs = %s)",
  176. min_ms,
  177. max_ms,
  178. include_null,
  179. )
  180. rooms = await self.store.get_rooms_for_retention_period_in_range(
  181. min_ms, max_ms, include_null
  182. )
  183. logger.debug("[purge] Rooms to purge: %s", rooms)
  184. for room_id, retention_policy in rooms.items():
  185. logger.info("[purge] Attempting to purge messages in room %s", room_id)
  186. if room_id in self._purges_in_progress_by_room:
  187. logger.warning(
  188. "[purge] not purging room %s as there's an ongoing purge running"
  189. " for this room",
  190. room_id,
  191. )
  192. continue
  193. # If max_lifetime is None, it means that the room has no retention policy.
  194. # Given we only retrieve such rooms when there's a default retention policy
  195. # defined in the server's configuration, we can safely assume that's the
  196. # case and use it for this room.
  197. max_lifetime = (
  198. retention_policy["max_lifetime"] or self._retention_default_max_lifetime
  199. )
  200. # Cap the effective max_lifetime to be within the range allowed in the
  201. # config.
  202. # We do this in two steps:
  203. # 1. Make sure it's higher or equal to the minimum allowed value, and if
  204. # it's not replace it with that value. This is because the server
  205. # operator can be required to not delete information before a given
  206. # time, e.g. to comply with freedom of information laws.
  207. # 2. Make sure the resulting value is lower or equal to the maximum allowed
  208. # value, and if it's not replace it with that value. This is because the
  209. # server operator can be required to delete any data after a specific
  210. # amount of time.
  211. if self._retention_allowed_lifetime_min is not None:
  212. max_lifetime = max(self._retention_allowed_lifetime_min, max_lifetime)
  213. if self._retention_allowed_lifetime_max is not None:
  214. max_lifetime = min(max_lifetime, self._retention_allowed_lifetime_max)
  215. logger.debug("[purge] max_lifetime for room %s: %s", room_id, max_lifetime)
  216. # Figure out what token we should start purging at.
  217. ts = self.clock.time_msec() - max_lifetime
  218. stream_ordering = await self.store.find_first_stream_ordering_after_ts(ts)
  219. r = await self.store.get_room_event_before_stream_ordering(
  220. room_id,
  221. stream_ordering,
  222. )
  223. if not r:
  224. logger.warning(
  225. "[purge] purging events not possible: No event found "
  226. "(ts %i => stream_ordering %i)",
  227. ts,
  228. stream_ordering,
  229. )
  230. continue
  231. (stream, topo, _event_id) = r
  232. token = "t%d-%d" % (topo, stream)
  233. purge_id = random_string(16)
  234. self._purges_by_id[purge_id] = PurgeStatus()
  235. logger.info(
  236. "Starting purging events in room %s (purge_id %s)" % (room_id, purge_id)
  237. )
  238. # We want to purge everything, including local events, and to run the purge in
  239. # the background so that it's not blocking any other operation apart from
  240. # other purges in the same room.
  241. run_as_background_process(
  242. "_purge_history",
  243. self._purge_history,
  244. purge_id,
  245. room_id,
  246. token,
  247. True,
  248. )
  249. def start_purge_history(
  250. self, room_id: str, token: str, delete_local_events: bool = False
  251. ) -> str:
  252. """Start off a history purge on a room.
  253. Args:
  254. room_id: The room to purge from
  255. token: topological token to delete events before
  256. delete_local_events: True to delete local events as well as
  257. remote ones
  258. Returns:
  259. unique ID for this purge transaction.
  260. """
  261. if room_id in self._purges_in_progress_by_room:
  262. raise SynapseError(
  263. 400, "History purge already in progress for %s" % (room_id,)
  264. )
  265. purge_id = random_string(16)
  266. # we log the purge_id here so that it can be tied back to the
  267. # request id in the log lines.
  268. logger.info("[purge] starting purge_id %s", purge_id)
  269. self._purges_by_id[purge_id] = PurgeStatus()
  270. run_as_background_process(
  271. "purge_history",
  272. self._purge_history,
  273. purge_id,
  274. room_id,
  275. token,
  276. delete_local_events,
  277. )
  278. return purge_id
  279. async def _purge_history(
  280. self, purge_id: str, room_id: str, token: str, delete_local_events: bool
  281. ) -> None:
  282. """Carry out a history purge on a room.
  283. Args:
  284. purge_id: The ID for this purge.
  285. room_id: The room to purge from
  286. token: topological token to delete events before
  287. delete_local_events: True to delete local events as well as remote ones
  288. """
  289. self._purges_in_progress_by_room.add(room_id)
  290. try:
  291. async with self.pagination_lock.write(room_id):
  292. await self.storage.purge_events.purge_history(
  293. room_id, token, delete_local_events
  294. )
  295. logger.info("[purge] complete")
  296. self._purges_by_id[purge_id].status = PurgeStatus.STATUS_COMPLETE
  297. except Exception:
  298. f = Failure()
  299. logger.error(
  300. "[purge] failed", exc_info=(f.type, f.value, f.getTracebackObject()) # type: ignore
  301. )
  302. self._purges_by_id[purge_id].status = PurgeStatus.STATUS_FAILED
  303. self._purges_by_id[purge_id].error = f.getErrorMessage()
  304. finally:
  305. self._purges_in_progress_by_room.discard(room_id)
  306. # remove the purge from the list 24 hours after it completes
  307. def clear_purge() -> None:
  308. del self._purges_by_id[purge_id]
  309. self.hs.get_reactor().callLater(
  310. PaginationHandler.CLEAR_PURGE_AFTER_MS / 1000, clear_purge
  311. )
  312. def get_purge_status(self, purge_id: str) -> Optional[PurgeStatus]:
  313. """Get the current status of an active purge
  314. Args:
  315. purge_id: purge_id returned by start_purge_history
  316. """
  317. return self._purges_by_id.get(purge_id)
  318. def get_delete_status(self, delete_id: str) -> Optional[DeleteStatus]:
  319. """Get the current status of an active deleting
  320. Args:
  321. delete_id: delete_id returned by start_shutdown_and_purge_room
  322. """
  323. return self._delete_by_id.get(delete_id)
  324. def get_delete_ids_by_room(self, room_id: str) -> Optional[Collection[str]]:
  325. """Get all active delete ids by room
  326. Args:
  327. room_id: room_id that is deleted
  328. """
  329. return self._delete_by_room.get(room_id)
  330. async def purge_room(self, room_id: str, force: bool = False) -> None:
  331. """Purge the given room from the database.
  332. This function is part the delete room v1 API.
  333. Args:
  334. room_id: room to be purged
  335. force: set true to skip checking for joined users.
  336. """
  337. async with self.pagination_lock.write(room_id):
  338. # first check that we have no users in this room
  339. if not force:
  340. joined = await self.store.is_host_joined(room_id, self._server_name)
  341. if joined:
  342. raise SynapseError(400, "Users are still joined to this room")
  343. await self.storage.purge_events.purge_room(room_id)
  344. async def get_messages(
  345. self,
  346. requester: Requester,
  347. room_id: str,
  348. pagin_config: PaginationConfig,
  349. as_client_event: bool = True,
  350. event_filter: Optional[Filter] = None,
  351. ) -> JsonDict:
  352. """Get messages in a room.
  353. Args:
  354. requester: The user requesting messages.
  355. room_id: The room they want messages from.
  356. pagin_config: The pagination config rules to apply, if any.
  357. as_client_event: True to get events in client-server format.
  358. event_filter: Filter to apply to results or None
  359. Returns:
  360. Pagination API results
  361. """
  362. user_id = requester.user.to_string()
  363. if pagin_config.from_token:
  364. from_token = pagin_config.from_token
  365. else:
  366. from_token = (
  367. await self.hs.get_event_sources().get_current_token_for_pagination(
  368. room_id
  369. )
  370. )
  371. # We expect `/messages` to use historic pagination tokens by default but
  372. # `/messages` should still works with live tokens when manually provided.
  373. assert from_token.room_key.topological is not None
  374. if pagin_config.limit is None:
  375. # This shouldn't happen as we've set a default limit before this
  376. # gets called.
  377. raise Exception("limit not set")
  378. room_token = from_token.room_key
  379. async with self.pagination_lock.read(room_id):
  380. (
  381. membership,
  382. member_event_id,
  383. ) = await self.auth.check_user_in_room_or_world_readable(
  384. room_id, user_id, allow_departed_users=True
  385. )
  386. if pagin_config.direction == "b":
  387. # if we're going backwards, we might need to backfill. This
  388. # requires that we have a topo token.
  389. if room_token.topological:
  390. curr_topo = room_token.topological
  391. else:
  392. curr_topo = await self.store.get_current_topological_token(
  393. room_id, room_token.stream
  394. )
  395. if membership == Membership.LEAVE:
  396. # If they have left the room then clamp the token to be before
  397. # they left the room, to save the effort of loading from the
  398. # database.
  399. # This is only None if the room is world_readable, in which
  400. # case "JOIN" would have been returned.
  401. assert member_event_id
  402. leave_token = await self.store.get_topological_token_for_event(
  403. member_event_id
  404. )
  405. assert leave_token.topological is not None
  406. if leave_token.topological < curr_topo:
  407. from_token = from_token.copy_and_replace(
  408. StreamKeyType.ROOM, leave_token
  409. )
  410. await self.hs.get_federation_handler().maybe_backfill(
  411. room_id,
  412. curr_topo,
  413. limit=pagin_config.limit,
  414. )
  415. to_room_key = None
  416. if pagin_config.to_token:
  417. to_room_key = pagin_config.to_token.room_key
  418. events, next_key = await self.store.paginate_room_events(
  419. room_id=room_id,
  420. from_key=from_token.room_key,
  421. to_key=to_room_key,
  422. direction=pagin_config.direction,
  423. limit=pagin_config.limit,
  424. event_filter=event_filter,
  425. )
  426. next_token = from_token.copy_and_replace(StreamKeyType.ROOM, next_key)
  427. if events:
  428. if event_filter:
  429. events = await event_filter.filter(events)
  430. events = await filter_events_for_client(
  431. self.storage, user_id, events, is_peeking=(member_event_id is None)
  432. )
  433. if not events:
  434. return {
  435. "chunk": [],
  436. "start": await from_token.to_string(self.store),
  437. "end": await next_token.to_string(self.store),
  438. }
  439. state = None
  440. if event_filter and event_filter.lazy_load_members and len(events) > 0:
  441. # TODO: remove redundant members
  442. # FIXME: we also care about invite targets etc.
  443. state_filter = StateFilter.from_types(
  444. (EventTypes.Member, event.sender) for event in events
  445. )
  446. state_ids = await self.state_store.get_state_ids_for_event(
  447. events[0].event_id, state_filter=state_filter
  448. )
  449. if state_ids:
  450. state_dict = await self.store.get_events(list(state_ids.values()))
  451. state = state_dict.values()
  452. aggregations = await self._relations_handler.get_bundled_aggregations(
  453. events, user_id
  454. )
  455. time_now = self.clock.time_msec()
  456. serialize_options = SerializeEventConfig(as_client_event=as_client_event)
  457. chunk = {
  458. "chunk": (
  459. self._event_serializer.serialize_events(
  460. events,
  461. time_now,
  462. config=serialize_options,
  463. bundle_aggregations=aggregations,
  464. )
  465. ),
  466. "start": await from_token.to_string(self.store),
  467. "end": await next_token.to_string(self.store),
  468. }
  469. if state:
  470. chunk["state"] = self._event_serializer.serialize_events(
  471. state, time_now, config=serialize_options
  472. )
  473. return chunk
  474. async def _shutdown_and_purge_room(
  475. self,
  476. delete_id: str,
  477. room_id: str,
  478. requester_user_id: str,
  479. new_room_user_id: Optional[str] = None,
  480. new_room_name: Optional[str] = None,
  481. message: Optional[str] = None,
  482. block: bool = False,
  483. purge: bool = True,
  484. force_purge: bool = False,
  485. ) -> None:
  486. """
  487. Shuts down and purges a room.
  488. See `RoomShutdownHandler.shutdown_room` for details of creation of the new room
  489. Args:
  490. delete_id: The ID for this delete.
  491. room_id: The ID of the room to shut down.
  492. requester_user_id:
  493. User who requested the action. Will be recorded as putting the room on the
  494. blocking list.
  495. new_room_user_id:
  496. If set, a new room will be created with this user ID
  497. as the creator and admin, and all users in the old room will be
  498. moved into that room. If not set, no new room will be created
  499. and the users will just be removed from the old room.
  500. new_room_name:
  501. A string representing the name of the room that new users will
  502. be invited to. Defaults to `Content Violation Notification`
  503. message:
  504. A string containing the first message that will be sent as
  505. `new_room_user_id` in the new room. Ideally this will clearly
  506. convey why the original room was shut down.
  507. Defaults to `Sharing illegal content on this server is not
  508. permitted and rooms in violation will be blocked.`
  509. block:
  510. If set to `true`, this room will be added to a blocking list,
  511. preventing future attempts to join the room. Defaults to `false`.
  512. purge:
  513. If set to `true`, purge the given room from the database.
  514. force_purge:
  515. If set to `true`, the room will be purged from database
  516. also if it fails to remove some users from room.
  517. Saves a `RoomShutdownHandler.ShutdownRoomResponse` in `DeleteStatus`:
  518. """
  519. self._purges_in_progress_by_room.add(room_id)
  520. try:
  521. async with self.pagination_lock.write(room_id):
  522. self._delete_by_id[delete_id].status = DeleteStatus.STATUS_SHUTTING_DOWN
  523. self._delete_by_id[
  524. delete_id
  525. ].shutdown_room = await self._room_shutdown_handler.shutdown_room(
  526. room_id=room_id,
  527. requester_user_id=requester_user_id,
  528. new_room_user_id=new_room_user_id,
  529. new_room_name=new_room_name,
  530. message=message,
  531. block=block,
  532. )
  533. self._delete_by_id[delete_id].status = DeleteStatus.STATUS_PURGING
  534. if purge:
  535. logger.info("starting purge room_id %s", room_id)
  536. # first check that we have no users in this room
  537. if not force_purge:
  538. joined = await self.store.is_host_joined(
  539. room_id, self._server_name
  540. )
  541. if joined:
  542. raise SynapseError(
  543. 400, "Users are still joined to this room"
  544. )
  545. await self.storage.purge_events.purge_room(room_id)
  546. logger.info("complete")
  547. self._delete_by_id[delete_id].status = DeleteStatus.STATUS_COMPLETE
  548. except Exception:
  549. f = Failure()
  550. logger.error(
  551. "failed",
  552. exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
  553. )
  554. self._delete_by_id[delete_id].status = DeleteStatus.STATUS_FAILED
  555. self._delete_by_id[delete_id].error = f.getErrorMessage()
  556. finally:
  557. self._purges_in_progress_by_room.discard(room_id)
  558. # remove the delete from the list 24 hours after it completes
  559. def clear_delete() -> None:
  560. del self._delete_by_id[delete_id]
  561. self._delete_by_room[room_id].remove(delete_id)
  562. if not self._delete_by_room[room_id]:
  563. del self._delete_by_room[room_id]
  564. self.hs.get_reactor().callLater(
  565. PaginationHandler.CLEAR_PURGE_AFTER_MS / 1000, clear_delete
  566. )
  567. def start_shutdown_and_purge_room(
  568. self,
  569. room_id: str,
  570. requester_user_id: str,
  571. new_room_user_id: Optional[str] = None,
  572. new_room_name: Optional[str] = None,
  573. message: Optional[str] = None,
  574. block: bool = False,
  575. purge: bool = True,
  576. force_purge: bool = False,
  577. ) -> str:
  578. """Start off shut down and purge on a room.
  579. Args:
  580. room_id: The ID of the room to shut down.
  581. requester_user_id:
  582. User who requested the action and put the room on the
  583. blocking list.
  584. new_room_user_id:
  585. If set, a new room will be created with this user ID
  586. as the creator and admin, and all users in the old room will be
  587. moved into that room. If not set, no new room will be created
  588. and the users will just be removed from the old room.
  589. new_room_name:
  590. A string representing the name of the room that new users will
  591. be invited to. Defaults to `Content Violation Notification`
  592. message:
  593. A string containing the first message that will be sent as
  594. `new_room_user_id` in the new room. Ideally this will clearly
  595. convey why the original room was shut down.
  596. Defaults to `Sharing illegal content on this server is not
  597. permitted and rooms in violation will be blocked.`
  598. block:
  599. If set to `true`, this room will be added to a blocking list,
  600. preventing future attempts to join the room. Defaults to `false`.
  601. purge:
  602. If set to `true`, purge the given room from the database.
  603. force_purge:
  604. If set to `true`, the room will be purged from database
  605. also if it fails to remove some users from room.
  606. Returns:
  607. unique ID for this delete transaction.
  608. """
  609. if room_id in self._purges_in_progress_by_room:
  610. raise SynapseError(
  611. 400, "History purge already in progress for %s" % (room_id,)
  612. )
  613. # This check is double to `RoomShutdownHandler.shutdown_room`
  614. # But here the requester get a direct response / error with HTTP request
  615. # and do not have to check the purge status
  616. if new_room_user_id is not None:
  617. if not self.hs.is_mine_id(new_room_user_id):
  618. raise SynapseError(
  619. 400, "User must be our own: %s" % (new_room_user_id,)
  620. )
  621. delete_id = random_string(16)
  622. # we log the delete_id here so that it can be tied back to the
  623. # request id in the log lines.
  624. logger.info(
  625. "starting shutdown room_id %s with delete_id %s",
  626. room_id,
  627. delete_id,
  628. )
  629. self._delete_by_id[delete_id] = DeleteStatus()
  630. self._delete_by_room.setdefault(room_id, []).append(delete_id)
  631. run_as_background_process(
  632. "shutdown_and_purge_room",
  633. self._shutdown_and_purge_room,
  634. delete_id,
  635. room_id,
  636. requester_user_id,
  637. new_room_user_id,
  638. new_room_name,
  639. message,
  640. block,
  641. purge,
  642. force_purge,
  643. )
  644. return delete_id