appservice.py 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190
  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. import logging
  19. logger = logging.getLogger(__name__)
  20. def log_failure(failure):
  21. logger.error(
  22. "Application Services Failure",
  23. exc_info=(
  24. failure.type,
  25. failure.value,
  26. failure.getTracebackObject()
  27. )
  28. )
  29. class ApplicationServicesHandler(object):
  30. def __init__(self, hs):
  31. self.store = hs.get_datastore()
  32. self.is_mine_id = hs.is_mine_id
  33. self.appservice_api = hs.get_application_service_api()
  34. self.scheduler = hs.get_application_service_scheduler()
  35. self.started_scheduler = False
  36. @defer.inlineCallbacks
  37. def notify_interested_services(self, event):
  38. """Notifies (pushes) all application services interested in this event.
  39. Pushing is done asynchronously, so this method won't block for any
  40. prolonged length of time.
  41. Args:
  42. event(Event): The event to push out to interested services.
  43. """
  44. # Gather interested services
  45. services = yield self._get_services_for_event(event)
  46. if len(services) == 0:
  47. return # no services need notifying
  48. # Do we know this user exists? If not, poke the user query API for
  49. # all services which match that user regex. This needs to block as these
  50. # user queries need to be made BEFORE pushing the event.
  51. yield self._check_user_exists(event.sender)
  52. if event.type == EventTypes.Member:
  53. yield self._check_user_exists(event.state_key)
  54. if not self.started_scheduler:
  55. self.scheduler.start().addErrback(log_failure)
  56. self.started_scheduler = True
  57. # Fork off pushes to these services
  58. for service in services:
  59. self.scheduler.submit_event_for_as(service, event)
  60. @defer.inlineCallbacks
  61. def query_user_exists(self, user_id):
  62. """Check if any application service knows this user_id exists.
  63. Args:
  64. user_id(str): The user to query if they exist on any AS.
  65. Returns:
  66. True if this user exists on at least one application service.
  67. """
  68. user_query_services = yield self._get_services_for_user(
  69. user_id=user_id
  70. )
  71. for user_service in user_query_services:
  72. is_known_user = yield self.appservice_api.query_user(
  73. user_service, user_id
  74. )
  75. if is_known_user:
  76. defer.returnValue(True)
  77. defer.returnValue(False)
  78. @defer.inlineCallbacks
  79. def query_room_alias_exists(self, room_alias):
  80. """Check if an application service knows this room alias exists.
  81. Args:
  82. room_alias(RoomAlias): The room alias to query.
  83. Returns:
  84. namedtuple: with keys "room_id" and "servers" or None if no
  85. association can be found.
  86. """
  87. room_alias_str = room_alias.to_string()
  88. alias_query_services = yield self._get_services_for_event(
  89. event=None,
  90. restrict_to=ApplicationService.NS_ALIASES,
  91. alias_list=[room_alias_str]
  92. )
  93. for alias_service in alias_query_services:
  94. is_known_alias = yield self.appservice_api.query_alias(
  95. alias_service, room_alias_str
  96. )
  97. if is_known_alias:
  98. # the alias exists now so don't query more ASes.
  99. result = yield self.store.get_association_from_room_alias(
  100. room_alias
  101. )
  102. defer.returnValue(result)
  103. @defer.inlineCallbacks
  104. def _get_services_for_event(self, event, restrict_to="", alias_list=None):
  105. """Retrieve a list of application services interested in this event.
  106. Args:
  107. event(Event): The event to check. Can be None if alias_list is not.
  108. restrict_to(str): The namespace to restrict regex tests to.
  109. alias_list: A list of aliases to get services for. If None, this
  110. list is obtained from the database.
  111. Returns:
  112. list<ApplicationService>: A list of services interested in this
  113. event based on the service regex.
  114. """
  115. member_list = None
  116. if hasattr(event, "room_id"):
  117. # We need to know the aliases associated with this event.room_id,
  118. # if any.
  119. if not alias_list:
  120. alias_list = yield self.store.get_aliases_for_room(
  121. event.room_id
  122. )
  123. # We need to know the members associated with this event.room_id,
  124. # if any.
  125. member_list = yield self.store.get_users_in_room(event.room_id)
  126. services = yield self.store.get_app_services()
  127. interested_list = [
  128. s for s in services if (
  129. s.is_interested(event, restrict_to, alias_list, member_list)
  130. )
  131. ]
  132. defer.returnValue(interested_list)
  133. @defer.inlineCallbacks
  134. def _get_services_for_user(self, user_id):
  135. services = yield self.store.get_app_services()
  136. interested_list = [
  137. s for s in services if (
  138. s.is_interested_in_user(user_id)
  139. )
  140. ]
  141. defer.returnValue(interested_list)
  142. @defer.inlineCallbacks
  143. def _is_unknown_user(self, user_id):
  144. if not self.is_mine_id(user_id):
  145. # we don't know if they are unknown or not since it isn't one of our
  146. # users. We can't poke ASes.
  147. defer.returnValue(False)
  148. return
  149. user_info = yield self.store.get_user_by_id(user_id)
  150. if user_info:
  151. defer.returnValue(False)
  152. return
  153. # user not found; could be the AS though, so check.
  154. services = yield self.store.get_app_services()
  155. service_list = [s for s in services if s.sender == user_id]
  156. defer.returnValue(len(service_list) == 0)
  157. @defer.inlineCallbacks
  158. def _check_user_exists(self, user_id):
  159. unknown_user = yield self._is_unknown_user(user_id)
  160. if unknown_user:
  161. exists = yield self.query_user_exists(user_id)
  162. defer.returnValue(exists)
  163. defer.returnValue(True)