__init__.py 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833
  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. Union,
  28. )
  29. import attr
  30. import jinja2
  31. from twisted.internet import defer
  32. from twisted.web.resource import IResource
  33. from synapse.events import EventBase
  34. from synapse.events.presence_router import PresenceRouter
  35. from synapse.http.client import SimpleHttpClient
  36. from synapse.http.server import (
  37. DirectServeHtmlResource,
  38. DirectServeJsonResource,
  39. respond_with_html,
  40. )
  41. from synapse.http.servlet import parse_json_object_from_request
  42. from synapse.http.site import SynapseRequest
  43. from synapse.logging.context import make_deferred_yieldable, run_in_background
  44. from synapse.metrics.background_process_metrics import run_as_background_process
  45. from synapse.rest.client.login import LoginResponse
  46. from synapse.storage.database import DatabasePool, LoggingTransaction
  47. from synapse.storage.databases.main.roommember import ProfileInfo
  48. from synapse.storage.state import StateFilter
  49. from synapse.types import (
  50. DomainSpecificString,
  51. JsonDict,
  52. Requester,
  53. UserID,
  54. UserInfo,
  55. create_requester,
  56. )
  57. from synapse.util import Clock
  58. from synapse.util.caches.descriptors import cached
  59. if TYPE_CHECKING:
  60. from synapse.server import HomeServer
  61. """
  62. This package defines the 'stable' API which can be used by extension modules which
  63. are loaded into Synapse.
  64. """
  65. PRESENCE_ALL_USERS = PresenceRouter.ALL_USERS
  66. __all__ = [
  67. "errors",
  68. "make_deferred_yieldable",
  69. "parse_json_object_from_request",
  70. "respond_with_html",
  71. "run_in_background",
  72. "cached",
  73. "UserID",
  74. "DatabasePool",
  75. "LoggingTransaction",
  76. "DirectServeHtmlResource",
  77. "DirectServeJsonResource",
  78. "ModuleApi",
  79. "PRESENCE_ALL_USERS",
  80. "LoginResponse",
  81. "JsonDict",
  82. ]
  83. logger = logging.getLogger(__name__)
  84. @attr.s(auto_attribs=True)
  85. class UserIpAndAgent:
  86. """
  87. An IP address and user agent used by a user to connect to this homeserver.
  88. """
  89. ip: str
  90. user_agent: str
  91. # The time at which this user agent/ip was last seen.
  92. last_seen: int
  93. class ModuleApi:
  94. """A proxy object that gets passed to various plugin modules so they
  95. can register new users etc if necessary.
  96. """
  97. def __init__(self, hs: "HomeServer", auth_handler):
  98. self._hs = hs
  99. self._store = hs.get_datastore()
  100. self._auth = hs.get_auth()
  101. self._auth_handler = auth_handler
  102. self._server_name = hs.hostname
  103. self._presence_stream = hs.get_event_sources().sources.presence
  104. self._state = hs.get_state_handler()
  105. self._clock: Clock = hs.get_clock()
  106. self._send_email_handler = hs.get_send_email_handler()
  107. self.custom_template_dir = hs.config.server.custom_template_directory
  108. try:
  109. app_name = self._hs.config.email.email_app_name
  110. self._from_string = self._hs.config.email.email_notif_from % {
  111. "app": app_name
  112. }
  113. except (KeyError, TypeError):
  114. # If substitution failed (which can happen if the string contains
  115. # placeholders other than just "app", or if the type of the placeholder is
  116. # not a string), fall back to the bare strings.
  117. self._from_string = self._hs.config.email.email_notif_from
  118. self._raw_from = email.utils.parseaddr(self._from_string)[1]
  119. # We expose these as properties below in order to attach a helpful docstring.
  120. self._http_client: SimpleHttpClient = hs.get_simple_http_client()
  121. self._public_room_list_manager = PublicRoomListManager(hs)
  122. self._spam_checker = hs.get_spam_checker()
  123. self._account_validity_handler = hs.get_account_validity_handler()
  124. self._third_party_event_rules = hs.get_third_party_event_rules()
  125. self._password_auth_provider = hs.get_password_auth_provider()
  126. self._presence_router = hs.get_presence_router()
  127. #################################################################################
  128. # The following methods should only be called during the module's initialisation.
  129. @property
  130. def register_spam_checker_callbacks(self):
  131. """Registers callbacks for spam checking capabilities."""
  132. return self._spam_checker.register_callbacks
  133. @property
  134. def register_account_validity_callbacks(self):
  135. """Registers callbacks for account validity capabilities."""
  136. return self._account_validity_handler.register_account_validity_callbacks
  137. @property
  138. def register_third_party_rules_callbacks(self):
  139. """Registers callbacks for third party event rules capabilities."""
  140. return self._third_party_event_rules.register_third_party_rules_callbacks
  141. @property
  142. def register_presence_router_callbacks(self):
  143. """Registers callbacks for presence router capabilities."""
  144. return self._presence_router.register_presence_router_callbacks
  145. @property
  146. def register_password_auth_provider_callbacks(self):
  147. """Registers callbacks for password auth provider capabilities."""
  148. return self._password_auth_provider.register_password_auth_provider_callbacks
  149. def register_web_resource(self, path: str, resource: IResource):
  150. """Registers a web resource to be served at the given path.
  151. This function should be called during initialisation of the module.
  152. If multiple modules register a resource for the same path, the module that
  153. appears the highest in the configuration file takes priority.
  154. Args:
  155. path: The path to register the resource for.
  156. resource: The resource to attach to this path.
  157. """
  158. self._hs.register_module_web_resource(path, resource)
  159. #########################################################################
  160. # The following methods can be called by the module at any point in time.
  161. @property
  162. def http_client(self):
  163. """Allows making outbound HTTP requests to remote resources.
  164. An instance of synapse.http.client.SimpleHttpClient
  165. """
  166. return self._http_client
  167. @property
  168. def public_room_list_manager(self):
  169. """Allows adding to, removing from and checking the status of rooms in the
  170. public room list.
  171. An instance of synapse.module_api.PublicRoomListManager
  172. """
  173. return self._public_room_list_manager
  174. @property
  175. def public_baseurl(self) -> str:
  176. """The configured public base URL for this homeserver."""
  177. return self._hs.config.server.public_baseurl
  178. @property
  179. def email_app_name(self) -> str:
  180. """The application name configured in the homeserver's configuration."""
  181. return self._hs.config.email.email_app_name
  182. async def get_userinfo_by_id(self, user_id: str) -> Optional[UserInfo]:
  183. """Get user info by user_id
  184. Args:
  185. user_id: Fully qualified user id.
  186. Returns:
  187. UserInfo object if a user was found, otherwise None
  188. """
  189. return await self._store.get_userinfo_by_id(user_id)
  190. async def get_user_by_req(
  191. self,
  192. req: SynapseRequest,
  193. allow_guest: bool = False,
  194. allow_expired: bool = False,
  195. ) -> Requester:
  196. """Check the access_token provided for a request
  197. Args:
  198. req: Incoming HTTP request
  199. allow_guest: True if guest users should be allowed. If this
  200. is False, and the access token is for a guest user, an
  201. AuthError will be thrown
  202. allow_expired: True if expired users should be allowed. If this
  203. is False, and the access token is for an expired user, an
  204. AuthError will be thrown
  205. Returns:
  206. The requester for this request
  207. Raises:
  208. InvalidClientCredentialsError: if no user by that token exists,
  209. or the token is invalid.
  210. """
  211. return await self._auth.get_user_by_req(
  212. req,
  213. allow_guest,
  214. allow_expired=allow_expired,
  215. )
  216. async def is_user_admin(self, user_id: str) -> bool:
  217. """Checks if a user is a server admin.
  218. Args:
  219. user_id: The Matrix ID of the user to check.
  220. Returns:
  221. True if the user is a server admin, False otherwise.
  222. """
  223. return await self._store.is_server_admin(UserID.from_string(user_id))
  224. def get_qualified_user_id(self, username):
  225. """Qualify a user id, if necessary
  226. Takes a user id provided by the user and adds the @ and :domain to
  227. qualify it, if necessary
  228. Args:
  229. username (str): provided user id
  230. Returns:
  231. str: qualified @user:id
  232. """
  233. if username.startswith("@"):
  234. return username
  235. return UserID(username, self._hs.hostname).to_string()
  236. async def get_profile_for_user(self, localpart: str) -> ProfileInfo:
  237. """Look up the profile info for the user with the given localpart.
  238. Args:
  239. localpart: The localpart to look up profile information for.
  240. Returns:
  241. The profile information (i.e. display name and avatar URL).
  242. """
  243. return await self._store.get_profileinfo(localpart)
  244. async def get_threepids_for_user(self, user_id: str) -> List[Dict[str, str]]:
  245. """Look up the threepids (email addresses and phone numbers) associated with the
  246. given Matrix user ID.
  247. Args:
  248. user_id: The Matrix user ID to look up threepids for.
  249. Returns:
  250. A list of threepids, each threepid being represented by a dictionary
  251. containing a "medium" key which value is "email" for email addresses and
  252. "msisdn" for phone numbers, and an "address" key which value is the
  253. threepid's address.
  254. """
  255. return await self._store.user_get_threepids(user_id)
  256. def check_user_exists(self, user_id):
  257. """Check if user exists.
  258. Args:
  259. user_id (str): Complete @user:id
  260. Returns:
  261. Deferred[str|None]: Canonical (case-corrected) user_id, or None
  262. if the user is not registered.
  263. """
  264. return defer.ensureDeferred(self._auth_handler.check_user_exists(user_id))
  265. @defer.inlineCallbacks
  266. def register(self, localpart, displayname=None, emails: Optional[List[str]] = None):
  267. """Registers a new user with given localpart and optional displayname, emails.
  268. Also returns an access token for the new user.
  269. Deprecated: avoid this, as it generates a new device with no way to
  270. return that device to the user. Prefer separate calls to register_user and
  271. register_device.
  272. Args:
  273. localpart (str): The localpart of the new user.
  274. displayname (str|None): The displayname of the new user.
  275. emails (List[str]): Emails to bind to the new user.
  276. Returns:
  277. Deferred[tuple[str, str]]: a 2-tuple of (user_id, access_token)
  278. """
  279. logger.warning(
  280. "Using deprecated ModuleApi.register which creates a dummy user device."
  281. )
  282. user_id = yield self.register_user(localpart, displayname, emails or [])
  283. _, access_token, _, _ = yield self.register_device(user_id)
  284. return user_id, access_token
  285. def register_user(
  286. self, localpart, displayname=None, emails: Optional[List[str]] = None
  287. ):
  288. """Registers a new user with given localpart and optional displayname, emails.
  289. Args:
  290. localpart (str): The localpart of the new user.
  291. displayname (str|None): The displayname of the new user.
  292. emails (List[str]): Emails to bind to the new user.
  293. Raises:
  294. SynapseError if there is an error performing the registration. Check the
  295. 'errcode' property for more information on the reason for failure
  296. Returns:
  297. defer.Deferred[str]: user_id
  298. """
  299. return defer.ensureDeferred(
  300. self._hs.get_registration_handler().register_user(
  301. localpart=localpart,
  302. default_display_name=displayname,
  303. bind_emails=emails or [],
  304. )
  305. )
  306. def register_device(self, user_id, device_id=None, initial_display_name=None):
  307. """Register a device for a user and generate an access token.
  308. Args:
  309. user_id (str): full canonical @user:id
  310. device_id (str|None): The device ID to check, or None to generate
  311. a new one.
  312. initial_display_name (str|None): An optional display name for the
  313. device.
  314. Returns:
  315. defer.Deferred[tuple[str, str]]: Tuple of device ID and access token
  316. """
  317. return defer.ensureDeferred(
  318. self._hs.get_registration_handler().register_device(
  319. user_id=user_id,
  320. device_id=device_id,
  321. initial_display_name=initial_display_name,
  322. )
  323. )
  324. def record_user_external_id(
  325. self, auth_provider_id: str, remote_user_id: str, registered_user_id: str
  326. ) -> defer.Deferred:
  327. """Record a mapping from an external user id to a mxid
  328. Args:
  329. auth_provider: identifier for the remote auth provider
  330. external_id: id on that system
  331. user_id: complete mxid that it is mapped to
  332. """
  333. return defer.ensureDeferred(
  334. self._store.record_user_external_id(
  335. auth_provider_id, remote_user_id, registered_user_id
  336. )
  337. )
  338. def generate_short_term_login_token(
  339. self,
  340. user_id: str,
  341. duration_in_ms: int = (2 * 60 * 1000),
  342. auth_provider_id: str = "",
  343. ) -> str:
  344. """Generate a login token suitable for m.login.token authentication
  345. Args:
  346. user_id: gives the ID of the user that the token is for
  347. duration_in_ms: the time that the token will be valid for
  348. auth_provider_id: the ID of the SSO IdP that the user used to authenticate
  349. to get this token, if any. This is encoded in the token so that
  350. /login can report stats on number of successful logins by IdP.
  351. """
  352. return self._hs.get_macaroon_generator().generate_short_term_login_token(
  353. user_id,
  354. auth_provider_id,
  355. duration_in_ms,
  356. )
  357. @defer.inlineCallbacks
  358. def invalidate_access_token(self, access_token):
  359. """Invalidate an access token for a user
  360. Args:
  361. access_token(str): access token
  362. Returns:
  363. twisted.internet.defer.Deferred - resolves once the access token
  364. has been removed.
  365. Raises:
  366. synapse.api.errors.AuthError: the access token is invalid
  367. """
  368. # see if the access token corresponds to a device
  369. user_info = yield defer.ensureDeferred(
  370. self._auth.get_user_by_access_token(access_token)
  371. )
  372. device_id = user_info.get("device_id")
  373. user_id = user_info["user"].to_string()
  374. if device_id:
  375. # delete the device, which will also delete its access tokens
  376. yield defer.ensureDeferred(
  377. self._hs.get_device_handler().delete_device(user_id, device_id)
  378. )
  379. else:
  380. # no associated device. Just delete the access token.
  381. yield defer.ensureDeferred(
  382. self._auth_handler.delete_access_token(access_token)
  383. )
  384. def run_db_interaction(self, desc, func, *args, **kwargs):
  385. """Run a function with a database connection
  386. Args:
  387. desc (str): description for the transaction, for metrics etc
  388. func (func): function to be run. Passed a database cursor object
  389. as well as *args and **kwargs
  390. *args: positional args to be passed to func
  391. **kwargs: named args to be passed to func
  392. Returns:
  393. Deferred[object]: result of func
  394. """
  395. return defer.ensureDeferred(
  396. self._store.db_pool.runInteraction(desc, func, *args, **kwargs)
  397. )
  398. def complete_sso_login(
  399. self, registered_user_id: str, request: SynapseRequest, client_redirect_url: str
  400. ):
  401. """Complete a SSO login by redirecting the user to a page to confirm whether they
  402. want their access token sent to `client_redirect_url`, or redirect them to that
  403. URL with a token directly if the URL matches with one of the whitelisted clients.
  404. This is deprecated in favor of complete_sso_login_async.
  405. Args:
  406. registered_user_id: The MXID that has been registered as a previous step of
  407. of this SSO login.
  408. request: The request to respond to.
  409. client_redirect_url: The URL to which to offer to redirect the user (or to
  410. redirect them directly if whitelisted).
  411. """
  412. self._auth_handler._complete_sso_login(
  413. registered_user_id,
  414. "<unknown>",
  415. request,
  416. client_redirect_url,
  417. )
  418. async def complete_sso_login_async(
  419. self,
  420. registered_user_id: str,
  421. request: SynapseRequest,
  422. client_redirect_url: str,
  423. new_user: bool = False,
  424. auth_provider_id: str = "<unknown>",
  425. ):
  426. """Complete a SSO login by redirecting the user to a page to confirm whether they
  427. want their access token sent to `client_redirect_url`, or redirect them to that
  428. URL with a token directly if the URL matches with one of the whitelisted clients.
  429. Args:
  430. registered_user_id: The MXID that has been registered as a previous step of
  431. of this SSO login.
  432. request: The request to respond to.
  433. client_redirect_url: The URL to which to offer to redirect the user (or to
  434. redirect them directly if whitelisted).
  435. new_user: set to true to use wording for the consent appropriate to a user
  436. who has just registered.
  437. auth_provider_id: the ID of the SSO IdP which was used to log in. This
  438. is used to track counts of sucessful logins by IdP.
  439. """
  440. await self._auth_handler.complete_sso_login(
  441. registered_user_id,
  442. auth_provider_id,
  443. request,
  444. client_redirect_url,
  445. new_user=new_user,
  446. )
  447. @defer.inlineCallbacks
  448. def get_state_events_in_room(
  449. self, room_id: str, types: Iterable[Tuple[str, Optional[str]]]
  450. ) -> Generator[defer.Deferred, Any, Iterable[EventBase]]:
  451. """Gets current state events for the given room.
  452. (This is exposed for compatibility with the old SpamCheckerApi. We should
  453. probably deprecate it and replace it with an async method in a subclass.)
  454. Args:
  455. room_id: The room ID to get state events in.
  456. types: The event type and state key (using None
  457. to represent 'any') of the room state to acquire.
  458. Returns:
  459. twisted.internet.defer.Deferred[list(synapse.events.FrozenEvent)]:
  460. The filtered state events in the room.
  461. """
  462. state_ids = yield defer.ensureDeferred(
  463. self._store.get_filtered_current_state_ids(
  464. room_id=room_id, state_filter=StateFilter.from_types(types)
  465. )
  466. )
  467. state = yield defer.ensureDeferred(self._store.get_events(state_ids.values()))
  468. return state.values()
  469. async def create_and_send_event_into_room(self, event_dict: JsonDict) -> EventBase:
  470. """Create and send an event into a room. Membership events are currently not supported.
  471. Args:
  472. event_dict: A dictionary representing the event to send.
  473. Required keys are `type`, `room_id`, `sender` and `content`.
  474. Returns:
  475. The event that was sent. If state event deduplication happened, then
  476. the previous, duplicate event instead.
  477. Raises:
  478. SynapseError if the event was not allowed.
  479. """
  480. # Create a requester object
  481. requester = create_requester(
  482. event_dict["sender"], authenticated_entity=self._server_name
  483. )
  484. # Create and send the event
  485. (
  486. event,
  487. _,
  488. ) = await self._hs.get_event_creation_handler().create_and_send_nonmember_event(
  489. requester,
  490. event_dict,
  491. ratelimit=False,
  492. ignore_shadow_ban=True,
  493. )
  494. return event
  495. async def send_local_online_presence_to(self, users: Iterable[str]) -> None:
  496. """
  497. Forces the equivalent of a presence initial_sync for a set of local or remote
  498. users. The users will receive presence for all currently online users that they
  499. are considered interested in.
  500. Updates to remote users will be sent immediately, whereas local users will receive
  501. them on their next sync attempt.
  502. Note that this method can only be run on the process that is configured to write to the
  503. presence stream. By default this is the main process.
  504. """
  505. if self._hs._instance_name not in self._hs.config.worker.writers.presence:
  506. raise Exception(
  507. "send_local_online_presence_to can only be run "
  508. "on the process that is configured to write to the "
  509. "presence stream (by default this is the main process)",
  510. )
  511. local_users = set()
  512. remote_users = set()
  513. for user in users:
  514. if self._hs.is_mine_id(user):
  515. local_users.add(user)
  516. else:
  517. remote_users.add(user)
  518. # We pull out the presence handler here to break a cyclic
  519. # dependency between the presence router and module API.
  520. presence_handler = self._hs.get_presence_handler()
  521. if local_users:
  522. # Force a presence initial_sync for these users next time they sync.
  523. await presence_handler.send_full_presence_to_users(local_users)
  524. for user in remote_users:
  525. # Retrieve presence state for currently online users that this user
  526. # is considered interested in.
  527. presence_events, _ = await self._presence_stream.get_new_events(
  528. UserID.from_string(user), from_key=None, include_offline=False
  529. )
  530. # Send to remote destinations.
  531. destination = UserID.from_string(user).domain
  532. presence_handler.get_federation_queue().send_presence_to_destinations(
  533. presence_events, destination
  534. )
  535. def looping_background_call(
  536. self,
  537. f: Callable,
  538. msec: float,
  539. *args,
  540. desc: Optional[str] = None,
  541. run_on_all_instances: bool = False,
  542. **kwargs,
  543. ):
  544. """Wraps a function as a background process and calls it repeatedly.
  545. NOTE: Will only run on the instance that is configured to run
  546. background processes (which is the main process by default), unless
  547. `run_on_all_workers` is set.
  548. Waits `msec` initially before calling `f` for the first time.
  549. Args:
  550. f: The function to call repeatedly. f can be either synchronous or
  551. asynchronous, and must follow Synapse's logcontext rules.
  552. More info about logcontexts is available at
  553. https://matrix-org.github.io/synapse/latest/log_contexts.html
  554. msec: How long to wait between calls in milliseconds.
  555. *args: Positional arguments to pass to function.
  556. desc: The background task's description. Default to the function's name.
  557. run_on_all_instances: Whether to run this on all instances, rather
  558. than just the instance configured to run background tasks.
  559. **kwargs: Key arguments to pass to function.
  560. """
  561. if desc is None:
  562. desc = f.__name__
  563. if self._hs.config.worker.run_background_tasks or run_on_all_instances:
  564. self._clock.looping_call(
  565. run_as_background_process,
  566. msec,
  567. desc,
  568. f,
  569. *args,
  570. **kwargs,
  571. )
  572. else:
  573. logger.warning(
  574. "Not running looping call %s as the configuration forbids it",
  575. f,
  576. )
  577. async def send_mail(
  578. self,
  579. recipient: str,
  580. subject: str,
  581. html: str,
  582. text: str,
  583. ):
  584. """Send an email on behalf of the homeserver.
  585. Args:
  586. recipient: The email address for the recipient.
  587. subject: The email's subject.
  588. html: The email's HTML content.
  589. text: The email's text content.
  590. """
  591. await self._send_email_handler.send_email(
  592. email_address=recipient,
  593. subject=subject,
  594. app_name=self.email_app_name,
  595. html=html,
  596. text=text,
  597. )
  598. def read_templates(
  599. self,
  600. filenames: List[str],
  601. custom_template_directory: Optional[str] = None,
  602. ) -> List[jinja2.Template]:
  603. """Read and load the content of the template files at the given location.
  604. By default, Synapse will look for these templates in its configured template
  605. directory, but another directory to search in can be provided.
  606. Args:
  607. filenames: The name of the template files to look for.
  608. custom_template_directory: An additional directory to look for the files in.
  609. Returns:
  610. A list containing the loaded templates, with the orders matching the one of
  611. the filenames parameter.
  612. """
  613. return self._hs.config.read_templates(
  614. filenames,
  615. (td for td in (self.custom_template_dir, custom_template_directory) if td),
  616. )
  617. def is_mine(self, id: Union[str, DomainSpecificString]) -> bool:
  618. """
  619. Checks whether an ID (user id, room, ...) comes from this homeserver.
  620. Args:
  621. id: any Matrix id (e.g. user id, room id, ...), either as a raw id,
  622. e.g. string "@user:example.com" or as a parsed UserID, RoomID, ...
  623. Returns:
  624. True if id comes from this homeserver, False otherwise.
  625. Added in Synapse v1.44.0.
  626. """
  627. if isinstance(id, DomainSpecificString):
  628. return self._hs.is_mine(id)
  629. else:
  630. return self._hs.is_mine_id(id)
  631. async def get_user_ip_and_agents(
  632. self, user_id: str, since_ts: int = 0
  633. ) -> List[UserIpAndAgent]:
  634. """
  635. Return the list of user IPs and agents for a user.
  636. Args:
  637. user_id: the id of a user, local or remote
  638. since_ts: a timestamp in seconds since the epoch,
  639. or the epoch itself if not specified.
  640. Returns:
  641. The list of all UserIpAndAgent that the user has
  642. used to connect to this homeserver since `since_ts`.
  643. If the user is remote, this list is empty.
  644. Added in Synapse v1.44.0.
  645. """
  646. # Don't hit the db if this is not a local user.
  647. is_mine = False
  648. try:
  649. # Let's be defensive against ill-formed strings.
  650. if self.is_mine(user_id):
  651. is_mine = True
  652. except Exception:
  653. pass
  654. if is_mine:
  655. raw_data = await self._store.get_user_ip_and_agents(
  656. UserID.from_string(user_id), since_ts
  657. )
  658. # Sanitize some of the data. We don't want to return tokens.
  659. return [
  660. UserIpAndAgent(
  661. ip=data["ip"],
  662. user_agent=data["user_agent"],
  663. last_seen=data["last_seen"],
  664. )
  665. for data in raw_data
  666. ]
  667. else:
  668. return []
  669. class PublicRoomListManager:
  670. """Contains methods for adding to, removing from and querying whether a room
  671. is in the public room list.
  672. """
  673. def __init__(self, hs: "HomeServer"):
  674. self._store = hs.get_datastore()
  675. async def room_is_in_public_room_list(self, room_id: str) -> bool:
  676. """Checks whether a room is in the public room list.
  677. Args:
  678. room_id: The ID of the room.
  679. Returns:
  680. Whether the room is in the public room list. Returns False if the room does
  681. not exist.
  682. """
  683. room = await self._store.get_room(room_id)
  684. if not room:
  685. return False
  686. return room.get("is_public", False)
  687. async def add_room_to_public_room_list(self, room_id: str) -> None:
  688. """Publishes a room to the public room list.
  689. Args:
  690. room_id: The ID of the room.
  691. """
  692. await self._store.set_room_is_public(room_id, True)
  693. async def remove_room_from_public_room_list(self, room_id: str) -> None:
  694. """Removes a room from the public room list.
  695. Args:
  696. room_id: The ID of the room.
  697. """
  698. await self._store.set_room_is_public(room_id, False)