You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

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