No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 
 
 

969 líneas
38 KiB

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