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

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