sync.py 58 KB

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