visibility.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2014 - 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 Membership, EventTypes
  17. from synapse.util.logcontext import preserve_fn, preserve_context_over_deferred
  18. import logging
  19. logger = logging.getLogger(__name__)
  20. VISIBILITY_PRIORITY = (
  21. "world_readable",
  22. "shared",
  23. "invited",
  24. "joined",
  25. )
  26. MEMBERSHIP_PRIORITY = (
  27. Membership.JOIN,
  28. Membership.INVITE,
  29. Membership.KNOCK,
  30. Membership.LEAVE,
  31. Membership.BAN,
  32. )
  33. @defer.inlineCallbacks
  34. def filter_events_for_clients(store, user_tuples, events, event_id_to_state):
  35. """ Returns dict of user_id -> list of events that user is allowed to
  36. see.
  37. Args:
  38. user_tuples (str, bool): (user id, is_peeking) for each user to be
  39. checked. is_peeking should be true if:
  40. * the user is not currently a member of the room, and:
  41. * the user has not been a member of the room since the
  42. given events
  43. events ([synapse.events.EventBase]): list of events to filter
  44. """
  45. forgotten = yield preserve_context_over_deferred(defer.gatherResults([
  46. preserve_fn(store.who_forgot_in_room)(
  47. room_id,
  48. )
  49. for room_id in frozenset(e.room_id for e in events)
  50. ], consumeErrors=True))
  51. # Set of membership event_ids that have been forgotten
  52. event_id_forgotten = frozenset(
  53. row["event_id"] for rows in forgotten for row in rows
  54. )
  55. ignore_dict_content = yield store.get_global_account_data_by_type_for_users(
  56. "m.ignored_user_list", user_ids=[user_id for user_id, _ in user_tuples]
  57. )
  58. # FIXME: This will explode if people upload something incorrect.
  59. ignore_dict = {
  60. user_id: frozenset(
  61. content.get("ignored_users", {}).keys() if content else []
  62. )
  63. for user_id, content in ignore_dict_content.items()
  64. }
  65. def allowed(event, user_id, is_peeking, ignore_list):
  66. """
  67. Args:
  68. event (synapse.events.EventBase): event to check
  69. user_id (str)
  70. is_peeking (bool)
  71. ignore_list (list): list of users to ignore
  72. """
  73. if not event.is_state() and event.sender in ignore_list:
  74. return False
  75. state = event_id_to_state[event.event_id]
  76. # get the room_visibility at the time of the event.
  77. visibility_event = state.get((EventTypes.RoomHistoryVisibility, ""), None)
  78. if visibility_event:
  79. visibility = visibility_event.content.get("history_visibility", "shared")
  80. else:
  81. visibility = "shared"
  82. if visibility not in VISIBILITY_PRIORITY:
  83. visibility = "shared"
  84. # if it was world_readable, it's easy: everyone can read it
  85. if visibility == "world_readable":
  86. return True
  87. # Always allow history visibility events on boundaries. This is done
  88. # by setting the effective visibility to the least restrictive
  89. # of the old vs new.
  90. if event.type == EventTypes.RoomHistoryVisibility:
  91. prev_content = event.unsigned.get("prev_content", {})
  92. prev_visibility = prev_content.get("history_visibility", None)
  93. if prev_visibility not in VISIBILITY_PRIORITY:
  94. prev_visibility = "shared"
  95. new_priority = VISIBILITY_PRIORITY.index(visibility)
  96. old_priority = VISIBILITY_PRIORITY.index(prev_visibility)
  97. if old_priority < new_priority:
  98. visibility = prev_visibility
  99. # likewise, if the event is the user's own membership event, use
  100. # the 'most joined' membership
  101. membership = None
  102. if event.type == EventTypes.Member and event.state_key == user_id:
  103. membership = event.content.get("membership", None)
  104. if membership not in MEMBERSHIP_PRIORITY:
  105. membership = "leave"
  106. prev_content = event.unsigned.get("prev_content", {})
  107. prev_membership = prev_content.get("membership", None)
  108. if prev_membership not in MEMBERSHIP_PRIORITY:
  109. prev_membership = "leave"
  110. new_priority = MEMBERSHIP_PRIORITY.index(membership)
  111. old_priority = MEMBERSHIP_PRIORITY.index(prev_membership)
  112. if old_priority < new_priority:
  113. membership = prev_membership
  114. # otherwise, get the user's membership at the time of the event.
  115. if membership is None:
  116. membership_event = state.get((EventTypes.Member, user_id), None)
  117. if membership_event:
  118. if membership_event.event_id not in event_id_forgotten:
  119. membership = membership_event.membership
  120. # if the user was a member of the room at the time of the event,
  121. # they can see it.
  122. if membership == Membership.JOIN:
  123. return True
  124. if visibility == "joined":
  125. # we weren't a member at the time of the event, so we can't
  126. # see this event.
  127. return False
  128. elif visibility == "invited":
  129. # user can also see the event if they were *invited* at the time
  130. # of the event.
  131. return membership == Membership.INVITE
  132. else:
  133. # visibility is shared: user can also see the event if they have
  134. # become a member since the event
  135. #
  136. # XXX: if the user has subsequently joined and then left again,
  137. # ideally we would share history up to the point they left. But
  138. # we don't know when they left.
  139. return not is_peeking
  140. defer.returnValue({
  141. user_id: [
  142. event
  143. for event in events
  144. if allowed(event, user_id, is_peeking, ignore_dict.get(user_id, []))
  145. ]
  146. for user_id, is_peeking in user_tuples
  147. })
  148. @defer.inlineCallbacks
  149. def filter_events_for_clients_context(store, user_tuples, events, event_id_to_context):
  150. user_ids = set(u[0] for u in user_tuples)
  151. event_id_to_state = {}
  152. for event_id, context in event_id_to_context.items():
  153. state = yield store.get_events([
  154. e_id
  155. for key, e_id in context.current_state_ids.iteritems()
  156. if key == (EventTypes.RoomHistoryVisibility, "")
  157. or (key[0] == EventTypes.Member and key[1] in user_ids)
  158. ])
  159. event_id_to_state[event_id] = state
  160. res = yield filter_events_for_clients(
  161. store, user_tuples, events, event_id_to_state
  162. )
  163. defer.returnValue(res)
  164. @defer.inlineCallbacks
  165. def filter_events_for_client(store, user_id, events, is_peeking=False):
  166. """
  167. Check which events a user is allowed to see
  168. Args:
  169. user_id(str): user id to be checked
  170. events([synapse.events.EventBase]): list of events to be checked
  171. is_peeking(bool): should be True if:
  172. * the user is not currently a member of the room, and:
  173. * the user has not been a member of the room since the given
  174. events
  175. Returns:
  176. [synapse.events.EventBase]
  177. """
  178. types = (
  179. (EventTypes.RoomHistoryVisibility, ""),
  180. (EventTypes.Member, user_id),
  181. )
  182. event_id_to_state = yield store.get_state_for_events(
  183. frozenset(e.event_id for e in events),
  184. types=types
  185. )
  186. res = yield filter_events_for_clients(
  187. store, [(user_id, is_peeking)], events, event_id_to_state
  188. )
  189. defer.returnValue(res.get(user_id, []))