server_notices_manager.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200
  1. # Copyright 2018 New Vector 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 Optional
  16. from synapse.api.constants import EventTypes, Membership, RoomCreationPreset
  17. from synapse.events import EventBase
  18. from synapse.types import UserID, create_requester
  19. from synapse.util.caches.descriptors import cached
  20. logger = logging.getLogger(__name__)
  21. SERVER_NOTICE_ROOM_TAG = "m.server_notice"
  22. class ServerNoticesManager:
  23. def __init__(self, hs):
  24. """
  25. Args:
  26. hs (synapse.server.HomeServer):
  27. """
  28. self._store = hs.get_datastore()
  29. self._config = hs.config
  30. self._account_data_handler = hs.get_account_data_handler()
  31. self._room_creation_handler = hs.get_room_creation_handler()
  32. self._room_member_handler = hs.get_room_member_handler()
  33. self._event_creation_handler = hs.get_event_creation_handler()
  34. self._is_mine_id = hs.is_mine_id
  35. self._server_name = hs.hostname
  36. self._notifier = hs.get_notifier()
  37. self.server_notices_mxid = self._config.server_notices_mxid
  38. def is_enabled(self):
  39. """Checks if server notices are enabled on this server.
  40. Returns:
  41. bool
  42. """
  43. return self._config.server_notices_mxid is not None
  44. async def send_notice(
  45. self,
  46. user_id: str,
  47. event_content: dict,
  48. type: str = EventTypes.Message,
  49. state_key: Optional[str] = None,
  50. ) -> EventBase:
  51. """Send a notice to the given user
  52. Creates the server notices room, if none exists.
  53. Args:
  54. user_id: mxid of user to send event to.
  55. event_content: content of event to send
  56. type: type of event
  57. is_state_event: Is the event a state event
  58. """
  59. room_id = await self.get_or_create_notice_room_for_user(user_id)
  60. await self.maybe_invite_user_to_room(user_id, room_id)
  61. system_mxid = self._config.server_notices_mxid
  62. requester = create_requester(
  63. system_mxid, authenticated_entity=self._server_name
  64. )
  65. logger.info("Sending server notice to %s", user_id)
  66. event_dict = {
  67. "type": type,
  68. "room_id": room_id,
  69. "sender": system_mxid,
  70. "content": event_content,
  71. }
  72. if state_key is not None:
  73. event_dict["state_key"] = state_key
  74. event, _ = await self._event_creation_handler.create_and_send_nonmember_event(
  75. requester, event_dict, ratelimit=False
  76. )
  77. return event
  78. @cached()
  79. async def get_or_create_notice_room_for_user(self, user_id: str) -> str:
  80. """Get the room for notices for a given user
  81. If we have not yet created a notice room for this user, create it, but don't
  82. invite the user to it.
  83. Args:
  84. user_id: complete user id for the user we want a room for
  85. Returns:
  86. room id of notice room.
  87. """
  88. if not self.is_enabled():
  89. raise Exception("Server notices not enabled")
  90. assert self._is_mine_id(user_id), "Cannot send server notices to remote users"
  91. rooms = await self._store.get_rooms_for_local_user_where_membership_is(
  92. user_id, [Membership.INVITE, Membership.JOIN]
  93. )
  94. for room in rooms:
  95. # it's worth noting that there is an asymmetry here in that we
  96. # expect the user to be invited or joined, but the system user must
  97. # be joined. This is kinda deliberate, in that if somebody somehow
  98. # manages to invite the system user to a room, that doesn't make it
  99. # the server notices room.
  100. user_ids = await self._store.get_users_in_room(room.room_id)
  101. if len(user_ids) <= 2 and self.server_notices_mxid in user_ids:
  102. # we found a room which our user shares with the system notice
  103. # user
  104. logger.info(
  105. "Using existing server notices room %s for user %s",
  106. room.room_id,
  107. user_id,
  108. )
  109. return room.room_id
  110. # apparently no existing notice room: create a new one
  111. logger.info("Creating server notices room for %s", user_id)
  112. # see if we want to override the profile info for the server user.
  113. # note that if we want to override either the display name or the
  114. # avatar, we have to use both.
  115. join_profile = None
  116. if (
  117. self._config.server_notices_mxid_display_name is not None
  118. or self._config.server_notices_mxid_avatar_url is not None
  119. ):
  120. join_profile = {
  121. "displayname": self._config.server_notices_mxid_display_name,
  122. "avatar_url": self._config.server_notices_mxid_avatar_url,
  123. }
  124. requester = create_requester(
  125. self.server_notices_mxid, authenticated_entity=self._server_name
  126. )
  127. info, _ = await self._room_creation_handler.create_room(
  128. requester,
  129. config={
  130. "preset": RoomCreationPreset.PRIVATE_CHAT,
  131. "name": self._config.server_notices_room_name,
  132. "power_level_content_override": {"users_default": -10},
  133. },
  134. ratelimit=False,
  135. creator_join_profile=join_profile,
  136. )
  137. room_id = info["room_id"]
  138. max_id = await self._account_data_handler.add_tag_to_room(
  139. user_id, room_id, SERVER_NOTICE_ROOM_TAG, {}
  140. )
  141. self._notifier.on_new_event("account_data_key", max_id, users=[user_id])
  142. logger.info("Created server notices room %s for %s", room_id, user_id)
  143. return room_id
  144. async def maybe_invite_user_to_room(self, user_id: str, room_id: str) -> None:
  145. """Invite the given user to the given server room, unless the user has already
  146. joined or been invited to it.
  147. Args:
  148. user_id: The ID of the user to invite.
  149. room_id: The ID of the room to invite the user to.
  150. """
  151. requester = create_requester(
  152. self.server_notices_mxid, authenticated_entity=self._server_name
  153. )
  154. # Check whether the user has already joined or been invited to this room. If
  155. # that's the case, there is no need to re-invite them.
  156. joined_rooms = await self._store.get_rooms_for_local_user_where_membership_is(
  157. user_id, [Membership.INVITE, Membership.JOIN]
  158. )
  159. for room in joined_rooms:
  160. if room.room_id == room_id:
  161. return
  162. await self._room_member_handler.update_membership(
  163. requester=requester,
  164. target=UserID.from_string(user_id),
  165. room_id=room_id,
  166. action="invite",
  167. )