UNPKG

99.1 kBSource Map (JSON)View Raw
1{"version":3,"sources":["../src/sync.js"],"names":["User","require","Room","Group","utils","Filter","EventTimeline","DEBUG","BUFFER_PERIOD_MS","FAILED_SYNC_ERROR_THRESHOLD","getFilterName","userId","suffix","debuglog","log","SyncApi","client","opts","initialSyncLimit","undefined","resolveInvitesToProfiles","pollTimeout","pendingEventOrdering","canResetEntireTimeline","roomId","_peekRoomId","_currentSyncRequest","_syncState","_syncStateData","_catchingUp","_running","_keepAliveTimer","_connectionReturnedDefer","_notifEvents","_failedSyncCount","_storeIsInvalid","getNotifTimelineSet","reEmitter","reEmit","prototype","createRoom","room","getUserId","lazyLoadMembers","timelineSupport","_registerStateListeners","createGroup","groupId","group","store","storeGroup","currentState","on","event","state","member","user","getUser","_deregisterStateListeners","removeAllListeners","syncLeftRooms","self","filter","credentials","setTimelineLimit","setIncludeLeaveRooms","localTimeoutMs","qps","timeout","getOrCreateFilter","then","filterId","_http","authedRequest","data","leaveRooms","rooms","leave","_mapSyncResponseToRoomArray","forEach","leaveObj","push","isBrandNewRoom","timeline","timelineEvents","_mapSyncEventsFormat","stateEvents","getLiveTimeline","setPaginationToken","prev_batch","BACKWARDS","_processRoomEvents","recalculate","storeRoom","emit","_processEventsForNotifs","peek","roomInitialSync","response","messages","chunk","peekRoom","oldStateEvents","map","deepCopy","getEventMapper","presence","isArray","presenceEvent","getContent","user_id","setPresenceEvent","createNewUser","storeUser","start","oldState","paginationToken","setStateEvents","_resolveInvites","addEventsToTimeline","reverse","_peekPoll","stopPeeking","token","room_id","from","done","res","e","type","events","addLiveEvents","end","err","console","error","setTimeout","getSyncState","getSyncStateData","recoverFromSyncStartupError","savedSyncPromise","keepaliveProm","_startKeepAlives","_updateSyncState","_wasLazyLoadingToggled","lazyLoadMembersBefore","isNewlyCreated","isStoreNewlyCreated","getClientOptions","prevClientOptions","sync","getPushRules","result","pushRules","checkLazyLoadStatus","getFilter","resetNotifTimelineSet","_doSyncRequest","savedSyncToken","_sync","global","document","_onOnlineBound","_onOnline","bind","addEventListener","Promise","resolve","isGuest","doesServerSupportLazyLoading","supported","createFilter","LAZY_LOADING_SYNC_FILTER","shouldClear","reason","InvalidStoreError","TOGGLED_LAZY_LOADING","warn","crypto","enableLazyLoading","_storeClientOptions","getSavedSyncToken","tok","getSavedSync","savedSync","_syncFromCache","stop","removeEventListener","abort","clearTimeout","retryImmediately","nextSyncToken","nextBatch","setSyncToken","syncEventData","oldSyncToken","catchingUp","next_batch","roomsData","groups","groupsData","account_data","accountData","_processSyncResponse","stack","syncOptions","reject","syncToken","getSyncToken","_onSyncError","setSyncData","onSyncWillProcess","hasSyncedBefore","onSyncCompleted","wantsSave","saveDeviceList","save","_getSyncParams","_getGuestFilter","disablePresence","set_presence","since","_cacheBuster","Date","now","connDidFail","getSender","storeAccountDataEvents","accountDataEvent","getType","to_device","length","toDeviceEvent","content","msgtype","invite","_processGroupSyncEntry","join","inviteRooms","joinRooms","inviteObj","invite_state","updateMyMembership","mapSeries","joinObj","isState","onCryptoEvent","getStateKey","_unstable_updateStatusMessage","processRoomEvent","ephemeralEvents","ephemeral","accountDataEvents","unread_notifications","setUnreadNotificationCount","notification_count","highlight_count","limited","i","eventId","getId","getTimelineForEvent","splice","resetLiveTimeline","summary","setSummary","addAccountData","sort","a","b","getTs","addLiveEvent","device_lists","handleDeviceListChanges","device_one_time_keys_count","currentCount","signed_curve25519","updateOneTimeKeyCount","delay","Math","floor","random","_pokeKeepAlive","defer","promise","success","request","prefix","httpStatus","groupsSection","sectionName","groupInfo","getGroup","isBrandNew","profile","setProfile","name","avatar_url","inviter","setInviter","setMyMembership","obj","keys","arrObj","getRoom","mapper","getMembersWithMembership","_requestedProfileInfo","avatarUrl","displayname","displayName","getProfileInfo","info","inviteEvent","membership","setMembershipEvent","stateEventList","timelineEventList","liveTimeline","timelineWasEmpty","getEvents","ev","getPushActionsForEvent","initialiseState","pushActions","notify","tweaks","highlight","guestRooms","_guestRooms","limit","newState","old","module","exports"],"mappings":"A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T,CAAuBhG,MAAvB,EAA+BL,MAA/B,EAAuC;AACnC,QAAM6C,OAAO,IAAIxD,IAAJ,CAASW,MAAT,CAAb;AACAK,WAAOqB,SAAP,CAAiBC,MAAjB,CAAwBkB,IAAxB,EAA8B,CAC1B,gBAD0B,EACR,kBADQ,EACY,eADZ,EAE1B,sBAF0B,EAEF,qBAFE,CAA9B;AAIA,WAAOA,IAAP;AACH;;AAED;AACAqR,OAAOC,OAAP,GAAiB/T,OAAjB","file":"sync.js","sourcesContent":["/*\nCopyright 2015, 2016 OpenMarket Ltd\nCopyright 2017 Vector Creations Ltd\nCopyright 2018 New Vector Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\"use strict\";\n\n/*\n * TODO:\n * This class mainly serves to take all the syncing logic out of client.js and\n * into a separate file. It's all very fluid, and this class gut wrenches a lot\n * of MatrixClient props (e.g. _http). Given we want to support WebSockets as\n * an alternative syncing API, we may want to have a proper syncing interface\n * for HTTP and WS at some point.\n */\nimport Promise from 'bluebird';\nconst User = require(\"./models/user\");\nconst Room = require(\"./models/room\");\nconst Group = require('./models/group');\nconst utils = require(\"./utils\");\nconst Filter = require(\"./filter\");\nconst EventTimeline = require(\"./models/event-timeline\");\n\nimport {InvalidStoreError} from './errors';\n\nconst DEBUG = true;\n\n// /sync requests allow you to set a timeout= but the request may continue\n// beyond that and wedge forever, so we need to track how long we are willing\n// to keep open the connection. This constant is *ADDED* to the timeout= value\n// to determine the max time we're willing to wait.\nconst BUFFER_PERIOD_MS = 80 * 1000;\n\n// Number of consecutive failed syncs that will lead to a syncState of ERROR as opposed\n// to RECONNECTING. This is needed to inform the client of server issues when the\n// keepAlive is successful but the server /sync fails.\nconst FAILED_SYNC_ERROR_THRESHOLD = 3;\n\nfunction getFilterName(userId, suffix) {\n // scope this on the user ID because people may login on many accounts\n // and they all need to be stored!\n return \"FILTER_SYNC_\" + userId + (suffix ? \"_\" + suffix : \"\");\n}\n\nfunction debuglog(...params) {\n if (!DEBUG) {\n return;\n }\n console.log(...params);\n}\n\n\n/**\n * <b>Internal class - unstable.</b>\n * Construct an entity which is able to sync with a homeserver.\n * @constructor\n * @param {MatrixClient} client The matrix client instance to use.\n * @param {Object} opts Config options\n * @param {module:crypto=} opts.crypto Crypto manager\n * @param {Function=} opts.canResetEntireTimeline A function which is called\n * with a room ID and returns a boolean. It should return 'true' if the SDK can\n * SAFELY remove events from this room. It may not be safe to remove events if\n * there are other references to the timelines for this room.\n * Default: returns false.\n * @param {Boolean=} opts.disablePresence True to perform syncing without automatically\n * updating presence.\n */\nfunction SyncApi(client, opts) {\n this.client = client;\n opts = opts || {};\n opts.initialSyncLimit = (\n opts.initialSyncLimit === undefined ? 8 : opts.initialSyncLimit\n );\n opts.resolveInvitesToProfiles = opts.resolveInvitesToProfiles || false;\n opts.pollTimeout = opts.pollTimeout || (30 * 1000);\n opts.pendingEventOrdering = opts.pendingEventOrdering || \"chronological\";\n if (!opts.canResetEntireTimeline) {\n opts.canResetEntireTimeline = function(roomId) {\n return false;\n };\n }\n this.opts = opts;\n this._peekRoomId = null;\n this._currentSyncRequest = null;\n this._syncState = null;\n this._syncStateData = null; // additional data (eg. error object for failed sync)\n this._catchingUp = false;\n this._running = false;\n this._keepAliveTimer = null;\n this._connectionReturnedDefer = null;\n this._notifEvents = []; // accumulator of sync events in the current sync response\n this._failedSyncCount = 0; // Number of consecutive failed /sync requests\n this._storeIsInvalid = false; // flag set if the store needs to be cleared before we can start\n\n if (client.getNotifTimelineSet()) {\n client.reEmitter.reEmit(client.getNotifTimelineSet(),\n [\"Room.timeline\", \"Room.timelineReset\"]);\n }\n}\n\n/**\n * @param {string} roomId\n * @return {Room}\n */\nSyncApi.prototype.createRoom = function(roomId) {\n const client = this.client;\n const room = new Room(roomId, client, client.getUserId(), {\n lazyLoadMembers: this.opts.lazyLoadMembers,\n pendingEventOrdering: this.opts.pendingEventOrdering,\n timelineSupport: client.timelineSupport,\n });\n client.reEmitter.reEmit(room, [\"Room.name\", \"Room.timeline\", \"Room.redaction\",\n \"Room.receipt\", \"Room.tags\",\n \"Room.timelineReset\",\n \"Room.localEchoUpdated\",\n \"Room.accountData\",\n \"Room.myMembership\",\n ]);\n this._registerStateListeners(room);\n return room;\n};\n\n/**\n * @param {string} groupId\n * @return {Group}\n */\nSyncApi.prototype.createGroup = function(groupId) {\n const client = this.client;\n const group = new Group(groupId);\n client.reEmitter.reEmit(group, [\"Group.profile\", \"Group.myMembership\"]);\n client.store.storeGroup(group);\n return group;\n};\n\n/**\n * @param {Room} room\n * @private\n */\nSyncApi.prototype._registerStateListeners = function(room) {\n const client = this.client;\n // we need to also re-emit room state and room member events, so hook it up\n // to the client now. We need to add a listener for RoomState.members in\n // order to hook them correctly. (TODO: find a better way?)\n client.reEmitter.reEmit(room.currentState, [\n \"RoomState.events\", \"RoomState.members\", \"RoomState.newMember\",\n ]);\n room.currentState.on(\"RoomState.newMember\", function(event, state, member) {\n member.user = client.getUser(member.userId);\n client.reEmitter.reEmit(\n member,\n [\n \"RoomMember.name\", \"RoomMember.typing\", \"RoomMember.powerLevel\",\n \"RoomMember.membership\",\n ],\n );\n });\n};\n\n/**\n * @param {Room} room\n * @private\n */\nSyncApi.prototype._deregisterStateListeners = function(room) {\n // could do with a better way of achieving this.\n room.currentState.removeAllListeners(\"RoomState.events\");\n room.currentState.removeAllListeners(\"RoomState.members\");\n room.currentState.removeAllListeners(\"RoomState.newMember\");\n};\n\n\n/**\n * Sync rooms the user has left.\n * @return {Promise} Resolved when they've been added to the store.\n */\nSyncApi.prototype.syncLeftRooms = function() {\n const client = this.client;\n const self = this;\n\n // grab a filter with limit=1 and include_leave=true\n const filter = new Filter(this.client.credentials.userId);\n filter.setTimelineLimit(1);\n filter.setIncludeLeaveRooms(true);\n\n const localTimeoutMs = this.opts.pollTimeout + BUFFER_PERIOD_MS;\n const qps = {\n timeout: 0, // don't want to block since this is a single isolated req\n };\n\n return client.getOrCreateFilter(\n getFilterName(client.credentials.userId, \"LEFT_ROOMS\"), filter,\n ).then(function(filterId) {\n qps.filter = filterId;\n return client._http.authedRequest(\n undefined, \"GET\", \"/sync\", qps, undefined, localTimeoutMs,\n );\n }).then(function(data) {\n let leaveRooms = [];\n if (data.rooms && data.rooms.leave) {\n leaveRooms = self._mapSyncResponseToRoomArray(data.rooms.leave);\n }\n const rooms = [];\n leaveRooms.forEach(function(leaveObj) {\n const room = leaveObj.room;\n rooms.push(room);\n if (!leaveObj.isBrandNewRoom) {\n // the intention behind syncLeftRooms is to add in rooms which were\n // *omitted* from the initial /sync. Rooms the user were joined to\n // but then left whilst the app is running will appear in this list\n // and we do not want to bother with them since they will have the\n // current state already (and may get dupe messages if we add\n // yet more timeline events!), so skip them.\n // NB: When we persist rooms to localStorage this will be more\n // complicated...\n return;\n }\n leaveObj.timeline = leaveObj.timeline || {};\n const timelineEvents =\n self._mapSyncEventsFormat(leaveObj.timeline, room);\n const stateEvents = self._mapSyncEventsFormat(leaveObj.state, room);\n\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(leaveObj.timeline.prev_batch,\n EventTimeline.BACKWARDS);\n\n self._processRoomEvents(room, stateEvents, timelineEvents);\n\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(\"Room\", room);\n\n self._processEventsForNotifs(room, timelineEvents);\n });\n return rooms;\n });\n};\n\n/**\n * Peek into a room. This will result in the room in question being synced so it\n * is accessible via getRooms(). Live updates for the room will be provided.\n * @param {string} roomId The room ID to peek into.\n * @return {Promise} A promise which resolves once the room has been added to the\n * store.\n */\nSyncApi.prototype.peek = function(roomId) {\n const self = this;\n const client = this.client;\n this._peekRoomId = roomId;\n return this.client.roomInitialSync(roomId, 20).then(function(response) {\n // make sure things are init'd\n response.messages = response.messages || {};\n response.messages.chunk = response.messages.chunk || [];\n response.state = response.state || [];\n\n const peekRoom = self.createRoom(roomId);\n\n // FIXME: Mostly duplicated from _processRoomEvents but not entirely\n // because \"state\" in this API is at the BEGINNING of the chunk\n const oldStateEvents = utils.map(\n utils.deepCopy(response.state), client.getEventMapper(),\n );\n const stateEvents = utils.map(\n response.state, client.getEventMapper(),\n );\n const messages = utils.map(\n response.messages.chunk, client.getEventMapper(),\n );\n\n // XXX: copypasted from /sync until we kill off this\n // minging v1 API stuff)\n // handle presence events (User objects)\n if (response.presence && utils.isArray(response.presence)) {\n response.presence.map(client.getEventMapper()).forEach(\n function(presenceEvent) {\n let user = client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(client, presenceEvent.getContent().user_id);\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(\"event\", presenceEvent);\n });\n }\n\n // set the pagination token before adding the events in case people\n // fire off pagination requests in response to the Room.timeline\n // events.\n if (response.messages.start) {\n peekRoom.oldState.paginationToken = response.messages.start;\n }\n\n // set the state of the room to as it was after the timeline executes\n peekRoom.oldState.setStateEvents(oldStateEvents);\n peekRoom.currentState.setStateEvents(stateEvents);\n\n self._resolveInvites(peekRoom);\n peekRoom.recalculate();\n\n // roll backwards to diverge old state. addEventsToTimeline\n // will overwrite the pagination token, so make sure it overwrites\n // it with the right thing.\n peekRoom.addEventsToTimeline(messages.reverse(), true,\n peekRoom.getLiveTimeline(),\n response.messages.start);\n\n client.store.storeRoom(peekRoom);\n client.emit(\"Room\", peekRoom);\n\n self._peekPoll(peekRoom);\n return peekRoom;\n });\n};\n\n/**\n * Stop polling for updates in the peeked room. NOPs if there is no room being\n * peeked.\n */\nSyncApi.prototype.stopPeeking = function() {\n this._peekRoomId = null;\n};\n\n/**\n * Do a peek room poll.\n * @param {Room} peekRoom\n * @param {string} token from= token\n */\nSyncApi.prototype._peekPoll = function(peekRoom, token) {\n if (this._peekRoomId !== peekRoom.roomId) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n\n const self = this;\n // FIXME: gut wrenching; hard-coded timeout values\n this.client._http.authedRequest(undefined, \"GET\", \"/events\", {\n room_id: peekRoom.roomId,\n timeout: 30 * 1000,\n from: token,\n }, undefined, 50 * 1000).done(function(res) {\n if (self._peekRoomId !== peekRoom.roomId) {\n debuglog(\"Stopped peeking in room %s\", peekRoom.roomId);\n return;\n }\n // We have a problem that we get presence both from /events and /sync\n // however, /sync only returns presence for users in rooms\n // you're actually joined to.\n // in order to be sure to get presence for all of the users in the\n // peeked room, we handle presence explicitly here. This may result\n // in duplicate presence events firing for some users, which is a\n // performance drain, but such is life.\n // XXX: copypasted from /sync until we can kill this minging v1 stuff.\n\n res.chunk.filter(function(e) {\n return e.type === \"m.presence\";\n }).map(self.client.getEventMapper()).forEach(function(presenceEvent) {\n let user = self.client.store.getUser(presenceEvent.getContent().user_id);\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(self.client, presenceEvent.getContent().user_id);\n user.setPresenceEvent(presenceEvent);\n self.client.store.storeUser(user);\n }\n self.client.emit(\"event\", presenceEvent);\n });\n\n // strip out events which aren't for the given room_id (e.g presence)\n const events = res.chunk.filter(function(e) {\n return e.room_id === peekRoom.roomId;\n }).map(self.client.getEventMapper());\n\n peekRoom.addLiveEvents(events);\n self._peekPoll(peekRoom, res.end);\n }, function(err) {\n console.error(\"[%s] Peek poll failed: %s\", peekRoom.roomId, err);\n setTimeout(function() {\n self._peekPoll(peekRoom, token);\n }, 30 * 1000);\n });\n};\n\n/**\n * Returns the current state of this sync object\n * @see module:client~MatrixClient#event:\"sync\"\n * @return {?String}\n */\nSyncApi.prototype.getSyncState = function() {\n return this._syncState;\n};\n\n/**\n * Returns the additional data object associated with\n * the current sync state, or null if there is no\n * such data.\n * Sync errors, if available, are put in the 'error' key of\n * this object.\n * @return {?Object}\n */\nSyncApi.prototype.getSyncStateData = function() {\n return this._syncStateData;\n};\n\nSyncApi.prototype.recoverFromSyncStartupError = async function(savedSyncPromise, err) {\n // Wait for the saved sync to complete - we send the pushrules and filter requests\n // before the saved sync has finished so they can run in parallel, but only process\n // the results after the saved sync is done. Equivalently, we wait for it to finish\n // before reporting failures from these functions.\n await savedSyncPromise;\n const keepaliveProm = this._startKeepAlives();\n this._updateSyncState(\"ERROR\", { error: err });\n await keepaliveProm;\n};\n\n/**\n * Is the lazy loading option different than in previous session?\n * @param {bool} lazyLoadMembers current options for lazy loading\n * @return {bool} whether or not the option has changed compared to the previous session */\nSyncApi.prototype._wasLazyLoadingToggled = async function(lazyLoadMembers) {\n lazyLoadMembers = !!lazyLoadMembers;\n // assume it was turned off before\n // if we don't know any better\n let lazyLoadMembersBefore = false;\n const isStoreNewlyCreated = await this.client.store.isNewlyCreated();\n if (!isStoreNewlyCreated) {\n const prevClientOptions = await this.client.store.getClientOptions();\n if (prevClientOptions) {\n lazyLoadMembersBefore = !!prevClientOptions.lazyLoadMembers;\n }\n return lazyLoadMembersBefore !== lazyLoadMembers;\n }\n return false;\n};\n\n/**\n * Main entry point\n */\nSyncApi.prototype.sync = function() {\n const client = this.client;\n const self = this;\n\n this._running = true;\n\n if (global.document) {\n this._onOnlineBound = this._onOnline.bind(this);\n global.document.addEventListener(\"online\", this._onOnlineBound, false);\n }\n\n let savedSyncPromise = Promise.resolve();\n let savedSyncToken = null;\n\n // We need to do one-off checks before we can begin the /sync loop.\n // These are:\n // 1) We need to get push rules so we can check if events should bing as we get\n // them from /sync.\n // 2) We need to get/create a filter which we can use for /sync.\n // 3) We need to check the lazy loading option matches what was used in the\n // stored sync. If it doesn't, we can't use the stored sync.\n\n async function getPushRules() {\n try {\n const result = await client.getPushRules();\n debuglog(\"Got push rules\");\n\n client.pushRules = result;\n } catch (err) {\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n await self.recoverFromSyncStartupError(savedSyncPromise, err);\n getPushRules();\n return;\n }\n checkLazyLoadStatus(); // advance to the next stage\n }\n\n const checkLazyLoadStatus = async () => {\n if (this.opts.lazyLoadMembers && client.isGuest()) {\n this.opts.lazyLoadMembers = false;\n }\n if (this.opts.lazyLoadMembers) {\n const supported = await client.doesServerSupportLazyLoading();\n if (supported) {\n this.opts.filter = await client.createFilter(\n Filter.LAZY_LOADING_SYNC_FILTER,\n );\n } else {\n console.log(\"LL: lazy loading requested but not supported \" +\n \"by server, so disabling\");\n this.opts.lazyLoadMembers = false;\n }\n }\n // need to vape the store when enabling LL and wasn't enabled before\n const shouldClear = await this._wasLazyLoadingToggled(this.opts.lazyLoadMembers);\n if (shouldClear) {\n this._storeIsInvalid = true;\n const reason = InvalidStoreError.TOGGLED_LAZY_LOADING;\n const error = new InvalidStoreError(reason, !!this.opts.lazyLoadMembers);\n this._updateSyncState(\"ERROR\", { error });\n // bail out of the sync loop now: the app needs to respond to this error.\n // we leave the state as 'ERROR' which isn't great since this normally means\n // we're retrying. The client must be stopped before clearing the stores anyway\n // so the app should stop the client, clear the store and start it again.\n console.warn(\"InvalidStoreError: store is not usable: stopping sync.\");\n return;\n }\n if (this.opts.lazyLoadMembers && this.opts.crypto) {\n this.opts.crypto.enableLazyLoading();\n }\n await this.client._storeClientOptions();\n\n getFilter(); // Now get the filter and start syncing\n };\n\n async function getFilter() {\n let filter;\n if (self.opts.filter) {\n filter = self.opts.filter;\n } else {\n filter = new Filter(client.credentials.userId);\n filter.setTimelineLimit(self.opts.initialSyncLimit);\n }\n\n let filterId;\n try {\n filterId = await client.getOrCreateFilter(\n getFilterName(client.credentials.userId), filter,\n );\n } catch (err) {\n // wait for saved sync to complete before doing anything else,\n // otherwise the sync state will end up being incorrect\n await self.recoverFromSyncStartupError(savedSyncPromise, err);\n getFilter();\n return;\n }\n // reset the notifications timeline to prepare it to paginate from\n // the current point in time.\n // The right solution would be to tie /sync pagination tokens into\n // /notifications API somehow.\n client.resetNotifTimelineSet();\n\n if (self._currentSyncRequest === null) {\n // Send this first sync request here so we can then wait for the saved\n // sync data to finish processing before we process the results of this one.\n console.log(\"Sending first sync request...\");\n self._currentSyncRequest = self._doSyncRequest({ filterId }, savedSyncToken);\n }\n\n // Now wait for the saved sync to finish...\n await savedSyncPromise;\n self._sync({ filterId });\n }\n\n if (client.isGuest()) {\n // no push rules for guests, no access to POST filter for guests.\n self._sync({});\n } else {\n // Pull the saved sync token out first, before the worker starts sending\n // all the sync data which could take a while. This will let us send our\n // first incremental sync request before we've processed our saved data.\n savedSyncPromise = client.store.getSavedSyncToken().then((tok) => {\n savedSyncToken = tok;\n return client.store.getSavedSync();\n }).then((savedSync) => {\n if (savedSync) {\n return self._syncFromCache(savedSync);\n }\n });\n // Now start the first incremental sync request: this can also\n // take a while so if we set it going now, we can wait for it\n // to finish while we process our saved sync data.\n getPushRules();\n }\n};\n\n/**\n * Stops the sync object from syncing.\n */\nSyncApi.prototype.stop = function() {\n debuglog(\"SyncApi.stop\");\n if (global.document) {\n global.document.removeEventListener(\"online\", this._onOnlineBound, false);\n this._onOnlineBound = undefined;\n }\n this._running = false;\n if (this._currentSyncRequest) {\n this._currentSyncRequest.abort();\n }\n if (this._keepAliveTimer) {\n clearTimeout(this._keepAliveTimer);\n this._keepAliveTimer = null;\n }\n};\n\n/**\n * Retry a backed off syncing request immediately. This should only be used when\n * the user <b>explicitly</b> attempts to retry their lost connection.\n * @return {boolean} True if this resulted in a request being retried.\n */\nSyncApi.prototype.retryImmediately = function() {\n if (!this._connectionReturnedDefer) {\n return false;\n }\n this._startKeepAlives(0);\n return true;\n};\n/**\n * Process a single set of cached sync data.\n * @param {Object} savedSync a saved sync that was persisted by a store. This\n * should have been acquired via client.store.getSavedSync().\n */\nSyncApi.prototype._syncFromCache = async function(savedSync) {\n debuglog(\"sync(): not doing HTTP hit, instead returning stored /sync data\");\n\n const nextSyncToken = savedSync.nextBatch;\n\n // Set sync token for future incremental syncing\n this.client.store.setSyncToken(nextSyncToken);\n\n // No previous sync, set old token to null\n const syncEventData = {\n oldSyncToken: null,\n nextSyncToken,\n catchingUp: false,\n };\n\n const data = {\n next_batch: nextSyncToken,\n rooms: savedSync.roomsData,\n groups: savedSync.groupsData,\n account_data: {\n events: savedSync.accountData,\n },\n };\n\n try {\n await this._processSyncResponse(syncEventData, data);\n } catch(e) {\n console.error(\"Error processing cached sync\", e.stack || e);\n }\n\n // Don't emit a prepared if we've bailed because the store is invalid:\n // in this case the client will not be usable until stopped & restarted\n // so this would be useless and misleading.\n if (!this._storeIsInvalid) {\n this._updateSyncState(\"PREPARED\", syncEventData);\n }\n};\n\n/**\n * Invoke me to do /sync calls\n * @param {Object} syncOptions\n * @param {string} syncOptions.filterId\n * @param {boolean} syncOptions.hasSyncedBefore\n */\nSyncApi.prototype._sync = async function(syncOptions) {\n const client = this.client;\n\n if (!this._running) {\n debuglog(\"Sync no longer running: exiting.\");\n if (this._connectionReturnedDefer) {\n this._connectionReturnedDefer.reject();\n this._connectionReturnedDefer = null;\n }\n this._updateSyncState(\"STOPPED\");\n return;\n }\n\n const syncToken = client.store.getSyncToken();\n\n let data;\n try {\n //debuglog('Starting sync since=' + syncToken);\n if (this._currentSyncRequest === null) {\n this._currentSyncRequest = this._doSyncRequest(syncOptions, syncToken);\n }\n data = await this._currentSyncRequest;\n } catch (e) {\n this._onSyncError(e, syncOptions);\n return;\n } finally {\n this._currentSyncRequest = null;\n }\n\n //debuglog('Completed sync, next_batch=' + data.next_batch);\n\n // set the sync token NOW *before* processing the events. We do this so\n // if something barfs on an event we can skip it rather than constantly\n // polling with the same token.\n client.store.setSyncToken(data.next_batch);\n\n // Reset after a successful sync\n this._failedSyncCount = 0;\n\n await client.store.setSyncData(data);\n\n const syncEventData = {\n oldSyncToken: syncToken,\n nextSyncToken: data.next_batch,\n catchingUp: this._catchingUp,\n };\n\n if (this.opts.crypto) {\n // tell the crypto module we're about to process a sync\n // response\n await this.opts.crypto.onSyncWillProcess(syncEventData);\n }\n\n try {\n await this._processSyncResponse(syncEventData, data);\n } catch(e) {\n // log the exception with stack if we have it, else fall back\n // to the plain description\n console.error(\"Caught /sync error\", e.stack || e);\n }\n\n // update this as it may have changed\n syncEventData.catchingUp = this._catchingUp;\n\n // emit synced events\n if (!syncOptions.hasSyncedBefore) {\n this._updateSyncState(\"PREPARED\", syncEventData);\n syncOptions.hasSyncedBefore = true;\n }\n\n // tell the crypto module to do its processing. It may block (to do a\n // /keys/changes request).\n if (this.opts.crypto) {\n await this.opts.crypto.onSyncCompleted(syncEventData);\n }\n\n // keep emitting SYNCING -> SYNCING for clients who want to do bulk updates\n this._updateSyncState(\"SYNCING\", syncEventData);\n\n if (client.store.wantsSave()) {\n // We always save the device list (if it's dirty) before saving the sync data:\n // this means we know the saved device list data is at least as fresh as the\n // stored sync data which means we don't have to worry that we may have missed\n // device changes. We can also skip the delay since we're not calling this very\n // frequently (and we don't really want to delay the sync for it).\n if (this.opts.crypto) {\n await this.opts.crypto.saveDeviceList(0);\n }\n\n // tell databases that everything is now in a consistent state and can be saved.\n client.store.save();\n }\n\n // Begin next sync\n this._sync(syncOptions);\n};\n\nSyncApi.prototype._doSyncRequest = function(syncOptions, syncToken) {\n const qps = this._getSyncParams(syncOptions, syncToken);\n return this.client._http.authedRequest(\n undefined, \"GET\", \"/sync\", qps, undefined,\n qps.timeout + BUFFER_PERIOD_MS,\n );\n};\n\nSyncApi.prototype._getSyncParams = function(syncOptions, syncToken) {\n let pollTimeout = this.opts.pollTimeout;\n\n if (this.getSyncState() !== 'SYNCING' || this._catchingUp) {\n // unless we are happily syncing already, we want the server to return\n // as quickly as possible, even if there are no events queued. This\n // serves two purposes:\n //\n // * When the connection dies, we want to know asap when it comes back,\n // so that we can hide the error from the user. (We don't want to\n // have to wait for an event or a timeout).\n //\n // * We want to know if the server has any to_device messages queued up\n // for us. We do that by calling it with a zero timeout until it\n // doesn't give us any more to_device messages.\n this._catchingUp = true;\n pollTimeout = 0;\n }\n\n let filterId = syncOptions.filterId;\n if (this.client.isGuest() && !filterId) {\n filterId = this._getGuestFilter();\n }\n\n const qps = {\n filter: filterId,\n timeout: pollTimeout,\n };\n\n if (this.opts.disablePresence) {\n qps.set_presence = \"offline\";\n }\n\n if (syncToken) {\n qps.since = syncToken;\n } else {\n // use a cachebuster for initialsyncs, to make sure that\n // we don't get a stale sync\n // (https://github.com/vector-im/vector-web/issues/1354)\n qps._cacheBuster = Date.now();\n }\n\n if (this.getSyncState() == 'ERROR' || this.getSyncState() == 'RECONNECTING') {\n // we think the connection is dead. If it comes back up, we won't know\n // about it till /sync returns. If the timeout= is high, this could\n // be a long time. Set it to 0 when doing retries so we don't have to wait\n // for an event or a timeout before emiting the SYNCING event.\n qps.timeout = 0;\n }\n\n return qps;\n};\n\nSyncApi.prototype._onSyncError = function(err, syncOptions) {\n if (!this._running) {\n debuglog(\"Sync no longer running: exiting\");\n if (this._connectionReturnedDefer) {\n this._connectionReturnedDefer.reject();\n this._connectionReturnedDefer = null;\n }\n this._updateSyncState(\"STOPPED\");\n return;\n }\n\n console.error(\"/sync error %s\", err);\n console.error(err);\n\n this._failedSyncCount++;\n console.log('Number of consecutive failed sync requests:', this._failedSyncCount);\n\n debuglog(\"Starting keep-alive\");\n // Note that we do *not* mark the sync connection as\n // lost yet: we only do this if a keepalive poke\n // fails, since long lived HTTP connections will\n // go away sometimes and we shouldn't treat this as\n // erroneous. We set the state to 'reconnecting'\n // instead, so that clients can observe this state\n // if they wish.\n this._startKeepAlives().then((connDidFail) => {\n // Only emit CATCHUP if we detected a connectivity error: if we didn't,\n // it's quite likely the sync will fail again for the same reason and we\n // want to stay in ERROR rather than keep flip-flopping between ERROR\n // and CATCHUP.\n if (connDidFail && this.getSyncState() === 'ERROR') {\n this._updateSyncState(\"CATCHUP\", {\n oldSyncToken: null,\n nextSyncToken: null,\n catchingUp: true,\n });\n }\n this._sync(syncOptions);\n });\n\n this._currentSyncRequest = null;\n // Transition from RECONNECTING to ERROR after a given number of failed syncs\n this._updateSyncState(\n this._failedSyncCount >= FAILED_SYNC_ERROR_THRESHOLD ?\n \"ERROR\" : \"RECONNECTING\",\n { error: err },\n );\n};\n\n/**\n * Process data returned from a sync response and propagate it\n * into the model objects\n *\n * @param {Object} syncEventData Object containing sync tokens associated with this sync\n * @param {Object} data The response from /sync\n */\nSyncApi.prototype._processSyncResponse = async function(\n syncEventData, data,\n) {\n const client = this.client;\n const self = this;\n\n // data looks like:\n // {\n // next_batch: $token,\n // presence: { events: [] },\n // account_data: { events: [] },\n // device_lists: { changed: [\"@user:server\", ... ]},\n // to_device: { events: [] },\n // device_one_time_keys_count: { signed_curve25519: 42 },\n // rooms: {\n // invite: {\n // $roomid: {\n // invite_state: { events: [] }\n // }\n // },\n // join: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token, limited: true },\n // ephemeral: { events: [] },\n // summary: {\n // m.heroes: [ $user_id ],\n // m.joined_member_count: $count,\n // m.invited_member_count: $count\n // },\n // account_data: { events: [] },\n // unread_notifications: {\n // highlight_count: 0,\n // notification_count: 0,\n // }\n // }\n // },\n // leave: {\n // $roomid: {\n // state: { events: [] },\n // timeline: { events: [], prev_batch: $token }\n // }\n // }\n // },\n // groups: {\n // invite: {\n // $groupId: {\n // inviter: $inviter,\n // profile: {\n // avatar_url: $avatarUrl,\n // name: $groupName,\n // },\n // },\n // },\n // join: {},\n // leave: {},\n // },\n // }\n\n // TODO-arch:\n // - Each event we pass through needs to be emitted via 'event', can we\n // do this in one place?\n // - The isBrandNewRoom boilerplate is boilerplatey.\n\n // handle presence events (User objects)\n if (data.presence && utils.isArray(data.presence.events)) {\n data.presence.events.map(client.getEventMapper()).forEach(\n function(presenceEvent) {\n let user = client.store.getUser(presenceEvent.getSender());\n if (user) {\n user.setPresenceEvent(presenceEvent);\n } else {\n user = createNewUser(client, presenceEvent.getSender());\n user.setPresenceEvent(presenceEvent);\n client.store.storeUser(user);\n }\n client.emit(\"event\", presenceEvent);\n });\n }\n\n // handle non-room account_data\n if (data.account_data && utils.isArray(data.account_data.events)) {\n const events = data.account_data.events.map(client.getEventMapper());\n client.store.storeAccountDataEvents(events);\n events.forEach(\n function(accountDataEvent) {\n // Honour push rules that come down the sync stream but also\n // honour push rules that were previously cached. Base rules\n // will be updated when we recieve push rules via getPushRules\n // (see SyncApi.prototype.sync) before syncing over the network.\n if (accountDataEvent.getType() == 'm.push_rules') {\n client.pushRules = accountDataEvent.getContent();\n }\n client.emit(\"accountData\", accountDataEvent);\n return accountDataEvent;\n },\n );\n }\n\n // handle to-device events\n if (data.to_device && utils.isArray(data.to_device.events) &&\n data.to_device.events.length > 0\n ) {\n data.to_device.events\n .map(client.getEventMapper())\n .forEach(\n function(toDeviceEvent) {\n const content = toDeviceEvent.getContent();\n if (\n toDeviceEvent.getType() == \"m.room.message\" &&\n content.msgtype == \"m.bad.encrypted\"\n ) {\n // the mapper already logged a warning.\n console.log(\n 'Ignoring undecryptable to-device event from ' +\n toDeviceEvent.getSender(),\n );\n return;\n }\n\n client.emit(\"toDeviceEvent\", toDeviceEvent);\n },\n );\n } else {\n // no more to-device events: we can stop polling with a short timeout.\n this._catchingUp = false;\n }\n\n if (data.groups) {\n if (data.groups.invite) {\n this._processGroupSyncEntry(data.groups.invite, 'invite');\n }\n\n if (data.groups.join) {\n this._processGroupSyncEntry(data.groups.join, 'join');\n }\n\n if (data.groups.leave) {\n this._processGroupSyncEntry(data.groups.leave, 'leave');\n }\n }\n\n // the returned json structure is a bit crap, so make it into a\n // nicer form (array) after applying sanity to make sure we don't fail\n // on missing keys (on the off chance)\n let inviteRooms = [];\n let joinRooms = [];\n let leaveRooms = [];\n\n if (data.rooms) {\n if (data.rooms.invite) {\n inviteRooms = this._mapSyncResponseToRoomArray(data.rooms.invite);\n }\n if (data.rooms.join) {\n joinRooms = this._mapSyncResponseToRoomArray(data.rooms.join);\n }\n if (data.rooms.leave) {\n leaveRooms = this._mapSyncResponseToRoomArray(data.rooms.leave);\n }\n }\n\n this._notifEvents = [];\n\n // Handle invites\n inviteRooms.forEach(function(inviteObj) {\n const room = inviteObj.room;\n const stateEvents =\n self._mapSyncEventsFormat(inviteObj.invite_state, room);\n\n room.updateMyMembership(\"invite\");\n self._processRoomEvents(room, stateEvents);\n if (inviteObj.isBrandNewRoom) {\n room.recalculate();\n client.store.storeRoom(room);\n client.emit(\"Room\", room);\n }\n stateEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n });\n\n // Handle joins\n await Promise.mapSeries(joinRooms, async function(joinObj) {\n const room = joinObj.room;\n const stateEvents = self._mapSyncEventsFormat(joinObj.state, room);\n const timelineEvents = self._mapSyncEventsFormat(joinObj.timeline, room);\n const ephemeralEvents = self._mapSyncEventsFormat(joinObj.ephemeral);\n const accountDataEvents = self._mapSyncEventsFormat(joinObj.account_data);\n\n // we do this first so it's correct when any of the events fire\n if (joinObj.unread_notifications) {\n room.setUnreadNotificationCount(\n 'total', joinObj.unread_notifications.notification_count,\n );\n room.setUnreadNotificationCount(\n 'highlight', joinObj.unread_notifications.highlight_count,\n );\n }\n\n room.updateMyMembership(\"join\");\n\n joinObj.timeline = joinObj.timeline || {};\n\n if (joinObj.isBrandNewRoom) {\n // set the back-pagination token. Do this *before* adding any\n // events so that clients can start back-paginating.\n room.getLiveTimeline().setPaginationToken(\n joinObj.timeline.prev_batch, EventTimeline.BACKWARDS);\n } else if (joinObj.timeline.limited) {\n let limited = true;\n\n // we've got a limited sync, so we *probably* have a gap in the\n // timeline, so should reset. But we might have been peeking or\n // paginating and already have some of the events, in which\n // case we just want to append any subsequent events to the end\n // of the existing timeline.\n //\n // This is particularly important in the case that we already have\n // *all* of the events in the timeline - in that case, if we reset\n // the timeline, we'll end up with an entirely empty timeline,\n // which we'll try to paginate but not get any new events (which\n // will stop us linking the empty timeline into the chain).\n //\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const eventId = timelineEvents[i].getId();\n if (room.getTimelineForEvent(eventId)) {\n debuglog(\"Already have event \" + eventId + \" in limited \" +\n \"sync - not resetting\");\n limited = false;\n\n // we might still be missing some of the events before i;\n // we don't want to be adding them to the end of the\n // timeline because that would put them out of order.\n timelineEvents.splice(0, i);\n\n // XXX: there's a problem here if the skipped part of the\n // timeline modifies the state set in stateEvents, because\n // we'll end up using the state from stateEvents rather\n // than the later state from timelineEvents. We probably\n // need to wind stateEvents forward over the events we're\n // skipping.\n\n break;\n }\n }\n\n if (limited) {\n self._deregisterStateListeners(room);\n room.resetLiveTimeline(\n joinObj.timeline.prev_batch,\n self.opts.canResetEntireTimeline(room.roomId) ?\n null : syncEventData.oldSyncToken,\n );\n\n // We have to assume any gap in any timeline is\n // reason to stop incrementally tracking notifications and\n // reset the timeline.\n client.resetNotifTimelineSet();\n\n self._registerStateListeners(room);\n }\n }\n\n self._processRoomEvents(room, stateEvents, timelineEvents);\n\n // set summary after processing events,\n // because it will trigger a name calculation\n // which needs the room state to be up to date\n if (joinObj.summary) {\n room.setSummary(joinObj.summary);\n }\n\n // XXX: should we be adding ephemeralEvents to the timeline?\n // It feels like that for symmetry with room.addAccountData()\n // there should be a room.addEphemeralEvents() or similar.\n room.addLiveEvents(ephemeralEvents);\n\n // we deliberately don't add accountData to the timeline\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (joinObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(\"Room\", room);\n }\n\n self._processEventsForNotifs(room, timelineEvents);\n\n async function processRoomEvent(e) {\n client.emit(\"event\", e);\n if (e.isState() && e.getType() == \"m.room.encryption\" && self.opts.crypto) {\n await self.opts.crypto.onCryptoEvent(e);\n }\n if (e.isState() && e.getType() === \"im.vector.user_status\") {\n let user = client.store.getUser(e.getStateKey());\n if (user) {\n user._unstable_updateStatusMessage(e);\n } else {\n user = createNewUser(client, e.getStateKey());\n user._unstable_updateStatusMessage(e);\n client.store.storeUser(user);\n }\n }\n }\n\n await Promise.mapSeries(stateEvents, processRoomEvent);\n await Promise.mapSeries(timelineEvents, processRoomEvent);\n ephemeralEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n accountDataEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n });\n\n // Handle leaves (e.g. kicked rooms)\n leaveRooms.forEach(function(leaveObj) {\n const room = leaveObj.room;\n const stateEvents =\n self._mapSyncEventsFormat(leaveObj.state, room);\n const timelineEvents =\n self._mapSyncEventsFormat(leaveObj.timeline, room);\n const accountDataEvents =\n self._mapSyncEventsFormat(leaveObj.account_data);\n\n room.updateMyMembership(\"leave\");\n\n self._processRoomEvents(room, stateEvents, timelineEvents);\n room.addAccountData(accountDataEvents);\n\n room.recalculate();\n if (leaveObj.isBrandNewRoom) {\n client.store.storeRoom(room);\n client.emit(\"Room\", room);\n }\n\n self._processEventsForNotifs(room, timelineEvents);\n\n stateEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n timelineEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n accountDataEvents.forEach(function(e) {\n client.emit(\"event\", e);\n });\n });\n\n // update the notification timeline, if appropriate.\n // we only do this for live events, as otherwise we can't order them sanely\n // in the timeline relative to ones paginated in by /notifications.\n // XXX: we could fix this by making EventTimeline support chronological\n // ordering... but it doesn't, right now.\n if (syncEventData.oldSyncToken && this._notifEvents.length) {\n this._notifEvents.sort(function(a, b) {\n return a.getTs() - b.getTs();\n });\n this._notifEvents.forEach(function(event) {\n client.getNotifTimelineSet().addLiveEvent(event);\n });\n }\n\n // Handle device list updates\n if (data.device_lists) {\n if (this.opts.crypto) {\n await this.opts.crypto.handleDeviceListChanges(\n syncEventData, data.device_lists,\n );\n } else {\n // FIXME if we *don't* have a crypto module, we still need to\n // invalidate the device lists. But that would require a\n // substantial bit of rework :/.\n }\n }\n\n // Handle one_time_keys_count\n if (this.opts.crypto && data.device_one_time_keys_count) {\n const currentCount = data.device_one_time_keys_count.signed_curve25519 || 0;\n this.opts.crypto.updateOneTimeKeyCount(currentCount);\n }\n};\n\n/**\n * Starts polling the connectivity check endpoint\n * @param {number} delay How long to delay until the first poll.\n * defaults to a short, randomised interval (to prevent\n * tightlooping if /versions succeeds but /sync etc. fail).\n * @return {promise} which resolves once the connection returns\n */\nSyncApi.prototype._startKeepAlives = function(delay) {\n if (delay === undefined) {\n delay = 2000 + Math.floor(Math.random() * 5000);\n }\n\n if (this._keepAliveTimer !== null) {\n clearTimeout(this._keepAliveTimer);\n }\n const self = this;\n if (delay > 0) {\n self._keepAliveTimer = setTimeout(\n self._pokeKeepAlive.bind(self),\n delay,\n );\n } else {\n self._pokeKeepAlive();\n }\n if (!this._connectionReturnedDefer) {\n this._connectionReturnedDefer = Promise.defer();\n }\n return this._connectionReturnedDefer.promise;\n};\n\n/**\n * Make a dummy call to /_matrix/client/versions, to see if the HS is\n * reachable.\n *\n * On failure, schedules a call back to itself. On success, resolves\n * this._connectionReturnedDefer.\n *\n * @param {bool} connDidFail True if a connectivity failure has been detected. Optional.\n */\nSyncApi.prototype._pokeKeepAlive = function(connDidFail) {\n if (connDidFail === undefined) connDidFail = false;\n const self = this;\n function success() {\n clearTimeout(self._keepAliveTimer);\n if (self._connectionReturnedDefer) {\n self._connectionReturnedDefer.resolve(connDidFail);\n self._connectionReturnedDefer = null;\n }\n }\n\n this.client._http.request(\n undefined, // callback\n \"GET\", \"/_matrix/client/versions\",\n undefined, // queryParams\n undefined, // data\n {\n prefix: '',\n localTimeoutMs: 15 * 1000,\n },\n ).done(function() {\n success();\n }, function(err) {\n if (err.httpStatus == 400 || err.httpStatus == 404) {\n // treat this as a success because the server probably just doesn't\n // support /versions: point is, we're getting a response.\n // We wait a short time though, just in case somehow the server\n // is in a mode where it 400s /versions responses and sync etc.\n // responses fail, this will mean we don't hammer in a loop.\n self._keepAliveTimer = setTimeout(success, 2000);\n } else {\n connDidFail = true;\n self._keepAliveTimer = setTimeout(\n self._pokeKeepAlive.bind(self, connDidFail),\n 5000 + Math.floor(Math.random() * 5000),\n );\n // A keepalive has failed, so we emit the\n // error state (whether or not this is the\n // first failure).\n // Note we do this after setting the timer:\n // this lets the unit tests advance the mock\n // clock when they get the error.\n self._updateSyncState(\"ERROR\", { error: err });\n }\n });\n};\n\n/**\n * @param {Object} groupsSection Groups section object, eg. response.groups.invite\n * @param {string} sectionName Which section this is ('invite', 'join' or 'leave')\n */\nSyncApi.prototype._processGroupSyncEntry = function(groupsSection, sectionName) {\n // Processes entries from 'groups' section of the sync stream\n for (const groupId of Object.keys(groupsSection)) {\n const groupInfo = groupsSection[groupId];\n let group = this.client.store.getGroup(groupId);\n const isBrandNew = group === null;\n if (group === null) {\n group = this.createGroup(groupId);\n }\n if (groupInfo.profile) {\n group.setProfile(\n groupInfo.profile.name, groupInfo.profile.avatar_url,\n );\n }\n if (groupInfo.inviter) {\n group.setInviter({userId: groupInfo.inviter});\n }\n group.setMyMembership(sectionName);\n if (isBrandNew) {\n // Now we've filled in all the fields, emit the Group event\n this.client.emit(\"Group\", group);\n }\n }\n};\n\n/**\n * @param {Object} obj\n * @return {Object[]}\n */\nSyncApi.prototype._mapSyncResponseToRoomArray = function(obj) {\n // Maps { roomid: {stuff}, roomid: {stuff} }\n // to\n // [{stuff+Room+isBrandNewRoom}, {stuff+Room+isBrandNewRoom}]\n const client = this.client;\n const self = this;\n return utils.keys(obj).map(function(roomId) {\n const arrObj = obj[roomId];\n let room = client.store.getRoom(roomId);\n let isBrandNewRoom = false;\n if (!room) {\n room = self.createRoom(roomId);\n isBrandNewRoom = true;\n }\n arrObj.room = room;\n arrObj.isBrandNewRoom = isBrandNewRoom;\n return arrObj;\n });\n};\n\n/**\n * @param {Object} obj\n * @param {Room} room\n * @return {MatrixEvent[]}\n */\nSyncApi.prototype._mapSyncEventsFormat = function(obj, room) {\n if (!obj || !utils.isArray(obj.events)) {\n return [];\n }\n const mapper = this.client.getEventMapper();\n return obj.events.map(function(e) {\n if (room) {\n e.room_id = room.roomId;\n }\n return mapper(e);\n });\n};\n\n/**\n * @param {Room} room\n */\nSyncApi.prototype._resolveInvites = function(room) {\n if (!room || !this.opts.resolveInvitesToProfiles) {\n return;\n }\n const client = this.client;\n // For each invited room member we want to give them a displayname/avatar url\n // if they have one (the m.room.member invites don't contain this).\n room.getMembersWithMembership(\"invite\").forEach(function(member) {\n if (member._requestedProfileInfo) {\n return;\n }\n member._requestedProfileInfo = true;\n // try to get a cached copy first.\n const user = client.getUser(member.userId);\n let promise;\n if (user) {\n promise = Promise.resolve({\n avatar_url: user.avatarUrl,\n displayname: user.displayName,\n });\n } else {\n promise = client.getProfileInfo(member.userId);\n }\n promise.done(function(info) {\n // slightly naughty by doctoring the invite event but this means all\n // the code paths remain the same between invite/join display name stuff\n // which is a worthy trade-off for some minor pollution.\n const inviteEvent = member.events.member;\n if (inviteEvent.getContent().membership !== \"invite\") {\n // between resolving and now they have since joined, so don't clobber\n return;\n }\n inviteEvent.getContent().avatar_url = info.avatar_url;\n inviteEvent.getContent().displayname = info.displayname;\n // fire listeners\n member.setMembershipEvent(inviteEvent, room.currentState);\n }, function(err) {\n // OH WELL.\n });\n });\n};\n\n/**\n * @param {Room} room\n * @param {MatrixEvent[]} stateEventList A list of state events. This is the state\n * at the *START* of the timeline list if it is supplied.\n * @param {MatrixEvent[]} [timelineEventList] A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\nSyncApi.prototype._processRoomEvents = function(room, stateEventList,\n timelineEventList) {\n // If there are no events in the timeline yet, initialise it with\n // the given state events\n const liveTimeline = room.getLiveTimeline();\n const timelineWasEmpty = liveTimeline.getEvents().length == 0;\n if (timelineWasEmpty) {\n // Passing these events into initialiseState will freeze them, so we need\n // to compute and cache the push actions for them now, otherwise sync dies\n // with an attempt to assign to read only property.\n // XXX: This is pretty horrible and is assuming all sorts of behaviour from\n // these functions that it shouldn't be. We should probably either store the\n // push actions cache elsewhere so we can freeze MatrixEvents, or otherwise\n // find some solution where MatrixEvents are immutable but allow for a cache\n // field.\n for (const ev of stateEventList) {\n this.client.getPushActionsForEvent(ev);\n }\n liveTimeline.initialiseState(stateEventList);\n }\n\n this._resolveInvites(room);\n\n // recalculate the room name at this point as adding events to the timeline\n // may make notifications appear which should have the right name.\n // XXX: This looks suspect: we'll end up recalculating the room once here\n // and then again after adding events (_processSyncResponse calls it after\n // calling us) even if no state events were added. It also means that if\n // one of the room events in timelineEventList is something that needs\n // a recalculation (like m.room.name) we won't recalculate until we've\n // finished adding all the events, which will cause the notification to have\n // the old room name rather than the new one.\n room.recalculate();\n\n // If the timeline wasn't empty, we process the state events here: they're\n // defined as updates to the state before the start of the timeline, so this\n // starts to roll the state forward.\n // XXX: That's what we *should* do, but this can happen if we were previously\n // peeking in a room, in which case we obviously do *not* want to add the\n // state events here onto the end of the timeline. Historically, the js-sdk\n // has just set these new state events on the old and new state. This seems\n // very wrong because there could be events in the timeline that diverge the\n // state, in which case this is going to leave things out of sync. However,\n // for now I think it;s best to behave the same as the code has done previously.\n if (!timelineWasEmpty) {\n // XXX: As above, don't do this...\n //room.addLiveEvents(stateEventList || []);\n // Do this instead...\n room.oldState.setStateEvents(stateEventList || []);\n room.currentState.setStateEvents(stateEventList || []);\n }\n // execute the timeline events. This will continue to diverge the current state\n // if the timeline has any state events in it.\n // This also needs to be done before running push rules on the events as they need\n // to be decorated with sender etc.\n room.addLiveEvents(timelineEventList || []);\n};\n\n/**\n * Takes a list of timelineEvents and adds and adds to _notifEvents\n * as appropriate.\n * This must be called after the room the events belong to has been stored.\n *\n * @param {Room} room\n * @param {MatrixEvent[]} [timelineEventList] A list of timeline events. Lower index\n * is earlier in time. Higher index is later.\n */\nSyncApi.prototype._processEventsForNotifs = function(room, timelineEventList) {\n // gather our notifications into this._notifEvents\n if (this.client.getNotifTimelineSet()) {\n for (let i = 0; i < timelineEventList.length; i++) {\n const pushActions = this.client.getPushActionsForEvent(timelineEventList[i]);\n if (pushActions && pushActions.notify &&\n pushActions.tweaks && pushActions.tweaks.highlight) {\n this._notifEvents.push(timelineEventList[i]);\n }\n }\n }\n};\n\n/**\n * @return {string}\n */\nSyncApi.prototype._getGuestFilter = function() {\n const guestRooms = this.client._guestRooms; // FIXME: horrible gut-wrenching\n if (!guestRooms) {\n return \"{}\";\n }\n // we just need to specify the filter inline if we're a guest because guests\n // can't create filters.\n return JSON.stringify({\n room: {\n timeline: {\n limit: 20,\n },\n },\n });\n};\n\n/**\n * Sets the sync state and emits an event to say so\n * @param {String} newState The new state string\n * @param {Object} data Object of additional data to emit in the event\n */\nSyncApi.prototype._updateSyncState = function(newState, data) {\n const old = this._syncState;\n this._syncState = newState;\n this._syncStateData = data;\n this.client.emit(\"sync\", this._syncState, old, data);\n};\n\n/**\n * Event handler for the 'online' event\n * This event is generally unreliable and precise behaviour\n * varies between browsers, so we poll for connectivity too,\n * but this might help us reconnect a little faster.\n */\nSyncApi.prototype._onOnline = function() {\n debuglog(\"Browser thinks we are back online\");\n this._startKeepAlives(0);\n};\n\nfunction createNewUser(client, userId) {\n const user = new User(userId);\n client.reEmitter.reEmit(user, [\n \"User.avatarUrl\", \"User.displayName\", \"User.presence\",\n \"User.currentlyActive\", \"User.lastPresenceTs\",\n ]);\n return user;\n}\n\n/** */\nmodule.exports = SyncApi;\n"]}
\No newline at end of file