Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.
 
 
 
 
 
 

1542 řádky
55 KiB

  1. # Copyright 2017 New Vector Ltd
  2. # Copyright 2020 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 email.utils
  16. import logging
  17. from typing import (
  18. TYPE_CHECKING,
  19. Any,
  20. Callable,
  21. Dict,
  22. Generator,
  23. Iterable,
  24. List,
  25. Optional,
  26. Tuple,
  27. TypeVar,
  28. Union,
  29. )
  30. import attr
  31. import jinja2
  32. from typing_extensions import ParamSpec
  33. from twisted.internet import defer
  34. from twisted.web.resource import Resource
  35. from synapse.api.errors import SynapseError
  36. from synapse.events import EventBase
  37. from synapse.events.presence_router import (
  38. GET_INTERESTED_USERS_CALLBACK,
  39. GET_USERS_FOR_STATES_CALLBACK,
  40. PresenceRouter,
  41. )
  42. from synapse.events.spamcheck import (
  43. CHECK_EVENT_FOR_SPAM_CALLBACK,
  44. CHECK_MEDIA_FILE_FOR_SPAM_CALLBACK,
  45. CHECK_REGISTRATION_FOR_SPAM_CALLBACK,
  46. CHECK_USERNAME_FOR_SPAM_CALLBACK,
  47. SHOULD_DROP_FEDERATED_EVENT_CALLBACK,
  48. USER_MAY_CREATE_ROOM_ALIAS_CALLBACK,
  49. USER_MAY_CREATE_ROOM_CALLBACK,
  50. USER_MAY_INVITE_CALLBACK,
  51. USER_MAY_JOIN_ROOM_CALLBACK,
  52. USER_MAY_PUBLISH_ROOM_CALLBACK,
  53. USER_MAY_SEND_3PID_INVITE_CALLBACK,
  54. SpamChecker,
  55. )
  56. from synapse.events.third_party_rules import (
  57. CHECK_CAN_DEACTIVATE_USER_CALLBACK,
  58. CHECK_CAN_SHUTDOWN_ROOM_CALLBACK,
  59. CHECK_EVENT_ALLOWED_CALLBACK,
  60. CHECK_THREEPID_CAN_BE_INVITED_CALLBACK,
  61. CHECK_VISIBILITY_CAN_BE_MODIFIED_CALLBACK,
  62. ON_CREATE_ROOM_CALLBACK,
  63. ON_NEW_EVENT_CALLBACK,
  64. ON_PROFILE_UPDATE_CALLBACK,
  65. ON_THREEPID_BIND_CALLBACK,
  66. ON_USER_DEACTIVATION_STATUS_CHANGED_CALLBACK,
  67. )
  68. from synapse.handlers.account_data import ON_ACCOUNT_DATA_UPDATED_CALLBACK
  69. from synapse.handlers.account_validity import (
  70. IS_USER_EXPIRED_CALLBACK,
  71. ON_LEGACY_ADMIN_REQUEST,
  72. ON_LEGACY_RENEW_CALLBACK,
  73. ON_LEGACY_SEND_MAIL_CALLBACK,
  74. ON_USER_REGISTRATION_CALLBACK,
  75. )
  76. from synapse.handlers.auth import (
  77. CHECK_3PID_AUTH_CALLBACK,
  78. CHECK_AUTH_CALLBACK,
  79. GET_DISPLAYNAME_FOR_REGISTRATION_CALLBACK,
  80. GET_USERNAME_FOR_REGISTRATION_CALLBACK,
  81. IS_3PID_ALLOWED_CALLBACK,
  82. ON_LOGGED_OUT_CALLBACK,
  83. AuthHandler,
  84. )
  85. from synapse.handlers.push_rules import RuleSpec, check_actions
  86. from synapse.http.client import SimpleHttpClient
  87. from synapse.http.server import (
  88. DirectServeHtmlResource,
  89. DirectServeJsonResource,
  90. respond_with_html,
  91. )
  92. from synapse.http.servlet import parse_json_object_from_request
  93. from synapse.http.site import SynapseRequest
  94. from synapse.logging.context import (
  95. defer_to_thread,
  96. make_deferred_yieldable,
  97. run_in_background,
  98. )
  99. from synapse.metrics.background_process_metrics import run_as_background_process
  100. from synapse.rest.client.login import LoginResponse
  101. from synapse.storage import DataStore
  102. from synapse.storage.background_updates import (
  103. DEFAULT_BATCH_SIZE_CALLBACK,
  104. MIN_BATCH_SIZE_CALLBACK,
  105. ON_UPDATE_CALLBACK,
  106. )
  107. from synapse.storage.database import DatabasePool, LoggingTransaction
  108. from synapse.storage.databases.main.roommember import ProfileInfo
  109. from synapse.storage.state import StateFilter
  110. from synapse.types import (
  111. DomainSpecificString,
  112. JsonDict,
  113. JsonMapping,
  114. Requester,
  115. StateMap,
  116. UserID,
  117. UserInfo,
  118. UserProfile,
  119. create_requester,
  120. )
  121. from synapse.util import Clock
  122. from synapse.util.async_helpers import maybe_awaitable
  123. from synapse.util.caches.descriptors import cached
  124. from synapse.util.frozenutils import freeze
  125. if TYPE_CHECKING:
  126. from synapse.app.generic_worker import GenericWorkerSlavedStore
  127. from synapse.server import HomeServer
  128. T = TypeVar("T")
  129. P = ParamSpec("P")
  130. """
  131. This package defines the 'stable' API which can be used by extension modules which
  132. are loaded into Synapse.
  133. """
  134. PRESENCE_ALL_USERS = PresenceRouter.ALL_USERS
  135. NOT_SPAM = SpamChecker.NOT_SPAM
  136. __all__ = [
  137. "errors",
  138. "make_deferred_yieldable",
  139. "parse_json_object_from_request",
  140. "respond_with_html",
  141. "run_in_background",
  142. "cached",
  143. "NOT_SPAM",
  144. "UserID",
  145. "DatabasePool",
  146. "LoggingTransaction",
  147. "DirectServeHtmlResource",
  148. "DirectServeJsonResource",
  149. "ModuleApi",
  150. "PRESENCE_ALL_USERS",
  151. "LoginResponse",
  152. "JsonDict",
  153. "JsonMapping",
  154. "EventBase",
  155. "StateMap",
  156. "ProfileInfo",
  157. "UserProfile",
  158. ]
  159. logger = logging.getLogger(__name__)
  160. @attr.s(auto_attribs=True)
  161. class UserIpAndAgent:
  162. """
  163. An IP address and user agent used by a user to connect to this homeserver.
  164. """
  165. ip: str
  166. user_agent: str
  167. # The time at which this user agent/ip was last seen.
  168. last_seen: int
  169. class ModuleApi:
  170. """A proxy object that gets passed to various plugin modules so they
  171. can register new users etc if necessary.
  172. """
  173. def __init__(self, hs: "HomeServer", auth_handler: AuthHandler) -> None:
  174. self._hs = hs
  175. # TODO: Fix this type hint once the types for the data stores have been ironed
  176. # out.
  177. self._store: Union[
  178. DataStore, "GenericWorkerSlavedStore"
  179. ] = hs.get_datastores().main
  180. self._auth = hs.get_auth()
  181. self._auth_handler = auth_handler
  182. self._server_name = hs.hostname
  183. self._presence_stream = hs.get_event_sources().sources.presence
  184. self._state = hs.get_state_handler()
  185. self._clock: Clock = hs.get_clock()
  186. self._registration_handler = hs.get_registration_handler()
  187. self._send_email_handler = hs.get_send_email_handler()
  188. self._push_rules_handler = hs.get_push_rules_handler()
  189. self.custom_template_dir = hs.config.server.custom_template_directory
  190. try:
  191. app_name = self._hs.config.email.email_app_name
  192. self._from_string = self._hs.config.email.email_notif_from % {
  193. "app": app_name
  194. }
  195. except (KeyError, TypeError):
  196. # If substitution failed (which can happen if the string contains
  197. # placeholders other than just "app", or if the type of the placeholder is
  198. # not a string), fall back to the bare strings.
  199. self._from_string = self._hs.config.email.email_notif_from
  200. self._raw_from = email.utils.parseaddr(self._from_string)[1]
  201. # We expose these as properties below in order to attach a helpful docstring.
  202. self._http_client: SimpleHttpClient = hs.get_simple_http_client()
  203. self._public_room_list_manager = PublicRoomListManager(hs)
  204. self._account_data_manager = AccountDataManager(hs)
  205. self._spam_checker = hs.get_spam_checker()
  206. self._account_validity_handler = hs.get_account_validity_handler()
  207. self._third_party_event_rules = hs.get_third_party_event_rules()
  208. self._password_auth_provider = hs.get_password_auth_provider()
  209. self._presence_router = hs.get_presence_router()
  210. self._account_data_handler = hs.get_account_data_handler()
  211. #################################################################################
  212. # The following methods should only be called during the module's initialisation.
  213. def register_spam_checker_callbacks(
  214. self,
  215. *,
  216. check_event_for_spam: Optional[CHECK_EVENT_FOR_SPAM_CALLBACK] = None,
  217. should_drop_federated_event: Optional[
  218. SHOULD_DROP_FEDERATED_EVENT_CALLBACK
  219. ] = None,
  220. user_may_join_room: Optional[USER_MAY_JOIN_ROOM_CALLBACK] = None,
  221. user_may_invite: Optional[USER_MAY_INVITE_CALLBACK] = None,
  222. user_may_send_3pid_invite: Optional[USER_MAY_SEND_3PID_INVITE_CALLBACK] = None,
  223. user_may_create_room: Optional[USER_MAY_CREATE_ROOM_CALLBACK] = None,
  224. user_may_create_room_alias: Optional[
  225. USER_MAY_CREATE_ROOM_ALIAS_CALLBACK
  226. ] = None,
  227. user_may_publish_room: Optional[USER_MAY_PUBLISH_ROOM_CALLBACK] = None,
  228. check_username_for_spam: Optional[CHECK_USERNAME_FOR_SPAM_CALLBACK] = None,
  229. check_registration_for_spam: Optional[
  230. CHECK_REGISTRATION_FOR_SPAM_CALLBACK
  231. ] = None,
  232. check_media_file_for_spam: Optional[CHECK_MEDIA_FILE_FOR_SPAM_CALLBACK] = None,
  233. ) -> None:
  234. """Registers callbacks for spam checking capabilities.
  235. Added in Synapse v1.37.0.
  236. """
  237. return self._spam_checker.register_callbacks(
  238. check_event_for_spam=check_event_for_spam,
  239. should_drop_federated_event=should_drop_federated_event,
  240. user_may_join_room=user_may_join_room,
  241. user_may_invite=user_may_invite,
  242. user_may_send_3pid_invite=user_may_send_3pid_invite,
  243. user_may_create_room=user_may_create_room,
  244. user_may_create_room_alias=user_may_create_room_alias,
  245. user_may_publish_room=user_may_publish_room,
  246. check_username_for_spam=check_username_for_spam,
  247. check_registration_for_spam=check_registration_for_spam,
  248. check_media_file_for_spam=check_media_file_for_spam,
  249. )
  250. def register_account_validity_callbacks(
  251. self,
  252. *,
  253. is_user_expired: Optional[IS_USER_EXPIRED_CALLBACK] = None,
  254. on_user_registration: Optional[ON_USER_REGISTRATION_CALLBACK] = None,
  255. on_legacy_send_mail: Optional[ON_LEGACY_SEND_MAIL_CALLBACK] = None,
  256. on_legacy_renew: Optional[ON_LEGACY_RENEW_CALLBACK] = None,
  257. on_legacy_admin_request: Optional[ON_LEGACY_ADMIN_REQUEST] = None,
  258. ) -> None:
  259. """Registers callbacks for account validity capabilities.
  260. Added in Synapse v1.39.0.
  261. """
  262. return self._account_validity_handler.register_account_validity_callbacks(
  263. is_user_expired=is_user_expired,
  264. on_user_registration=on_user_registration,
  265. on_legacy_send_mail=on_legacy_send_mail,
  266. on_legacy_renew=on_legacy_renew,
  267. on_legacy_admin_request=on_legacy_admin_request,
  268. )
  269. def register_third_party_rules_callbacks(
  270. self,
  271. *,
  272. check_event_allowed: Optional[CHECK_EVENT_ALLOWED_CALLBACK] = None,
  273. on_create_room: Optional[ON_CREATE_ROOM_CALLBACK] = None,
  274. check_threepid_can_be_invited: Optional[
  275. CHECK_THREEPID_CAN_BE_INVITED_CALLBACK
  276. ] = None,
  277. check_visibility_can_be_modified: Optional[
  278. CHECK_VISIBILITY_CAN_BE_MODIFIED_CALLBACK
  279. ] = None,
  280. on_new_event: Optional[ON_NEW_EVENT_CALLBACK] = None,
  281. check_can_shutdown_room: Optional[CHECK_CAN_SHUTDOWN_ROOM_CALLBACK] = None,
  282. check_can_deactivate_user: Optional[CHECK_CAN_DEACTIVATE_USER_CALLBACK] = None,
  283. on_profile_update: Optional[ON_PROFILE_UPDATE_CALLBACK] = None,
  284. on_user_deactivation_status_changed: Optional[
  285. ON_USER_DEACTIVATION_STATUS_CHANGED_CALLBACK
  286. ] = None,
  287. on_threepid_bind: Optional[ON_THREEPID_BIND_CALLBACK] = None,
  288. ) -> None:
  289. """Registers callbacks for third party event rules capabilities.
  290. Added in Synapse v1.39.0.
  291. """
  292. return self._third_party_event_rules.register_third_party_rules_callbacks(
  293. check_event_allowed=check_event_allowed,
  294. on_create_room=on_create_room,
  295. check_threepid_can_be_invited=check_threepid_can_be_invited,
  296. check_visibility_can_be_modified=check_visibility_can_be_modified,
  297. on_new_event=on_new_event,
  298. check_can_shutdown_room=check_can_shutdown_room,
  299. check_can_deactivate_user=check_can_deactivate_user,
  300. on_profile_update=on_profile_update,
  301. on_user_deactivation_status_changed=on_user_deactivation_status_changed,
  302. on_threepid_bind=on_threepid_bind,
  303. )
  304. def register_presence_router_callbacks(
  305. self,
  306. *,
  307. get_users_for_states: Optional[GET_USERS_FOR_STATES_CALLBACK] = None,
  308. get_interested_users: Optional[GET_INTERESTED_USERS_CALLBACK] = None,
  309. ) -> None:
  310. """Registers callbacks for presence router capabilities.
  311. Added in Synapse v1.42.0.
  312. """
  313. return self._presence_router.register_presence_router_callbacks(
  314. get_users_for_states=get_users_for_states,
  315. get_interested_users=get_interested_users,
  316. )
  317. def register_password_auth_provider_callbacks(
  318. self,
  319. *,
  320. check_3pid_auth: Optional[CHECK_3PID_AUTH_CALLBACK] = None,
  321. on_logged_out: Optional[ON_LOGGED_OUT_CALLBACK] = None,
  322. auth_checkers: Optional[
  323. Dict[Tuple[str, Tuple[str, ...]], CHECK_AUTH_CALLBACK]
  324. ] = None,
  325. is_3pid_allowed: Optional[IS_3PID_ALLOWED_CALLBACK] = None,
  326. get_username_for_registration: Optional[
  327. GET_USERNAME_FOR_REGISTRATION_CALLBACK
  328. ] = None,
  329. get_displayname_for_registration: Optional[
  330. GET_DISPLAYNAME_FOR_REGISTRATION_CALLBACK
  331. ] = None,
  332. ) -> None:
  333. """Registers callbacks for password auth provider capabilities.
  334. Added in Synapse v1.46.0.
  335. """
  336. return self._password_auth_provider.register_password_auth_provider_callbacks(
  337. check_3pid_auth=check_3pid_auth,
  338. on_logged_out=on_logged_out,
  339. is_3pid_allowed=is_3pid_allowed,
  340. auth_checkers=auth_checkers,
  341. get_username_for_registration=get_username_for_registration,
  342. get_displayname_for_registration=get_displayname_for_registration,
  343. )
  344. def register_background_update_controller_callbacks(
  345. self,
  346. *,
  347. on_update: ON_UPDATE_CALLBACK,
  348. default_batch_size: Optional[DEFAULT_BATCH_SIZE_CALLBACK] = None,
  349. min_batch_size: Optional[MIN_BATCH_SIZE_CALLBACK] = None,
  350. ) -> None:
  351. """Registers background update controller callbacks.
  352. Added in Synapse v1.49.0.
  353. """
  354. for db in self._hs.get_datastores().databases:
  355. db.updates.register_update_controller_callbacks(
  356. on_update=on_update,
  357. default_batch_size=default_batch_size,
  358. min_batch_size=min_batch_size,
  359. )
  360. def register_account_data_callbacks(
  361. self,
  362. *,
  363. on_account_data_updated: Optional[ON_ACCOUNT_DATA_UPDATED_CALLBACK] = None,
  364. ) -> None:
  365. """Registers account data callbacks.
  366. Added in Synapse 1.57.0.
  367. """
  368. return self._account_data_handler.register_module_callbacks(
  369. on_account_data_updated=on_account_data_updated,
  370. )
  371. def register_web_resource(self, path: str, resource: Resource) -> None:
  372. """Registers a web resource to be served at the given path.
  373. This function should be called during initialisation of the module.
  374. If multiple modules register a resource for the same path, the module that
  375. appears the highest in the configuration file takes priority.
  376. Added in Synapse v1.37.0.
  377. Args:
  378. path: The path to register the resource for.
  379. resource: The resource to attach to this path.
  380. """
  381. self._hs.register_module_web_resource(path, resource)
  382. #########################################################################
  383. # The following methods can be called by the module at any point in time.
  384. @property
  385. def http_client(self) -> SimpleHttpClient:
  386. """Allows making outbound HTTP requests to remote resources.
  387. An instance of synapse.http.client.SimpleHttpClient
  388. Added in Synapse v1.22.0.
  389. """
  390. return self._http_client
  391. @property
  392. def public_room_list_manager(self) -> "PublicRoomListManager":
  393. """Allows adding to, removing from and checking the status of rooms in the
  394. public room list.
  395. An instance of synapse.module_api.PublicRoomListManager
  396. Added in Synapse v1.22.0.
  397. """
  398. return self._public_room_list_manager
  399. @property
  400. def account_data_manager(self) -> "AccountDataManager":
  401. """Allows reading and modifying users' account data.
  402. Added in Synapse v1.57.0.
  403. """
  404. return self._account_data_manager
  405. @property
  406. def public_baseurl(self) -> str:
  407. """The configured public base URL for this homeserver.
  408. Added in Synapse v1.39.0.
  409. """
  410. return self._hs.config.server.public_baseurl
  411. @property
  412. def email_app_name(self) -> str:
  413. """The application name configured in the homeserver's configuration.
  414. Added in Synapse v1.39.0.
  415. """
  416. return self._hs.config.email.email_app_name
  417. @property
  418. def server_name(self) -> str:
  419. """The server name for the local homeserver.
  420. Added in Synapse v1.53.0.
  421. """
  422. return self._server_name
  423. @property
  424. def worker_name(self) -> Optional[str]:
  425. """The name of the worker this specific instance is running as per the
  426. "worker_name" configuration setting, or None if it's the main process.
  427. Added in Synapse v1.53.0.
  428. """
  429. return self._hs.config.worker.worker_name
  430. @property
  431. def worker_app(self) -> Optional[str]:
  432. """The name of the worker app this specific instance is running as per the
  433. "worker_app" configuration setting, or None if it's the main process.
  434. Added in Synapse v1.53.0.
  435. """
  436. return self._hs.config.worker.worker_app
  437. async def get_userinfo_by_id(self, user_id: str) -> Optional[UserInfo]:
  438. """Get user info by user_id
  439. Added in Synapse v1.41.0.
  440. Args:
  441. user_id: Fully qualified user id.
  442. Returns:
  443. UserInfo object if a user was found, otherwise None
  444. """
  445. return await self._store.get_userinfo_by_id(user_id)
  446. async def get_user_by_req(
  447. self,
  448. req: SynapseRequest,
  449. allow_guest: bool = False,
  450. allow_expired: bool = False,
  451. ) -> Requester:
  452. """Check the access_token provided for a request
  453. Added in Synapse v1.39.0.
  454. Args:
  455. req: Incoming HTTP request
  456. allow_guest: True if guest users should be allowed. If this
  457. is False, and the access token is for a guest user, an
  458. AuthError will be thrown
  459. allow_expired: True if expired users should be allowed. If this
  460. is False, and the access token is for an expired user, an
  461. AuthError will be thrown
  462. Returns:
  463. The requester for this request
  464. Raises:
  465. InvalidClientCredentialsError: if no user by that token exists,
  466. or the token is invalid.
  467. """
  468. return await self._auth.get_user_by_req(
  469. req,
  470. allow_guest,
  471. allow_expired=allow_expired,
  472. )
  473. async def is_user_admin(self, user_id: str) -> bool:
  474. """Checks if a user is a server admin.
  475. Added in Synapse v1.39.0.
  476. Args:
  477. user_id: The Matrix ID of the user to check.
  478. Returns:
  479. True if the user is a server admin, False otherwise.
  480. """
  481. return await self._store.is_server_admin(UserID.from_string(user_id))
  482. async def set_user_admin(self, user_id: str, admin: bool) -> None:
  483. """Sets if a user is a server admin.
  484. Added in Synapse v1.56.0.
  485. Args:
  486. user_id: The Matrix ID of the user to set admin status for.
  487. admin: True iff the user is to be a server admin, false otherwise.
  488. """
  489. await self._store.set_server_admin(UserID.from_string(user_id), admin)
  490. def get_qualified_user_id(self, username: str) -> str:
  491. """Qualify a user id, if necessary
  492. Takes a user id provided by the user and adds the @ and :domain to
  493. qualify it, if necessary
  494. Added in Synapse v0.25.0.
  495. Args:
  496. username: provided user id
  497. Returns:
  498. qualified @user:id
  499. """
  500. if username.startswith("@"):
  501. return username
  502. return UserID(username, self._hs.hostname).to_string()
  503. async def get_profile_for_user(self, localpart: str) -> ProfileInfo:
  504. """Look up the profile info for the user with the given localpart.
  505. Added in Synapse v1.39.0.
  506. Args:
  507. localpart: The localpart to look up profile information for.
  508. Returns:
  509. The profile information (i.e. display name and avatar URL).
  510. """
  511. return await self._store.get_profileinfo(localpart)
  512. async def get_threepids_for_user(self, user_id: str) -> List[Dict[str, str]]:
  513. """Look up the threepids (email addresses and phone numbers) associated with the
  514. given Matrix user ID.
  515. Added in Synapse v1.39.0.
  516. Args:
  517. user_id: The Matrix user ID to look up threepids for.
  518. Returns:
  519. A list of threepids, each threepid being represented by a dictionary
  520. containing a "medium" key which value is "email" for email addresses and
  521. "msisdn" for phone numbers, and an "address" key which value is the
  522. threepid's address.
  523. """
  524. return await self._store.user_get_threepids(user_id)
  525. def check_user_exists(self, user_id: str) -> "defer.Deferred[Optional[str]]":
  526. """Check if user exists.
  527. Added in Synapse v0.25.0.
  528. Args:
  529. user_id: Complete @user:id
  530. Returns:
  531. Canonical (case-corrected) user_id, or None
  532. if the user is not registered.
  533. """
  534. return defer.ensureDeferred(self._auth_handler.check_user_exists(user_id))
  535. @defer.inlineCallbacks
  536. def register(
  537. self,
  538. localpart: str,
  539. displayname: Optional[str] = None,
  540. emails: Optional[List[str]] = None,
  541. ) -> Generator["defer.Deferred[Any]", Any, Tuple[str, str]]:
  542. """Registers a new user with given localpart and optional displayname, emails.
  543. Also returns an access token for the new user.
  544. Deprecated: avoid this, as it generates a new device with no way to
  545. return that device to the user. Prefer separate calls to register_user and
  546. register_device.
  547. Added in Synapse v0.25.0.
  548. Args:
  549. localpart: The localpart of the new user.
  550. displayname: The displayname of the new user.
  551. emails: Emails to bind to the new user.
  552. Returns:
  553. a 2-tuple of (user_id, access_token)
  554. """
  555. logger.warning(
  556. "Using deprecated ModuleApi.register which creates a dummy user device."
  557. )
  558. user_id = yield self.register_user(localpart, displayname, emails or [])
  559. _, access_token, _, _ = yield self.register_device(user_id)
  560. return user_id, access_token
  561. def register_user(
  562. self,
  563. localpart: str,
  564. displayname: Optional[str] = None,
  565. emails: Optional[List[str]] = None,
  566. admin: bool = False,
  567. ) -> "defer.Deferred[str]":
  568. """Registers a new user with given localpart and optional displayname, emails.
  569. Added in Synapse v1.2.0.
  570. Changed in Synapse v1.56.0: add 'admin' argument to register the user as admin.
  571. Args:
  572. localpart: The localpart of the new user.
  573. displayname: The displayname of the new user.
  574. emails: Emails to bind to the new user.
  575. admin: True if the user should be registered as a server admin.
  576. Raises:
  577. SynapseError if there is an error performing the registration. Check the
  578. 'errcode' property for more information on the reason for failure
  579. Returns:
  580. user_id
  581. """
  582. return defer.ensureDeferred(
  583. self._hs.get_registration_handler().register_user(
  584. localpart=localpart,
  585. default_display_name=displayname,
  586. bind_emails=emails or [],
  587. admin=admin,
  588. )
  589. )
  590. def register_device(
  591. self,
  592. user_id: str,
  593. device_id: Optional[str] = None,
  594. initial_display_name: Optional[str] = None,
  595. ) -> "defer.Deferred[Tuple[str, str, Optional[int], Optional[str]]]":
  596. """Register a device for a user and generate an access token.
  597. Added in Synapse v1.2.0.
  598. Args:
  599. user_id: full canonical @user:id
  600. device_id: The device ID to check, or None to generate
  601. a new one.
  602. initial_display_name: An optional display name for the
  603. device.
  604. Returns:
  605. Tuple of device ID, access token, access token expiration time and refresh token
  606. """
  607. return defer.ensureDeferred(
  608. self._hs.get_registration_handler().register_device(
  609. user_id=user_id,
  610. device_id=device_id,
  611. initial_display_name=initial_display_name,
  612. )
  613. )
  614. def record_user_external_id(
  615. self, auth_provider_id: str, remote_user_id: str, registered_user_id: str
  616. ) -> defer.Deferred:
  617. """Record a mapping between an external user id from a single sign-on provider
  618. and a mxid.
  619. Added in Synapse v1.9.0.
  620. Args:
  621. auth_provider: identifier for the remote auth provider, see `sso` and
  622. `oidc_providers` in the homeserver configuration.
  623. Note that no error is raised if the provided value is not in the
  624. homeserver configuration.
  625. external_id: id on that system
  626. user_id: complete mxid that it is mapped to
  627. """
  628. return defer.ensureDeferred(
  629. self._store.record_user_external_id(
  630. auth_provider_id, remote_user_id, registered_user_id
  631. )
  632. )
  633. def generate_short_term_login_token(
  634. self,
  635. user_id: str,
  636. duration_in_ms: int = (2 * 60 * 1000),
  637. auth_provider_id: str = "",
  638. auth_provider_session_id: Optional[str] = None,
  639. ) -> str:
  640. """Generate a login token suitable for m.login.token authentication
  641. Added in Synapse v1.9.0.
  642. Args:
  643. user_id: gives the ID of the user that the token is for
  644. duration_in_ms: the time that the token will be valid for
  645. auth_provider_id: the ID of the SSO IdP that the user used to authenticate
  646. to get this token, if any. This is encoded in the token so that
  647. /login can report stats on number of successful logins by IdP.
  648. """
  649. return self._hs.get_macaroon_generator().generate_short_term_login_token(
  650. user_id,
  651. auth_provider_id,
  652. auth_provider_session_id,
  653. duration_in_ms,
  654. )
  655. @defer.inlineCallbacks
  656. def invalidate_access_token(
  657. self, access_token: str
  658. ) -> Generator["defer.Deferred[Any]", Any, None]:
  659. """Invalidate an access token for a user
  660. Added in Synapse v0.25.0.
  661. Args:
  662. access_token(str): access token
  663. Returns:
  664. twisted.internet.defer.Deferred - resolves once the access token
  665. has been removed.
  666. Raises:
  667. synapse.api.errors.AuthError: the access token is invalid
  668. """
  669. # see if the access token corresponds to a device
  670. user_info = yield defer.ensureDeferred(
  671. self._auth.get_user_by_access_token(access_token)
  672. )
  673. device_id = user_info.get("device_id")
  674. user_id = user_info["user"].to_string()
  675. if device_id:
  676. # delete the device, which will also delete its access tokens
  677. yield defer.ensureDeferred(
  678. self._hs.get_device_handler().delete_device(user_id, device_id)
  679. )
  680. else:
  681. # no associated device. Just delete the access token.
  682. yield defer.ensureDeferred(
  683. self._auth_handler.delete_access_token(access_token)
  684. )
  685. def run_db_interaction(
  686. self,
  687. desc: str,
  688. func: Callable[P, T],
  689. *args: P.args,
  690. **kwargs: P.kwargs,
  691. ) -> "defer.Deferred[T]":
  692. """Run a function with a database connection
  693. Added in Synapse v0.25.0.
  694. Args:
  695. desc: description for the transaction, for metrics etc
  696. func: function to be run. Passed a database cursor object
  697. as well as *args and **kwargs
  698. *args: positional args to be passed to func
  699. **kwargs: named args to be passed to func
  700. Returns:
  701. Deferred[object]: result of func
  702. """
  703. # type-ignore: See https://github.com/python/mypy/issues/8862
  704. return defer.ensureDeferred(
  705. self._store.db_pool.runInteraction(desc, func, *args, **kwargs) # type: ignore[arg-type]
  706. )
  707. def complete_sso_login(
  708. self, registered_user_id: str, request: SynapseRequest, client_redirect_url: str
  709. ) -> None:
  710. """Complete a SSO login by redirecting the user to a page to confirm whether they
  711. want their access token sent to `client_redirect_url`, or redirect them to that
  712. URL with a token directly if the URL matches with one of the whitelisted clients.
  713. This is deprecated in favor of complete_sso_login_async.
  714. Added in Synapse v1.11.1.
  715. Args:
  716. registered_user_id: The MXID that has been registered as a previous step of
  717. of this SSO login.
  718. request: The request to respond to.
  719. client_redirect_url: The URL to which to offer to redirect the user (or to
  720. redirect them directly if whitelisted).
  721. """
  722. self._auth_handler._complete_sso_login(
  723. registered_user_id,
  724. "<unknown>",
  725. request,
  726. client_redirect_url,
  727. )
  728. async def complete_sso_login_async(
  729. self,
  730. registered_user_id: str,
  731. request: SynapseRequest,
  732. client_redirect_url: str,
  733. new_user: bool = False,
  734. auth_provider_id: str = "<unknown>",
  735. ) -> None:
  736. """Complete a SSO login by redirecting the user to a page to confirm whether they
  737. want their access token sent to `client_redirect_url`, or redirect them to that
  738. URL with a token directly if the URL matches with one of the whitelisted clients.
  739. Added in Synapse v1.13.0.
  740. Args:
  741. registered_user_id: The MXID that has been registered as a previous step of
  742. of this SSO login.
  743. request: The request to respond to.
  744. client_redirect_url: The URL to which to offer to redirect the user (or to
  745. redirect them directly if whitelisted).
  746. new_user: set to true to use wording for the consent appropriate to a user
  747. who has just registered.
  748. auth_provider_id: the ID of the SSO IdP which was used to log in. This
  749. is used to track counts of sucessful logins by IdP.
  750. """
  751. await self._auth_handler.complete_sso_login(
  752. registered_user_id,
  753. auth_provider_id,
  754. request,
  755. client_redirect_url,
  756. new_user=new_user,
  757. )
  758. @defer.inlineCallbacks
  759. def get_state_events_in_room(
  760. self, room_id: str, types: Iterable[Tuple[str, Optional[str]]]
  761. ) -> Generator[defer.Deferred, Any, Iterable[EventBase]]:
  762. """Gets current state events for the given room.
  763. (This is exposed for compatibility with the old SpamCheckerApi. We should
  764. probably deprecate it and replace it with an async method in a subclass.)
  765. Added in Synapse v1.22.0.
  766. Args:
  767. room_id: The room ID to get state events in.
  768. types: The event type and state key (using None
  769. to represent 'any') of the room state to acquire.
  770. Returns:
  771. twisted.internet.defer.Deferred[list(synapse.events.FrozenEvent)]:
  772. The filtered state events in the room.
  773. """
  774. state_ids = yield defer.ensureDeferred(
  775. self._store.get_filtered_current_state_ids(
  776. room_id=room_id, state_filter=StateFilter.from_types(types)
  777. )
  778. )
  779. state = yield defer.ensureDeferred(self._store.get_events(state_ids.values()))
  780. return state.values()
  781. async def update_room_membership(
  782. self,
  783. sender: str,
  784. target: str,
  785. room_id: str,
  786. new_membership: str,
  787. content: Optional[JsonDict] = None,
  788. ) -> EventBase:
  789. """Updates the membership of a user to the given value.
  790. Added in Synapse v1.46.0.
  791. Args:
  792. sender: The user performing the membership change. Must be a user local to
  793. this homeserver.
  794. target: The user whose membership is changing. This is often the same value
  795. as `sender`, but it might differ in some cases (e.g. when kicking a user,
  796. the `sender` is the user performing the kick and the `target` is the user
  797. being kicked).
  798. room_id: The room in which to change the membership.
  799. new_membership: The new membership state of `target` after this operation. See
  800. https://spec.matrix.org/unstable/client-server-api/#mroommember for the
  801. list of allowed values.
  802. content: Additional values to include in the resulting event's content.
  803. Returns:
  804. The newly created membership event.
  805. Raises:
  806. RuntimeError if the `sender` isn't a local user.
  807. ShadowBanError if a shadow-banned requester attempts to send an invite.
  808. SynapseError if the module attempts to send a membership event that isn't
  809. allowed, either by the server's configuration (e.g. trying to set a
  810. per-room display name that's too long) or by the validation rules around
  811. membership updates (e.g. the `membership` value is invalid).
  812. """
  813. if not self.is_mine(sender):
  814. raise RuntimeError(
  815. "Tried to send an event as a user that isn't local to this homeserver",
  816. )
  817. requester = create_requester(sender)
  818. target_user_id = UserID.from_string(target)
  819. if content is None:
  820. content = {}
  821. # Set the profile if not already done by the module.
  822. if "avatar_url" not in content or "displayname" not in content:
  823. try:
  824. # Try to fetch the user's profile.
  825. profile = await self._hs.get_profile_handler().get_profile(
  826. target_user_id.to_string(),
  827. )
  828. except SynapseError as e:
  829. # If the profile couldn't be found, use default values.
  830. profile = {
  831. "displayname": target_user_id.localpart,
  832. "avatar_url": None,
  833. }
  834. if e.code != 404:
  835. # If the error isn't 404, it means we tried to fetch the profile over
  836. # federation but the remote server responded with a non-standard
  837. # status code.
  838. logger.error(
  839. "Got non-404 error status when fetching profile for %s",
  840. target_user_id.to_string(),
  841. )
  842. # Set the profile where it needs to be set.
  843. if "avatar_url" not in content:
  844. content["avatar_url"] = profile["avatar_url"]
  845. if "displayname" not in content:
  846. content["displayname"] = profile["displayname"]
  847. event_id, _ = await self._hs.get_room_member_handler().update_membership(
  848. requester=requester,
  849. target=target_user_id,
  850. room_id=room_id,
  851. action=new_membership,
  852. content=content,
  853. )
  854. # Try to retrieve the resulting event.
  855. event = await self._hs.get_datastores().main.get_event(event_id)
  856. # update_membership is supposed to always return after the event has been
  857. # successfully persisted.
  858. assert event is not None
  859. return event
  860. async def create_and_send_event_into_room(self, event_dict: JsonDict) -> EventBase:
  861. """Create and send an event into a room.
  862. Membership events are not supported by this method. To update a user's membership
  863. in a room, please use the `update_room_membership` method instead.
  864. Added in Synapse v1.22.0.
  865. Args:
  866. event_dict: A dictionary representing the event to send.
  867. Required keys are `type`, `room_id`, `sender` and `content`.
  868. Returns:
  869. The event that was sent. If state event deduplication happened, then
  870. the previous, duplicate event instead.
  871. Raises:
  872. SynapseError if the event was not allowed.
  873. """
  874. # Create a requester object
  875. requester = create_requester(
  876. event_dict["sender"], authenticated_entity=self._server_name
  877. )
  878. # Create and send the event
  879. (
  880. event,
  881. _,
  882. ) = await self._hs.get_event_creation_handler().create_and_send_nonmember_event(
  883. requester,
  884. event_dict,
  885. ratelimit=False,
  886. ignore_shadow_ban=True,
  887. )
  888. return event
  889. async def send_local_online_presence_to(self, users: Iterable[str]) -> None:
  890. """
  891. Forces the equivalent of a presence initial_sync for a set of local or remote
  892. users. The users will receive presence for all currently online users that they
  893. are considered interested in.
  894. Updates to remote users will be sent immediately, whereas local users will receive
  895. them on their next sync attempt.
  896. Note that this method can only be run on the process that is configured to write to the
  897. presence stream. By default this is the main process.
  898. Added in Synapse v1.32.0.
  899. """
  900. if self._hs._instance_name not in self._hs.config.worker.writers.presence:
  901. raise Exception(
  902. "send_local_online_presence_to can only be run "
  903. "on the process that is configured to write to the "
  904. "presence stream (by default this is the main process)",
  905. )
  906. local_users = set()
  907. remote_users = set()
  908. for user in users:
  909. if self._hs.is_mine_id(user):
  910. local_users.add(user)
  911. else:
  912. remote_users.add(user)
  913. # We pull out the presence handler here to break a cyclic
  914. # dependency between the presence router and module API.
  915. presence_handler = self._hs.get_presence_handler()
  916. if local_users:
  917. # Force a presence initial_sync for these users next time they sync.
  918. await presence_handler.send_full_presence_to_users(local_users)
  919. for user in remote_users:
  920. # Retrieve presence state for currently online users that this user
  921. # is considered interested in.
  922. presence_events, _ = await self._presence_stream.get_new_events(
  923. UserID.from_string(user), from_key=None, include_offline=False
  924. )
  925. # Send to remote destinations.
  926. destination = UserID.from_string(user).domain
  927. presence_handler.get_federation_queue().send_presence_to_destinations(
  928. presence_events, destination
  929. )
  930. def looping_background_call(
  931. self,
  932. f: Callable,
  933. msec: float,
  934. *args: object,
  935. desc: Optional[str] = None,
  936. run_on_all_instances: bool = False,
  937. **kwargs: object,
  938. ) -> None:
  939. """Wraps a function as a background process and calls it repeatedly.
  940. NOTE: Will only run on the instance that is configured to run
  941. background processes (which is the main process by default), unless
  942. `run_on_all_workers` is set.
  943. Waits `msec` initially before calling `f` for the first time.
  944. Added in Synapse v1.39.0.
  945. Args:
  946. f: The function to call repeatedly. f can be either synchronous or
  947. asynchronous, and must follow Synapse's logcontext rules.
  948. More info about logcontexts is available at
  949. https://matrix-org.github.io/synapse/latest/log_contexts.html
  950. msec: How long to wait between calls in milliseconds.
  951. *args: Positional arguments to pass to function.
  952. desc: The background task's description. Default to the function's name.
  953. run_on_all_instances: Whether to run this on all instances, rather
  954. than just the instance configured to run background tasks.
  955. **kwargs: Key arguments to pass to function.
  956. """
  957. if desc is None:
  958. desc = f.__name__
  959. if self._hs.config.worker.run_background_tasks or run_on_all_instances:
  960. self._clock.looping_call(
  961. run_as_background_process,
  962. msec,
  963. desc,
  964. lambda: maybe_awaitable(f(*args, **kwargs)),
  965. )
  966. else:
  967. logger.warning(
  968. "Not running looping call %s as the configuration forbids it",
  969. f,
  970. )
  971. async def sleep(self, seconds: float) -> None:
  972. """Sleeps for the given number of seconds."""
  973. await self._clock.sleep(seconds)
  974. async def send_mail(
  975. self,
  976. recipient: str,
  977. subject: str,
  978. html: str,
  979. text: str,
  980. ) -> None:
  981. """Send an email on behalf of the homeserver.
  982. Added in Synapse v1.39.0.
  983. Args:
  984. recipient: The email address for the recipient.
  985. subject: The email's subject.
  986. html: The email's HTML content.
  987. text: The email's text content.
  988. """
  989. await self._send_email_handler.send_email(
  990. email_address=recipient,
  991. subject=subject,
  992. app_name=self.email_app_name,
  993. html=html,
  994. text=text,
  995. )
  996. def read_templates(
  997. self,
  998. filenames: List[str],
  999. custom_template_directory: Optional[str] = None,
  1000. ) -> List[jinja2.Template]:
  1001. """Read and load the content of the template files at the given location.
  1002. By default, Synapse will look for these templates in its configured template
  1003. directory, but another directory to search in can be provided.
  1004. Added in Synapse v1.39.0.
  1005. Args:
  1006. filenames: The name of the template files to look for.
  1007. custom_template_directory: An additional directory to look for the files in.
  1008. Returns:
  1009. A list containing the loaded templates, with the orders matching the one of
  1010. the filenames parameter.
  1011. """
  1012. return self._hs.config.server.read_templates(
  1013. filenames,
  1014. (td for td in (self.custom_template_dir, custom_template_directory) if td),
  1015. )
  1016. def is_mine(self, id: Union[str, DomainSpecificString]) -> bool:
  1017. """
  1018. Checks whether an ID (user id, room, ...) comes from this homeserver.
  1019. Added in Synapse v1.44.0.
  1020. Args:
  1021. id: any Matrix id (e.g. user id, room id, ...), either as a raw id,
  1022. e.g. string "@user:example.com" or as a parsed UserID, RoomID, ...
  1023. Returns:
  1024. True if id comes from this homeserver, False otherwise.
  1025. """
  1026. if isinstance(id, DomainSpecificString):
  1027. return self._hs.is_mine(id)
  1028. else:
  1029. return self._hs.is_mine_id(id)
  1030. async def get_user_ip_and_agents(
  1031. self, user_id: str, since_ts: int = 0
  1032. ) -> List[UserIpAndAgent]:
  1033. """
  1034. Return the list of user IPs and agents for a user.
  1035. Added in Synapse v1.44.0.
  1036. Args:
  1037. user_id: the id of a user, local or remote
  1038. since_ts: a timestamp in seconds since the epoch,
  1039. or the epoch itself if not specified.
  1040. Returns:
  1041. The list of all UserIpAndAgent that the user has
  1042. used to connect to this homeserver since `since_ts`.
  1043. If the user is remote, this list is empty.
  1044. """
  1045. # Don't hit the db if this is not a local user.
  1046. is_mine = False
  1047. try:
  1048. # Let's be defensive against ill-formed strings.
  1049. if self.is_mine(user_id):
  1050. is_mine = True
  1051. except Exception:
  1052. pass
  1053. if is_mine:
  1054. raw_data = await self._store.get_user_ip_and_agents(
  1055. UserID.from_string(user_id), since_ts
  1056. )
  1057. # Sanitize some of the data. We don't want to return tokens.
  1058. return [
  1059. UserIpAndAgent(
  1060. ip=data["ip"],
  1061. user_agent=data["user_agent"],
  1062. last_seen=data["last_seen"],
  1063. )
  1064. for data in raw_data
  1065. ]
  1066. else:
  1067. return []
  1068. async def get_room_state(
  1069. self,
  1070. room_id: str,
  1071. event_filter: Optional[Iterable[Tuple[str, Optional[str]]]] = None,
  1072. ) -> StateMap[EventBase]:
  1073. """Returns the current state of the given room.
  1074. The events are returned as a mapping, in which the key for each event is a tuple
  1075. which first element is the event's type and the second one is its state key.
  1076. Added in Synapse v1.47.0
  1077. Args:
  1078. room_id: The ID of the room to get state from.
  1079. event_filter: A filter to apply when retrieving events. None if no filter
  1080. should be applied. If provided, must be an iterable of tuples. A tuple's
  1081. first element is the event type and the second is the state key, or is
  1082. None if the state key should not be filtered on.
  1083. An example of a filter is:
  1084. [
  1085. ("m.room.member", "@alice:example.com"), # Member event for @alice:example.com
  1086. ("org.matrix.some_event", ""), # State event of type "org.matrix.some_event"
  1087. # with an empty string as its state key
  1088. ("org.matrix.some_other_event", None), # State events of type "org.matrix.some_other_event"
  1089. # regardless of their state key
  1090. ]
  1091. """
  1092. if event_filter:
  1093. # If a filter was provided, turn it into a StateFilter and retrieve a filtered
  1094. # view of the state.
  1095. state_filter = StateFilter.from_types(event_filter)
  1096. state_ids = await self._store.get_filtered_current_state_ids(
  1097. room_id,
  1098. state_filter,
  1099. )
  1100. else:
  1101. # If no filter was provided, get the whole state. We could also reuse the call
  1102. # to get_filtered_current_state_ids above, with `state_filter = StateFilter.all()`,
  1103. # but get_filtered_current_state_ids isn't cached and `get_current_state_ids`
  1104. # is, so using the latter when we can is better for perf.
  1105. state_ids = await self._store.get_current_state_ids(room_id)
  1106. state_events = await self._store.get_events(state_ids.values())
  1107. return {key: state_events[event_id] for key, event_id in state_ids.items()}
  1108. async def defer_to_thread(
  1109. self,
  1110. f: Callable[P, T],
  1111. *args: P.args,
  1112. **kwargs: P.kwargs,
  1113. ) -> T:
  1114. """Runs the given function in a separate thread from Synapse's thread pool.
  1115. Added in Synapse v1.49.0.
  1116. Args:
  1117. f: The function to run.
  1118. args: The function's arguments.
  1119. kwargs: The function's keyword arguments.
  1120. Returns:
  1121. The return value of the function once ran in a thread.
  1122. """
  1123. return await defer_to_thread(self._hs.get_reactor(), f, *args, **kwargs)
  1124. async def check_username(self, username: str) -> None:
  1125. """Checks if the provided username uses the grammar defined in the Matrix
  1126. specification, and is already being used by an existing user.
  1127. Added in Synapse v1.52.0.
  1128. Args:
  1129. username: The username to check. This is the local part of the user's full
  1130. Matrix user ID, i.e. it's "alice" if the full user ID is "@alice:foo.com".
  1131. Raises:
  1132. SynapseError with the errcode "M_USER_IN_USE" if the username is already in
  1133. use.
  1134. """
  1135. await self._registration_handler.check_username(username)
  1136. async def store_remote_3pid_association(
  1137. self, user_id: str, medium: str, address: str, id_server: str
  1138. ) -> None:
  1139. """Stores an existing association between a user ID and a third-party identifier.
  1140. The association must already exist on the remote identity server.
  1141. Added in Synapse v1.56.0.
  1142. Args:
  1143. user_id: The user ID that's been associated with the 3PID.
  1144. medium: The medium of the 3PID (current supported values are "msisdn" and
  1145. "email").
  1146. address: The address of the 3PID.
  1147. id_server: The identity server the 3PID association has been registered on.
  1148. This should only be the domain (or IP address, optionally with the port
  1149. number) for the identity server. This will be used to reach out to the
  1150. identity server using HTTPS (unless specified otherwise by Synapse's
  1151. configuration) when attempting to unbind the third-party identifier.
  1152. """
  1153. await self._store.add_user_bound_threepid(user_id, medium, address, id_server)
  1154. def check_push_rule_actions(
  1155. self, actions: List[Union[str, Dict[str, str]]]
  1156. ) -> None:
  1157. """Checks if the given push rule actions are valid according to the Matrix
  1158. specification.
  1159. See https://spec.matrix.org/v1.2/client-server-api/#actions for the list of valid
  1160. actions.
  1161. Added in Synapse v1.58.0.
  1162. Args:
  1163. actions: the actions to check.
  1164. Raises:
  1165. synapse.module_api.errors.InvalidRuleException if the actions are invalid.
  1166. """
  1167. check_actions(actions)
  1168. async def set_push_rule_action(
  1169. self,
  1170. user_id: str,
  1171. scope: str,
  1172. kind: str,
  1173. rule_id: str,
  1174. actions: List[Union[str, Dict[str, str]]],
  1175. ) -> None:
  1176. """Changes the actions of an existing push rule for the given user.
  1177. See https://spec.matrix.org/v1.2/client-server-api/#push-rules for more
  1178. information about push rules and their syntax.
  1179. Can only be called on the main process.
  1180. Added in Synapse v1.58.0.
  1181. Args:
  1182. user_id: the user for which to change the push rule's actions.
  1183. scope: the push rule's scope, currently only "global" is allowed.
  1184. kind: the push rule's kind.
  1185. rule_id: the push rule's identifier.
  1186. actions: the actions to run when the rule's conditions match.
  1187. Raises:
  1188. RuntimeError if this method is called on a worker or `scope` is invalid.
  1189. synapse.module_api.errors.RuleNotFoundException if the rule being modified
  1190. can't be found.
  1191. synapse.module_api.errors.InvalidRuleException if the actions are invalid.
  1192. """
  1193. if self.worker_app is not None:
  1194. raise RuntimeError("module tried to change push rule actions on a worker")
  1195. if scope != "global":
  1196. raise RuntimeError(
  1197. "invalid scope %s, only 'global' is currently allowed" % scope
  1198. )
  1199. spec = RuleSpec(scope, kind, rule_id, "actions")
  1200. await self._push_rules_handler.set_rule_attr(
  1201. user_id, spec, {"actions": actions}
  1202. )
  1203. class PublicRoomListManager:
  1204. """Contains methods for adding to, removing from and querying whether a room
  1205. is in the public room list.
  1206. """
  1207. def __init__(self, hs: "HomeServer"):
  1208. self._store = hs.get_datastores().main
  1209. async def room_is_in_public_room_list(self, room_id: str) -> bool:
  1210. """Checks whether a room is in the public room list.
  1211. Added in Synapse v1.22.0.
  1212. Args:
  1213. room_id: The ID of the room.
  1214. Returns:
  1215. Whether the room is in the public room list. Returns False if the room does
  1216. not exist.
  1217. """
  1218. room = await self._store.get_room(room_id)
  1219. if not room:
  1220. return False
  1221. return room.get("is_public", False)
  1222. async def add_room_to_public_room_list(self, room_id: str) -> None:
  1223. """Publishes a room to the public room list.
  1224. Added in Synapse v1.22.0.
  1225. Args:
  1226. room_id: The ID of the room.
  1227. """
  1228. await self._store.set_room_is_public(room_id, True)
  1229. async def remove_room_from_public_room_list(self, room_id: str) -> None:
  1230. """Removes a room from the public room list.
  1231. Added in Synapse v1.22.0.
  1232. Args:
  1233. room_id: The ID of the room.
  1234. """
  1235. await self._store.set_room_is_public(room_id, False)
  1236. class AccountDataManager:
  1237. """
  1238. Allows modules to manage account data.
  1239. """
  1240. def __init__(self, hs: "HomeServer") -> None:
  1241. self._hs = hs
  1242. self._store = hs.get_datastores().main
  1243. self._handler = hs.get_account_data_handler()
  1244. def _validate_user_id(self, user_id: str) -> None:
  1245. """
  1246. Validates a user ID is valid and local.
  1247. Private method to be used in other account data methods.
  1248. """
  1249. user = UserID.from_string(user_id)
  1250. if not self._hs.is_mine(user):
  1251. raise ValueError(
  1252. f"{user_id} is not local to this homeserver; can't access account data for remote users."
  1253. )
  1254. async def get_global(self, user_id: str, data_type: str) -> Optional[JsonMapping]:
  1255. """
  1256. Gets some global account data, of a specified type, for the specified user.
  1257. The provided user ID must be a valid user ID of a local user.
  1258. Added in Synapse v1.57.0.
  1259. """
  1260. self._validate_user_id(user_id)
  1261. data = await self._store.get_global_account_data_by_type_for_user(
  1262. user_id, data_type
  1263. )
  1264. # We clone and freeze to prevent the module accidentally mutating the
  1265. # dict that lives in the cache, as that could introduce nasty bugs.
  1266. return freeze(data)
  1267. async def put_global(
  1268. self, user_id: str, data_type: str, new_data: JsonDict
  1269. ) -> None:
  1270. """
  1271. Puts some global account data, of a specified type, for the specified user.
  1272. The provided user ID must be a valid user ID of a local user.
  1273. Please note that this will overwrite existing the account data of that type
  1274. for that user!
  1275. Added in Synapse v1.57.0.
  1276. """
  1277. self._validate_user_id(user_id)
  1278. if not isinstance(data_type, str):
  1279. raise TypeError(f"data_type must be a str; got {type(data_type).__name__}")
  1280. if not isinstance(new_data, dict):
  1281. raise TypeError(f"new_data must be a dict; got {type(new_data).__name__}")
  1282. # Ensure the user exists, so we don't just write to users that aren't there.
  1283. if await self._store.get_userinfo_by_id(user_id) is None:
  1284. raise ValueError(f"User {user_id} does not exist on this server.")
  1285. await self._handler.add_account_data_for_user(user_id, data_type, new_data)