appservice.py 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830
  1. # Copyright 2015, 2016 OpenMarket Ltd
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. import logging
  15. from typing import TYPE_CHECKING, Collection, Dict, Iterable, List, Optional, Union
  16. from prometheus_client import Counter
  17. from twisted.internet import defer
  18. import synapse
  19. from synapse.api.constants import EventTypes
  20. from synapse.appservice import ApplicationService
  21. from synapse.events import EventBase
  22. from synapse.handlers.presence import format_user_presence_state
  23. from synapse.logging.context import make_deferred_yieldable, run_in_background
  24. from synapse.metrics import (
  25. event_processing_loop_counter,
  26. event_processing_loop_room_count,
  27. )
  28. from synapse.metrics.background_process_metrics import (
  29. run_as_background_process,
  30. wrap_as_background_process,
  31. )
  32. from synapse.storage.databases.main.directory import RoomAliasMapping
  33. from synapse.types import (
  34. DeviceListUpdates,
  35. JsonDict,
  36. RoomAlias,
  37. RoomStreamToken,
  38. StreamKeyType,
  39. UserID,
  40. )
  41. from synapse.util.async_helpers import Linearizer
  42. from synapse.util.metrics import Measure
  43. if TYPE_CHECKING:
  44. from synapse.server import HomeServer
  45. logger = logging.getLogger(__name__)
  46. events_processed_counter = Counter("synapse_handlers_appservice_events_processed", "")
  47. class ApplicationServicesHandler:
  48. def __init__(self, hs: "HomeServer"):
  49. self.store = hs.get_datastores().main
  50. self.is_mine_id = hs.is_mine_id
  51. self.appservice_api = hs.get_application_service_api()
  52. self.scheduler = hs.get_application_service_scheduler()
  53. self.started_scheduler = False
  54. self.clock = hs.get_clock()
  55. self.notify_appservices = hs.config.worker.should_notify_appservices
  56. self.event_sources = hs.get_event_sources()
  57. self._msc2409_to_device_messages_enabled = (
  58. hs.config.experimental.msc2409_to_device_messages_enabled
  59. )
  60. self._msc3202_transaction_extensions_enabled = (
  61. hs.config.experimental.msc3202_transaction_extensions
  62. )
  63. self.current_max = 0
  64. self.is_processing = False
  65. self._ephemeral_events_linearizer = Linearizer(
  66. name="appservice_ephemeral_events"
  67. )
  68. def notify_interested_services(self, max_token: RoomStreamToken) -> None:
  69. """Notifies (pushes) all application services interested in this event.
  70. Pushing is done asynchronously, so this method won't block for any
  71. prolonged length of time.
  72. """
  73. # We just use the minimum stream ordering and ignore the vector clock
  74. # component. This is safe to do as long as we *always* ignore the vector
  75. # clock components.
  76. current_id = max_token.stream
  77. services = self.store.get_app_services()
  78. if not services or not self.notify_appservices:
  79. return
  80. self.current_max = max(self.current_max, current_id)
  81. if self.is_processing:
  82. return
  83. # We only start a new background process if necessary rather than
  84. # optimistically (to cut down on overhead).
  85. self._notify_interested_services(max_token)
  86. @wrap_as_background_process("notify_interested_services")
  87. async def _notify_interested_services(self, max_token: RoomStreamToken) -> None:
  88. with Measure(self.clock, "notify_interested_services"):
  89. self.is_processing = True
  90. try:
  91. limit = 100
  92. upper_bound = -1
  93. while upper_bound < self.current_max:
  94. (
  95. upper_bound,
  96. events,
  97. ) = await self.store.get_new_events_for_appservice(
  98. self.current_max, limit
  99. )
  100. events_by_room: Dict[str, List[EventBase]] = {}
  101. for event in events:
  102. events_by_room.setdefault(event.room_id, []).append(event)
  103. async def handle_event(event: EventBase) -> None:
  104. # Gather interested services
  105. services = await self._get_services_for_event(event)
  106. if len(services) == 0:
  107. return # no services need notifying
  108. # Do we know this user exists? If not, poke the user
  109. # query API for all services which match that user regex.
  110. # This needs to block as these user queries need to be
  111. # made BEFORE pushing the event.
  112. await self._check_user_exists(event.sender)
  113. if event.type == EventTypes.Member:
  114. await self._check_user_exists(event.state_key)
  115. if not self.started_scheduler:
  116. async def start_scheduler() -> None:
  117. try:
  118. await self.scheduler.start()
  119. except Exception:
  120. logger.error("Application Services Failure")
  121. run_as_background_process("as_scheduler", start_scheduler)
  122. self.started_scheduler = True
  123. # Fork off pushes to these services
  124. for service in services:
  125. self.scheduler.enqueue_for_appservice(
  126. service, events=[event]
  127. )
  128. now = self.clock.time_msec()
  129. ts = await self.store.get_received_ts(event.event_id)
  130. assert ts is not None
  131. synapse.metrics.event_processing_lag_by_event.labels(
  132. "appservice_sender"
  133. ).observe((now - ts) / 1000)
  134. async def handle_room_events(events: Iterable[EventBase]) -> None:
  135. for event in events:
  136. await handle_event(event)
  137. await make_deferred_yieldable(
  138. defer.gatherResults(
  139. [
  140. run_in_background(handle_room_events, evs)
  141. for evs in events_by_room.values()
  142. ],
  143. consumeErrors=True,
  144. )
  145. )
  146. await self.store.set_appservice_last_pos(upper_bound)
  147. synapse.metrics.event_processing_positions.labels(
  148. "appservice_sender"
  149. ).set(upper_bound)
  150. events_processed_counter.inc(len(events))
  151. event_processing_loop_room_count.labels("appservice_sender").inc(
  152. len(events_by_room)
  153. )
  154. event_processing_loop_counter.labels("appservice_sender").inc()
  155. if events:
  156. now = self.clock.time_msec()
  157. ts = await self.store.get_received_ts(events[-1].event_id)
  158. assert ts is not None
  159. synapse.metrics.event_processing_lag.labels(
  160. "appservice_sender"
  161. ).set(now - ts)
  162. synapse.metrics.event_processing_last_ts.labels(
  163. "appservice_sender"
  164. ).set(ts)
  165. finally:
  166. self.is_processing = False
  167. def notify_interested_services_ephemeral(
  168. self,
  169. stream_key: str,
  170. new_token: Union[int, RoomStreamToken],
  171. users: Collection[Union[str, UserID]],
  172. ) -> None:
  173. """
  174. This is called by the notifier in the background when an ephemeral event is handled
  175. by the homeserver.
  176. This will determine which appservices are interested in the event, and submit them.
  177. Args:
  178. stream_key: The stream the event came from.
  179. `stream_key` can be StreamKeyType.TYPING, StreamKeyType.RECEIPT, StreamKeyType.PRESENCE,
  180. StreamKeyType.TO_DEVICE or StreamKeyType.DEVICE_LIST. Any other value for `stream_key`
  181. will cause this function to return early.
  182. Ephemeral events will only be pushed to appservices that have opted into
  183. receiving them by setting `push_ephemeral` to true in their registration
  184. file. Note that while MSC2409 is experimental, this option is called
  185. `de.sorunome.msc2409.push_ephemeral`.
  186. Appservices will only receive ephemeral events that fall within their
  187. registered user and room namespaces.
  188. new_token: The stream token of the event.
  189. users: The users that should be informed of the new event, if any.
  190. """
  191. if not self.notify_appservices:
  192. return
  193. # Notify appservices of updates in ephemeral event streams.
  194. # Only the following streams are currently supported.
  195. # FIXME: We should use constants for these values.
  196. if stream_key not in (
  197. StreamKeyType.TYPING,
  198. StreamKeyType.RECEIPT,
  199. StreamKeyType.PRESENCE,
  200. StreamKeyType.TO_DEVICE,
  201. StreamKeyType.DEVICE_LIST,
  202. ):
  203. return
  204. # Assert that new_token is an integer (and not a RoomStreamToken).
  205. # All of the supported streams that this function handles use an
  206. # integer to track progress (rather than a RoomStreamToken - a
  207. # vector clock implementation) as they don't support multiple
  208. # stream writers.
  209. #
  210. # As a result, we simply assert that new_token is an integer.
  211. # If we do end up needing to pass a RoomStreamToken down here
  212. # in the future, using RoomStreamToken.stream (the minimum stream
  213. # position) to convert to an ascending integer value should work.
  214. # Additional context: https://github.com/matrix-org/synapse/pull/11137
  215. assert isinstance(new_token, int)
  216. # Ignore to-device messages if the feature flag is not enabled
  217. if (
  218. stream_key == StreamKeyType.TO_DEVICE
  219. and not self._msc2409_to_device_messages_enabled
  220. ):
  221. return
  222. # Ignore device lists if the feature flag is not enabled
  223. if (
  224. stream_key == StreamKeyType.DEVICE_LIST
  225. and not self._msc3202_transaction_extensions_enabled
  226. ):
  227. return
  228. # Check whether there are any appservices which have registered to receive
  229. # ephemeral events.
  230. #
  231. # Note that whether these events are actually relevant to these appservices
  232. # is decided later on.
  233. services = self.store.get_app_services()
  234. services = [
  235. service
  236. for service in services
  237. # Different stream keys require different support booleans
  238. if (
  239. stream_key
  240. in (
  241. StreamKeyType.TYPING,
  242. StreamKeyType.RECEIPT,
  243. StreamKeyType.PRESENCE,
  244. StreamKeyType.TO_DEVICE,
  245. )
  246. and service.supports_ephemeral
  247. )
  248. or (
  249. stream_key == StreamKeyType.DEVICE_LIST
  250. and service.msc3202_transaction_extensions
  251. )
  252. ]
  253. if not services:
  254. # Bail out early if none of the target appservices have explicitly registered
  255. # to receive these ephemeral events.
  256. return
  257. # We only start a new background process if necessary rather than
  258. # optimistically (to cut down on overhead).
  259. self._notify_interested_services_ephemeral(
  260. services, stream_key, new_token, users
  261. )
  262. @wrap_as_background_process("notify_interested_services_ephemeral")
  263. async def _notify_interested_services_ephemeral(
  264. self,
  265. services: List[ApplicationService],
  266. stream_key: str,
  267. new_token: int,
  268. users: Collection[Union[str, UserID]],
  269. ) -> None:
  270. logger.debug("Checking interested services for %s", stream_key)
  271. with Measure(self.clock, "notify_interested_services_ephemeral"):
  272. for service in services:
  273. if stream_key == StreamKeyType.TYPING:
  274. # Note that we don't persist the token (via set_appservice_stream_type_pos)
  275. # for typing_key due to performance reasons and due to their highly
  276. # ephemeral nature.
  277. #
  278. # Instead we simply grab the latest typing updates in _handle_typing
  279. # and, if they apply to this application service, send it off.
  280. events = await self._handle_typing(service, new_token)
  281. if events:
  282. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  283. continue
  284. # Since we read/update the stream position for this AS/stream
  285. async with self._ephemeral_events_linearizer.queue(
  286. (service.id, stream_key)
  287. ):
  288. if stream_key == StreamKeyType.RECEIPT:
  289. events = await self._handle_receipts(service, new_token)
  290. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  291. # Persist the latest handled stream token for this appservice
  292. await self.store.set_appservice_stream_type_pos(
  293. service, "read_receipt", new_token
  294. )
  295. elif stream_key == StreamKeyType.PRESENCE:
  296. events = await self._handle_presence(service, users, new_token)
  297. self.scheduler.enqueue_for_appservice(service, ephemeral=events)
  298. # Persist the latest handled stream token for this appservice
  299. await self.store.set_appservice_stream_type_pos(
  300. service, "presence", new_token
  301. )
  302. elif stream_key == StreamKeyType.TO_DEVICE:
  303. # Retrieve a list of to-device message events, as well as the
  304. # maximum stream token of the messages we were able to retrieve.
  305. to_device_messages = await self._get_to_device_messages(
  306. service, new_token, users
  307. )
  308. self.scheduler.enqueue_for_appservice(
  309. service, to_device_messages=to_device_messages
  310. )
  311. # Persist the latest handled stream token for this appservice
  312. await self.store.set_appservice_stream_type_pos(
  313. service, "to_device", new_token
  314. )
  315. elif stream_key == StreamKeyType.DEVICE_LIST:
  316. device_list_summary = await self._get_device_list_summary(
  317. service, new_token
  318. )
  319. if device_list_summary:
  320. self.scheduler.enqueue_for_appservice(
  321. service, device_list_summary=device_list_summary
  322. )
  323. # Persist the latest handled stream token for this appservice
  324. await self.store.set_appservice_stream_type_pos(
  325. service, "device_list", new_token
  326. )
  327. async def _handle_typing(
  328. self, service: ApplicationService, new_token: int
  329. ) -> List[JsonDict]:
  330. """
  331. Return the typing events since the given stream token that the given application
  332. service should receive.
  333. First fetch all typing events between the given typing stream token (non-inclusive)
  334. and the latest typing event stream token (inclusive). Then return only those typing
  335. events that the given application service may be interested in.
  336. Args:
  337. service: The application service to check for which events it should receive.
  338. new_token: A typing event stream token.
  339. Returns:
  340. A list of JSON dictionaries containing data derived from the typing events that
  341. should be sent to the given application service.
  342. """
  343. typing_source = self.event_sources.sources.typing
  344. # Get the typing events from just before current
  345. typing, _ = await typing_source.get_new_events_as(
  346. service=service,
  347. # For performance reasons, we don't persist the previous
  348. # token in the DB and instead fetch the latest typing event
  349. # for appservices.
  350. # TODO: It'd likely be more efficient to simply fetch the
  351. # typing event with the given 'new_token' stream token and
  352. # check if the given service was interested, rather than
  353. # iterating over all typing events and only grabbing the
  354. # latest few.
  355. from_key=new_token - 1,
  356. )
  357. return typing
  358. async def _handle_receipts(
  359. self, service: ApplicationService, new_token: int
  360. ) -> List[JsonDict]:
  361. """
  362. Return the latest read receipts that the given application service should receive.
  363. First fetch all read receipts between the last receipt stream token that this
  364. application service should have previously received (non-inclusive) and the
  365. latest read receipt stream token (inclusive). Then from that set, return only
  366. those read receipts that the given application service may be interested in.
  367. Args:
  368. service: The application service to check for which events it should receive.
  369. new_token: A receipts event stream token. Purely used to double-check that the
  370. from_token we pull from the database isn't greater than or equal to this
  371. token. Prevents accidentally duplicating work.
  372. Returns:
  373. A list of JSON dictionaries containing data derived from the read receipts that
  374. should be sent to the given application service.
  375. """
  376. from_key = await self.store.get_type_stream_id_for_appservice(
  377. service, "read_receipt"
  378. )
  379. if new_token is not None and new_token <= from_key:
  380. logger.debug(
  381. "Rejecting token lower than or equal to stored: %s" % (new_token,)
  382. )
  383. return []
  384. receipts_source = self.event_sources.sources.receipt
  385. receipts, _ = await receipts_source.get_new_events_as(
  386. service=service, from_key=from_key, to_key=new_token
  387. )
  388. return receipts
  389. async def _handle_presence(
  390. self,
  391. service: ApplicationService,
  392. users: Collection[Union[str, UserID]],
  393. new_token: Optional[int],
  394. ) -> List[JsonDict]:
  395. """
  396. Return the latest presence updates that the given application service should receive.
  397. First, filter the given users list to those that the application service is
  398. interested in. Then retrieve the latest presence updates since the
  399. the last-known previously received presence stream token for the given
  400. application service. Return those presence updates.
  401. Args:
  402. service: The application service that ephemeral events are being sent to.
  403. users: The users that should receive the presence update.
  404. new_token: A presence update stream token. Purely used to double-check that the
  405. from_token we pull from the database isn't greater than or equal to this
  406. token. Prevents accidentally duplicating work.
  407. Returns:
  408. A list of json dictionaries containing data derived from the presence events
  409. that should be sent to the given application service.
  410. """
  411. events: List[JsonDict] = []
  412. presence_source = self.event_sources.sources.presence
  413. from_key = await self.store.get_type_stream_id_for_appservice(
  414. service, "presence"
  415. )
  416. if new_token is not None and new_token <= from_key:
  417. logger.debug(
  418. "Rejecting token lower than or equal to stored: %s" % (new_token,)
  419. )
  420. return []
  421. for user in users:
  422. if isinstance(user, str):
  423. user = UserID.from_string(user)
  424. interested = await service.is_interested_in_presence(user, self.store)
  425. if not interested:
  426. continue
  427. presence_events, _ = await presence_source.get_new_events(
  428. user=user,
  429. from_key=from_key,
  430. )
  431. time_now = self.clock.time_msec()
  432. events.extend(
  433. {
  434. "type": "m.presence",
  435. "sender": event.user_id,
  436. "content": format_user_presence_state(
  437. event, time_now, include_user_id=False
  438. ),
  439. }
  440. for event in presence_events
  441. )
  442. return events
  443. async def _get_to_device_messages(
  444. self,
  445. service: ApplicationService,
  446. new_token: int,
  447. users: Collection[Union[str, UserID]],
  448. ) -> List[JsonDict]:
  449. """
  450. Given an application service, determine which events it should receive
  451. from those between the last-recorded to-device message stream token for this
  452. appservice and the given stream token.
  453. Args:
  454. service: The application service to check for which events it should receive.
  455. new_token: The latest to-device event stream token.
  456. users: The users to be notified for the new to-device messages
  457. (ie, the recipients of the messages).
  458. Returns:
  459. A list of JSON dictionaries containing data derived from the to-device events
  460. that should be sent to the given application service.
  461. """
  462. # Get the stream token that this application service has processed up until
  463. from_key = await self.store.get_type_stream_id_for_appservice(
  464. service, "to_device"
  465. )
  466. # Filter out users that this appservice is not interested in
  467. users_appservice_is_interested_in: List[str] = []
  468. for user in users:
  469. # FIXME: We should do this farther up the call stack. We currently repeat
  470. # this operation in _handle_presence.
  471. if isinstance(user, UserID):
  472. user = user.to_string()
  473. if service.is_interested_in_user(user):
  474. users_appservice_is_interested_in.append(user)
  475. if not users_appservice_is_interested_in:
  476. # Return early if the AS was not interested in any of these users
  477. return []
  478. # Retrieve the to-device messages for each user
  479. recipient_device_to_messages = await self.store.get_messages_for_user_devices(
  480. users_appservice_is_interested_in,
  481. from_key,
  482. new_token,
  483. )
  484. # According to MSC2409, we'll need to add 'to_user_id' and 'to_device_id' fields
  485. # to the event JSON so that the application service will know which user/device
  486. # combination this messages was intended for.
  487. #
  488. # So we mangle this dict into a flat list of to-device messages with the relevant
  489. # user ID and device ID embedded inside each message dict.
  490. message_payload: List[JsonDict] = []
  491. for (
  492. user_id,
  493. device_id,
  494. ), messages in recipient_device_to_messages.items():
  495. for message_json in messages:
  496. # Remove 'message_id' from the to-device message, as it's an internal ID
  497. message_json.pop("message_id", None)
  498. message_payload.append(
  499. {
  500. "to_user_id": user_id,
  501. "to_device_id": device_id,
  502. **message_json,
  503. }
  504. )
  505. return message_payload
  506. async def _get_device_list_summary(
  507. self,
  508. appservice: ApplicationService,
  509. new_key: int,
  510. ) -> DeviceListUpdates:
  511. """
  512. Retrieve a list of users who have changed their device lists.
  513. Args:
  514. appservice: The application service to retrieve device list changes for.
  515. new_key: The stream key of the device list change that triggered this method call.
  516. Returns:
  517. A set of device list updates, comprised of users that the appservices needs to:
  518. * resync the device list of, and
  519. * stop tracking the device list of.
  520. """
  521. # Fetch the last successfully processed device list update stream ID
  522. # for this appservice.
  523. from_key = await self.store.get_type_stream_id_for_appservice(
  524. appservice, "device_list"
  525. )
  526. # Fetch the users who have modified their device list since then.
  527. users_with_changed_device_lists = (
  528. await self.store.get_users_whose_devices_changed(from_key, to_key=new_key)
  529. )
  530. # Filter out any users the application service is not interested in
  531. #
  532. # For each user who changed their device list, we want to check whether this
  533. # appservice would be interested in the change.
  534. filtered_users_with_changed_device_lists = {
  535. user_id
  536. for user_id in users_with_changed_device_lists
  537. if await self._is_appservice_interested_in_device_lists_of_user(
  538. appservice, user_id
  539. )
  540. }
  541. # Create a summary of "changed" and "left" users.
  542. # TODO: Calculate "left" users.
  543. device_list_summary = DeviceListUpdates(
  544. changed=filtered_users_with_changed_device_lists
  545. )
  546. return device_list_summary
  547. async def _is_appservice_interested_in_device_lists_of_user(
  548. self,
  549. appservice: ApplicationService,
  550. user_id: str,
  551. ) -> bool:
  552. """
  553. Returns whether a given application service is interested in the device list
  554. updates of a given user.
  555. The application service is interested in the user's device list updates if any
  556. of the following are true:
  557. * The user is the appservice's sender localpart user.
  558. * The user is in the appservice's user namespace.
  559. * At least one member of one room that the user is a part of is in the
  560. appservice's user namespace.
  561. * The appservice is explicitly (via room ID or alias) interested in at
  562. least one room that the user is in.
  563. Args:
  564. appservice: The application service to gauge interest of.
  565. user_id: The ID of the user whose device list interest is in question.
  566. Returns:
  567. True if the application service is interested in the user's device lists, False
  568. otherwise.
  569. """
  570. # This method checks against both the sender localpart user as well as if the
  571. # user is in the appservice's user namespace.
  572. if appservice.is_interested_in_user(user_id):
  573. return True
  574. # Determine whether any of the rooms the user is in justifies sending this
  575. # device list update to the application service.
  576. room_ids = await self.store.get_rooms_for_user(user_id)
  577. for room_id in room_ids:
  578. # This method covers checking room members for appservice interest as well as
  579. # room ID and alias checks.
  580. if await appservice.is_interested_in_room(room_id, self.store):
  581. return True
  582. return False
  583. async def query_user_exists(self, user_id: str) -> bool:
  584. """Check if any application service knows this user_id exists.
  585. Args:
  586. user_id: The user to query if they exist on any AS.
  587. Returns:
  588. True if this user exists on at least one application service.
  589. """
  590. user_query_services = self._get_services_for_user(user_id=user_id)
  591. for user_service in user_query_services:
  592. is_known_user = await self.appservice_api.query_user(user_service, user_id)
  593. if is_known_user:
  594. return True
  595. return False
  596. async def query_room_alias_exists(
  597. self, room_alias: RoomAlias
  598. ) -> Optional[RoomAliasMapping]:
  599. """Check if an application service knows this room alias exists.
  600. Args:
  601. room_alias: The room alias to query.
  602. Returns:
  603. RoomAliasMapping or None if no association can be found.
  604. """
  605. room_alias_str = room_alias.to_string()
  606. services = self.store.get_app_services()
  607. alias_query_services = [
  608. s for s in services if (s.is_room_alias_in_namespace(room_alias_str))
  609. ]
  610. for alias_service in alias_query_services:
  611. is_known_alias = await self.appservice_api.query_alias(
  612. alias_service, room_alias_str
  613. )
  614. if is_known_alias:
  615. # the alias exists now so don't query more ASes.
  616. return await self.store.get_association_from_room_alias(room_alias)
  617. return None
  618. async def query_3pe(
  619. self, kind: str, protocol: str, fields: Dict[bytes, List[bytes]]
  620. ) -> List[JsonDict]:
  621. services = self._get_services_for_3pn(protocol)
  622. results = await make_deferred_yieldable(
  623. defer.DeferredList(
  624. [
  625. run_in_background(
  626. self.appservice_api.query_3pe, service, kind, protocol, fields
  627. )
  628. for service in services
  629. ],
  630. consumeErrors=True,
  631. )
  632. )
  633. ret = []
  634. for (success, result) in results:
  635. if success:
  636. ret.extend(result)
  637. return ret
  638. async def get_3pe_protocols(
  639. self, only_protocol: Optional[str] = None
  640. ) -> Dict[str, JsonDict]:
  641. services = self.store.get_app_services()
  642. protocols: Dict[str, List[JsonDict]] = {}
  643. # Collect up all the individual protocol responses out of the ASes
  644. for s in services:
  645. for p in s.protocols:
  646. if only_protocol is not None and p != only_protocol:
  647. continue
  648. if p not in protocols:
  649. protocols[p] = []
  650. info = await self.appservice_api.get_3pe_protocol(s, p)
  651. if info is not None:
  652. protocols[p].append(info)
  653. def _merge_instances(infos: List[JsonDict]) -> JsonDict:
  654. # Merge the 'instances' lists of multiple results, but just take
  655. # the other fields from the first as they ought to be identical
  656. # copy the result so as not to corrupt the cached one
  657. combined = dict(infos[0])
  658. combined["instances"] = list(combined["instances"])
  659. for info in infos[1:]:
  660. combined["instances"].extend(info["instances"])
  661. return combined
  662. return {
  663. p: _merge_instances(protocols[p]) for p in protocols.keys() if protocols[p]
  664. }
  665. async def _get_services_for_event(
  666. self, event: EventBase
  667. ) -> List[ApplicationService]:
  668. """Retrieve a list of application services interested in this event.
  669. Args:
  670. event: The event to check.
  671. Returns:
  672. A list of services interested in this event based on the service regex.
  673. """
  674. services = self.store.get_app_services()
  675. # we can't use a list comprehension here. Since python 3, list
  676. # comprehensions use a generator internally. This means you can't yield
  677. # inside of a list comprehension anymore.
  678. interested_list = []
  679. for s in services:
  680. if await s.is_interested_in_event(event.event_id, event, self.store):
  681. interested_list.append(s)
  682. return interested_list
  683. def _get_services_for_user(self, user_id: str) -> List[ApplicationService]:
  684. services = self.store.get_app_services()
  685. return [s for s in services if (s.is_interested_in_user(user_id))]
  686. def _get_services_for_3pn(self, protocol: str) -> List[ApplicationService]:
  687. services = self.store.get_app_services()
  688. return [s for s in services if s.is_interested_in_protocol(protocol)]
  689. async def _is_unknown_user(self, user_id: str) -> bool:
  690. if not self.is_mine_id(user_id):
  691. # we don't know if they are unknown or not since it isn't one of our
  692. # users. We can't poke ASes.
  693. return False
  694. user_info = await self.store.get_user_by_id(user_id)
  695. if user_info:
  696. return False
  697. # user not found; could be the AS though, so check.
  698. services = self.store.get_app_services()
  699. service_list = [s for s in services if s.sender == user_id]
  700. return len(service_list) == 0
  701. async def _check_user_exists(self, user_id: str) -> bool:
  702. unknown_user = await self._is_unknown_user(user_id)
  703. if unknown_user:
  704. return await self.query_user_exists(user_id)
  705. return True