sync.py 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288
  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 synapse.api.constants import Membership, EventTypes
  16. from synapse.util.async import concurrently_execute
  17. from synapse.util.logcontext import LoggingContext
  18. from synapse.util.metrics import Measure, measure_func
  19. from synapse.util.caches.response_cache import ResponseCache
  20. from synapse.push.clientformat import format_push_rules_for_user
  21. from synapse.visibility import filter_events_for_client
  22. from synapse.types import RoomStreamToken
  23. from twisted.internet import defer
  24. import collections
  25. import logging
  26. import itertools
  27. logger = logging.getLogger(__name__)
  28. SyncConfig = collections.namedtuple("SyncConfig", [
  29. "user",
  30. "filter_collection",
  31. "is_guest",
  32. "request_key",
  33. "device_id",
  34. ])
  35. class TimelineBatch(collections.namedtuple("TimelineBatch", [
  36. "prev_batch",
  37. "events",
  38. "limited",
  39. ])):
  40. __slots__ = []
  41. def __nonzero__(self):
  42. """Make the result appear empty if there are no updates. This is used
  43. to tell if room needs to be part of the sync result.
  44. """
  45. return bool(self.events)
  46. class JoinedSyncResult(collections.namedtuple("JoinedSyncResult", [
  47. "room_id", # str
  48. "timeline", # TimelineBatch
  49. "state", # dict[(str, str), FrozenEvent]
  50. "ephemeral",
  51. "account_data",
  52. "unread_notifications",
  53. ])):
  54. __slots__ = []
  55. def __nonzero__(self):
  56. """Make the result appear empty if there are no updates. This is used
  57. to tell if room needs to be part of the sync result.
  58. """
  59. return bool(
  60. self.timeline
  61. or self.state
  62. or self.ephemeral
  63. or self.account_data
  64. # nb the notification count does not, er, count: if there's nothing
  65. # else in the result, we don't need to send it.
  66. )
  67. class ArchivedSyncResult(collections.namedtuple("ArchivedSyncResult", [
  68. "room_id", # str
  69. "timeline", # TimelineBatch
  70. "state", # dict[(str, str), FrozenEvent]
  71. "account_data",
  72. ])):
  73. __slots__ = []
  74. def __nonzero__(self):
  75. """Make the result appear empty if there are no updates. This is used
  76. to tell if room needs to be part of the sync result.
  77. """
  78. return bool(
  79. self.timeline
  80. or self.state
  81. or self.account_data
  82. )
  83. class InvitedSyncResult(collections.namedtuple("InvitedSyncResult", [
  84. "room_id", # str
  85. "invite", # FrozenEvent: the invite event
  86. ])):
  87. __slots__ = []
  88. def __nonzero__(self):
  89. """Invited rooms should always be reported to the client"""
  90. return True
  91. class SyncResult(collections.namedtuple("SyncResult", [
  92. "next_batch", # Token for the next sync
  93. "presence", # List of presence events for the user.
  94. "account_data", # List of account_data events for the user.
  95. "joined", # JoinedSyncResult for each joined room.
  96. "invited", # InvitedSyncResult for each invited room.
  97. "archived", # ArchivedSyncResult for each archived room.
  98. "to_device", # List of direct messages for the device.
  99. "device_lists", # List of user_ids whose devices have chanegd
  100. "device_one_time_keys_count", # Dict of algorithm to count for one time keys
  101. # for this device
  102. ])):
  103. __slots__ = []
  104. def __nonzero__(self):
  105. """Make the result appear empty if there are no updates. This is used
  106. to tell if the notifier needs to wait for more events when polling for
  107. events.
  108. """
  109. return bool(
  110. self.presence or
  111. self.joined or
  112. self.invited or
  113. self.archived or
  114. self.account_data or
  115. self.to_device or
  116. self.device_lists
  117. )
  118. class SyncHandler(object):
  119. def __init__(self, hs):
  120. self.store = hs.get_datastore()
  121. self.notifier = hs.get_notifier()
  122. self.presence_handler = hs.get_presence_handler()
  123. self.event_sources = hs.get_event_sources()
  124. self.clock = hs.get_clock()
  125. self.response_cache = ResponseCache(hs)
  126. self.state = hs.get_state_handler()
  127. def wait_for_sync_for_user(self, sync_config, since_token=None, timeout=0,
  128. full_state=False):
  129. """Get the sync for a client if we have new data for it now. Otherwise
  130. wait for new data to arrive on the server. If the timeout expires, then
  131. return an empty sync result.
  132. Returns:
  133. A Deferred SyncResult.
  134. """
  135. result = self.response_cache.get(sync_config.request_key)
  136. if not result:
  137. result = self.response_cache.set(
  138. sync_config.request_key,
  139. self._wait_for_sync_for_user(
  140. sync_config, since_token, timeout, full_state
  141. )
  142. )
  143. return result
  144. @defer.inlineCallbacks
  145. def _wait_for_sync_for_user(self, sync_config, since_token, timeout,
  146. full_state):
  147. context = LoggingContext.current_context()
  148. if context:
  149. if since_token is None:
  150. context.tag = "initial_sync"
  151. elif full_state:
  152. context.tag = "full_state_sync"
  153. else:
  154. context.tag = "incremental_sync"
  155. if timeout == 0 or since_token is None or full_state:
  156. # we are going to return immediately, so don't bother calling
  157. # notifier.wait_for_events.
  158. result = yield self.current_sync_for_user(
  159. sync_config, since_token, full_state=full_state,
  160. )
  161. defer.returnValue(result)
  162. else:
  163. def current_sync_callback(before_token, after_token):
  164. return self.current_sync_for_user(sync_config, since_token)
  165. result = yield self.notifier.wait_for_events(
  166. sync_config.user.to_string(), timeout, current_sync_callback,
  167. from_token=since_token,
  168. )
  169. defer.returnValue(result)
  170. def current_sync_for_user(self, sync_config, since_token=None,
  171. full_state=False):
  172. """Get the sync for client needed to match what the server has now.
  173. Returns:
  174. A Deferred SyncResult.
  175. """
  176. return self.generate_sync_result(sync_config, since_token, full_state)
  177. @defer.inlineCallbacks
  178. def push_rules_for_user(self, user):
  179. user_id = user.to_string()
  180. rules = yield self.store.get_push_rules_for_user(user_id)
  181. rules = format_push_rules_for_user(user, rules)
  182. defer.returnValue(rules)
  183. @defer.inlineCallbacks
  184. def ephemeral_by_room(self, sync_config, now_token, since_token=None):
  185. """Get the ephemeral events for each room the user is in
  186. Args:
  187. sync_config (SyncConfig): The flags, filters and user for the sync.
  188. now_token (StreamToken): Where the server is currently up to.
  189. since_token (StreamToken): Where the server was when the client
  190. last synced.
  191. Returns:
  192. A tuple of the now StreamToken, updated to reflect the which typing
  193. events are included, and a dict mapping from room_id to a list of
  194. typing events for that room.
  195. """
  196. with Measure(self.clock, "ephemeral_by_room"):
  197. typing_key = since_token.typing_key if since_token else "0"
  198. room_ids = yield self.store.get_rooms_for_user(sync_config.user.to_string())
  199. typing_source = self.event_sources.sources["typing"]
  200. typing, typing_key = yield typing_source.get_new_events(
  201. user=sync_config.user,
  202. from_key=typing_key,
  203. limit=sync_config.filter_collection.ephemeral_limit(),
  204. room_ids=room_ids,
  205. is_guest=sync_config.is_guest,
  206. )
  207. now_token = now_token.copy_and_replace("typing_key", typing_key)
  208. ephemeral_by_room = {}
  209. for event in typing:
  210. # we want to exclude the room_id from the event, but modifying the
  211. # result returned by the event source is poor form (it might cache
  212. # the object)
  213. room_id = event["room_id"]
  214. event_copy = {k: v for (k, v) in event.iteritems()
  215. if k != "room_id"}
  216. ephemeral_by_room.setdefault(room_id, []).append(event_copy)
  217. receipt_key = since_token.receipt_key if since_token else "0"
  218. receipt_source = self.event_sources.sources["receipt"]
  219. receipts, receipt_key = yield receipt_source.get_new_events(
  220. user=sync_config.user,
  221. from_key=receipt_key,
  222. limit=sync_config.filter_collection.ephemeral_limit(),
  223. room_ids=room_ids,
  224. is_guest=sync_config.is_guest,
  225. )
  226. now_token = now_token.copy_and_replace("receipt_key", receipt_key)
  227. for event in receipts:
  228. room_id = event["room_id"]
  229. # exclude room id, as above
  230. event_copy = {k: v for (k, v) in event.iteritems()
  231. if k != "room_id"}
  232. ephemeral_by_room.setdefault(room_id, []).append(event_copy)
  233. defer.returnValue((now_token, ephemeral_by_room))
  234. @defer.inlineCallbacks
  235. def _load_filtered_recents(self, room_id, sync_config, now_token,
  236. since_token=None, recents=None, newly_joined_room=False):
  237. """
  238. Returns:
  239. a Deferred TimelineBatch
  240. """
  241. with Measure(self.clock, "load_filtered_recents"):
  242. timeline_limit = sync_config.filter_collection.timeline_limit()
  243. block_all_timeline = sync_config.filter_collection.blocks_all_room_timeline()
  244. if recents is None or newly_joined_room or timeline_limit < len(recents):
  245. limited = True
  246. else:
  247. limited = False
  248. if recents:
  249. recents = sync_config.filter_collection.filter_room_timeline(recents)
  250. recents = yield filter_events_for_client(
  251. self.store,
  252. sync_config.user.to_string(),
  253. recents,
  254. )
  255. else:
  256. recents = []
  257. if not limited or block_all_timeline:
  258. defer.returnValue(TimelineBatch(
  259. events=recents,
  260. prev_batch=now_token,
  261. limited=False
  262. ))
  263. filtering_factor = 2
  264. load_limit = max(timeline_limit * filtering_factor, 10)
  265. max_repeat = 5 # Only try a few times per room, otherwise
  266. room_key = now_token.room_key
  267. end_key = room_key
  268. since_key = None
  269. if since_token and not newly_joined_room:
  270. since_key = since_token.room_key
  271. while limited and len(recents) < timeline_limit and max_repeat:
  272. events, end_key = yield self.store.get_room_events_stream_for_room(
  273. room_id,
  274. limit=load_limit + 1,
  275. from_key=since_key,
  276. to_key=end_key,
  277. )
  278. loaded_recents = sync_config.filter_collection.filter_room_timeline(
  279. events
  280. )
  281. loaded_recents = yield filter_events_for_client(
  282. self.store,
  283. sync_config.user.to_string(),
  284. loaded_recents,
  285. )
  286. loaded_recents.extend(recents)
  287. recents = loaded_recents
  288. if len(events) <= load_limit:
  289. limited = False
  290. break
  291. max_repeat -= 1
  292. if len(recents) > timeline_limit:
  293. limited = True
  294. recents = recents[-timeline_limit:]
  295. room_key = recents[0].internal_metadata.before
  296. prev_batch_token = now_token.copy_and_replace(
  297. "room_key", room_key
  298. )
  299. defer.returnValue(TimelineBatch(
  300. events=recents,
  301. prev_batch=prev_batch_token,
  302. limited=limited or newly_joined_room
  303. ))
  304. @defer.inlineCallbacks
  305. def get_state_after_event(self, event):
  306. """
  307. Get the room state after the given event
  308. Args:
  309. event(synapse.events.EventBase): event of interest
  310. Returns:
  311. A Deferred map from ((type, state_key)->Event)
  312. """
  313. state_ids = yield self.store.get_state_ids_for_event(event.event_id)
  314. if event.is_state():
  315. state_ids = state_ids.copy()
  316. state_ids[(event.type, event.state_key)] = event.event_id
  317. defer.returnValue(state_ids)
  318. @defer.inlineCallbacks
  319. def get_state_at(self, room_id, stream_position):
  320. """ Get the room state at a particular stream position
  321. Args:
  322. room_id(str): room for which to get state
  323. stream_position(StreamToken): point at which to get state
  324. Returns:
  325. A Deferred map from ((type, state_key)->Event)
  326. """
  327. last_events, token = yield self.store.get_recent_events_for_room(
  328. room_id, end_token=stream_position.room_key, limit=1,
  329. )
  330. if last_events:
  331. last_event = last_events[-1]
  332. state = yield self.get_state_after_event(last_event)
  333. else:
  334. # no events in this room - so presumably no state
  335. state = {}
  336. defer.returnValue(state)
  337. @defer.inlineCallbacks
  338. def compute_state_delta(self, room_id, batch, sync_config, since_token, now_token,
  339. full_state):
  340. """ Works out the differnce in state between the start of the timeline
  341. and the previous sync.
  342. Args:
  343. room_id(str):
  344. batch(synapse.handlers.sync.TimelineBatch): The timeline batch for
  345. the room that will be sent to the user.
  346. sync_config(synapse.handlers.sync.SyncConfig):
  347. since_token(str|None): Token of the end of the previous batch. May
  348. be None.
  349. now_token(str): Token of the end of the current batch.
  350. full_state(bool): Whether to force returning the full state.
  351. Returns:
  352. A deferred new event dictionary
  353. """
  354. # TODO(mjark) Check if the state events were received by the server
  355. # after the previous sync, since we need to include those state
  356. # updates even if they occured logically before the previous event.
  357. # TODO(mjark) Check for new redactions in the state events.
  358. with Measure(self.clock, "compute_state_delta"):
  359. if full_state:
  360. if batch:
  361. current_state_ids = yield self.store.get_state_ids_for_event(
  362. batch.events[-1].event_id
  363. )
  364. state_ids = yield self.store.get_state_ids_for_event(
  365. batch.events[0].event_id
  366. )
  367. else:
  368. current_state_ids = yield self.get_state_at(
  369. room_id, stream_position=now_token
  370. )
  371. state_ids = current_state_ids
  372. timeline_state = {
  373. (event.type, event.state_key): event.event_id
  374. for event in batch.events if event.is_state()
  375. }
  376. state_ids = _calculate_state(
  377. timeline_contains=timeline_state,
  378. timeline_start=state_ids,
  379. previous={},
  380. current=current_state_ids,
  381. )
  382. elif batch.limited:
  383. state_at_previous_sync = yield self.get_state_at(
  384. room_id, stream_position=since_token
  385. )
  386. current_state_ids = yield self.store.get_state_ids_for_event(
  387. batch.events[-1].event_id
  388. )
  389. state_at_timeline_start = yield self.store.get_state_ids_for_event(
  390. batch.events[0].event_id
  391. )
  392. timeline_state = {
  393. (event.type, event.state_key): event.event_id
  394. for event in batch.events if event.is_state()
  395. }
  396. state_ids = _calculate_state(
  397. timeline_contains=timeline_state,
  398. timeline_start=state_at_timeline_start,
  399. previous=state_at_previous_sync,
  400. current=current_state_ids,
  401. )
  402. else:
  403. state_ids = {}
  404. state = {}
  405. if state_ids:
  406. state = yield self.store.get_events(state_ids.values())
  407. defer.returnValue({
  408. (e.type, e.state_key): e
  409. for e in sync_config.filter_collection.filter_room_state(state.values())
  410. })
  411. @defer.inlineCallbacks
  412. def unread_notifs_for_room_id(self, room_id, sync_config):
  413. with Measure(self.clock, "unread_notifs_for_room_id"):
  414. last_unread_event_id = yield self.store.get_last_receipt_event_id_for_user(
  415. user_id=sync_config.user.to_string(),
  416. room_id=room_id,
  417. receipt_type="m.read"
  418. )
  419. notifs = []
  420. if last_unread_event_id:
  421. notifs = yield self.store.get_unread_event_push_actions_by_room_for_user(
  422. room_id, sync_config.user.to_string(), last_unread_event_id
  423. )
  424. defer.returnValue(notifs)
  425. # There is no new information in this period, so your notification
  426. # count is whatever it was last time.
  427. defer.returnValue(None)
  428. @defer.inlineCallbacks
  429. def generate_sync_result(self, sync_config, since_token=None, full_state=False):
  430. """Generates a sync result.
  431. Args:
  432. sync_config (SyncConfig)
  433. since_token (StreamToken)
  434. full_state (bool)
  435. Returns:
  436. Deferred(SyncResult)
  437. """
  438. logger.info("Calculating sync response for %r", sync_config.user)
  439. # NB: The now_token gets changed by some of the generate_sync_* methods,
  440. # this is due to some of the underlying streams not supporting the ability
  441. # to query up to a given point.
  442. # Always use the `now_token` in `SyncResultBuilder`
  443. now_token = yield self.event_sources.get_current_token()
  444. sync_result_builder = SyncResultBuilder(
  445. sync_config, full_state,
  446. since_token=since_token,
  447. now_token=now_token,
  448. )
  449. account_data_by_room = yield self._generate_sync_entry_for_account_data(
  450. sync_result_builder
  451. )
  452. res = yield self._generate_sync_entry_for_rooms(
  453. sync_result_builder, account_data_by_room
  454. )
  455. newly_joined_rooms, newly_joined_users = res
  456. block_all_presence_data = (
  457. since_token is None and
  458. sync_config.filter_collection.blocks_all_presence()
  459. )
  460. if not block_all_presence_data:
  461. yield self._generate_sync_entry_for_presence(
  462. sync_result_builder, newly_joined_rooms, newly_joined_users
  463. )
  464. yield self._generate_sync_entry_for_to_device(sync_result_builder)
  465. device_lists = yield self._generate_sync_entry_for_device_list(
  466. sync_result_builder
  467. )
  468. device_id = sync_config.device_id
  469. one_time_key_counts = {}
  470. if device_id:
  471. user_id = sync_config.user.to_string()
  472. one_time_key_counts = yield self.store.count_e2e_one_time_keys(
  473. user_id, device_id
  474. )
  475. defer.returnValue(SyncResult(
  476. presence=sync_result_builder.presence,
  477. account_data=sync_result_builder.account_data,
  478. joined=sync_result_builder.joined,
  479. invited=sync_result_builder.invited,
  480. archived=sync_result_builder.archived,
  481. to_device=sync_result_builder.to_device,
  482. device_lists=device_lists,
  483. device_one_time_keys_count=one_time_key_counts,
  484. next_batch=sync_result_builder.now_token,
  485. ))
  486. @measure_func("_generate_sync_entry_for_device_list")
  487. @defer.inlineCallbacks
  488. def _generate_sync_entry_for_device_list(self, sync_result_builder):
  489. user_id = sync_result_builder.sync_config.user.to_string()
  490. since_token = sync_result_builder.since_token
  491. if since_token and since_token.device_list_key:
  492. room_ids = yield self.store.get_rooms_for_user(user_id)
  493. user_ids_changed = set()
  494. changed = yield self.store.get_user_whose_devices_changed(
  495. since_token.device_list_key
  496. )
  497. for other_user_id in changed:
  498. other_room_ids = yield self.store.get_rooms_for_user(other_user_id)
  499. if room_ids.intersection(other_room_ids):
  500. user_ids_changed.add(other_user_id)
  501. defer.returnValue(user_ids_changed)
  502. else:
  503. defer.returnValue([])
  504. @defer.inlineCallbacks
  505. def _generate_sync_entry_for_to_device(self, sync_result_builder):
  506. """Generates the portion of the sync response. Populates
  507. `sync_result_builder` with the result.
  508. Args:
  509. sync_result_builder(SyncResultBuilder)
  510. Returns:
  511. Deferred(dict): A dictionary containing the per room account data.
  512. """
  513. user_id = sync_result_builder.sync_config.user.to_string()
  514. device_id = sync_result_builder.sync_config.device_id
  515. now_token = sync_result_builder.now_token
  516. since_stream_id = 0
  517. if sync_result_builder.since_token is not None:
  518. since_stream_id = int(sync_result_builder.since_token.to_device_key)
  519. if since_stream_id != int(now_token.to_device_key):
  520. # We only delete messages when a new message comes in, but that's
  521. # fine so long as we delete them at some point.
  522. deleted = yield self.store.delete_messages_for_device(
  523. user_id, device_id, since_stream_id
  524. )
  525. logger.debug("Deleted %d to-device messages up to %d",
  526. deleted, since_stream_id)
  527. messages, stream_id = yield self.store.get_new_messages_for_device(
  528. user_id, device_id, since_stream_id, now_token.to_device_key
  529. )
  530. logger.debug(
  531. "Returning %d to-device messages between %d and %d (current token: %d)",
  532. len(messages), since_stream_id, stream_id, now_token.to_device_key
  533. )
  534. sync_result_builder.now_token = now_token.copy_and_replace(
  535. "to_device_key", stream_id
  536. )
  537. sync_result_builder.to_device = messages
  538. else:
  539. sync_result_builder.to_device = []
  540. @defer.inlineCallbacks
  541. def _generate_sync_entry_for_account_data(self, sync_result_builder):
  542. """Generates the account data portion of the sync response. Populates
  543. `sync_result_builder` with the result.
  544. Args:
  545. sync_result_builder(SyncResultBuilder)
  546. Returns:
  547. Deferred(dict): A dictionary containing the per room account data.
  548. """
  549. sync_config = sync_result_builder.sync_config
  550. user_id = sync_result_builder.sync_config.user.to_string()
  551. since_token = sync_result_builder.since_token
  552. if since_token and not sync_result_builder.full_state:
  553. account_data, account_data_by_room = (
  554. yield self.store.get_updated_account_data_for_user(
  555. user_id,
  556. since_token.account_data_key,
  557. )
  558. )
  559. push_rules_changed = yield self.store.have_push_rules_changed_for_user(
  560. user_id, int(since_token.push_rules_key)
  561. )
  562. if push_rules_changed:
  563. account_data["m.push_rules"] = yield self.push_rules_for_user(
  564. sync_config.user
  565. )
  566. else:
  567. account_data, account_data_by_room = (
  568. yield self.store.get_account_data_for_user(
  569. sync_config.user.to_string()
  570. )
  571. )
  572. account_data['m.push_rules'] = yield self.push_rules_for_user(
  573. sync_config.user
  574. )
  575. account_data_for_user = sync_config.filter_collection.filter_account_data([
  576. {"type": account_data_type, "content": content}
  577. for account_data_type, content in account_data.items()
  578. ])
  579. sync_result_builder.account_data = account_data_for_user
  580. defer.returnValue(account_data_by_room)
  581. @defer.inlineCallbacks
  582. def _generate_sync_entry_for_presence(self, sync_result_builder, newly_joined_rooms,
  583. newly_joined_users):
  584. """Generates the presence portion of the sync response. Populates the
  585. `sync_result_builder` with the result.
  586. Args:
  587. sync_result_builder(SyncResultBuilder)
  588. newly_joined_rooms(list): List of rooms that the user has joined
  589. since the last sync (or empty if an initial sync)
  590. newly_joined_users(list): List of users that have joined rooms
  591. since the last sync (or empty if an initial sync)
  592. """
  593. now_token = sync_result_builder.now_token
  594. sync_config = sync_result_builder.sync_config
  595. user = sync_result_builder.sync_config.user
  596. presence_source = self.event_sources.sources["presence"]
  597. since_token = sync_result_builder.since_token
  598. if since_token and not sync_result_builder.full_state:
  599. presence_key = since_token.presence_key
  600. include_offline = True
  601. else:
  602. presence_key = None
  603. include_offline = False
  604. presence, presence_key = yield presence_source.get_new_events(
  605. user=user,
  606. from_key=presence_key,
  607. is_guest=sync_config.is_guest,
  608. include_offline=include_offline,
  609. )
  610. sync_result_builder.now_token = now_token.copy_and_replace(
  611. "presence_key", presence_key
  612. )
  613. extra_users_ids = set(newly_joined_users)
  614. for room_id in newly_joined_rooms:
  615. users = yield self.state.get_current_user_in_room(room_id)
  616. extra_users_ids.update(users)
  617. extra_users_ids.discard(user.to_string())
  618. if extra_users_ids:
  619. states = yield self.presence_handler.get_states(
  620. extra_users_ids,
  621. )
  622. presence.extend(states)
  623. # Deduplicate the presence entries so that there's at most one per user
  624. presence = {p.user_id: p for p in presence}.values()
  625. presence = sync_config.filter_collection.filter_presence(
  626. presence
  627. )
  628. sync_result_builder.presence = presence
  629. @defer.inlineCallbacks
  630. def _generate_sync_entry_for_rooms(self, sync_result_builder, account_data_by_room):
  631. """Generates the rooms portion of the sync response. Populates the
  632. `sync_result_builder` with the result.
  633. Args:
  634. sync_result_builder(SyncResultBuilder)
  635. account_data_by_room(dict): Dictionary of per room account data
  636. Returns:
  637. Deferred(tuple): Returns a 2-tuple of
  638. `(newly_joined_rooms, newly_joined_users)`
  639. """
  640. user_id = sync_result_builder.sync_config.user.to_string()
  641. block_all_room_ephemeral = (
  642. sync_result_builder.since_token is None and
  643. sync_result_builder.sync_config.filter_collection.blocks_all_room_ephemeral()
  644. )
  645. if block_all_room_ephemeral:
  646. ephemeral_by_room = {}
  647. else:
  648. now_token, ephemeral_by_room = yield self.ephemeral_by_room(
  649. sync_result_builder.sync_config,
  650. now_token=sync_result_builder.now_token,
  651. since_token=sync_result_builder.since_token,
  652. )
  653. sync_result_builder.now_token = now_token
  654. # We check up front if anything has changed, if it hasn't then there is
  655. # no point in going futher.
  656. since_token = sync_result_builder.since_token
  657. if not sync_result_builder.full_state:
  658. if since_token and not ephemeral_by_room and not account_data_by_room:
  659. have_changed = yield self._have_rooms_changed(sync_result_builder)
  660. if not have_changed:
  661. tags_by_room = yield self.store.get_updated_tags(
  662. user_id,
  663. since_token.account_data_key,
  664. )
  665. if not tags_by_room:
  666. logger.debug("no-oping sync")
  667. defer.returnValue(([], []))
  668. ignored_account_data = yield self.store.get_global_account_data_by_type_for_user(
  669. "m.ignored_user_list", user_id=user_id,
  670. )
  671. if ignored_account_data:
  672. ignored_users = ignored_account_data.get("ignored_users", {}).keys()
  673. else:
  674. ignored_users = frozenset()
  675. if since_token:
  676. res = yield self._get_rooms_changed(sync_result_builder, ignored_users)
  677. room_entries, invited, newly_joined_rooms = res
  678. tags_by_room = yield self.store.get_updated_tags(
  679. user_id, since_token.account_data_key,
  680. )
  681. else:
  682. res = yield self._get_all_rooms(sync_result_builder, ignored_users)
  683. room_entries, invited, newly_joined_rooms = res
  684. tags_by_room = yield self.store.get_tags_for_user(user_id)
  685. def handle_room_entries(room_entry):
  686. return self._generate_room_entry(
  687. sync_result_builder,
  688. ignored_users,
  689. room_entry,
  690. ephemeral=ephemeral_by_room.get(room_entry.room_id, []),
  691. tags=tags_by_room.get(room_entry.room_id),
  692. account_data=account_data_by_room.get(room_entry.room_id, {}),
  693. always_include=sync_result_builder.full_state,
  694. )
  695. yield concurrently_execute(handle_room_entries, room_entries, 10)
  696. sync_result_builder.invited.extend(invited)
  697. # Now we want to get any newly joined users
  698. newly_joined_users = set()
  699. if since_token:
  700. for joined_sync in sync_result_builder.joined:
  701. it = itertools.chain(
  702. joined_sync.timeline.events, joined_sync.state.values()
  703. )
  704. for event in it:
  705. if event.type == EventTypes.Member:
  706. if event.membership == Membership.JOIN:
  707. newly_joined_users.add(event.state_key)
  708. defer.returnValue((newly_joined_rooms, newly_joined_users))
  709. @defer.inlineCallbacks
  710. def _have_rooms_changed(self, sync_result_builder):
  711. """Returns whether there may be any new events that should be sent down
  712. the sync. Returns True if there are.
  713. """
  714. user_id = sync_result_builder.sync_config.user.to_string()
  715. since_token = sync_result_builder.since_token
  716. now_token = sync_result_builder.now_token
  717. assert since_token
  718. # Get a list of membership change events that have happened.
  719. rooms_changed = yield self.store.get_membership_changes_for_user(
  720. user_id, since_token.room_key, now_token.room_key
  721. )
  722. if rooms_changed:
  723. defer.returnValue(True)
  724. app_service = self.store.get_app_service_by_user_id(user_id)
  725. if app_service:
  726. rooms = yield self.store.get_app_service_rooms(app_service)
  727. joined_room_ids = set(r.room_id for r in rooms)
  728. else:
  729. joined_room_ids = yield self.store.get_rooms_for_user(user_id)
  730. stream_id = RoomStreamToken.parse_stream_token(since_token.room_key).stream
  731. for room_id in joined_room_ids:
  732. if self.store.has_room_changed_since(room_id, stream_id):
  733. defer.returnValue(True)
  734. defer.returnValue(False)
  735. @defer.inlineCallbacks
  736. def _get_rooms_changed(self, sync_result_builder, ignored_users):
  737. """Gets the the changes that have happened since the last sync.
  738. Args:
  739. sync_result_builder(SyncResultBuilder)
  740. ignored_users(set(str)): Set of users ignored by user.
  741. Returns:
  742. Deferred(tuple): Returns a tuple of the form:
  743. `([RoomSyncResultBuilder], [InvitedSyncResult], newly_joined_rooms)`
  744. """
  745. user_id = sync_result_builder.sync_config.user.to_string()
  746. since_token = sync_result_builder.since_token
  747. now_token = sync_result_builder.now_token
  748. sync_config = sync_result_builder.sync_config
  749. assert since_token
  750. app_service = self.store.get_app_service_by_user_id(user_id)
  751. if app_service:
  752. rooms = yield self.store.get_app_service_rooms(app_service)
  753. joined_room_ids = set(r.room_id for r in rooms)
  754. else:
  755. joined_room_ids = yield self.store.get_rooms_for_user(user_id)
  756. # Get a list of membership change events that have happened.
  757. rooms_changed = yield self.store.get_membership_changes_for_user(
  758. user_id, since_token.room_key, now_token.room_key
  759. )
  760. mem_change_events_by_room_id = {}
  761. for event in rooms_changed:
  762. mem_change_events_by_room_id.setdefault(event.room_id, []).append(event)
  763. newly_joined_rooms = []
  764. room_entries = []
  765. invited = []
  766. for room_id, events in mem_change_events_by_room_id.items():
  767. non_joins = [e for e in events if e.membership != Membership.JOIN]
  768. has_join = len(non_joins) != len(events)
  769. # We want to figure out if we joined the room at some point since
  770. # the last sync (even if we have since left). This is to make sure
  771. # we do send down the room, and with full state, where necessary
  772. if room_id in joined_room_ids or has_join:
  773. old_state_ids = yield self.get_state_at(room_id, since_token)
  774. old_mem_ev_id = old_state_ids.get((EventTypes.Member, user_id), None)
  775. old_mem_ev = None
  776. if old_mem_ev_id:
  777. old_mem_ev = yield self.store.get_event(
  778. old_mem_ev_id, allow_none=True
  779. )
  780. if not old_mem_ev or old_mem_ev.membership != Membership.JOIN:
  781. newly_joined_rooms.append(room_id)
  782. if room_id in joined_room_ids:
  783. continue
  784. if not non_joins:
  785. continue
  786. # Only bother if we're still currently invited
  787. should_invite = non_joins[-1].membership == Membership.INVITE
  788. if should_invite:
  789. if event.sender not in ignored_users:
  790. room_sync = InvitedSyncResult(room_id, invite=non_joins[-1])
  791. if room_sync:
  792. invited.append(room_sync)
  793. # Always include leave/ban events. Just take the last one.
  794. # TODO: How do we handle ban -> leave in same batch?
  795. leave_events = [
  796. e for e in non_joins
  797. if e.membership in (Membership.LEAVE, Membership.BAN)
  798. ]
  799. if leave_events:
  800. leave_event = leave_events[-1]
  801. leave_stream_token = yield self.store.get_stream_token_for_event(
  802. leave_event.event_id
  803. )
  804. leave_token = since_token.copy_and_replace(
  805. "room_key", leave_stream_token
  806. )
  807. if since_token and since_token.is_after(leave_token):
  808. continue
  809. room_entries.append(RoomSyncResultBuilder(
  810. room_id=room_id,
  811. rtype="archived",
  812. events=None,
  813. newly_joined=room_id in newly_joined_rooms,
  814. full_state=False,
  815. since_token=since_token,
  816. upto_token=leave_token,
  817. ))
  818. timeline_limit = sync_config.filter_collection.timeline_limit()
  819. # Get all events for rooms we're currently joined to.
  820. room_to_events = yield self.store.get_room_events_stream_for_rooms(
  821. room_ids=joined_room_ids,
  822. from_key=since_token.room_key,
  823. to_key=now_token.room_key,
  824. limit=timeline_limit + 1,
  825. )
  826. # We loop through all room ids, even if there are no new events, in case
  827. # there are non room events taht we need to notify about.
  828. for room_id in joined_room_ids:
  829. room_entry = room_to_events.get(room_id, None)
  830. if room_entry:
  831. events, start_key = room_entry
  832. prev_batch_token = now_token.copy_and_replace("room_key", start_key)
  833. room_entries.append(RoomSyncResultBuilder(
  834. room_id=room_id,
  835. rtype="joined",
  836. events=events,
  837. newly_joined=room_id in newly_joined_rooms,
  838. full_state=False,
  839. since_token=None if room_id in newly_joined_rooms else since_token,
  840. upto_token=prev_batch_token,
  841. ))
  842. else:
  843. room_entries.append(RoomSyncResultBuilder(
  844. room_id=room_id,
  845. rtype="joined",
  846. events=[],
  847. newly_joined=room_id in newly_joined_rooms,
  848. full_state=False,
  849. since_token=since_token,
  850. upto_token=since_token,
  851. ))
  852. defer.returnValue((room_entries, invited, newly_joined_rooms))
  853. @defer.inlineCallbacks
  854. def _get_all_rooms(self, sync_result_builder, ignored_users):
  855. """Returns entries for all rooms for the user.
  856. Args:
  857. sync_result_builder(SyncResultBuilder)
  858. ignored_users(set(str)): Set of users ignored by user.
  859. Returns:
  860. Deferred(tuple): Returns a tuple of the form:
  861. `([RoomSyncResultBuilder], [InvitedSyncResult], [])`
  862. """
  863. user_id = sync_result_builder.sync_config.user.to_string()
  864. since_token = sync_result_builder.since_token
  865. now_token = sync_result_builder.now_token
  866. sync_config = sync_result_builder.sync_config
  867. membership_list = (
  868. Membership.INVITE, Membership.JOIN, Membership.LEAVE, Membership.BAN
  869. )
  870. room_list = yield self.store.get_rooms_for_user_where_membership_is(
  871. user_id=user_id,
  872. membership_list=membership_list
  873. )
  874. room_entries = []
  875. invited = []
  876. for event in room_list:
  877. if event.membership == Membership.JOIN:
  878. room_entries.append(RoomSyncResultBuilder(
  879. room_id=event.room_id,
  880. rtype="joined",
  881. events=None,
  882. newly_joined=False,
  883. full_state=True,
  884. since_token=since_token,
  885. upto_token=now_token,
  886. ))
  887. elif event.membership == Membership.INVITE:
  888. if event.sender in ignored_users:
  889. continue
  890. invite = yield self.store.get_event(event.event_id)
  891. invited.append(InvitedSyncResult(
  892. room_id=event.room_id,
  893. invite=invite,
  894. ))
  895. elif event.membership in (Membership.LEAVE, Membership.BAN):
  896. # Always send down rooms we were banned or kicked from.
  897. if not sync_config.filter_collection.include_leave:
  898. if event.membership == Membership.LEAVE:
  899. if user_id == event.sender:
  900. continue
  901. leave_token = now_token.copy_and_replace(
  902. "room_key", "s%d" % (event.stream_ordering,)
  903. )
  904. room_entries.append(RoomSyncResultBuilder(
  905. room_id=event.room_id,
  906. rtype="archived",
  907. events=None,
  908. newly_joined=False,
  909. full_state=True,
  910. since_token=since_token,
  911. upto_token=leave_token,
  912. ))
  913. defer.returnValue((room_entries, invited, []))
  914. @defer.inlineCallbacks
  915. def _generate_room_entry(self, sync_result_builder, ignored_users,
  916. room_builder, ephemeral, tags, account_data,
  917. always_include=False):
  918. """Populates the `joined` and `archived` section of `sync_result_builder`
  919. based on the `room_builder`.
  920. Args:
  921. sync_result_builder(SyncResultBuilder)
  922. ignored_users(set(str)): Set of users ignored by user.
  923. room_builder(RoomSyncResultBuilder)
  924. ephemeral(list): List of new ephemeral events for room
  925. tags(list): List of *all* tags for room, or None if there has been
  926. no change.
  927. account_data(list): List of new account data for room
  928. always_include(bool): Always include this room in the sync response,
  929. even if empty.
  930. """
  931. newly_joined = room_builder.newly_joined
  932. full_state = (
  933. room_builder.full_state
  934. or newly_joined
  935. or sync_result_builder.full_state
  936. )
  937. events = room_builder.events
  938. # We want to shortcut out as early as possible.
  939. if not (always_include or account_data or ephemeral or full_state):
  940. if events == [] and tags is None:
  941. return
  942. since_token = sync_result_builder.since_token
  943. now_token = sync_result_builder.now_token
  944. sync_config = sync_result_builder.sync_config
  945. room_id = room_builder.room_id
  946. since_token = room_builder.since_token
  947. upto_token = room_builder.upto_token
  948. batch = yield self._load_filtered_recents(
  949. room_id, sync_config,
  950. now_token=upto_token,
  951. since_token=since_token,
  952. recents=events,
  953. newly_joined_room=newly_joined,
  954. )
  955. account_data_events = []
  956. if tags is not None:
  957. account_data_events.append({
  958. "type": "m.tag",
  959. "content": {"tags": tags},
  960. })
  961. for account_data_type, content in account_data.items():
  962. account_data_events.append({
  963. "type": account_data_type,
  964. "content": content,
  965. })
  966. account_data = sync_config.filter_collection.filter_room_account_data(
  967. account_data_events
  968. )
  969. ephemeral = sync_config.filter_collection.filter_room_ephemeral(ephemeral)
  970. if not (always_include or batch or account_data or ephemeral or full_state):
  971. return
  972. state = yield self.compute_state_delta(
  973. room_id, batch, sync_config, since_token, now_token,
  974. full_state=full_state
  975. )
  976. if room_builder.rtype == "joined":
  977. unread_notifications = {}
  978. room_sync = JoinedSyncResult(
  979. room_id=room_id,
  980. timeline=batch,
  981. state=state,
  982. ephemeral=ephemeral,
  983. account_data=account_data_events,
  984. unread_notifications=unread_notifications,
  985. )
  986. if room_sync or always_include:
  987. notifs = yield self.unread_notifs_for_room_id(
  988. room_id, sync_config
  989. )
  990. if notifs is not None:
  991. unread_notifications["notification_count"] = notifs["notify_count"]
  992. unread_notifications["highlight_count"] = notifs["highlight_count"]
  993. sync_result_builder.joined.append(room_sync)
  994. elif room_builder.rtype == "archived":
  995. room_sync = ArchivedSyncResult(
  996. room_id=room_id,
  997. timeline=batch,
  998. state=state,
  999. account_data=account_data,
  1000. )
  1001. if room_sync or always_include:
  1002. sync_result_builder.archived.append(room_sync)
  1003. else:
  1004. raise Exception("Unrecognized rtype: %r", room_builder.rtype)
  1005. def _action_has_highlight(actions):
  1006. for action in actions:
  1007. try:
  1008. if action.get("set_tweak", None) == "highlight":
  1009. return action.get("value", True)
  1010. except AttributeError:
  1011. pass
  1012. return False
  1013. def _calculate_state(timeline_contains, timeline_start, previous, current):
  1014. """Works out what state to include in a sync response.
  1015. Args:
  1016. timeline_contains (dict): state in the timeline
  1017. timeline_start (dict): state at the start of the timeline
  1018. previous (dict): state at the end of the previous sync (or empty dict
  1019. if this is an initial sync)
  1020. current (dict): state at the end of the timeline
  1021. Returns:
  1022. dict
  1023. """
  1024. event_id_to_key = {
  1025. e: key
  1026. for key, e in itertools.chain(
  1027. timeline_contains.items(),
  1028. previous.items(),
  1029. timeline_start.items(),
  1030. current.items(),
  1031. )
  1032. }
  1033. c_ids = set(e for e in current.values())
  1034. tc_ids = set(e for e in timeline_contains.values())
  1035. p_ids = set(e for e in previous.values())
  1036. ts_ids = set(e for e in timeline_start.values())
  1037. state_ids = ((c_ids | ts_ids) - p_ids) - tc_ids
  1038. return {
  1039. event_id_to_key[e]: e for e in state_ids
  1040. }
  1041. class SyncResultBuilder(object):
  1042. "Used to help build up a new SyncResult for a user"
  1043. def __init__(self, sync_config, full_state, since_token, now_token):
  1044. """
  1045. Args:
  1046. sync_config(SyncConfig)
  1047. full_state(bool): The full_state flag as specified by user
  1048. since_token(StreamToken): The token supplied by user, or None.
  1049. now_token(StreamToken): The token to sync up to.
  1050. """
  1051. self.sync_config = sync_config
  1052. self.full_state = full_state
  1053. self.since_token = since_token
  1054. self.now_token = now_token
  1055. self.presence = []
  1056. self.account_data = []
  1057. self.joined = []
  1058. self.invited = []
  1059. self.archived = []
  1060. self.device = []
  1061. class RoomSyncResultBuilder(object):
  1062. """Stores information needed to create either a `JoinedSyncResult` or
  1063. `ArchivedSyncResult`.
  1064. """
  1065. def __init__(self, room_id, rtype, events, newly_joined, full_state,
  1066. since_token, upto_token):
  1067. """
  1068. Args:
  1069. room_id(str)
  1070. rtype(str): One of `"joined"` or `"archived"`
  1071. events(list): List of events to include in the room, (more events
  1072. may be added when generating result).
  1073. newly_joined(bool): If the user has newly joined the room
  1074. full_state(bool): Whether the full state should be sent in result
  1075. since_token(StreamToken): Earliest point to return events from, or None
  1076. upto_token(StreamToken): Latest point to return events from.
  1077. """
  1078. self.room_id = room_id
  1079. self.rtype = rtype
  1080. self.events = events
  1081. self.newly_joined = newly_joined
  1082. self.full_state = full_state
  1083. self.since_token = since_token
  1084. self.upto_token = upto_token