user_directory.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702
  1. # -*- coding: utf-8 -*-
  2. # Copyright 2017 Vector Creations 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. import logging
  16. from six import iteritems
  17. from twisted.internet import defer
  18. from synapse.api.constants import EventTypes, JoinRules, Membership
  19. from synapse.metrics.background_process_metrics import run_as_background_process
  20. from synapse.storage.roommember import ProfileInfo
  21. from synapse.types import get_localpart_from_id
  22. from synapse.util.metrics import Measure
  23. logger = logging.getLogger(__name__)
  24. class UserDirectoryHandler(object):
  25. """Handles querying of and keeping updated the user_directory.
  26. N.B.: ASSUMES IT IS THE ONLY THING THAT MODIFIES THE USER DIRECTORY
  27. The user directory is filled with users who this server can see are joined to a
  28. world_readable or publically joinable room. We keep a database table up to date
  29. by streaming changes of the current state and recalculating whether users should
  30. be in the directory or not when necessary.
  31. For each user in the directory we also store a room_id which is public and that the
  32. user is joined to. This allows us to ignore history_visibility and join_rules changes
  33. for that user in all other public rooms, as we know they'll still be in at least
  34. one public room.
  35. """
  36. INITIAL_ROOM_SLEEP_MS = 50
  37. INITIAL_ROOM_SLEEP_COUNT = 100
  38. INITIAL_ROOM_BATCH_SIZE = 100
  39. INITIAL_USER_SLEEP_MS = 10
  40. def __init__(self, hs):
  41. self.store = hs.get_datastore()
  42. self.state = hs.get_state_handler()
  43. self.server_name = hs.hostname
  44. self.clock = hs.get_clock()
  45. self.notifier = hs.get_notifier()
  46. self.is_mine_id = hs.is_mine_id
  47. self.update_user_directory = hs.config.update_user_directory
  48. self.search_all_users = hs.config.user_directory_search_all_users
  49. # When start up for the first time we need to populate the user_directory.
  50. # This is a set of user_id's we've inserted already
  51. self.initially_handled_users = set()
  52. self.initially_handled_users_in_public = set()
  53. self.initially_handled_users_share = set()
  54. self.initially_handled_users_share_private_room = set()
  55. # The current position in the current_state_delta stream
  56. self.pos = None
  57. # Guard to ensure we only process deltas one at a time
  58. self._is_processing = False
  59. if self.update_user_directory:
  60. self.notifier.add_replication_callback(self.notify_new_event)
  61. # We kick this off so that we don't have to wait for a change before
  62. # we start populating the user directory
  63. self.clock.call_later(0, self.notify_new_event)
  64. def search_users(self, user_id, search_term, limit):
  65. """Searches for users in directory
  66. Returns:
  67. dict of the form::
  68. {
  69. "limited": <bool>, # whether there were more results or not
  70. "results": [ # Ordered by best match first
  71. {
  72. "user_id": <user_id>,
  73. "display_name": <display_name>,
  74. "avatar_url": <avatar_url>
  75. }
  76. ]
  77. }
  78. """
  79. return self.store.search_user_dir(user_id, search_term, limit)
  80. def notify_new_event(self):
  81. """Called when there may be more deltas to process
  82. """
  83. if not self.update_user_directory:
  84. return
  85. if self._is_processing:
  86. return
  87. @defer.inlineCallbacks
  88. def process():
  89. try:
  90. yield self._unsafe_process()
  91. finally:
  92. self._is_processing = False
  93. self._is_processing = True
  94. run_as_background_process("user_directory.notify_new_event", process)
  95. @defer.inlineCallbacks
  96. def handle_local_profile_change(self, user_id, profile):
  97. """Called to update index of our local user profiles when they change
  98. irrespective of any rooms the user may be in.
  99. """
  100. # FIXME(#3714): We should probably do this in the same worker as all
  101. # the other changes.
  102. is_support = yield self.store.is_support_user(user_id)
  103. # Support users are for diagnostics and should not appear in the user directory.
  104. if not is_support:
  105. yield self.store.update_profile_in_user_dir(
  106. user_id, profile.display_name, profile.avatar_url, None,
  107. )
  108. @defer.inlineCallbacks
  109. def handle_user_deactivated(self, user_id):
  110. """Called when a user ID is deactivated
  111. """
  112. # FIXME(#3714): We should probably do this in the same worker as all
  113. # the other changes.
  114. yield self.store.remove_from_user_dir(user_id)
  115. yield self.store.remove_from_user_in_public_room(user_id)
  116. @defer.inlineCallbacks
  117. def _unsafe_process(self):
  118. # If self.pos is None then means we haven't fetched it from DB
  119. if self.pos is None:
  120. self.pos = yield self.store.get_user_directory_stream_pos()
  121. # If still None then we need to do the initial fill of directory
  122. if self.pos is None:
  123. yield self._do_initial_spam()
  124. self.pos = yield self.store.get_user_directory_stream_pos()
  125. # Loop round handling deltas until we're up to date
  126. while True:
  127. with Measure(self.clock, "user_dir_delta"):
  128. deltas = yield self.store.get_current_state_deltas(self.pos)
  129. if not deltas:
  130. return
  131. logger.info("Handling %d state deltas", len(deltas))
  132. yield self._handle_deltas(deltas)
  133. self.pos = deltas[-1]["stream_id"]
  134. yield self.store.update_user_directory_stream_pos(self.pos)
  135. @defer.inlineCallbacks
  136. def _do_initial_spam(self):
  137. """Populates the user_directory from the current state of the DB, used
  138. when synapse first starts with user_directory support
  139. """
  140. new_pos = yield self.store.get_max_stream_id_in_current_state_deltas()
  141. # Delete any existing entries just in case there are any
  142. yield self.store.delete_all_from_user_dir()
  143. # We process by going through each existing room at a time.
  144. room_ids = yield self.store.get_all_rooms()
  145. logger.info("Doing initial update of user directory. %d rooms", len(room_ids))
  146. num_processed_rooms = 0
  147. for room_id in room_ids:
  148. logger.info("Handling room %d/%d", num_processed_rooms + 1, len(room_ids))
  149. yield self._handle_initial_room(room_id)
  150. num_processed_rooms += 1
  151. yield self.clock.sleep(self.INITIAL_ROOM_SLEEP_MS / 1000.)
  152. logger.info("Processed all rooms.")
  153. if self.search_all_users:
  154. num_processed_users = 0
  155. user_ids = yield self.store.get_all_local_users()
  156. logger.info("Doing initial update of user directory. %d users", len(user_ids))
  157. for user_id in user_ids:
  158. # We add profiles for all users even if they don't match the
  159. # include pattern, just in case we want to change it in future
  160. logger.info("Handling user %d/%d", num_processed_users + 1, len(user_ids))
  161. yield self._handle_local_user(user_id)
  162. num_processed_users += 1
  163. yield self.clock.sleep(self.INITIAL_USER_SLEEP_MS / 1000.)
  164. logger.info("Processed all users")
  165. self.initially_handled_users = None
  166. self.initially_handled_users_in_public = None
  167. self.initially_handled_users_share = None
  168. self.initially_handled_users_share_private_room = None
  169. yield self.store.update_user_directory_stream_pos(new_pos)
  170. @defer.inlineCallbacks
  171. def _handle_initial_room(self, room_id):
  172. """Called when we initially fill out user_directory one room at a time
  173. """
  174. is_in_room = yield self.store.is_host_joined(room_id, self.server_name)
  175. if not is_in_room:
  176. return
  177. is_public = yield self.store.is_room_world_readable_or_publicly_joinable(room_id)
  178. users_with_profile = yield self.state.get_current_user_in_room(room_id)
  179. user_ids = set(users_with_profile)
  180. unhandled_users = user_ids - self.initially_handled_users
  181. yield self.store.add_profiles_to_user_dir(
  182. room_id, {
  183. user_id: users_with_profile[user_id] for user_id in unhandled_users
  184. }
  185. )
  186. self.initially_handled_users |= unhandled_users
  187. if is_public:
  188. yield self.store.add_users_to_public_room(
  189. room_id,
  190. user_ids=user_ids - self.initially_handled_users_in_public
  191. )
  192. self.initially_handled_users_in_public |= user_ids
  193. # We now go and figure out the new users who share rooms with user entries
  194. # We sleep aggressively here as otherwise it can starve resources.
  195. # We also batch up inserts/updates, but try to avoid too many at once.
  196. to_insert = set()
  197. to_update = set()
  198. count = 0
  199. for user_id in user_ids:
  200. if count % self.INITIAL_ROOM_SLEEP_COUNT == 0:
  201. yield self.clock.sleep(self.INITIAL_ROOM_SLEEP_MS / 1000.)
  202. if not self.is_mine_id(user_id):
  203. count += 1
  204. continue
  205. if self.store.get_if_app_services_interested_in_user(user_id):
  206. count += 1
  207. continue
  208. for other_user_id in user_ids:
  209. if user_id == other_user_id:
  210. continue
  211. if count % self.INITIAL_ROOM_SLEEP_COUNT == 0:
  212. yield self.clock.sleep(self.INITIAL_ROOM_SLEEP_MS / 1000.)
  213. count += 1
  214. user_set = (user_id, other_user_id)
  215. if user_set in self.initially_handled_users_share_private_room:
  216. continue
  217. if user_set in self.initially_handled_users_share:
  218. if is_public:
  219. continue
  220. to_update.add(user_set)
  221. else:
  222. to_insert.add(user_set)
  223. if is_public:
  224. self.initially_handled_users_share.add(user_set)
  225. else:
  226. self.initially_handled_users_share_private_room.add(user_set)
  227. if len(to_insert) > self.INITIAL_ROOM_BATCH_SIZE:
  228. yield self.store.add_users_who_share_room(
  229. room_id, not is_public, to_insert,
  230. )
  231. to_insert.clear()
  232. if len(to_update) > self.INITIAL_ROOM_BATCH_SIZE:
  233. yield self.store.update_users_who_share_room(
  234. room_id, not is_public, to_update,
  235. )
  236. to_update.clear()
  237. if to_insert:
  238. yield self.store.add_users_who_share_room(
  239. room_id, not is_public, to_insert,
  240. )
  241. to_insert.clear()
  242. if to_update:
  243. yield self.store.update_users_who_share_room(
  244. room_id, not is_public, to_update,
  245. )
  246. to_update.clear()
  247. @defer.inlineCallbacks
  248. def _handle_deltas(self, deltas):
  249. """Called with the state deltas to process
  250. """
  251. for delta in deltas:
  252. typ = delta["type"]
  253. state_key = delta["state_key"]
  254. room_id = delta["room_id"]
  255. event_id = delta["event_id"]
  256. prev_event_id = delta["prev_event_id"]
  257. logger.debug("Handling: %r %r, %s", typ, state_key, event_id)
  258. # For join rule and visibility changes we need to check if the room
  259. # may have become public or not and add/remove the users in said room
  260. if typ in (EventTypes.RoomHistoryVisibility, EventTypes.JoinRules):
  261. yield self._handle_room_publicity_change(
  262. room_id, prev_event_id, event_id, typ,
  263. )
  264. elif typ == EventTypes.Member:
  265. change = yield self._get_key_change(
  266. prev_event_id, event_id,
  267. key_name="membership",
  268. public_value=Membership.JOIN,
  269. )
  270. if change is False:
  271. # Need to check if the server left the room entirely, if so
  272. # we might need to remove all the users in that room
  273. is_in_room = yield self.store.is_host_joined(
  274. room_id, self.server_name,
  275. )
  276. if not is_in_room:
  277. logger.info("Server left room: %r", room_id)
  278. # Fetch all the users that we marked as being in user
  279. # directory due to being in the room and then check if
  280. # need to remove those users or not
  281. user_ids = yield self.store.get_users_in_dir_due_to_room(room_id)
  282. for user_id in user_ids:
  283. yield self._handle_remove_user(room_id, user_id)
  284. return
  285. else:
  286. logger.debug("Server is still in room: %r", room_id)
  287. is_support = yield self.store.is_support_user(state_key)
  288. if not is_support:
  289. if change is None:
  290. # Handle any profile changes
  291. yield self._handle_profile_change(
  292. state_key, room_id, prev_event_id, event_id,
  293. )
  294. continue
  295. if change: # The user joined
  296. event = yield self.store.get_event(event_id, allow_none=True)
  297. profile = ProfileInfo(
  298. avatar_url=event.content.get("avatar_url"),
  299. display_name=event.content.get("displayname"),
  300. )
  301. yield self._handle_new_user(room_id, state_key, profile)
  302. else: # The user left
  303. yield self._handle_remove_user(room_id, state_key)
  304. else:
  305. logger.debug("Ignoring irrelevant type: %r", typ)
  306. @defer.inlineCallbacks
  307. def _handle_room_publicity_change(self, room_id, prev_event_id, event_id, typ):
  308. """Handle a room having potentially changed from/to world_readable/publically
  309. joinable.
  310. Args:
  311. room_id (str)
  312. prev_event_id (str|None): The previous event before the state change
  313. event_id (str|None): The new event after the state change
  314. typ (str): Type of the event
  315. """
  316. logger.debug("Handling change for %s: %s", typ, room_id)
  317. if typ == EventTypes.RoomHistoryVisibility:
  318. change = yield self._get_key_change(
  319. prev_event_id, event_id,
  320. key_name="history_visibility",
  321. public_value="world_readable",
  322. )
  323. elif typ == EventTypes.JoinRules:
  324. change = yield self._get_key_change(
  325. prev_event_id, event_id,
  326. key_name="join_rule",
  327. public_value=JoinRules.PUBLIC,
  328. )
  329. else:
  330. raise Exception("Invalid event type")
  331. # If change is None, no change. True => become world_readable/public,
  332. # False => was world_readable/public
  333. if change is None:
  334. logger.debug("No change")
  335. return
  336. # There's been a change to or from being world readable.
  337. is_public = yield self.store.is_room_world_readable_or_publicly_joinable(
  338. room_id
  339. )
  340. logger.debug("Change: %r, is_public: %r", change, is_public)
  341. if change and not is_public:
  342. # If we became world readable but room isn't currently public then
  343. # we ignore the change
  344. return
  345. elif not change and is_public:
  346. # If we stopped being world readable but are still public,
  347. # ignore the change
  348. return
  349. if change:
  350. users_with_profile = yield self.state.get_current_user_in_room(room_id)
  351. for user_id, profile in iteritems(users_with_profile):
  352. yield self._handle_new_user(room_id, user_id, profile)
  353. else:
  354. users = yield self.store.get_users_in_public_due_to_room(room_id)
  355. for user_id in users:
  356. yield self._handle_remove_user(room_id, user_id)
  357. @defer.inlineCallbacks
  358. def _handle_local_user(self, user_id):
  359. """Adds a new local roomless user into the user_directory_search table.
  360. Used to populate up the user index when we have an
  361. user_directory_search_all_users specified.
  362. """
  363. logger.debug("Adding new local user to dir, %r", user_id)
  364. profile = yield self.store.get_profileinfo(get_localpart_from_id(user_id))
  365. row = yield self.store.get_user_in_directory(user_id)
  366. if not row:
  367. yield self.store.add_profiles_to_user_dir(None, {user_id: profile})
  368. @defer.inlineCallbacks
  369. def _handle_new_user(self, room_id, user_id, profile):
  370. """Called when we might need to add user to directory
  371. Args:
  372. room_id (str): room_id that user joined or started being public
  373. user_id (str)
  374. """
  375. logger.debug("Adding new user to dir, %r", user_id)
  376. row = yield self.store.get_user_in_directory(user_id)
  377. if not row:
  378. yield self.store.add_profiles_to_user_dir(room_id, {user_id: profile})
  379. is_public = yield self.store.is_room_world_readable_or_publicly_joinable(
  380. room_id
  381. )
  382. if is_public:
  383. row = yield self.store.get_user_in_public_room(user_id)
  384. if not row:
  385. yield self.store.add_users_to_public_room(room_id, [user_id])
  386. else:
  387. logger.debug("Not adding new user to public dir, %r", user_id)
  388. # Now we update users who share rooms with users. We do this by getting
  389. # all the current users in the room and seeing which aren't already
  390. # marked in the database as sharing with `user_id`
  391. users_with_profile = yield self.state.get_current_user_in_room(room_id)
  392. to_insert = set()
  393. to_update = set()
  394. is_appservice = self.store.get_if_app_services_interested_in_user(user_id)
  395. # First, if they're our user then we need to update for every user
  396. if self.is_mine_id(user_id) and not is_appservice:
  397. # Returns a map of other_user_id -> shared_private. We only need
  398. # to update mappings if for users that either don't share a room
  399. # already (aren't in the map) or, if the room is private, those that
  400. # only share a public room.
  401. user_ids_shared = yield self.store.get_users_who_share_room_from_dir(
  402. user_id
  403. )
  404. for other_user_id in users_with_profile:
  405. if user_id == other_user_id:
  406. continue
  407. shared_is_private = user_ids_shared.get(other_user_id)
  408. if shared_is_private is True:
  409. # We've already marked in the database they share a private room
  410. continue
  411. elif shared_is_private is False:
  412. # They already share a public room, so only update if this is
  413. # a private room
  414. if not is_public:
  415. to_update.add((user_id, other_user_id))
  416. elif shared_is_private is None:
  417. # This is the first time they both share a room
  418. to_insert.add((user_id, other_user_id))
  419. # Next we need to update for every local user in the room
  420. for other_user_id in users_with_profile:
  421. if user_id == other_user_id:
  422. continue
  423. is_appservice = self.store.get_if_app_services_interested_in_user(
  424. other_user_id
  425. )
  426. if self.is_mine_id(other_user_id) and not is_appservice:
  427. shared_is_private = yield self.store.get_if_users_share_a_room(
  428. other_user_id, user_id,
  429. )
  430. if shared_is_private is True:
  431. # We've already marked in the database they share a private room
  432. continue
  433. elif shared_is_private is False:
  434. # They already share a public room, so only update if this is
  435. # a private room
  436. if not is_public:
  437. to_update.add((other_user_id, user_id))
  438. elif shared_is_private is None:
  439. # This is the first time they both share a room
  440. to_insert.add((other_user_id, user_id))
  441. if to_insert:
  442. yield self.store.add_users_who_share_room(
  443. room_id, not is_public, to_insert,
  444. )
  445. if to_update:
  446. yield self.store.update_users_who_share_room(
  447. room_id, not is_public, to_update,
  448. )
  449. @defer.inlineCallbacks
  450. def _handle_remove_user(self, room_id, user_id):
  451. """Called when we might need to remove user to directory
  452. Args:
  453. room_id (str): room_id that user left or stopped being public that
  454. user_id (str)
  455. """
  456. logger.debug("Maybe removing user %r", user_id)
  457. row = yield self.store.get_user_in_directory(user_id)
  458. update_user_dir = row and row["room_id"] == room_id
  459. row = yield self.store.get_user_in_public_room(user_id)
  460. update_user_in_public = row and row["room_id"] == room_id
  461. if (update_user_in_public or update_user_dir):
  462. # XXX: Make this faster?
  463. rooms = yield self.store.get_rooms_for_user(user_id)
  464. for j_room_id in rooms:
  465. if (not update_user_in_public and not update_user_dir):
  466. break
  467. is_in_room = yield self.store.is_host_joined(
  468. j_room_id, self.server_name,
  469. )
  470. if not is_in_room:
  471. continue
  472. if update_user_dir:
  473. update_user_dir = False
  474. yield self.store.update_user_in_user_dir(user_id, j_room_id)
  475. is_public = yield self.store.is_room_world_readable_or_publicly_joinable(
  476. j_room_id
  477. )
  478. if update_user_in_public and is_public:
  479. yield self.store.update_user_in_public_user_list(user_id, j_room_id)
  480. update_user_in_public = False
  481. if update_user_dir:
  482. yield self.store.remove_from_user_dir(user_id)
  483. elif update_user_in_public:
  484. yield self.store.remove_from_user_in_public_room(user_id)
  485. # Now handle users_who_share_rooms.
  486. # Get a list of user tuples that were in the DB due to this room and
  487. # users (this includes tuples where the other user matches `user_id`)
  488. user_tuples = yield self.store.get_users_in_share_dir_with_room_id(
  489. user_id, room_id,
  490. )
  491. for user_id, other_user_id in user_tuples:
  492. # For each user tuple get a list of rooms that they still share,
  493. # trying to find a private room, and update the entry in the DB
  494. rooms = yield self.store.get_rooms_in_common_for_users(user_id, other_user_id)
  495. # If they dont share a room anymore, remove the mapping
  496. if not rooms:
  497. yield self.store.remove_user_who_share_room(
  498. user_id, other_user_id,
  499. )
  500. continue
  501. found_public_share = None
  502. for j_room_id in rooms:
  503. is_public = yield self.store.is_room_world_readable_or_publicly_joinable(
  504. j_room_id
  505. )
  506. if is_public:
  507. found_public_share = j_room_id
  508. else:
  509. found_public_share = None
  510. yield self.store.update_users_who_share_room(
  511. room_id, not is_public, [(user_id, other_user_id)],
  512. )
  513. break
  514. if found_public_share:
  515. yield self.store.update_users_who_share_room(
  516. room_id, not is_public, [(user_id, other_user_id)],
  517. )
  518. @defer.inlineCallbacks
  519. def _handle_profile_change(self, user_id, room_id, prev_event_id, event_id):
  520. """Check member event changes for any profile changes and update the
  521. database if there are.
  522. """
  523. if not prev_event_id or not event_id:
  524. return
  525. prev_event = yield self.store.get_event(prev_event_id, allow_none=True)
  526. event = yield self.store.get_event(event_id, allow_none=True)
  527. if not prev_event or not event:
  528. return
  529. if event.membership != Membership.JOIN:
  530. return
  531. prev_name = prev_event.content.get("displayname")
  532. new_name = event.content.get("displayname")
  533. prev_avatar = prev_event.content.get("avatar_url")
  534. new_avatar = event.content.get("avatar_url")
  535. if prev_name != new_name or prev_avatar != new_avatar:
  536. yield self.store.update_profile_in_user_dir(
  537. user_id, new_name, new_avatar, room_id,
  538. )
  539. @defer.inlineCallbacks
  540. def _get_key_change(self, prev_event_id, event_id, key_name, public_value):
  541. """Given two events check if the `key_name` field in content changed
  542. from not matching `public_value` to doing so.
  543. For example, check if `history_visibility` (`key_name`) changed from
  544. `shared` to `world_readable` (`public_value`).
  545. Returns:
  546. None if the field in the events either both match `public_value`
  547. or if neither do, i.e. there has been no change.
  548. True if it didnt match `public_value` but now does
  549. False if it did match `public_value` but now doesn't
  550. """
  551. prev_event = None
  552. event = None
  553. if prev_event_id:
  554. prev_event = yield self.store.get_event(prev_event_id, allow_none=True)
  555. if event_id:
  556. event = yield self.store.get_event(event_id, allow_none=True)
  557. if not event and not prev_event:
  558. logger.debug("Neither event exists: %r %r", prev_event_id, event_id)
  559. defer.returnValue(None)
  560. prev_value = None
  561. value = None
  562. if prev_event:
  563. prev_value = prev_event.content.get(key_name)
  564. if event:
  565. value = event.content.get(key_name)
  566. logger.debug("prev_value: %r -> value: %r", prev_value, value)
  567. if value == public_value and prev_value != public_value:
  568. defer.returnValue(True)
  569. elif value != public_value and prev_value == public_value:
  570. defer.returnValue(False)
  571. else:
  572. defer.returnValue(None)