Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.
 
 
 
 
 
 

356 rader
13 KiB

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