presence.py 50 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360
  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. """This module is responsible for keeping track of presence status of local
  16. and remote users.
  17. The methods that define policy are:
  18. - PresenceHandler._update_states
  19. - PresenceHandler._handle_timeouts
  20. - should_notify
  21. """
  22. from twisted.internet import defer, reactor
  23. from contextlib import contextmanager
  24. from synapse.api.errors import SynapseError
  25. from synapse.api.constants import PresenceState
  26. from synapse.storage.presence import UserPresenceState
  27. from synapse.util.caches.descriptors import cachedInlineCallbacks
  28. from synapse.util.async import Linearizer
  29. from synapse.util.logcontext import preserve_fn
  30. from synapse.util.logutils import log_function
  31. from synapse.util.metrics import Measure
  32. from synapse.util.wheel_timer import WheelTimer
  33. from synapse.types import UserID, get_domain_from_id
  34. import synapse.metrics
  35. import logging
  36. logger = logging.getLogger(__name__)
  37. metrics = synapse.metrics.get_metrics_for(__name__)
  38. notified_presence_counter = metrics.register_counter("notified_presence")
  39. federation_presence_out_counter = metrics.register_counter("federation_presence_out")
  40. presence_updates_counter = metrics.register_counter("presence_updates")
  41. timers_fired_counter = metrics.register_counter("timers_fired")
  42. federation_presence_counter = metrics.register_counter("federation_presence")
  43. bump_active_time_counter = metrics.register_counter("bump_active_time")
  44. get_updates_counter = metrics.register_counter("get_updates", labels=["type"])
  45. notify_reason_counter = metrics.register_counter("notify_reason", labels=["reason"])
  46. state_transition_counter = metrics.register_counter(
  47. "state_transition", labels=["from", "to"]
  48. )
  49. # If a user was last active in the last LAST_ACTIVE_GRANULARITY, consider them
  50. # "currently_active"
  51. LAST_ACTIVE_GRANULARITY = 60 * 1000
  52. # How long to wait until a new /events or /sync request before assuming
  53. # the client has gone.
  54. SYNC_ONLINE_TIMEOUT = 30 * 1000
  55. # How long to wait before marking the user as idle. Compared against last active
  56. IDLE_TIMER = 5 * 60 * 1000
  57. # How often we expect remote servers to resend us presence.
  58. FEDERATION_TIMEOUT = 30 * 60 * 1000
  59. # How often to resend presence to remote servers
  60. FEDERATION_PING_INTERVAL = 25 * 60 * 1000
  61. # How long we will wait before assuming that the syncs from an external process
  62. # are dead.
  63. EXTERNAL_PROCESS_EXPIRY = 5 * 60 * 1000
  64. assert LAST_ACTIVE_GRANULARITY < IDLE_TIMER
  65. class PresenceHandler(object):
  66. def __init__(self, hs):
  67. self.is_mine = hs.is_mine
  68. self.is_mine_id = hs.is_mine_id
  69. self.clock = hs.get_clock()
  70. self.store = hs.get_datastore()
  71. self.wheel_timer = WheelTimer()
  72. self.notifier = hs.get_notifier()
  73. self.replication = hs.get_replication_layer()
  74. self.federation = hs.get_federation_sender()
  75. self.state = hs.get_state_handler()
  76. self.replication.register_edu_handler(
  77. "m.presence", self.incoming_presence
  78. )
  79. self.replication.register_edu_handler(
  80. "m.presence_invite",
  81. lambda origin, content: self.invite_presence(
  82. observed_user=UserID.from_string(content["observed_user"]),
  83. observer_user=UserID.from_string(content["observer_user"]),
  84. )
  85. )
  86. self.replication.register_edu_handler(
  87. "m.presence_accept",
  88. lambda origin, content: self.accept_presence(
  89. observed_user=UserID.from_string(content["observed_user"]),
  90. observer_user=UserID.from_string(content["observer_user"]),
  91. )
  92. )
  93. self.replication.register_edu_handler(
  94. "m.presence_deny",
  95. lambda origin, content: self.deny_presence(
  96. observed_user=UserID.from_string(content["observed_user"]),
  97. observer_user=UserID.from_string(content["observer_user"]),
  98. )
  99. )
  100. distributor = hs.get_distributor()
  101. distributor.observe("user_joined_room", self.user_joined_room)
  102. active_presence = self.store.take_presence_startup_info()
  103. # A dictionary of the current state of users. This is prefilled with
  104. # non-offline presence from the DB. We should fetch from the DB if
  105. # we can't find a users presence in here.
  106. self.user_to_current_state = {
  107. state.user_id: state
  108. for state in active_presence
  109. }
  110. metrics.register_callback(
  111. "user_to_current_state_size", lambda: len(self.user_to_current_state)
  112. )
  113. now = self.clock.time_msec()
  114. for state in active_presence:
  115. self.wheel_timer.insert(
  116. now=now,
  117. obj=state.user_id,
  118. then=state.last_active_ts + IDLE_TIMER,
  119. )
  120. self.wheel_timer.insert(
  121. now=now,
  122. obj=state.user_id,
  123. then=state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT,
  124. )
  125. if self.is_mine_id(state.user_id):
  126. self.wheel_timer.insert(
  127. now=now,
  128. obj=state.user_id,
  129. then=state.last_federation_update_ts + FEDERATION_PING_INTERVAL,
  130. )
  131. else:
  132. self.wheel_timer.insert(
  133. now=now,
  134. obj=state.user_id,
  135. then=state.last_federation_update_ts + FEDERATION_TIMEOUT,
  136. )
  137. # Set of users who have presence in the `user_to_current_state` that
  138. # have not yet been persisted
  139. self.unpersisted_users_changes = set()
  140. reactor.addSystemEventTrigger("before", "shutdown", self._on_shutdown)
  141. self.serial_to_user = {}
  142. self._next_serial = 1
  143. # Keeps track of the number of *ongoing* syncs on this process. While
  144. # this is non zero a user will never go offline.
  145. self.user_to_num_current_syncs = {}
  146. # Keeps track of the number of *ongoing* syncs on other processes.
  147. # While any sync is ongoing on another process the user will never
  148. # go offline.
  149. # Each process has a unique identifier and an update frequency. If
  150. # no update is received from that process within the update period then
  151. # we assume that all the sync requests on that process have stopped.
  152. # Stored as a dict from process_id to set of user_id, and a dict of
  153. # process_id to millisecond timestamp last updated.
  154. self.external_process_to_current_syncs = {}
  155. self.external_process_last_updated_ms = {}
  156. self.external_sync_linearizer = Linearizer(name="external_sync_linearizer")
  157. # Start a LoopingCall in 30s that fires every 5s.
  158. # The initial delay is to allow disconnected clients a chance to
  159. # reconnect before we treat them as offline.
  160. self.clock.call_later(
  161. 30,
  162. self.clock.looping_call,
  163. self._handle_timeouts,
  164. 5000,
  165. )
  166. self.clock.call_later(
  167. 60,
  168. self.clock.looping_call,
  169. self._persist_unpersisted_changes,
  170. 60 * 1000,
  171. )
  172. metrics.register_callback("wheel_timer_size", lambda: len(self.wheel_timer))
  173. @defer.inlineCallbacks
  174. def _on_shutdown(self):
  175. """Gets called when shutting down. This lets us persist any updates that
  176. we haven't yet persisted, e.g. updates that only changes some internal
  177. timers. This allows changes to persist across startup without having to
  178. persist every single change.
  179. If this does not run it simply means that some of the timers will fire
  180. earlier than they should when synapse is restarted. This affect of this
  181. is some spurious presence changes that will self-correct.
  182. """
  183. logger.info(
  184. "Performing _on_shutdown. Persisting %d unpersisted changes",
  185. len(self.user_to_current_state)
  186. )
  187. if self.unpersisted_users_changes:
  188. yield self.store.update_presence([
  189. self.user_to_current_state[user_id]
  190. for user_id in self.unpersisted_users_changes
  191. ])
  192. logger.info("Finished _on_shutdown")
  193. @defer.inlineCallbacks
  194. def _persist_unpersisted_changes(self):
  195. """We periodically persist the unpersisted changes, as otherwise they
  196. may stack up and slow down shutdown times.
  197. """
  198. logger.info(
  199. "Performing _persist_unpersisted_changes. Persisting %d unpersisted changes",
  200. len(self.unpersisted_users_changes)
  201. )
  202. unpersisted = self.unpersisted_users_changes
  203. self.unpersisted_users_changes = set()
  204. if unpersisted:
  205. yield self.store.update_presence([
  206. self.user_to_current_state[user_id]
  207. for user_id in unpersisted
  208. ])
  209. logger.info("Finished _persist_unpersisted_changes")
  210. @defer.inlineCallbacks
  211. def _update_states(self, new_states):
  212. """Updates presence of users. Sets the appropriate timeouts. Pokes
  213. the notifier and federation if and only if the changed presence state
  214. should be sent to clients/servers.
  215. """
  216. now = self.clock.time_msec()
  217. with Measure(self.clock, "presence_update_states"):
  218. # NOTE: We purposefully don't yield between now and when we've
  219. # calculated what we want to do with the new states, to avoid races.
  220. to_notify = {} # Changes we want to notify everyone about
  221. to_federation_ping = {} # These need sending keep-alives
  222. # Only bother handling the last presence change for each user
  223. new_states_dict = {}
  224. for new_state in new_states:
  225. new_states_dict[new_state.user_id] = new_state
  226. new_state = new_states_dict.values()
  227. for new_state in new_states:
  228. user_id = new_state.user_id
  229. # Its fine to not hit the database here, as the only thing not in
  230. # the current state cache are OFFLINE states, where the only field
  231. # of interest is last_active which is safe enough to assume is 0
  232. # here.
  233. prev_state = self.user_to_current_state.get(
  234. user_id, UserPresenceState.default(user_id)
  235. )
  236. new_state, should_notify, should_ping = handle_update(
  237. prev_state, new_state,
  238. is_mine=self.is_mine_id(user_id),
  239. wheel_timer=self.wheel_timer,
  240. now=now
  241. )
  242. self.user_to_current_state[user_id] = new_state
  243. if should_notify:
  244. to_notify[user_id] = new_state
  245. elif should_ping:
  246. to_federation_ping[user_id] = new_state
  247. # TODO: We should probably ensure there are no races hereafter
  248. presence_updates_counter.inc_by(len(new_states))
  249. if to_notify:
  250. notified_presence_counter.inc_by(len(to_notify))
  251. yield self._persist_and_notify(to_notify.values())
  252. self.unpersisted_users_changes |= set(s.user_id for s in new_states)
  253. self.unpersisted_users_changes -= set(to_notify.keys())
  254. to_federation_ping = {
  255. user_id: state for user_id, state in to_federation_ping.items()
  256. if user_id not in to_notify
  257. }
  258. if to_federation_ping:
  259. federation_presence_out_counter.inc_by(len(to_federation_ping))
  260. self._push_to_remotes(to_federation_ping.values())
  261. def _handle_timeouts(self):
  262. """Checks the presence of users that have timed out and updates as
  263. appropriate.
  264. """
  265. logger.info("Handling presence timeouts")
  266. now = self.clock.time_msec()
  267. try:
  268. with Measure(self.clock, "presence_handle_timeouts"):
  269. # Fetch the list of users that *may* have timed out. Things may have
  270. # changed since the timeout was set, so we won't necessarily have to
  271. # take any action.
  272. users_to_check = set(self.wheel_timer.fetch(now))
  273. # Check whether the lists of syncing processes from an external
  274. # process have expired.
  275. expired_process_ids = [
  276. process_id for process_id, last_update
  277. in self.external_process_last_updated_ms.items()
  278. if now - last_update > EXTERNAL_PROCESS_EXPIRY
  279. ]
  280. for process_id in expired_process_ids:
  281. users_to_check.update(
  282. self.external_process_last_updated_ms.pop(process_id, ())
  283. )
  284. self.external_process_last_update.pop(process_id)
  285. states = [
  286. self.user_to_current_state.get(
  287. user_id, UserPresenceState.default(user_id)
  288. )
  289. for user_id in users_to_check
  290. ]
  291. timers_fired_counter.inc_by(len(states))
  292. changes = handle_timeouts(
  293. states,
  294. is_mine_fn=self.is_mine_id,
  295. syncing_user_ids=self.get_currently_syncing_users(),
  296. now=now,
  297. )
  298. preserve_fn(self._update_states)(changes)
  299. except Exception:
  300. logger.exception("Exception in _handle_timeouts loop")
  301. @defer.inlineCallbacks
  302. def bump_presence_active_time(self, user):
  303. """We've seen the user do something that indicates they're interacting
  304. with the app.
  305. """
  306. return
  307. user_id = user.to_string()
  308. bump_active_time_counter.inc()
  309. prev_state = yield self.current_state_for_user(user_id)
  310. new_fields = {
  311. "last_active_ts": self.clock.time_msec(),
  312. }
  313. if prev_state.state == PresenceState.UNAVAILABLE:
  314. new_fields["state"] = PresenceState.ONLINE
  315. yield self._update_states([prev_state.copy_and_replace(**new_fields)])
  316. @defer.inlineCallbacks
  317. def user_syncing(self, user_id, affect_presence=True):
  318. """Returns a context manager that should surround any stream requests
  319. from the user.
  320. This allows us to keep track of who is currently streaming and who isn't
  321. without having to have timers outside of this module to avoid flickering
  322. when users disconnect/reconnect.
  323. Args:
  324. user_id (str)
  325. affect_presence (bool): If false this function will be a no-op.
  326. Useful for streams that are not associated with an actual
  327. client that is being used by a user.
  328. """
  329. affect_presence = False
  330. if affect_presence:
  331. curr_sync = self.user_to_num_current_syncs.get(user_id, 0)
  332. self.user_to_num_current_syncs[user_id] = curr_sync + 1
  333. prev_state = yield self.current_state_for_user(user_id)
  334. if prev_state.state == PresenceState.OFFLINE:
  335. # If they're currently offline then bring them online, otherwise
  336. # just update the last sync times.
  337. yield self._update_states([prev_state.copy_and_replace(
  338. state=PresenceState.ONLINE,
  339. last_active_ts=self.clock.time_msec(),
  340. last_user_sync_ts=self.clock.time_msec(),
  341. )])
  342. else:
  343. yield self._update_states([prev_state.copy_and_replace(
  344. last_user_sync_ts=self.clock.time_msec(),
  345. )])
  346. @defer.inlineCallbacks
  347. def _end():
  348. if affect_presence:
  349. self.user_to_num_current_syncs[user_id] -= 1
  350. prev_state = yield self.current_state_for_user(user_id)
  351. yield self._update_states([prev_state.copy_and_replace(
  352. last_user_sync_ts=self.clock.time_msec(),
  353. )])
  354. @contextmanager
  355. def _user_syncing():
  356. try:
  357. yield
  358. finally:
  359. preserve_fn(_end)()
  360. defer.returnValue(_user_syncing())
  361. def get_currently_syncing_users(self):
  362. """Get the set of user ids that are currently syncing on this HS.
  363. Returns:
  364. set(str): A set of user_id strings.
  365. """
  366. # presence is disabled on matrix.org, so we return the empty set
  367. return set()
  368. syncing_user_ids = {
  369. user_id for user_id, count in self.user_to_num_current_syncs.items()
  370. if count
  371. }
  372. for user_ids in self.external_process_to_current_syncs.values():
  373. syncing_user_ids.update(user_ids)
  374. return syncing_user_ids
  375. @defer.inlineCallbacks
  376. def update_external_syncs(self, process_id, syncing_user_ids):
  377. """Update the syncing users for an external process
  378. Args:
  379. process_id(str): An identifier for the process the users are
  380. syncing against. This allows synapse to process updates
  381. as user start and stop syncing against a given process.
  382. syncing_user_ids(set(str)): The set of user_ids that are
  383. currently syncing on that server.
  384. """
  385. return
  386. # Grab the previous list of user_ids that were syncing on that process
  387. prev_syncing_user_ids = (
  388. self.external_process_to_current_syncs.get(process_id, set())
  389. )
  390. # Grab the current presence state for both the users that are syncing
  391. # now and the users that were syncing before this update.
  392. prev_states = yield self.current_state_for_users(
  393. syncing_user_ids | prev_syncing_user_ids
  394. )
  395. updates = []
  396. time_now_ms = self.clock.time_msec()
  397. # For each new user that is syncing check if we need to mark them as
  398. # being online.
  399. for new_user_id in syncing_user_ids - prev_syncing_user_ids:
  400. prev_state = prev_states[new_user_id]
  401. if prev_state.state == PresenceState.OFFLINE:
  402. updates.append(prev_state.copy_and_replace(
  403. state=PresenceState.ONLINE,
  404. last_active_ts=time_now_ms,
  405. last_user_sync_ts=time_now_ms,
  406. ))
  407. else:
  408. updates.append(prev_state.copy_and_replace(
  409. last_user_sync_ts=time_now_ms,
  410. ))
  411. # For each user that is still syncing or stopped syncing update the
  412. # last sync time so that we will correctly apply the grace period when
  413. # they stop syncing.
  414. for old_user_id in prev_syncing_user_ids:
  415. prev_state = prev_states[old_user_id]
  416. updates.append(prev_state.copy_and_replace(
  417. last_user_sync_ts=time_now_ms,
  418. ))
  419. yield self._update_states(updates)
  420. # Update the last updated time for the process. We expire the entries
  421. # if we don't receive an update in the given timeframe.
  422. self.external_process_last_updated_ms[process_id] = self.clock.time_msec()
  423. self.external_process_to_current_syncs[process_id] = syncing_user_ids
  424. @defer.inlineCallbacks
  425. def update_external_syncs_row(self, process_id, user_id, is_syncing, sync_time_msec):
  426. """Update the syncing users for an external process as a delta.
  427. Args:
  428. process_id (str): An identifier for the process the users are
  429. syncing against. This allows synapse to process updates
  430. as user start and stop syncing against a given process.
  431. user_id (str): The user who has started or stopped syncing
  432. is_syncing (bool): Whether or not the user is now syncing
  433. sync_time_msec(int): Time in ms when the user was last syncing
  434. """
  435. with (yield self.external_sync_linearizer.queue(process_id)):
  436. prev_state = yield self.current_state_for_user(user_id)
  437. process_presence = self.external_process_to_current_syncs.setdefault(
  438. process_id, set()
  439. )
  440. updates = []
  441. if is_syncing and user_id not in process_presence:
  442. if prev_state.state == PresenceState.OFFLINE:
  443. updates.append(prev_state.copy_and_replace(
  444. state=PresenceState.ONLINE,
  445. last_active_ts=sync_time_msec,
  446. last_user_sync_ts=sync_time_msec,
  447. ))
  448. else:
  449. updates.append(prev_state.copy_and_replace(
  450. last_user_sync_ts=sync_time_msec,
  451. ))
  452. process_presence.add(user_id)
  453. elif user_id in process_presence:
  454. updates.append(prev_state.copy_and_replace(
  455. last_user_sync_ts=sync_time_msec,
  456. ))
  457. if not is_syncing:
  458. process_presence.discard(user_id)
  459. if updates:
  460. yield self._update_states(updates)
  461. self.external_process_last_updated_ms[process_id] = self.clock.time_msec()
  462. @defer.inlineCallbacks
  463. def update_external_syncs_clear(self, process_id):
  464. """Marks all users that had been marked as syncing by a given process
  465. as offline.
  466. Used when the process has stopped/disappeared.
  467. """
  468. with (yield self.external_sync_linearizer.queue(process_id)):
  469. process_presence = self.external_process_to_current_syncs.pop(
  470. process_id, set()
  471. )
  472. prev_states = yield self.current_state_for_users(process_presence)
  473. time_now_ms = self.clock.time_msec()
  474. yield self._update_states([
  475. prev_state.copy_and_replace(
  476. last_user_sync_ts=time_now_ms,
  477. )
  478. for prev_state in prev_states.itervalues()
  479. ])
  480. self.external_process_last_updated_ms.pop(process_id, None)
  481. @defer.inlineCallbacks
  482. def current_state_for_user(self, user_id):
  483. """Get the current presence state for a user.
  484. """
  485. res = yield self.current_state_for_users([user_id])
  486. defer.returnValue(res[user_id])
  487. @defer.inlineCallbacks
  488. def current_state_for_users(self, user_ids):
  489. """Get the current presence state for multiple users.
  490. Returns:
  491. dict: `user_id` -> `UserPresenceState`
  492. """
  493. states = {
  494. user_id: self.user_to_current_state.get(user_id, None)
  495. for user_id in user_ids
  496. }
  497. missing = [user_id for user_id, state in states.iteritems() if not state]
  498. if missing:
  499. # There are things not in our in memory cache. Lets pull them out of
  500. # the database.
  501. res = yield self.store.get_presence_for_users(missing)
  502. states.update(res)
  503. missing = [user_id for user_id, state in states.iteritems() if not state]
  504. if missing:
  505. new = {
  506. user_id: UserPresenceState.default(user_id)
  507. for user_id in missing
  508. }
  509. states.update(new)
  510. self.user_to_current_state.update(new)
  511. defer.returnValue(states)
  512. @defer.inlineCallbacks
  513. def _persist_and_notify(self, states):
  514. """Persist states in the database, poke the notifier and send to
  515. interested remote servers
  516. """
  517. stream_id, max_token = yield self.store.update_presence(states)
  518. parties = yield get_interested_parties(self.store, states)
  519. room_ids_to_states, users_to_states = parties
  520. self.notifier.on_new_event(
  521. "presence_key", stream_id, rooms=room_ids_to_states.keys(),
  522. users=[UserID.from_string(u) for u in users_to_states]
  523. )
  524. self._push_to_remotes(states)
  525. @defer.inlineCallbacks
  526. def notify_for_states(self, state, stream_id):
  527. parties = yield get_interested_parties(self.store, [state])
  528. room_ids_to_states, users_to_states = parties
  529. self.notifier.on_new_event(
  530. "presence_key", stream_id, rooms=room_ids_to_states.keys(),
  531. users=[UserID.from_string(u) for u in users_to_states]
  532. )
  533. def _push_to_remotes(self, states):
  534. """Sends state updates to remote servers.
  535. Args:
  536. states (list(UserPresenceState))
  537. """
  538. self.federation.send_presence(states)
  539. @defer.inlineCallbacks
  540. def incoming_presence(self, origin, content):
  541. """Called when we receive a `m.presence` EDU from a remote server.
  542. """
  543. now = self.clock.time_msec()
  544. updates = []
  545. for push in content.get("push", []):
  546. # A "push" contains a list of presence that we are probably interested
  547. # in.
  548. # TODO: Actually check if we're interested, rather than blindly
  549. # accepting presence updates.
  550. user_id = push.get("user_id", None)
  551. if not user_id:
  552. logger.info(
  553. "Got presence update from %r with no 'user_id': %r",
  554. origin, push,
  555. )
  556. continue
  557. if get_domain_from_id(user_id) != origin:
  558. logger.info(
  559. "Got presence update from %r with bad 'user_id': %r",
  560. origin, user_id,
  561. )
  562. continue
  563. presence_state = push.get("presence", None)
  564. if not presence_state:
  565. logger.info(
  566. "Got presence update from %r with no 'presence_state': %r",
  567. origin, push,
  568. )
  569. continue
  570. new_fields = {
  571. "state": presence_state,
  572. "last_federation_update_ts": now,
  573. }
  574. last_active_ago = push.get("last_active_ago", None)
  575. if last_active_ago is not None:
  576. new_fields["last_active_ts"] = now - last_active_ago
  577. new_fields["status_msg"] = push.get("status_msg", None)
  578. new_fields["currently_active"] = push.get("currently_active", False)
  579. prev_state = yield self.current_state_for_user(user_id)
  580. updates.append(prev_state.copy_and_replace(**new_fields))
  581. if updates:
  582. federation_presence_counter.inc_by(len(updates))
  583. yield self._update_states(updates)
  584. @defer.inlineCallbacks
  585. def get_state(self, target_user, as_event=False):
  586. results = yield self.get_states(
  587. [target_user.to_string()],
  588. as_event=as_event,
  589. )
  590. defer.returnValue(results[0])
  591. @defer.inlineCallbacks
  592. def get_states(self, target_user_ids, as_event=False):
  593. """Get the presence state for users.
  594. Args:
  595. target_user_ids (list)
  596. as_event (bool): Whether to format it as a client event or not.
  597. Returns:
  598. list
  599. """
  600. updates = yield self.current_state_for_users(target_user_ids)
  601. updates = updates.values()
  602. for user_id in set(target_user_ids) - set(u.user_id for u in updates):
  603. updates.append(UserPresenceState.default(user_id))
  604. now = self.clock.time_msec()
  605. if as_event:
  606. defer.returnValue([
  607. {
  608. "type": "m.presence",
  609. "content": format_user_presence_state(state, now),
  610. }
  611. for state in updates
  612. ])
  613. else:
  614. defer.returnValue(updates)
  615. @defer.inlineCallbacks
  616. def set_state(self, target_user, state, ignore_status_msg=False):
  617. """Set the presence state of the user.
  618. """
  619. status_msg = state.get("status_msg", None)
  620. presence = state["presence"]
  621. valid_presence = (
  622. PresenceState.ONLINE, PresenceState.UNAVAILABLE, PresenceState.OFFLINE
  623. )
  624. if presence not in valid_presence:
  625. raise SynapseError(400, "Invalid presence state")
  626. user_id = target_user.to_string()
  627. prev_state = yield self.current_state_for_user(user_id)
  628. new_fields = {
  629. "state": presence
  630. }
  631. if not ignore_status_msg:
  632. msg = status_msg if presence != PresenceState.OFFLINE else None
  633. new_fields["status_msg"] = msg
  634. if presence == PresenceState.ONLINE:
  635. new_fields["last_active_ts"] = self.clock.time_msec()
  636. yield self._update_states([prev_state.copy_and_replace(**new_fields)])
  637. @defer.inlineCallbacks
  638. def user_joined_room(self, user, room_id):
  639. """Called (via the distributor) when a user joins a room. This funciton
  640. sends presence updates to servers, either:
  641. 1. the joining user is a local user and we send their presence to
  642. all servers in the room.
  643. 2. the joining user is a remote user and so we send presence for all
  644. local users in the room.
  645. """
  646. # We only need to send presence to servers that don't have it yet. We
  647. # don't need to send to local clients here, as that is done as part
  648. # of the event stream/sync.
  649. # TODO: Only send to servers not already in the room.
  650. if self.is_mine(user):
  651. state = yield self.current_state_for_user(user.to_string())
  652. self._push_to_remotes([state])
  653. else:
  654. user_ids = yield self.store.get_users_in_room(room_id)
  655. user_ids = filter(self.is_mine_id, user_ids)
  656. states = yield self.current_state_for_users(user_ids)
  657. self._push_to_remotes(states.values())
  658. @defer.inlineCallbacks
  659. def get_presence_list(self, observer_user, accepted=None):
  660. """Returns the presence for all users in their presence list.
  661. """
  662. if not self.is_mine(observer_user):
  663. raise SynapseError(400, "User is not hosted on this Home Server")
  664. presence_list = yield self.store.get_presence_list(
  665. observer_user.localpart, accepted=accepted
  666. )
  667. results = yield self.get_states(
  668. target_user_ids=[row["observed_user_id"] for row in presence_list],
  669. as_event=False,
  670. )
  671. now = self.clock.time_msec()
  672. results[:] = [format_user_presence_state(r, now) for r in results]
  673. is_accepted = {
  674. row["observed_user_id"]: row["accepted"] for row in presence_list
  675. }
  676. for result in results:
  677. result.update({
  678. "accepted": is_accepted,
  679. })
  680. defer.returnValue(results)
  681. @defer.inlineCallbacks
  682. def send_presence_invite(self, observer_user, observed_user):
  683. """Sends a presence invite.
  684. """
  685. yield self.store.add_presence_list_pending(
  686. observer_user.localpart, observed_user.to_string()
  687. )
  688. if self.is_mine(observed_user):
  689. yield self.invite_presence(observed_user, observer_user)
  690. else:
  691. yield self.federation.send_edu(
  692. destination=observed_user.domain,
  693. edu_type="m.presence_invite",
  694. content={
  695. "observed_user": observed_user.to_string(),
  696. "observer_user": observer_user.to_string(),
  697. }
  698. )
  699. @defer.inlineCallbacks
  700. def invite_presence(self, observed_user, observer_user):
  701. """Handles new presence invites.
  702. """
  703. if not self.is_mine(observed_user):
  704. raise SynapseError(400, "User is not hosted on this Home Server")
  705. # TODO: Don't auto accept
  706. if self.is_mine(observer_user):
  707. yield self.accept_presence(observed_user, observer_user)
  708. else:
  709. self.federation.send_edu(
  710. destination=observer_user.domain,
  711. edu_type="m.presence_accept",
  712. content={
  713. "observed_user": observed_user.to_string(),
  714. "observer_user": observer_user.to_string(),
  715. }
  716. )
  717. state_dict = yield self.get_state(observed_user, as_event=False)
  718. state_dict = format_user_presence_state(state_dict, self.clock.time_msec())
  719. self.federation.send_edu(
  720. destination=observer_user.domain,
  721. edu_type="m.presence",
  722. content={
  723. "push": [state_dict]
  724. }
  725. )
  726. @defer.inlineCallbacks
  727. def accept_presence(self, observed_user, observer_user):
  728. """Handles a m.presence_accept EDU. Mark a presence invite from a
  729. local or remote user as accepted in a local user's presence list.
  730. Starts polling for presence updates from the local or remote user.
  731. Args:
  732. observed_user(UserID): The user to update in the presence list.
  733. observer_user(UserID): The owner of the presence list to update.
  734. """
  735. yield self.store.set_presence_list_accepted(
  736. observer_user.localpart, observed_user.to_string()
  737. )
  738. @defer.inlineCallbacks
  739. def deny_presence(self, observed_user, observer_user):
  740. """Handle a m.presence_deny EDU. Removes a local or remote user from a
  741. local user's presence list.
  742. Args:
  743. observed_user(UserID): The local or remote user to remove from the
  744. list.
  745. observer_user(UserID): The local owner of the presence list.
  746. Returns:
  747. A Deferred.
  748. """
  749. yield self.store.del_presence_list(
  750. observer_user.localpart, observed_user.to_string()
  751. )
  752. # TODO(paul): Inform the user somehow?
  753. @defer.inlineCallbacks
  754. def drop(self, observed_user, observer_user):
  755. """Remove a local or remote user from a local user's presence list and
  756. unsubscribe the local user from updates that user.
  757. Args:
  758. observed_user(UserId): The local or remote user to remove from the
  759. list.
  760. observer_user(UserId): The local owner of the presence list.
  761. Returns:
  762. A Deferred.
  763. """
  764. if not self.is_mine(observer_user):
  765. raise SynapseError(400, "User is not hosted on this Home Server")
  766. yield self.store.del_presence_list(
  767. observer_user.localpart, observed_user.to_string()
  768. )
  769. # TODO: Inform the remote that we've dropped the presence list.
  770. @defer.inlineCallbacks
  771. def is_visible(self, observed_user, observer_user):
  772. """Returns whether a user can see another user's presence.
  773. """
  774. observer_room_ids = yield self.store.get_rooms_for_user(
  775. observer_user.to_string()
  776. )
  777. observed_room_ids = yield self.store.get_rooms_for_user(
  778. observed_user.to_string()
  779. )
  780. if observer_room_ids & observed_room_ids:
  781. defer.returnValue(True)
  782. accepted_observers = yield self.store.get_presence_list_observers_accepted(
  783. observed_user.to_string()
  784. )
  785. defer.returnValue(observer_user.to_string() in accepted_observers)
  786. @defer.inlineCallbacks
  787. def get_all_presence_updates(self, last_id, current_id):
  788. """
  789. Gets a list of presence update rows from between the given stream ids.
  790. Each row has:
  791. - stream_id(str)
  792. - user_id(str)
  793. - state(str)
  794. - last_active_ts(int)
  795. - last_federation_update_ts(int)
  796. - last_user_sync_ts(int)
  797. - status_msg(int)
  798. - currently_active(int)
  799. """
  800. # TODO(markjh): replicate the unpersisted changes.
  801. # This could use the in-memory stores for recent changes.
  802. rows = yield self.store.get_all_presence_updates(last_id, current_id)
  803. defer.returnValue(rows)
  804. def should_notify(old_state, new_state):
  805. """Decides if a presence state change should be sent to interested parties.
  806. """
  807. if old_state == new_state:
  808. return False
  809. if old_state.status_msg != new_state.status_msg:
  810. notify_reason_counter.inc("status_msg_change")
  811. return True
  812. if old_state.state != new_state.state:
  813. notify_reason_counter.inc("state_change")
  814. state_transition_counter.inc(old_state.state, new_state.state)
  815. return True
  816. if old_state.state == PresenceState.ONLINE:
  817. if new_state.currently_active != old_state.currently_active:
  818. notify_reason_counter.inc("current_active_change")
  819. return True
  820. if new_state.last_active_ts - old_state.last_active_ts > LAST_ACTIVE_GRANULARITY:
  821. # Only notify about last active bumps if we're not currently acive
  822. if not new_state.currently_active:
  823. notify_reason_counter.inc("last_active_change_online")
  824. return True
  825. elif new_state.last_active_ts - old_state.last_active_ts > LAST_ACTIVE_GRANULARITY:
  826. # Always notify for a transition where last active gets bumped.
  827. notify_reason_counter.inc("last_active_change_not_online")
  828. return True
  829. return False
  830. def format_user_presence_state(state, now, include_user_id=True):
  831. """Convert UserPresenceState to a format that can be sent down to clients
  832. and to other servers.
  833. The "user_id" is optional so that this function can be used to format presence
  834. updates for client /sync responses and for federation /send requests.
  835. """
  836. content = {
  837. "presence": state.state,
  838. }
  839. if include_user_id:
  840. content["user_id"] = state.user_id
  841. if state.last_active_ts:
  842. content["last_active_ago"] = now - state.last_active_ts
  843. if state.status_msg and state.state != PresenceState.OFFLINE:
  844. content["status_msg"] = state.status_msg
  845. if state.state == PresenceState.ONLINE:
  846. content["currently_active"] = state.currently_active
  847. return content
  848. class PresenceEventSource(object):
  849. def __init__(self, hs):
  850. # We can't call get_presence_handler here because there's a cycle:
  851. #
  852. # Presence -> Notifier -> PresenceEventSource -> Presence
  853. #
  854. self.get_presence_handler = hs.get_presence_handler
  855. self.clock = hs.get_clock()
  856. self.store = hs.get_datastore()
  857. self.state = hs.get_state_handler()
  858. @defer.inlineCallbacks
  859. @log_function
  860. def get_new_events(self, user, from_key, room_ids=None, include_offline=True,
  861. explicit_room_id=None, **kwargs):
  862. # The process for getting presence events are:
  863. # 1. Get the rooms the user is in.
  864. # 2. Get the list of user in the rooms.
  865. # 3. Get the list of users that are in the user's presence list.
  866. # 4. If there is a from_key set, cross reference the list of users
  867. # with the `presence_stream_cache` to see which ones we actually
  868. # need to check.
  869. # 5. Load current state for the users.
  870. #
  871. # We don't try and limit the presence updates by the current token, as
  872. # sending down the rare duplicate is not a concern.
  873. with Measure(self.clock, "presence.get_new_events"):
  874. if from_key is not None:
  875. from_key = int(from_key)
  876. presence = self.get_presence_handler()
  877. stream_change_cache = self.store.presence_stream_cache
  878. max_token = self.store.get_current_presence_token()
  879. users_interested_in = yield self._get_interested_in(user, explicit_room_id)
  880. user_ids_changed = set()
  881. changed = None
  882. if from_key:
  883. changed = stream_change_cache.get_all_entities_changed(from_key)
  884. if changed is not None and len(changed) < 500:
  885. # For small deltas, its quicker to get all changes and then
  886. # work out if we share a room or they're in our presence list
  887. get_updates_counter.inc("stream")
  888. for other_user_id in changed:
  889. if other_user_id in users_interested_in:
  890. user_ids_changed.add(other_user_id)
  891. else:
  892. # Too many possible updates. Find all users we can see and check
  893. # if any of them have changed.
  894. get_updates_counter.inc("full")
  895. if from_key:
  896. user_ids_changed = stream_change_cache.get_entities_changed(
  897. users_interested_in, from_key,
  898. )
  899. else:
  900. user_ids_changed = users_interested_in
  901. updates = yield presence.current_state_for_users(user_ids_changed)
  902. if include_offline:
  903. defer.returnValue((updates.values(), max_token))
  904. else:
  905. defer.returnValue(([
  906. s for s in updates.itervalues()
  907. if s.state != PresenceState.OFFLINE
  908. ], max_token))
  909. def get_current_key(self):
  910. return self.store.get_current_presence_token()
  911. def get_pagination_rows(self, user, pagination_config, key):
  912. return self.get_new_events(user, from_key=None, include_offline=False)
  913. @cachedInlineCallbacks(num_args=2, cache_context=True)
  914. def _get_interested_in(self, user, explicit_room_id, cache_context):
  915. """Returns the set of users that the given user should see presence
  916. updates for
  917. """
  918. user_id = user.to_string()
  919. plist = yield self.store.get_presence_list_accepted(
  920. user.localpart, on_invalidate=cache_context.invalidate,
  921. )
  922. users_interested_in = set(row["observed_user_id"] for row in plist)
  923. users_interested_in.add(user_id) # So that we receive our own presence
  924. users_who_share_room = yield self.store.get_users_who_share_room_with_user(
  925. user_id, on_invalidate=cache_context.invalidate,
  926. )
  927. users_interested_in.update(users_who_share_room)
  928. if explicit_room_id:
  929. user_ids = yield self.store.get_users_in_room(
  930. explicit_room_id, on_invalidate=cache_context.invalidate,
  931. )
  932. users_interested_in.update(user_ids)
  933. defer.returnValue(users_interested_in)
  934. def handle_timeouts(user_states, is_mine_fn, syncing_user_ids, now):
  935. """Checks the presence of users that have timed out and updates as
  936. appropriate.
  937. Args:
  938. user_states(list): List of UserPresenceState's to check.
  939. is_mine_fn (fn): Function that returns if a user_id is ours
  940. syncing_user_ids (set): Set of user_ids with active syncs.
  941. now (int): Current time in ms.
  942. Returns:
  943. List of UserPresenceState updates
  944. """
  945. changes = {} # Actual changes we need to notify people about
  946. for state in user_states:
  947. is_mine = is_mine_fn(state.user_id)
  948. new_state = handle_timeout(state, is_mine, syncing_user_ids, now)
  949. if new_state:
  950. changes[state.user_id] = new_state
  951. return changes.values()
  952. def handle_timeout(state, is_mine, syncing_user_ids, now):
  953. """Checks the presence of the user to see if any of the timers have elapsed
  954. Args:
  955. state (UserPresenceState)
  956. is_mine (bool): Whether the user is ours
  957. syncing_user_ids (set): Set of user_ids with active syncs.
  958. now (int): Current time in ms.
  959. Returns:
  960. A UserPresenceState update or None if no update.
  961. """
  962. if state.state == PresenceState.OFFLINE:
  963. # No timeouts are associated with offline states.
  964. return None
  965. changed = False
  966. user_id = state.user_id
  967. if is_mine:
  968. if state.state == PresenceState.ONLINE:
  969. if now - state.last_active_ts > IDLE_TIMER:
  970. # Currently online, but last activity ages ago so auto
  971. # idle
  972. state = state.copy_and_replace(
  973. state=PresenceState.UNAVAILABLE,
  974. )
  975. changed = True
  976. elif now - state.last_active_ts > LAST_ACTIVE_GRANULARITY:
  977. # So that we send down a notification that we've
  978. # stopped updating.
  979. changed = True
  980. if now - state.last_federation_update_ts > FEDERATION_PING_INTERVAL:
  981. # Need to send ping to other servers to ensure they don't
  982. # timeout and set us to offline
  983. changed = True
  984. # If there are have been no sync for a while (and none ongoing),
  985. # set presence to offline
  986. if user_id not in syncing_user_ids:
  987. # If the user has done something recently but hasn't synced,
  988. # don't set them as offline.
  989. sync_or_active = max(state.last_user_sync_ts, state.last_active_ts)
  990. if now - sync_or_active > SYNC_ONLINE_TIMEOUT:
  991. state = state.copy_and_replace(
  992. state=PresenceState.OFFLINE,
  993. status_msg=None,
  994. )
  995. changed = True
  996. else:
  997. # We expect to be poked occasionally by the other side.
  998. # This is to protect against forgetful/buggy servers, so that
  999. # no one gets stuck online forever.
  1000. if now - state.last_federation_update_ts > FEDERATION_TIMEOUT:
  1001. # The other side seems to have disappeared.
  1002. state = state.copy_and_replace(
  1003. state=PresenceState.OFFLINE,
  1004. status_msg=None,
  1005. )
  1006. changed = True
  1007. return state if changed else None
  1008. def handle_update(prev_state, new_state, is_mine, wheel_timer, now):
  1009. """Given a presence update:
  1010. 1. Add any appropriate timers.
  1011. 2. Check if we should notify anyone.
  1012. Args:
  1013. prev_state (UserPresenceState)
  1014. new_state (UserPresenceState)
  1015. is_mine (bool): Whether the user is ours
  1016. wheel_timer (WheelTimer)
  1017. now (int): Time now in ms
  1018. Returns:
  1019. 3-tuple: `(new_state, persist_and_notify, federation_ping)` where:
  1020. - new_state: is the state to actually persist
  1021. - persist_and_notify (bool): whether to persist and notify people
  1022. - federation_ping (bool): whether we should send a ping over federation
  1023. """
  1024. user_id = new_state.user_id
  1025. persist_and_notify = False
  1026. federation_ping = False
  1027. # If the users are ours then we want to set up a bunch of timers
  1028. # to time things out.
  1029. if is_mine:
  1030. if new_state.state == PresenceState.ONLINE:
  1031. # Idle timer
  1032. wheel_timer.insert(
  1033. now=now,
  1034. obj=user_id,
  1035. then=new_state.last_active_ts + IDLE_TIMER
  1036. )
  1037. active = now - new_state.last_active_ts < LAST_ACTIVE_GRANULARITY
  1038. new_state = new_state.copy_and_replace(
  1039. currently_active=active,
  1040. )
  1041. if active:
  1042. wheel_timer.insert(
  1043. now=now,
  1044. obj=user_id,
  1045. then=new_state.last_active_ts + LAST_ACTIVE_GRANULARITY
  1046. )
  1047. if new_state.state != PresenceState.OFFLINE:
  1048. # User has stopped syncing
  1049. wheel_timer.insert(
  1050. now=now,
  1051. obj=user_id,
  1052. then=new_state.last_user_sync_ts + SYNC_ONLINE_TIMEOUT
  1053. )
  1054. last_federate = new_state.last_federation_update_ts
  1055. if now - last_federate > FEDERATION_PING_INTERVAL:
  1056. # Been a while since we've poked remote servers
  1057. new_state = new_state.copy_and_replace(
  1058. last_federation_update_ts=now,
  1059. )
  1060. federation_ping = True
  1061. else:
  1062. wheel_timer.insert(
  1063. now=now,
  1064. obj=user_id,
  1065. then=new_state.last_federation_update_ts + FEDERATION_TIMEOUT
  1066. )
  1067. # Check whether the change was something worth notifying about
  1068. if should_notify(prev_state, new_state):
  1069. new_state = new_state.copy_and_replace(
  1070. last_federation_update_ts=now,
  1071. )
  1072. persist_and_notify = True
  1073. return new_state, persist_and_notify, federation_ping
  1074. @defer.inlineCallbacks
  1075. def get_interested_parties(store, states):
  1076. """Given a list of states return which entities (rooms, users)
  1077. are interested in the given states.
  1078. Args:
  1079. states (list(UserPresenceState))
  1080. Returns:
  1081. 2-tuple: `(room_ids_to_states, users_to_states)`,
  1082. with each item being a dict of `entity_name` -> `[UserPresenceState]`
  1083. """
  1084. room_ids_to_states = {}
  1085. users_to_states = {}
  1086. for state in states:
  1087. room_ids = yield store.get_rooms_for_user(state.user_id)
  1088. for room_id in room_ids:
  1089. room_ids_to_states.setdefault(room_id, []).append(state)
  1090. plist = yield store.get_presence_list_observers_accepted(state.user_id)
  1091. for u in plist:
  1092. users_to_states.setdefault(u, []).append(state)
  1093. # Always notify self
  1094. users_to_states.setdefault(state.user_id, []).append(state)
  1095. defer.returnValue((room_ids_to_states, users_to_states))
  1096. @defer.inlineCallbacks
  1097. def get_interested_remotes(store, states, state_handler):
  1098. """Given a list of presence states figure out which remote servers
  1099. should be sent which.
  1100. All the presence states should be for local users only.
  1101. Args:
  1102. store (DataStore)
  1103. states (list(UserPresenceState))
  1104. Returns:
  1105. Deferred list of ([destinations], [UserPresenceState]), where for
  1106. each row the list of UserPresenceState should be sent to each
  1107. destination
  1108. """
  1109. hosts_and_states = []
  1110. # First we look up the rooms each user is in (as well as any explicit
  1111. # subscriptions), then for each distinct room we look up the remote
  1112. # hosts in those rooms.
  1113. room_ids_to_states, users_to_states = yield get_interested_parties(store, states)
  1114. for room_id, states in room_ids_to_states.iteritems():
  1115. hosts = yield state_handler.get_current_hosts_in_room(room_id)
  1116. hosts_and_states.append((hosts, states))
  1117. for user_id, states in users_to_states.iteritems():
  1118. host = get_domain_from_id(user_id)
  1119. hosts_and_states.append(([host], states))
  1120. defer.returnValue(hosts_and_states)