account_data.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. # Copyright 2021 The Matrix.org Foundation C.I.C.
  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. import random
  17. from typing import TYPE_CHECKING, List, Optional, Tuple
  18. from synapse.api.constants import AccountDataTypes
  19. from synapse.replication.http.account_data import (
  20. ReplicationAddRoomAccountDataRestServlet,
  21. ReplicationAddTagRestServlet,
  22. ReplicationAddUserAccountDataRestServlet,
  23. ReplicationRemoveRoomAccountDataRestServlet,
  24. ReplicationRemoveTagRestServlet,
  25. ReplicationRemoveUserAccountDataRestServlet,
  26. )
  27. from synapse.streams import EventSource
  28. from synapse.types import JsonDict, StrCollection, StreamKeyType, UserID
  29. if TYPE_CHECKING:
  30. from synapse.server import HomeServer
  31. logger = logging.getLogger(__name__)
  32. class AccountDataHandler:
  33. def __init__(self, hs: "HomeServer"):
  34. self._store = hs.get_datastores().main
  35. self._instance_name = hs.get_instance_name()
  36. self._notifier = hs.get_notifier()
  37. self._add_user_data_client = (
  38. ReplicationAddUserAccountDataRestServlet.make_client(hs)
  39. )
  40. self._remove_user_data_client = (
  41. ReplicationRemoveUserAccountDataRestServlet.make_client(hs)
  42. )
  43. self._add_room_data_client = (
  44. ReplicationAddRoomAccountDataRestServlet.make_client(hs)
  45. )
  46. self._remove_room_data_client = (
  47. ReplicationRemoveRoomAccountDataRestServlet.make_client(hs)
  48. )
  49. self._add_tag_client = ReplicationAddTagRestServlet.make_client(hs)
  50. self._remove_tag_client = ReplicationRemoveTagRestServlet.make_client(hs)
  51. self._account_data_writers = hs.config.worker.writers.account_data
  52. self._module_api_callbacks = hs.get_module_api_callbacks().account_data
  53. async def _notify_modules(
  54. self,
  55. user_id: str,
  56. room_id: Optional[str],
  57. account_data_type: str,
  58. content: JsonDict,
  59. ) -> None:
  60. """Notifies modules about new account data changes.
  61. A change can be either a new account data type being added, or the content
  62. associated with a type being changed. Account data for a given type is removed by
  63. changing the associated content to an empty dictionary.
  64. Note that this is not called when the tags associated with a room change.
  65. Args:
  66. user_id: The user whose account data is changing.
  67. room_id: The ID of the room the account data change concerns, if any.
  68. account_data_type: The type of the account data.
  69. content: The content that is now associated with this type.
  70. """
  71. for callback in self._module_api_callbacks.on_account_data_updated_callbacks:
  72. try:
  73. await callback(user_id, room_id, account_data_type, content)
  74. except Exception as e:
  75. logger.exception("Failed to run module callback %s: %s", callback, e)
  76. async def add_account_data_to_room(
  77. self, user_id: str, room_id: str, account_data_type: str, content: JsonDict
  78. ) -> int:
  79. """Add some account_data to a room for a user.
  80. Args:
  81. user_id: The user to add a tag for.
  82. room_id: The room to add a tag for.
  83. account_data_type: The type of account_data to add.
  84. content: A json object to associate with the tag.
  85. Returns:
  86. The maximum stream ID.
  87. """
  88. if self._instance_name in self._account_data_writers:
  89. max_stream_id = await self._store.add_account_data_to_room(
  90. user_id, room_id, account_data_type, content
  91. )
  92. self._notifier.on_new_event(
  93. StreamKeyType.ACCOUNT_DATA, max_stream_id, users=[user_id]
  94. )
  95. await self._notify_modules(user_id, room_id, account_data_type, content)
  96. return max_stream_id
  97. else:
  98. response = await self._add_room_data_client(
  99. instance_name=random.choice(self._account_data_writers),
  100. user_id=user_id,
  101. room_id=room_id,
  102. account_data_type=account_data_type,
  103. content=content,
  104. )
  105. return response["max_stream_id"]
  106. async def remove_account_data_for_room(
  107. self, user_id: str, room_id: str, account_data_type: str
  108. ) -> Optional[int]:
  109. """
  110. Deletes the room account data for the given user and account data type.
  111. "Deleting" account data merely means setting the content of the account data
  112. to an empty JSON object: {}.
  113. Args:
  114. user_id: The user ID to remove room account data for.
  115. room_id: The room ID to target.
  116. account_data_type: The account data type to remove.
  117. Returns:
  118. The maximum stream ID, or None if the room account data item did not exist.
  119. """
  120. if self._instance_name in self._account_data_writers:
  121. max_stream_id = await self._store.remove_account_data_for_room(
  122. user_id, room_id, account_data_type
  123. )
  124. self._notifier.on_new_event(
  125. StreamKeyType.ACCOUNT_DATA, max_stream_id, users=[user_id]
  126. )
  127. # Notify Synapse modules that the content of the type has changed to an
  128. # empty dictionary.
  129. await self._notify_modules(user_id, room_id, account_data_type, {})
  130. return max_stream_id
  131. else:
  132. response = await self._remove_room_data_client(
  133. instance_name=random.choice(self._account_data_writers),
  134. user_id=user_id,
  135. room_id=room_id,
  136. account_data_type=account_data_type,
  137. content={},
  138. )
  139. return response["max_stream_id"]
  140. async def add_account_data_for_user(
  141. self, user_id: str, account_data_type: str, content: JsonDict
  142. ) -> int:
  143. """Add some global account_data for a user.
  144. Args:
  145. user_id: The user to add some account data for.
  146. account_data_type: The type of account_data to add.
  147. content: The content json dictionary.
  148. Returns:
  149. The maximum stream ID.
  150. """
  151. if self._instance_name in self._account_data_writers:
  152. max_stream_id = await self._store.add_account_data_for_user(
  153. user_id, account_data_type, content
  154. )
  155. self._notifier.on_new_event(
  156. StreamKeyType.ACCOUNT_DATA, max_stream_id, users=[user_id]
  157. )
  158. await self._notify_modules(user_id, None, account_data_type, content)
  159. return max_stream_id
  160. else:
  161. response = await self._add_user_data_client(
  162. instance_name=random.choice(self._account_data_writers),
  163. user_id=user_id,
  164. account_data_type=account_data_type,
  165. content=content,
  166. )
  167. return response["max_stream_id"]
  168. async def remove_account_data_for_user(
  169. self, user_id: str, account_data_type: str
  170. ) -> Optional[int]:
  171. """Removes a piece of global account_data for a user.
  172. Args:
  173. user_id: The user to remove account data for.
  174. account_data_type: The type of account_data to remove.
  175. Returns:
  176. The maximum stream ID, or None if the room account data item did not exist.
  177. """
  178. if self._instance_name in self._account_data_writers:
  179. max_stream_id = await self._store.remove_account_data_for_user(
  180. user_id, account_data_type
  181. )
  182. self._notifier.on_new_event(
  183. StreamKeyType.ACCOUNT_DATA, max_stream_id, users=[user_id]
  184. )
  185. # Notify Synapse modules that the content of the type has changed to an
  186. # empty dictionary.
  187. await self._notify_modules(user_id, None, account_data_type, {})
  188. return max_stream_id
  189. else:
  190. response = await self._remove_user_data_client(
  191. instance_name=random.choice(self._account_data_writers),
  192. user_id=user_id,
  193. account_data_type=account_data_type,
  194. )
  195. return response["max_stream_id"]
  196. async def add_tag_to_room(
  197. self, user_id: str, room_id: str, tag: str, content: JsonDict
  198. ) -> int:
  199. """Add a tag to a room for a user.
  200. Args:
  201. user_id: The user to add a tag for.
  202. room_id: The room to add a tag for.
  203. tag: The tag name to add.
  204. content: A json object to associate with the tag.
  205. Returns:
  206. The next account data ID.
  207. """
  208. if self._instance_name in self._account_data_writers:
  209. max_stream_id = await self._store.add_tag_to_room(
  210. user_id, room_id, tag, content
  211. )
  212. self._notifier.on_new_event(
  213. StreamKeyType.ACCOUNT_DATA, max_stream_id, users=[user_id]
  214. )
  215. return max_stream_id
  216. else:
  217. response = await self._add_tag_client(
  218. instance_name=random.choice(self._account_data_writers),
  219. user_id=user_id,
  220. room_id=room_id,
  221. tag=tag,
  222. content=content,
  223. )
  224. return response["max_stream_id"]
  225. async def remove_tag_from_room(self, user_id: str, room_id: str, tag: str) -> int:
  226. """Remove a tag from a room for a user.
  227. Returns:
  228. The next account data ID.
  229. """
  230. if self._instance_name in self._account_data_writers:
  231. max_stream_id = await self._store.remove_tag_from_room(
  232. user_id, room_id, tag
  233. )
  234. self._notifier.on_new_event(
  235. StreamKeyType.ACCOUNT_DATA, max_stream_id, users=[user_id]
  236. )
  237. return max_stream_id
  238. else:
  239. response = await self._remove_tag_client(
  240. instance_name=random.choice(self._account_data_writers),
  241. user_id=user_id,
  242. room_id=room_id,
  243. tag=tag,
  244. )
  245. return response["max_stream_id"]
  246. class AccountDataEventSource(EventSource[int, JsonDict]):
  247. def __init__(self, hs: "HomeServer"):
  248. self.store = hs.get_datastores().main
  249. def get_current_key(self) -> int:
  250. return self.store.get_max_account_data_stream_id()
  251. async def get_new_events(
  252. self,
  253. user: UserID,
  254. from_key: int,
  255. limit: int,
  256. room_ids: StrCollection,
  257. is_guest: bool,
  258. explicit_room_id: Optional[str] = None,
  259. ) -> Tuple[List[JsonDict], int]:
  260. user_id = user.to_string()
  261. last_stream_id = from_key
  262. current_stream_id = self.store.get_max_account_data_stream_id()
  263. results = []
  264. tags = await self.store.get_updated_tags(user_id, last_stream_id)
  265. for room_id, room_tags in tags.items():
  266. results.append(
  267. {
  268. "type": AccountDataTypes.TAG,
  269. "content": {"tags": room_tags},
  270. "room_id": room_id,
  271. }
  272. )
  273. account_data = await self.store.get_updated_global_account_data_for_user(
  274. user_id, last_stream_id
  275. )
  276. room_account_data = await self.store.get_updated_room_account_data_for_user(
  277. user_id, last_stream_id
  278. )
  279. for account_data_type, content in account_data.items():
  280. results.append({"type": account_data_type, "content": content})
  281. for room_id, account_data in room_account_data.items():
  282. for account_data_type, content in account_data.items():
  283. results.append(
  284. {"type": account_data_type, "content": content, "room_id": room_id}
  285. )
  286. return results, current_stream_id