appservice.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2015, 2016 OpenMarket Ltd
  3. #
  4. # Licensed under the Apache License, Version 2.0 (the "License");
  5. # you may not use this file except in compliance with the License.
  6. # You may obtain a copy of the License at
  7. #
  8. # http://www.apache.org/licenses/LICENSE-2.0
  9. #
  10. # Unless required by applicable law or agreed to in writing, software
  11. # distributed under the License is distributed on an "AS IS" BASIS,
  12. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. # See the License for the specific language governing permissions and
  14. # limitations under the License.
  15. from twisted.internet import defer
  16. from synapse.api.constants import EventTypes
  17. from synapse.appservice import ApplicationService
  18. from synapse.types import UserID
  19. import logging
  20. logger = logging.getLogger(__name__)
  21. def log_failure(failure):
  22. logger.error(
  23. "Application Services Failure",
  24. exc_info=(
  25. failure.type,
  26. failure.value,
  27. failure.getTracebackObject()
  28. )
  29. )
  30. # NB: Purposefully not inheriting BaseHandler since that contains way too much
  31. # setup code which this handler does not need or use. This makes testing a lot
  32. # easier.
  33. class ApplicationServicesHandler(object):
  34. def __init__(self, hs, appservice_api, appservice_scheduler):
  35. self.store = hs.get_datastore()
  36. self.hs = hs
  37. self.appservice_api = appservice_api
  38. self.scheduler = appservice_scheduler
  39. self.started_scheduler = False
  40. @defer.inlineCallbacks
  41. def notify_interested_services(self, event):
  42. """Notifies (pushes) all application services interested in this event.
  43. Pushing is done asynchronously, so this method won't block for any
  44. prolonged length of time.
  45. Args:
  46. event(Event): The event to push out to interested services.
  47. """
  48. # Gather interested services
  49. services = yield self._get_services_for_event(event)
  50. if len(services) == 0:
  51. return # no services need notifying
  52. # Do we know this user exists? If not, poke the user query API for
  53. # all services which match that user regex. This needs to block as these
  54. # user queries need to be made BEFORE pushing the event.
  55. yield self._check_user_exists(event.sender)
  56. if event.type == EventTypes.Member:
  57. yield self._check_user_exists(event.state_key)
  58. if not self.started_scheduler:
  59. self.scheduler.start().addErrback(log_failure)
  60. self.started_scheduler = True
  61. # Fork off pushes to these services
  62. for service in services:
  63. self.scheduler.submit_event_for_as(service, event)
  64. @defer.inlineCallbacks
  65. def query_user_exists(self, user_id):
  66. """Check if any application service knows this user_id exists.
  67. Args:
  68. user_id(str): The user to query if they exist on any AS.
  69. Returns:
  70. True if this user exists on at least one application service.
  71. """
  72. user_query_services = yield self._get_services_for_user(
  73. user_id=user_id
  74. )
  75. for user_service in user_query_services:
  76. is_known_user = yield self.appservice_api.query_user(
  77. user_service, user_id
  78. )
  79. if is_known_user:
  80. defer.returnValue(True)
  81. defer.returnValue(False)
  82. @defer.inlineCallbacks
  83. def query_room_alias_exists(self, room_alias):
  84. """Check if an application service knows this room alias exists.
  85. Args:
  86. room_alias(RoomAlias): The room alias to query.
  87. Returns:
  88. namedtuple: with keys "room_id" and "servers" or None if no
  89. association can be found.
  90. """
  91. room_alias_str = room_alias.to_string()
  92. alias_query_services = yield self._get_services_for_event(
  93. event=None,
  94. restrict_to=ApplicationService.NS_ALIASES,
  95. alias_list=[room_alias_str]
  96. )
  97. for alias_service in alias_query_services:
  98. is_known_alias = yield self.appservice_api.query_alias(
  99. alias_service, room_alias_str
  100. )
  101. if is_known_alias:
  102. # the alias exists now so don't query more ASes.
  103. result = yield self.store.get_association_from_room_alias(
  104. room_alias
  105. )
  106. defer.returnValue(result)
  107. @defer.inlineCallbacks
  108. def _get_services_for_event(self, event, restrict_to="", alias_list=None):
  109. """Retrieve a list of application services interested in this event.
  110. Args:
  111. event(Event): The event to check. Can be None if alias_list is not.
  112. restrict_to(str): The namespace to restrict regex tests to.
  113. alias_list: A list of aliases to get services for. If None, this
  114. list is obtained from the database.
  115. Returns:
  116. list<ApplicationService>: A list of services interested in this
  117. event based on the service regex.
  118. """
  119. member_list = None
  120. if hasattr(event, "room_id"):
  121. # We need to know the aliases associated with this event.room_id,
  122. # if any.
  123. if not alias_list:
  124. alias_list = yield self.store.get_aliases_for_room(
  125. event.room_id
  126. )
  127. # We need to know the members associated with this event.room_id,
  128. # if any.
  129. member_list = yield self.store.get_users_in_room(event.room_id)
  130. services = yield self.store.get_app_services()
  131. interested_list = [
  132. s for s in services if (
  133. s.is_interested(event, restrict_to, alias_list, member_list)
  134. )
  135. ]
  136. defer.returnValue(interested_list)
  137. @defer.inlineCallbacks
  138. def _get_services_for_user(self, user_id):
  139. services = yield self.store.get_app_services()
  140. interested_list = [
  141. s for s in services if (
  142. s.is_interested_in_user(user_id)
  143. )
  144. ]
  145. defer.returnValue(interested_list)
  146. @defer.inlineCallbacks
  147. def _is_unknown_user(self, user_id):
  148. user = UserID.from_string(user_id)
  149. if not self.hs.is_mine(user):
  150. # we don't know if they are unknown or not since it isn't one of our
  151. # users. We can't poke ASes.
  152. defer.returnValue(False)
  153. return
  154. user_info = yield self.store.get_user_by_id(user_id)
  155. if user_info:
  156. defer.returnValue(False)
  157. return
  158. # user not found; could be the AS though, so check.
  159. services = yield self.store.get_app_services()
  160. service_list = [s for s in services if s.sender == user_id]
  161. defer.returnValue(len(service_list) == 0)
  162. @defer.inlineCallbacks
  163. def _check_user_exists(self, user_id):
  164. unknown_user = yield self._is_unknown_user(user_id)
  165. if unknown_user:
  166. exists = yield self.query_user_exists(user_id)
  167. defer.returnValue(exists)
  168. defer.returnValue(True)